<commit_before>/*

Copyright (c) 2014, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "resolve_links.hpp"

#include "libtorrent/torrent_info.hpp"
#include <boost/shared_ptr.hpp>

namespace libtorrent
{

#ifndef TORRENT_DISABLE_MUTABLE_TORRENTS
resolve_links::resolve_links(boost::shared_ptr<torrent_info> ti)
	: m_torrent_file(ti)
{
	TORRENT_ASSERT(ti);

	int piece_size = ti->piece_length();

	file_storage const& fs = ti->files();
	m_file_sizes.reserve(fs.num_files());
	for (int i = 0; i < fs.num_files(); ++i)
	{
		// don't match pad-files, and don't match files that aren't aligned to
		// ieces. Files are matched by comparing piece hashes, so pieces must
		// be aligned and the same size
		if (fs.pad_file_at(i)) continue;
		if ((fs.file_offset(i) % piece_size) != 0) continue;

		m_file_sizes.insert(std::make_pair(fs.file_size(i), i));
	}

	m_links.resize(m_torrent_file->num_files());
}

void resolve_links::match(boost::shared_ptr<const torrent_info> const& ti
	, std::string const& save_path)
{
	if (!ti) return;

	// only torrents with the same
	if (ti->piece_length() != m_torrent_file->piece_length()) return;

	int piece_size = ti->piece_length();

	file_storage const& fs = ti->files();
	m_file_sizes.reserve(fs.num_files());
	for (int i = 0; i < fs.num_files(); ++i)
	{
		// for every file in the other torrent, see if we have one that match
		// it in m_torrent_file

		// if the file base is not aligned to pieces, we're not going to match
		// it anyway (we only compare piece hashes)
		if ((fs.file_offset(i) % piece_size) != 0) continue;
		if (fs.pad_file_at(i)) continue;

		boost::int64_t file_size = fs.file_size(i);

		typedef boost::unordered_multimap<boost::int64_t, int>::iterator iterator;
		iterator iter = m_file_sizes.find(file_size);

		// we don't have a file whose size matches, look at the next one
		if (iter == m_file_sizes.end()) continue;

		TORRENT_ASSERT(iter->second < m_torrent_file->files().num_files());
		TORRENT_ASSERT(iter->second >= 0);

		// if we already have found a duplicate for this file, no need
		// to keep looking
		if (m_links[iter->second].ti) continue;

		// files are aligned and have the same size, now start comparing
		// piece hashes, to see if the files are identical

		// the pieces of the incoming file
		int their_piece = fs.map_file(i, 0, 0).piece;
		// the pieces of "this" file (from m_torrent_file)
		int our_piece = m_torrent_file->files().map_file(
			iter->second, 0, 0).piece;

		int num_pieces = (file_size + piece_size - 1) / piece_size;

		bool match = true;
		for (int p = 0; p < num_pieces; ++p, ++their_piece, ++our_piece)
		{
			if (m_torrent_file->hash_for_piece(our_piece)
				!= ti->hash_for_piece(their_piece))
			{
				match = false;
				break;
			}
		}
		if (!match) continue;

		m_links[iter->second].ti = ti;
		m_links[iter->second].save_path = save_path;
		m_links[iter->second].file_idx = i;

		// since we have a duplicate for this file, we may as well remove
		// it from the file-size map, so we won't find it again.
		m_file_sizes.erase(iter);
	}

}
#endif // TORRENT_DISABLE_MUTABLE_TORRENTS

} // namespace libtorrent

<commit_msg>fix inlude in resolve_links.cpp<commit_after>/*

Copyright (c) 2014, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/resolve_links.hpp"

#include "libtorrent/torrent_info.hpp"
#include <boost/shared_ptr.hpp>

namespace libtorrent
{

#ifndef TORRENT_DISABLE_MUTABLE_TORRENTS
resolve_links::resolve_links(boost::shared_ptr<torrent_info> ti)
	: m_torrent_file(ti)
{
	TORRENT_ASSERT(ti);

	int piece_size = ti->piece_length();

	file_storage const& fs = ti->files();
	m_file_sizes.reserve(fs.num_files());
	for (int i = 0; i < fs.num_files(); ++i)
	{
		// don't match pad-files, and don't match files that aren't aligned to
		// ieces. Files are matched by comparing piece hashes, so pieces must
		// be aligned and the same size
		if (fs.pad_file_at(i)) continue;
		if ((fs.file_offset(i) % piece_size) != 0) continue;

		m_file_sizes.insert(std::make_pair(fs.file_size(i), i));
	}

	m_links.resize(m_torrent_file->num_files());
}

void resolve_links::match(boost::shared_ptr<const torrent_info> const& ti
	, std::string const& save_path)
{
	if (!ti) return;

	// only torrents with the same
	if (ti->piece_length() != m_torrent_file->piece_length()) return;

	int piece_size = ti->piece_length();

	file_storage const& fs = ti->files();
	m_file_sizes.reserve(fs.num_files());
	for (int i = 0; i < fs.num_files(); ++i)
	{
		// for every file in the other torrent, see if we have one that match
		// it in m_torrent_file

		// if the file base is not aligned to pieces, we're not going to match
		// it anyway (we only compare piece hashes)
		if ((fs.file_offset(i) % piece_size) != 0) continue;
		if (fs.pad_file_at(i)) continue;

		boost::int64_t file_size = fs.file_size(i);

		typedef boost::unordered_multimap<boost::int64_t, int>::iterator iterator;
		iterator iter = m_file_sizes.find(file_size);

		// we don't have a file whose size matches, look at the next one
		if (iter == m_file_sizes.end()) continue;

		TORRENT_ASSERT(iter->second < m_torrent_file->files().num_files());
		TORRENT_ASSERT(iter->second >= 0);

		// if we already have found a duplicate for this file, no need
		// to keep looking
		if (m_links[iter->second].ti) continue;

		// files are aligned and have the same size, now start comparing
		// piece hashes, to see if the files are identical

		// the pieces of the incoming file
		int their_piece = fs.map_file(i, 0, 0).piece;
		// the pieces of "this" file (from m_torrent_file)
		int our_piece = m_torrent_file->files().map_file(
			iter->second, 0, 0).piece;

		int num_pieces = (file_size + piece_size - 1) / piece_size;

		bool match = true;
		for (int p = 0; p < num_pieces; ++p, ++their_piece, ++our_piece)
		{
			if (m_torrent_file->hash_for_piece(our_piece)
				!= ti->hash_for_piece(their_piece))
			{
				match = false;
				break;
			}
		}
		if (!match) continue;

		m_links[iter->second].ti = ti;
		m_links[iter->second].save_path = save_path;
		m_links[iter->second].file_idx = i;

		// since we have a duplicate for this file, we may as well remove
		// it from the file-size map, so we won't find it again.
		m_file_sizes.erase(iter);
	}

}
#endif // TORRENT_DISABLE_MUTABLE_TORRENTS

} // namespace libtorrent

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: connctr.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2006-04-20 15:15:01 $
 *
 *  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 "connctr.hxx"
#include "objwin.hxx"
#include "depwin.hxx"
//#include "depapp.hxx"
#include "math.h"

BOOL Connector::msbHideMode = FALSE;

Connector::Connector( DepWin* pParent, WinBits nWinStyle ) :
mpStartWin( 0L ),
mpEndWin( 0L ),
mnStartId( 0 ),
mnEndId( 0 ),
len( 70 ),
bVisible( FALSE )
{
    mpParent = pParent;
    if ( mpParent )
        mpParent->AddConnector( this );
}

Connector::~Connector()
{
    if ( mpStartWin )
        mpStartWin->RemoveConnector( this );
    if ( mpEndWin )
        mpEndWin->RemoveConnector( this );
    if ( mpParent )
        mpParent->RemoveConnector( this );
    mpParent->Invalidate( Rectangle( mStart, mEnd ));
    mpParent->Invalidate( Rectangle( mEnd - Point( 3, 3), mEnd + Point( 3, 3)));
}

void Connector::Initialize( ObjectWin* pStartWin, ObjectWin* pEndWin, BOOL bVis )
{
    mpStartWin = pStartWin;
    mpEndWin = pEndWin;
    mpStartWin->AddConnector( this );
    mpEndWin->AddConnector( this );
    mCenter = GetMiddle();
    mStart = pStartWin->GetFixPoint( mCenter );
    mEnd = pEndWin->GetFixPoint( mCenter );
    mnStartId = pStartWin->GetId();
    mnEndId = pEndWin->GetId();
    bVisible = bVis;

//  if ( mpParent->IsPaintEnabled())
    if ( IsVisible() )
    {
        mpParent->DrawLine( mEnd, mStart );
        mpParent->DrawEllipse( Rectangle( mEnd - Point( 2, 2), mEnd + Point( 2, 2)));
    }
    UpdateVisibility(); //null_Project
}

void Connector::UpdateVisibility()
{
    bVisible = mpStartWin->IsVisible() && mpEndWin->IsVisible();
}

Point Connector::GetMiddle()
{
    Point aStartPoint = mpStartWin->GetPosPixel();
    Size aStartSize = mpStartWin->GetSizePixel();
    int nMoveHorz, nMoveVert;
    aStartPoint.Move( aStartSize.Width() / 2, aStartSize.Height() / 2 );

    Point aEndPoint = mpEndWin->GetPosPixel();
    Size aEndSize = mpEndWin->GetSizePixel();

    aEndPoint.Move( aEndSize.Width() / 2, aEndSize.Height() / 2 );

    Point aRetPoint = aEndPoint;

    nMoveHorz = aStartPoint.X() - aEndPoint.X();
    if ( nMoveHorz )
        nMoveHorz /= 2;
    nMoveVert = aStartPoint.Y() - aEndPoint.Y();
    if ( nMoveVert )
        nMoveVert /= 2;
    aRetPoint.Move( nMoveHorz, nMoveVert );
    return aRetPoint;

}

void Connector::Paint( const Rectangle& rRect )
{
    //MyApp *pApp = (MyApp*)GetpApp();
    //SolDep *pSoldep = pApp->GetSolDep();
    if (msbHideMode)
    {
    /*
        if ((mpStartWin->GetMarkMode() == 0) || (mpEndWin->GetMarkMode() == 0))
        {
            //bVisible = FALSE;
            UpdateVisibility();
            fprintf( ((MyApp*)GetpApp())->pDebugFile, "FALSE connctr: Start: %s %i - End: %s %i\n",
                mpStartWin->GetBodyText().GetBuffer(),mpStartWin->GetMarkMode(),
                mpEndWin->GetBodyText().GetBuffer(),mpEndWin->GetMarkMode());
        } else
        {
            bVisible = TRUE;
            fprintf( ((MyApp*)GetpApp())->pDebugFile, "TRUE connctr: Start: %s %i - End: %s %i\n",
                mpStartWin->GetBodyText().GetBuffer(),mpStartWin->GetMarkMode(),
                mpEndWin->GetBodyText().GetBuffer(),mpEndWin->GetMarkMode());
        }
     */
    if (!(mpStartWin->IsNullObject())) //null_project
    {
        if (mpStartWin->GetMarkMode() == 0)
        {
            mpStartWin->SetViewMask(0); //objwin invisible
        } else
        {
            mpStartWin->SetViewMask(1); //objwin visible
        }
    }
    if (!(mpEndWin->IsNullObject()))
    {
        if (mpEndWin->GetMarkMode() == 0)
        {
            mpEndWin->SetViewMask(0); //objwin invisible
        } else
        {
            mpEndWin->SetViewMask(1); //objwin visible
        }
    }
    UpdateVisibility();
    } else //IsHideMode
    {
        //bVisible = TRUE;
        if (!(mpStartWin->IsNullObject())) //null_project
        {
             mpStartWin->SetViewMask(1);
        }
        if (!(mpEndWin->IsNullObject())) //null_project
        {
             mpEndWin->SetViewMask(1);
        }
        UpdateVisibility();
    }
    if ( (mpStartWin->GetBodyText() != ByteString("null")) &&              //null_project
         (mpEndWin->GetBodyText() != ByteString("null")) && IsVisible())  //null_project
    {
        mpParent->DrawLine( mEnd, mStart );
        mpParent->DrawEllipse( Rectangle( mEnd - Point( 2, 2), mEnd + Point( 2, 2)));
    }
}

