<commit_before>
#include "AbstractShadingLanguageIncludeImplementation.h"

#include <globjects/globjects.h>

#include <glbinding/gl/extension.h>

#include "ShadingLanguageIncludeImplementation_ShadingLanguageIncludeARB.h"
#include "ShadingLanguageIncludeImplementation_Fallback.h"

using namespace gl;

namespace globjects
{

AbstractShadingLanguageIncludeImplementation::AbstractShadingLanguageIncludeImplementation()
{
}

AbstractShadingLanguageIncludeImplementation::~AbstractShadingLanguageIncludeImplementation()
{
}

AbstractShadingLanguageIncludeImplementation * AbstractShadingLanguageIncludeImplementation::get(const Shader::IncludeImplementation impl)
{
    if (impl == Shader::IncludeImplementation::ShadingLanguageIncludeARB
     && hasExtension(GLextension::GL_ARB_shading_language_include))
    {
        return ShadingLanguageIncludeImplementation_ARB::instance();
    }
    else
    {
        return ShadingLanguageIncludeImplementation_Fallback::instance();
    }
}

std::vector<const char *> AbstractShadingLanguageIncludeImplementation::collectCStrings(const std::vector<std::string> & strings)
{
    std::vector<const char *> cStrings;

    for (const std::string & str : strings)
    {
        cStrings.push_back(str.c_str());
    }

    return cStrings;
}

} // namespace globjects
<commit_msg>Circumvent empty shader source<commit_after>
#include "AbstractShadingLanguageIncludeImplementation.h"

#include <globjects/globjects.h>

#include <glbinding/gl/extension.h>

#include "ShadingLanguageIncludeImplementation_ShadingLanguageIncludeARB.h"
#include "ShadingLanguageIncludeImplementation_Fallback.h"

using namespace gl;

namespace globjects
{

AbstractShadingLanguageIncludeImplementation::AbstractShadingLanguageIncludeImplementation()
{
}

AbstractShadingLanguageIncludeImplementation::~AbstractShadingLanguageIncludeImplementation()
{
}

AbstractShadingLanguageIncludeImplementation * AbstractShadingLanguageIncludeImplementation::get(const Shader::IncludeImplementation impl)
{
    if (impl == Shader::IncludeImplementation::ShadingLanguageIncludeARB
     && hasExtension(GLextension::GL_ARB_shading_language_include))
    {
        return ShadingLanguageIncludeImplementation_ARB::instance();
    }
    else
    {
        return ShadingLanguageIncludeImplementation_Fallback::instance();
    }
}

std::vector<const char *> AbstractShadingLanguageIncludeImplementation::collectCStrings(const std::vector<std::string> & strings)
{
    std::vector<const char *> cStrings;

    for (const std::string & str : strings)
    {
        cStrings.push_back(str.c_str());
    }

    if (cStrings.empty())
    {
        cStrings.push_back("");
    }

    return cStrings;
}

} // namespace globjects
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _SVX_FMGROUP_HXX
#define _SVX_FMGROUP_HXX

#ifndef _SVX_FMCPONT_HXX
#include "fmcpont.hxx"
#endif

#ifndef __DBFORM_HXX
#include <dbform.hxx>
#endif

DECLARE_LIST( FmCtrlModelList, XInterface* );

struct FmXGroupModel_Impl;

//==================================================================
// FmXGroupModel
//==================================================================
class FmXGroupModel : public XBoundControl,
                      public XLoadListener,
                      public XPropertyChangeListener,
                      public XGroup,
                      public FmXControlModel
{
    FmFormControlMap        aControlMap;

    friend Reflection*      FmXGroupModel_getReflection();
    FmXGroupModel_Impl*     pGroupModelData;            // Properties

public:
    FmXGroupModel();
    virtual ~FmXGroupModel();

    // UNO Anbindung
    SMART_UNO_DECLARATION( FmXGroupModel, FmXControlModel );
    virtual XInterface*     queryInterface(UsrUik);
    virtual XIdlClassRef    getIdlClass();

    // XGroup
    virtual sal_Int32 getFormControlCount();
    virtual XFormControlRef getFormControlByName( const XubString& sName ) const;
    virtual XFormControlRef getFormControlByIndex( sal_Int32 Index ) const;
    virtual void appendFormControl( const XFormControlRef& FormControl );
    virtual XFormControlRef removeFormControl( const XFormControlRef& FormControl );

    // XFormControl
    virtual void setParent( const XFormRef& Parent );

    // XEventListener
    virtual void disposing( const EventObject& Source );

    // XPropertiesChangeListener
    virtual void propertyChange( const PropertyChangeEvent& evt );

    // XLoadListener
    virtual void loaded( const EventObject& rEvent );
    virtual void unloaded( const EventObject& rEvent );

    // XBoundControl
    virtual void addBoundControlListener( const XBoundControlListenerRef& l );
    virtual void removeBoundControlListener( const XBoundControlListenerRef& l );

    // XPersistObject
    virtual XubString getServiceName( void ) const;
    virtual void write( const XObjectOutputStreamRef& OutStream );
    virtual void read( const XObjectInputStreamRef& InStream );

    // PropertySetInterface
    virtual FmXPropertySetInfo* createPropertySetInfo() const;
    virtual sal_Bool setPropertyValue( sal_uInt16 nId, const XubString& aPropertyName,
                                   const UsrAny& aValue,
                                   PropertyChangeEventSequence* pSeq,
                                   sal_Int32 nIndex );
    virtual UsrAny getPropertyValue( sal_uInt16 nId, const XubString& aPropertyName ) const;
    virtual void addPropertyChangeListener( const XubString& aPropertyName, const XPropertyChangeListenerRef& aListener );
    virtual void removePropertyChangeListener( const XubString& aPropertyName, const XPropertyChangeListenerRef& aListener );
};

//==================================================================
// FmXGroupModelInfo
// Properties:
//==================================================================
class FmXGroupModelInfo : public FmXControlModelInfo
{
    friend class FmXGroupModel;

protected:
    FmXGroupModelInfo( const FmXGroupModel* pCp );
    virtual void fillProperties( sal_uInt32& nIndex, PropertySequence& aSeq ) const;
};

#endif // _SVX_FMGROUP_HXX

<commit_msg>Remove DECLARE_LIST( FmCtrlModelList, XInterface* ).<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _SVX_FMGROUP_HXX
#define _SVX_FMGROUP_HXX

#ifndef _SVX_FMCPONT_HXX
#include "fmcpont.hxx"
#endif

#ifndef __DBFORM_HXX
#include <dbform.hxx>
#endif

struct FmXGroupModel_Impl;

//==================================================================
// FmXGroupModel
//==================================================================
class FmXGroupModel : public XBoundControl,
                      public XLoadListener,
                      public XPropertyChangeListener,
                      public XGroup,
                      public FmXControlModel
{
    FmFormControlMap        aControlMap;

    friend Reflection*      FmXGroupModel_getReflection();
    FmXGroupModel_Impl*     pGroupModelData;            // Properties

public:
    FmXGroupModel();
    virtual ~FmXGroupModel();

    // UNO Anbindung
    SMART_UNO_DECLARATION( FmXGroupModel, FmXControlModel );
    virtual XInterface*     queryInterface(UsrUik);
    virtual XIdlClassRef    getIdlClass();

    // XGroup
    virtual sal_Int32 getFormControlCount();
    virtual XFormControlRef getFormControlByName( const XubString& sName ) const;
    virtual XFormControlRef getFormControlByIndex( sal_Int32 Index ) const;
    virtual void appendFormControl( const XFormControlRef& FormControl );
    virtual XFormControlRef removeFormControl( const XFormControlRef& FormControl );

    // XFormControl
    virtual void setParent( const XFormRef& Parent );

    // XEventListener
    virtual void disposing( const EventObject& Source );

    // XPropertiesChangeListener
    virtual void propertyChange( const PropertyChangeEvent& evt );

    // XLoadListener
    virtual void loaded( const EventObject& rEvent );
    virtual void unloaded( const EventObject& rEvent );

    // XBoundControl
    virtual void addBoundControlListener( const XBoundControlListenerRef& l );
    virtual void removeBoundControlListener( const XBoundControlListenerRef& l );

    // XPersistObject
    virtual XubString getServiceName( void ) const;
    virtual void write( const XObjectOutputStreamRef& OutStream );
    virtual void read( const XObjectInputStreamRef& InStream );

    // PropertySetInterface
    virtual FmXPropertySetInfo* createPropertySetInfo() const;
    virtual sal_Bool setPropertyValue( sal_uInt16 nId, const XubString& aPropertyName,
                                   const UsrAny& aValue,
                                   PropertyChangeEventSequence* pSeq,
                                   sal_Int32 nIndex );
    virtual UsrAny getPropertyValue( sal_uInt16 nId, const XubString& aPropertyName ) const;
    virtual void addPropertyChangeListener( const XubString& aPropertyName, const XPropertyChangeListenerRef& aListener );
    virtual void removePropertyChangeListener( const XubString& aPropertyName, const XPropertyChangeListenerRef& aListener );
};

//==================================================================
// FmXGroupModelInfo
// Properties:
//==================================================================
class FmXGroupModelInfo : public FmXControlModelInfo
{
    friend class FmXGroupModel;

protected:
    FmXGroupModelInfo( const FmXGroupModel* pCp );
    virtual void fillProperties( sal_uInt32& nIndex, PropertySequence& aSeq ) const;
};

#endif // _SVX_FMGROUP_HXX

<|endoftext|>


<commit_before>// Copyright (c) 2015-2016 William W. Fisher (at gmail dot com)
// This file is distributed under the MIT License.

