<commit_before>/*  cbr
 *  TimerSpeedBenchmark.cpp
 *
 *  Copyright (c) 2009, Ewen Cheslack-Postava
 *  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 cbr 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 "sirikata/network/IOServiceFactory.hpp"
#include "sirikata/network/IOService.hpp"
#include "sirikata/network/StreamFactory.hpp"
#include "sirikata/network/StreamListenerFactory.hpp"

#include <functional>
#include "SSTBenchmark.hpp"
#include "Timer.hpp"
#include "Options.hpp"
#include "sirikata/util/PluginManager.hpp"
#define ITERATIONS 1000000

namespace CBR {

SSTBenchmark::SSTBenchmark(const FinishedCallback& finished_cb, const String&param)
        : Benchmark(finished_cb),
         mForceStop(false),
         mPingRate(Duration::seconds(0)),
         mStartTime(Time::epoch())
{
    mPingsReceived=0;
    mPingsSent=0;
    mStream=NULL;
    mListener=NULL;

    OptionValue*port;
    OptionValue*host;
    OptionValue*pingSize;
    OptionValue*pingRate;
    OptionValue*ordered;
    OptionValue*streamOptions;
    OptionValue*listenOptions;
    OptionValue*whichPlugin;
    OptionValue*numPings;
    mIOService = Sirikata::Network::IOServiceFactory::makeIOService();
    Sirikata::InitializeClassOptions ico("SSTBenchmark",this,
                                         port=new OptionValue("port","4091",Sirikata::OptionValueType<String>(),"port to connect/listen on"),
                                         host=new OptionValue("host","",Sirikata::OptionValueType<String>(),"host to connect to (blank for listen)"),
                                         pingSize=new OptionValue("ping-size","10",Sirikata::OptionValueType<size_t>(),"Size of each individual ping"),
                                         pingRate=new OptionValue("pings-per-second","0",Sirikata::OptionValueType<double>(),"number of pings launched per second"),
                                         ordered=new OptionValue("ordered","true",Sirikata::OptionValueType<bool>(),"are the pings unordered"),
                                         listenOptions=new OptionValue("listen-options","",Sirikata::OptionValueType<String>(),"options passed to tcpsst"),
                                         streamOptions=new OptionValue("stream-options","",Sirikata::OptionValueType<String>(),"options passed to tcpsst"),
                                         whichPlugin=new OptionValue("stream-plugin","tcpsst",Sirikata::OptionValueType<String>(),"which plugin to load for sst functionality"),
                                         numPings=new OptionValue("num-pings","1000",Sirikata::OptionValueType<size_t>(),"How many pings to "),
                                         NULL);

    OptionSet* optionsSet = OptionSet::getOptions("SSTBenchmark",this);
    optionsSet->parse(param);

    mPort=port->as<String>();
    mHost=host->as<String>();
    mPingSize=pingSize->as<size_t>();
    double pr=pingRate->as<double>();
    mPingRate=Duration::seconds(pr?1./pr:0);
    mListenOptions=listenOptions->as<String>();
    mStreamOptions=streamOptions->as<String>();
    mStreamPlugin=whichPlugin->as<String>();
    mOrdered=ordered->as<bool>();
    mPingFunction=std::tr1::bind(&SSTBenchmark::pingPoller,this);
    mNumPings=numPings->as<size_t>();
}

String SSTBenchmark::name() {
    return "ping";
}

void SSTBenchmark::pingPoller(){
    if (mPingsSent<mNumPings&&!mForceStop) {
        size_t pingNumber=mOutstandingPings.size();
        Time cur=Time::now(Duration::zero());
        double invPingRate=mPingRate.toSeconds();
        size_t numPings=invPingRate?(size_t)((cur-mStartTime).toSeconds()/invPingRate):1;
        for (size_t i=0;i<numPings;++i) {
            mOutstandingPings.push_back(cur);
            mPingResponses.push_back(Duration::zero());
            Sirikata::Network::Chunk serializedChunk;
            for (int i=0;i<8;++i) {
                unsigned char pn=pingNumber%256;
                serializedChunk.push_back(pn);
                pingNumber/=256;
            }
            if (mPingSize>serializedChunk.size()) {
                serializedChunk.resize(mPingSize);
            }
            if (mStream->send(serializedChunk,mOrdered?Sirikata::Network::ReliableOrdered:Sirikata::Network::ReliableUnordered)) {
                ++mPingsSent;
            }
        }
        if (mPingRate.toSeconds()!=0) {
            mIOService->post(mPingRate,mPingFunction);
        }
    }

}
void SSTBenchmark::connected(Sirikata::Network::Stream::ConnectionStatus connectionStatus,const std::string&reason){
    if (connectionStatus==Sirikata::Network::Stream::Connected) {
       //FIXME start pinging
        mStartTime = Time::now(Duration::zero());
        mIOService->post(mPingRate,mPingFunction);
    }
}
void SSTBenchmark::remoteConnected(Sirikata::Network::Stream*strm, Sirikata::Network::Stream::ConnectionStatus connectionStatus,const std::string&reason){
    if (connectionStatus!=Sirikata::Network::Stream::Connected) {
        strm->close();
    }
}

Sirikata::Network::Stream::ReceivedResponse SSTBenchmark::computePingTime(Sirikata::Network::Chunk&chk){
    Time cur=Time::now(Duration::zero());
    size_t index=0;
    if (chk.size()>=8) {
        for (int i=8;i-- > 0;) {
            index*=256;
            index+=chk[i];
        }
        if (index<mOutstandingPings.size()&&index<mPingResponses.size()) {
            mPingResponses[index]=cur-mOutstandingPings[index];
        }else {
            SILOG(benchmark,error,"Malformed ping packet contained invalida index");
        }
    }else {
        SILOG(benchmark,error,"Malformed time packet");
    }
    if (++mPingsReceived>=mNumPings) {
        Duration avg(Duration::zero());
        for(size_t i=0;i<mPingResponses.size();++i){
            avg+=mPingResponses[i];
        }
        avg/=(double)mPingResponses.size();
        SILOG(benchmark,info,"Ping Average "<<avg);
        SILOG(benchmark,info,"Transfer Rate "<<2*mNumPings*(double)chk.size()/(cur-mStartTime).toSeconds());
        stop();
    }else
    if (mPingRate.toSeconds()==0) {
        pingPoller();
    }
    return Sirikata::Network::Stream::AcceptedData;
}
Sirikata::Network::Stream::ReceivedResponse SSTBenchmark::bouncePing(Sirikata::Network::Stream* strm, Sirikata::Network::Chunk&chk){
    if (!mForceStop) {
        strm->send(chk,mOrdered?Sirikata::Network::ReliableOrdered:Sirikata::Network::ReliableUnordered);
    }
    return Sirikata::Network::Stream::AcceptedData;
}
void SSTBenchmark::newStream(Sirikata::Network::Stream*newStream, Sirikata::Network::Stream::SetCallbacks&cb) {
    if (newStream) {
        cb(std::tr1::bind(&SSTBenchmark::remoteConnected,this,newStream,_1,_2),
           std::tr1::bind(&SSTBenchmark::bouncePing,this,newStream,_1),
           &Sirikata::Network::Stream::ignoreReadySendCallback);
    }
}

void noop(){}
void SSTBenchmark::start() {
    static Sirikata::PluginManager pluginManager;
    pluginManager.load(Sirikata::DynamicLibrary::filename(mStreamPlugin));
    mForceStop = false;
    if (!mHost.empty()) {
        mStream=Sirikata::Network::StreamFactory::getSingleton().getConstructor(mStreamPlugin)(mIOService,Sirikata::Network::StreamFactory::getSingleton().getOptionParser(mStreamPlugin)(mStreamOptions));
        mStream->connect(Sirikata::Network::Address(mHost,mPort),
                         &Sirikata::Network::Stream::ignoreSubstreamCallback,
                         std::tr1::bind(&SSTBenchmark::connected,this,_1,_2),
                         std::tr1::bind(&SSTBenchmark::computePingTime,this,_1),
                         &Sirikata::Network::Stream::ignoreReadySendCallback);

    }else {
        mListener=Sirikata::Network::StreamListenerFactory::getSingleton().getConstructor(mStreamPlugin)(mIOService,Sirikata::Network::StreamFactory::getSingleton().getOptionParser(mStreamPlugin)(mListenOptions));
        mListener->listen(Sirikata::Network::Address("127.0.0.1",mPort),
                          std::tr1::bind(&SSTBenchmark::newStream,this,_1,_2));

        mIOService->post(Duration::seconds(10000000.),&noop);

    }
    mIOService->run();
}

void SSTBenchmark::stop() {
    mForceStop = true;
    if(mIOService)
        mIOService->stop();
    if (mListener)
        mListener->close();
    if(mStream)
        mStream->close();
    if (mIOService)
        IOServiceFactory::destroyIOService(mIOService);
    mIOService=NULL;
    mStream=NULL;
    mListener=NULL;
        notifyFinished();
}

} // namespace CBR
<commit_msg>Fix SSTBenchmark, which was trying to boost::placeholders instead of std::tr1::placeholders.<commit_after>/*  cbr
 *  TimerSpeedBenchmark.cpp
 *
 *  Copyright (c) 2009, Ewen Cheslack-Postava
 *  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 cbr 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 "sirikata/network/IOServiceFactory.hpp"
#include "sirikata/network/IOService.hpp"
#include "sirikata/network/StreamFactory.hpp"
#include "sirikata/network/StreamListenerFactory.hpp"

#include <functional>
#include "SSTBenchmark.hpp"
#include "Timer.hpp"
#include "Options.hpp"
#include "sirikata/util/PluginManager.hpp"
#define ITERATIONS 1000000

namespace CBR {

using std::tr1::placeholders::_1;
using std::tr1::placeholders::_2;

SSTBenchmark::SSTBenchmark(const FinishedCallback& finished_cb, const String&param)
        : Benchmark(finished_cb),
         mForceStop(false),
         mPingRate(Duration::seconds(0)),
         mStartTime(Time::epoch())
{
    mPingsReceived=0;
    mPingsSent=0;
    mStream=NULL;
    mListener=NULL;

    OptionValue*port;
    OptionValue*host;
    OptionValue*pingSize;
    OptionValue*pingRate;
    OptionValue*ordered;
    OptionValue*streamOptions;
    OptionValue*listenOptions;
    OptionValue*whichPlugin;
    OptionValue*numPings;
    mIOService = Sirikata::Network::IOServiceFactory::makeIOService();
    Sirikata::InitializeClassOptions ico("SSTBenchmark",this,
                                         port=new OptionValue("port","4091",Sirikata::OptionValueType<String>(),"port to connect/listen on"),
                                         host=new OptionValue("host","",Sirikata::OptionValueType<String>(),"host to connect to (blank for listen)"),
                                         pingSize=new OptionValue("ping-size","10",Sirikata::OptionValueType<size_t>(),"Size of each individual ping"),
                                         pingRate=new OptionValue("pings-per-second","0",Sirikata::OptionValueType<double>(),"number of pings launched per second"),
                                         ordered=new OptionValue("ordered","true",Sirikata::OptionValueType<bool>(),"are the pings unordered"),
                                         listenOptions=new OptionValue("listen-options","",Sirikata::OptionValueType<String>(),"options passed to tcpsst"),
                                         streamOptions=new OptionValue("stream-options","",Sirikata::OptionValueType<String>(),"options passed to tcpsst"),
                                         whichPlugin=new OptionValue("stream-plugin","tcpsst",Sirikata::OptionValueType<String>(),"which plugin to load for sst functionality"),
                                         numPings=new OptionValue("num-pings","1000",Sirikata::OptionValueType<size_t>(),"How many pings to "),
                                         NULL);

    OptionSet* optionsSet = OptionSet::getOptions("SSTBenchmark",this);
    optionsSet->parse(param);

    mPort=port->as<String>();
    mHost=host->as<String>();
    mPingSize=pingSize->as<size_t>();
    double pr=pingRate->as<double>();
    mPingRate=Duration::seconds(pr?1./pr:0);
    mListenOptions=listenOptions->as<String>();
    mStreamOptions=streamOptions->as<String>();
    mStreamPlugin=whichPlugin->as<String>();
    mOrdered=ordered->as<bool>();
    mPingFunction=std::tr1::bind(&SSTBenchmark::pingPoller,this);
    mNumPings=numPings->as<size_t>();
}

String SSTBenchmark::name() {
    return "ping";
}

void SSTBenchmark::pingPoller(){
    if (mPingsSent<mNumPings&&!mForceStop) {
        size_t pingNumber=mOutstandingPings.size();
        Time cur=Time::now(Duration::zero());
        double invPingRate=mPingRate.toSeconds();
        size_t numPings=invPingRate?(size_t)((cur-mStartTime).toSeconds()/invPingRate):1;
        for (size_t i=0;i<numPings;++i) {
            mOutstandingPings.push_back(cur);
            mPingResponses.push_back(Duration::zero());
            Sirikata::Network::Chunk serializedChunk;
            for (int i=0;i<8;++i) {
                unsigned char pn=pingNumber%256;
                serializedChunk.push_back(pn);
                pingNumber/=256;
            }
            if (mPingSize>serializedChunk.size()) {
                serializedChunk.resize(mPingSize);
            }
            if (mStream->send(serializedChunk,mOrdered?Sirikata::Network::ReliableOrdered:Sirikata::Network::ReliableUnordered)) {
                ++mPingsSent;
            }
        }
        if (mPingRate.toSeconds()!=0) {
            mIOService->post(mPingRate,mPingFunction);
        }
    }

}
void SSTBenchmark::connected(Sirikata::Network::Stream::ConnectionStatus connectionStatus,const std::string&reason){
    if (connectionStatus==Sirikata::Network::Stream::Connected) {
       //FIXME start pinging
        mStartTime = Time::now(Duration::zero());
        mIOService->post(mPingRate,mPingFunction);
    }
}
void SSTBenchmark::remoteConnected(Sirikata::Network::Stream*strm, Sirikata::Network::Stream::ConnectionStatus connectionStatus,const std::string&reason){
    if (connectionStatus!=Sirikata::Network::Stream::Connected) {
        strm->close();
    }
}

Sirikata::Network::Stream::ReceivedResponse SSTBenchmark::computePingTime(Sirikata::Network::Chunk&chk){
    Time cur=Time::now(Duration::zero());
    size_t index=0;
    if (chk.size()>=8) {
        for (int i=8;i-- > 0;) {
            index*=256;
            index+=chk[i];
        }
        if (index<mOutstandingPings.size()&&index<mPingResponses.size()) {
            mPingResponses[index]=cur-mOutstandingPings[index];
        }else {
            SILOG(benchmark,error,"Malformed ping packet contained invalida index");
        }
    }else {
        SILOG(benchmark,error,"Malformed time packet");
    }
    if (++mPingsReceived>=mNumPings) {
        Duration avg(Duration::zero());
        for(size_t i=0;i<mPingResponses.size();++i){
            avg+=mPingResponses[i];
        }
        avg/=(double)mPingResponses.size();
        SILOG(benchmark,info,"Ping Average "<<avg);
        SILOG(benchmark,info,"Transfer Rate "<<2*mNumPings*(double)chk.size()/(cur-mStartTime).toSeconds());
        stop();
    }else
    if (mPingRate.toSeconds()==0) {
        pingPoller();
    }
    return Sirikata::Network::Stream::AcceptedData;
}
Sirikata::Network::Stream::ReceivedResponse SSTBenchmark::bouncePing(Sirikata::Network::Stream* strm, Sirikata::Network::Chunk&chk){
    if (!mForceStop) {
        strm->send(chk,mOrdered?Sirikata::Network::ReliableOrdered:Sirikata::Network::ReliableUnordered);
    }
    return Sirikata::Network::Stream::AcceptedData;
}
void SSTBenchmark::newStream(Sirikata::Network::Stream*newStream, Sirikata::Network::Stream::SetCallbacks&cb) {
    if (newStream) {
        cb(std::tr1::bind(&SSTBenchmark::remoteConnected,this,newStream,_1,_2),
           std::tr1::bind(&SSTBenchmark::bouncePing,this,newStream,_1),
           &Sirikata::Network::Stream::ignoreReadySendCallback);
    }
}

void noop(){}
void SSTBenchmark::start() {
    static Sirikata::PluginManager pluginManager;
    pluginManager.load(Sirikata::DynamicLibrary::filename(mStreamPlugin));
    mForceStop = false;
    if (!mHost.empty()) {
        mStream=Sirikata::Network::StreamFactory::getSingleton().getConstructor(mStreamPlugin)(mIOService,Sirikata::Network::StreamFactory::getSingleton().getOptionParser(mStreamPlugin)(mStreamOptions));
        mStream->connect(Sirikata::Network::Address(mHost,mPort),
                         &Sirikata::Network::Stream::ignoreSubstreamCallback,
                         std::tr1::bind(&SSTBenchmark::connected,this,_1,_2),
                         std::tr1::bind(&SSTBenchmark::computePingTime,this,_1),
                         &Sirikata::Network::Stream::ignoreReadySendCallback);

    }else {
        mListener=Sirikata::Network::StreamListenerFactory::getSingleton().getConstructor(mStreamPlugin)(mIOService,Sirikata::Network::StreamFactory::getSingleton().getOptionParser(mStreamPlugin)(mListenOptions));
        mListener->listen(Sirikata::Network::Address("127.0.0.1",mPort),
                          std::tr1::bind(&SSTBenchmark::newStream,this,_1,_2));

        mIOService->post(Duration::seconds(10000000.),&noop);

    }
    mIOService->run();
}

void SSTBenchmark::stop() {
    mForceStop = true;
    if(mIOService)
        mIOService->stop();
    if (mListener)
        mListener->close();
    if(mStream)
        mStream->close();
    if (mIOService)
        IOServiceFactory::destroyIOService(mIOService);
    mIOService=NULL;
    mStream=NULL;
    mListener=NULL;
        notifyFinished();
}

} // namespace CBR
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: filelist.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 22:49: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_sot.hxx"

#include<tools/list.hxx>
#include<tools/stream.hxx>
#include<tools/string.hxx>
#include<tools/rtti.hxx>
#include<sot/exchange.hxx>
#include<filelist.hxx>

#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif

TYPEINIT1_AUTOFACTORY( FileList, SvDataCopyStream );

// String-Liste zum Speichern der Namen deklarieren
DECLARE_LIST( FileStringList, String* )

/*************************************************************************
|*
|*    FileList - Ctor/Dtor
|*
\*************************************************************************/