void Connector::UpdatePosition( ObjectWin* pWin, BOOL bPaint )
{
//  more than one call ?
//
    Point OldStart, OldEnd;
    static ULONG nCallCount = 0;

    //MyApp *pApp = (MyApp*)GetpApp();
    //SolDep *pSoldep = pApp->GetSolDep();
    if (msbHideMode)
        bVisible = 1;

    if ( nCallCount )           // only one call
        nCallCount++;
    else
    {
        nCallCount++;
        while ( nCallCount )
        {
            if ( bPaint )
            {
                OldStart = mStart;
                OldEnd = mEnd;
            }
            mCenter = GetMiddle();
            mStart=mpStartWin->GetFixPoint( mCenter, bPaint );
            mEnd=mpEndWin->GetFixPoint( mCenter, bPaint );
            if ( bPaint )
            {
                mpParent->Invalidate( Rectangle( OldStart, OldEnd ));
                mpParent->Invalidate( Rectangle( OldEnd - Point( 2, 2), OldEnd + Point( 2, 2)));
//Don't paint "null_project" connectors
                if ( (mpStartWin->GetBodyText() != ByteString("null")) &&               //null_project
                     (mpEndWin->GetBodyText() != ByteString("null")))                   //null_project
                {
                    Paint ( Rectangle( mEnd - Point( 3, 3), mEnd + Point( 3, 3)));
                    Paint ( Rectangle( mEnd, mStart ));
                }
            }
            nCallCount--;
        }
    }
}

USHORT Connector::Save( SvFileStream& rOutFile )
{
    rOutFile << mpStartWin->GetId();
    rOutFile << mpEndWin->GetId();

    return 0;
}

USHORT Connector::Load( SvFileStream& rInFile )
{
    rInFile >> mnStartId;
    rInFile >> mnEndId;

    return 0;
}

ObjectWin* Connector::GetOtherWin( ObjectWin* pWin )
{
// get correspondent object ptr
    if ( mpStartWin == pWin )
        return mpEndWin;
    else
        if ( mpEndWin == pWin )
            return mpStartWin;

    return NULL;
}

ULONG Connector::GetOtherId( ULONG nId )
{
// get correspondent object id
    if ( mnStartId == nId )
        return mnEndId;
    else
        if ( mnEndId == nId )
            return mnStartId;

    return NULL;
}

ULONG Connector::GetLen()
{
    double dx, dy;

    dx = mStart.X() - mEnd.X();
    dy = mStart.Y() - mEnd.Y();

    return sqrt( dx * dx + dy * dy );
}

BOOL Connector::IsStart( ObjectWin* pWin )
{
    return pWin == mpStartWin;
}
<commit_msg>INTEGRATION: CWS soldep2 (1.2.2); FILE MERGED 2006/11/21 16:27:53 obo 1.2.2.1: #143484# dialog for workspace has to support minors<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: connctr.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: ihi $ $Date: 2006-12-21 12:22:21 $
 *
 *  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
 *
 ************************************************************************/
#ifdef _MSC_VER
#pragma warning(disable:4100)
#endif
#include "connctr.hxx"
#include "objwin.hxx"
#include "depwin.hxx"
#include "math.h"

BOOL Connector::msbHideMode = FALSE;

Connector::Connector( DepWin* pParent, WinBits nWinStyle ) :
mpStartWin( 0L ),
mpEndWin( 0L ),
mnStartId( 0 ),
mnEndId( 0 ),
len( 70 ),
bVisible( FALSE )
{
    mpParent = pParent;
    if ( mpParent )
        mpParent->AddConnector( this );
}

Connector::~Connector()
{
    if ( mpStartWin )
        mpStartWin->RemoveConnector( this );
    if ( mpEndWin )
        mpEndWin->RemoveConnector( this );
    if ( mpParent )
        mpParent->RemoveConnector( this );
    mpParent->Invalidate( Rectangle( mStart, mEnd ));
    mpParent->Invalidate( Rectangle( mEnd - Point( 3, 3), mEnd + Point( 3, 3)));
}

void Connector::Initialize( ObjectWin* pStartWin, ObjectWin* pEndWin, BOOL bVis )
{
    mpStartWin = pStartWin;
    mpEndWin = pEndWin;
    mpStartWin->AddConnector( this );
    mpEndWin->AddConnector( this );
    mCenter = GetMiddle();
    mStart = pStartWin->GetFixPoint( mCenter );
    mEnd = pEndWin->GetFixPoint( mCenter );
    mnStartId = pStartWin->GetId();
    mnEndId = pEndWin->GetId();
    bVisible = bVis;

//  if ( mpParent->IsPaintEnabled())
    if ( IsVisible() )
    {
        mpParent->DrawLine( mEnd, mStart );
        mpParent->DrawEllipse( Rectangle( mEnd - Point( 2, 2), mEnd + Point( 2, 2)));
    }
    UpdateVisibility(); //null_Project
}

void Connector::UpdateVisibility()
{
    bVisible = mpStartWin->IsVisible() && mpEndWin->IsVisible();
}

Point Connector::GetMiddle()
{
    Point aStartPoint = mpStartWin->GetPosPixel();
    Size aStartSize = mpStartWin->GetSizePixel();
    int nMoveHorz, nMoveVert;
    aStartPoint.Move( aStartSize.Width() / 2, aStartSize.Height() / 2 );

    Point aEndPoint = mpEndWin->GetPosPixel();
    Size aEndSize = mpEndWin->GetSizePixel();

    aEndPoint.Move( aEndSize.Width() / 2, aEndSize.Height() / 2 );

    Point aRetPoint = aEndPoint;

    nMoveHorz = aStartPoint.X() - aEndPoint.X();
    if ( nMoveHorz )
        nMoveHorz /= 2;
    nMoveVert = aStartPoint.Y() - aEndPoint.Y();
    if ( nMoveVert )
        nMoveVert /= 2;
    aRetPoint.Move( nMoveHorz, nMoveVert );
    return aRetPoint;

}

void Connector::Paint( const Rectangle& rRect )
{
    //MyApp *pApp = (MyApp*)GetpApp();
    //SolDep *pSoldep = pApp->GetSolDep();
    if (msbHideMode)
    {
    /*
        if ((mpStartWin->GetMarkMode() == 0) || (mpEndWin->GetMarkMode() == 0))
        {
            //bVisible = FALSE;
            UpdateVisibility();
            fprintf( ((MyApp*)GetpApp())->pDebugFile, "FALSE connctr: Start: %s %i - End: %s %i\n",
                mpStartWin->GetBodyText().GetBuffer(),mpStartWin->GetMarkMode(),
                mpEndWin->GetBodyText().GetBuffer(),mpEndWin->GetMarkMode());
        } else
        {
            bVisible = TRUE;
            fprintf( ((MyApp*)GetpApp())->pDebugFile, "TRUE connctr: Start: %s %i - End: %s %i\n",
                mpStartWin->GetBodyText().GetBuffer(),mpStartWin->GetMarkMode(),
                mpEndWin->GetBodyText().GetBuffer(),mpEndWin->GetMarkMode());
        }
     */
    if (!(mpStartWin->IsNullObject())) //null_project
    {
        if (mpStartWin->GetMarkMode() == 0)
        {
            mpStartWin->SetViewMask(0); //objwin invisible
        } else
        {
            mpStartWin->SetViewMask(1); //objwin visible
        }
    }
    if (!(mpEndWin->IsNullObject()))
    {
        if (mpEndWin->GetMarkMode() == 0)
        {
            mpEndWin->SetViewMask(0); //objwin invisible
        } else
        {
            mpEndWin->SetViewMask(1); //objwin visible
        }
    }
    UpdateVisibility();
    } else //IsHideMode
    {
        //bVisible = TRUE;
        if (!(mpStartWin->IsNullObject())) //null_project
        {
             mpStartWin->SetViewMask(1);
        }
        if (!(mpEndWin->IsNullObject())) //null_project
        {
             mpEndWin->SetViewMask(1);
        }
        UpdateVisibility();
    }
    if ( (mpStartWin->GetBodyText() != ByteString("null")) &&              //null_project
         (mpEndWin->GetBodyText() != ByteString("null")) && IsVisible())  //null_project
    {
        mpParent->DrawLine( mEnd, mStart );
        mpParent->DrawEllipse( Rectangle( mEnd - Point( 2, 2), mEnd + Point( 2, 2)));
    }
}