#include "ofp/ofp.h"
#include "./ofpx_decode.h"
#include "./ofpx_encode.h"
#if LIBOFP_ENABLE_JSONRPC
#include <openssl/ssl.h>  // For OPENSSL_VERSION_NUMBER
#include <asio/version.hpp>
#include "./ofpx_jsonrpc.h"
#endif  // LIBOFP_ENABLE_JSONRPC
#include "./libofp.h"
#include "./ofpx_help.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/raw_ostream.h"

using namespace llvm;

struct SubprogramEntry {
  const char *name;
  ofpx::RunSubprogram run;
};

static const SubprogramEntry programs[] = {
    {"encode", ofpx::Run<ofpx::Encode>},
    {"decode", ofpx::Run<ofpx::Decode>},
#if LIBOFP_ENABLE_JSONRPC
    {"jsonrpc", ofpx::Run<ofpx::JsonRpc>},
#endif  // LIBOFP_ENABLE_JSONRPC
    {"help", ofpx::Run<ofpx::Help>}};

static void print_usage(std::ostream &out);
static void print_version();
static void force_link_api();

int main(int argc, const char *const *argv) {
  if (argc < 2) {
    if (argc == 0)
      force_link_api();
    print_usage(std::cerr);
    return 1;
  }

  std::string name = argv[1];
  if (name == "--help" || name == "-h") {
    print_usage(std::cout);
    return 0;
  }

  if (name == "version" || name == "-v" || name == "-version" ||
      name == "--version") {
    print_version();
    return 0;
  }

  cl::SetVersionPrinter(print_version);

  for (size_t i = 0; i < ofp::ArrayLength(programs); ++i) {
    if (name == programs[i].name) {
      return (*programs[i].run)(argc - 1, argv + 1);
    }
  }

  std::cerr << "libofp: '" << name
            << "' is not a libofp command. See 'libofp --help'.\n";

  return 1;
}

void print_usage(std::ostream &out) {
  out << "Usage: libofp <command> [ <options> ]\n\n";
  out << "Commands:\n";
  for (size_t i = 0; i < ofp::ArrayLength(programs); ++i) {
    out << "  " << programs[i].name << '\n';
  }
  out << '\n';
}

void print_version() {
  raw_ostream &os = outs();

  std::string libofpCommit{LIBOFP_GIT_COMMIT_LIBOFP};
  os << "libofp " << LIBOFP_VERSION_STRING << " (" << libofpCommit.substr(0, 7)
     << ")";

  os << "  <" << LIBOFP_GITHUB_URL << ">\n";

#ifndef __OPTIMIZE__
  os << "  DEBUG build";
#else
  os << "  Optimized build";
#endif
#ifndef NDEBUG
  os << " with assertions";
#endif
  os << '\n';

#if LIBOFP_ENABLE_JSONRPC
  unsigned asioMajor = ASIO_VERSION / 100000;
  unsigned asioMinor = ASIO_VERSION / 100 % 1000;
  unsigned asioPatch = ASIO_VERSION % 100;
  std::string asioCommit{LIBOFP_GIT_COMMIT_ASIO};

  os << "  ASIO " << asioMajor << '.' << asioMinor << '.' << asioPatch << " ("
     << asioCommit.substr(0, 7) << ")\n";

  unsigned sslMajor = (OPENSSL_VERSION_NUMBER >> 28) & 0x0F;
  unsigned sslMinor = (OPENSSL_VERSION_NUMBER >> 20) & 0xFF;
  unsigned sslPatch = (OPENSSL_VERSION_NUMBER >> 12) & 0xFF;
  std::string sslCommit{LIBOFP_GIT_COMMIT_BORINGSSL};

  os << "  BoringSSL " << sslMajor << '.' << sslMinor << '.' << sslPatch << " ("
     << sslCommit.substr(0, 7) << ")\n";
#endif  // LIBOFP_ENABLE_JSONRPC
}

void force_link_api() {
  libofp_buffer buf = {nullptr, 0};
  libofp_version(&buf);
  libofp_buffer_free(&buf);

  libofp_encode(&buf, "", 0);
  libofp_buffer_free(&buf);

  libofp_buffer empty = {nullptr, 0};
  libofp_decode(&buf, &empty, 0);
  libofp_buffer_free(&buf);
}
<commit_msg>Include 32/64 bit build information in version string.<commit_after>// Copyright (c) 2015-2016 William W. Fisher (at gmail dot com)
// This file is distributed under the MIT License.

#include "ofp/ofp.h"
#include "./ofpx_decode.h"
#include "./ofpx_encode.h"
#if LIBOFP_ENABLE_JSONRPC
#include <openssl/ssl.h>  // For OPENSSL_VERSION_NUMBER
#include <asio/version.hpp>
#include "./ofpx_jsonrpc.h"
#endif  // LIBOFP_ENABLE_JSONRPC
#include "./libofp.h"
#include "./ofpx_help.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/raw_ostream.h"

using namespace llvm;

struct SubprogramEntry {
  const char *name;
  ofpx::RunSubprogram run;
};

static const SubprogramEntry programs[] = {
    {"encode", ofpx::Run<ofpx::Encode>},
    {"decode", ofpx::Run<ofpx::Decode>},
#if LIBOFP_ENABLE_JSONRPC
    {"jsonrpc", ofpx::Run<ofpx::JsonRpc>},
#endif  // LIBOFP_ENABLE_JSONRPC
    {"help", ofpx::Run<ofpx::Help>}};

static void print_usage(std::ostream &out);
static void print_version();
static void force_link_api();

int main(int argc, const char *const *argv) {
  if (argc < 2) {
    if (argc == 0)
      force_link_api();
    print_usage(std::cerr);
    return 1;
  }

  std::string name = argv[1];
  if (name == "--help" || name == "-h") {
    print_usage(std::cout);
    return 0;
  }

  if (name == "version" || name == "-v" || name == "-version" ||
      name == "--version") {
    print_version();
    return 0;
  }

  cl::SetVersionPrinter(print_version);

  for (size_t i = 0; i < ofp::ArrayLength(programs); ++i) {
    if (name == programs[i].name) {
      return (*programs[i].run)(argc - 1, argv + 1);
    }
  }

  std::cerr << "libofp: '" << name
            << "' is not a libofp command. See 'libofp --help'.\n";

  return 1;
}

void print_usage(std::ostream &out) {
  out << "Usage: libofp <command> [ <options> ]\n\n";
  out << "Commands:\n";
  for (size_t i = 0; i < ofp::ArrayLength(programs); ++i) {
    out << "  " << programs[i].name << '\n';
  }
  out << '\n';
}

void print_version() {
  raw_ostream &os = outs();

  std::string libofpCommit{LIBOFP_GIT_COMMIT_LIBOFP};
  os << "libofp " << LIBOFP_VERSION_STRING << " (" << libofpCommit.substr(0, 7)
     << ")";

  os << "  <" << LIBOFP_GITHUB_URL << ">\n";

  const char *bits = "? bit";
  if (sizeof(void*) == 8) {
    bits = "64 bit";
  } else if (sizeof(void*) == 4) {
    bits = "32 bit";
  }

#ifndef __OPTIMIZE__
  os << "  DEBUG ";
#else
  os << "  Optimized ";
#endif
  os << bits << " build";
#ifndef NDEBUG
  os << " with assertions";
#endif
  os << '\n';

#if LIBOFP_ENABLE_JSONRPC
  unsigned asioMajor = ASIO_VERSION / 100000;
  unsigned asioMinor = ASIO_VERSION / 100 % 1000;
  unsigned asioPatch = ASIO_VERSION % 100;
  std::string asioCommit{LIBOFP_GIT_COMMIT_ASIO};

  os << "  ASIO " << asioMajor << '.' << asioMinor << '.' << asioPatch << " ("
     << asioCommit.substr(0, 7) << ")\n";

  unsigned sslMajor = (OPENSSL_VERSION_NUMBER >> 28) & 0x0F;
  unsigned sslMinor = (OPENSSL_VERSION_NUMBER >> 20) & 0xFF;
  unsigned sslPatch = (OPENSSL_VERSION_NUMBER >> 12) & 0xFF;
  std::string sslCommit{LIBOFP_GIT_COMMIT_BORINGSSL};

  os << "  BoringSSL " << sslMajor << '.' << sslMinor << '.' << sslPatch << " ("
     << sslCommit.substr(0, 7) << ")\n";
#endif  // LIBOFP_ENABLE_JSONRPC
}

