<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: filedlg.cxx,v $
 *
 *  $Revision: 1.18 $
 *
 *  last change: $Author: kz $ $Date: 2008-03-07 16:26:00 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef  _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef  _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_COMMONFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_LISTBOXCONTROLACTIONS_HPP_
#include <com/sun/star/ui/dialogs/ListboxControlActions.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_TEMPLATEDESCRIPTION_HPP_
#include <com/sun/star/ui/dialogs/TemplateDescription.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERCONTROLACCESS_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERLISTENER_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerListener.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERNOTIFIER_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerNotifier.hpp>
#endif
#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFILEPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFilePicker.hpp>
#endif

#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif

#ifndef _VOS_THREAD_HXX_
#include <vos/thread.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif

#include <svx/impgrf.hxx>

#include <avmedia/mediawindow.hxx>
#include "filedlg.hxx"
#include "sdresid.hxx"
#include "strings.hrc"

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

namespace css = ::com::sun::star;

// --------------------------------------------------------------------
// -----------      SdFileDialog_Imp        ---------------------------
// --------------------------------------------------------------------
class SdFileDialog_Imp : public sfx2::FileDialogHelper
{
private:
#if defined __SUNPRO_CC
    using sfx2::FileDialogHelper::Execute;
#endif

    friend class SdExportFileDialog;
    friend class SdOpenSoundFileDialog;

    css::uno::Reference< css::ui::dialogs::XFilePickerControlAccess >   mxControlAccess;

    css::uno::Reference< css::media::XPlayer > mxPlayer;
    ULONG                       mnPlaySoundEvent;
    BOOL                        mbUsableSelection;
    BOOL                        mbLabelPlaying;

    void                        CheckSelectionState();

                                DECL_LINK( PlayMusicHdl, void * );

    Timer                       maUpdateTimer;

                                DECL_LINK( IsMusicStoppedHdl, void * );

public:
                                SdFileDialog_Imp( const short nDialogType, sal_Bool bUsableSelection );
                                   ~SdFileDialog_Imp();

    ErrCode                     Execute();

    // overwritten from FileDialogHelper, to receive user feedback
    virtual void SAL_CALL       ControlStateChanged( const css::ui::dialogs::FilePickerEvent& aEvent );

    sal_Bool                    SelectionBoxState() const;
};

// ------------------------------------------------------------------------
void SAL_CALL SdFileDialog_Imp::ControlStateChanged( const css::ui::dialogs::FilePickerEvent& aEvent )
{
    ::vos::OGuard aGuard( Application::GetSolarMutex() );

    switch( aEvent.ElementId )
    {
        case css::ui::dialogs::CommonFilePickerElementIds::LISTBOX_FILTER:
            CheckSelectionState();
            break;

        case css::ui::dialogs::ExtendedFilePickerElementIds::PUSHBUTTON_PLAY:
            if( mxControlAccess.is() )
            {
                if( mnPlaySoundEvent )
                    Application::RemoveUserEvent( mnPlaySoundEvent );

                mnPlaySoundEvent = Application::PostUserEvent( LINK( this, SdFileDialog_Imp, PlayMusicHdl ) );
            }
            break;
    }
}

// ------------------------------------------------------------------------
IMPL_LINK( SdFileDialog_Imp, PlayMusicHdl, void *, EMPTYARG )
{
    maUpdateTimer.Stop();
    mnPlaySoundEvent = 0;

    if (mxPlayer.is())
    {
        if (mxPlayer->isPlaying())
            mxPlayer->stop();
        mxPlayer.clear();
    }

    if( mbLabelPlaying )
    {
        try
        {
            mxControlAccess->setLabel( css::ui::dialogs::ExtendedFilePickerElementIds::PUSHBUTTON_PLAY,
                                       String( SdResId( STR_PLAY ) ) );

            mbLabelPlaying = FALSE;
        }
        catch( css::lang::IllegalArgumentException )
        {
#ifdef DBG_UTIL
            DBG_ERROR( "Cannot access play button" );
#endif
        }
    }
    else
    {
        rtl::OUString aUrl( GetPath() );
        if ( aUrl.getLength() )
        {
            try
            {
                mxPlayer.set( avmedia::MediaWindow::createPlayer( aUrl ), css::uno::UNO_QUERY_THROW );
                mxPlayer->start();
                maUpdateTimer.SetTimeout( 100 );
                maUpdateTimer.Start();
            }
            catch( css::uno::Exception& e )
            {
                (void)e;
                mxPlayer.clear();
            }

            if (mxPlayer.is())
            {
                try
                {
                    mxControlAccess->setLabel( css::ui::dialogs::ExtendedFilePickerElementIds::PUSHBUTTON_PLAY,
                                               String( SdResId( STR_STOP ) ) );

                    mbLabelPlaying = TRUE;
                }
                catch( css::lang::IllegalArgumentException )
                {
#ifdef DBG_UTIL
                    DBG_ERROR( "Cannot access play button" );
#endif
                }
            }
        }
    }

    return 0;
}

// ------------------------------------------------------------------------
IMPL_LINK( SdFileDialog_Imp, IsMusicStoppedHdl, void *, EMPTYARG )
{
    ::vos::OGuard aGuard( Application::GetSolarMutex() );

    if (
        mxPlayer.is() && mxPlayer->isPlaying() &&
        mxPlayer->getMediaTime() < mxPlayer->getDuration()
       )
    {
        maUpdateTimer.Start();
        return 0L;
    }

    if( mxControlAccess.is() )
    {
        try
        {
            mxControlAccess->setLabel( css::ui::dialogs::ExtendedFilePickerElementIds::PUSHBUTTON_PLAY,
                                       String( SdResId( STR_PLAY ) ) );
            mbLabelPlaying = FALSE;
        }
        catch( css::lang::IllegalArgumentException )
        {
#ifdef DBG_UTIL
            DBG_ERROR( "Cannot access play button" );
#endif
        }
    }

    return( 0L );
}

// check whether to disable the "selection" checkbox
void SdFileDialog_Imp::CheckSelectionState()
{
    if( mbUsableSelection && mxControlAccess.is() )
    {
        String  aCurrFilter( GetCurrentFilter() );

        try
        {
            if( !aCurrFilter.Len() || ( aCurrFilter == String( SdResId( STR_EXPORT_HTML_NAME ) ) ) )
                mxControlAccess->enableControl( css::ui::dialogs::ExtendedFilePickerElementIds::CHECKBOX_SELECTION, FALSE );
            else
                mxControlAccess->enableControl( css::ui::dialogs::ExtendedFilePickerElementIds::CHECKBOX_SELECTION, TRUE );
        }
        catch( css::lang::IllegalArgumentException )
        {
#ifdef DBG_UTIL
            DBG_ERROR( "Cannot access \"selection\" checkbox" );
#endif
        }
    }
}

//-----------------------------------------------------------------------------
SdFileDialog_Imp::SdFileDialog_Imp( const short     nDialogType,
                                    sal_Bool        bUsableSelection    ) :
    FileDialogHelper( nDialogType, 0 ),
    mnPlaySoundEvent( 0 ),
    mbUsableSelection( bUsableSelection ),
    mbLabelPlaying(FALSE)
{
    maUpdateTimer.SetTimeoutHdl(LINK(this, SdFileDialog_Imp, IsMusicStoppedHdl));

    css::uno::Reference < ::com::sun::star::ui::dialogs::XFilePicker > xFileDlg = GetFilePicker();

    // get the control access
    mxControlAccess = css::uno::Reference< css::ui::dialogs::XFilePickerControlAccess > ( xFileDlg, css::uno::UNO_QUERY );

    if( mxControlAccess.is() )
    {
        if( nDialogType ==
            css::ui::dialogs::TemplateDescription::FILEOPEN_PLAY )
        {
            try
            {
                mxControlAccess->setLabel( css::ui::dialogs::ExtendedFilePickerElementIds::PUSHBUTTON_PLAY,
                                           String( SdResId( STR_PLAY ) ) );
            }
            catch( css::lang::IllegalArgumentException )
            {
#ifdef DBG_UTIL
                DBG_ERROR( "Cannot set play button label" );
#endif
            }
        }
        else if( mbUsableSelection != sal_True )
        {
            try
            {
                mxControlAccess->enableControl( css::ui::dialogs::ExtendedFilePickerElementIds::CHECKBOX_SELECTION, FALSE );
            }
            catch( css::lang::IllegalArgumentException )
            {
#ifdef DBG_UTIL
                DBG_ERROR( "Cannot disable selection checkbox" );
#endif
            }
        }
    }
}

// ------------------------------------------------------------------------
SdFileDialog_Imp::~SdFileDialog_Imp()
{
    if( mnPlaySoundEvent )
        Application::RemoveUserEvent( mnPlaySoundEvent );
}

// ------------------------------------------------------------------------
ErrCode SdFileDialog_Imp::Execute()
{
    // make sure selection checkbox is disabled if
    // HTML is current filter!
    CheckSelectionState();
    return FileDialogHelper::Execute();
}