void Connector::UpdatePosition( ObjectWin* pWin, BOOL bPaint )
{
//  more than one call ?
//
    Point OldStart, OldEnd;
    static ULONG nCallCount = 0;

    //MyApp *pApp = (MyApp*)GetpApp();
    //SolDep *pSoldep = pApp->GetSolDep();
    if (msbHideMode)
        bVisible = 1;

    if ( nCallCount )           // only one call
        nCallCount++;
    else
    {
        nCallCount++;
        while ( nCallCount )
        {
            if ( bPaint )
            {
                OldStart = mStart;
                OldEnd = mEnd;
            }
            mCenter = GetMiddle();
            mStart=mpStartWin->GetFixPoint( mCenter, bPaint );
            mEnd=mpEndWin->GetFixPoint( mCenter, bPaint );
            if ( bPaint )
            {
                mpParent->Invalidate( Rectangle( OldStart, OldEnd ));
                mpParent->Invalidate( Rectangle( OldEnd - Point( 2, 2), OldEnd + Point( 2, 2)));
//Don't paint "null_project" connectors
                if ( (mpStartWin->GetBodyText() != ByteString("null")) &&               //null_project
                     (mpEndWin->GetBodyText() != ByteString("null")))                   //null_project
                {
                    Paint ( Rectangle( mEnd - Point( 3, 3), mEnd + Point( 3, 3)));
                    Paint ( Rectangle( mEnd, mStart ));
                }
            }
            nCallCount--;
        }
    }
}

USHORT Connector::Save( SvFileStream& rOutFile )
{
    rOutFile << mpStartWin->GetId();
    rOutFile << mpEndWin->GetId();

    return 0;
}

USHORT Connector::Load( SvFileStream& rInFile )
{
    rInFile >> mnStartId;
    rInFile >> mnEndId;

    return 0;
}

ObjectWin* Connector::GetOtherWin( ObjectWin* pWin )
{
// get correspondent object ptr
    if ( mpStartWin == pWin )
        return mpEndWin;
    else
        if ( mpEndWin == pWin )
            return mpStartWin;

    return NULL;
}

ULONG Connector::GetOtherId( ULONG nId )
{
// get correspondent object id
    if ( mnStartId == nId )
        return mnEndId;
    else
        if ( mnEndId == nId )
            return mnStartId;

    return NULL;
}

ULONG Connector::GetLen()
{
    double dx, dy;

    dx = mStart.X() - mEnd.X();
    dy = mStart.Y() - mEnd.Y();

    return (ULONG) sqrt( dx * dx + dy * dy );
}

BOOL Connector::IsStart( ObjectWin* pWin )
{
    return pWin == mpStartWin;
}<|endoftext|>


<commit_before>#include <common.h>
#include <Tokenizer.h>
#include <ErrorProcessor.h>
#include <Tools.h>

namespace Lspl {
namespace Parser {

///////////////////////////////////////////////////////////////////////////////

void CToken::Print( ostream& out ) const
{
	switch( Type ) {
		case TT_Regexp:
			out << '"' << Text << '"';
			break;
		case TT_Number:
			out << Number;
			break;
		case TT_Identifier:
			out << Text;
			break;
		case TT_Dot:
			out << ".";
			break;
		case TT_Comma:
			out << ",";
			break;
		case TT_DollarSign:
			out << "$";
			break;
		case TT_NumberSign:
			out << "#";
			break;
		case TT_VerticalBar:
			out << "|";
			break;
		case TT_OpeningBrace:
			out << "{";
			break;
		case TT_ClosingBrace:
			out << "}";
			break;
		case TT_OpeningBracket:
			out << "[";
			break;
		case TT_ClosingBracket:
			out << "]";
			break;
		case TT_OpeningParenthesis:
			out << "(";
			break;
		case TT_ClosingParenthesis:
			out << ")";
			break;
		case TT_EqualSign:
			out << "=";
			break;
		case TT_DoubleEqualSign:
			out << "==";
			break;
		case TT_Tilde:
			out << "~";
			break;
		case TT_TildeGreaterThanSign:
			out << "~>";
			break;
		case TT_LessThanSign:
			out << "<";
			break;
		case TT_DoubleLessThanSign:
			out << "<<";
			break;
		case TT_GreaterThanSign:
			out << ">";
			break;
		case TT_DoubleGreaterThanSign:
			out << ">>";
			break;
		case TT_ExclamationPointEqualSign:
			out << "!=";
			break;
	}
}

///////////////////////////////////////////////////////////////////////////////

inline bool IsIdentifierCharacter( char c )
{
	return !IsByteAsciiSymbol( c )
		|| ( isalnum( c, locale::classic() ) || c == '-' || c == '_' );
}

///////////////////////////////////////////////////////////////////////////////

CTokenizer::CTokenizer( CErrorProcessor& _errorProcessor ) :
	errorProcessor( _errorProcessor )
{
	Reset();
}

CTokenizer::~CTokenizer()
{
	Reset();
}

void CTokenizer::Reset()
{
	clear();
	reset();
}

void CTokenizer::TokenizeLine( CSharedFileLine _line )
{
	initialize( _line );
	for( char c : line->Line ) {
		step( c );
		offset++;
	}
	finalize();
}

void CTokenizer::initialize( CSharedFileLine _line )
{
	check_logic( _line );
	state = &CTokenizer::initialState;
	line = _line;
	text.clear();
	offset = 0;
}

void CTokenizer::step( char c )
{
	( this->*state )( c );
}

void CTokenizer::finalize()
{
	step( ' ' );
	if( state == &CTokenizer::regexState ) {
		addToken( TT_Regexp, true /* decreaseAnOffsetByOne */ );
		errorProcessor.AddError( CError(
			CLineSegment( offset - text.length(), numeric_limits<size_t>::max() ),
			line, "newline in regular expression" ) );
	}

	reset();
}

void CTokenizer::reset()
{
	state = nullptr;
	line = CSharedFileLine();
	text.clear();
	offset = 0;
}

void CTokenizer::addToken( TTokenType type, bool decreaseAnOffsetByOne )
{
	CLineSegment lineSegment( offset - text.length() );
	if( decreaseAnOffsetByOne ) {
		lineSegment.Offset--;
	}
	push_back( CTokenPtr( new CToken( type, line, lineSegment ) ) );
	CToken& token = *back();
	switch( type ) {
		case TT_Regexp:
			token.Text = text;
			token.Length = text.length() + 2;
			break;
		case TT_Number:
			token.Number = stoul( text );
			token.Length = text.length();
			break;
		case TT_Identifier:
			token.Text = text;
			token.Length = text.length();
			break;
		case TT_DoubleEqualSign:
		case TT_TildeGreaterThanSign:
		case TT_DoubleLessThanSign:
		case TT_DoubleGreaterThanSign:
		case TT_ExclamationPointEqualSign:
			token.Length = 2;
			break;
		default:
			break;
	}
	text.clear();
}

void CTokenizer::checkIdentifier()
{
	// check text
}

void CTokenizer::initialState( char c )
{
	switch( c ) {
		case ' ':
			break; // skip blank character
		case ';':
			state = &CTokenizer::commentState;
			break;
		case '.':
			addToken( TT_Dot );
			break;
		case ',':
			addToken( TT_Comma );
			break;
		case '$':
			addToken( TT_DollarSign );
			break;
		case '#':
			addToken( TT_NumberSign );
			break;
		case '|':
			addToken( TT_VerticalBar );
			break;
		case '{':
			addToken( TT_OpeningBrace );
			break;
		case '}':
			addToken( TT_ClosingBrace );
			break;
		case '[':
			addToken( TT_OpeningBracket );
			break;
		case ']':
			addToken( TT_ClosingBracket );
			break;
		case '(':
			addToken( TT_OpeningParenthesis );
			break;
		case ')':
			addToken( TT_ClosingParenthesis );
			break;
		case '=':
			state = &CTokenizer::equalSignState;
			break;
		case '~':
			state = &CTokenizer::tildeState;
			break;
		case '<':
			state = &CTokenizer::lessThanSignState;
			break;
		case '>':
			state = &CTokenizer::greaterThanSignState;
			break;
		case '!':
			state = &CTokenizer::exclamationSignState;
			break;
		case '"':
			state = &CTokenizer::regexState;
			text.clear();
			break;
		default:
			if( isdigit( c, locale::classic() ) ) {
				state = &CTokenizer::numberState;
				text.assign( 1, c );
			} else if( IsIdentifierCharacter( c ) ) {
				state = &CTokenizer::indentifierState;
				text.assign( 1, c );
			} else {
				errorProcessor.AddError( CError( CLineSegment( offset ),
					line, "unknown character " + c, ES_CriticalError ) );
			}
			break;
	}
}

void CTokenizer::commentState( char /* c */ )
{
	// just skip any characters after ';'
}

void CTokenizer::regexState( char c )
{
	if( c == '"' ) {
		addToken( TT_Regexp, true /* decreaseAnOffsetByOne */ );
		state = &CTokenizer::initialState;
	} else {
		if( c == '\\' ) {
			state = &CTokenizer::regexStateAfterBackslash;
		}
		text.append( 1, c );
	}
}

void CTokenizer::regexStateAfterBackslash( char c )
{
	state = &CTokenizer::regexState;
	text.append( 1, c );
}

void CTokenizer::numberState( char c )
{
	if( isdigit( c, locale::classic() ) ) {
		text.append( 1, c );
	} else {
		addToken( TT_Number );
		state = &CTokenizer::initialState;
		step( c );
	}
}

void CTokenizer::indentifierState( char c )
{
	if( IsIdentifierCharacter( c ) ) {
		text.append( 1, c );
	} else {
		checkIdentifier();
		addToken( TT_Identifier );
		state = &CTokenizer::initialState;
		step( c );
	}
}

void CTokenizer::tildeState( char c )
{
	state = &CTokenizer::initialState;
	if( c == '>' ) {
		addToken( TT_TildeGreaterThanSign, true /* decreaseAnOffsetByOne */ );
	} else {
		addToken( TT_Tilde, true /* decreaseAnOffsetByOne */ );
		step( c );
	}
}

void CTokenizer::equalSignState( char c )
{
	state = &CTokenizer::initialState;
	if( c == '=' ) {
		addToken( TT_DoubleEqualSign, true /* decreaseAnOffsetByOne */ );
	} else {
		addToken( TT_EqualSign, true /* decreaseAnOffsetByOne */ );
		step( c );
	}
}

void CTokenizer::lessThanSignState( char c )
{
	state = &CTokenizer::initialState;
	if( c == '<' ) {
		addToken( TT_DoubleLessThanSign, true /* decreaseAnOffsetByOne */ );
	} else {
		addToken( TT_LessThanSign, true /* decreaseAnOffsetByOne */ );
		step( c );
	}
}

void CTokenizer::greaterThanSignState( char c )
{
	state = &CTokenizer::initialState;
	if( c == '>' ) {
		addToken( TT_DoubleGreaterThanSign, true/* decreaseAnOffsetByOne */ );
	} else {
		addToken( TT_GreaterThanSign, true /* decreaseAnOffsetByOne */ );
		step( c );
	}
}

void CTokenizer::exclamationSignState( char c )
{
	if( c != '=' ) {
		errorProcessor.AddError( CError( CLineSegment( offset - 1, 2 ),
			line, "incorrect operation, you may possibly mean !=" ) );
	}

	addToken( TT_ExclamationPointEqualSign, true/*decreaseAnOffsetByOne*/ );
	state = &CTokenizer::initialState;
}

///////////////////////////////////////////////////////////////////////////////

} // end of Parser namespace
} // end of Lspl namespace
<commit_msg>small bug fixed<commit_after>#include <common.h>
#include <Tokenizer.h>
#include <ErrorProcessor.h>
#include <Tools.h>