FileList::FileList()
{
    pStrList = new FileStringList();
}

FileList::~FileList()
{
    ClearAll();
}

void FileList::ClearAll( void )
{
    // Strings in der Liste loeschen
    ULONG nCount = pStrList->Count();
    for( ULONG i = 0 ; i < nCount ; i++ )
        delete pStrList->GetObject( i );

    // Liste loeschen
    delete pStrList;
}

/*************************************************************************
|*
|*    FileList - Zuweisungsoperator
|*
\*************************************************************************/

FileList& FileList::operator=( const FileList& rFileList )
{
    // Liste duplizieren
    *pStrList = *rFileList.pStrList;

    // Strings in der Liste kopieren
    ULONG nCount = pStrList->Count();
    for( ULONG i = 0 ; i < nCount ; i++ )
        pStrList->Replace( new String( *rFileList.pStrList->GetObject( i ) ), i );

    return *this;
}

/*************************************************************************
|*
|*    FileList::GetFormatName()
|*
\*************************************************************************/

ULONG FileList::GetFormat()
{
    return FORMAT_FILE_LIST;
}

/******************************************************************************
|*
|*  virtuelle SvData-Methoden
|*
\******************************************************************************/

void FileList::Load( SvStream& rIStm )
{
    rIStm >> *this;
}

void FileList::Save( SvStream& rOStm )
{
    rOStm << *this;
}

void FileList::Assign( const SvDataCopyStream& rCopyStream )
{
    *this = (const FileList&)rCopyStream;
}

/******************************************************************************
|*
|*  Stream-Operatoren
|*
\******************************************************************************/

/*
 * NOTE: to correctly handle this Protocol with Unicode, native Win32 must be called:
 * e.g. DropQueryFile
 */

SvStream& operator<<( SvStream& rOStm, const FileList& /*rFileList*/ )
{
    OSL_ENSURE(false, "Not implemented!");
    return rOStm;
}

/* #i28176#
   The Windows clipboard bridge now provides a double '\0'
   terminated list of file names for format SOT_FORMAT_FILE_LIST
   instead of the original Windows Sv_DROPFILES structure. All strings
   in this list are UTF16 strings. Shell link files will be already
   resolved by the Windows clipboard bridge.*/
SvStream& operator>>( SvStream& rIStm, FileList& rFileList )
{
    rFileList.ClearAll();
    rFileList.pStrList = new FileStringList();

    String aStr;
    sal_uInt16 c;

    while (!rIStm.IsEof())
    {
        aStr.Erase();

        // read first character of filepath; c==0 > reach end of stream
        rIStm >> c;
        if (!c)
            break;

        // read string till c==0
        while (c && !rIStm.IsEof())
        {
            aStr += (sal_Unicode)c;
            rIStm >> c;
        }

        // append the filepath
        rFileList.AppendFile(aStr);
    }
    return rIStm;
}

/******************************************************************************
|*
|*  Liste fuellen/abfragen
|*
\******************************************************************************/