// ------------------------------------------------------------------------
sal_Bool SdFileDialog_Imp::SelectionBoxState() const
{
    if ( !mbUsableSelection || !mxControlAccess.is() )
        return sal_False;

    sal_Bool bState(0);
    try
    {
        mxControlAccess->getValue( css::ui::dialogs::ExtendedFilePickerElementIds::CHECKBOX_SELECTION, 0 ) >>= bState;
    }
    catch( css::lang::IllegalArgumentException )
    {
#ifdef DBG_UTIL
        DBG_ERROR( "Cannot access \"selection\" checkbox" );
#endif
    }

    return bState;
}

// --------------------------------------------------------------------
// -----------      SdExportFileDialog      ---------------------------
// --------------------------------------------------------------------

// these are simple forwarders
SdExportFileDialog::SdExportFileDialog(BOOL bHaveCheckbox) :
    mpImpl( new SdFileDialog_Imp( css::ui::dialogs::TemplateDescription::FILESAVE_AUTOEXTENSION_SELECTION,
                                  bHaveCheckbox ) )
{
    // setup filter
    const String    aHTMLFilter( SdResId( STR_EXPORT_HTML_NAME ) );
    GraphicFilter*  pFilter = GetGrfFilter();
    const USHORT    nFilterCount = pFilter->GetExportFormatCount();

    // add HTML filter
    mpImpl->AddFilter( aHTMLFilter, String( SdResId( STR_EXPORT_HTML_FILTER ) ) );

    // add other graphic filters
    for ( USHORT i = 0; i < nFilterCount; i++ )
    {
        mpImpl->AddFilter( pFilter->GetExportFormatName( i ),
                           pFilter->GetExportWildcard( i ) );
    }

    // set dialog title
    mpImpl->SetTitle( String( SdResId( STR_EXPORT_DIALOG_TITLE ) ) );
}

// ------------------------------------------------------------------------
SdExportFileDialog::~SdExportFileDialog()
{
}

// ------------------------------------------------------------------------
ErrCode SdExportFileDialog::Execute()
{
    return mpImpl->Execute();
}

String SdExportFileDialog::GetPath() const
{
    return mpImpl->GetPath();
}

// ------------------------------------------------------------------------
void SdExportFileDialog::SetPath( const String& rPath )
{
    mpImpl->SetDisplayDirectory( rPath );
}

// ------------------------------------------------------------------------
String SdExportFileDialog::ReqCurrentFilter() const
{
    return mpImpl->GetCurrentFilter();
}

// ------------------------------------------------------------------------
BOOL SdExportFileDialog::IsExportSelection() const
{
    return mpImpl->SelectionBoxState();
}

// --------------------------------------------------------------------
// -----------      SdOpenSoundFileDialog       -----------------------
// --------------------------------------------------------------------

// these are simple forwarders
SdOpenSoundFileDialog::SdOpenSoundFileDialog() :
    mpImpl(
        new SdFileDialog_Imp(
            css::ui::dialogs::TemplateDescription::FILEOPEN_PLAY, sal_False ) )
{
    String aDescr;
    aDescr = String(SdResId(STR_ALL_FILES));
    mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "*.*" ) ) );

    // setup filter
#if defined UNX
    aDescr = String(SdResId(STR_AU_FILE));
    mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "*.au;*.snd" ) ) );
    aDescr = String(SdResId(STR_VOC_FILE));
    mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "*.voc" ) ) );
    aDescr = String(SdResId(STR_WAV_FILE));
    mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "*.wav" ) ) );
    aDescr = String(SdResId(STR_AIFF_FILE));
    mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "*.aiff" ) ) );
    aDescr = String(SdResId(STR_SVX_FILE));
    mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "*.svx" ) ) );
#else
    aDescr = String(SdResId(STR_WAV_FILE));
    mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "*.wav;*.mp3;*.ogg" ) ) );
    aDescr = String(SdResId(STR_MIDI_FILE));
    mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "*.mid" ) ) );
#endif
}

// ------------------------------------------------------------------------
SdOpenSoundFileDialog::~SdOpenSoundFileDialog()
{
}

// ------------------------------------------------------------------------
ErrCode SdOpenSoundFileDialog::Execute()
{
    return mpImpl->Execute();
}

// ------------------------------------------------------------------------
String SdOpenSoundFileDialog::GetPath() const
{
    return mpImpl->GetPath();
}

// ------------------------------------------------------------------------
void SdOpenSoundFileDialog::SetPath( const String& rPath )
{
    mpImpl->SetDisplayDirectory( rPath );
}
<commit_msg>INTEGRATION: CWS changefileheader (1.18.24); FILE MERGED 2008/04/01 15:34:19 thb 1.18.24.3: #i85898# Stripping all external header guards 2008/04/01 12:38:41 thb 1.18.24.2: #i85898# Stripping all external header guards 2008/03/31 13:57:45 rt 1.18.24.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: filedlg.cxx,v $
 * $Revision: 1.19 $
 *
 * 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.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include <tools/debug.hxx>
#include <cppuhelper/implbase1.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/ui/dialogs/CommonFilePickerElementIds.hpp>
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#include <com/sun/star/ui/dialogs/ListboxControlActions.hpp>
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#include <com/sun/star/ui/dialogs/TemplateDescription.hpp>
#include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp>
#include <com/sun/star/ui/dialogs/XFilePickerListener.hpp>
#include <com/sun/star/ui/dialogs/XFilePickerNotifier.hpp>
#include <com/sun/star/ui/dialogs/XFilePicker.hpp>
#include <vcl/msgbox.hxx>
#include <sal/types.h>
#include <tools/urlobj.hxx>
#include <vos/thread.hxx>
#include <vos/mutex.hxx>
#include <vcl/svapp.hxx>
#include <sfx2/filedlghelper.hxx>

#include <svx/impgrf.hxx>

#include <avmedia/mediawindow.hxx>
#include "filedlg.hxx"
#include "sdresid.hxx"
#include "strings.hrc"

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

namespace css = ::com::sun::star;

// --------------------------------------------------------------------
// -----------      SdFileDialog_Imp        ---------------------------
// --------------------------------------------------------------------
class SdFileDialog_Imp : public sfx2::FileDialogHelper
{
private:
#if defined __SUNPRO_CC
    using sfx2::FileDialogHelper::Execute;
#endif

    friend class SdExportFileDialog;
    friend class SdOpenSoundFileDialog;

    css::uno::Reference< css::ui::dialogs::XFilePickerControlAccess >   mxControlAccess;

    css::uno::Reference< css::media::XPlayer > mxPlayer;
    ULONG                       mnPlaySoundEvent;
    BOOL                        mbUsableSelection;
    BOOL                        mbLabelPlaying;

    void                        CheckSelectionState();

                                DECL_LINK( PlayMusicHdl, void * );

    Timer                       maUpdateTimer;

                                DECL_LINK( IsMusicStoppedHdl, void * );

public:
                                SdFileDialog_Imp( const short nDialogType, sal_Bool bUsableSelection );
                                   ~SdFileDialog_Imp();

    ErrCode                     Execute();

    // overwritten from FileDialogHelper, to receive user feedback
    virtual void SAL_CALL       ControlStateChanged( const css::ui::dialogs::FilePickerEvent& aEvent );

    sal_Bool                    SelectionBoxState() const;
};

// ------------------------------------------------------------------------
void SAL_CALL SdFileDialog_Imp::ControlStateChanged( const css::ui::dialogs::FilePickerEvent& aEvent )
{
    ::vos::OGuard aGuard( Application::GetSolarMutex() );

    switch( aEvent.ElementId )
    {
        case css::ui::dialogs::CommonFilePickerElementIds::LISTBOX_FILTER:
            CheckSelectionState();
            break;

        case css::ui::dialogs::ExtendedFilePickerElementIds::PUSHBUTTON_PLAY:
            if( mxControlAccess.is() )
            {
                if( mnPlaySoundEvent )
                    Application::RemoveUserEvent( mnPlaySoundEvent );

                mnPlaySoundEvent = Application::PostUserEvent( LINK( this, SdFileDialog_Imp, PlayMusicHdl ) );
            }
            break;
    }
}

// ------------------------------------------------------------------------
IMPL_LINK( SdFileDialog_Imp, PlayMusicHdl, void *, EMPTYARG )
{
    maUpdateTimer.Stop();
    mnPlaySoundEvent = 0;

    if (mxPlayer.is())
    {
        if (mxPlayer->isPlaying())
            mxPlayer->stop();
        mxPlayer.clear();
    }

    if( mbLabelPlaying )
    {
        try
        {
            mxControlAccess->setLabel( css::ui::dialogs::ExtendedFilePickerElementIds::PUSHBUTTON_PLAY,
                                       String( SdResId( STR_PLAY ) ) );

            mbLabelPlaying = FALSE;
        }
        catch( css::lang::IllegalArgumentException )
        {
#ifdef DBG_UTIL
            DBG_ERROR( "Cannot access play button" );
#endif
        }
    }
    else
    {
        rtl::OUString aUrl( GetPath() );
        if ( aUrl.getLength() )
        {
            try
            {
                mxPlayer.set( avmedia::MediaWindow::createPlayer( aUrl ), css::uno::UNO_QUERY_THROW );
                mxPlayer->start();
                maUpdateTimer.SetTimeout( 100 );
                maUpdateTimer.Start();
            }
            catch( css::uno::Exception& e )
            {
                (void)e;
                mxPlayer.clear();
            }

            if (mxPlayer.is())
            {
                try
                {
                    mxControlAccess->setLabel( css::ui::dialogs::ExtendedFilePickerElementIds::PUSHBUTTON_PLAY,
                                               String( SdResId( STR_STOP ) ) );

                    mbLabelPlaying = TRUE;
                }
                catch( css::lang::IllegalArgumentException )
                {
#ifdef DBG_UTIL
                    DBG_ERROR( "Cannot access play button" );
#endif
                }
            }
        }
    }

    return 0;
}