namespace Lspl {
namespace Parser {

///////////////////////////////////////////////////////////////////////////////

void CToken::Print( ostream& out ) const
{
	switch( Type ) {
		case TT_Regexp:
			out << '"' << Text << '"';
			break;
		case TT_Number:
			out << Number;
			break;
		case TT_Identifier:
			out << Text;
			break;
		case TT_Dot:
			out << ".";
			break;
		case TT_Comma:
			out << ",";
			break;
		case TT_DollarSign:
			out << "$";
			break;
		case TT_NumberSign:
			out << "#";
			break;
		case TT_VerticalBar:
			out << "|";
			break;
		case TT_OpeningBrace:
			out << "{";
			break;
		case TT_ClosingBrace:
			out << "}";
			break;
		case TT_OpeningBracket:
			out << "[";
			break;
		case TT_ClosingBracket:
			out << "]";
			break;
		case TT_OpeningParenthesis:
			out << "(";
			break;
		case TT_ClosingParenthesis:
			out << ")";
			break;
		case TT_EqualSign:
			out << "=";
			break;
		case TT_DoubleEqualSign:
			out << "==";
			break;
		case TT_Tilde:
			out << "~";
			break;
		case TT_TildeGreaterThanSign:
			out << "~>";
			break;
		case TT_LessThanSign:
			out << "<";
			break;
		case TT_DoubleLessThanSign:
			out << "<<";
			break;
		case TT_GreaterThanSign:
			out << ">";
			break;
		case TT_DoubleGreaterThanSign:
			out << ">>";
			break;
		case TT_ExclamationPointEqualSign:
			out << "!=";
			break;
	}
}

///////////////////////////////////////////////////////////////////////////////

inline bool IsIdentifierCharacter( char c )
{
	return !IsByteAsciiSymbol( c )
		|| ( isalnum( c, locale::classic() ) || c == '-' || c == '_' );
}

///////////////////////////////////////////////////////////////////////////////

CTokenizer::CTokenizer( CErrorProcessor& _errorProcessor ) :
	errorProcessor( _errorProcessor )
{
	Reset();
}

CTokenizer::~CTokenizer()
{
	Reset();
}

void CTokenizer::Reset()
{
	clear();
	reset();
}

void CTokenizer::TokenizeLine( CSharedFileLine _line )
{
	initialize( _line );
	for( char c : line->Line ) {
		step( c );
		offset++;
	}
	finalize();
}

void CTokenizer::initialize( CSharedFileLine _line )
{
	check_logic( _line );
	state = &CTokenizer::initialState;
	line = _line;
	text.clear();
	offset = 0;
}

void CTokenizer::step( char c )
{
	( this->*state )( c );
}

void CTokenizer::finalize()
{
	step( ' ' );
	if( state == &CTokenizer::regexState ) {
		addToken( TT_Regexp, true /* decreaseAnOffsetByOne */ );
		errorProcessor.AddError( CError(
			CLineSegment( offset - text.length(), numeric_limits<size_t>::max() ),
			line, "newline in regular expression" ) );
	}

	reset();
}

void CTokenizer::reset()
{
	state = nullptr;
	line = CSharedFileLine();
	text.clear();
	offset = 0;
}

void CTokenizer::addToken( TTokenType type, bool decreaseAnOffsetByOne )
{
	CLineSegment lineSegment( offset - text.length() );
	if( decreaseAnOffsetByOne ) {
		lineSegment.Offset--;
	}
	push_back( CTokenPtr( new CToken( type, line, lineSegment ) ) );
	CToken& token = *back();
	switch( type ) {
		case TT_Regexp:
			token.Text = text;
			token.Length = text.length() + 2;
			break;
		case TT_Number:
			token.Number = stoul( text );
			token.Length = text.length();
			break;
		case TT_Identifier:
			token.Text = text;
			token.Length = text.length();
			break;
		case TT_DoubleEqualSign:
		case TT_TildeGreaterThanSign:
		case TT_DoubleLessThanSign:
		case TT_DoubleGreaterThanSign:
		case TT_ExclamationPointEqualSign:
			token.Length = 2;
			break;
		default:
			break;
	}
	text.clear();
}

void CTokenizer::checkIdentifier()
{
	// check text
}

void CTokenizer::initialState( char c )
{
	switch( c ) {
		case ' ':
			break; // skip blank character
		case ';':
			state = &CTokenizer::commentState;
			break;
		case '.':
			addToken( TT_Dot );
			break;
		case ',':
			addToken( TT_Comma );
			break;
		case '$':
			addToken( TT_DollarSign );
			break;
		case '#':
			addToken( TT_NumberSign );
			break;
		case '|':
			addToken( TT_VerticalBar );
			break;
		case '{':
			addToken( TT_OpeningBrace );
			break;
		case '}':
			addToken( TT_ClosingBrace );
			break;
		case '[':
			addToken( TT_OpeningBracket );
			break;
		case ']':
			addToken( TT_ClosingBracket );
			break;
		case '(':
			addToken( TT_OpeningParenthesis );
			break;
		case ')':
			addToken( TT_ClosingParenthesis );
			break;
		case '=':
			state = &CTokenizer::equalSignState;
			break;
		case '~':
			state = &CTokenizer::tildeState;
			break;
		case '<':
			state = &CTokenizer::lessThanSignState;
			break;
		case '>':
			state = &CTokenizer::greaterThanSignState;
			break;
		case '!':
			state = &CTokenizer::exclamationSignState;
			break;
		case '"':
			state = &CTokenizer::regexState;
			text.clear();
			break;
		default:
			if( isdigit( c, locale::classic() ) ) {
				state = &CTokenizer::numberState;
				text.assign( 1, c );
			} else if( IsIdentifierCharacter( c ) ) {
				state = &CTokenizer::indentifierState;
				text.assign( 1, c );
			} else {
				errorProcessor.AddError( CError( CLineSegment( offset ), line,
					"unknown character " + string( 1, c ), ES_CriticalError ) );
			}
			break;
	}
}

void CTokenizer::commentState( char /* c */ )
{
	// just skip any characters after ';'
}

void CTokenizer::regexState( char c )
{
	if( c == '"' ) {
		addToken( TT_Regexp, true /* decreaseAnOffsetByOne */ );
		state = &CTokenizer::initialState;
	} else {
		if( c == '\\' ) {
			state = &CTokenizer::regexStateAfterBackslash;
		}
		text.append( 1, c );
	}
}

void CTokenizer::regexStateAfterBackslash( char c )
{
	state = &CTokenizer::regexState;
	text.append( 1, c );
}

void CTokenizer::numberState( char c )
{
	if( isdigit( c, locale::classic() ) ) {
		text.append( 1, c );
	} else {
		addToken( TT_Number );
		state = &CTokenizer::initialState;
		step( c );
	}
}

void CTokenizer::indentifierState( char c )
{
	if( IsIdentifierCharacter( c ) ) {
		text.append( 1, c );
	} else {
		checkIdentifier();
		addToken( TT_Identifier );
		state = &CTokenizer::initialState;
		step( c );
	}
}

void CTokenizer::tildeState( char c )
{
	state = &CTokenizer::initialState;
	if( c == '>' ) {
		addToken( TT_TildeGreaterThanSign, true /* decreaseAnOffsetByOne */ );
	} else {
		addToken( TT_Tilde, true /* decreaseAnOffsetByOne */ );
		step( c );
	}
}

void CTokenizer::equalSignState( char c )
{
	state = &CTokenizer::initialState;
	if( c == '=' ) {
		addToken( TT_DoubleEqualSign, true /* decreaseAnOffsetByOne */ );
	} else {
		addToken( TT_EqualSign, true /* decreaseAnOffsetByOne */ );
		step( c );
	}
}

void CTokenizer::lessThanSignState( char c )
{
	state = &CTokenizer::initialState;
	if( c == '<' ) {
		addToken( TT_DoubleLessThanSign, true /* decreaseAnOffsetByOne */ );
	} else {
		addToken( TT_LessThanSign, true /* decreaseAnOffsetByOne */ );
		step( c );
	}
}

void CTokenizer::greaterThanSignState( char c )
{
	state = &CTokenizer::initialState;
	if( c == '>' ) {
		addToken( TT_DoubleGreaterThanSign, true/* decreaseAnOffsetByOne */ );
	} else {
		addToken( TT_GreaterThanSign, true /* decreaseAnOffsetByOne */ );
		step( c );
	}
}

void CTokenizer::exclamationSignState( char c )
{
	if( c != '=' ) {
		errorProcessor.AddError( CError( CLineSegment( offset - 1, 2 ),
			line, "incorrect operation, you may possibly mean !=" ) );
	}

	addToken( TT_ExclamationPointEqualSign, true/*decreaseAnOffsetByOne*/ );
	state = &CTokenizer::initialState;
}

///////////////////////////////////////////////////////////////////////////////

} // end of Parser namespace
} // end of Lspl namespace
<|endoftext|>


<commit_before>#ifdef __unix__

#include <iostream>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>

#include "Tools.h"

void StartBotProcess(const std::string& CommandLine)
{
    FILE* pipe = popen(CommandLine.c_str(), "r");
    if (!pipe)
    {
        std::cerr << "Can't launch command '" <<
            CommandLine << "'" << std::endl;
        return;
    }

    int returnCode = pclose(pipe);
    if (returnCode != 0)
    {
        std::cerr << "Failed to finish command '" <<
            CommandLine << "', code: " << returnCode << std::endl;
    }
}

void SleepFor(int seconds)
{
    sleep(seconds);
}