void FileList::AppendFile( const String& rStr )
{
    pStrList->Insert( new String( rStr ) , pStrList->Count() );
}

String FileList::GetFile( ULONG i ) const
{
    String aStr;
    if( i < pStrList->Count() )
        aStr = *pStrList->GetObject( i );
    return aStr;
}

ULONG FileList::Count( void ) const
{
    return pStrList->Count();
}

<commit_msg>INTEGRATION: CWS changefileheader (1.10.28); FILE MERGED 2008/04/01 15:41:33 thb 1.10.28.2: #i85898# Stripping all external header guards 2008/03/31 12:49:57 rt 1.10.28.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: filelist.cxx,v $
 * $Revision: 1.11 $
 *
 * 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_sot.hxx"

#include<tools/list.hxx>
#include<tools/stream.hxx>
#include<tools/string.hxx>
#include<tools/rtti.hxx>
#include<sot/exchange.hxx>
#include<filelist.hxx>
#include <osl/thread.h>

TYPEINIT1_AUTOFACTORY( FileList, SvDataCopyStream );

// String-Liste zum Speichern der Namen deklarieren
DECLARE_LIST( FileStringList, String* )

/*************************************************************************
|*
|*    FileList - Ctor/Dtor
|*
\*************************************************************************/

FileList::FileList()
{
    pStrList = new FileStringList();
}

FileList::~FileList()
{
    ClearAll();
}

void FileList::ClearAll( void )
{
    // Strings in der Liste loeschen
    ULONG nCount = pStrList->Count();
    for( ULONG i = 0 ; i < nCount ; i++ )
        delete pStrList->GetObject( i );

    // Liste loeschen
    delete pStrList;
}

/*************************************************************************
|*
|*    FileList - Zuweisungsoperator
|*
\*************************************************************************/

FileList& FileList::operator=( const FileList& rFileList )
{
    // Liste duplizieren
    *pStrList = *rFileList.pStrList;

    // Strings in der Liste kopieren
    ULONG nCount = pStrList->Count();
    for( ULONG i = 0 ; i < nCount ; i++ )
        pStrList->Replace( new String( *rFileList.pStrList->GetObject( i ) ), i );

    return *this;
}

/*************************************************************************
|*
|*    FileList::GetFormatName()
|*
\*************************************************************************/

ULONG FileList::GetFormat()
{
    return FORMAT_FILE_LIST;
}

/******************************************************************************
|*
|*  virtuelle SvData-Methoden
|*
\******************************************************************************/

void FileList::Load( SvStream& rIStm )
{
    rIStm >> *this;
}

void FileList::Save( SvStream& rOStm )
{
    rOStm << *this;
}

void FileList::Assign( const SvDataCopyStream& rCopyStream )
{
    *this = (const FileList&)rCopyStream;
}

/******************************************************************************
|*
|*  Stream-Operatoren
|*
\******************************************************************************/

/*
 * NOTE: to correctly handle this Protocol with Unicode, native Win32 must be called:
 * e.g. DropQueryFile
 */

SvStream& operator<<( SvStream& rOStm, const FileList& /*rFileList*/ )
{
    OSL_ENSURE(false, "Not implemented!");
    return rOStm;
}

/* #i28176#
   The Windows clipboard bridge now provides a double '\0'
   terminated list of file names for format SOT_FORMAT_FILE_LIST
   instead of the original Windows Sv_DROPFILES structure. All strings
   in this list are UTF16 strings. Shell link files will be already
   resolved by the Windows clipboard bridge.*/
SvStream& operator>>( SvStream& rIStm, FileList& rFileList )
{
    rFileList.ClearAll();
    rFileList.pStrList = new FileStringList();

    String aStr;
    sal_uInt16 c;

    while (!rIStm.IsEof())
    {
        aStr.Erase();

        // read first character of filepath; c==0 > reach end of stream
        rIStm >> c;
        if (!c)
            break;

        // read string till c==0
        while (c && !rIStm.IsEof())
        {
            aStr += (sal_Unicode)c;
            rIStm >> c;
        }

        // append the filepath
        rFileList.AppendFile(aStr);
    }
    return rIStm;
}

/******************************************************************************
|*
|*  Liste fuellen/abfragen
|*
\******************************************************************************/

void FileList::AppendFile( const String& rStr )
{
    pStrList->Insert( new String( rStr ) , pStrList->Count() );
}

String FileList::GetFile( ULONG i ) const
{
    String aStr;
    if( i < pStrList->Count() )
        aStr = *pStrList->GetObject( i );
    return aStr;
}

ULONG FileList::Count( void ) const
{
    return pStrList->Count();
}

<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <cmath>
#include <data.h>
#include <constants.h>
#include <initialconditions.h>
#include <mesh.h>
#include <fluxes.h>
#include <omp.h>

using namespace std;

extern vector<node> n;
extern vector<element> e;
extern vector<type1> tp1;
extern vector<type2> tp2;
extern vector<type3> tp3;

double extrapolate(int i, string variable)
{

  //first order extrapolation from the first interior element

  int a;

  for(int d = 0; d < 4; d++)
    {
      if(e[i].neigh[d] == 0 && e[e[i].neigh[(d + 2) % 4]].c == 0)
        a = (d + 2) % 4;
    }

  if(variable == "u")
    {
      return e[e[i].neigh[a]].u;
    }
  else if(variable == "v")
    {
      return e[e[i].neigh[a]].v;
    }
  else if(variable == "ro")
    {
      return e[e[i].neigh[a]].ro;
    }
  else if(variable == "p")
    {
      return e[e[i].neigh[a]].p;
    }
  else if(variable == "T")
    {
      return e[e[i].neigh[a]].T;
    }
  else if(variable == "et")
    {
      return e[e[i].neigh[a]].et;
    }

}

void boundarycondition(int i)
{

  for(int d = 0; d < 4; d++)
    {
      if (e[i].side[d].ca == 1)
        {
          tp1[i].Fc[d][0] = roinf / roinf * (uinf / Vinf * e[i].vn[d].x + vinf / Vinf * e[i].vn[d].y);

          tp1[i].Fc[d][1] = roinf / roinf * (uinf / Vinf) * (uinf / Vinf * e[i].vn[d].x + vinf / Vinf * e[i].vn[d].y) + e[i].vn[d].x * pinf / (roinf * pow(Vinf, 2));

          tp1[i].Fc[d][2] = roinf / roinf * (vinf / Vinf) * (uinf / Vinf * e[i].vn[d].x + vinf / Vinf * e[i].vn[d].y) + e[i].vn[d].y * pinf / (roinf * pow(Vinf, 2));

          tp1[i].Fc[d][3] = roinf / roinf * (((cv * Tinf + pow(Vinf, 2) / 2.) / pow(Vinf, 2)) + pinf / (roinf * pow(Vinf, 2))) * (uinf / Vinf * e[i].vn[d].x + vinf / Vinf * e[i].vn[d].y);

        }

      else if (e[i].side[d].ca == 2)
        {
          tp1[i].Fc[d][0] = e[i].ro * (e[i].u * e[i].vn[d].x + e[i].v * e[i].vn[d].y);

          tp1[i].Fc[d][1] = e[i].ro * e[i].u * (e[i].u * e[i].vn[d].x + e[i].v * e[i].vn[d].y) + e[i].vn[d].x * e[i].p;

          tp1[i].Fc[d][2] = e[i].ro * e[i].v * (e[i].u * e[i].vn[d].x + e[i].v * e[i].vn[d].y) + e[i].vn[d].y * e[i].p;

          tp1[i].Fc[d][3] = e[i].ro * (e[i].et + e[i].p / e[i].ro) * (e[i].u * e[i].vn[d].x + e[i].v * e[i].vn[d].y);
        }

      else if (e[i].side[d].ca == 4 || e[i].side[d].ca == 5)
        {
          tp1[i].Fc[d][0] = 0;

          tp1[i].Fc[d][1] = e[i].vn[d].x * e[i].p;

          tp1[i].Fc[d][2] = e[i].vn[d].y * e[i].p;

          tp1[i].Fc[d][3] = 0;

        }

    }

  //for viscous

  if(schemetype == 4 || schemetype == 5 || schemetype == 6)
    {
      double gradTx, gradTy, gradux, graduy, gradvx, gradvy, qx, qy;

      double taoxx, taoxy, taoyy, mu;

      double rx,ry, rm;

      for(int d = 0; d < 4; d++)
        {
          rx = (n[e[i].node[d]].x + n[e[i].node[(d + 1) % 4]].x) / 2. - e[i].x;

          ry = (n[e[i].node[d]].y + n[e[i].node[(d + 1) % 4]].y) / 2. - e[i].y;

          rm = sqrt(pow(rx, 2) + pow(ry, 2));

          if (e[i].side[d].ca == 1)
            {
              gradux = (uinf / Vinf - e[i].u) / rm * rx / rm;

              graduy = (uinf / Vinf - e[i].u) / rm * ry / rm;

              gradvx = (vinf / Vinf - e[i].v) / rm * rx / rm;

              gradvy = (vinf / Vinf - e[i].v) / rm * ry / rm;

              gradTx = (Tinf / Tinf - e[i].T) / rm * rx / rm;

              gradTy = (Tinf / Tinf - e[i].T) / rm * ry / rm;

              taoxx = (muinf / muinf) / Reinf * (4. / 3. * gradux - 2. / 3. * gradvy);

              taoxy = (muinf / muinf) / Reinf * (graduy + gradvx);

              taoyy = (muinf / muinf) / Reinf * (4. / 3. * gradvy - 2. / 3. * gradux);

              qx = (muinf / muinf) / (Reinf * Pr * (gama - 1.) * pow(Machinf,2)) * gradTx;

              qy = (muinf / muinf) / (Reinf * Pr * (gama - 1.) * pow(Machinf,2)) * gradTy;

              tp2[i].Fv[d][0] = 0;

              tp2[i].Fv[d][1] = e[i].vn[d].x * taoxx + e[i].vn[d].y * taoxy;

              tp2[i].Fv[d][2] = e[i].vn[d].x * taoxy + e[i].vn[d].y * taoyy;

              tp2[i].Fv[d][3] = e[i].vn[d].x * (uinf / Vinf * taoxx + vinf / Vinf * taoxy + qx) + e[i].vn[d].y * (uinf / Vinf * taoxy + vinf / Vinf * taoyy + qy);
            }

          else if (e[i].side[d].ca == 2)
            {
              gradux = (e[i].u - e[i].u) / rm * rx / rm;

              graduy = (e[i].u - e[i].u) / rm * ry / rm;

              gradvx = (e[i].v - e[i].v) / rm * rx / rm;

              gradvy = (e[i].v - e[i].v) / rm * ry / rm;

              gradTx = (e[i].T - e[i].T) / rm * rx / rm;

              gradTy = (e[i].T - e[i].T) / rm * ry / rm;

              mu = (1.461e-6 * pow(e[i].T * Tinf, (3. / 2.)) / (e[i].T * Tinf + 110.3)) / muinf;

              taoxx = mu / Reinf * (4. / 3. * gradux - 2. / 3. * gradvy);

              taoxy = mu / Reinf * (graduy + gradvx);

              taoyy = mu / Reinf * (4. / 3. * gradvy - 2. / 3. * gradux);

              qx = mu / (Reinf * Pr * (gama - 1.) * pow(Machinf,2)) * gradTx;

              qy = mu / (Reinf * Pr * (gama - 1.) * pow(Machinf,2)) * gradTy;

              tp2[i].Fv[d][0] = 0;

              tp2[i].Fv[d][1] = e[i].vn[d].x * taoxx + e[i].vn[d].y * taoxy;

              tp2[i].Fv[d][2] = e[i].vn[d].x * taoxy + e[i].vn[d].y * taoyy;

              tp2[i].Fv[d][3] = e[i].vn[d].x * (e[i].u * taoxx +  e[i].v * taoxy + qx) + e[i].vn[d].y * (e[i].u * taoxy + e[i].v * taoyy + qy);
            }

          else if (e[i].side[d].ca == 5)
            {
              gradux = (0. - e[i].u) / rm * rx / rm;

              graduy = (0. - e[i].u) / rm * ry / rm;

              gradvx = (0. - e[i].v) / rm * rx / rm;

              gradvy = (0. - e[i].v) / rm * ry / rm;

              gradTx = (e[i].T - e[i].T) / rm * rx / rm;

              gradTy = (e[i].T - e[i].T) / rm * ry / rm;

              taoxx = e[i].mu / Reinf * (4. / 3. * gradux - 2. / 3. * gradvy);

              taoxy = e[i].mu / Reinf * (graduy + gradvx);

              taoyy = e[i].mu / Reinf * (4. / 3. * gradvy - 2. / 3. * gradux);

              qx = e[i].mu / (Reinf * Pr * (gama - 1.) * pow(Machinf,2)) * gradTx;

              qy = e[i].mu / (Reinf * Pr * (gama - 1.) * pow(Machinf,2)) * gradTy;

              tp2[i].Fv[d][0] = 0;

              tp2[i].Fv[d][1] = e[i].vn[d].x * taoxx + e[i].vn[d].y * taoxy;

              tp2[i].Fv[d][2] = e[i].vn[d].x * taoxy + e[i].vn[d].y * taoyy;

              tp2[i].Fv[d][3] = e[i].vn[d].x * qx + e[i].vn[d].y * qy;

            }

        }
    }

}