// ------------------------------------------------------------------------
IMPL_LINK( SdFileDialog_Imp, IsMusicStoppedHdl, void *, EMPTYARG )
{
    ::vos::OGuard aGuard( Application::GetSolarMutex() );

    if (
        mxPlayer.is() && mxPlayer->isPlaying() &&
        mxPlayer->getMediaTime() < mxPlayer->getDuration()
       )
    {
        maUpdateTimer.Start();
        return 0L;
    }

    if( mxControlAccess.is() )
    {
        try
        {
            mxControlAccess->setLabel( css::ui::dialogs::ExtendedFilePickerElementIds::PUSHBUTTON_PLAY,
                                       String( SdResId( STR_PLAY ) ) );
            mbLabelPlaying = FALSE;
        }
        catch( css::lang::IllegalArgumentException )
        {
#ifdef DBG_UTIL
            DBG_ERROR( "Cannot access play button" );
#endif
        }
    }

    return( 0L );
}

// check whether to disable the "selection" checkbox
void SdFileDialog_Imp::CheckSelectionState()
{
    if( mbUsableSelection && mxControlAccess.is() )
    {
        String  aCurrFilter( GetCurrentFilter() );

        try
        {
            if( !aCurrFilter.Len() || ( aCurrFilter == String( SdResId( STR_EXPORT_HTML_NAME ) ) ) )
                mxControlAccess->enableControl( css::ui::dialogs::ExtendedFilePickerElementIds::CHECKBOX_SELECTION, FALSE );
            else
                mxControlAccess->enableControl( css::ui::dialogs::ExtendedFilePickerElementIds::CHECKBOX_SELECTION, TRUE );
        }
        catch( css::lang::IllegalArgumentException )
        {
#ifdef DBG_UTIL
            DBG_ERROR( "Cannot access \"selection\" checkbox" );
#endif
        }
    }
}

//-----------------------------------------------------------------------------
SdFileDialog_Imp::SdFileDialog_Imp( const short     nDialogType,
                                    sal_Bool        bUsableSelection    ) :
    FileDialogHelper( nDialogType, 0 ),
    mnPlaySoundEvent( 0 ),
    mbUsableSelection( bUsableSelection ),
    mbLabelPlaying(FALSE)
{
    maUpdateTimer.SetTimeoutHdl(LINK(this, SdFileDialog_Imp, IsMusicStoppedHdl));

    css::uno::Reference < ::com::sun::star::ui::dialogs::XFilePicker > xFileDlg = GetFilePicker();

    // get the control access
    mxControlAccess = css::uno::Reference< css::ui::dialogs::XFilePickerControlAccess > ( xFileDlg, css::uno::UNO_QUERY );

    if( mxControlAccess.is() )
    {
        if( nDialogType ==
            css::ui::dialogs::TemplateDescription::FILEOPEN_PLAY )
        {
            try
            {
                mxControlAccess->setLabel( css::ui::dialogs::ExtendedFilePickerElementIds::PUSHBUTTON_PLAY,
                                           String( SdResId( STR_PLAY ) ) );
            }
            catch( css::lang::IllegalArgumentException )
            {
#ifdef DBG_UTIL
                DBG_ERROR( "Cannot set play button label" );
#endif
            }
        }
        else if( mbUsableSelection != sal_True )
        {
            try
            {
                mxControlAccess->enableControl( css::ui::dialogs::ExtendedFilePickerElementIds::CHECKBOX_SELECTION, FALSE );
            }
            catch( css::lang::IllegalArgumentException )
            {
#ifdef DBG_UTIL
                DBG_ERROR( "Cannot disable selection checkbox" );
#endif
            }
        }
    }
}

// ------------------------------------------------------------------------
SdFileDialog_Imp::~SdFileDialog_Imp()
{
    if( mnPlaySoundEvent )
        Application::RemoveUserEvent( mnPlaySoundEvent );
}

// ------------------------------------------------------------------------
ErrCode SdFileDialog_Imp::Execute()
{
    // make sure selection checkbox is disabled if
    // HTML is current filter!
    CheckSelectionState();
    return FileDialogHelper::Execute();
}

// ------------------------------------------------------------------------
sal_Bool SdFileDialog_Imp::SelectionBoxState() const
{
    if ( !mbUsableSelection || !mxControlAccess.is() )
        return sal_False;

    sal_Bool bState(0);
    try
    {
        mxControlAccess->getValue( css::ui::dialogs::ExtendedFilePickerElementIds::CHECKBOX_SELECTION, 0 ) >>= bState;
    }
    catch( css::lang::IllegalArgumentException )
    {
#ifdef DBG_UTIL
        DBG_ERROR( "Cannot access \"selection\" checkbox" );
#endif
    }

    return bState;
}

// --------------------------------------------------------------------
// -----------      SdExportFileDialog      ---------------------------
// --------------------------------------------------------------------

// these are simple forwarders
SdExportFileDialog::SdExportFileDialog(BOOL bHaveCheckbox) :
    mpImpl( new SdFileDialog_Imp( css::ui::dialogs::TemplateDescription::FILESAVE_AUTOEXTENSION_SELECTION,
                                  bHaveCheckbox ) )
{
    // setup filter
    const String    aHTMLFilter( SdResId( STR_EXPORT_HTML_NAME ) );
    GraphicFilter*  pFilter = GetGrfFilter();
    const USHORT    nFilterCount = pFilter->GetExportFormatCount();

    // add HTML filter
    mpImpl->AddFilter( aHTMLFilter, String( SdResId( STR_EXPORT_HTML_FILTER ) ) );

    // add other graphic filters
    for ( USHORT i = 0; i < nFilterCount; i++ )
    {
        mpImpl->AddFilter( pFilter->GetExportFormatName( i ),
                           pFilter->GetExportWildcard( i ) );
    }

    // set dialog title
    mpImpl->SetTitle( String( SdResId( STR_EXPORT_DIALOG_TITLE ) ) );
}

// ------------------------------------------------------------------------
SdExportFileDialog::~SdExportFileDialog()
{
}

// ------------------------------------------------------------------------
ErrCode SdExportFileDialog::Execute()
{
    return mpImpl->Execute();
}

String SdExportFileDialog::GetPath() const
{
    return mpImpl->GetPath();
}

// ------------------------------------------------------------------------
void SdExportFileDialog::SetPath( const String& rPath )
{
    mpImpl->SetDisplayDirectory( rPath );
}

// ------------------------------------------------------------------------
String SdExportFileDialog::ReqCurrentFilter() const
{
    return mpImpl->GetCurrentFilter();
}

// ------------------------------------------------------------------------
BOOL SdExportFileDialog::IsExportSelection() const
{
    return mpImpl->SelectionBoxState();
}

// --------------------------------------------------------------------
// -----------      SdOpenSoundFileDialog       -----------------------
// --------------------------------------------------------------------

// these are simple forwarders
SdOpenSoundFileDialog::SdOpenSoundFileDialog() :
    mpImpl(
        new SdFileDialog_Imp(
            css::ui::dialogs::TemplateDescription::FILEOPEN_PLAY, sal_False ) )
{
    String aDescr;
    aDescr = String(SdResId(STR_ALL_FILES));
    mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "*.*" ) ) );

    // setup filter
#if defined UNX
    aDescr = String(SdResId(STR_AU_FILE));
    mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "*.au;*.snd" ) ) );
    aDescr = String(SdResId(STR_VOC_FILE));
    mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "*.voc" ) ) );
    aDescr = String(SdResId(STR_WAV_FILE));
    mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "*.wav" ) ) );
    aDescr = String(SdResId(STR_AIFF_FILE));
    mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "*.aiff" ) ) );
    aDescr = String(SdResId(STR_SVX_FILE));
    mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "*.svx" ) ) );
#else
    aDescr = String(SdResId(STR_WAV_FILE));
    mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "*.wav;*.mp3;*.ogg" ) ) );
    aDescr = String(SdResId(STR_MIDI_FILE));
    mpImpl->AddFilter( aDescr, UniString::CreateFromAscii( RTL_CONSTASCII_STRINGPARAM( "*.mid" ) ) );
#endif
}

// ------------------------------------------------------------------------
SdOpenSoundFileDialog::~SdOpenSoundFileDialog()
{
}

// ------------------------------------------------------------------------
ErrCode SdOpenSoundFileDialog::Execute()
{
    return mpImpl->Execute();
}