void KillSc2Process(unsigned long pid)
{
    kill(pid, SIGKILL);
}

bool MoveReplayFile(char* lpExistingFileName, char* lpNewFileName)
{
	// todo
	throw "MoveFile is not implemented for linux yet.";
}

#endif<commit_msg>Fix linking error (again, but for Unix this time)<commit_after>#ifdef __unix__

#include <iostream>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>

#include "Tools.h"

void StartBotProcess(const std::string& CommandLine)
{
    FILE* pipe = popen(CommandLine.c_str(), "r");
    if (!pipe)
    {
        std::cerr << "Can't launch command '" <<
            CommandLine << "'" << std::endl;
        return;
    }

    int returnCode = pclose(pipe);
    if (returnCode != 0)
    {
        std::cerr << "Failed to finish command '" <<
            CommandLine << "', code: " << returnCode << std::endl;
    }
}

void SleepFor(int seconds)
{
    sleep(seconds);
}

void KillSc2Process(unsigned long pid)
{
    kill(pid, SIGKILL);
}

bool MoveReplayFile(const char* lpExistingFileName, const  char* lpNewFileName)
{
	// todo
	throw "MoveFile is not implemented for linux yet.";
}

#endif<|endoftext|>


<commit_before>/*
 * Ascent MMORPG Server
 * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
 *
 * 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
 * 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 "DBCStores.h"
#include "DataStore.h"
#include "NGLog.h"

SERVER_DECL DBCStorage<GemPropertyEntry> dbcGemProperty;
SERVER_DECL DBCStorage<ItemSetEntry> dbcItemSet;
SERVER_DECL DBCStorage<Lock> dbcLock;
SERVER_DECL DBCStorage<SpellEntry> dbcSpell;
SERVER_DECL DBCStorage<SpellDuration> dbcSpellDuration;
SERVER_DECL DBCStorage<SpellRange> dbcSpellRange;
SERVER_DECL DBCStorage<emoteentry> dbcEmoteEntry;
SERVER_DECL DBCStorage<SpellRadius> dbcSpellRadius;
SERVER_DECL DBCStorage<SpellCastTime> dbcSpellCastTime;
SERVER_DECL DBCStorage<AreaTable> dbcArea;
SERVER_DECL DBCStorage<FactionTemplateDBC> dbcFactionTemplate;
SERVER_DECL DBCStorage<FactionDBC> dbcFaction;
SERVER_DECL DBCStorage<EnchantEntry> dbcEnchant;
SERVER_DECL DBCStorage<RandomProps> dbcRandomProps;
SERVER_DECL DBCStorage<skilllinespell> dbcSkillLineSpell;
SERVER_DECL DBCStorage<skilllineentry> dbcSkillLine;
SERVER_DECL DBCStorage<DBCTaxiNode> dbcTaxiNode;
SERVER_DECL DBCStorage<DBCTaxiPath> dbcTaxiPath;
SERVER_DECL DBCStorage<DBCTaxiPathNode> dbcTaxiPathNode;
SERVER_DECL DBCStorage<AuctionHouseDBC> dbcAuctionHouse;
SERVER_DECL DBCStorage<TalentEntry> dbcTalent;
SERVER_DECL DBCStorage<CreatureSpellDataEntry> dbcCreatureSpellData;
SERVER_DECL DBCStorage<CreatureFamilyEntry> dbcCreatureFamily;
SERVER_DECL DBCStorage<CharClassEntry> dbcCharClass;
SERVER_DECL DBCStorage<CharRaceEntry> dbcCharRace;
SERVER_DECL DBCStorage<MapEntry> dbcMap;
SERVER_DECL DBCStorage<ItemExtendedCostEntry> dbcItemExtendedCost;
SERVER_DECL DBCStorage<ItemRandomSuffixEntry> dbcItemRandomSuffix;

const char * ItemSetFormat = "uuxxxxxxxxxxxxxxxuuuuuuuuuxxxxxxxxxuuuuuuuuuuuuuuuuuu";
const char * LockFormat = "uuuuuuxxxuuuuuxxxuuuuuxxxxxxxxxxx";
const char * EmoteEntryFormat = "uxuuuuxuxuxxxxxxxxx";
const char * skilllinespellFormat = "uuuxxxxxuuuuxxu";
const char * EnchantEntrYFormat = "uuuuuuuuuuuuuxxxxxxxxxxxxxxxxxuuuu";
const char * GemPropertyEntryFormat = "uuuuu";
const char * skilllineentrYFormat = "uuuxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const char * spellentrYFormat = "uuuuuuuuuuuuuuuuuuuuuuuuuuuuuiuuuuuuuuuufuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuffffffiiiiiiuuuuuuuuuuuuuuufffuuuuuuuuuuuufffuuuuuxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxuuuuuuuuuuifffuuuuuu";
const char * itemextendedcostFormat = "uuuuuuuuuuuuu";
const char * talententryFormat = "uuuuuuuuuxxxxuxxuxxxx";
const char * spellcasttimeFormat = "uuxx";
const char * spellradiusFormat = "ufxf";
const char * spellrangeFormat = "uffxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const char * spelldurationFormat = "uuuu";
const char * randompropsFormat = "uxuuuxxxxxxxxxxxxxxxxxxx";
const char * areatableFormat = "uuuuuxxxuxuxxxxxxxxxxxxxxxxxuxxxxxx";
const char * factiontemplatedbcFormat = "uuuuuuuuuuuuuu";
const char * auctionhousedbcFormat = "uuuuxxxxxxxxxxxxxxxxx";
const char * factiondbcFormat = "uiuuuuxxxxiiiixxxxuxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const char * dbctaxinodeFormat = "uufffxxxxxxxxxxxxxxxxxuu";
const char * dbctaxipathFormat = "uuuu";
const char * dbctaxipathnodeFormat = "uuuufffuuxx";
const char * creaturespelldataFormat = "uuuuuuuuu";
const char * charraceFormat = "uxuxxxxxuxxxxuxxxxxxxxxxxxxxxxxxxxx";
const char * charclassFormat = "uxuxxxxxxxxxxxxxxxxxxxxx";
const char * creaturefamilyFormat = "ufufuuuuxxxxxxxxxxxxxxxxxx";
const char * mapentryFormat = "uxuxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const char * itemrandomsuffixformat = "uxxxxxxxxxxxxxxxxxxuuuuuu";

template<class T>
bool loader_stub(const char * filename, const char * format, bool ind, T& l)
{
	Log.Notice("DBC", "Loading %s.", filename);
	return l.Load(filename, format, ind);
}

#define LOAD_DBC(filename, format, ind, stor) if(!loader_stub(filename, format, ind, stor)) { return false; }

bool LoadDBCs()
{
	LOAD_DBC("DBC/ItemSet.dbc", ItemSetFormat, true, dbcItemSet);
	LOAD_DBC("DBC/Lock.dbc", LockFormat, true, dbcLock);
	LOAD_DBC("DBC/EmotesText.dbc", EmoteEntryFormat, true, dbcEmoteEntry);
	LOAD_DBC("DBC/SkillLineAbility.dbc", skilllinespellFormat, false, dbcSkillLineSpell);
	LOAD_DBC("DBC/SpellItemEnchantment.dbc", EnchantEntrYFormat, true, dbcEnchant);
	LOAD_DBC("DBC/GemProperties.dbc", GemPropertyEntryFormat, true, dbcGemProperty);
	LOAD_DBC("DBC/SkillLine.dbc", skilllineentrYFormat, true, dbcSkillLine);
	LOAD_DBC("DBC/Spell.dbc", spellentrYFormat, true, dbcSpell);
	LOAD_DBC("DBC/ItemExtendedCost.dbc", itemextendedcostFormat, true, dbcItemExtendedCost);
	LOAD_DBC("DBC/Talent.dbc", talententryFormat, true, dbcTalent);
	LOAD_DBC("DBC/SpellCastTimes.dbc", spellcasttimeFormat, true, dbcSpellCastTime);
	LOAD_DBC("DBC/SpellRadius.dbc", spellradiusFormat, true, dbcSpellRadius);
	LOAD_DBC("DBC/SpellRange.dbc", spellrangeFormat, true, dbcSpellRange);
	LOAD_DBC("DBC/SpellDuration.dbc", spelldurationFormat, true, dbcSpellDuration);
	LOAD_DBC("DBC/ItemRandomProperties.dbc", randompropsFormat, true, dbcRandomProps);
	LOAD_DBC("DBC/AreaTable.dbc", areatableFormat, true, dbcArea);
	LOAD_DBC("DBC/FactionTemplate.dbc", factiontemplatedbcFormat, true, dbcFactionTemplate);
	LOAD_DBC("DBC/Faction.dbc", factiondbcFormat, true, dbcFaction);
	LOAD_DBC("DBC/TaxiNodes.dbc", dbctaxinodeFormat, false, dbcTaxiNode);
	LOAD_DBC("DBC/TaxiPath.dbc", dbctaxipathFormat, false, dbcTaxiPath);
	LOAD_DBC("DBC/TaxiPathNode.dbc", dbctaxipathnodeFormat, false, dbcTaxiPathNode);
	LOAD_DBC("DBC/CreatureSpellData.dbc", creaturespelldataFormat, true, dbcCreatureSpellData);
	LOAD_DBC("DBC/CreatureFamily.dbc", creaturefamilyFormat, true, dbcCreatureFamily);
	LOAD_DBC("DBC/ChrRaces.dbc", charraceFormat, true, dbcCharRace);
	LOAD_DBC("DBC/ChrClasses.dbc", charclassFormat, true, dbcCharClass);
	LOAD_DBC("DBC/Map.dbc", mapentryFormat, true, dbcMap);
	LOAD_DBC("DBC/AuctionHouse.dbc", auctionhousedbcFormat, true, dbcAuctionHouse);
	LOAD_DBC("DBC/ItemRandomSuffix.dbc", itemrandomsuffixformat, true, dbcItemRandomSuffix);
	return true;
}

<commit_msg>* 2.3.0 dbc updates<commit_after>/*
 * Ascent MMORPG Server
 * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
 *
 * 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
 * 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 "DBCStores.h"
#include "DataStore.h"
#include "NGLog.h"

SERVER_DECL DBCStorage<GemPropertyEntry> dbcGemProperty;
SERVER_DECL DBCStorage<ItemSetEntry> dbcItemSet;
SERVER_DECL DBCStorage<Lock> dbcLock;
SERVER_DECL DBCStorage<SpellEntry> dbcSpell;
SERVER_DECL DBCStorage<SpellDuration> dbcSpellDuration;
SERVER_DECL DBCStorage<SpellRange> dbcSpellRange;
SERVER_DECL DBCStorage<emoteentry> dbcEmoteEntry;
SERVER_DECL DBCStorage<SpellRadius> dbcSpellRadius;
SERVER_DECL DBCStorage<SpellCastTime> dbcSpellCastTime;
SERVER_DECL DBCStorage<AreaTable> dbcArea;
SERVER_DECL DBCStorage<FactionTemplateDBC> dbcFactionTemplate;
SERVER_DECL DBCStorage<FactionDBC> dbcFaction;
SERVER_DECL DBCStorage<EnchantEntry> dbcEnchant;
SERVER_DECL DBCStorage<RandomProps> dbcRandomProps;
SERVER_DECL DBCStorage<skilllinespell> dbcSkillLineSpell;
SERVER_DECL DBCStorage<skilllineentry> dbcSkillLine;
SERVER_DECL DBCStorage<DBCTaxiNode> dbcTaxiNode;
SERVER_DECL DBCStorage<DBCTaxiPath> dbcTaxiPath;
SERVER_DECL DBCStorage<DBCTaxiPathNode> dbcTaxiPathNode;
SERVER_DECL DBCStorage<AuctionHouseDBC> dbcAuctionHouse;
SERVER_DECL DBCStorage<TalentEntry> dbcTalent;
SERVER_DECL DBCStorage<CreatureSpellDataEntry> dbcCreatureSpellData;
SERVER_DECL DBCStorage<CreatureFamilyEntry> dbcCreatureFamily;
SERVER_DECL DBCStorage<CharClassEntry> dbcCharClass;
SERVER_DECL DBCStorage<CharRaceEntry> dbcCharRace;
SERVER_DECL DBCStorage<MapEntry> dbcMap;
SERVER_DECL DBCStorage<ItemExtendedCostEntry> dbcItemExtendedCost;
SERVER_DECL DBCStorage<ItemRandomSuffixEntry> dbcItemRandomSuffix;

const char * ItemSetFormat = "uuxxxxxxxxxxxxxxxuuuuuuuuuxxxxxxxxxuuuuuuuuuuuuuuuuuu";
const char * LockFormat = "uuuuuuxxxuuuuuxxxuuuuuxxxxxxxxxxx";
const char * EmoteEntryFormat = "uxuuuuxuxuxxxxxxxxx";
const char * skilllinespellFormat = "uuuxxxxxuuuuxxu";
const char * EnchantEntrYFormat = "uuuuuuuuuuuuuxxxxxxxxxxxxxxxxxuuuu";
const char * GemPropertyEntryFormat = "uuuuu";
const char * skilllineentrYFormat = "uuuxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const char * spellentrYFormat = "uuuuuuuuuuuuuuuuuuuuuuuuuuuuuiuuuuuuuuuufuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuffffffiiiiiiuuuuuuuuuuuuuuufffuuuuuuuuuuuufffuuuuuxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxuuuuuuuuuuifffuuuuuu";
const char * itemextendedcostFormat = "uuuuuuuuuuuuux";
const char * talententryFormat = "uuuuuuuuuxxxxuxxuxxxx";
const char * spellcasttimeFormat = "uuxx";
const char * spellradiusFormat = "ufxf";
const char * spellrangeFormat = "uffxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const char * spelldurationFormat = "uuuu";
const char * randompropsFormat = "uxuuuxxxxxxxxxxxxxxxxxxx";
const char * areatableFormat = "uuuuuxxxuxuxxxxxxxxxxxxxxxxxuxxxxxx";
const char * factiontemplatedbcFormat = "uuuuuuuuuuuuuu";
const char * auctionhousedbcFormat = "uuuuxxxxxxxxxxxxxxxxx";
const char * factiondbcFormat = "uiuuuuxxxxiiiixxxxuxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const char * dbctaxinodeFormat = "uufffxxxxxxxxxxxxxxxxxuu";
const char * dbctaxipathFormat = "uuuu";
const char * dbctaxipathnodeFormat = "uuuufffuuxx";
const char * creaturespelldataFormat = "uuuuuuuuu";
const char * charraceFormat = "uxuxxxxxuxxxxuxxxxxxxxxxxxxxxxxxxxx";
const char * charclassFormat = "uxuxxxxxxxxxxxxxxxxxxxxx";
const char * creaturefamilyFormat = "ufufuuuuxxxxxxxxxxxxxxxxxx";
const char * mapentryFormat = "uxuxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const char * itemrandomsuffixformat = "uxxxxxxxxxxxxxxxxxxuuuuuu";

template<class T>
bool loader_stub(const char * filename, const char * format, bool ind, T& l)
{
	Log.Notice("DBC", "Loading %s.", filename);
	return l.Load(filename, format, ind);
}

#define LOAD_DBC(filename, format, ind, stor) if(!loader_stub(filename, format, ind, stor)) { return false; }

bool LoadDBCs()
{
	LOAD_DBC("DBC/ItemSet.dbc", ItemSetFormat, true, dbcItemSet);
	LOAD_DBC("DBC/Lock.dbc", LockFormat, true, dbcLock);
	LOAD_DBC("DBC/EmotesText.dbc", EmoteEntryFormat, true, dbcEmoteEntry);
	LOAD_DBC("DBC/SkillLineAbility.dbc", skilllinespellFormat, false, dbcSkillLineSpell);
	LOAD_DBC("DBC/SpellItemEnchantment.dbc", EnchantEntrYFormat, true, dbcEnchant);
	LOAD_DBC("DBC/GemProperties.dbc", GemPropertyEntryFormat, true, dbcGemProperty);
	LOAD_DBC("DBC/SkillLine.dbc", skilllineentrYFormat, true, dbcSkillLine);
	LOAD_DBC("DBC/Spell.dbc", spellentrYFormat, true, dbcSpell);
	LOAD_DBC("DBC/ItemExtendedCost.dbc", itemextendedcostFormat, true, dbcItemExtendedCost);
	LOAD_DBC("DBC/Talent.dbc", talententryFormat, true, dbcTalent);
	LOAD_DBC("DBC/SpellCastTimes.dbc", spellcasttimeFormat, true, dbcSpellCastTime);
	LOAD_DBC("DBC/SpellRadius.dbc", spellradiusFormat, true, dbcSpellRadius);
	LOAD_DBC("DBC/SpellRange.dbc", spellrangeFormat, true, dbcSpellRange);
	LOAD_DBC("DBC/SpellDuration.dbc", spelldurationFormat, true, dbcSpellDuration);
	LOAD_DBC("DBC/ItemRandomProperties.dbc", randompropsFormat, true, dbcRandomProps);
	LOAD_DBC("DBC/AreaTable.dbc", areatableFormat, true, dbcArea);
	LOAD_DBC("DBC/FactionTemplate.dbc", factiontemplatedbcFormat, true, dbcFactionTemplate);
	LOAD_DBC("DBC/Faction.dbc", factiondbcFormat, true, dbcFaction);
	LOAD_DBC("DBC/TaxiNodes.dbc", dbctaxinodeFormat, false, dbcTaxiNode);
	LOAD_DBC("DBC/TaxiPath.dbc", dbctaxipathFormat, false, dbcTaxiPath);
	LOAD_DBC("DBC/TaxiPathNode.dbc", dbctaxipathnodeFormat, false, dbcTaxiPathNode);
	LOAD_DBC("DBC/CreatureSpellData.dbc", creaturespelldataFormat, true, dbcCreatureSpellData);
	LOAD_DBC("DBC/CreatureFamily.dbc", creaturefamilyFormat, true, dbcCreatureFamily);
	LOAD_DBC("DBC/ChrRaces.dbc", charraceFormat, true, dbcCharRace);
	LOAD_DBC("DBC/ChrClasses.dbc", charclassFormat, true, dbcCharClass);
	LOAD_DBC("DBC/Map.dbc", mapentryFormat, true, dbcMap);
	LOAD_DBC("DBC/AuctionHouse.dbc", auctionhousedbcFormat, true, dbcAuctionHouse);
	LOAD_DBC("DBC/ItemRandomSuffix.dbc", itemrandomsuffixformat, true, dbcItemRandomSuffix);
	return true;
}

<|endoftext|>


<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

//  stable_double.hpp
//
// Contains an implementation of an underflow- and overflow-resistant
// alternative to floating point numbers
//

#ifndef structures_stable_double_hpp
#define structures_stable_double_hpp

#include <ostream>
#include <cmath>
#include <limits>

namespace structures {

using namespace std;

/*
 * A class that supports basic floating point arithmetic operations on internal values stored
 * in log-transformed space to reduce risk of overflow and underflow at the cost of precision
 * in some ranges of values
 */