void boundarycondition3(int i)
{

  for(int d = 0; d < 4; d++)
    {
      if (e[i].side[d].ca == 1)
        {
          tp1[i].Fc[d][0] = roinf / roinf * (uinf / Vinf * e[i].vn[d].x + vinf / Vinf * e[i].vn[d].y);

          tp1[i].Fc[d][1] = roinf / roinf * (uinf / Vinf) * (uinf / Vinf * e[i].vn[d].x + vinf / Vinf * e[i].vn[d].y) + e[i].vn[d].x * pinf / (roinf * pow(Vinf, 2));

          tp1[i].Fc[d][2] = roinf / roinf * (vinf / Vinf) * (uinf / Vinf * e[i].vn[d].x + vinf / Vinf * e[i].vn[d].y) + e[i].vn[d].y * pinf / (roinf * pow(Vinf, 2));

          tp1[i].Fc[d][3] = roinf / roinf * (((cv * Tinf + pow(Vinf, 2) / 2.) / pow(Vinf, 2)) + pinf / (roinf * pow(Vinf, 2))) * (uinf / Vinf * e[i].vn[d].x + vinf / Vinf * e[i].vn[d].y);

        }

      else if (e[i].side[d].ca == 2)
        {
          tp1[i].Fc[d][0] = e[i].ronew * (e[i].unew * e[i].vn[d].x + e[i].vnew * e[i].vn[d].y);

          tp1[i].Fc[d][1] = e[i].ronew * e[i].unew * (e[i].unew * e[i].vn[d].x + e[i].vnew * e[i].vn[d].y) + e[i].vn[d].x * e[i].pnew;

          tp1[i].Fc[d][2] = e[i].ronew * e[i].vnew * (e[i].unew * e[i].vn[d].x + e[i].vnew * e[i].vn[d].y) + e[i].vn[d].y * e[i].pnew;

          tp1[i].Fc[d][3] = e[i].ronew * (e[i].etnew + e[i].pnew / e[i].ronew) * (e[i].unew * e[i].vn[d].x + e[i].vnew * e[i].vn[d].y);
        }

      else if (e[i].side[d].ca == 4 || e[i].side[d].ca == 5)
        {
          tp1[i].Fc[d][0] = 0;

          tp1[i].Fc[d][1] = e[i].vn[d].x * e[i].pnew;

          tp1[i].Fc[d][2] = e[i].vn[d].y * e[i].pnew;

          tp1[i].Fc[d][3] = 0;

        }

    }

  //for viscous

  if(schemetype == 4 || schemetype == 5 || schemetype == 6)
    {
      double gradTx, gradTy, gradux, graduy, gradvx, gradvy, qx, qy;

      double taoxx, taoxy, taoyy, mu;

      double rx,ry, rm;

      for(int d = 0; d < 4; d++)
        {
          rx = (n[e[i].node[d]].x + n[e[i].node[(d + 1) % 4]].x) / 2. - e[i].x;

          ry = (n[e[i].node[d]].y + n[e[i].node[(d + 1) % 4]].y) / 2. - e[i].y;

          rm = sqrt(pow(rx, 2) + pow(ry, 2));

          if (e[i].side[d].ca == 1)
            {
              gradux = (uinf / Vinf - e[i].unew) / rm * rx / rm;

              graduy = (uinf / Vinf - e[i].unew) / rm * ry / rm;

              gradvx = (vinf / Vinf - e[i].vnew) / rm * rx / rm;

              gradvy = (vinf / Vinf - e[i].vnew) / rm * ry / rm;

              gradTx = (Tinf / Tinf - e[i].Tnew) / rm * rx / rm;

              gradTy = (Tinf / Tinf - e[i].Tnew) / rm * ry / rm;

              taoxx = (muinf / muinf) / Reinf * (4. / 3. * gradux - 2. / 3. * gradvy);

              taoxy = (muinf / muinf) / Reinf * (graduy + gradvx);

              taoyy = (muinf / muinf) / Reinf * (4. / 3. * gradvy - 2. / 3. * gradux);

              qx = (muinf / muinf) / (Reinf * Pr * (gama - 1.) * pow(Machinf,2)) * gradTx;

              qy = (muinf / muinf) / (Reinf * Pr * (gama - 1.) * pow(Machinf,2)) * gradTy;

              tp2[i].Fv[d][0] = 0;

              tp2[i].Fv[d][1] = e[i].vn[d].x * taoxx + e[i].vn[d].y * taoxy;

              tp2[i].Fv[d][2] = e[i].vn[d].x * taoxy + e[i].vn[d].y * taoyy;

              tp2[i].Fv[d][3] = e[i].vn[d].x * (uinf / Vinf * taoxx + vinf / Vinf * taoxy + qx) + e[i].vn[d].y * (uinf / Vinf * taoxy + vinf / Vinf * taoyy + qy);
            }

          else if (e[i].side[d].ca == 2)
            {
              gradux = (e[i].u - e[i].u) / rm * rx / rm;

              graduy = (e[i].u - e[i].u) / rm * ry / rm;

              gradvx = (e[i].v - e[i].v) / rm * rx / rm;

              gradvy = (e[i].v - e[i].v) / rm * ry / rm;

              gradTx = (e[i].T - e[i].T) / rm * rx / rm;

              gradTy = (e[i].T - e[i].T) / rm * ry / rm;

              mu = (1.461e-6 * pow(e[i].T * Tinf, (3. / 2.)) / (e[i].T * Tinf + 110.3)) / muinf;

              taoxx = mu / Reinf * (4. / 3. * gradux - 2. / 3. * gradvy);

              taoxy = mu / Reinf * (graduy + gradvx);

              taoyy = mu / Reinf * (4. / 3. * gradvy - 2. / 3. * gradux);

              qx = mu / (Reinf * Pr * (gama - 1.) * pow(Machinf,2)) * gradTx;

              qy = mu / (Reinf * Pr * (gama - 1.) * pow(Machinf,2)) * gradTy;

              tp2[i].Fv[d][0] = 0;

              tp2[i].Fv[d][1] = e[i].vn[d].x * taoxx + e[i].vn[d].y * taoxy;

              tp2[i].Fv[d][2] = e[i].vn[d].x * taoxy + e[i].vn[d].y * taoyy;

              tp2[i].Fv[d][3] = e[i].vn[d].x * (e[i].u * taoxx +  e[i].v * taoxy + qx) + e[i].vn[d].y * (e[i].u * taoxy + e[i].v * taoyy + qy);
            }

          else if (e[i].side[d].ca == 5)
            {
              gradux = (0. - e[i].unew) / rm * rx / rm;

              graduy = (0. - e[i].unew) / rm * ry / rm;

              gradvx = (0. - e[i].vnew) / rm * rx / rm;

              gradvy = (0. - e[i].vnew) / rm * ry / rm;

              gradTx = (e[i].Tnew - e[i].Tnew) / rm * rx / rm;

              gradTy = (e[i].Tnew - e[i].Tnew) / rm * ry / rm;

              taoxx = e[i].munew / Reinf * (4. / 3. * gradux - 2. / 3. * gradvy);

              taoxy = e[i].munew / Reinf * (graduy + gradvx);

              taoyy = e[i].munew / Reinf * (4. / 3. * gradvy - 2. / 3. * gradux);

              qx = e[i].munew / (Reinf * Pr * (gama - 1.) * pow(Machinf,2)) * gradTx;

              qy = e[i].munew / (Reinf * Pr * (gama - 1.) * pow(Machinf,2)) * gradTy;

              tp2[i].Fv[d][0] = 0;

              tp2[i].Fv[d][1] = e[i].vn[d].x * taoxx + e[i].vn[d].y * taoxy;

              tp2[i].Fv[d][2] = e[i].vn[d].x * taoxy + e[i].vn[d].y * taoyy;

              tp2[i].Fv[d][3] = e[i].vn[d].x * qx + e[i].vn[d].y * qy;

            }

        }
    }

}
<commit_msg>Delete boundaryconditions.cpp<commit_after><|endoftext|>


<commit_before>/***********************************************************************
KCalendar support for OpenSync kdepim-sync plugin
Copyright (C) 2004 Conectiva S. A.

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation;

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
SOFTWARE IS DISCLAIMED.
*************************************************************************/
/**
 * @autor Eduardo Pereira Habkost <ehabkost@conectiva.com.br>
 */