// ------------------------------------------------------------------------
String SdOpenSoundFileDialog::GetPath() const
{
    return mpImpl->GetPath();
}

// ------------------------------------------------------------------------
void SdOpenSoundFileDialog::SetPath( const String& rPath )
{
    mpImpl->SetDisplayDirectory( rPath );
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: docprev.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: kz $ $Date: 2008-04-03 14:00:46 $
 *
 *  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 _SD_DOCPREV_HXX_
#define _SD_DOCPREV_HXX_

#ifndef _COM_SUN_STAR_PRESENTATION_FADEEFFECT_HPP_
#include <com/sun/star/presentation/FadeEffect.hpp>
#endif

#ifndef _SV_WINDOW_HXX //autogen
#include <vcl/window.hxx>
#endif

#ifndef _SV_GEN_HXX //autogen
#include <tools/gen.hxx>
#endif

#include <rtl/ref.hxx>

#ifndef _SFXLSTNER_HXX
#include <svtools/lstner.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_COLORCFG_HXX
#include <svtools/colorcfg.hxx>
#endif

#ifndef _SD_FADEDEF_H
#include "fadedef.h"
#endif
#ifndef INCLUDED_SDDLLAPI_H
#include "sddllapi.h"
#endif

namespace sd {
    class SlideShow;
}

class GDIMetaFile;

class SD_DLLPUBLIC SdDocPreviewWin : public Control, public SfxListener
{
protected:
    GDIMetaFile*    pMetaFile;
    BOOL            bInEffect;
    Link            aClickHdl;
    SfxObjectShell* mpObj;
    sal_uInt16      mnShowPage;
    Color           maDocumentColor;
    rtl::Reference< sd::SlideShow > mxSlideShow;

    virtual void    Paint( const Rectangle& rRect );
    static void     CalcSizeAndPos( GDIMetaFile* pFile, Size& rSize, Point& rPoint );
    void            ImpPaint( GDIMetaFile* pFile, OutputDevice* pVDev );

    static const int FRAME;

    svtools::ColorConfig maColorConfig;

    virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType);

    void updateViewSettings();

public:
                    SdDocPreviewWin( Window* pParent, const ResId& rResId );
                    SdDocPreviewWin( Window* pParent );
                    ~SdDocPreviewWin();
    void            SetObjectShell( SfxObjectShell* pObj, sal_uInt16 nShowPage = 0 );
    void            SetGDIFile( GDIMetaFile* pFile );
    virtual void    Resize();
    void            startPreview();

    virtual long    Notify( NotifyEvent& rNEvt );

    void            SetClickHdl( const Link& rLink ) { aClickHdl = rLink; }
    const Link&     GetClickHdl() const { return aClickHdl; }

    virtual void DataChanged( const DataChangedEvent& rDCEvt );

};

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.8.624); FILE MERGED 2008/04/01 15:35:22 thb 1.8.624.3: #i85898# Stripping all external header guards 2008/04/01 12:39:03 thb 1.8.624.2: #i85898# Stripping all external header guards 2008/03/31 13:58:13 rt 1.8.624.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: docprev.hxx,v $
 * $Revision: 1.10 $
 *
 * 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 _SD_DOCPREV_HXX_
#define _SD_DOCPREV_HXX_

#include <com/sun/star/presentation/FadeEffect.hpp>
#include <vcl/window.hxx>
#include <tools/gen.hxx>

#include <rtl/ref.hxx>

#include <svtools/lstner.hxx>
#include <svtools/colorcfg.hxx>
#include "fadedef.h"
#include "sddllapi.h"

namespace sd {
    class SlideShow;
}

class GDIMetaFile;

class SD_DLLPUBLIC SdDocPreviewWin : public Control, public SfxListener
{
protected:
    GDIMetaFile*    pMetaFile;
    BOOL            bInEffect;
    Link            aClickHdl;
    SfxObjectShell* mpObj;
    sal_uInt16      mnShowPage;
    Color           maDocumentColor;
    rtl::Reference< sd::SlideShow > mxSlideShow;

    virtual void    Paint( const Rectangle& rRect );
    static void     CalcSizeAndPos( GDIMetaFile* pFile, Size& rSize, Point& rPoint );
    void            ImpPaint( GDIMetaFile* pFile, OutputDevice* pVDev );

    static const int FRAME;

    svtools::ColorConfig maColorConfig;

    virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType);

    void updateViewSettings();

public:
                    SdDocPreviewWin( Window* pParent, const ResId& rResId );
                    SdDocPreviewWin( Window* pParent );
                    ~SdDocPreviewWin();
    void            SetObjectShell( SfxObjectShell* pObj, sal_uInt16 nShowPage = 0 );
    void            SetGDIFile( GDIMetaFile* pFile );
    virtual void    Resize();
    void            startPreview();

    virtual long    Notify( NotifyEvent& rNEvt );

    void            SetClickHdl( const Link& rLink ) { aClickHdl = rLink; }
    const Link&     GetClickHdl() const { return aClickHdl; }

    virtual void DataChanged( const DataChangedEvent& rDCEvt );

};

#endif

<|endoftext|>


<commit_before>#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
#include <sstream>
#include "StateSpace.h"
#include "PriorityQueue.h"
#include "State.h"
#include "encoder.h"
#include "CreateModule.h"

/**
 * @brief Gives a std::string representation of a primitive type
 *
 * @param x Primitive type such as int, double, long
 * @return std::string conversion of param x
 */
template<typename T> std::string to_string(T x) {
	return static_cast<std::ostringstream&>((std::ostringstream() << std::dec << x)).str();
}

//function to calculate a temperature for the select action function as a function of time
double temperature();

//function to select next action
int * selectAction(PriorityQueue<int,double>& a_queue);

//function to update a q value
void updateQ(StateSpace & space, int * action, State & new_state, State & old_state, double alpha, double gamma);

int main()
{
	// STUFF WE DONT UNDERSTAND, AND DONT NEED TO
	//__________________________________________________________________________________________
	//__________________________________________________________________________________________
	// Libraries to load
	std::string bodyLibName = "bodyinfo";
	std::string movementLibName = "movementtools";

	// Name of camera module in library
	std::string bodyModuleName = "BodyInfo";
	std::string movementModuleName = "MovementTools";

	// Set broker name, ip and port, finding first available port from 54000
	const std::string brokerName = "MotionTimingBroker";
	int brokerPort = qi::os::findAvailablePort(54000);
	const std::string brokerIp = "0.0.0.0";

	// Default parent port and ip
	int pport = 9559;
	std::string pip = "127.0.0.1";

	// Need this for SOAP serialisation of floats to work
	setlocale(LC_NUMERIC, "C");

	// Create a broker
	boost::shared_ptr<AL::ALBroker> broker;
	try
	{
		broker = AL::ALBroker::createBroker(
				brokerName,
				brokerIp,
				brokerPort,
				pip,
				pport,
				0);
	}
	// Throw error and quit if a broker could not be created
	catch(...)
	{
		std::cerr << "Failed to connect broker to: "
			  << pip
			  << ":"
			  << pport
			  << std::endl;
		AL::ALBrokerManager::getInstance()->killAllBroker();
		AL::ALBrokerManager::kill();

		return 1;
	}

	// Add the broker to NAOqi
	AL::ALBrokerManager::setInstance(broker->fBrokerManager.lock());
	AL::ALBrokerManager::getInstance()->addBroker(broker);

	CreateModule(movementLibName, movementModuleName, broker, false, true);
	CreateModule(bodyLibName, bodyModuleName, broker, false, true);

	AL::ALProxy bodyInfoProxy(bodyModuleName, pip, pport);
	AL::ALProxy movementToolsProxy(movementModuleName, pip, pport);
	AL::ALMotionProxy motion(pip, pport);
	//__________________________________________________________________________________________
	//__________________________________________________________________________________________
	//END OF STUFF WE DONT UNDERSTAND, BREATHE NOW

	//learning factor
	const double alpha=0.5;
	//discount factor
	const double gamma=0.5;

	//seed rng
	std::srand(std::time(NULL));

	int action_forwards = FORWARD;
	int* p_action_forwards = &action_forwards;
	int action_backwards = BACKWARD;
	int* p_action_backwards = &action_backwards;
	int* chosen_action = &action_forwards;

	//create a priority queue to copy to all the state space priority queues
	PriorityQueue<int*,double> initiator_queue(MAX);
	initiator_queue.enqueueWithPriority(p_action_forwards,0);
	initiator_queue.enqueueWithPriority(p_action_backwards,0);

	//create encoder
	Encoder encoder();
	encoder.calibrate();

	//create the state space
	StateSpace space(initiator_queue);
	space.setAngle(100);
	space.setVelocity(50);

	//state objects
	State current_state(0,0,FORWARD);
	State old_state(0,0,FORWARD);

	while(true)
	{
		current_state.theta= M_PI * encoder.GetAngle()/180;
		current_state.theta_dot=(current_state.theta - old_state.theta)/700; //Needs actual time
		current_state.robot_state=*chosen_action;

		updateQ(space, chosen_action, old_state, current_state, alpha, gamma);

		old_state=current_state;

		chosen_action=selectAction(space[current_state]);

		(*chosen_action)?movementToolsProxy.callVoid("swingForwards"):movementToolsProxy.callVoid("swingBackwards");
	}

	return 1;
}