class StableDouble {
public:

    /// Defaults to 0
    StableDouble();
    /// Convert from a double
    StableDouble(double x);
    /// Construct from log-transformed absolute value and a sign
    StableDouble(double log_abs_x, bool positive);

    /// Convert to double
    inline double to_double() const;

    /// Unary operators

    inline StableDouble operator-() const;
    inline StableDouble inverse() const;

    /// Binary operators with StableDoubles

    inline StableDouble operator*(const StableDouble& other) const;
    inline StableDouble operator/(const StableDouble& other) const;
    inline StableDouble operator+(const StableDouble& other) const;
    inline StableDouble operator-(const StableDouble& other) const;

    /// Binary operators with standard doubles

    inline StableDouble operator*(const double other) const;
    inline StableDouble operator/(const double other) const;
    inline StableDouble operator+(const double other) const;
    inline StableDouble operator-(const double other) const;

    /// Assignment operators with StableDoubles

    inline StableDouble& operator*=(const StableDouble& other);
    inline StableDouble& operator/=(const StableDouble& other);
    inline StableDouble& operator+=(const StableDouble& other);
    inline StableDouble& operator-=(const StableDouble& other);

    /// Assignment operators with standard doubles

    inline StableDouble& operator*=(const double other);
    inline StableDouble& operator/=(const double other);
    inline StableDouble& operator+=(const double other);
    inline StableDouble& operator-=(const double other);

    // Comparison operators with StableDoubles

    inline bool operator<(const StableDouble& other) const;
    inline bool operator>(const StableDouble& other) const;
    inline bool operator<=(const StableDouble& other) const;
    inline bool operator>=(const StableDouble& other) const;

    // Comparison operators with standard doubles

    inline bool operator<(const double other) const;
    inline bool operator>(const double other) const;
    inline bool operator<=(const double other) const;
    inline bool operator>=(const double other) const;