#include <libkcal/calendarresources.h>
#include <libkcal/vcalformat.h>
#include <libkcal/calendarlocal.h>

#include "osyncbase.h"
#include "kcal.h"

char* writeMemVObject(char *s, int *len, VObject *o);

KCalDataSource::KCalDataSource(OSyncMember *member, OSyncHashTable *hashtable)
    : hashtable(hashtable), member(member)
{
}

bool KCalDataSource::connect(OSyncContext *ctx)
{
    calendar = new KCal::CalendarResources();
    if (!calendar) {
        osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, "Can't open KDE calendar");
        return false;
    }
    calendar->readConfig();
    calendar->load();
    osync_debug("kcal", 3, "Calendar: %d events", calendar->events().size());
    /*FIXME: load and lock here? */
    return true;
}

bool KCalDataSource::disconnect(OSyncContext *)
{
    calendar->save();
    delete calendar;
    calendar = NULL;
    return true;
}

static QString calc_hash(const KCal::Event *e)
{
    QDateTime d = e->lastModified();
    if (!d.isValid())
        d = QDateTime::currentDateTime();
    /*FIXME: not i18ned string */
    return d.toString();
}

bool KCalDataSource::get_changeinfo(OSyncContext *ctx)
{
    KCal::Event::List events = calendar->events();
    osync_debug("kcal", 3, "Number of events: %d", events.size());

    for (KCal::Event::List::ConstIterator i = events.begin(); i != events.end(); i++) {
        osync_debug("kcal", 3, "One calendar event");
        KCal::Event *e = *i;
        QString hash = calc_hash(e);

        QString uid = e->uid();

        KCal::VCalFormat format;
        KCal::CalendarLocal cal(calendar->timeZoneId());
        osync_debug("kcal", 3, "timezoneid: %s\n", cal.timeZoneId().latin1());
        cal.addEvent(e->clone());
        QString datastr(format.toString(&cal));
        const char *data = datastr.latin1();

        osync_debug("kcal", 3, "UID: %s\n", uid.latin1());
        OSyncChange *chg = osync_change_new();
        osync_change_set_uid(chg, uid.latin1());
        osync_change_set_member(chg, member);

        // object type and format
        osync_change_set_objtype_string(chg, "calendar");
        osync_change_set_objformat_string(chg, "vcalendar");
        //FIXME: deallocate data somewhere
        osync_change_set_data(chg, strdup(data), strlen(data), 1);

        // Use the hash table to check if the object
        // needs to be reported
        osync_change_set_hash(chg, hash.data());
        if (osync_hashtable_detect_change(hashtable, chg)) {
            osync_context_report_change(ctx, chg);
            osync_hashtable_update_hash(hashtable, chg);
        }
    }
    osync_hashtable_report_deleted(hashtable, ctx, "calendar");
    return true;
}

void KCalDataSource::get_data(OSyncContext *ctx, OSyncChange *)
{
    osync_context_report_error(ctx, OSYNC_ERROR_NOT_SUPPORTED, "Not implemented yet");
}

bool KCalDataSource::access(OSyncContext *ctx, OSyncChange *)
{
    osync_context_report_error(ctx, OSYNC_ERROR_NOT_SUPPORTED, "Not implemented yet");
    return false;
}
<commit_msg>Ugly hack to a VCalFormat bug<commit_after>/***********************************************************************
KCalendar support for OpenSync kdepim-sync plugin
Copyright (C) 2004 Conectiva S. A.

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation;

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
SOFTWARE IS DISCLAIMED.
*************************************************************************/
/**
 * @autor Eduardo Pereira Habkost <ehabkost@conectiva.com.br>
 */

#include <libkcal/calendarresources.h>
#include <libkcal/vcalformat.h>
#include <libkcal/calendarlocal.h>

#include "osyncbase.h"
#include "kcal.h"

char* writeMemVObject(char *s, int *len, VObject *o);

KCalDataSource::KCalDataSource(OSyncMember *member, OSyncHashTable *hashtable)
    : hashtable(hashtable), member(member)
{
}

bool KCalDataSource::connect(OSyncContext *ctx)
{
    calendar = new KCal::CalendarResources();
    if (!calendar) {
        osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, "Can't open KDE calendar");
        return false;
    }
    calendar->readConfig();
    calendar->load();
    osync_debug("kcal", 3, "Calendar: %d events", calendar->events().size());
    /*FIXME: load and lock here? */
    return true;
}

bool KCalDataSource::disconnect(OSyncContext *)
{
    calendar->save();
    delete calendar;
    calendar = NULL;
    return true;
}

static QString calc_hash(const KCal::Event *e)
{
    QDateTime d = e->lastModified();
    if (!d.isValid())
        d = QDateTime::currentDateTime();
    /*FIXME: not i18ned string */
    return d.toString();
}

bool KCalDataSource::get_changeinfo(OSyncContext *ctx)
{
    KCal::Event::List events = calendar->events();
    osync_debug("kcal", 3, "Number of events: %d", events.size());

    for (KCal::Event::List::ConstIterator i = events.begin(); i != events.end(); i++) {
        osync_debug("kcal", 3, "One calendar event");
        KCal::Event *e = *i;
        QString hash = calc_hash(e);

        QString uid = e->uid();

        KCal::VCalFormat format;
        KCal::CalendarLocal cal(calendar->timeZoneId());
        osync_debug("kcal", 3, "timezoneid: %s\n", cal.timeZoneId().latin1());
        cal.addEvent(e->clone());
        /* Ugly workaround to a VCalFormat bug, format.toString()
         * doesn't work, but if save() or load() is called before
         * toString(), the segmentation fault will not happen (as
         * the mCalendar private field will be set)
         */
        format.save(&cal, "");
        QString datastr(format.toString(&cal));
        const char *data = datastr.latin1();

        osync_debug("kcal", 3, "UID: %s\n", uid.latin1());
        OSyncChange *chg = osync_change_new();
        osync_change_set_uid(chg, uid.latin1());
        osync_change_set_member(chg, member);

        // object type and format
        osync_change_set_objtype_string(chg, "calendar");
        osync_change_set_objformat_string(chg, "vcalendar");
        //FIXME: deallocate data somewhere
        osync_change_set_data(chg, strdup(data), strlen(data), 1);

        // Use the hash table to check if the object
        // needs to be reported
        osync_change_set_hash(chg, hash.data());
        if (osync_hashtable_detect_change(hashtable, chg)) {
            osync_context_report_change(ctx, chg);
            osync_hashtable_update_hash(hashtable, chg);
        }
    }
    osync_hashtable_report_deleted(hashtable, ctx, "calendar");
    return true;
}

void KCalDataSource::get_data(OSyncContext *ctx, OSyncChange *)
{
    osync_context_report_error(ctx, OSYNC_ERROR_NOT_SUPPORTED, "Not implemented yet");
}