double temperature()
{
	return std::time(NULL);
}

//function is fed with a priority queue of action-values
//generates Boltzmann distribution of these action-values
//and selects an action based on probabilities
int * selectAction(PriorityQueue<int *,double>& a_queue)
{
	typedef PriorityQueue<int *,double> PQ;
	typedef std::vector< std::pair<int *, double> > Vec_Pair;
	typedef std::pair<int *, double> Pair;

	double sum= 0;
	int i = 0;

	int size = a_queue.getSize();
	Vec_Pair action_vec(size);

	//Calculate partition function by iterating over action-values
	for(PQ::const_iterator iter = a_queue.begin(),end=a_queue.end(); iter < end; ++iter)
	{
		sum += std::exp((iter->second)/temperature());
	}
	//Calculate boltzmann factors for action-values
	for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
	{
	    it->first = a_queue[i].first;
	    it->second = std::exp(a_queue[i].second /temperature()) / sum;
	    ++i;
	}

	//calculate cumulative probability distribution
	for(Vec_Pair::iterator it1 = action_vec.begin()++,it2 = action_vec.begin(),end=action_vec.end(); it < end; ++it1,++it2)
	{
	    it1->second += it2->second;
	}

	//generate RN between 0 and 1
	double rand_num = static_cast<double>(rand()/ (RAND_MAX));

	//select action based on probability
	for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
	{
		//if RN falls within cumulative probability bin return the corresponding action
		if(rand_num < it->second)return &(it->first);
	}

	return NULL; //note that this line should never be reached
}

void updateQ(StateSpace & space, int * action, State & new_state, State & old_state, double alpha, double gamma)
{
    //oldQ value reference
    double oldQ = space[old_state].search(action).second;

    //reward given to current state
    double R = new_state.getReward();

    //optimal Q value for new state i.e. first element
    double maxQ = space[current_state].peekFront().second;

    //new Q value determined by Q learning algorithm
    double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);

    // change priority of action to new Q value
    space[old_state].changePriority(action, newQ);
}

<commit_msg>Update Main.cpp<commit_after>#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string>
#include <sstream>
#include "StateSpace.h"
#include "PriorityQueue.h"
#include "State.h"
#include "encoder.h"
#include "CreateModule.h"

/**
 * @brief Gives a std::string representation of a primitive type
 *
 * @param x Primitive type such as int, double, long
 * @return std::string conversion of param x
 */
template<typename T> std::string to_string(T x) {
	return static_cast<std::ostringstream&>((std::ostringstream() << std::dec << x)).str();
}

//function to calculate a temperature for the select action function as a function of time
double temperature();

//function to select next action
int * selectAction(PriorityQueue<int,double>& a_queue);

//function to update a q value
void updateQ(StateSpace & space, int * action, State & new_state, State & old_state, double alpha, double gamma);

int main()
{
	// STUFF WE DONT UNDERSTAND, AND DONT NEED TO
	//__________________________________________________________________________________________
	//__________________________________________________________________________________________
	// Libraries to load
	std::string bodyLibName = "bodyinfo";
	std::string movementLibName = "movementtools";

	// Name of camera module in library
	std::string bodyModuleName = "BodyInfo";
	std::string movementModuleName = "MovementTools";

	// Set broker name, ip and port, finding first available port from 54000
	const std::string brokerName = "MotionTimingBroker";
	int brokerPort = qi::os::findAvailablePort(54000);
	const std::string brokerIp = "0.0.0.0";

	// Default parent port and ip
	int pport = 9559;
	std::string pip = "127.0.0.1";

	// Need this for SOAP serialisation of floats to work
	setlocale(LC_NUMERIC, "C");

	// Create a broker
	boost::shared_ptr<AL::ALBroker> broker;
	try
	{
		broker = AL::ALBroker::createBroker(
				brokerName,
				brokerIp,
				brokerPort,
				pip,
				pport,
				0);
	}
	// Throw error and quit if a broker could not be created
	catch(...)
	{
		std::cerr << "Failed to connect broker to: "
			  << pip
			  << ":"
			  << pport
			  << std::endl;
		AL::ALBrokerManager::getInstance()->killAllBroker();
		AL::ALBrokerManager::kill();

		return 1;
	}

	// Add the broker to NAOqi
	AL::ALBrokerManager::setInstance(broker->fBrokerManager.lock());
	AL::ALBrokerManager::getInstance()->addBroker(broker);

	CreateModule(movementLibName, movementModuleName, broker, false, true);
	CreateModule(bodyLibName, bodyModuleName, broker, false, true);

	AL::ALProxy bodyInfoProxy(bodyModuleName, pip, pport);
	AL::ALProxy movementToolsProxy(movementModuleName, pip, pport);
	AL::ALMotionProxy motion(pip, pport);
	//__________________________________________________________________________________________
	//__________________________________________________________________________________________
	//END OF STUFF WE DONT UNDERSTAND, BREATHE NOW

	//learning factor
	const double alpha=0.5;
	//discount factor
	const double gamma=0.5;

	//seed rng
	std::srand(std::time(NULL));

	int action_forwards = FORWARD;
	int* p_action_forwards = &action_forwards;
	int action_backwards = BACKWARD;
	int* p_action_backwards = &action_backwards;
	int* chosen_action = &action_forwards;

	//create a priority queue to copy to all the state space priority queues
	PriorityQueue<int*,double> initiator_queue(MAX);
	initiator_queue.enqueueWithPriority(p_action_forwards,0);
	initiator_queue.enqueueWithPriority(p_action_backwards,0);

	//create encoder
	Encoder encoder();
	encoder.calibrate();

	//create the state space
	StateSpace space(initiator_queue);
	space.setAngleBins(100);
	space.setVelocityBins(50);

	//state objects
	State current_state(0,0,FORWARD);
	State old_state(0,0,FORWARD);

	while(true)
	{
		current_state.theta= M_PI * encoder.GetAngle()/180;
		current_state.theta_dot=(current_state.theta - old_state.theta)/700; //Needs actual time
		current_state.robot_state=*chosen_action;

		updateQ(space, chosen_action, old_state, current_state, alpha, gamma);

		old_state=current_state;

		chosen_action=selectAction(space[current_state]);

		(*chosen_action)?movementToolsProxy.callVoid("swingForwards"):movementToolsProxy.callVoid("swingBackwards");
	}

	return 1;
}

double temperature()
{
	return std::time(NULL);
}

//function is fed with a priority queue of action-values
//generates Boltzmann distribution of these action-values
//and selects an action based on probabilities
int * selectAction(PriorityQueue<int *,double>& a_queue)
{
	typedef PriorityQueue<int *,double> PQ;
	typedef std::vector< std::pair<int *, double> > Vec_Pair;
	typedef std::pair<int *, double> Pair;

	double sum= 0;
	int i = 0;

	int size = a_queue.getSize();
	Vec_Pair action_vec(size);

	//Calculate partition function by iterating over action-values
	for(PQ::const_iterator iter = a_queue.begin(),end=a_queue.end(); iter < end; ++iter)
	{
		sum += std::exp((iter->second)/temperature());
	}
	//Calculate boltzmann factors for action-values
	for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
	{
	    it->first = a_queue[i].first;
	    it->second = std::exp(a_queue[i].second /temperature()) / sum;
	    ++i;
	}

	//calculate cumulative probability distribution
	for(Vec_Pair::iterator it1 = action_vec.begin()++,it2 = action_vec.begin(),end=action_vec.end(); it < end; ++it1,++it2)
	{
	    it1->second += it2->second;
	}

	//generate RN between 0 and 1
	double rand_num = static_cast<double>(rand()/ (RAND_MAX));

	//select action based on probability
	for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
	{
		//if RN falls within cumulative probability bin return the corresponding action
		if(rand_num < it->second)return &(it->first);
	}

	return NULL; //note that this line should never be reached
}

void updateQ(StateSpace & space, int * action, State & new_state, State & old_state, double alpha, double gamma)
{
    //oldQ value reference
    double oldQ = space[old_state].search(action).second;

    //reward given to current state
    double R = new_state.getReward();

    //optimal Q value for new state i.e. first element
    double maxQ = space[current_state].peekFront().second;

    //new Q value determined by Q learning algorithm
    double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);

    // change priority of action to new Q value
    space[old_state].changePriority(action, newQ);
}

<|endoftext|>