    // Equality operators with StableDoubles

    inline bool operator==(const StableDouble& other) const;
    inline bool operator!=(const StableDouble& other) const;

    // Equality operators with standard doubles

    inline bool operator==(const double other) const;
    inline bool operator!=(const double other) const;

    friend ostream& operator<<(ostream& out, const StableDouble& val);

private:

    // Logarithm of the absolute value
    double log_abs_x;
    // Sign
    bool positive;

    // Returns the log of the sum of two log-transformed values without taking them
    // out of log space.
    inline double add_log(const double log_x, const double log_y) const;

    // Returns the log of the difference of two log-transformed values without taking
    // them out of log space.
    inline double subtract_log(const double log_x, const double log_y) const;
};

ostream& operator<<(ostream& out, const StableDouble& val);

inline double StableDouble::add_log(const double log_x, const double log_y) const {
    return log_x > log_y ? log_x + log(1.0 + exp(log_y - log_x)) : log_y + log(1.0 + exp(log_x - log_y));
}

inline double StableDouble::subtract_log(const double log_x, const double log_y) const {
    return log_x + log(1.0 - exp(log_y - log_x));
}

inline double StableDouble::to_double() const {
    return positive ? exp(log_abs_x) : -exp(log_abs_x);
}

inline StableDouble StableDouble::inverse() const {
    return StableDouble(-log_abs_x, positive);
}

inline StableDouble StableDouble::operator-() const {
    return StableDouble(log_abs_x, !positive);
}

inline StableDouble StableDouble::operator*(const StableDouble& other) const {
    return StableDouble(log_abs_x + other.log_abs_x, positive == other.positive);
}

inline StableDouble StableDouble::operator/(const StableDouble& other) const {
    return StableDouble(log_abs_x - other.log_abs_x, positive == other.positive);
}

inline StableDouble StableDouble::operator+(const StableDouble& other) const {
    if (positive == other.positive) {
        return StableDouble(add_log(log_abs_x, other.log_abs_x), positive);
    }
    else if (log_abs_x == other.log_abs_x) {
        return StableDouble();
    }
    else if (log_abs_x > other.log_abs_x) {
        return StableDouble(subtract_log(log_abs_x, other.log_abs_x), positive);
    }
    else {
        return StableDouble(subtract_log(other.log_abs_x, log_abs_x), other.positive);
    }
}

inline StableDouble StableDouble::operator-(const StableDouble& other) const {
    return *this + (-other);
}

inline StableDouble StableDouble::operator*(const double other) const {
    return *this * StableDouble(other);
}

inline StableDouble StableDouble::operator/(const double other) const {
    return *this / StableDouble(other);
}

inline StableDouble StableDouble::operator+(const double other) const {
    return *this + StableDouble(other);
}

inline StableDouble StableDouble::operator-(const double other) const {
    return *this - StableDouble(other);
}

inline StableDouble& StableDouble::operator*=(const StableDouble& other) {
    *this = *this * other;
    return *this;
}

inline StableDouble& StableDouble::operator/=(const StableDouble& other) {
    *this = *this / other;
    return *this;
}

inline StableDouble& StableDouble::operator+=(const StableDouble& other) {
    *this = *this + other;
    return *this;
}

inline StableDouble& StableDouble::operator-=(const StableDouble& other) {
    *this = *this - other;
    return *this;
}

inline StableDouble& StableDouble::operator*=(const double other) {
    *this = *this * other;
    return *this;
}

inline StableDouble& StableDouble::operator/=(const double other) {
    *this = *this / other;
    return *this;
}

inline StableDouble& StableDouble::operator+=(const double other) {
    *this = *this + other;
    return *this;
}

inline StableDouble& StableDouble::operator-=(const double other) {
    *this = *this - other;
    return *this;
}

inline bool StableDouble::operator<(const StableDouble& other) const {
    if (positive != other.positive) {
        // make sure they're not both 0 with the sign arbitrarily set
        return other.positive && (log_abs_x != numeric_limits<double>::lowest() ||
                                  other.log_abs_x != numeric_limits<double>::lowest());
    }
    else {
        return positive ? (log_abs_x < other.log_abs_x) : (log_abs_x > other.log_abs_x) ;
    }
}

inline bool StableDouble::operator>(const StableDouble& other) const {
    return other < *this;
}

inline bool StableDouble::operator<=(const StableDouble& other) const {
    return !(other < *this);
}

inline bool StableDouble::operator>=(const StableDouble& other) const {
    return !(*this < other);
}

inline bool StableDouble::operator<(const double other) const {
    return *this < StableDouble(other);
}

inline bool StableDouble::operator>(const double other) const {
    return *this > StableDouble(other);
}

inline bool StableDouble::operator<=(const double other) const {
    return *this <= StableDouble(other);
}

inline bool StableDouble::operator>=(const double other) const {
    return *this >= StableDouble(other);
}

inline bool StableDouble::operator==(const StableDouble& other) const {
    return ((log_abs_x == other.log_abs_x) &&
            (log_abs_x == numeric_limits<double>::lowest() || positive == other.positive));
}

inline bool StableDouble::operator!=(const StableDouble& other) const {
    return !(*this == other);
}

inline bool StableDouble::operator==(const double other) const {
    return *this == StableDouble(other);
}

inline bool StableDouble::operator!=(const double other) const {
    return *this != StableDouble(other);
}

}

#endif /* structures_stable_double_hpp */
<commit_msg>use log1p for improved stability<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

//  stable_double.hpp
//
// Contains an implementation of an underflow- and overflow-resistant
// alternative to floating point numbers
//

#ifndef structures_stable_double_hpp
#define structures_stable_double_hpp

#include <ostream>
#include <cmath>
#include <limits>

namespace structures {

using namespace std;

/*
 * A class that supports basic floating point arithmetic operations on internal values stored
 * in log-transformed space to reduce risk of overflow and underflow at the cost of precision
 * in some ranges of values
 */
class StableDouble {
public:

    /// Defaults to 0
    StableDouble();
    /// Convert from a double
    StableDouble(double x);
    /// Construct from log-transformed absolute value and a sign
    StableDouble(double log_abs_x, bool positive);

    /// Convert to double
    inline double to_double() const;

    /// Unary operators

    inline StableDouble operator-() const;
    inline StableDouble inverse() const;

    /// Binary operators with StableDoubles

    inline StableDouble operator*(const StableDouble& other) const;
    inline StableDouble operator/(const StableDouble& other) const;
    inline StableDouble operator+(const StableDouble& other) const;
    inline StableDouble operator-(const StableDouble& other) const;

    /// Binary operators with standard doubles

    inline StableDouble operator*(const double other) const;
    inline StableDouble operator/(const double other) const;
    inline StableDouble operator+(const double other) const;
    inline StableDouble operator-(const double other) const;

    /// Assignment operators with StableDoubles

    inline StableDouble& operator*=(const StableDouble& other);
    inline StableDouble& operator/=(const StableDouble& other);
    inline StableDouble& operator+=(const StableDouble& other);
    inline StableDouble& operator-=(const StableDouble& other);

    /// Assignment operators with standard doubles

    inline StableDouble& operator*=(const double other);
    inline StableDouble& operator/=(const double other);
    inline StableDouble& operator+=(const double other);
    inline StableDouble& operator-=(const double other);

    // Comparison operators with StableDoubles

    inline bool operator<(const StableDouble& other) const;
    inline bool operator>(const StableDouble& other) const;
    inline bool operator<=(const StableDouble& other) const;
    inline bool operator>=(const StableDouble& other) const;

    // Comparison operators with standard doubles

    inline bool operator<(const double other) const;
    inline bool operator>(const double other) const;
    inline bool operator<=(const double other) const;
    inline bool operator>=(const double other) const;

    // Equality operators with StableDoubles

    inline bool operator==(const StableDouble& other) const;
    inline bool operator!=(const StableDouble& other) const;

    // Equality operators with standard doubles

    inline bool operator==(const double other) const;
    inline bool operator!=(const double other) const;

    friend ostream& operator<<(ostream& out, const StableDouble& val);

private:

    // Logarithm of the absolute value
    double log_abs_x;
    // Sign
    bool positive;

    // Returns the log of the sum of two log-transformed values without taking them
    // out of log space.
    inline double add_log(const double log_x, const double log_y) const;