bool KCalDataSource::access(OSyncContext *ctx, OSyncChange *)
{
    osync_context_report_error(ctx, OSYNC_ERROR_NOT_SUPPORTED, "Not implemented yet");
    return false;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: stgavl.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 16:09:08 $
 *
 *  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_sot.hxx"

#include "stgavl.hxx"

StgAvlNode::StgAvlNode()
{
    pLeft = pRight = NULL;
    nBalance = nId = 0;
}

StgAvlNode::~StgAvlNode()
{
    delete pLeft;
    delete pRight;
}

StgAvlNode* StgAvlNode::Find( StgAvlNode* pFind )
{
    StgAvlNode* p = this;
    while( p )
    {
        short nRes = p->Compare( pFind );
        if( !nRes )
            return p;
        else p = ( nRes < 0 ) ? p->pLeft : p->pRight;
    }
    return NULL;
}

// find point to add node to AVL tree and returns
// +/0/- for >/=/< previous

short StgAvlNode::Locate
    ( StgAvlNode* pFind,
      StgAvlNode** pPivot, StgAvlNode **pParent, StgAvlNode** pPrev )
{
    short nRes = 0;
    StgAvlNode* pCur = this;
    *pParent = *pPrev = NULL;
    *pPivot = this;

    // search tree for insertion point

    while( pCur != NULL )
    {
        // check for pPivot
        if( pCur->nBalance != 0 )
            *pPivot = pCur, *pParent = *pPrev;
        // save pPrev location and see what direction to go
        *pPrev = pCur;
        nRes = pCur->Compare( pFind );
        if( nRes == 0 )
            break;
        else pCur = ( nRes < 0 ) ? pCur->pLeft : pCur->pRight;
    }
    return( nRes );
}

// adjust balance factors in AVL tree from pivot down.
// Returns delta balance.

short StgAvlNode::Adjust( StgAvlNode** pHeavy, StgAvlNode* pNew )
{
    StgAvlNode* pCur = this;
    short nDelta;
    // no traversing
    if( pCur == pNew )
        return nBalance;
    short nRes = Compare( pNew );
    if( nRes > 0 )
    {
        *pHeavy = pCur = pRight;
        nDelta = -1;
    }
    else
    {
        *pHeavy = pCur = pLeft;
        nDelta = 1;
    }
    nBalance = 0;
    while( pCur != pNew )
    {
        nRes = pCur->Compare( pNew );
        if( nRes > 0 )
        {
            // height of right increases by 1
            pCur->nBalance = -1;
            pCur = pCur->pRight;
        }
        else
        {
            // height of left increases by 1
            pCur->nBalance = 1;
            pCur = pCur->pLeft;
        }
    }
    nBalance = nBalance + nDelta;
    return nDelta;
}

// perform LL rotation and return new root

StgAvlNode* StgAvlNode::RotLL()
{
    StgAvlNode *pHeavy = pLeft;
    pLeft = pHeavy->pRight;
    pHeavy->pRight = this;
    pHeavy->nBalance = nBalance = 0;
    return pHeavy;
}

// perform LR rotation and return new root

StgAvlNode* StgAvlNode::RotLR()
{

    StgAvlNode* pHeavy = pLeft;
    StgAvlNode* pNewRoot = pHeavy->pRight;

    pHeavy->pRight = pNewRoot->pLeft;
    pLeft = pNewRoot->pRight;
    pNewRoot->pLeft = pHeavy;
    pNewRoot->pRight = this;

    switch( pNewRoot->nBalance )
    {
        case 1:     // LR( b )
            nBalance = -1;
            pHeavy->nBalance = 0;
            break;
        case -1:    // LR( c )
            pHeavy->nBalance = 1;
            nBalance = 0;
            break;
        case 0:     // LR( a )
            nBalance = 0;
            pHeavy->nBalance = 0;
            break;
    }
    pNewRoot->nBalance = 0;
    return pNewRoot;
}

// perform RR rotation and return new root

StgAvlNode* StgAvlNode::RotRR()
{
    StgAvlNode* pHeavy = pRight;
    pRight = pHeavy->pLeft;
    pHeavy->pLeft = this;
    nBalance = pHeavy->nBalance = 0;
    return pHeavy;
}

// perform the RL rotation and return the new root

StgAvlNode* StgAvlNode::RotRL()
{
    StgAvlNode* pHeavy = pRight;
    StgAvlNode* pNewRoot = pHeavy->pLeft;
    pHeavy->pLeft = pNewRoot->pRight;
    pRight = pNewRoot->pLeft;
    pNewRoot->pRight = pHeavy;
    pNewRoot->pLeft = this;
    switch( pNewRoot->nBalance )
    {
        case -1:    // RL( b )
            nBalance = 1;
            pHeavy->nBalance = 0;
            break;
        case 1:     // RL( c )
            pHeavy->nBalance = -1;
            nBalance = 0;
            break;
        case 0:     // RL( a )
            nBalance = 0;
            pHeavy->nBalance = 0;
            break;
    }
    pNewRoot->nBalance = 0;
    return pNewRoot;
}

// Remove a tree element. Return the removed element or NULL.

StgAvlNode* StgAvlNode::Rem( StgAvlNode** p, StgAvlNode* pDel, BOOL bPtrs )
{
    if( *p )
    {
        StgAvlNode* pCur = *p;
        short nRes = bPtrs ? short( pCur == pDel ) : short(pCur->Compare( pDel ));
        if( !nRes )
        {
            // Element found: remove
            if( !pCur->pRight )
            {
                *p = pCur->pLeft; pCur->pLeft = NULL;
            }
            else if( !pCur->pLeft )
            {
                *p = pCur->pRight; pCur->pRight = NULL;
            }
            else
            {
                // The damn element has two leaves. Get the
                // rightmost element of the left subtree (which
                // is lexically before this element) and replace
                // this element with the element found.
                StgAvlNode* last = pCur;
                StgAvlNode* l;
                for( l = pCur->pLeft;
                     l->pRight; last = l, l = l->pRight ) {}
                // remove the element from chain
                if( l == last->pRight )
                    last->pRight = l->pLeft;
                else
                    last->pLeft = l->pLeft;
                // perform the replacement
                l->pLeft = pCur->pLeft;
                l->pRight = pCur->pRight;
                *p = l;
                // delete the element
                pCur->pLeft = pCur->pRight = NULL;
            }
            return pCur;
        }
        else
        {
            if( nRes < 0 )
                return Rem( &pCur->pLeft, pDel, bPtrs );
            else
                return Rem( &pCur->pRight, pDel, bPtrs );
        }
    }
    return NULL;
}

// Enumerate the tree for later iteration

void StgAvlNode::StgEnum( short& n )
{
    if( this )
    {
        if( pLeft )
            pLeft->StgEnum( n );
        nId = n++;
        if( pRight )
            pRight->StgEnum( n );
    }
}

// Add node to AVL tree.
// Return FALSE if the element already exists.

BOOL StgAvlNode::Insert( StgAvlNode** pRoot, StgAvlNode* pIns )
{
    StgAvlNode* pPivot, *pHeavy, *pNewRoot, *pParent, *pPrev;
    // special case - empty tree
    if( *pRoot == NULL )
    {
        *pRoot = pIns;
        return TRUE;
    }
    // find insertion point and return if already present
    short nRes = (*pRoot)->Locate( pIns, &pPivot, &pParent, &pPrev );
    if( !nRes )
        return FALSE;
    // add new node
    if( nRes < 0 )
        pPrev->pLeft = pIns;
    else
        pPrev->pRight = pIns;
    // rebalance tree
    short nDelta = pPivot->Adjust( &pHeavy, pIns );
    if( pPivot->nBalance >= 2 || pPivot->nBalance <= -2 )
    {
        pHeavy = ( nDelta < 0 ) ? pPivot->pRight : pPivot->pLeft;
        // left imbalance
        if( nDelta > 0 )
            if( pHeavy->nBalance == 1 )
                pNewRoot = pPivot->RotLL();
            else
                pNewRoot = pPivot->RotLR();
        // right imbalance
        else if( pHeavy->nBalance == -1 )
            pNewRoot = pPivot->RotRR();
        else
            pNewRoot = pPivot->RotRL();
        // relink balanced subtree
        if( pParent == NULL )
            *pRoot = pNewRoot;
        else if( pPivot == pParent->pLeft )
            pParent->pLeft = pNewRoot;
        else if( pPivot == pParent->pRight )
            pParent->pRight = pNewRoot;
    }
    return TRUE;
}

// Remove node from tree. Returns TRUE is found and removed.
// Actually delete if bDel

BOOL StgAvlNode::Remove( StgAvlNode** pRoot, StgAvlNode* pDel, BOOL bDel )
{
    // special case - empty tree
    if( *pRoot == NULL )
        return FALSE;
    // delete the element
    pDel = Rem( pRoot, pDel, FALSE );
    if( pDel )
    {
        if( bDel )
            delete pDel;
        // Rebalance the tree the hard way
        // OS 22.09.95: Auf MD's Wunsch auskommentiert wg. Absturz
/*      StgAvlNode* pNew = NULL;
        while( *pRoot )
        {
            StgAvlNode* p = Rem( pRoot, *pRoot, FALSE );
            Insert( &pNew, p );
        }
        *pRoot = pNew;*/
        return TRUE;
    }
    else
        return FALSE;
}

// Move node to a different tree. Returns TRUE is found and moved. This routine
// may be called when the key has changed.

BOOL StgAvlNode::Move
    ( StgAvlNode** pRoot1, StgAvlNode** pRoot2, StgAvlNode* pMove )
{
    // special case - empty tree
    if( *pRoot1 == NULL )
        return FALSE;
    pMove = Rem( pRoot1, pMove, FALSE );
    if( pMove )
        return Insert( pRoot2, pMove );
    else
        return FALSE;
}

////////////////////////// class AvlIterator /////////////////////////

// The iterator walks through a tree one entry by one.

StgAvlIterator::StgAvlIterator( StgAvlNode* p )
{
    pRoot = p;
    nCount = 0;
    if( p )
        p->StgEnum( nCount );
}

StgAvlNode* StgAvlIterator::Find( short n )
{
    StgAvlNode* p = pRoot;
    while( p )
    {
        if( n == p->nId )
            break;
        else p = ( n < p->nId ) ? p->pLeft : p->pRight;
    }
    return p;
}

StgAvlNode* StgAvlIterator::First()
{
    nCur = -1;
    return Next();
}

StgAvlNode* StgAvlIterator::Last()
{
    nCur = nCount;
    return Prev();
}

StgAvlNode* StgAvlIterator::Next()
{
    return Find( ++nCur );
}

StgAvlNode* StgAvlIterator::Prev()
{
    return Find( --nCur );
}

<commit_msg>INTEGRATION: CWS changefileheader (1.5.66); FILE MERGED 2008/03/31 12:49:58 rt 1.5.66.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: stgavl.cxx,v $
 * $Revision: 1.6 $
 *
 * 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_sot.hxx"

#include "stgavl.hxx"

StgAvlNode::StgAvlNode()
{
    pLeft = pRight = NULL;
    nBalance = nId = 0;
}

StgAvlNode::~StgAvlNode()
{
    delete pLeft;
    delete pRight;
}

StgAvlNode* StgAvlNode::Find( StgAvlNode* pFind )
{
    StgAvlNode* p = this;
    while( p )
    {
        short nRes = p->Compare( pFind );
        if( !nRes )
            return p;
        else p = ( nRes < 0 ) ? p->pLeft : p->pRight;
    }
    return NULL;
}

// find point to add node to AVL tree and returns
// +/0/- for >/=/< previous

short StgAvlNode::Locate
    ( StgAvlNode* pFind,
      StgAvlNode** pPivot, StgAvlNode **pParent, StgAvlNode** pPrev )
{
    short nRes = 0;
    StgAvlNode* pCur = this;
    *pParent = *pPrev = NULL;
    *pPivot = this;

    // search tree for insertion point

    while( pCur != NULL )
    {
        // check for pPivot
        if( pCur->nBalance != 0 )
            *pPivot = pCur, *pParent = *pPrev;
        // save pPrev location and see what direction to go
        *pPrev = pCur;
        nRes = pCur->Compare( pFind );
        if( nRes == 0 )
            break;
        else pCur = ( nRes < 0 ) ? pCur->pLeft : pCur->pRight;
    }
    return( nRes );
}

// adjust balance factors in AVL tree from pivot down.
// Returns delta balance.

short StgAvlNode::Adjust( StgAvlNode** pHeavy, StgAvlNode* pNew )
{
    StgAvlNode* pCur = this;
    short nDelta;
    // no traversing
    if( pCur == pNew )
        return nBalance;
    short nRes = Compare( pNew );
    if( nRes > 0 )
    {
        *pHeavy = pCur = pRight;
        nDelta = -1;
    }
    else
    {
        *pHeavy = pCur = pLeft;
        nDelta = 1;
    }
    nBalance = 0;
    while( pCur != pNew )
    {
        nRes = pCur->Compare( pNew );
        if( nRes > 0 )
        {
            // height of right increases by 1
            pCur->nBalance = -1;
            pCur = pCur->pRight;
        }
        else
        {
            // height of left increases by 1
            pCur->nBalance = 1;
            pCur = pCur->pLeft;
        }
    }
    nBalance = nBalance + nDelta;
    return nDelta;
}

// perform LL rotation and return new root

StgAvlNode* StgAvlNode::RotLL()
{
    StgAvlNode *pHeavy = pLeft;
    pLeft = pHeavy->pRight;
    pHeavy->pRight = this;
    pHeavy->nBalance = nBalance = 0;
    return pHeavy;
}

// perform LR rotation and return new root

StgAvlNode* StgAvlNode::RotLR()
{

    StgAvlNode* pHeavy = pLeft;
    StgAvlNode* pNewRoot = pHeavy->pRight;

    pHeavy->pRight = pNewRoot->pLeft;
    pLeft = pNewRoot->pRight;
    pNewRoot->pLeft = pHeavy;
    pNewRoot->pRight = this;

    switch( pNewRoot->nBalance )
    {
        case 1:     // LR( b )
            nBalance = -1;
            pHeavy->nBalance = 0;
            break;
        case -1:    // LR( c )
            pHeavy->nBalance = 1;
            nBalance = 0;
            break;
        case 0:     // LR( a )
            nBalance = 0;
            pHeavy->nBalance = 0;
            break;
    }
    pNewRoot->nBalance = 0;
    return pNewRoot;
}

// perform RR rotation and return new root

StgAvlNode* StgAvlNode::RotRR()
{
    StgAvlNode* pHeavy = pRight;
    pRight = pHeavy->pLeft;
    pHeavy->pLeft = this;
    nBalance = pHeavy->nBalance = 0;
    return pHeavy;
}

// perform the RL rotation and return the new root

StgAvlNode* StgAvlNode::RotRL()
{
    StgAvlNode* pHeavy = pRight;
    StgAvlNode* pNewRoot = pHeavy->pLeft;
    pHeavy->pLeft = pNewRoot->pRight;
    pRight = pNewRoot->pLeft;
    pNewRoot->pRight = pHeavy;
    pNewRoot->pLeft = this;
    switch( pNewRoot->nBalance )
    {
        case -1:    // RL( b )
            nBalance = 1;
            pHeavy->nBalance = 0;
            break;
        case 1:     // RL( c )
            pHeavy->nBalance = -1;
            nBalance = 0;
            break;
        case 0:     // RL( a )
            nBalance = 0;
            pHeavy->nBalance = 0;
            break;
    }
    pNewRoot->nBalance = 0;
    return pNewRoot;
}

// Remove a tree element. Return the removed element or NULL.

StgAvlNode* StgAvlNode::Rem( StgAvlNode** p, StgAvlNode* pDel, BOOL bPtrs )
{
    if( *p )
    {
        StgAvlNode* pCur = *p;
        short nRes = bPtrs ? short( pCur == pDel ) : short(pCur->Compare( pDel ));
        if( !nRes )
        {
            // Element found: remove
            if( !pCur->pRight )
            {
                *p = pCur->pLeft; pCur->pLeft = NULL;
            }
            else if( !pCur->pLeft )
            {
                *p = pCur->pRight; pCur->pRight = NULL;
            }
            else
            {
                // The damn element has two leaves. Get the
                // rightmost element of the left subtree (which
                // is lexically before this element) and replace
                // this element with the element found.
                StgAvlNode* last = pCur;
                StgAvlNode* l;
                for( l = pCur->pLeft;
                     l->pRight; last = l, l = l->pRight ) {}
                // remove the element from chain
                if( l == last->pRight )
                    last->pRight = l->pLeft;
                else
                    last->pLeft = l->pLeft;
                // perform the replacement
                l->pLeft = pCur->pLeft;
                l->pRight = pCur->pRight;
                *p = l;
                // delete the element
                pCur->pLeft = pCur->pRight = NULL;
            }
            return pCur;
        }
        else
        {
            if( nRes < 0 )
                return Rem( &pCur->pLeft, pDel, bPtrs );
            else
                return Rem( &pCur->pRight, pDel, bPtrs );
        }
    }
    return NULL;
}

// Enumerate the tree for later iteration

void StgAvlNode::StgEnum( short& n )
{
    if( this )
    {
        if( pLeft )
            pLeft->StgEnum( n );
        nId = n++;
        if( pRight )
            pRight->StgEnum( n );
    }
}

// Add node to AVL tree.
// Return FALSE if the element already exists.

BOOL StgAvlNode::Insert( StgAvlNode** pRoot, StgAvlNode* pIns )
{
    StgAvlNode* pPivot, *pHeavy, *pNewRoot, *pParent, *pPrev;
    // special case - empty tree
    if( *pRoot == NULL )
    {
        *pRoot = pIns;
        return TRUE;
    }
    // find insertion point and return if already present
    short nRes = (*pRoot)->Locate( pIns, &pPivot, &pParent, &pPrev );
    if( !nRes )
        return FALSE;
    // add new node
    if( nRes < 0 )
        pPrev->pLeft = pIns;
    else
        pPrev->pRight = pIns;
    // rebalance tree
    short nDelta = pPivot->Adjust( &pHeavy, pIns );
    if( pPivot->nBalance >= 2 || pPivot->nBalance <= -2 )
    {
        pHeavy = ( nDelta < 0 ) ? pPivot->pRight : pPivot->pLeft;
        // left imbalance
        if( nDelta > 0 )
            if( pHeavy->nBalance == 1 )
                pNewRoot = pPivot->RotLL();
            else
                pNewRoot = pPivot->RotLR();
        // right imbalance
        else if( pHeavy->nBalance == -1 )
            pNewRoot = pPivot->RotRR();
        else
            pNewRoot = pPivot->RotRL();
        // relink balanced subtree
        if( pParent == NULL )
            *pRoot = pNewRoot;
        else if( pPivot == pParent->pLeft )
            pParent->pLeft = pNewRoot;
        else if( pPivot == pParent->pRight )
            pParent->pRight = pNewRoot;
    }
    return TRUE;
}

// Remove node from tree. Returns TRUE is found and removed.
// Actually delete if bDel

BOOL StgAvlNode::Remove( StgAvlNode** pRoot, StgAvlNode* pDel, BOOL bDel )
{
    // special case - empty tree
    if( *pRoot == NULL )
        return FALSE;
    // delete the element
    pDel = Rem( pRoot, pDel, FALSE );
    if( pDel )
    {
        if( bDel )
            delete pDel;
        // Rebalance the tree the hard way
        // OS 22.09.95: Auf MD's Wunsch auskommentiert wg. Absturz
/*      StgAvlNode* pNew = NULL;
        while( *pRoot )
        {
            StgAvlNode* p = Rem( pRoot, *pRoot, FALSE );
            Insert( &pNew, p );
        }
        *pRoot = pNew;*/
        return TRUE;
    }
    else
        return FALSE;
}

// Move node to a different tree. Returns TRUE is found and moved. This routine
// may be called when the key has changed.

BOOL StgAvlNode::Move
    ( StgAvlNode** pRoot1, StgAvlNode** pRoot2, StgAvlNode* pMove )
{
    // special case - empty tree
    if( *pRoot1 == NULL )
        return FALSE;
    pMove = Rem( pRoot1, pMove, FALSE );
    if( pMove )
        return Insert( pRoot2, pMove );
    else
        return FALSE;
}

////////////////////////// class AvlIterator /////////////////////////

// The iterator walks through a tree one entry by one.

StgAvlIterator::StgAvlIterator( StgAvlNode* p )
{
    pRoot = p;
    nCount = 0;
    if( p )
        p->StgEnum( nCount );
}

StgAvlNode* StgAvlIterator::Find( short n )
{
    StgAvlNode* p = pRoot;
    while( p )
    {
        if( n == p->nId )
            break;
        else p = ( n < p->nId ) ? p->pLeft : p->pRight;
    }
    return p;
}

StgAvlNode* StgAvlIterator::First()
{
    nCur = -1;
    return Next();
}

StgAvlNode* StgAvlIterator::Last()
{
    nCur = nCount;
    return Prev();
}

StgAvlNode* StgAvlIterator::Next()
{
    return Find( ++nCur );
}

StgAvlNode* StgAvlIterator::Prev()
{
    return Find( --nCur );
}

<|endoftext|>


<commit_before>// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed 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.

#include "breadboard/version.h"

namespace breadboard {

#define BREADBOARD_VERSION_MAJOR 1
#define BREADBOARD_VERSION_MINOR 0
#define BREADBOARD_VERSION_REVISION 1

// Turn X into a string literal.
#define BREADBOARD_STRING_EXPAND(X) #X
#define BREADBOARD_STRING(X) BREADBOARD_STRING_EXPAND(X)

/// @var kVersion
/// @brief String which identifies the current version of MathFu.
///
/// @ref kVersion is used by Google developers to identify which applications
/// uploaded to Google Play are using this library. This allows the development
/// team at Google to determine the popularity of the library.
/// How it works: Applications that are uploaded to the Google Play Store are
/// scanned for this version string. We track which applications are using it
/// to measure popularity. You are free to remove it (of course) but we would
/// appreciate if you left it in.
///
static const BreadboardVersion kVersion = {
  BREADBOARD_VERSION_MAJOR,
  BREADBOARD_VERSION_MINOR,
  BREADBOARD_VERSION_REVISION,
  "Breadboard "
  BREADBOARD_STRING(BREADBOARD_VERSION_MAJOR) "."
  BREADBOARD_STRING(BREADBOARD_VERSION_MINOR) "."
  BREADBOARD_STRING(BREADBOARD_VERSION_REVISION)
};

const BreadboardVersion& Version() { return kVersion; }

}  // namespace breadboard
<commit_msg>Update version numbers on all FPL projects. PiperOrigin-RevId: 148149051 Change-Id: I5a82c813fd5a4dd281f9ba12b562d129c26cd257<commit_after>// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed 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.

#include "breadboard/version.h"

namespace breadboard {

#define BREADBOARD_VERSION_MAJOR 1
#define BREADBOARD_VERSION_MINOR 0
#define BREADBOARD_VERSION_REVISION 2

// Turn X into a string literal.
#define BREADBOARD_STRING_EXPAND(X) #X
#define BREADBOARD_STRING(X) BREADBOARD_STRING_EXPAND(X)

/// @var kVersion
/// @brief String which identifies the current version of MathFu.
///
/// @ref kVersion is used by Google developers to identify which applications
/// uploaded to Google Play are using this library. This allows the development
/// team at Google to determine the popularity of the library.
/// How it works: Applications that are uploaded to the Google Play Store are
/// scanned for this version string. We track which applications are using it
/// to measure popularity. You are free to remove it (of course) but we would
/// appreciate if you left it in.
///
static const BreadboardVersion kVersion = {
  BREADBOARD_VERSION_MAJOR,
  BREADBOARD_VERSION_MINOR,
  BREADBOARD_VERSION_REVISION,
  "Breadboard "
  BREADBOARD_STRING(BREADBOARD_VERSION_MAJOR) "."
  BREADBOARD_STRING(BREADBOARD_VERSION_MINOR) "."
  BREADBOARD_STRING(BREADBOARD_VERSION_REVISION)
};

const BreadboardVersion& Version() { return kVersion; }

}  // namespace breadboard
<|endoftext|>


<commit_before>/*  This file is part of the Vc library.

    Copyright (C) 2010 Matthias Kretz <kretz@kde.org>

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

    Vc 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 Vc.  If not, see <http://www.gnu.org/licenses/>.

*/

#include <Vc/Vc>
#include "unittest.h"

using namespace Vc;

template<typename V> void reads()
{
    typedef typename V::EntryType T;
    typedef typename V::IndexType I;

    V a = V::Zero();
    const T zero = 0;
    for (int i = 0; i < V::Size; ++i) {
        const T x = a[i];
        COMPARE(x, zero);
    }
    a = static_cast<V>(I::IndexesFromZero());
    for (int i = 0; i < V::Size; ++i) {
        const T x = a[i];
        const T y = i;
        COMPARE(x, y);
    }
}

template<typename V> void writes()
{
    typedef typename V::EntryType T;
    typedef typename V::IndexType I;

    V a;
    for (int i = 0; i < V::Size; ++i) {
        a[i] = static_cast<T>(i);
    }
    V b = static_cast<V>(I::IndexesFromZero());
    COMPARE(a, b);

    const T one = 1;
    const T two = 2;

    if (V::Size == 1) {
        a(a == 0) += one;
        a[0] += one;
        a(a == 0) += one;
        COMPARE(a, V(2));
    } else if (V::Size == 4) {
        a(a == 1) += two;
        a[2] += one;
        a(a == 3) += one;
        b(b == 1) += one;
        b(b == 2) += one;
        b(b == 3) += one;
        COMPARE(a, b);
    } else if (V::Size == 8 || V::Size == 16) {
        a(a == 2) += two;
        a[3] += one;
        a(a == 4) += one;
        b(b == 2) += one;
        b(b == 3) += one;
        b(b == 4) += one;
        COMPARE(a, b);
    } else {
        a(a == 0) += two;
        a[1] += one;
        a(a == 2) += one;
        b(b == 0) += one;
        b(b == 1) += one;
        b(b == 2) += one;
        COMPARE(a, b);
    }
}

int main()
{
    testAllTypes(reads);
    testAllTypes(writes);

    return 0;
}
<commit_msg>make the scalar writes with GCC 4.3.x XFAILs<commit_after>/*  This file is part of the Vc library.

    Copyright (C) 2010 Matthias Kretz <kretz@kde.org>

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

    Vc 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 Vc.  If not, see <http://www.gnu.org/licenses/>.

*/

#include <Vc/Vc>
#include "unittest.h"

using namespace Vc;

template<typename V> void reads()
{
    typedef typename V::EntryType T;
    typedef typename V::IndexType I;

    V a = V::Zero();
    const T zero = 0;
    for (int i = 0; i < V::Size; ++i) {
        const T x = a[i];
        COMPARE(x, zero);
    }
    a = static_cast<V>(I::IndexesFromZero());
    for (int i = 0; i < V::Size; ++i) {
        const T x = a[i];
        const T y = i;
        COMPARE(x, y);
    }
}

template<typename V> void writes()
{
    typedef typename V::EntryType T;
    typedef typename V::IndexType I;

    V a;
    for (int i = 0; i < V::Size; ++i) {
        a[i] = static_cast<T>(i);
    }
    V b = static_cast<V>(I::IndexesFromZero());
#if defined(__GNUC__) && !defined(__INTEL_COMPILER) && __GNUC__ == 4 && __GNUC_MINOR__ == 3 && __OPTIMIZE__ && VC_IMPL_SSE
    // GCC 4.3.x miscompiles. Somehow it fails to get the may_alias type right here
    if (isEqualType<V, int_v>() || isEqualType<V, short_v>() || isEqualType<V, ushort_v>()) {
        EXPECT_FAILURE();
    }
#endif
    COMPARE(a, b);

    const T one = 1;
    const T two = 2;

    if (V::Size == 1) {
        a(a == 0) += one;
        a[0] += one;
        a(a == 0) += one;
        COMPARE(a, V(2));
    } else if (V::Size == 4) {
        a(a == 1) += two;
        a[2] += one;
        a(a == 3) += one;
        b(b == 1) += one;
        b(b == 2) += one;
        b(b == 3) += one;
        COMPARE(a, b);
    } else if (V::Size == 8 || V::Size == 16) {
        a(a == 2) += two;
        a[3] += one;
        a(a == 4) += one;
        b(b == 2) += one;
        b(b == 3) += one;
        b(b == 4) += one;
        COMPARE(a, b);
    } else {
        a(a == 0) += two;
        a[1] += one;
        a(a == 2) += one;
        b(b == 0) += one;
        b(b == 1) += one;
        b(b == 2) += one;
        COMPARE(a, b);
    }
}

int main()
{
    testAllTypes(reads);
    testAllTypes(writes);

    return 0;
}
<|endoftext|>


<commit_before>/******************************************************************************
* Copyright (c) 2014, Brad Chambers (brad.chambers@gmail.com)
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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 "PCLVisualizer.hpp"

#include <boost/thread/thread.hpp>

#include <pcl/io/pcd_io.h>
#include <pcl/visualization/pcl_visualizer.h>

#include "PCLConversions.hpp"
#include <pdal/PointBuffer.hpp>
#include <pdal/StageFactory.hpp>

CREATE_WRITER_PLUGIN(pclvisualizer, pdal::PclVisualizer)

namespace pdal
{

void PclVisualizer::write(const PointBuffer& data)
{
    // Determine XYZ bounds
    BOX3D const& buffer_bounds = data.calculateBounds();

    // Convert PointBuffer to a PCL PointCloud
    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
    pclsupport::PDALtoPCD(const_cast<PointBuffer&>(data), *cloud, buffer_bounds);

    // Create PCLVisualizer
    boost::shared_ptr<pcl::visualization::PCLVisualizer> p(new pcl::visualization::PCLVisualizer("3D Viewer"));

    // Set background to black
    p->setBackgroundColor(0, 0, 0);

    // Use Z dimension to colorize points
    pcl::visualization::PointCloudColorHandlerGenericField<pcl::PointXYZ> color(cloud, "z");

    // Add point cloud to the viewer with the Z dimension color handler
    p->addPointCloud<pcl::PointXYZ> (cloud, color, "cloud");

    while (!p->wasStopped())
    {
        p->spinOnce(100);
        boost::this_thread::sleep(boost::posix_time::microseconds(100000));
    }
}

} // namespaces
<commit_msg>PCLVisualizer now has x, y, z, rgb, and intensity color handlers<commit_after>/******************************************************************************
* Copyright (c) 2014, Brad Chambers (brad.chambers@gmail.com)
*
* 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 Hobu, Inc. or Flaxen Geo Consulting 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 "PCLVisualizer.hpp"

#include <boost/thread/thread.hpp>

#include <pcl/conversions.h>
#include <pcl/io/pcd_io.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/visualization/impl/pcl_visualizer.hpp>
#include <pcl/visualization/point_cloud_handlers.h>
#include <pcl/visualization/impl/point_cloud_handlers.hpp>

#include "PCLConversions.hpp"
#include "point_types.hpp"
#include <pdal/PointBuffer.hpp>
#include <pdal/StageFactory.hpp>

CREATE_WRITER_PLUGIN(pclvisualizer, pdal::PclVisualizer)

bool
isValidFieldName(const std::string &field)
{
    if (field == "_")
        return (false);

    return (true);
}

namespace pcl
{
namespace visualization
{
template <typename PointT>
class PointCloudColorHandlerIntensity : public PointCloudColorHandler<PointT>
{
    using PointCloudColorHandler<PointT>::capable_;
    using PointCloudColorHandler<PointT>::cloud_;

    typedef typename PointCloudColorHandler<PointT>::PointCloud::ConstPtr PointCloudConstPtr;

public:
    typedef boost::shared_ptr<PointCloudColorHandlerIntensity<PointT> > Ptr;
    typedef boost::shared_ptr<const PointCloudColorHandlerIntensity<PointT> > ConstPtr;

    PointCloudColorHandlerIntensity(const PointCloudConstPtr& cloud) :
        PointCloudColorHandler<PointT> (cloud)
    {
        capable_ = true;
    }

    virtual bool
    getColor(vtkSmartPointer<vtkDataArray> &scalars) const
    {
        if (!capable_ || !cloud_)
            return (false);

        if (!scalars)
            scalars = vtkSmartPointer<vtkUnsignedCharArray>::New();
        scalars->SetNumberOfComponents(3);

        vtkIdType nr_points = cloud_->width * cloud_->height;
        reinterpret_cast<vtkUnsignedCharArray*>(&(*scalars))->SetNumberOfTuples(nr_points);
        unsigned char* colors = reinterpret_cast<vtkUnsignedCharArray*>(&(*scalars))->GetPointer(0);

        int int_idx = pcl::getFieldIndex(*cloud_, "intensity");

        if (int_idx != -1)
        {
            float int_data;
            int int_point_offset = cloud_->fields[int_idx].offset;
            for (vtkIdType cp = 0; cp < nr_points; ++cp, int_point_offset += cloud_->point_step)
            {
                int idx = cp * 3;
                memcpy(&int_data, &cloud_->data[int_point_offset], sizeof(float));
                colors[idx + 0] = int_data * 255;
                colors[idx + 1] = int_data * 255;
                colors[idx + 2] = int_data * 255;
            }
        }
        return (true);
    }

private:
    virtual std::string getFieldName() const
    {
        return ("intensity");
    }
    virtual inline std::string getName() const
    {
        return ("PointCloudColorHandlerIntensity");
    }
};
}
}

namespace pdal
{

void PclVisualizer::write(const PointBuffer& data)
{
    // Determine XYZ bounds
    BOX3D const& buffer_bounds = data.calculateBounds();

    typedef XYZIRGBA PointType;

    // Convert PointBuffer to a PCL PointCloud
    pcl::PointCloud<PointType>::Ptr cloud(new pcl::PointCloud<PointType>);
    pclsupport::PDALtoPCD(const_cast<PointBuffer&>(data), *cloud, buffer_bounds);

    // Create PCLVisualizer
    boost::shared_ptr<pcl::visualization::PCLVisualizer> p(new pcl::visualization::PCLVisualizer("3D Viewer"));

    // Set background to black
    p->setBackgroundColor(0, 0, 0);

    pcl::PCLPointCloud2::Ptr cloud_blob(new pcl::PCLPointCloud2);
    toPCLPointCloud2(*cloud, *cloud_blob);

    typedef pcl::visualization::PointCloudColorHandler<pcl::PCLPointCloud2> ColorHandler;
    typedef ColorHandler::Ptr ColorHandlerPtr;
    ColorHandlerPtr color_handler;
    for (size_t f = 0; f < cloud_blob->fields.size(); ++f)
    {
        if (cloud_blob->fields[f].name == "rgb" || cloud_blob->fields[f].name == "rgba")
        {
            color_handler.reset(new pcl::visualization::PointCloudColorHandlerRGBField<pcl::PCLPointCloud2> (cloud_blob));
        }
        else if (cloud_blob->fields[f].name == "intensity")
        {
            color_handler.reset(new pcl::visualization::PointCloudColorHandlerIntensity<pcl::PCLPointCloud2> (cloud_blob));
        }
        else
        {
            if (!isValidFieldName(cloud_blob->fields[f].name))
                continue;
            color_handler.reset(new pcl::visualization::PointCloudColorHandlerGenericField<pcl::PCLPointCloud2> (cloud_blob, cloud_blob->fields[f].name));
        }
        p->addPointCloud(cloud_blob, color_handler, cloud->sensor_origin_, cloud->sensor_orientation_);
    }
    p->updateColorHandlerIndex("cloud", 2);

    while (!p->wasStopped())
    {
        p->spinOnce(100);
        boost::this_thread::sleep(boost::posix_time::microseconds(100000));
    }
}

} // namespaces
<|endoftext|>