<commit_before>/*
UselessMine
    Copyright (C) 2014 Vladimir "allejo" Jimenez

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <memory>
#include <stdlib.h>

#include "bzfsAPI.h"
#include "bztoolkit/bzToolkitAPI.h"

// Define plugin name
const std::string PLUGIN_NAME = "Useless Mine";

// Define plugin version numbering
const int MAJOR = 1;
const int MINOR = 0;
const int REV = 0;
const int BUILD = 8;

class UselessMine : public bz_Plugin, public bz_CustomSlashCommandHandler
{
public:
    virtual const char* Name ();
    virtual void Init (const char* config);
    virtual void Event (bz_EventData *eventData);
    virtual void Cleanup (void);

    virtual bool SlashCommand (int playerID, bz_ApiString, bz_ApiString, bz_APIStringList*);

    virtual int  getMineCount ();
    virtual void initializeMessages (void),
                 removeAllMines(int playerID),
                 removeMine (int mineIndex),
                 setMine (int owner, float pos[3], bz_eTeamType team);

    // The information each mine will contain
    struct Mine
    {
        int owner, victim; // The owner of the mine and the victim, respectively

        float x, y, z;     // The coordinates of where the mine was placed

        bz_eTeamType team; // The team of the owner

        bool detonated;    // Whether or not the mine has been detonated; to prepare it for removal from play

        Mine (int _owner, float _pos[3], bz_eTeamType _team) :
            owner(_owner),
            victim(-1),
            x(_pos[0]),
            y(_pos[1]),
            z(_pos[2]),
            team(_team),
            detonated(false)
        {}
    };

    std::vector<Mine>        activeMines;   // A vector that will store all of the mines that are in play
    std::vector<std::string> deathMessages; // A vector that will store all of the witty death messages

    double bzdb_SpawnSafetyTime, // The BZDB variable that will store the amount of seconds a player has before a mine is detonated
           playerSpawnTime[256]; // The time of a player's last spawn time used to calculate their safety from detonation
};

BZ_PLUGIN(UselessMine)

const char* UselessMine::Name (void)
{
    static std::string pluginBuild = "";

    if (!pluginBuild.size())
    {
        std::ostringstream pluginBuildStream;

        pluginBuildStream << PLUGIN_NAME << " " << MAJOR << "." << MINOR << "." << REV << " (" << BUILD << ")";
        pluginBuild = pluginBuildStream.str();
    }

    return pluginBuild.c_str();
}

void UselessMine::Init (const char* commandLine)
{
    // Register our events with Register()
    Register(bz_eFlagGrabbedEvent);
    Register(bz_ePlayerDieEvent);
    Register(bz_ePlayerPartEvent);
    Register(bz_ePlayerSpawnEvent);
    Register(bz_ePlayerUpdateEvent);

    // Register our custom slash commands
    bz_registerCustomSlashCommand("mine", this);

    // Initialize all of the witty death messages
    initializeMessages();

    // Set some custom BZDB variables
    bzdb_SpawnSafetyTime = bztk_registerCustomDoubleBZDB("_mineSafetyTime", 5.0);
}

void UselessMine::Cleanup (void)
{
    Flush(); // Clean up all the events

    // Clean up our custom slash commands
    bz_removeCustomSlashCommand("mine");
}

void UselessMine::Event (bz_EventData *eventData)
{
    switch (eventData->eventType)
    {
        case bz_eFlagGrabbedEvent: // This event is called each time a flag is grabbed by a player
        {
            bz_FlagGrabbedEventData_V1* flagGrabData = (bz_FlagGrabbedEventData_V1*)eventData;

            // Data
            // ---
            //    (int)           playerID  - The player that grabbed the flag
            //    (int)           flagID    - The flag ID that was grabbed
            //    (bz_ApiString)  flagType  - The flag abbreviation of the flag that was grabbed
            //    (float[3])      pos       - The position at which the flag was grabbed
            //    (double)        eventTime - This value is the local server time of the event.

            // If the user grabbed the Useless flag, let them know they can place a mine
            if (strcmp(flagGrabData->flagType, "US") == 0)
            {
                bz_sendTextMessage(BZ_SERVER, flagGrabData->playerID, "You grabbed a Useless flag! Type /mine at any time to set a useless mine!");
            }
        }
        break;

        case bz_ePlayerDieEvent: // This event is called each time a tank is killed.
        {
            bz_PlayerDieEventData_V1* dieData = (bz_PlayerDieEventData_V1*)eventData;

            // Data
            // ---
            //   (int)                   playerID       - ID of the player who was killed.
            //   (bz_eTeamType)          team           - The team the killed player was on.
            //   (int)                   killerID       - The owner of the shot that killed the player, or BZ_SERVER for server side kills
            //   (bz_eTeamType)          killerTeam     - The team the owner of the shot was on.
            //   (bz_ApiString)          flagKilledWith - The flag name the owner of the shot had when the shot was fired.
            //   (int)                   shotID         - The shot ID that killed the player, if the player was not killed by a shot, the id will be -1.
            //   (bz_PlayerUpdateState)  state          - The state record for the killed player at the time of the event
            //   (double)                eventTime      - Time of the event on the server.

            int playerID = dieData->playerID;

            // Loop through all the mines in play
            for (int i = 0; i < getMineCount(); i++)
            {
                // Create a local variable for easy access
                Mine &detonatedMine = activeMines.at(i);

                // Check if the mine has already been detonated
                if (detonatedMine.detonated)
                {
                    // Check if the victim killed is the player who just died
                    if (detonatedMine.victim == playerID)
                    {
                        // Check if the player who just died was killed by the server
                        if (dieData->killerID == 253)
                        {
                            // The random number used to fetch a random taunting death message
                            int randomNumber = rand() % deathMessages.size();

                            // Get the callsigns of the players
                            const char* owner  = bz_getPlayerCallsign(detonatedMine.owner);
                            const char* victim = bz_getPlayerCallsign(detonatedMine.victim);

                            // Attribute the kill to the mine owner
                            dieData->killerID = detonatedMine.owner;

                            // This mine has been detonated and we're done with the information that we need
                            removeMine(i);

                            bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS, deathMessages.at(randomNumber).c_str(), owner, victim);
                            break;
                        }
                    }
                }
            }
        }
        break;

        case bz_ePlayerPartEvent: // This event is called each time a player leaves a game
        {
            bz_PlayerJoinPartEventData_V1* partData = (bz_PlayerJoinPartEventData_V1*)eventData;

            // Data
            // ---
            //    (int)                   playerID  - The player ID that is leaving
            //    (bz_BasePlayerRecord*)  record    - The player record for the leaving player
            //    (bz_ApiString)          reason    - The reason for leaving, such as a kick or a ban
            //    (double)                eventTime - Time of event.

            int playerID = partData->playerID;

            removeAllMines(playerID);
        }
        break;

        case bz_ePlayerSpawnEvent: // This event is called each time a playing tank is being spawned into the world
        {
            bz_PlayerSpawnEventData_V1* spawnData = (bz_PlayerSpawnEventData_V1*)eventData;

            // Data
            // ---
            //    (int)                   playerID  - ID of the player who was added to the world.
            //    (bz_eTeamType)          team      - The team the player is a member of.
            //    (bz_PlayerUpdateState)  state     - The state record for the spawning player
            //    (double)                eventTime - Time local server time for the event.

            int playerID = spawnData->playerID;

            // Save the time the player spawned last
            playerSpawnTime[playerID] = bz_getCurrentTime();
        }
        break;

        case bz_ePlayerUpdateEvent: // This event is called each time a player sends an update to the server
        {
            bz_PlayerUpdateEventData_V1* updateData = (bz_PlayerUpdateEventData_V1*)eventData;

            // Data
            // ---
            //   (int)       playerID  - ID of the player that sent the update
            //   (float[3])  pos       - The player's current position
            //   (float[3])  velocity  - The player's current velocity
            //   (float)     azimuth   - The direction the player is facing
            //   (float)     angvel    - The player's angular velocity
            //   (int)       phydrv    - The physics driver the player is on
            //   (double)    eventTime - The current server time

            int playerID = updateData->playerID;

            // Loop through all of the players
            for (int i = 0; i < getMineCount(); i++)
            {
                // Make an easy access mine
                Mine &currentMine = activeMines.at(i);

                // If the mine owner is not the player triggering the mine (so no self kills) and the player is a rogue or does is an enemy team relative to the mine owner
                if (currentMine.owner != playerID && (bz_getPlayerTeam(playerID) == eRogueTeam || bz_getPlayerTeam(playerID) != currentMine.team))
                {
                    // Make easy to access variables
                    float  playerPos[3] = {updateData->state.pos[0], updateData->state.pos[1], updateData->state.pos[2]};
                    double shockRange   = bz_getBZDBDouble("_shockOutRadius") * 0.75;

                    // Check if the player is in the detonation range
                    if ((playerPos[0] > currentMine.x - shockRange && playerPos[0] < currentMine.x + shockRange) &&
                        (playerPos[1] > currentMine.y - shockRange && playerPos[1] < currentMine.y + shockRange) &&
                        (playerPos[2] > currentMine.z - shockRange && playerPos[2] < currentMine.z + shockRange) &&
                        playerSpawnTime[playerID] + bzdb_SpawnSafetyTime <= bz_getCurrentTime() && !currentMine.detonated)
                    {
                        // Check that the mine owner exists and is not an observer
                        if (bztk_isValidPlayerID(currentMine.owner) && bz_getPlayerTeam(currentMine.owner) != eObservers)
                        {
                            // Get the current mine position
                            float minePos[3] = {currentMine.x, currentMine.y, currentMine.z};

                            // Save who detonated the mine and mark it as detonated
                            currentMine.victim    = playerID;
                            currentMine.detonated = true;

                            // BOOM!
                            bz_fireWorldWep("SW", 2.0, BZ_SERVER, minePos, 0, 0, 0, currentMine.team);
                        }
                        // Just in case the player doesn't exist or is an observer, then remove the mine because it shouldn't be there
                        else
                        {
                            removeMine(i);
                        }

                        break;
                    }
                }
            }
        }
        break;

        default: break;
    }
}

bool UselessMine::SlashCommand(int playerID, bz_ApiString command, bz_ApiString /*message*/, bz_APIStringList *params)
{
    if (command == "mine")
    {
        std::shared_ptr<bz_BasePlayerRecord> playerRecord(bz_getPlayerByIndex(playerID));

        // If the player is not an observer, they let them proceed to the next check
        if (playerRecord->team != eObservers)
        {
            // Check if the player has the Useless flag
            if (playerRecord->currentFlag == "USeless (+US)")
            {
                // Store their current position
                float currentPosition[3] = {playerRecord->lastKnownState.pos[0], playerRecord->lastKnownState.pos[1], playerRecord->lastKnownState.pos[2]};

                setMine(playerID, currentPosition, playerRecord->team);
            }
            else
            {
                bz_sendTextMessage(BZ_SERVER, playerID, "You can't place a mine without the Useless flag!");
            }
        }
        else
        {
            bz_sendTextMessage(BZ_SERVER, playerID, "Silly observer, you can't place a mine.");
        }

        return true;
    }
}