    // Returns the log of the difference of two log-transformed values without taking
    // them out of log space.
    inline double subtract_log(const double log_x, const double log_y) const;
};

ostream& operator<<(ostream& out, const StableDouble& val);

inline double StableDouble::add_log(const double log_x, const double log_y) const {
    return log_x > log_y ? log_x + log1p(exp(log_y - log_x)) : log_y + log(exp(log_x - log_y));
}

inline double StableDouble::subtract_log(const double log_x, const double log_y) const {
    return log_x + log1p(-exp(log_y - log_x));
}

inline double StableDouble::to_double() const {
    return positive ? exp(log_abs_x) : -exp(log_abs_x);
}

inline StableDouble StableDouble::inverse() const {
    return StableDouble(-log_abs_x, positive);
}

inline StableDouble StableDouble::operator-() const {
    return StableDouble(log_abs_x, !positive);
}

inline StableDouble StableDouble::operator*(const StableDouble& other) const {
    return StableDouble(log_abs_x + other.log_abs_x, positive == other.positive);
}

inline StableDouble StableDouble::operator/(const StableDouble& other) const {
    return StableDouble(log_abs_x - other.log_abs_x, positive == other.positive);
}

inline StableDouble StableDouble::operator+(const StableDouble& other) const {
    if (positive == other.positive) {
        return StableDouble(add_log(log_abs_x, other.log_abs_x), positive);
    }
    else if (log_abs_x == other.log_abs_x) {
        return StableDouble();
    }
    else if (log_abs_x > other.log_abs_x) {
        return StableDouble(subtract_log(log_abs_x, other.log_abs_x), positive);
    }
    else {
        return StableDouble(subtract_log(other.log_abs_x, log_abs_x), other.positive);
    }
}

inline StableDouble StableDouble::operator-(const StableDouble& other) const {
    return *this + (-other);
}

inline StableDouble StableDouble::operator*(const double other) const {
    return *this * StableDouble(other);
}

inline StableDouble StableDouble::operator/(const double other) const {
    return *this / StableDouble(other);
}

inline StableDouble StableDouble::operator+(const double other) const {
    return *this + StableDouble(other);
}

inline StableDouble StableDouble::operator-(const double other) const {
    return *this - StableDouble(other);
}

inline StableDouble& StableDouble::operator*=(const StableDouble& other) {
    *this = *this * other;
    return *this;
}

inline StableDouble& StableDouble::operator/=(const StableDouble& other) {
    *this = *this / other;
    return *this;
}

inline StableDouble& StableDouble::operator+=(const StableDouble& other) {
    *this = *this + other;
    return *this;
}

inline StableDouble& StableDouble::operator-=(const StableDouble& other) {
    *this = *this - other;
    return *this;
}

inline StableDouble& StableDouble::operator*=(const double other) {
    *this = *this * other;
    return *this;
}

inline StableDouble& StableDouble::operator/=(const double other) {
    *this = *this / other;
    return *this;
}

inline StableDouble& StableDouble::operator+=(const double other) {
    *this = *this + other;
    return *this;
}

inline StableDouble& StableDouble::operator-=(const double other) {
    *this = *this - other;
    return *this;
}

inline bool StableDouble::operator<(const StableDouble& other) const {
    if (positive != other.positive) {
        // make sure they're not both 0 with the sign arbitrarily set
        return other.positive && (log_abs_x != numeric_limits<double>::lowest() ||
                                  other.log_abs_x != numeric_limits<double>::lowest());
    }
    else {
        return positive ? (log_abs_x < other.log_abs_x) : (log_abs_x > other.log_abs_x) ;
    }
}

inline bool StableDouble::operator>(const StableDouble& other) const {
    return other < *this;
}

inline bool StableDouble::operator<=(const StableDouble& other) const {
    return !(other < *this);
}

inline bool StableDouble::operator>=(const StableDouble& other) const {
    return !(*this < other);
}

inline bool StableDouble::operator<(const double other) const {
    return *this < StableDouble(other);
}

inline bool StableDouble::operator>(const double other) const {
    return *this > StableDouble(other);
}

inline bool StableDouble::operator<=(const double other) const {
    return *this <= StableDouble(other);
}

inline bool StableDouble::operator>=(const double other) const {
    return *this >= StableDouble(other);
}

inline bool StableDouble::operator==(const StableDouble& other) const {
    return ((log_abs_x == other.log_abs_x) &&
            (log_abs_x == numeric_limits<double>::lowest() || positive == other.positive));
}

inline bool StableDouble::operator!=(const StableDouble& other) const {
    return !(*this == other);
}

inline bool StableDouble::operator==(const double other) const {
    return *this == StableDouble(other);
}

inline bool StableDouble::operator!=(const double other) const {
    return *this != StableDouble(other);
}

}

#endif /* structures_stable_double_hpp */
<|endoftext|>


<commit_before>/**
 * @file TextPlot.cpp
 *
 * A simple console-based data plotter.
 *
 * This file is part of the Aquila DSP library.
 * Aquila is free software, licensed under the MIT/X11 License. A copy of
 * the license is provided with the library in the LICENSE file.
 *
 * @package Aquila
 * @version 3.0.0-dev
 * @author Zbigniew Siciarz
 * @date 2007-2013
 * @license http://www.opensource.org/licenses/mit-license.php MIT
 * @since 3.0.0
 */

#include "TextPlot.h"
#include <boost/scoped_array.hpp>

namespace Aquila
{
    /**
     * Creates the plot object.
     *
     * @param title plot title (optional, default is "Data plot")
     * @param out where to output the plot data (default is std::cout)
     */
    TextPlot::TextPlot(const std::string &title, std::ostream &out):
        m_title(title), m_out(out), m_width(64), m_height(16)
    {
    }

    /**
     * "Draws" the plot to the output stream.
     *
     * @param plot internal plot data
     */
    void TextPlot::drawPlotMatrix(const PlotMatrixType &plot)
    {
        const std::size_t length = plot.size();

        m_out << "\n" << m_title << "\n";
        // output the plot data, flushing only at the end
        for (unsigned int y = 0; y < m_height; ++y)
        {
            for (unsigned int x = 0; x < length; ++x)
            {
                m_out << plot[x][y];
            }
            m_out << "\n";
        }
        m_out.flush();
    }

    /**
     * A shorthand for plotting only the first half of magnitude spectrum.
     *
     * @param spectrum an array of complex numbers
     * @param length size of the spectrum (total, not half!)
     */
    void TextPlot::plotSpectrum(Aquila::ComplexType spectrum[], std::size_t length)
    {
        boost::scoped_array<double> absSpectrum(new double[length/2]);
        for (std::size_t i = 0; i < length/2; ++i)
        {
            absSpectrum[i] = std::abs(spectrum[i]);
        }
        plot(absSpectrum.get(), length/2);
    }
}
<commit_msg>Using unique_ptr in TextPlot.<commit_after>/**
 * @file TextPlot.cpp
 *
 * A simple console-based data plotter.
 *
 * This file is part of the Aquila DSP library.
 * Aquila is free software, licensed under the MIT/X11 License. A copy of
 * the license is provided with the library in the LICENSE file.
 *
 * @package Aquila
 * @version 3.0.0-dev
 * @author Zbigniew Siciarz
 * @date 2007-2013
 * @license http://www.opensource.org/licenses/mit-license.php MIT
 * @since 3.0.0
 */

#include "TextPlot.h"
#include <memory>

namespace Aquila
{
    /**
     * Creates the plot object.
     *
     * @param title plot title (optional, default is "Data plot")
     * @param out where to output the plot data (default is std::cout)
     */
    TextPlot::TextPlot(const std::string &title, std::ostream &out):
        m_title(title), m_out(out), m_width(64), m_height(16)
    {
    }

    /**
     * "Draws" the plot to the output stream.
     *
     * @param plot internal plot data
     */
    void TextPlot::drawPlotMatrix(const PlotMatrixType &plot)
    {
        const std::size_t length = plot.size();

        m_out << "\n" << m_title << "\n";
        // output the plot data, flushing only at the end
        for (unsigned int y = 0; y < m_height; ++y)
        {
            for (unsigned int x = 0; x < length; ++x)
            {
                m_out << plot[x][y];
            }
            m_out << "\n";
        }
        m_out.flush();
    }

    /**
     * A shorthand for plotting only the first half of magnitude spectrum.
     *
     * @param spectrum an array of complex numbers
     * @param length size of the spectrum (total, not half!)
     */
    void TextPlot::plotSpectrum(Aquila::ComplexType spectrum[], std::size_t length)
    {
        std::unique_ptr<double[]> absSpectrum(new double[length/2]);
        for (std::size_t i = 0; i < length/2; ++i)
        {
            absSpectrum[i] = std::abs(spectrum[i]);
        }
        plot(absSpectrum.get(), length/2);
    }
}
<|endoftext|>


<commit_before>
#include "U8Gettext.h"
#include <Arduino.h>

#define ENSURE(condition) do { if (!(condition)) {Serial.println("ENSURE failed at: "#condition); while(1); } } while(0)
#define SIZE_OF_ARRAY(array) (sizeof((array))/sizeof((array)[0]))
#define PTR_OFFSET_BYTES(ptr, nBytes) ((void*)(((char *)(ptr)) + (nBytes)))
#define PTR_OFFSET_BETWEEN(ptrBegin, ptrEnd) ((char*)(ptrEnd) - (char*)(ptrBegin))

extern const size_t gU8GettextLanguagesLength;
extern const U8GettextLanguage gU8GettextLanguages[];

static const U8GettextLanguage *
sLanguageInstance = NULL;

const char *U8GettextSetLanguage(const char *language)
{
  const char * oldLanguage = sU8GettextLanguage;

  sU8GettextLanguage = language;
  return oldLanguage;
}

const char *U8GettextGetLanguage()
{
  if (sLanguageInstance) {
    return sLanguageInstance->language;
  }

  // If you have not set any langauge, it return empty string. So that
  // it won't cause program crash if any other function invoke this
  // function without set language.
  return "";
}

const char *U8Gettext(const char *str)
{
  uint16_t i = 0;
  const U8GettextTranslation *translation = NULL;

  if (!sLanguageInstance) {
    return str;
  }

  translation = sLanguageInstance->translations;
  for(i = 0; i < sLanguageInstance->translationCount; ++i, ++translation) {
    // Slowest way to find translation
    if(0 == strcmp(str, translation->msgId)) {
      return translation->msgStr;
    }
  }

  // Can't find any translations!
  return str;
}
<commit_msg>Search and set language instance during U8GettextSetLanguage<commit_after>
#include "U8Gettext.h"
#include <Arduino.h>

#define ENSURE(condition) do { if (!(condition)) {Serial.println("ENSURE failed at: "#condition); while(1); } } while(0)
#define SIZE_OF_ARRAY(array) (sizeof((array))/sizeof((array)[0]))
#define PTR_OFFSET_BYTES(ptr, nBytes) ((void*)(((char *)(ptr)) + (nBytes)))
#define PTR_OFFSET_BETWEEN(ptrBegin, ptrEnd) ((char*)(ptrEnd) - (char*)(ptrBegin))

extern const size_t gU8GettextLanguagesLength;
extern const U8GettextLanguage gU8GettextLanguages[];

static const U8GettextLanguage *
sLanguageInstance = NULL;

const char *U8GettextSetLanguage(const char *language)
{
  uint16_t i = 0;
  const char * oldLanguage = "";
  const U8GettextLanguage * languageInstance = NULL;

  if (sLanguageInstance) {
    oldLanguage = sLanguageInstance->language;
  }

  languageInstance = gU8GettextLanguages;
  for(i = 0; i < gU8GettextLanguagesLength; ++i, ++languageInstance) {
    // Set the language instance by specific language
    if(0 == strcmp(language, languageInstance->language)) {
      sLanguageInstance = languageInstance;
      break;
    }
  }

  return oldLanguage;
}

const char *U8GettextGetLanguage()
{
  if (sLanguageInstance) {
    return sLanguageInstance->language;
  }

  // If you have not set any langauge, it return empty string. So that
  // it won't cause program crash if any other function invoke this
  // function without set language.
  return "";
}

const char *U8Gettext(const char *str)
{
  uint16_t i = 0;
  const U8GettextTranslation *translation = NULL;

  if (!sLanguageInstance) {
    return str;
  }

  translation = sLanguageInstance->translations;
  for(i = 0; i < sLanguageInstance->translationCount; ++i, ++translation) {
    // Slowest way to find translation
    if(0 == strcmp(str, translation->msgId)) {
      return translation->msgStr;
    }
  }

  // Can't find any translations!
  return str;
}
<|endoftext|>