void force_link_api() {
  libofp_buffer buf = {nullptr, 0};
  libofp_version(&buf);
  libofp_buffer_free(&buf);

  libofp_encode(&buf, "", 0);
  libofp_buffer_free(&buf);

  libofp_buffer empty = {nullptr, 0};
  libofp_decode(&buf, &empty, 0);
  libofp_buffer_free(&buf);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: svdoimp.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: ihi $ $Date: 2006-11-14 13:27:59 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SVX_SVDOIMP_HXX
#define _SVX_SVDOIMP_HXX

#include <memory>
#include <vector>

#ifndef _CPPUHELPER_WEAKREF_HXX_
#include <cppuhelper/weakref.hxx>
#endif

#ifndef _MAPMOD_HXX //autogen
#include <vcl/mapmod.hxx>
#endif

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

#ifndef _SV_TIMER_HXX
#include <vcl/timer.hxx>
#endif

#ifndef _SVDSOB_HXX //autogen
#include "svdsob.hxx"
#endif

#ifndef _SVDTYPES_HXX
#include "svdtypes.hxx" // fuer SdrLayerID
#endif

#ifndef _SVDGLUE_HXX
#include "svdglue.hxx" // Klebepunkte
#endif

#ifndef _SVX_XDASH_HXX
#include "xdash.hxx"
#endif

#ifndef _XPOLY_HXX
#include "xpoly.hxx"
#endif

//#ifndef _POLY3D_HXX
//#include "poly3d.hxx"
//#endif

#ifndef _XENUM_HXX
#include "xenum.hxx"
#endif

#ifndef _BGFX_VECTOR_B2DVECTOR_HXX
#include <basegfx/vector/b2dvector.hxx>
#endif

#ifndef _SVX_RECTENUM_HXX
#include "rectenum.hxx"
#endif

#ifndef _BGFX_POLYGON_B2DPOLYPOLYGON_HXX
#include <basegfx/polygon/b2dpolypolygon.hxx>
#endif

class SdrObject;
class XOutputDevice;
class XFillAttrSetItem;
class XLineAttrSetItem;
class SfxItemSet;
class Bitmap;

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

// #100127# Bracket filled shapes with a comment, if recording a Mtf
class ImpGraphicFill
{
public:
    ImpGraphicFill( const SdrObject& rObj, const XOutputDevice& rXOut, const SfxItemSet& rFillItemSet, bool bIsShadow=false );
    ~ImpGraphicFill();

private:
    const SdrObject&        mrObj;
    const XOutputDevice&    mrXOut;
    bool                    mbCommentWritten;
};

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

// #104609# Extracted from XOutputDevice::ImpCalcBmpFillStartValues

/** Calc offset and size for bitmap fill

    This method calculates the size and the offset from the left, top
    position of a shape in logical coordinates

    @param rStartOffset
    The offset from the left, top position of the output rectangle is returned

    @param rBmpOutputSize
    The output size of the bitmap is returned herein

    @param rOutputRect
    Specifies the output rectangle into which the bitmap should be tiled into

    @param rOutputMapMode
    Specifies the logical coordinate system the output rectangle is in

    @param rFillBitmap
    Specifies the bitmap to fill with

    @param rBmpSize
    The desired destination bitmap size. If null, size is taken from the bitmap

    @param rBmpPerCent
    Percentage of bitmap size, relative to the output rectangle

    @param rBmpOffPerCent
    Offset for bitmap tiling, in percentage relative to bitmap output size

    @param bBmpLogSize
    True when using the preferred bitmap size, False when using the percentage value

    @param bBmpTile
    True for tiling. False only paints one instance of the bitmap

    @param bBmpStretch
    True if bitmap should be stretched to output rect dimension

    @param eBmpRectPoint
    Position of the start point relative to the bitmap

 */
void ImpCalcBmpFillSizes( Size&            rStartOffset,
                          Size&            rBmpOutputSize,
                          const Rectangle& rOutputRect,
                          const MapMode&   rOutputMapMode,
                          const Bitmap&    rFillBitmap,
                          const Size&      rBmpSize,
                          const Size&      rBmpPerCent,
                          const Size&      rBmpOffPerCent,
                          BOOL             bBmpLogSize,
                          BOOL             bBmpTile,
                          BOOL             bBmpStretch,
                          RECT_POINT       eBmpRectPoint );

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

class ImpLineStyleParameterPack
{
    XLineJoint                      meLineJoint;
    basegfx::B2DPolyPolygon     maStartPolyPolygon;
    basegfx::B2DPolyPolygon     maEndPolyPolygon;

    sal_Int32                       mnLineWidth;
    sal_Int32                       mnStartWidth;
    sal_Int32                       mnEndWidth;

    ::std::vector<double>           maDotDashArray;
    double                          mfFullDotDashLen;
    double                          mfDegreeStepWidth;

    // bitfield
    unsigned                        mbStartCentered : 1;
    unsigned                        mbEndCentered : 1;
    unsigned                        mbForceNoArrowsLeft : 1;
    unsigned                        mbForceNoArrowsRight : 1;
    unsigned                        mbForceHair : 1;

    // flag for LineStyle. True is XLINE_SOLID, false is XLINE_DASH
    unsigned                        mbLineStyleSolid : 1;

public:
    ImpLineStyleParameterPack(const SfxItemSet& rSet, bool bForceHair);
    ~ImpLineStyleParameterPack();

    sal_Int32 GetLineWidth() const { return mnLineWidth; }
    sal_Int32 GetDisplayLineWidth() const { return mbForceHair ? 0L : mnLineWidth; }
    bool IsLineStyleSolid() const { return mbLineStyleSolid; }

    sal_Int32 GetStartWidth() const { return mnStartWidth; }
    sal_Int32 GetEndWidth() const { return mnEndWidth; }

    const basegfx::B2DPolyPolygon& GetStartPolyPolygon() const { return maStartPolyPolygon; }
    const basegfx::B2DPolyPolygon& GetEndPolyPolygon() const { return maEndPolyPolygon; }

    double GetDegreeStepWidth() const { return mfDegreeStepWidth; }

    XLineJoint GetLineJoint() const { return meLineJoint; }
    double GetLinejointMiterMinimumAngle() const { return 15.0; }

    double GetFullDotDashLen() const { return mfFullDotDashLen; }
    const ::std::vector< double >& GetDotDash() const { return maDotDashArray; }

    bool IsStartCentered() const { return mbStartCentered; }
    bool IsEndCentered() const { return mbEndCentered; }

    bool IsStartActive() const;
    bool IsEndActive() const;

    void ForceNoArrowsLeft(bool bNew) { mbForceNoArrowsLeft = bNew; }
    void ForceNoArrowsRight(bool bNew) { mbForceNoArrowsRight = bNew; }
};

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

class ImpLineGeometryCreator
{
    const ImpLineStyleParameterPack&        mrLineAttr;
    basegfx::B2DPolyPolygon&                maAreaPolyPolygon;
    basegfx::B2DPolyPolygon&                maLinePolyPolygon;

    // bitfield
    unsigned                                mbLineDraft : 1;

    // private support functions
    // help functions for line geometry creation
    void ImpCreateLineGeometry(
        const basegfx::B2DPolygon& rSourcePoly);

public:
    ImpLineGeometryCreator(
        const ImpLineStyleParameterPack& rAttr,
        basegfx::B2DPolyPolygon& rPoPo,
        basegfx::B2DPolyPolygon& rPoLi,
        bool bIsLineDraft = false)
    :   mrLineAttr(rAttr),
        maAreaPolyPolygon(rPoPo),
        maLinePolyPolygon(rPoLi),
        mbLineDraft(bIsLineDraft)
    {
    }

    void AddPolygon(const basegfx::B2DPolygon& rPoly) { ImpCreateLineGeometry(rPoly); }
    const basegfx::B2DPolyPolygon& GetAreaPolyPolygon() const { return maAreaPolyPolygon; }
    const basegfx::B2DPolyPolygon& GetLinePolyPolygon() const { return maLinePolyPolygon; }
};

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

class SdrLineGeometry
{
    basegfx::B2DPolyPolygon             maAreaPolyPolygon;
    basegfx::B2DPolyPolygon             maLinePolyPolygon;
    ImpLineStyleParameterPack               maLineAttr;

    // bitfield
    unsigned                                mbForceOnePixel : 1;
    unsigned                                mbForceTwoPixel : 1;

public:
    SdrLineGeometry(
        const basegfx::B2DPolyPolygon& rAreaPolyPolygon,
        const basegfx::B2DPolyPolygon& rLinePolyPolygon,
        const ImpLineStyleParameterPack& rLineAttr,
        bool bForceOnePixel,
        bool bForceTwoPixel)
    :   maAreaPolyPolygon(rAreaPolyPolygon),
        maLinePolyPolygon(rLinePolyPolygon),
        maLineAttr(rLineAttr),
        mbForceOnePixel(bForceOnePixel),
        mbForceTwoPixel(bForceTwoPixel)
    {}

    const basegfx::B2DPolyPolygon& GetAreaPolyPolygon() { return maAreaPolyPolygon; }
    const basegfx::B2DPolyPolygon& GetLinePolyPolygon() { return maLinePolyPolygon; }
    const ImpLineStyleParameterPack& GetLineAttr() { return maLineAttr; }
    bool DoForceOnePixel() const { return mbForceOnePixel; }
    bool DoForceTwoPixel() const { return mbForceTwoPixel; }
};

#endif // _SVX_SVDOIMP_HXX

// eof
<commit_msg>INTEGRATION: CWS vgbugs07 (1.9.254); FILE MERGED 2007/06/04 13:27:03 vg 1.9.254.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: svdoimp.hxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 18:24:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SVX_SVDOIMP_HXX
#define _SVX_SVDOIMP_HXX

#include <memory>
#include <vector>

#ifndef _CPPUHELPER_WEAKREF_HXX_
#include <cppuhelper/weakref.hxx>
#endif

#ifndef _MAPMOD_HXX //autogen
#include <vcl/mapmod.hxx>
#endif

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

#ifndef _SV_TIMER_HXX
#include <vcl/timer.hxx>
#endif

#ifndef _SVDSOB_HXX //autogen
#include <svx/svdsob.hxx>
#endif

#ifndef _SVDTYPES_HXX
#include <svx/svdtypes.hxx> // fuer SdrLayerID
#endif

#ifndef _SVDGLUE_HXX
#include <svx/svdglue.hxx> // Klebepunkte
#endif

#ifndef _SVX_XDASH_HXX
#include <svx/xdash.hxx>
#endif

#ifndef _XPOLY_HXX
#include <svx/xpoly.hxx>
#endif

//#ifndef _POLY3D_HXX
//#include "poly3d.hxx"
//#endif

#ifndef _XENUM_HXX
#include <svx/xenum.hxx>
#endif

#ifndef _BGFX_VECTOR_B2DVECTOR_HXX
#include <basegfx/vector/b2dvector.hxx>
#endif

#ifndef _SVX_RECTENUM_HXX
#include <svx/rectenum.hxx>
#endif

#ifndef _BGFX_POLYGON_B2DPOLYPOLYGON_HXX
#include <basegfx/polygon/b2dpolypolygon.hxx>
#endif

class SdrObject;
class XOutputDevice;
class XFillAttrSetItem;
class XLineAttrSetItem;
class SfxItemSet;
class Bitmap;

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

// #100127# Bracket filled shapes with a comment, if recording a Mtf
class ImpGraphicFill
{
public:
    ImpGraphicFill( const SdrObject& rObj, const XOutputDevice& rXOut, const SfxItemSet& rFillItemSet, bool bIsShadow=false );
    ~ImpGraphicFill();

private:
    const SdrObject&        mrObj;
    const XOutputDevice&    mrXOut;
    bool                    mbCommentWritten;
};

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

// #104609# Extracted from XOutputDevice::ImpCalcBmpFillStartValues

/** Calc offset and size for bitmap fill

    This method calculates the size and the offset from the left, top
    position of a shape in logical coordinates

    @param rStartOffset
    The offset from the left, top position of the output rectangle is returned

    @param rBmpOutputSize
    The output size of the bitmap is returned herein

    @param rOutputRect
    Specifies the output rectangle into which the bitmap should be tiled into

    @param rOutputMapMode
    Specifies the logical coordinate system the output rectangle is in

    @param rFillBitmap
    Specifies the bitmap to fill with

    @param rBmpSize
    The desired destination bitmap size. If null, size is taken from the bitmap

    @param rBmpPerCent
    Percentage of bitmap size, relative to the output rectangle

    @param rBmpOffPerCent
    Offset for bitmap tiling, in percentage relative to bitmap output size

    @param bBmpLogSize
    True when using the preferred bitmap size, False when using the percentage value

    @param bBmpTile
    True for tiling. False only paints one instance of the bitmap

    @param bBmpStretch
    True if bitmap should be stretched to output rect dimension

    @param eBmpRectPoint
    Position of the start point relative to the bitmap

 */
void ImpCalcBmpFillSizes( Size&            rStartOffset,
                          Size&            rBmpOutputSize,
                          const Rectangle& rOutputRect,
                          const MapMode&   rOutputMapMode,
                          const Bitmap&    rFillBitmap,
                          const Size&      rBmpSize,
                          const Size&      rBmpPerCent,
                          const Size&      rBmpOffPerCent,
                          BOOL             bBmpLogSize,
                          BOOL             bBmpTile,
                          BOOL             bBmpStretch,
                          RECT_POINT       eBmpRectPoint );

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

class ImpLineStyleParameterPack
{
    XLineJoint                      meLineJoint;
    basegfx::B2DPolyPolygon     maStartPolyPolygon;
    basegfx::B2DPolyPolygon     maEndPolyPolygon;

    sal_Int32                       mnLineWidth;
    sal_Int32                       mnStartWidth;
    sal_Int32                       mnEndWidth;

    ::std::vector<double>           maDotDashArray;
    double                          mfFullDotDashLen;
    double                          mfDegreeStepWidth;

    // bitfield
    unsigned                        mbStartCentered : 1;
    unsigned                        mbEndCentered : 1;
    unsigned                        mbForceNoArrowsLeft : 1;
    unsigned                        mbForceNoArrowsRight : 1;
    unsigned                        mbForceHair : 1;

    // flag for LineStyle. True is XLINE_SOLID, false is XLINE_DASH
    unsigned                        mbLineStyleSolid : 1;

public:
    ImpLineStyleParameterPack(const SfxItemSet& rSet, bool bForceHair);
    ~ImpLineStyleParameterPack();

    sal_Int32 GetLineWidth() const { return mnLineWidth; }
    sal_Int32 GetDisplayLineWidth() const { return mbForceHair ? 0L : mnLineWidth; }
    bool IsLineStyleSolid() const { return mbLineStyleSolid; }

    sal_Int32 GetStartWidth() const { return mnStartWidth; }
    sal_Int32 GetEndWidth() const { return mnEndWidth; }

    const basegfx::B2DPolyPolygon& GetStartPolyPolygon() const { return maStartPolyPolygon; }
    const basegfx::B2DPolyPolygon& GetEndPolyPolygon() const { return maEndPolyPolygon; }

    double GetDegreeStepWidth() const { return mfDegreeStepWidth; }

    XLineJoint GetLineJoint() const { return meLineJoint; }
    double GetLinejointMiterMinimumAngle() const { return 15.0; }

    double GetFullDotDashLen() const { return mfFullDotDashLen; }
    const ::std::vector< double >& GetDotDash() const { return maDotDashArray; }

    bool IsStartCentered() const { return mbStartCentered; }
    bool IsEndCentered() const { return mbEndCentered; }

    bool IsStartActive() const;
    bool IsEndActive() const;

    void ForceNoArrowsLeft(bool bNew) { mbForceNoArrowsLeft = bNew; }
    void ForceNoArrowsRight(bool bNew) { mbForceNoArrowsRight = bNew; }
};

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

class ImpLineGeometryCreator
{
    const ImpLineStyleParameterPack&        mrLineAttr;
    basegfx::B2DPolyPolygon&                maAreaPolyPolygon;
    basegfx::B2DPolyPolygon&                maLinePolyPolygon;

    // bitfield
    unsigned                                mbLineDraft : 1;

    // private support functions
    // help functions for line geometry creation
    void ImpCreateLineGeometry(
        const basegfx::B2DPolygon& rSourcePoly);

public:
    ImpLineGeometryCreator(
        const ImpLineStyleParameterPack& rAttr,
        basegfx::B2DPolyPolygon& rPoPo,
        basegfx::B2DPolyPolygon& rPoLi,
        bool bIsLineDraft = false)
    :   mrLineAttr(rAttr),
        maAreaPolyPolygon(rPoPo),
        maLinePolyPolygon(rPoLi),
        mbLineDraft(bIsLineDraft)
    {
    }

    void AddPolygon(const basegfx::B2DPolygon& rPoly) { ImpCreateLineGeometry(rPoly); }
    const basegfx::B2DPolyPolygon& GetAreaPolyPolygon() const { return maAreaPolyPolygon; }
    const basegfx::B2DPolyPolygon& GetLinePolyPolygon() const { return maLinePolyPolygon; }
};

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

class SdrLineGeometry
{
    basegfx::B2DPolyPolygon             maAreaPolyPolygon;
    basegfx::B2DPolyPolygon             maLinePolyPolygon;
    ImpLineStyleParameterPack               maLineAttr;

    // bitfield
    unsigned                                mbForceOnePixel : 1;
    unsigned                                mbForceTwoPixel : 1;

public:
    SdrLineGeometry(
        const basegfx::B2DPolyPolygon& rAreaPolyPolygon,
        const basegfx::B2DPolyPolygon& rLinePolyPolygon,
        const ImpLineStyleParameterPack& rLineAttr,
        bool bForceOnePixel,
        bool bForceTwoPixel)
    :   maAreaPolyPolygon(rAreaPolyPolygon),
        maLinePolyPolygon(rLinePolyPolygon),
        maLineAttr(rLineAttr),
        mbForceOnePixel(bForceOnePixel),
        mbForceTwoPixel(bForceTwoPixel)
    {}

    const basegfx::B2DPolyPolygon& GetAreaPolyPolygon() { return maAreaPolyPolygon; }
    const basegfx::B2DPolyPolygon& GetLinePolyPolygon() { return maLinePolyPolygon; }
    const ImpLineStyleParameterPack& GetLineAttr() { return maLineAttr; }
    bool DoForceOnePixel() const { return mbForceOnePixel; }
    bool DoForceTwoPixel() const { return mbForceTwoPixel; }
};

#endif // _SVX_SVDOIMP_HXX

// eof
<|endoftext|>


<commit_before><commit_msg>Reserve vector capacity in advance and avoid copying it<commit_after><|endoftext|>


<commit_before>/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the Willow Garage 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.
 *********************************************************************/

/* Author: Ioan Sucan */

#include "collision_detection/collision_world.h"
#include <geometric_shapes/shape_operations.h>
#include <ros/console.h>

collision_detection::CollisionWorld::CollisionWorld(void) : record_changes_(false)
{
}

collision_detection::CollisionWorld::CollisionWorld(const CollisionWorld &other) : record_changes_(false)
{
  objects_ = other.objects_;
}

void collision_detection::CollisionWorld::checkCollision(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot, const planning_models::KinematicState &state) const
{
  robot.checkSelfCollision(req, res, state);
  if (!res.collision || (req.contacts && res.contacts.size() < req.max_contacts))
    checkRobotCollision(req, res, robot, state);
}

void collision_detection::CollisionWorld::checkCollision(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot, const planning_models::KinematicState &state, const AllowedCollisionMatrix &acm) const
{
  robot.checkSelfCollision(req, res, state, acm);
  if (!res.collision || (req.contacts && res.contacts.size() < req.max_contacts))
    checkRobotCollision(req, res, robot, state, acm);
}

void collision_detection::CollisionWorld::checkCollision(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot,
                                                         const planning_models::KinematicState &state1, const planning_models::KinematicState &state2) const
{
  robot.checkSelfCollision(req, res, state1, state2);
  if (!res.collision || (req.contacts && res.contacts.size() < req.max_contacts))
    checkRobotCollision(req, res, robot, state1, state2);
}

void collision_detection::CollisionWorld::checkCollision(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot,
                                                         const planning_models::KinematicState &state1, const planning_models::KinematicState &state2, const AllowedCollisionMatrix &acm) const
{
  robot.checkSelfCollision(req, res, state1, state2, acm);
  if (!res.collision || (req.contacts && res.contacts.size() < req.max_contacts))
    checkRobotCollision(req, res, robot, state1, state2, acm);
}

void collision_detection::CollisionWorld::addToObject(const std::string &id, const std::vector<shapes::ShapeConstPtr> &shapes, const std::vector<Eigen::Affine3d> &poses)
{
  if (shapes.size() != poses.size())
    ROS_ERROR("Number of shapes and number of poses do not match. Not adding this object to collision world.");
  else
  {
    // make sure that if a new object is created, it knows its name
    std::map<std::string, ObjectPtr>::iterator it = objects_.find(id);
    if (it == objects_.end())
    {
      objects_[id].reset(new Object(id));
      it = objects_.find(id);
    }
    else
      if (record_changes_)
        changeRemoveObj(id);

    ensureUnique(it->second);
    for (std::size_t i = 0 ; i < shapes.size() ; ++i)
      addToObjectInternal(it->second, shapes[i], poses[i]);

    if (record_changes_)
      changeAddObj(it->second.get());
  }
}

std::vector<std::string> collision_detection::CollisionWorld::getObjectIds(void) const
{
  std::vector<std::string> id;
  for (std::map<std::string, ObjectPtr>::const_iterator it = objects_.begin() ; it != objects_.end() ; ++it)
    id.push_back(it->first);
  return id;
}

collision_detection::CollisionWorld::ObjectConstPtr collision_detection::CollisionWorld::getObject(const std::string &id) const
{
  static ObjectConstPtr empty;
  std::map<std::string, ObjectPtr>::const_iterator it = objects_.find(id);
  if (it == objects_.end())
    return empty;
  else
    return it->second;
}

bool collision_detection::CollisionWorld::hasObject(const std::string &id) const
{
  return objects_.find(id) != objects_.end();
}

void collision_detection::CollisionWorld::ensureUnique(ObjectPtr &id)
{
  if (id && !id.unique())
    id.reset(new Object(*id));
}

void collision_detection::CollisionWorld::addToObject(const std::string &id, const shapes::ShapeConstPtr &shape, const Eigen::Affine3d &pose)
{
  // make sure that if a new object is created, it knows its name
  std::map<std::string, ObjectPtr>::iterator it = objects_.find(id);
  if (it == objects_.end())
  {
    objects_[id].reset(new Object(id));
    it = objects_.find(id);
  }
  else
    if (record_changes_)
      changeRemoveObj(id);

  ensureUnique(it->second);
  addToObjectInternal(it->second, shape, pose);

  if (record_changes_)
    changeAddObj(it->second.get());
}

void collision_detection::CollisionWorld::addToObjectInternal(const ObjectPtr &obj, const shapes::ShapeConstPtr &shape, const Eigen::Affine3d &pose)
{
  obj->shapes_.push_back(shape);
  obj->shape_poses_.push_back(pose);
}

bool collision_detection::CollisionWorld::moveShapeInObject(const std::string &id, const shapes::ShapeConstPtr &shape, const Eigen::Affine3d &pose)
{
  std::map<std::string, ObjectPtr>::iterator it = objects_.find(id);
  if (it != objects_.end())
  {
    unsigned int n = it->second->shapes_.size();
    for (unsigned int i = 0 ; i < n ; ++i)
      if (it->second->shapes_[i] == shape)
      {
        ensureUnique(it->second);
        it->second->shape_poses_[i] = pose;

	if (record_changes_)
	{
	  changeRemoveObj(id);
	  changeAddObj(it->second.get());
	}
	return true;
      }
  }
  return false;
}

bool collision_detection::CollisionWorld::removeShapeFromObject(const std::string &id, const shapes::ShapeConstPtr &shape)
{
  std::map<std::string, ObjectPtr>::iterator it = objects_.find(id);
  if (it != objects_.end())
  {
    unsigned int n = it->second->shapes_.size();
    for (unsigned int i = 0 ; i < n ; ++i)
      if (it->second->shapes_[i] == shape)
      {
	ensureUnique(it->second);
	it->second->shapes_.erase(it->second->shapes_.begin() + i);
	it->second->shape_poses_.erase(it->second->shape_poses_.begin() + i);
	if (it->second->shapes_.empty())
	{
	  objects_.erase(it);
	  if (record_changes_)
	    changeRemoveObj(id);
	}
	else
	  if (record_changes_)
	  {
	    changeRemoveObj(id);
	    changeAddObj(it->second.get());
	  }
	return true;
      }
  }
  return false;
}

void collision_detection::CollisionWorld::removeObject(const std::string &id)
{
  if (objects_.erase(id) == 1)
    if (record_changes_)
      changeRemoveObj(id);
}

void collision_detection::CollisionWorld::clearObjects(void)
{
  if (record_changes_)
    for (std::map<std::string, ObjectPtr>::const_iterator it = objects_.begin() ; it != objects_.end() ; ++it)
      changeRemoveObj(it->first);
  objects_.clear();
}

collision_detection::CollisionWorld::Object::Object(const std::string &id) : id_(id)
{
}

void collision_detection::CollisionWorld::changeRemoveObj(const std::string &id)
{
  for (std::vector<Change>::reverse_iterator it = changes_.rbegin() ; it != changes_.rend() ; ++it)
    if (it->type_ == Change::ADD && it->id_ == id)
    {
      changes_.erase(--it.base());
      return;
    }
  Change c;
  c.type_ = Change::REMOVE;
  c.id_ = id;
  changes_.push_back(c);
}

void collision_detection::CollisionWorld::changeAddObj(const Object *obj)
{
  Change c;
  c.type_ = Change::ADD;
  c.id_ = obj->id_;
  changes_.push_back(c);
}

void collision_detection::CollisionWorld::recordChanges(bool flag)
{
  record_changes_ = flag;
}

bool collision_detection::CollisionWorld::isRecordingChanges(void) const
{
  return record_changes_;
}

const std::vector<collision_detection::CollisionWorld::Change>& collision_detection::CollisionWorld::getChanges(void) const
{
  return changes_;
}

void collision_detection::CollisionWorld::clearChanges(void)
{
  changes_.clear();
}

collision_detection::CollisionWorld::Object::~Object(void)
{
}
<commit_msg>Incremental changes for object adding and moving<commit_after>/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the Willow Garage 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.
 *********************************************************************/

/* Author: Ioan Sucan */

#include "collision_detection/collision_world.h"
#include <geometric_shapes/shape_operations.h>
#include <ros/console.h>

collision_detection::CollisionWorld::CollisionWorld(void) : record_changes_(false)
{
}

collision_detection::CollisionWorld::CollisionWorld(const CollisionWorld &other) : record_changes_(false)
{
  objects_ = other.objects_;
}

void collision_detection::CollisionWorld::checkCollision(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot, const planning_models::KinematicState &state) const
{
  robot.checkSelfCollision(req, res, state);
  if (!res.collision || (req.contacts && res.contacts.size() < req.max_contacts))
    checkRobotCollision(req, res, robot, state);
}

void collision_detection::CollisionWorld::checkCollision(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot, const planning_models::KinematicState &state, const AllowedCollisionMatrix &acm) const
{
  robot.checkSelfCollision(req, res, state, acm);
  if (!res.collision || (req.contacts && res.contacts.size() < req.max_contacts))
    checkRobotCollision(req, res, robot, state, acm);
}

void collision_detection::CollisionWorld::checkCollision(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot,
                                                         const planning_models::KinematicState &state1, const planning_models::KinematicState &state2) const
{
  robot.checkSelfCollision(req, res, state1, state2);
  if (!res.collision || (req.contacts && res.contacts.size() < req.max_contacts))
    checkRobotCollision(req, res, robot, state1, state2);
}

void collision_detection::CollisionWorld::checkCollision(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot,
                                                         const planning_models::KinematicState &state1, const planning_models::KinematicState &state2, const AllowedCollisionMatrix &acm) const
{
  robot.checkSelfCollision(req, res, state1, state2, acm);
  if (!res.collision || (req.contacts && res.contacts.size() < req.max_contacts))
    checkRobotCollision(req, res, robot, state1, state2, acm);
}

void collision_detection::CollisionWorld::addToObject(const std::string &id, const std::vector<shapes::ShapeConstPtr> &shapes, const std::vector<Eigen::Affine3d> &poses)
{
  if (shapes.size() != poses.size())
    ROS_ERROR("Number of shapes and number of poses do not match. Not adding this object to collision world.");
  else
  {
    // make sure that if a new object is created, it knows its name
    std::map<std::string, ObjectPtr>::iterator it = objects_.find(id);
    if (it == objects_.end())
    {
      objects_[id].reset(new Object(id));
      it = objects_.find(id);
    }
    else
      if (record_changes_)
        changeRemoveObj(id);

    ensureUnique(it->second);
    for (std::size_t i = 0 ; i < shapes.size() ; ++i)
      addToObjectInternal(it->second, shapes[i], poses[i]);

    if (record_changes_)
      changeAddObj(it->second.get());
  }
}

std::vector<std::string> collision_detection::CollisionWorld::getObjectIds(void) const
{
  std::vector<std::string> id;
  for (std::map<std::string, ObjectPtr>::const_iterator it = objects_.begin() ; it != objects_.end() ; ++it)
    id.push_back(it->first);
  return id;
}

collision_detection::CollisionWorld::ObjectConstPtr collision_detection::CollisionWorld::getObject(const std::string &id) const
{
  static ObjectConstPtr empty;
  std::map<std::string, ObjectPtr>::const_iterator it = objects_.find(id);
  if (it == objects_.end())
    return empty;
  else
    return it->second;
}

bool collision_detection::CollisionWorld::hasObject(const std::string &id) const
{
  return objects_.find(id) != objects_.end();
}

void collision_detection::CollisionWorld::ensureUnique(ObjectPtr &id)
{
  if (id && !id.unique()) {
    ROS_INFO_STREAM("New obj");
    id.reset(new Object(*id));
  }
}

void collision_detection::CollisionWorld::addToObject(const std::string &id, const shapes::ShapeConstPtr &shape, const Eigen::Affine3d &pose)
{
  // make sure that if a new object is created, it knows its name
  std::map<std::string, ObjectPtr>::iterator it = objects_.find(id);
  if (it == objects_.end())
  {
    objects_[id].reset(new Object(id));
    it = objects_.find(id);
  }
  else
    if (record_changes_)
      changeRemoveObj(id);

  ensureUnique(it->second);
  addToObjectInternal(it->second, shape, pose);

  if (record_changes_)
    changeAddObj(it->second.get());
}

void collision_detection::CollisionWorld::addToObjectInternal(const ObjectPtr &obj, const shapes::ShapeConstPtr &shape, const Eigen::Affine3d &pose)
{
  obj->shapes_.push_back(shape);
  obj->shape_poses_.push_back(pose);
}

bool collision_detection::CollisionWorld::moveShapeInObject(const std::string &id, const shapes::ShapeConstPtr &shape, const Eigen::Affine3d &pose)
{
  std::map<std::string, ObjectPtr>::iterator it = objects_.find(id);
  if (it != objects_.end())
  {
    unsigned int n = it->second->shapes_.size();
    for (unsigned int i = 0 ; i < n ; ++i)
      if (it->second->shapes_[i] == shape)
      {
        ensureUnique(it->second);
        it->second->shape_poses_[i] = pose;

	if (record_changes_)
	{
	  changeRemoveObj(id);
	  changeAddObj(it->second.get());
	}
	return true;
      }
  }
  return false;
}

bool collision_detection::CollisionWorld::removeShapeFromObject(const std::string &id, const shapes::ShapeConstPtr &shape)
{
  std::map<std::string, ObjectPtr>::iterator it = objects_.find(id);
  if (it != objects_.end())
  {
    unsigned int n = it->second->shapes_.size();
    for (unsigned int i = 0 ; i < n ; ++i)
      if (it->second->shapes_[i] == shape)
      {
	ensureUnique(it->second);
	it->second->shapes_.erase(it->second->shapes_.begin() + i);
	it->second->shape_poses_.erase(it->second->shape_poses_.begin() + i);
	if (it->second->shapes_.empty())
	{
	  objects_.erase(it);
	  if (record_changes_)
	    changeRemoveObj(id);
	}
	else
	  if (record_changes_)
	  {
	    changeRemoveObj(id);
	    changeAddObj(it->second.get());
	  }
	return true;
      }
  }
  return false;
}

void collision_detection::CollisionWorld::removeObject(const std::string &id)
{
  if (objects_.erase(id) == 1)
    if (record_changes_)
      changeRemoveObj(id);
}

void collision_detection::CollisionWorld::clearObjects(void)
{
  if (record_changes_)
    for (std::map<std::string, ObjectPtr>::const_iterator it = objects_.begin() ; it != objects_.end() ; ++it)
      changeRemoveObj(it->first);
  objects_.clear();
}

collision_detection::CollisionWorld::Object::Object(const std::string &id) : id_(id)
{
}

void collision_detection::CollisionWorld::changeRemoveObj(const std::string &id)
{
  for (std::vector<Change>::reverse_iterator it = changes_.rbegin() ; it != changes_.rend() ; ++it)
    if (it->type_ == Change::ADD && it->id_ == id)
    {
      changes_.erase(--it.base());
      return;
    }
  Change c;
  c.type_ = Change::REMOVE;
  c.id_ = id;
  changes_.push_back(c);
}

void collision_detection::CollisionWorld::changeAddObj(const Object *obj)
{
  Change c;
  c.type_ = Change::ADD;
  c.id_ = obj->id_;
  changes_.push_back(c);
}

void collision_detection::CollisionWorld::recordChanges(bool flag)
{
  record_changes_ = flag;
}

bool collision_detection::CollisionWorld::isRecordingChanges(void) const
{
  return record_changes_;
}

const std::vector<collision_detection::CollisionWorld::Change>& collision_detection::CollisionWorld::getChanges(void) const
{
  return changes_;
}

void collision_detection::CollisionWorld::clearChanges(void)
{
  changes_.clear();
}

collision_detection::CollisionWorld::Object::~Object(void)
{
}
<|endoftext|>


<commit_before>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * 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.
 */

<commit_msg>Deleted unused and empty NOTATION.cpp file.<commit_after><|endoftext|>


<commit_before>#pragma once

/** ==========================================================================
 * 2011 by KjellKod.cc. This is PUBLIC DOMAIN to use at your own risk and comes
 * with no warranties. This code is yours to share, use and modify with no
 * strings attached and no restrictions or obligations.
 *
 * For more information see g3log/LICENSE or refer refer to http://unlicense.org
 * ============================================================================*/
#include <string>
#include "g3log/loglevels.hpp"
#include "g3log/generated_definitions.hpp"

// kjell. Separera på crashhandler.hpp och crashhanlder_internal.hpp
// implementationsfilen kan vara den samma
namespace g3 {

   // PUBLIC API:
   /** Install signal handler that catches FATAL C-runtime or OS signals
     See the wikipedia site for details http://en.wikipedia.org/wiki/SIGFPE
     See the this site for example usage: http://www.tutorialspoint.com/cplusplus/cpp_signal_handling.hpptm
     SIGABRT  ABORT (ANSI), abnormal termination
     SIGFPE   Floating point exception (ANSI)
     SIGILL   ILlegal instruction (ANSI)
     SIGSEGV  Segmentation violation i.e. illegal memory reference
     SIGTERM  TERMINATION (ANSI)  */
   void installCrashHandler();

#if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__))
   typedef unsigned long SignalType;
   ///  SIGFPE, SIGILL, and SIGSEGV handling must be installed per thread
   /// on Windows. This is automatically done if you do at least one LOG(...) call
   /// you can also use this function call, per thread so make sure these three
   /// fatal signals are covered in your thread (even if you don't do a LOG(...) call
   void installSignalHandlerForThread();
#else
   typedef int SignalType;

   /// Probably only needed for unit testing. Resets the signal handling back to default
   /// which might be needed in case it was previously overridden
   /// The default signals are: SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGTERM
   void restoreSignalHandlerToDefault();

   /// Overrides the existing signal handling for custom signals
   /// For example: usage of zcmq relies on its own signal handler for SIGTERM
   ///     so users of g3log with zcmq should then use the @ref overrideSetupSignals
   ///     , likely with the original set of signals but with SIGTERM removed
   ///
   /// call example:
   ///  g3::overrideSetupSignals({ {SIGABRT, "SIGABRT"}, {SIGFPE, "SIGFPE"},{SIGILL, "SIGILL"},
   //                          {SIGSEGV, "SIGSEGV"},});
   void overrideSetupSignals(const std::map<int, std::string> overrideSignals);
#endif

   namespace internal {
      /** return whether or any fatal handling is still ongoing
       *  this is used by g3log::fatalCallToLogger
       *  only in the case of Windows exceptions (not fatal signals)
       *  are we interested in changing this from false to true to
       *  help any other exceptions handler work with 'EXCEPTION_CONTINUE_SEARCH'*/
      bool shouldBlockForFatalHandling();

      /** \return signal_name Ref: signum.hpp and \ref installSignalHandler
      *  or for Windows exception name */
      std::string exitReasonName(const LEVELS& level, g3::SignalType signal_number);

      /** return calling thread's stackdump*/
      std::string stackdump(const char* dump = nullptr);

      /** Re-"throw" a fatal signal, previously caught. This will exit the application
       * This is an internal only function. Do not use it elsewhere. It is triggered
       * from g3log, g3LogWorker after flushing messages to file */
      void exitWithDefaultSignalHandler(const LEVELS& level, g3::SignalType signal_number);
   } // end g3::internal
} // g3
<commit_msg>fix build lib<commit_after>#pragma once

/** ==========================================================================
 * 2011 by KjellKod.cc. This is PUBLIC DOMAIN to use at your own risk and comes
 * with no warranties. This code is yours to share, use and modify with no
 * strings attached and no restrictions or obligations.
 *
 * For more information see g3log/LICENSE or refer refer to http://unlicense.org
 * ============================================================================*/
#include <string>
#include <map>
#include "g3log/loglevels.hpp"
#include "g3log/generated_definitions.hpp"

// kjell. Separera på crashhandler.hpp och crashhanlder_internal.hpp
// implementationsfilen kan vara den samma
namespace g3 {

   // PUBLIC API:
   /** Install signal handler that catches FATAL C-runtime or OS signals
     See the wikipedia site for details http://en.wikipedia.org/wiki/SIGFPE
     See the this site for example usage: http://www.tutorialspoint.com/cplusplus/cpp_signal_handling.hpptm
     SIGABRT  ABORT (ANSI), abnormal termination
     SIGFPE   Floating point exception (ANSI)
     SIGILL   ILlegal instruction (ANSI)
     SIGSEGV  Segmentation violation i.e. illegal memory reference
     SIGTERM  TERMINATION (ANSI)  */
   void installCrashHandler();

#if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__))
   typedef unsigned long SignalType;
   ///  SIGFPE, SIGILL, and SIGSEGV handling must be installed per thread
   /// on Windows. This is automatically done if you do at least one LOG(...) call
   /// you can also use this function call, per thread so make sure these three
   /// fatal signals are covered in your thread (even if you don't do a LOG(...) call
   void installSignalHandlerForThread();
#else
   typedef int SignalType;

   /// Probably only needed for unit testing. Resets the signal handling back to default
   /// which might be needed in case it was previously overridden
   /// The default signals are: SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGTERM
   void restoreSignalHandlerToDefault();

   /// Overrides the existing signal handling for custom signals
   /// For example: usage of zcmq relies on its own signal handler for SIGTERM
   ///     so users of g3log with zcmq should then use the @ref overrideSetupSignals
   ///     , likely with the original set of signals but with SIGTERM removed
   ///
   /// call example:
   ///  g3::overrideSetupSignals({ {SIGABRT, "SIGABRT"}, {SIGFPE, "SIGFPE"},{SIGILL, "SIGILL"},
   //                          {SIGSEGV, "SIGSEGV"},});
   void overrideSetupSignals(const std::map<int, std::string> overrideSignals);
#endif

   namespace internal {
      /** return whether or any fatal handling is still ongoing
       *  this is used by g3log::fatalCallToLogger
       *  only in the case of Windows exceptions (not fatal signals)
       *  are we interested in changing this from false to true to
       *  help any other exceptions handler work with 'EXCEPTION_CONTINUE_SEARCH'*/
      bool shouldBlockForFatalHandling();

      /** \return signal_name Ref: signum.hpp and \ref installSignalHandler
      *  or for Windows exception name */
      std::string exitReasonName(const LEVELS& level, g3::SignalType signal_number);

      /** return calling thread's stackdump*/
      std::string stackdump(const char* dump = nullptr);

      /** Re-"throw" a fatal signal, previously caught. This will exit the application
       * This is an internal only function. Do not use it elsewhere. It is triggered
       * from g3log, g3LogWorker after flushing messages to file */
      void exitWithDefaultSignalHandler(const LEVELS& level, g3::SignalType signal_number);
   } // end g3::internal
} // g3
<|endoftext|>


<commit_before>#ifndef MJOLNIR_MULTIPLE_LOCAL_POTENTIAL
#define MJOLNIR_MULTIPLE_LOCAL_POTENTIAL
#include <tuple>

namespace mjolnir
{
template<typename T> class System;

template<typename traitsT, template<typename>class ... Ts>
class MultipleLocalPotential
{
  public:
    typedef traitsT traits_type;
    typedef System<traits_type> system_type;
    typedef typename traits_type::real_type real_type;
    constexpr static std::size_t multiplicity = sizeof...(Ts);

  public:

    MultipleLocalPotential(Ts<traits_type> const& ... args)
        : potentials_(args...)
    {}
    MultipleLocalPotential(Ts<traits_type>&& ... args)
        : potentials_(std::move(args)...)
    {}
    ~MultipleLocalPotential() = default;

    real_type potential(const real_type x) const
    {
        return accumurate_potentials<0, multiplicity>::invoke(potentials_, x);
    }

    real_type derivative(const real_type x) const
    {
        return accumurate_derivatives<0, multiplicity>::invoke(potentials_, x);
    }

    void update(const system_type&, const real_type) const noexcept {return;}

  private:

    template<std::size_t I, std::size_t N>
    struct accumurate_potentials
    {
        static constexpr real_type
        invoke(const std::tuple<Ts<traits_type>...>& pots, const real_type x)
        {
            return std::get<I>(pots).potential(x) +
                   accumurate_potentials<I+1, N>::invoke(pots, x);
        }
    };
    template<std::size_t N>
    struct accumurate_potentials<N, N>
    {
        static constexpr real_type
        invoke(const std::tuple<Ts<traits_type>...>& pots, const real_type x)
        {
            return 0.;
        }
    };

    template<std::size_t I, std::size_t N>
    struct accumurate_derivatives
    {
        static constexpr real_type
        invoke(const std::tuple<Ts<traits_type>...>& pots, const real_type x)
        {
            return std::get<I>(pots).derivative(x) +
                   accumurate_derivatives<I+1, N>::invoke(pots, x);
        }
    };
    template<std::size_t N>
    struct accumurate_derivatives<N, N>
    {
        static constexpr real_type
        invoke(const std::tuple<Ts<traits_type>...>& pots, const real_type x)
        {
            return 0.;
        }
    };

  private:
    std::tuple<Ts<traits_type>...> potentials_;
};

}
#endif//MJOLNIR_MULTIPLE_LOCAL_POTENTIAL
<commit_msg>collect names in multiple local potentials<commit_after>#ifndef MJOLNIR_MULTIPLE_LOCAL_POTENTIAL
#define MJOLNIR_MULTIPLE_LOCAL_POTENTIAL
#include <tuple>

namespace mjolnir
{
template<typename T> class System;

template<typename traitsT, template<typename>class ... Ts>
class MultipleLocalPotential
{
  public:
    typedef traitsT traits_type;
    typedef System<traits_type> system_type;
    typedef typename traits_type::real_type real_type;
    constexpr static std::size_t multiplicity = sizeof...(Ts);

  public:

    MultipleLocalPotential(Ts<traits_type> const& ... args)
        : potentials_(args...)
    {}
    MultipleLocalPotential(Ts<traits_type>&& ... args)
        : potentials_(std::move(args)...)
    {}
    ~MultipleLocalPotential() = default;

    real_type potential(const real_type x) const
    {
        return accumurate_potentials<0, multiplicity>::invoke(potentials_, x);
    }

    real_type derivative(const real_type x) const
    {
        return accumurate_derivatives<0, multiplicity>::invoke(potentials_, x);
    }

    void update(const system_type&, const real_type) const noexcept {return;}

    std::string name() const
    {
        return collect_names<0, multiplicity>::invoke(this->potentials_);
    }

  private:

    template<std::size_t I, std::size_t N>
    struct accumurate_potentials
    {
        static constexpr real_type
        invoke(const std::tuple<Ts<traits_type>...>& pots, const real_type x)
        {
            return std::get<I>(pots).potential(x) +
                   accumurate_potentials<I+1, N>::invoke(pots, x);
        }
    };
    template<std::size_t N>
    struct accumurate_potentials<N, N>
    {
        static constexpr real_type
        invoke(const std::tuple<Ts<traits_type>...>& pots, const real_type x)
        {
            return 0.;
        }
    };

    template<std::size_t I, std::size_t N>
    struct accumurate_derivatives
    {
        static constexpr real_type
        invoke(const std::tuple<Ts<traits_type>...>& pots, const real_type x)
        {
            return std::get<I>(pots).derivative(x) +
                   accumurate_derivatives<I+1, N>::invoke(pots, x);
        }
    };
    template<std::size_t N>
    struct accumurate_derivatives<N, N>
    {
        static constexpr real_type
        invoke(const std::tuple<Ts<traits_type>...>& pots, const real_type x)
        {
            return 0.;
        }
    };

    template<std::size_t I, std::size_t N>
    struct collect_names
    {
        static std::string
        invoke(const std::tuple<Ts<traits_type>...>& pots)
        {
            return std::string(":") + std::string(std::get<I>(pots).name()) +
                   accumurate_potentials<I+1, N>::invoke(pots);
        }
    };
    template<std::size_t N>
    struct collect_names<0, N>
    {
        static std::string
        invoke(const std::tuple<Ts<traits_type>...>& pots)
        {
            return std::string(std::get<I>(pots).name()) +
                   accumurate_potentials<I+1, N>::invoke(pots);
        }
    };
    template<std::size_t N>
    struct collect_names<N, N>
    {
        static std::string
        invoke(const std::tuple<Ts<traits_type>...>& pots)
        {
            return "";
        }
    };

  private:
    std::tuple<Ts<traits_type>...> potentials_;
};
template<typename traitsT, template<typename>class ... Ts>
constexpr std::size_t MultipleLocalPotential<traitsT, Ts...>::multiplicity;

} // mjolnir
#endif//MJOLNIR_MULTIPLE_LOCAL_POTENTIAL
<|endoftext|>


<commit_before>// FIXME Lock for _read() method - listen()/_read() may start even when object is already reading. this has to be disabled!
// FIXME close() only if FIFO is open.
// FIXME maybe split close() to close() and _kill() - _kill() into destructor -- kill MUST NEVER throw/fail.
// FIXME catch references
// LICENSE/*{{{*/
/*
  sxc - Simple Xmpp Client
  Copyright (C) 2008 Dennis Felsing, Andreas Waidler

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

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

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

/* $Id$ */

#ifndef FILE_INPUTBASE_HXX
#define FILE_INPUTBASE_HXX

// INCLUDES/*{{{*/

#include <string>
#include <fstream>
#include <pthread.h>

/*}}}*/

namespace File
{
    /**
     * @author Andreas Waidler
     * @brief Abstract Base Class handling input (FIFOs).
     *
     * Handles creation and checking of, listening (non-blocking) on and reading
     * (blocking) off FIFOs.
     * Contains pure virtual methods that will define the location of the FIFO
     * and how the input is handled.
     */
    class InputBase
    {
        public:
            // InputBase();/*{{{*/

            /// Constructor, initializes private variables with default values.
            InputBase();

/*}}}*/
            // virtual ~InputBase();/*{{{*/

            /**
             * @brief Destructor, frees resources and cleans up.
             *
             * Takes care of a clean termination of the thread if running.
             * Closes the FIFO if open.
             */
            virtual ~InputBase();

/*}}}*/
            // void initialize();/*{{{*/

            /**
             * @brief Initializes the object.
             *
             * Calls @ref _createPath() to set @ref _path. Tries to create
             * the FIFO or checks its permissions by calling @ref _tryCreate()
             * or @ref _validateFile().
             *
             * @note This method has to be called before any other method can
             *       be used! You may want to call it in the constructor of
             *       the childs.
             *
             * @warning Do not override this method!
             */
            void initialize();

/*}}}*/
            // void listen(bool blocking = false);/*{{{*/

            /**
             * @brief Initiates listening on the FIFO.
             *
             * If @a blocking is set to @c true this method will read blocking,
             * i.e. it will finish when @ref close() is run. Per default, @a
             * blocking is @c false.
             *
             * This method creates a thread that executes @ref _listen()
             * which will run in the background. If @a blocking is true @c
             * pthread_join() is called which causes this method to wait until
             * the thread terminates.
             *
             * @warning Do not override this method!
             *
             * @param blocking Specifies whether this method should listen
             * blocking or non-blocking.
             */
            void listen(bool blocking = false);

/*}}}*/

        protected:

        private:
            /// The path including file name where the FIFO is located.
            std::string _path;
            /// The FIFO from which will be read.
            std::fstream _fifo;
            /// Indicates whether @ref _fifo is valid.
            bool _isFifoValid;
            /// The thread running @ref _listen
            pthread_t _thread;
            /// Indicates whether @ref _thread is running.
            bool _isThreadRunning;
            /// Indicates whether @ref _read() or @ref listen() are active.
            bool _isLocked;
            // virtual const std::string &_createPath() const = 0;/*{{{*/

            /**
             * @brief Returns the path and file name of the FIFO.
             *
             * Called by @ref initialize() which stores the result in @ref _path
             * which is used throughout the class in the other methods.
             *
             * @note Pure virtual.
             *
             * @return Path and file name where the FIFO should be placed.
             */
            virtual const std::string &_createPath() const = 0;

/*}}}*/
            // virtual void _handleInput(std::string input) = 0;/*{{{*/

            /**
             * @brief Handles input that has been written into the FIFO.
             *
             * @note Pure virtual.
             *
             * @param input Something that has been written into the FIFO.
             */
            virtual void _handleInput(std::string input) = 0;

/*}}}*/
            // void _create();/*{{{*/

            /** Creates the FIFO.
             *
             * @exception Exception::FileInputException When the file could not
             *            be created. @c Exception::Type is the result of
             *            @ref Exception::errnoToType().
             */
            void _create();

/*}}}*/
            // void _validateFile();/*{{{*/

            /**
             * @brief Checks the FIFO for validity and throws an exception if
             *        something is not like expected.
             *
             * The FIFOs owner-uid has to be the one who runs this program.
             * Additionally, the FIFO must @b not be readable or writable for
             * other users. (chmod 600).
             *
             * @exception Exception::FileInputException When file is invalid.
             *            @ref Exception::Type will be @ref BadFile or @c errno
             *            converted to Type by @ref Exception::errnoToType().
             */

            void _validateFile();

/*}}}*/
            // void _read();/*{{{*/

            /**
             * @brief Reads the FIFO blocking until the other end is closed.
             *
             * Input is handled by calling @ref _handleInput().
             *
             * @warning Do not override this method!
             */
            void _read();

/*}}}*/
            // static void *_listen(void *fifo);/*{{{*/

            /**
             * @brief Listens blocking on the passed FIFO.
             *
             * Runs an infinite loop on @ref _read() of the object @a fifo.
             *
             * @warning Should only be called by a pthread created in @ref
             *          listen. This method will never stop by itsself, thus
             *          its thread has to be canceled.
             * @warning The parameter @a fifo should not be anything other than
             *          a this-pointer.
             *
             * @param fifo Pointer to object of class InputBase.
             * @return NULL
             * @see InputBase::listen()
             * @see InputBase::close()
             * @see InputBase::_read()
             */
            static void *_listen(void *fifo);

/*}}}*/
            // void close();/*{{{*/

            /**
             * @brief Closes the FIFO.
             *
             * Closes the FIFO and cancles the thread, if running.
             *
             * @warning Do not override this method!
             */
            void close();

/*}}}*/
    };
}

#endif // FILE_INPUTBASE_HXX

// Use no tabs at all; four spaces indentation; max. eighty chars per line.
// vim: et ts=4 sw=4 tw=80 fo+=c fdm=marker
<commit_msg>Changed visibility of following methods of InputBase from private to protected without renaming them: * _create() * close() * _validateFile<commit_after>// FIXME Lock for _read() method - listen()/_read() may start even when object is already reading. this has to be disabled!
// FIXME close() only if FIFO is open.
// FIXME maybe split close() to close() and _kill() - _kill() into destructor -- kill MUST NEVER throw/fail.
// FIXME catch references
// LICENSE/*{{{*/
/*
  sxc - Simple Xmpp Client
  Copyright (C) 2008 Dennis Felsing, Andreas Waidler

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

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

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

/* $Id$ */

#ifndef FILE_INPUTBASE_HXX
#define FILE_INPUTBASE_HXX

// INCLUDES/*{{{*/

#include <string>
#include <fstream>
#include <pthread.h>

/*}}}*/

namespace File
{
    /**
     * @author Andreas Waidler
     * @brief Abstract Base Class handling input (FIFOs).
     *
     * Handles creation and checking of, listening (non-blocking) on and reading
     * (blocking) off FIFOs.
     * Contains pure virtual methods that will define the location of the FIFO
     * and how the input is handled.
     */
    class InputBase
    {
        public:
            // InputBase();/*{{{*/

            /// Constructor, initializes private variables with default values.
            InputBase();

/*}}}*/
            // virtual ~InputBase();/*{{{*/

            /**
             * @brief Destructor, frees resources and cleans up.
             *
             * Takes care of a clean termination of the thread if running.
             * Closes the FIFO if open.
             */
            virtual ~InputBase();

/*}}}*/
            // void initialize();/*{{{*/

            /**
             * @brief Initializes the object.
             *
             * Calls @ref _createPath() to set @ref _path. Tries to create
             * the FIFO or checks its permissions by calling @ref _tryCreate()
             * or @ref _validateFile().
             *
             * @note This method has to be called before any other method can
             *       be used! You may want to call it in the constructor of
             *       the childs.
             *
             * @warning Do not override this method!
             */
            void initialize();

/*}}}*/
            // void listen(bool blocking = false);/*{{{*/

            /**
             * @brief Initiates listening on the FIFO.
             *
             * If @a blocking is set to @c true this method will read blocking,
             * i.e. it will finish when @ref close() is run. Per default, @a
             * blocking is @c false.
             *
             * This method creates a thread that executes @ref _listen()
             * which will run in the background. If @a blocking is true @c
             * pthread_join() is called which causes this method to wait until
             * the thread terminates.
             *
             * @warning Do not override this method!
             *
             * @param blocking Specifies whether this method should listen
             * blocking or non-blocking.
             */
            void listen(bool blocking = false);

/*}}}*/

        protected:
            // void _create();/*{{{*/

            /** Creates the FIFO.
             *
             * @exception Exception::FileInputException When the file could not
             *            be created. @c Exception::Type is the result of
             *            @ref Exception::errnoToType().
             */
            void _create();

/*}}}*/
            // void close();/*{{{*/

            /**
             * @brief Closes the FIFO.
             *
             * Closes the FIFO and cancles the thread, if running.
             *
             * @warning Do not override this method!
             */
            void close();

/*}}}*/
            // void _validateFile();/*{{{*/

            /**
             * @brief Checks the FIFO for validity and throws an exception if
             *        something is not like expected.
             *
             * The FIFOs owner-uid has to be the one who runs this program.
             * Additionally, the FIFO must @b not be readable or writable for
             * other users. (chmod 600).
             *
             * @exception Exception::FileInputException When file is invalid.
             *            @ref Exception::Type will be @ref BadFile or @c errno
             *            converted to Type by @ref Exception::errnoToType().
             */

            void _validateFile();

/*}}}*/

        private:
            /// The path including file name where the FIFO is located.
            std::string _path;
            /// The FIFO from which will be read.
            std::fstream _fifo;
            /// Indicates whether @ref _fifo is valid.
            bool _isFifoValid;
            /// The thread running @ref _listen
            pthread_t _thread;
            /// Indicates whether @ref _thread is running.
            bool _isThreadRunning;
            /// Indicates whether @ref _read() or @ref listen() are active.
            bool _isLocked;
            // virtual const std::string &_createPath() const = 0;/*{{{*/

            /**
             * @brief Returns the path and file name of the FIFO.
             *
             * Called by @ref initialize() which stores the result in @ref _path
             * which is used throughout the class in the other methods.
             *
             * @note Pure virtual.
             *
             * @return Path and file name where the FIFO should be placed.
             */
            virtual const std::string &_createPath() const = 0;

/*}}}*/
            // virtual void _handleInput(std::string input) = 0;/*{{{*/

            /**
             * @brief Handles input that has been written into the FIFO.
             *
             * @note Pure virtual.
             *
             * @param input Something that has been written into the FIFO.
             */
            virtual void _handleInput(std::string input) = 0;

/*}}}*/
            // void _read();/*{{{*/

            /**
             * @brief Reads the FIFO blocking until the other end is closed.
             *
             * Input is handled by calling @ref _handleInput().
             *
             * @warning Do not override this method!
             */
            void _read();

/*}}}*/
            // static void *_listen(void *fifo);/*{{{*/

            /**
             * @brief Listens blocking on the passed FIFO.
             *
             * Runs an infinite loop on @ref _read() of the object @a fifo.
             *
             * @warning Should only be called by a pthread created in @ref
             *          listen. This method will never stop by itsself, thus
             *          its thread has to be canceled.
             * @warning The parameter @a fifo should not be anything other than
             *          a this-pointer.
             *
             * @param fifo Pointer to object of class InputBase.
             * @return NULL
             * @see InputBase::listen()
             * @see InputBase::close()
             * @see InputBase::_read()
             */
            static void *_listen(void *fifo);

/*}}}*/
    };
}

#endif // FILE_INPUTBASE_HXX

// Use no tabs at all; four spaces indentation; max. eighty chars per line.
// vim: et ts=4 sw=4 tw=80 fo+=c fdm=marker
<|endoftext|>