// A shortcut to get the amount of mines that are in play
int UselessMine::getMineCount()
{
    return activeMines.size();
}

// In order to keep things organized, this function is where you can specify all the witty death messages you want to be available
void UselessMine::initializeMessages()
{
    deathMessages.push_back("%s was killed by %s's mine.");
    deathMessages.push_back("%s was owned by %s's mine.");
    deathMessages.push_back("%s was obliterated by %s's mine.");
    deathMessages.push_back("%s's tank disintegrated from %s's mine.");
    deathMessages.push_back("%s was permanently blinded by the bright light from %s's mine.");
    deathMessages.push_back("%s was sent shooting into the stars by %s's mine.");
    deathMessages.push_back("%s was never heard from again thanks to %s's mine.");
    deathMessages.push_back("We salute %s for taking an atrocious hit from %s's mine.");
    deathMessages.push_back("%s's mine left %s's tank parts scattered all over.");
    deathMessages.push_back("%s thought %s's mine was a shiny brand new car.");
    deathMessages.push_back("%s was bombarded by many concussive attacks from %s's mine.");
    deathMessages.push_back("%s was ignited by %s's mine.");
    deathMessages.push_back("%s's mine bursted %s's tank to bite-size flaming pieces.");
    deathMessages.push_back("%s took a nosedive into %s's mine.");
    deathMessages.push_back("%s fell face first into %s's mine.");
    deathMessages.push_back("I knew %s would be clumsy enough to run into %s's mine.");
    deathMessages.push_back("%s killed %s with a mine. No surprise there.");
    deathMessages.push_back("DID YOU SEE THAT? %s did total carnage to %s's tank with that one little mine.");
    deathMessages.push_back("%s purposely ran into %s's mine.");
    deathMessages.push_back("I ascertain that %s has been ruptured by a mine created from the heavens with the name dubbed %s.");
}

void UselessMine::removeAllMines(int playerID)
{
    // Go through all of the mines
    for (int i = 0; i < getMineCount(); i++)
    {
        // Quick access mine
        Mine &currentMine = activeMines.at(i);

        // If the mine belongs to the player, remove it
        if (currentMine.owner == playerID)
        {
            removeMine(i);
        }
    }
}

// A shortcut to remove a mine from play
void UselessMine::removeMine(int mineIndex)
{
    activeMines.erase(activeMines.begin() + mineIndex);
}

// A shortcut to set a mine
void UselessMine::setMine(int owner, float pos[3], bz_eTeamType team)
{
    // Remove their flag because it's going to be a US flag
    bz_removePlayerFlag(owner);

    // Push the new mine
    Mine newMine(owner, pos, team);
    activeMines.push_back(newMine);
}<commit_msg>Silly me. Fix order of mine owner and victim in death messages<commit_after>/*
UselessMine
    Copyright (C) 2014 Vladimir "allejo" Jimenez

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <memory>
#include <stdlib.h>

#include "bzfsAPI.h"
#include "bztoolkit/bzToolkitAPI.h"

// Define plugin name
const std::string PLUGIN_NAME = "Useless Mine";

// Define plugin version numbering
const int MAJOR = 1;
const int MINOR = 0;
const int REV = 0;
const int BUILD = 8;

class UselessMine : public bz_Plugin, public bz_CustomSlashCommandHandler
{
public:
    virtual const char* Name ();
    virtual void Init (const char* config);
    virtual void Event (bz_EventData *eventData);
    virtual void Cleanup (void);

    virtual bool SlashCommand (int playerID, bz_ApiString, bz_ApiString, bz_APIStringList*);

    virtual int  getMineCount ();
    virtual void initializeMessages (void),
                 removeAllMines(int playerID),
                 removeMine (int mineIndex),
                 setMine (int owner, float pos[3], bz_eTeamType team);

    // The information each mine will contain
    struct Mine
    {
        int owner, victim; // The owner of the mine and the victim, respectively

        float x, y, z;     // The coordinates of where the mine was placed

        bz_eTeamType team; // The team of the owner

        bool detonated;    // Whether or not the mine has been detonated; to prepare it for removal from play

        Mine (int _owner, float _pos[3], bz_eTeamType _team) :
            owner(_owner),
            victim(-1),
            x(_pos[0]),
            y(_pos[1]),
            z(_pos[2]),
            team(_team),
            detonated(false)
        {}
    };

    std::vector<Mine>        activeMines;   // A vector that will store all of the mines that are in play
    std::vector<std::string> deathMessages; // A vector that will store all of the witty death messages

    double bzdb_SpawnSafetyTime, // The BZDB variable that will store the amount of seconds a player has before a mine is detonated
           playerSpawnTime[256]; // The time of a player's last spawn time used to calculate their safety from detonation
};

BZ_PLUGIN(UselessMine)

const char* UselessMine::Name (void)
{
    static std::string pluginBuild = "";

    if (!pluginBuild.size())
    {
        std::ostringstream pluginBuildStream;

        pluginBuildStream << PLUGIN_NAME << " " << MAJOR << "." << MINOR << "." << REV << " (" << BUILD << ")";
        pluginBuild = pluginBuildStream.str();
    }

    return pluginBuild.c_str();
}

void UselessMine::Init (const char* commandLine)
{
    // Register our events with Register()
    Register(bz_eFlagGrabbedEvent);
    Register(bz_ePlayerDieEvent);
    Register(bz_ePlayerPartEvent);
    Register(bz_ePlayerSpawnEvent);
    Register(bz_ePlayerUpdateEvent);

    // Register our custom slash commands
    bz_registerCustomSlashCommand("mine", this);

    // Initialize all of the witty death messages
    initializeMessages();

    // Set some custom BZDB variables
    bzdb_SpawnSafetyTime = bztk_registerCustomDoubleBZDB("_mineSafetyTime", 5.0);
}

void UselessMine::Cleanup (void)
{
    Flush(); // Clean up all the events

    // Clean up our custom slash commands
    bz_removeCustomSlashCommand("mine");
}

void UselessMine::Event (bz_EventData *eventData)
{
    switch (eventData->eventType)
    {
        case bz_eFlagGrabbedEvent: // This event is called each time a flag is grabbed by a player
        {
            bz_FlagGrabbedEventData_V1* flagGrabData = (bz_FlagGrabbedEventData_V1*)eventData;

            // Data
            // ---
            //    (int)           playerID  - The player that grabbed the flag
            //    (int)           flagID    - The flag ID that was grabbed
            //    (bz_ApiString)  flagType  - The flag abbreviation of the flag that was grabbed
            //    (float[3])      pos       - The position at which the flag was grabbed
            //    (double)        eventTime - This value is the local server time of the event.

            // If the user grabbed the Useless flag, let them know they can place a mine
            if (strcmp(flagGrabData->flagType, "US") == 0)
            {
                bz_sendTextMessage(BZ_SERVER, flagGrabData->playerID, "You grabbed a Useless flag! Type /mine at any time to set a useless mine!");
            }
        }
        break;

        case bz_ePlayerDieEvent: // This event is called each time a tank is killed.
        {
            bz_PlayerDieEventData_V1* dieData = (bz_PlayerDieEventData_V1*)eventData;

            // Data
            // ---
            //   (int)                   playerID       - ID of the player who was killed.
            //   (bz_eTeamType)          team           - The team the killed player was on.
            //   (int)                   killerID       - The owner of the shot that killed the player, or BZ_SERVER for server side kills
            //   (bz_eTeamType)          killerTeam     - The team the owner of the shot was on.
            //   (bz_ApiString)          flagKilledWith - The flag name the owner of the shot had when the shot was fired.
            //   (int)                   shotID         - The shot ID that killed the player, if the player was not killed by a shot, the id will be -1.
            //   (bz_PlayerUpdateState)  state          - The state record for the killed player at the time of the event
            //   (double)                eventTime      - Time of the event on the server.

            int playerID = dieData->playerID;

            // Loop through all the mines in play
            for (int i = 0; i < getMineCount(); i++)
            {
                // Create a local variable for easy access
                Mine &detonatedMine = activeMines.at(i);

                // Check if the mine has already been detonated
                if (detonatedMine.detonated)
                {
                    // Check if the victim killed is the player who just died
                    if (detonatedMine.victim == playerID)
                    {
                        // Check if the player who just died was killed by the server
                        if (dieData->killerID == 253)
                        {
                            // The random number used to fetch a random taunting death message
                            int randomNumber = rand() % deathMessages.size();

                            // Get the callsigns of the players
                            const char* owner  = bz_getPlayerCallsign(detonatedMine.owner);
                            const char* victim = bz_getPlayerCallsign(detonatedMine.victim);

                            // Attribute the kill to the mine owner
                            dieData->killerID = detonatedMine.owner;

                            // This mine has been detonated and we're done with the information that we need
                            removeMine(i);

                            bz_sendTextMessagef(BZ_SERVER, BZ_ALLUSERS, deathMessages.at(randomNumber).c_str(), victim, owner);
                            break;
                        }
                    }
                }
            }
        }
        break;

        case bz_ePlayerPartEvent: // This event is called each time a player leaves a game
        {
            bz_PlayerJoinPartEventData_V1* partData = (bz_PlayerJoinPartEventData_V1*)eventData;

            // Data
            // ---
            //    (int)                   playerID  - The player ID that is leaving
            //    (bz_BasePlayerRecord*)  record    - The player record for the leaving player
            //    (bz_ApiString)          reason    - The reason for leaving, such as a kick or a ban
            //    (double)                eventTime - Time of event.

            int playerID = partData->playerID;

            removeAllMines(playerID);
        }
        break;

        case bz_ePlayerSpawnEvent: // This event is called each time a playing tank is being spawned into the world
        {
            bz_PlayerSpawnEventData_V1* spawnData = (bz_PlayerSpawnEventData_V1*)eventData;

            // Data
            // ---
            //    (int)                   playerID  - ID of the player who was added to the world.
            //    (bz_eTeamType)          team      - The team the player is a member of.
            //    (bz_PlayerUpdateState)  state     - The state record for the spawning player
            //    (double)                eventTime - Time local server time for the event.

            int playerID = spawnData->playerID;

            // Save the time the player spawned last
            playerSpawnTime[playerID] = bz_getCurrentTime();
        }
        break;

        case bz_ePlayerUpdateEvent: // This event is called each time a player sends an update to the server
        {
            bz_PlayerUpdateEventData_V1* updateData = (bz_PlayerUpdateEventData_V1*)eventData;

            // Data
            // ---
            //   (int)       playerID  - ID of the player that sent the update
            //   (float[3])  pos       - The player's current position
            //   (float[3])  velocity  - The player's current velocity
            //   (float)     azimuth   - The direction the player is facing
            //   (float)     angvel    - The player's angular velocity
            //   (int)       phydrv    - The physics driver the player is on
            //   (double)    eventTime - The current server time

            int playerID = updateData->playerID;

            // Loop through all of the players
            for (int i = 0; i < getMineCount(); i++)
            {
                // Make an easy access mine
                Mine &currentMine = activeMines.at(i);

                // If the mine owner is not the player triggering the mine (so no self kills) and the player is a rogue or does is an enemy team relative to the mine owner
                if (currentMine.owner != playerID && (bz_getPlayerTeam(playerID) == eRogueTeam || bz_getPlayerTeam(playerID) != currentMine.team))
                {
                    // Make easy to access variables
                    float  playerPos[3] = {updateData->state.pos[0], updateData->state.pos[1], updateData->state.pos[2]};
                    double shockRange   = bz_getBZDBDouble("_shockOutRadius") * 0.75;

                    // Check if the player is in the detonation range
                    if ((playerPos[0] > currentMine.x - shockRange && playerPos[0] < currentMine.x + shockRange) &&
                        (playerPos[1] > currentMine.y - shockRange && playerPos[1] < currentMine.y + shockRange) &&
                        (playerPos[2] > currentMine.z - shockRange && playerPos[2] < currentMine.z + shockRange) &&
                        playerSpawnTime[playerID] + bzdb_SpawnSafetyTime <= bz_getCurrentTime() && !currentMine.detonated)
                    {
                        // Check that the mine owner exists and is not an observer
                        if (bztk_isValidPlayerID(currentMine.owner) && bz_getPlayerTeam(currentMine.owner) != eObservers)
                        {
                            // Get the current mine position
                            float minePos[3] = {currentMine.x, currentMine.y, currentMine.z};

                            // Save who detonated the mine and mark it as detonated
                            currentMine.victim    = playerID;
                            currentMine.detonated = true;

                            // BOOM!
                            bz_fireWorldWep("SW", 2.0, BZ_SERVER, minePos, 0, 0, 0, currentMine.team);
                        }
                        // Just in case the player doesn't exist or is an observer, then remove the mine because it shouldn't be there
                        else
                        {
                            removeMine(i);
                        }

                        break;
                    }
                }
            }
        }
        break;

        default: break;
    }
}

bool UselessMine::SlashCommand(int playerID, bz_ApiString command, bz_ApiString /*message*/, bz_APIStringList *params)
{
    if (command == "mine")
    {
        std::shared_ptr<bz_BasePlayerRecord> playerRecord(bz_getPlayerByIndex(playerID));

        // If the player is not an observer, they let them proceed to the next check
        if (playerRecord->team != eObservers)
        {
            // Check if the player has the Useless flag
            if (playerRecord->currentFlag == "USeless (+US)")
            {
                // Store their current position
                float currentPosition[3] = {playerRecord->lastKnownState.pos[0], playerRecord->lastKnownState.pos[1], playerRecord->lastKnownState.pos[2]};

                setMine(playerID, currentPosition, playerRecord->team);
            }
            else
            {
                bz_sendTextMessage(BZ_SERVER, playerID, "You can't place a mine without the Useless flag!");
            }
        }
        else
        {
            bz_sendTextMessage(BZ_SERVER, playerID, "Silly observer, you can't place a mine.");
        }

        return true;
    }
}

// A shortcut to get the amount of mines that are in play
int UselessMine::getMineCount()
{
    return activeMines.size();
}

// In order to keep things organized, this function is where you can specify all the witty death messages you want to be available
void UselessMine::initializeMessages()
{
    deathMessages.push_back("%s was killed by %s's mine.");
    deathMessages.push_back("%s was owned by %s's mine.");
    deathMessages.push_back("%s was obliterated by %s's mine.");
    deathMessages.push_back("%s's tank disintegrated from %s's mine.");
    deathMessages.push_back("%s was permanently blinded by the bright light from %s's mine.");
    deathMessages.push_back("%s was sent shooting into the stars by %s's mine.");
    deathMessages.push_back("%s was never heard from again thanks to %s's mine.");
    deathMessages.push_back("We salute %s for taking an atrocious hit from %s's mine.");
    deathMessages.push_back("%s's mine left %s's tank parts scattered all over.");
    deathMessages.push_back("%s thought %s's mine was a shiny brand new car.");
    deathMessages.push_back("%s was bombarded by many concussive attacks from %s's mine.");
    deathMessages.push_back("%s was ignited by %s's mine.");
    deathMessages.push_back("%s's mine bursted %s's tank to bite-size flaming pieces.");
    deathMessages.push_back("%s took a nosedive into %s's mine.");
    deathMessages.push_back("%s fell face first into %s's mine.");
    deathMessages.push_back("I knew %s would be clumsy enough to run into %s's mine.");
    deathMessages.push_back("%s killed %s with a mine. No surprise there.");
    deathMessages.push_back("DID YOU SEE THAT? %s did total carnage to %s's tank with that one little mine.");
    deathMessages.push_back("%s purposely ran into %s's mine.");
    deathMessages.push_back("I ascertain that %s has been ruptured by a mine created from the heavens with the name dubbed %s.");
}

void UselessMine::removeAllMines(int playerID)
{
    // Go through all of the mines
    for (int i = 0; i < getMineCount(); i++)
    {
        // Quick access mine
        Mine &currentMine = activeMines.at(i);

        // If the mine belongs to the player, remove it
        if (currentMine.owner == playerID)
        {
            removeMine(i);
        }
    }
}

// A shortcut to remove a mine from play
void UselessMine::removeMine(int mineIndex)
{
    activeMines.erase(activeMines.begin() + mineIndex);
}

// A shortcut to set a mine
void UselessMine::setMine(int owner, float pos[3], bz_eTeamType team)
{
    // Remove their flag because it's going to be a US flag
    bz_removePlayerFlag(owner);

    // Push the new mine
    Mine newMine(owner, pos, team);
    activeMines.push_back(newMine);
}<|endoftext|>