<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * 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.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_comphelper.hxx"
#include <comphelper/propstate.hxx>
#include <com/sun/star/uno/genfunc.h>
#include <cppuhelper/queryinterface.hxx>
#include <comphelper/sequence.hxx>
#include <rtl/instance.hxx>

//.........................................................................
namespace comphelper
{
//.........................................................................

    using ::com::sun::star::uno::Reference;
    using ::com::sun::star::uno::Type;
    using ::com::sun::star::uno::RuntimeException;
    using ::com::sun::star::uno::Sequence;
    using ::com::sun::star::lang::XTypeProvider;
    using ::com::sun::star::uno::Any;
    using ::com::sun::star::uno::cpp_queryInterface;
    using ::com::sun::star::uno::cpp_release;
    using ::com::sun::star::beans::PropertyState_DEFAULT_VALUE;
    using ::com::sun::star::beans::PropertyState_DIRECT_VALUE;

    //=====================================================================
    // OPropertyStateHelper
    //=====================================================================

    //---------------------------------------------------------------------
    ::com::sun::star::uno::Any SAL_CALL OPropertyStateHelper::queryInterface(const  ::com::sun::star::uno::Type& _rType) throw( ::com::sun::star::uno::RuntimeException)
    {
        ::com::sun::star::uno::Any aReturn = OPropertySetHelper::queryInterface(_rType);
        // our own ifaces
        if ( !aReturn.hasValue() )
            aReturn = ::cppu::queryInterface(_rType, static_cast< ::com::sun::star::beans::XPropertyState*>(this));

        return aReturn;
    }

    //---------------------------------------------------------------------
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> OPropertyStateHelper::getTypes() throw( ::com::sun::star::uno::RuntimeException)
    {
        static  ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> aTypes;
        if (!aTypes.getLength())
        {
            aTypes.realloc(4);
            ::com::sun::star::uno::Type* pTypes = aTypes.getArray();
            // base class types
            pTypes[0] = getCppuType(( ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>*)NULL);
            pTypes[1] = getCppuType(( ::com::sun::star::uno::Reference< ::com::sun::star::beans::XMultiPropertySet>*)NULL);
            pTypes[2] = getCppuType(( ::com::sun::star::uno::Reference< ::com::sun::star::beans::XFastPropertySet>*)NULL);
            // my own type
            pTypes[3] = getCppuType(( ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyState>*)NULL);
        }
        return aTypes;
    }

    OPropertyStateHelper::OPropertyStateHelper(
        ::cppu::OBroadcastHelper& rBHlp,
        ::cppu::IEventNotificationHook *i_pFireEvents)
        :   ::cppu::OPropertySetHelper(rBHlp, i_pFireEvents) { }

    OPropertyStateHelper::~OPropertyStateHelper() {}

    //---------------------------------------------------------------------
    void OPropertyStateHelper::firePropertyChange(sal_Int32 nHandle, const  ::com::sun::star::uno::Any& aNewValue, const  ::com::sun::star::uno::Any& aOldValue)
    {
        fire(&nHandle, &aNewValue, &aOldValue, 1, sal_False);
    }

    // XPropertyState
    //---------------------------------------------------------------------
    ::com::sun::star::beans::PropertyState SAL_CALL OPropertyStateHelper::getPropertyState(const ::rtl::OUString& _rsName) throw( ::com::sun::star::beans::UnknownPropertyException,  ::com::sun::star::uno::RuntimeException)
    {
        cppu::IPropertyArrayHelper& rPH = getInfoHelper();
        sal_Int32 nHandle = rPH.getHandleByName(_rsName);

        if (nHandle == -1)
            throw  ::com::sun::star::beans::UnknownPropertyException();

        return getPropertyStateByHandle(nHandle);
    }

    //---------------------------------------------------------------------
    void SAL_CALL OPropertyStateHelper::setPropertyToDefault(const ::rtl::OUString& _rsName) throw( ::com::sun::star::beans::UnknownPropertyException,  ::com::sun::star::uno::RuntimeException)
    {
        cppu::IPropertyArrayHelper& rPH = getInfoHelper();
        sal_Int32 nHandle = rPH.getHandleByName(_rsName);

        if (nHandle == -1)
            throw  ::com::sun::star::beans::UnknownPropertyException();

        setPropertyToDefaultByHandle(nHandle);
    }

    //---------------------------------------------------------------------
    ::com::sun::star::uno::Any SAL_CALL OPropertyStateHelper::getPropertyDefault(const ::rtl::OUString& _rsName) throw( ::com::sun::star::beans::UnknownPropertyException,  ::com::sun::star::lang::WrappedTargetException,  ::com::sun::star::uno::RuntimeException)
    {
        cppu::IPropertyArrayHelper& rPH = getInfoHelper();
        sal_Int32 nHandle = rPH.getHandleByName(_rsName);

        if (nHandle == -1)
            throw  ::com::sun::star::beans::UnknownPropertyException();

        return getPropertyDefaultByHandle(nHandle);
    }

    //---------------------------------------------------------------------
    ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyState> SAL_CALL OPropertyStateHelper::getPropertyStates(const  ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rPropertyNames) throw( ::com::sun::star::beans::UnknownPropertyException,  ::com::sun::star::uno::RuntimeException)
    {
        sal_Int32 nLen = _rPropertyNames.getLength();
        ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyState> aRet(nLen);
        ::com::sun::star::beans::PropertyState* pValues = aRet.getArray();
        const ::rtl::OUString* pNames = _rPropertyNames.getConstArray();

        cppu::IPropertyArrayHelper& rHelper = getInfoHelper();

        ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property> aProps = rHelper.getProperties();
        const  ::com::sun::star::beans::Property* pProps = aProps.getConstArray();
        sal_Int32 nPropCount       = aProps.getLength();

        osl::MutexGuard aGuard(rBHelper.rMutex);
        for (sal_Int32 i=0, j=0; i<nPropCount && j<nLen; ++i, ++pProps)
        {
            // get the values only for valid properties
            if (pProps->Name.equals(*pNames))
            {
                *pValues = getPropertyState(*pNames);
                ++pValues;
                ++pNames;
                ++j;
            }
        }

        return aRet;
    }

    //---------------------------------------------------------------------
    ::com::sun::star::beans::PropertyState OPropertyStateHelper::getPropertyStateByHandle( sal_Int32 _nHandle )
    {
        // simply compare the current and the default value
        Any aCurrentValue = getPropertyDefaultByHandle( _nHandle );
        Any aDefaultValue;  getFastPropertyValue( aDefaultValue, _nHandle );

        sal_Bool bEqual = uno_type_equalData(
                const_cast< void* >( aCurrentValue.getValue() ), aCurrentValue.getValueType().getTypeLibType(),
                const_cast< void* >( aDefaultValue.getValue() ), aDefaultValue.getValueType().getTypeLibType(),
                reinterpret_cast< uno_QueryInterfaceFunc >(cpp_queryInterface),
                reinterpret_cast< uno_ReleaseFunc >(cpp_release)
            );
        return bEqual ? PropertyState_DEFAULT_VALUE : PropertyState_DIRECT_VALUE;
    }

    //---------------------------------------------------------------------
    void OPropertyStateHelper::setPropertyToDefaultByHandle( sal_Int32 _nHandle )
    {
        setFastPropertyValue( _nHandle, getPropertyDefaultByHandle( _nHandle ) );
    }

    //---------------------------------------------------------------------
    ::com::sun::star::uno::Any OPropertyStateHelper::getPropertyDefaultByHandle( sal_Int32 ) const
    {
        return  ::com::sun::star::uno::Any();
    }

    //=====================================================================
    // OStatefulPropertySet
    //=====================================================================
    //---------------------------------------------------------------------
    OStatefulPropertySet::OStatefulPropertySet()
        :OPropertyStateHelper( GetBroadcastHelper() )
    {
    }

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

    //---------------------------------------------------------------------
    Sequence< Type > SAL_CALL OStatefulPropertySet::getTypes() throw(RuntimeException)
    {
        Sequence< Type > aOwnTypes( 2 );
        aOwnTypes[0] = XWeak::static_type();
        aOwnTypes[1] = XTypeProvider::static_type();

        return concatSequences(
            aOwnTypes,
            OPropertyStateHelper::getTypes()
        );
    }

    namespace { struct lcl_ImplId : public rtl::Static< ::cppu::OImplementationId, lcl_ImplId > {}; }

    //---------------------------------------------------------------------
    Sequence< sal_Int8 > SAL_CALL OStatefulPropertySet::getImplementationId() throw(RuntimeException)
    {
        ::cppu::OImplementationId &rID = lcl_ImplId::get();
        return rID.getImplementationId();
    }

    //---------------------------------------------------------------------
    Any SAL_CALL OStatefulPropertySet::queryInterface( const Type& _rType ) throw(RuntimeException)
    {
        Any aReturn = OWeakObject::queryInterface( _rType );
        if ( !aReturn.hasValue() )
            aReturn = ::cppu::queryInterface( _rType, static_cast< XTypeProvider* >( this ) );
        if ( !aReturn.hasValue() )
            aReturn = OPropertyStateHelper::queryInterface( _rType );
        return aReturn;
    }

    //---------------------------------------------------------------------
    void SAL_CALL OStatefulPropertySet::acquire() throw()
    {
        ::cppu::OWeakObject::acquire();
    }

    //---------------------------------------------------------------------
    void SAL_CALL OStatefulPropertySet::release() throw()
    {
        ::cppu::OWeakObject::release();
    }

//.........................................................................
}
//.........................................................................

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>overly static<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * 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.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_comphelper.hxx"
#include <comphelper/propstate.hxx>
#include <com/sun/star/uno/genfunc.h>
#include <cppuhelper/queryinterface.hxx>
#include <comphelper/sequence.hxx>
#include <rtl/instance.hxx>

//.........................................................................
namespace comphelper
{
//.........................................................................

    using ::com::sun::star::uno::Reference;
    using ::com::sun::star::uno::Type;
    using ::com::sun::star::uno::RuntimeException;
    using ::com::sun::star::uno::Sequence;
    using ::com::sun::star::lang::XTypeProvider;
    using ::com::sun::star::uno::Any;
    using ::com::sun::star::uno::cpp_queryInterface;
    using ::com::sun::star::uno::cpp_release;
    using ::com::sun::star::beans::PropertyState_DEFAULT_VALUE;
    using ::com::sun::star::beans::PropertyState_DIRECT_VALUE;

    //=====================================================================
    // OPropertyStateHelper
    //=====================================================================

    //---------------------------------------------------------------------
    ::com::sun::star::uno::Any SAL_CALL OPropertyStateHelper::queryInterface(const  ::com::sun::star::uno::Type& _rType) throw( ::com::sun::star::uno::RuntimeException)
    {
        ::com::sun::star::uno::Any aReturn = OPropertySetHelper::queryInterface(_rType);
        // our own ifaces
        if ( !aReturn.hasValue() )
            aReturn = ::cppu::queryInterface(_rType, static_cast< ::com::sun::star::beans::XPropertyState*>(this));

        return aReturn;
    }

    //---------------------------------------------------------------------
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> OPropertyStateHelper::getTypes() throw( ::com::sun::star::uno::RuntimeException)
    {
        ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> aTypes(4);
        ::com::sun::star::uno::Type* pTypes = aTypes.getArray();
        // base class types
        pTypes[0] = getCppuType(( ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>*)NULL);
        pTypes[1] = getCppuType(( ::com::sun::star::uno::Reference< ::com::sun::star::beans::XMultiPropertySet>*)NULL);
        pTypes[2] = getCppuType(( ::com::sun::star::uno::Reference< ::com::sun::star::beans::XFastPropertySet>*)NULL);
        // my own type
        pTypes[3] = getCppuType(( ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyState>*)NULL);
        return aTypes;
    }

    OPropertyStateHelper::OPropertyStateHelper(
        ::cppu::OBroadcastHelper& rBHlp,
        ::cppu::IEventNotificationHook *i_pFireEvents)
        :   ::cppu::OPropertySetHelper(rBHlp, i_pFireEvents) { }

    OPropertyStateHelper::~OPropertyStateHelper() {}

    //---------------------------------------------------------------------
    void OPropertyStateHelper::firePropertyChange(sal_Int32 nHandle, const  ::com::sun::star::uno::Any& aNewValue, const  ::com::sun::star::uno::Any& aOldValue)
    {
        fire(&nHandle, &aNewValue, &aOldValue, 1, sal_False);
    }

    // XPropertyState
    //---------------------------------------------------------------------
    ::com::sun::star::beans::PropertyState SAL_CALL OPropertyStateHelper::getPropertyState(const ::rtl::OUString& _rsName) throw( ::com::sun::star::beans::UnknownPropertyException,  ::com::sun::star::uno::RuntimeException)
    {
        cppu::IPropertyArrayHelper& rPH = getInfoHelper();
        sal_Int32 nHandle = rPH.getHandleByName(_rsName);

        if (nHandle == -1)
            throw  ::com::sun::star::beans::UnknownPropertyException();

        return getPropertyStateByHandle(nHandle);
    }

    //---------------------------------------------------------------------
    void SAL_CALL OPropertyStateHelper::setPropertyToDefault(const ::rtl::OUString& _rsName) throw( ::com::sun::star::beans::UnknownPropertyException,  ::com::sun::star::uno::RuntimeException)
    {
        cppu::IPropertyArrayHelper& rPH = getInfoHelper();
        sal_Int32 nHandle = rPH.getHandleByName(_rsName);

        if (nHandle == -1)
            throw  ::com::sun::star::beans::UnknownPropertyException();

        setPropertyToDefaultByHandle(nHandle);
    }

    //---------------------------------------------------------------------
    ::com::sun::star::uno::Any SAL_CALL OPropertyStateHelper::getPropertyDefault(const ::rtl::OUString& _rsName) throw( ::com::sun::star::beans::UnknownPropertyException,  ::com::sun::star::lang::WrappedTargetException,  ::com::sun::star::uno::RuntimeException)
    {
        cppu::IPropertyArrayHelper& rPH = getInfoHelper();
        sal_Int32 nHandle = rPH.getHandleByName(_rsName);

        if (nHandle == -1)
            throw  ::com::sun::star::beans::UnknownPropertyException();

        return getPropertyDefaultByHandle(nHandle);
    }

    //---------------------------------------------------------------------
    ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyState> SAL_CALL OPropertyStateHelper::getPropertyStates(const  ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rPropertyNames) throw( ::com::sun::star::beans::UnknownPropertyException,  ::com::sun::star::uno::RuntimeException)
    {
        sal_Int32 nLen = _rPropertyNames.getLength();
        ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyState> aRet(nLen);
        ::com::sun::star::beans::PropertyState* pValues = aRet.getArray();
        const ::rtl::OUString* pNames = _rPropertyNames.getConstArray();

        cppu::IPropertyArrayHelper& rHelper = getInfoHelper();

        ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property> aProps = rHelper.getProperties();
        const  ::com::sun::star::beans::Property* pProps = aProps.getConstArray();
        sal_Int32 nPropCount       = aProps.getLength();

        osl::MutexGuard aGuard(rBHelper.rMutex);
        for (sal_Int32 i=0, j=0; i<nPropCount && j<nLen; ++i, ++pProps)
        {
            // get the values only for valid properties
            if (pProps->Name.equals(*pNames))
            {
                *pValues = getPropertyState(*pNames);
                ++pValues;
                ++pNames;
                ++j;
            }
        }

        return aRet;
    }

    //---------------------------------------------------------------------
    ::com::sun::star::beans::PropertyState OPropertyStateHelper::getPropertyStateByHandle( sal_Int32 _nHandle )
    {
        // simply compare the current and the default value
        Any aCurrentValue = getPropertyDefaultByHandle( _nHandle );
        Any aDefaultValue;  getFastPropertyValue( aDefaultValue, _nHandle );

        sal_Bool bEqual = uno_type_equalData(
                const_cast< void* >( aCurrentValue.getValue() ), aCurrentValue.getValueType().getTypeLibType(),
                const_cast< void* >( aDefaultValue.getValue() ), aDefaultValue.getValueType().getTypeLibType(),
                reinterpret_cast< uno_QueryInterfaceFunc >(cpp_queryInterface),
                reinterpret_cast< uno_ReleaseFunc >(cpp_release)
            );
        return bEqual ? PropertyState_DEFAULT_VALUE : PropertyState_DIRECT_VALUE;
    }

    //---------------------------------------------------------------------
    void OPropertyStateHelper::setPropertyToDefaultByHandle( sal_Int32 _nHandle )
    {
        setFastPropertyValue( _nHandle, getPropertyDefaultByHandle( _nHandle ) );
    }

    //---------------------------------------------------------------------
    ::com::sun::star::uno::Any OPropertyStateHelper::getPropertyDefaultByHandle( sal_Int32 ) const
    {
        return  ::com::sun::star::uno::Any();
    }

    //=====================================================================
    // OStatefulPropertySet
    //=====================================================================
    //---------------------------------------------------------------------
    OStatefulPropertySet::OStatefulPropertySet()
        :OPropertyStateHelper( GetBroadcastHelper() )
    {
    }

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

    //---------------------------------------------------------------------
    Sequence< Type > SAL_CALL OStatefulPropertySet::getTypes() throw(RuntimeException)
    {
        Sequence< Type > aOwnTypes( 2 );
        aOwnTypes[0] = XWeak::static_type();
        aOwnTypes[1] = XTypeProvider::static_type();

        return concatSequences(
            aOwnTypes,
            OPropertyStateHelper::getTypes()
        );
    }

    namespace { struct lcl_ImplId : public rtl::Static< ::cppu::OImplementationId, lcl_ImplId > {}; }

    //---------------------------------------------------------------------
    Sequence< sal_Int8 > SAL_CALL OStatefulPropertySet::getImplementationId() throw(RuntimeException)
    {
        ::cppu::OImplementationId &rID = lcl_ImplId::get();
        return rID.getImplementationId();
    }

    //---------------------------------------------------------------------
    Any SAL_CALL OStatefulPropertySet::queryInterface( const Type& _rType ) throw(RuntimeException)
    {
        Any aReturn = OWeakObject::queryInterface( _rType );
        if ( !aReturn.hasValue() )
            aReturn = ::cppu::queryInterface( _rType, static_cast< XTypeProvider* >( this ) );
        if ( !aReturn.hasValue() )
            aReturn = OPropertyStateHelper::queryInterface( _rType );
        return aReturn;
    }

    //---------------------------------------------------------------------
    void SAL_CALL OStatefulPropertySet::acquire() throw()
    {
        ::cppu::OWeakObject::acquire();
    }

    //---------------------------------------------------------------------
    void SAL_CALL OStatefulPropertySet::release() throw()
    {
        ::cppu::OWeakObject::release();
    }

//.........................................................................
}
//.........................................................................

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "app/gfx/chrome_canvas.h"

#include <pango/pango.h>

#include "app/gfx/chrome_font.h"
#include "base/gfx/rect.h"
#include "base/logging.h"
#include "base/string_util.h"

namespace {

// Returns a new pango font, free with pango_font_description_free().
PangoFontDescription* PangoFontFromChromeFont(const ChromeFont& chrome_font) {
  ChromeFont font = chrome_font;  // Copy so we can call non-const methods.
  PangoFontDescription* pfd = pango_font_description_new();
  pango_font_description_set_family(pfd, WideToUTF8(font.FontName()).c_str());
  pango_font_description_set_size(pfd, font.FontSize() * PANGO_SCALE);

  switch (font.style()) {
    case ChromeFont::NORMAL:
      // Nothing to do, should already be PANGO_STYLE_NORMAL.
      break;
    case ChromeFont::BOLD:
      pango_font_description_set_weight(pfd, PANGO_WEIGHT_BOLD);
      break;
    case ChromeFont::ITALIC:
      pango_font_description_set_style(pfd, PANGO_STYLE_ITALIC);
      break;
    case ChromeFont::UNDERLINED:
      // TODO(deanm): How to do underlined?  Where do we use it?  Probably have
      // to paint it ourselves, see pango_font_metrics_get_underline_position.
      break;
  }

  return pfd;
}

}  // namespace

ChromeCanvas::ChromeCanvas(int width, int height, bool is_opaque)
    : skia::PlatformCanvasLinux(width, height, is_opaque) {
}

ChromeCanvas::ChromeCanvas() : skia::PlatformCanvasLinux() {
}

ChromeCanvas::~ChromeCanvas() {
}

// static
void ChromeCanvas::SizeStringInt(const std::wstring& text,
                                 const ChromeFont& font,
                                 int* width, int* height, int flags) {
  NOTIMPLEMENTED();
}

void ChromeCanvas::ApplySkiaMatrixToCairoContext(cairo_t* cr) {
  const SkMatrix& skia_matrix = getTotalMatrix();
  cairo_matrix_t cairo_matrix;
  cairo_matrix_init(&cairo_matrix,
                    SkScalarToFloat(skia_matrix.getScaleX()),
                    SkScalarToFloat(skia_matrix.getSkewY()),
                    SkScalarToFloat(skia_matrix.getSkewX()),
                    SkScalarToFloat(skia_matrix.getScaleY()),
                    SkScalarToFloat(skia_matrix.getTranslateX()),
                    SkScalarToFloat(skia_matrix.getTranslateY()));
  cairo_set_matrix(cr, &cairo_matrix);
}

void ChromeCanvas::DrawStringInt(const std::wstring& text,
                                 const ChromeFont& font,
                                 const SkColor& color, int x, int y, int w,
                                 int h, int flags) {
  cairo_surface_t* surface = beginPlatformPaint();
  cairo_t* cr = cairo_create(surface);
  // We're going to draw onto the surface directly. This circumvents the matrix
  // installed by Skia. Apply the matrix from skia to cairo so they align and
  // we draw at the right place.
  ApplySkiaMatrixToCairoContext(cr);
  PangoLayout* layout = pango_cairo_create_layout(cr);

  cairo_set_source_rgb(cr,
                       SkColorGetR(color) / 255.0,
                       SkColorGetG(color) / 255.0,
                       SkColorGetB(color) / 255.0);

  // TODO(deanm): Implement the rest of the ChromeCanvas flags.
  if (!(flags & ChromeCanvas::NO_ELLIPSIS))
    pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_END);

  pango_layout_set_width(layout, w * PANGO_SCALE);
  pango_layout_set_height(layout, h * PANGO_SCALE);

  std::string utf8 = WideToUTF8(text);
  pango_layout_set_text(layout, utf8.data(), utf8.size());

  PangoFontDescription* desc = PangoFontFromChromeFont(font);
  pango_layout_set_font_description(layout, desc);
  pango_font_description_free(desc);

  int width, height;
  pango_layout_get_size(layout, &width, &height);

  if (flags & ChromeCanvas::TEXT_VALIGN_TOP) {
    // Cairo should draw from the top left corner already.
  } else if (flags & ChromeCanvas::TEXT_VALIGN_BOTTOM) {
    y = y + (h - (height / PANGO_SCALE));
  } else {
    // Vertically centered.
    y = y + ((h - (height / PANGO_SCALE)) / 2);
  }

  cairo_move_to(cr, x, y);
  pango_cairo_show_layout(cr, layout);

  g_object_unref(layout);
  cairo_destroy(cr);
  // NOTE: beginPlatformPaint returned its surface, we shouldn't destroy it.
}
<commit_msg>Fix the ChromeCanvas code to respect text alignment in Linux by using pango.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "app/gfx/chrome_canvas.h"

#include <pango/pango.h>

#include "app/gfx/chrome_font.h"
#include "base/gfx/rect.h"
#include "base/logging.h"
#include "base/string_util.h"

namespace {

// Returns a new pango font, free with pango_font_description_free().
PangoFontDescription* PangoFontFromChromeFont(const ChromeFont& chrome_font) {
  ChromeFont font = chrome_font;  // Copy so we can call non-const methods.
  PangoFontDescription* pfd = pango_font_description_new();
  pango_font_description_set_family(pfd, WideToUTF8(font.FontName()).c_str());
  pango_font_description_set_size(pfd, font.FontSize() * PANGO_SCALE);

  switch (font.style()) {
    case ChromeFont::NORMAL:
      // Nothing to do, should already be PANGO_STYLE_NORMAL.
      break;
    case ChromeFont::BOLD:
      pango_font_description_set_weight(pfd, PANGO_WEIGHT_BOLD);
      break;
    case ChromeFont::ITALIC:
      pango_font_description_set_style(pfd, PANGO_STYLE_ITALIC);
      break;
    case ChromeFont::UNDERLINED:
      // TODO(deanm): How to do underlined?  Where do we use it?  Probably have
      // to paint it ourselves, see pango_font_metrics_get_underline_position.
      break;
  }

  return pfd;
}

}  // namespace

ChromeCanvas::ChromeCanvas(int width, int height, bool is_opaque)
    : skia::PlatformCanvasLinux(width, height, is_opaque) {
}

ChromeCanvas::ChromeCanvas() : skia::PlatformCanvasLinux() {
}

ChromeCanvas::~ChromeCanvas() {
}

// static
void ChromeCanvas::SizeStringInt(const std::wstring& text,
                                 const ChromeFont& font,
                                 int* width, int* height, int flags) {
  NOTIMPLEMENTED();
}

void ChromeCanvas::ApplySkiaMatrixToCairoContext(cairo_t* cr) {
  const SkMatrix& skia_matrix = getTotalMatrix();
  cairo_matrix_t cairo_matrix;
  cairo_matrix_init(&cairo_matrix,
                    SkScalarToFloat(skia_matrix.getScaleX()),
                    SkScalarToFloat(skia_matrix.getSkewY()),
                    SkScalarToFloat(skia_matrix.getSkewX()),
                    SkScalarToFloat(skia_matrix.getScaleY()),
                    SkScalarToFloat(skia_matrix.getTranslateX()),
                    SkScalarToFloat(skia_matrix.getTranslateY()));
  cairo_set_matrix(cr, &cairo_matrix);
}

void ChromeCanvas::DrawStringInt(const std::wstring& text,
                                 const ChromeFont& font,
                                 const SkColor& color, int x, int y, int w,
                                 int h, int flags) {
  cairo_surface_t* surface = beginPlatformPaint();
  cairo_t* cr = cairo_create(surface);
  // We're going to draw onto the surface directly. This circumvents the matrix
  // installed by Skia. Apply the matrix from skia to cairo so they align and
  // we draw at the right place.
  ApplySkiaMatrixToCairoContext(cr);
  PangoLayout* layout = pango_cairo_create_layout(cr);

  cairo_set_source_rgb(cr,
                       SkColorGetR(color) / 255.0,
                       SkColorGetG(color) / 255.0,
                       SkColorGetB(color) / 255.0);

  // TODO(deanm): Implement the rest of the ChromeCanvas flags.
  if (!(flags & ChromeCanvas::NO_ELLIPSIS))
    pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_END);

  pango_layout_set_width(layout, w * PANGO_SCALE);
  pango_layout_set_height(layout, h * PANGO_SCALE);

  if (flags & TEXT_ALIGN_CENTER) {
    pango_layout_set_alignment(layout, PANGO_ALIGN_CENTER);
  } else if (flags & TEXT_ALIGN_RIGHT) {
    pango_layout_set_alignment(layout, PANGO_ALIGN_RIGHT);
  }

  std::string utf8 = WideToUTF8(text);
  pango_layout_set_text(layout, utf8.data(), utf8.size());

  PangoFontDescription* desc = PangoFontFromChromeFont(font);
  pango_layout_set_font_description(layout, desc);
  pango_font_description_free(desc);

  int width, height;
  pango_layout_get_size(layout, &width, &height);

  if (flags & ChromeCanvas::TEXT_VALIGN_TOP) {
    // Cairo should draw from the top left corner already.
  } else if (flags & ChromeCanvas::TEXT_VALIGN_BOTTOM) {
    y = y + (h - (height / PANGO_SCALE));
  } else {
    // Vertically centered.
    y = y + ((h - (height / PANGO_SCALE)) / 2);
  }

  cairo_move_to(cr, x, y);
  pango_cairo_show_layout(cr, layout);

  g_object_unref(layout);
  cairo_destroy(cr);
  // NOTE: beginPlatformPaint returned its surface, we shouldn't destroy it.
}
<|endoftext|>


<commit_before>//Marlo Zeroth mzero001@ucr.edu 861309346
//Emmilio Segovia esego001@ucr.edu 861305177

#include "test_command.h"

Test_Command::Test_Command(std::vector<std::string> input) : Command(input) {

}

// Issues the exit program program
int Test_Command::execute() {

    //size_t size = PATH_MAX + 1;
    int status; // Return value after execution
    std::cout << "In test command path: " << cmd[2] << std::endl;
    char *buffer1 = new char[PATH_MAX+1]; /* not sure about the "+ 1" */
    //char *buffer2 = new char[PATH_MAX+1]; /* not sure about the "+ 1" */
    std::string temp("../");
    temp+= std::string(cmd[2]);

    char *resolvedPath = realpath(temp.c_str(), buffer1);
    std::cout << "Path: " << temp.c_str() << std::endl;
    //char *currentDir = getcwd(buffer2, size);
    if (resolvedPath) {
            std::cout << "Path: " << resolvedPath << std::endl;
    } else {
        perror("Error");
    }

    struct stat sb;

        // We test whether this is a file, directory or otherwise
        if (stat(cmd[2], &sb) == -1) {
            status = 1;
            //perror("stat"); // Outputs an error to the command line
        }
        else{
            // If it is either a directory or file
            if ( (!std::strcmp(cmd[1], "-e")) && ((S_ISREG(sb.st_mode) == 1)
                || (S_ISDIR(sb.st_mode) == 1)) ){
                status = 0;
            }// If it is a file only
            else if ( !std::strcmp(cmd[1], "-f") && S_ISREG(sb.st_mode) == 1){
                status = 0;
            }// If it is a directory only
            else if ( !std::strcmp(cmd[1], "-d") && S_ISDIR(sb.st_mode) == 1){
                status = 0;
            }
            else {
                status = 1;
            }
        }
    delete buffer1;
    //delete buffer2;
    // We output the success of the test function
    if (status == 0){
        std::cout << "(True)" << std::endl;
    }
    else{
        std::cout << "(False)" << std::endl;
    }
    return status;
}

<commit_msg>Update test_command.cpp<commit_after>//Marlo Zeroth mzero001@ucr.edu 861309346
//Emmilio Segovia esego001@ucr.edu 861305177

#include "test_command.h"

Test_Command::Test_Command(std::vector<std::string> input) : Command(input) {

}

// Issues the exit program program
int Test_Command::execute() {

    //size_t size = PATH_MAX + 1;
    int status; // Return value after execution
    //std::cout << "In test command path: " << cmd[2] << std::endl;
    char *buffer1 = new char[PATH_MAX+1]; /* not sure about the "+ 1" */
    //char *buffer2 = new char[PATH_MAX+1]; /* not sure about the "+ 1" */
    std::string temp("../");
    temp+= std::string(cmd[2]);

    char *resolvedPath = realpath(temp.c_str(), buffer1);
    std::cout << "Path: " << temp.c_str() << std::endl;
    //char *currentDir = getcwd(buffer2, size);
    if (resolvedPath) {
            //std::cout << "Path: " << resolvedPath << std::endl;
    } else {
        perror("Error");
    }

    struct stat sb;

        // We test whether this is a file, directory or otherwise
        if (stat(cmd[2], &sb) == -1) {
            status = 1;
            //perror("stat"); // Outputs an error to the command line
        }
        else{
            // If it is either a directory or file
            if ( (!std::strcmp(cmd[1], "-e")) && ((S_ISREG(sb.st_mode) == 1)
                || (S_ISDIR(sb.st_mode) == 1)) ){
                status = 0;
            }// If it is a file only
            else if ( !std::strcmp(cmd[1], "-f") && S_ISREG(sb.st_mode) == 1){
                status = 0;
            }// If it is a directory only
            else if ( !std::strcmp(cmd[1], "-d") && S_ISDIR(sb.st_mode) == 1){
                status = 0;
            }
            else {
                status = 1;
            }
        }
    delete buffer1;
    //delete buffer2;
    // We output the success of the test function
    if (status == 0){
        std::cout << "(True)" << std::endl;
    }
    else{
        std::cout << "(False)" << std::endl;
    }
    return status;
}

<|endoftext|>


<commit_before>#include "removeDeadSymbols.h"
#include "analysis.h"
#include "stmt.h"
#include "expr.h"
#include "../traversals/view.h"

RemoveDeadSymbols::RemoveDeadSymbols(void) {
  //  whichModules = MODULES_USER;
}

void RemoveDeadSymbols::processSymbol(Symbol* sym) {
  if (sym->parentScope->type == SCOPE_INTRINSIC) {
    return;
  }
  if (sym->keepLive) {
    return;
  }

#ifdef USE_AST_IS_USED
  if (!AST_is_used(sym)) {
    sym->isDead = true;

    if (sym->defPoint) {
      // BLC: This is overkill, but mirrors what removeDeadSymbols did
      sym->defPoint->parentStmt->extract();
    }
    fprintf(stderr, "%s is dead\n", sym->name);
  }
#else
  if (TypeSymbol* typeSym = dynamic_cast<TypeSymbol*>(sym)) {
    if (!type_is_used(typeSym)) {
      typeSym->isDead = true;

      // BLC: this is a bad assumption: that if one DefExpr is dead
      // then the whole statement can be extracted; instead, we
      // should pull just the defExpr (but this breaks other stuff
      // that assumes that every defStmt).
      if (sym->defPoint) { // JBP 4/5/05 for intents-classes4.chpl this is NULL

        // SJD: Don't want to remove function is parameter is dead
        if (dynamic_cast<FnSymbol*>(sym->defPoint->sym)) {
          return;
        }

        sym->defPoint->parentStmt->extract();
      }
    }
  }
  if (FnSymbol* fnSym = dynamic_cast<FnSymbol*>(sym)) {
    if (!function_is_used(fnSym)) {
      fnSym->isDead = true;
      // BLC: see comment on previous conditional
      if (!sym->defPoint->next && !sym->defPoint->prev) {
	sym->defPoint->parentStmt->extract();
      } else {
	sym->defPoint->extract();
      }
    }
  }
#endif
}
<commit_msg>Cleaned and improved RemoveDeadSymbols.  It now only removes the symbol that is dead.  Previously it removed the whole DefStmt even if it contained other DefExprs than the one for the dead symbol.  Except for functions which I fixed earlier.<commit_after>#include "removeDeadSymbols.h"
#include "analysis.h"
#include "stmt.h"
#include "expr.h"
#include "../traversals/view.h"

RemoveDeadSymbols::RemoveDeadSymbols(void) {
  //  whichModules = MODULES_USER;
}

static void markAsDeadAndExtract(Symbol* sym) {
  sym->isDead = true;
  if (!sym->defPoint->next && !sym->defPoint->prev) {
    sym->defPoint->parentStmt->extract();
  } else {
    sym->defPoint->extract();
  }
}

void RemoveDeadSymbols::processSymbol(Symbol* sym) {
  if (sym->parentScope->type == SCOPE_INTRINSIC) {
    return;
  }
  if (sym->keepLive) {
    return;
  }

#ifdef USE_AST_IS_USED
  if (!AST_is_used(sym)) {
    markAsDeadAndExtract(sym);
    fprintf(stderr, "%s is dead\n", sym->name);
  }
#else
  if (TypeSymbol* typeSym = dynamic_cast<TypeSymbol*>(sym)) {
    if (!type_is_used(typeSym)) {
      // SJD: Don't want to remove function if type variable parameter
      // is dead
      if (dynamic_cast<FnSymbol*>(sym->defPoint->sym)) {
        return;
      }
      markAsDeadAndExtract(sym);
    }
  } else if (FnSymbol* fnSym = dynamic_cast<FnSymbol*>(sym)) {
    if (!function_is_used(fnSym)) {
      markAsDeadAndExtract(sym);
    }
  }
#endif
}
<|endoftext|>


<commit_before>
// Copyright (c) 2015 Pierre MOULON.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "openMVG/sfm/sfm_data_io.hpp"

#include "openMVG/stl/stlMap.hpp"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"

#include "openMVG/sfm/sfm_data_io_cereal.hpp"
#include "openMVG/sfm/sfm_data_io_ply.hpp"
#include "openMVG/sfm/sfm_data_io_baf.hpp"

#include "openMVG/dataio/AlembicExporter.hpp"
#include "openMVG/dataio/AlembicImporter.hpp"

namespace openMVG {
namespace sfm {

///Check that each pose have a valid intrinsic and pose id in the existing View ids
bool ValidIds(const SfM_Data & sfm_data, ESfM_Data flags_part)
{
  const bool bCheck_Intrinsic = (flags_part & INTRINSICS);
  const bool bCheck_Extrinsic = (flags_part & EXTRINSICS);

  std::set<IndexT> intrinsicIdsDeclared;
  transform(sfm_data.GetIntrinsics().begin(), sfm_data.GetIntrinsics().end(),
    std::inserter(intrinsicIdsDeclared, intrinsicIdsDeclared.begin()), stl::RetrieveKey());

  std::set<IndexT> extrinsicIdsDeclared; //unique so can use a set
  transform(sfm_data.GetPoses().begin(), sfm_data.GetPoses().end(),
    std::inserter(extrinsicIdsDeclared, extrinsicIdsDeclared.begin()), stl::RetrieveKey());

  // Collect id_intrinsic and id_extrinsic referenced from views
  std::set<IndexT> intrinsicIdsReferenced;
  std::set<IndexT> extrinsicIdsReferenced;
  for(const auto& v: sfm_data.GetViews())
  {
    const IndexT id_intrinsic = v.second.get()->id_intrinsic;
    intrinsicIdsReferenced.insert(id_intrinsic);

    const IndexT id_pose = v.second.get()->id_pose;
    extrinsicIdsReferenced.insert(id_pose);
  }

  // We may have some views with undefined Intrinsics,
  // so erase the UndefinedIndex value if exist.
  intrinsicIdsReferenced.erase(UndefinedIndexT);
  extrinsicIdsReferenced.erase(UndefinedIndexT);

  // Check if defined intrinsic & extrinsic are at least connected to views
  bool bRet = true;
  if(bCheck_Intrinsic && intrinsicIdsDeclared != intrinsicIdsReferenced)
  {
    std::cerr << "The number of intrinsics is incoherent:" << std::endl;
    std::cerr << intrinsicIdsDeclared.size() << " intrinsics declared and " << intrinsicIdsReferenced.size() << " intrinsics used." << std::endl;
    std::set<IndexT> undefinedIntrinsicIds;
    // undefinedIntrinsicIds = intrinsicIdsReferenced - intrinsicIdsDeclared
    std::set_difference(intrinsicIdsReferenced.begin(), intrinsicIdsReferenced.end(),
                        intrinsicIdsDeclared.begin(), intrinsicIdsDeclared.end(),
                        std::inserter(undefinedIntrinsicIds, undefinedIntrinsicIds.begin()));
    // If undefinedIntrinsicIds is not empty,
    // some intrinsics are used in Views but never declared.
    // So the file structure is invalid and may create troubles.
    if(!undefinedIntrinsicIds.empty())
      bRet = false; // error
  }

  if (bCheck_Extrinsic && extrinsicIdsDeclared != extrinsicIdsReferenced)
  {
    std::cerr << "The number of extrinsics is incoherent:" << std::endl;
    std::cerr << extrinsicIdsDeclared.size() << " extrinsics declared and " << extrinsicIdsReferenced.size() << " extrinsics used." << std::endl;
    std::set<IndexT> undefinedExtrinsicIds;
    // undefinedExtrinsicIds = extrinsicIdsReferenced - extrinsicIdsDeclared
    std::set_difference(extrinsicIdsReferenced.begin(), extrinsicIdsReferenced.end(),
                        extrinsicIdsDeclared.begin(), extrinsicIdsDeclared.end(),
                        std::inserter(undefinedExtrinsicIds, undefinedExtrinsicIds.begin()));
    // If undefinedExtrinsicIds is not empty,
    // some extrinsics are used in Views but never declared.
    // So the file structure is invalid and may create troubles.
    if(!undefinedExtrinsicIds.empty())
      bRet = false; // error
  }

  return bRet;
}

bool Load(SfM_Data & sfm_data, const std::string & filename, ESfM_Data flags_part)
{
  bool bStatus = false;
  const std::string ext = stlplus::extension_part(filename);
  if (ext == "json")
    bStatus = Load_Cereal<cereal::JSONInputArchive>(sfm_data, filename, flags_part);
  else if (ext == "bin")
    bStatus = Load_Cereal<cereal::PortableBinaryInputArchive>(sfm_data, filename, flags_part);
  else if (ext == "xml")
    bStatus = Load_Cereal<cereal::XMLInputArchive>(sfm_data, filename, flags_part);
#if HAVE_ALEMBIC
  else if (ext == "abc") {
    openMVG::dataio::AlembicImporter(filename).populate(sfm_data, flags_part);
    bStatus = true;
  }
#endif // HAVE_ALEMBIC

  // Assert that loaded intrinsics | extrinsics are linked to valid view
  if(bStatus &&
     (flags_part & VIEWS) &&
     ((flags_part & INTRINSICS) || (flags_part & EXTRINSICS)))
  {
    return ValidIds(sfm_data, flags_part);
  }
  return bStatus;
}

bool Save(const SfM_Data & sfm_data, const std::string & filename, ESfM_Data flags_part)
{
  const std::string ext = stlplus::extension_part(filename);
  if (ext == "json")
    return Save_Cereal<cereal::JSONOutputArchive>(sfm_data, filename, flags_part);
  else if (ext == "bin")
    return Save_Cereal<cereal::PortableBinaryOutputArchive>(sfm_data, filename, flags_part);
  else if (ext == "xml")
    return Save_Cereal<cereal::XMLOutputArchive>(sfm_data, filename, flags_part);
  else if (ext == "ply")
    return Save_PLY(sfm_data, filename, flags_part);
  else if (ext == "baf") // Bundle Adjustment file
    return Save_BAF(sfm_data, filename, flags_part);
#if HAVE_ALEMBIC
  else if (ext == "abc") // Alembic
  {
    openMVG::dataio::AlembicExporter(filename).add(sfm_data, flags_part);
    return true;
  }
#endif // HAVE_ALEMBIC
  return false;
}

} // namespace sfm
} // namespace openMVG

<commit_msg>[sfmdata io] too strong test<commit_after>
// Copyright (c) 2015 Pierre MOULON.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "openMVG/sfm/sfm_data_io.hpp"

#include "openMVG/stl/stlMap.hpp"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"

#include "openMVG/sfm/sfm_data_io_cereal.hpp"
#include "openMVG/sfm/sfm_data_io_ply.hpp"
#include "openMVG/sfm/sfm_data_io_baf.hpp"

#include "openMVG/dataio/AlembicExporter.hpp"
#include "openMVG/dataio/AlembicImporter.hpp"

namespace openMVG {
namespace sfm {

///Check that each pose have a valid intrinsic and pose id in the existing View ids
bool ValidIds(const SfM_Data & sfm_data, ESfM_Data flags_part)
{
  const bool bCheck_Intrinsic = (flags_part & INTRINSICS);
  const bool bCheck_Extrinsic = (flags_part & EXTRINSICS);

  std::set<IndexT> intrinsicIdsDeclared;
  transform(sfm_data.GetIntrinsics().begin(), sfm_data.GetIntrinsics().end(),
    std::inserter(intrinsicIdsDeclared, intrinsicIdsDeclared.begin()), stl::RetrieveKey());

  std::set<IndexT> extrinsicIdsDeclared; //unique so can use a set
  transform(sfm_data.GetPoses().begin(), sfm_data.GetPoses().end(),
    std::inserter(extrinsicIdsDeclared, extrinsicIdsDeclared.begin()), stl::RetrieveKey());

  // Collect id_intrinsic and id_extrinsic referenced from views
  std::set<IndexT> intrinsicIdsReferenced;
  std::set<IndexT> extrinsicIdsReferenced;
  for(const auto& v: sfm_data.GetViews())
  {
    const IndexT id_intrinsic = v.second.get()->id_intrinsic;
    intrinsicIdsReferenced.insert(id_intrinsic);

    const IndexT id_pose = v.second.get()->id_pose;
    extrinsicIdsReferenced.insert(id_pose);
  }

  // We may have some views with undefined Intrinsics,
  // so erase the UndefinedIndex value if exist.
  intrinsicIdsReferenced.erase(UndefinedIndexT);
  extrinsicIdsReferenced.erase(UndefinedIndexT);

  // Check if defined intrinsic & extrinsic are at least connected to views
  bool bRet = true;
  if(bCheck_Intrinsic && intrinsicIdsDeclared != intrinsicIdsReferenced)
  {
    std::cerr << "The number of intrinsics is incoherent:" << std::endl;
    std::cerr << intrinsicIdsDeclared.size() << " intrinsics declared and " << intrinsicIdsReferenced.size() << " intrinsics used." << std::endl;
    std::set<IndexT> undefinedIntrinsicIds;
    // undefinedIntrinsicIds = intrinsicIdsReferenced - intrinsicIdsDeclared
    std::set_difference(intrinsicIdsReferenced.begin(), intrinsicIdsReferenced.end(),
                        intrinsicIdsDeclared.begin(), intrinsicIdsDeclared.end(),
                        std::inserter(undefinedIntrinsicIds, undefinedIntrinsicIds.begin()));
    // If undefinedIntrinsicIds is not empty,
    // some intrinsics are used in Views but never declared.
    // So the file structure is invalid and may create troubles.
    if(!undefinedIntrinsicIds.empty())
      bRet = false; // error
  }

  if (bCheck_Extrinsic && extrinsicIdsDeclared != extrinsicIdsReferenced)
  {
    std::cerr << "The number of extrinsics is incoherent:" << std::endl;
    std::cerr << extrinsicIdsDeclared.size() << " extrinsics declared and " << extrinsicIdsReferenced.size() << " extrinsics used." << std::endl;
    std::set<IndexT> undefinedExtrinsicIds;
    // undefinedExtrinsicIds = extrinsicIdsReferenced - extrinsicIdsDeclared
    std::set_difference(extrinsicIdsDeclared.begin(), extrinsicIdsDeclared.end(),
                        extrinsicIdsReferenced.begin(), extrinsicIdsReferenced.end(),
                        std::inserter(undefinedExtrinsicIds, undefinedExtrinsicIds.begin()));
    // If undefinedExtrinsicIds is not empty,
    // some extrinsics are used in Views but never declared.
    // So the file structure is invalid and may create troubles.
    if(!undefinedExtrinsicIds.empty())
      bRet = false; // error
  }

  return bRet;
}

bool Load(SfM_Data & sfm_data, const std::string & filename, ESfM_Data flags_part)
{
  bool bStatus = false;
  const std::string ext = stlplus::extension_part(filename);
  if (ext == "json")
    bStatus = Load_Cereal<cereal::JSONInputArchive>(sfm_data, filename, flags_part);
  else if (ext == "bin")
    bStatus = Load_Cereal<cereal::PortableBinaryInputArchive>(sfm_data, filename, flags_part);
  else if (ext == "xml")
    bStatus = Load_Cereal<cereal::XMLInputArchive>(sfm_data, filename, flags_part);
#if HAVE_ALEMBIC
  else if (ext == "abc") {
    openMVG::dataio::AlembicImporter(filename).populate(sfm_data, flags_part);
    bStatus = true;
  }
#endif // HAVE_ALEMBIC

  // Assert that loaded intrinsics | extrinsics are linked to valid view
  if(bStatus &&
     (flags_part & VIEWS) &&
     ((flags_part & INTRINSICS) || (flags_part & EXTRINSICS)))
  {
    return ValidIds(sfm_data, flags_part);
  }
  return bStatus;
}

bool Save(const SfM_Data & sfm_data, const std::string & filename, ESfM_Data flags_part)
{
  const std::string ext = stlplus::extension_part(filename);
  if (ext == "json")
    return Save_Cereal<cereal::JSONOutputArchive>(sfm_data, filename, flags_part);
  else if (ext == "bin")
    return Save_Cereal<cereal::PortableBinaryOutputArchive>(sfm_data, filename, flags_part);
  else if (ext == "xml")
    return Save_Cereal<cereal::XMLOutputArchive>(sfm_data, filename, flags_part);
  else if (ext == "ply")
    return Save_PLY(sfm_data, filename, flags_part);
  else if (ext == "baf") // Bundle Adjustment file
    return Save_BAF(sfm_data, filename, flags_part);
#if HAVE_ALEMBIC
  else if (ext == "abc") // Alembic
  {
    openMVG::dataio::AlembicExporter(filename).add(sfm_data, flags_part);
    return true;
  }
#endif // HAVE_ALEMBIC
  return false;
}

} // namespace sfm
} // namespace openMVG

<|endoftext|>


<commit_before>/*
 * File:   Main.cpp
 * Author: thomas
 *
 * Created on 27. November 2008, 17:20
 */

#include <glib.h>
#include <glib-object.h>

#include <PlatformInterface/Platform.h>
//#include <Tools/Debug/Stopwatch.h>
#include <ModuleFramework/ModuleManager.h>
#include <ModuleFramework/ModuleCreator.h>

#include <cstring>
#include "Simulator.h"

using namespace std;
using namespace naoth;

// kind of a HACK, needed by the logsimulator
extern ModuleManager* getModuleManager(Cognition* c);
extern ModuleManager* getModuleManager(Motion* m);

#define TO_STRING_INT(x) #x
#define TO_STRING(x) TO_STRING_INT(x)

void print_info()
{
  std::cout << "=========================================="  << std::endl;
  std::cout << "LogSimulator compiled on: " << __DATE__ << " at " << __TIME__ << std::endl;

  #ifdef REVISION
  std::cout << "Revision number: " << TO_STRING(REVISION) << std::endl;
  #endif
  #ifdef USER_NAME
  std::cout << "Owner: " << TO_STRING(USER_NAME) << std::endl;
  #endif
  #ifdef BRANCH_PATH
  std::cout << "Branch path: " << TO_STRING(BRANCH_PATH) << std::endl;
  #endif
  std::cout << "==========================================\n"  << std::endl;
}

/*
 *
 */
int main(int argc, char** argv)
{
  print_info();

  g_type_init();

  bool backendMode = false;
  bool realTime = false;
  unsigned short port = 5401;
  bool start = false;

  char* logpath = getenv("NAOTH_LOGFILE");
  if(logpath == NULL && argc > 1) {
    logpath = argv[argc-1];
  }

  // search for parameters
  for (int i = 1; i <= argc - 1; i++) {
    if (strcmp(argv[i], "-b") == 0) {
      backendMode = true;
    }
    if (strcmp(argv[i], "-r") == 0) {
      realTime = true;
    }
    if (strcmp(argv[i], "-h") == 0) {
        std::cout << "syntax: (-b)? (-r)? (-h)? (-p <port number>)? <logfile>" << std::endl;
        std::cout << "\"-b\" enable the backend mode which is only used by LogfileSimulatorJNI" << std::endl;
        std::cout << "\"-r\" play and loop the logfile according to the time recorded in the FrameInfo of the logfile" << std::endl;
        std::cout << "\"-p\" debug port number, range of valid values: [1,65535]" << std::endl;
        std::cout << "\"-s\" starts playing the log file immediatly" << std::endl;
        std::cout << "\"-h\" help" << std::endl;
        return (EXIT_SUCCESS);
    }
    if (strcmp(argv[i], "-p") == 0) {
      port = (unsigned short) strtol(argv[++i],0,10);
      if (port == 0) {
          cerr << "invalid port number" << endl;
          return (EXIT_FAILURE);
      }
    }
    if (strcmp(argv[i], "-s") == 0) {
       start = true;
    }
  }

  if(logpath == NULL)
  {
    cerr << "You need to give the path to the logfile as argument" << endl;
    cerr << "arguments: (-b)? (-r)? (-h)? (-p <port number>)? <logfile>" << endl;
    cerr << "\"-b\" enable the backend mode which is only used by LogfilePlayer of RobotControl" << endl;
    cerr << "\"-r\" play and loop the logfile according to the time recorded in the FrameInfo of the logfile" << endl;
    cerr << "\"-p\" debug port number, range of valid values: [1,65535]" << std::endl;
    cerr << "\"-s\" starts playing the log file immediatly" << std::endl;
    cerr << "\"-h\" help" << endl;
    return (EXIT_FAILURE);
  }

  // create the simulator instance
  Simulator sim(logpath, backendMode, realTime, port);

  // init the platform
  Platform::getInstance().init(&sim);

  //init_agent(sim);
  Cognition* theCognition = createCognition();
  Motion* theMotion = createMotion();

  // ACHTUNG: C-Cast (!)
  ModuleManager* theCognitionManager = getModuleManager(theCognition);
  if(!theCognitionManager)
  {
    std::cerr << "ERROR: theCognition is not of type ModuleManager" << std::endl;
    return (EXIT_FAILURE);
  }

  ModuleManager* theMotionManager = getModuleManager(theMotion);
  if(!theMotionManager)
  {
    std::cerr << "ERROR: theMotion is not of type ModuleManager" << std::endl;
    return (EXIT_FAILURE);
  }

  // register a module to provide all the logged data
  ModuleCreator<LogProvider>* theLogProviderCognition = theCognitionManager->registerModule<LogProvider>(std::string("LogProvider"));
  ModuleCreator<LogProvider>* theLogProviderMotion = theMotionManager->registerModule<LogProvider>(std::string("LogProvider"));

  // register processes
  sim.registerCognition((naoth::Callable*)(theCognition));
  sim.registerMotion((naoth::Callable*)(theMotion));

  theLogProviderCognition->setEnabled(true);
  theLogProviderCognition->getModuleT()->init(sim.logFileScanner, sim.getRepresentations(), sim.getIncludedRepresentations());

  theLogProviderMotion->setEnabled(true);
  theLogProviderMotion->getModuleT()->init(sim.logFileScanner, sim.getRepresentations(), sim.getIncludedRepresentations());

  // start the execution
  sim.main(start);

  // dump some debug information
  //StopwatchManager::getInstance().dump();

  deleteCognition(theCognition);
  deleteMotion(theMotion);

  return (EXIT_SUCCESS);
}//end main

<commit_msg>change arguments to avoid confusion<commit_after>/*
 * File:   Main.cpp
 * Author: thomas
 *
 * Created on 27. November 2008, 17:20
 */

#include <glib.h>
#include <glib-object.h>

#include <PlatformInterface/Platform.h>
//#include <Tools/Debug/Stopwatch.h>
#include <ModuleFramework/ModuleManager.h>
#include <ModuleFramework/ModuleCreator.h>

#include <cstring>
#include "Simulator.h"

using namespace std;
using namespace naoth;

// kind of a HACK, needed by the logsimulator
extern ModuleManager* getModuleManager(Cognition* c);
extern ModuleManager* getModuleManager(Motion* m);

#define TO_STRING_INT(x) #x
#define TO_STRING(x) TO_STRING_INT(x)

void print_info()
{
  std::cout << "=========================================="  << std::endl;
  std::cout << "LogSimulator compiled on: " << __DATE__ << " at " << __TIME__ << std::endl;

  #ifdef REVISION
  std::cout << "Revision number: " << TO_STRING(REVISION) << std::endl;
  #endif
  #ifdef USER_NAME
  std::cout << "Owner: " << TO_STRING(USER_NAME) << std::endl;
  #endif
  #ifdef BRANCH_PATH
  std::cout << "Branch path: " << TO_STRING(BRANCH_PATH) << std::endl;
  #endif
  std::cout << "==========================================\n"  << std::endl;
}

/*
 *
 */
int main(int argc, char** argv)
{
  print_info();

  g_type_init();

  bool backendMode = false;
  bool realTime = false;
  unsigned short port = 5401;
  bool start = false;

  char* logpath = getenv("NAOTH_LOGFILE");
  if(logpath == NULL && argc > 1) {
    logpath = argv[argc-1];
  }

  // search for parameters
  for (int i = 1; i <= argc - 1; i++) {
    if (strcmp(argv[i], "-b") == 0) {
      backendMode = true;
    }
    if (strcmp(argv[i], "-r") == 0) {
      realTime = true;
    }
    if (strcmp(argv[i], "-h") == 0) {
        std::cout << "syntax: (-b)? (-r)? (-h)? (-p <port number>)? <logfile>" << std::endl;
        std::cout << "\"-b\" enable the backend mode which is only used by LogfileSimulatorJNI" << std::endl;
        std::cout << "\"-r\" play and loop the logfile according to the time recorded in the FrameInfo of the logfile" << std::endl;
        std::cout << "\"--port\" debug port number, range of valid values: [1,65535]" << std::endl;
        std::cout << "\"-a\" autoplay the log file immediately" << std::endl;
        std::cout << "\"-h\" help" << std::endl;
        return (EXIT_SUCCESS);
    }
    if (strcmp(argv[i], "--port") == 0) {
      port = (unsigned short) strtol(argv[++i],0,10);
      if (port == 0) {
          cerr << "invalid port number" << endl;
          return (EXIT_FAILURE);
      }
    }
    if (strcmp(argv[i], "-a") == 0) {
       start = true;
    }
  }

  if(logpath == NULL)
  {
    cerr << "You need to give the path to the logfile as argument" << endl;
    cerr << "arguments: (-b)? (-r)? (-h)? (-p <port number>)? <logfile>" << endl;
    cerr << "\"-b\" enable the backend mode which is only used by LogfilePlayer of RobotControl" << endl;
    cerr << "\"-r\" play and loop the logfile according to the time recorded in the FrameInfo of the logfile" << endl;
    cerr << "\"--port\" debug port number, range of valid values: [1,65535]" << std::endl;
    cerr << "\"-a\" starts playing the log file immediatly" << std::endl;
    cerr << "\"-h\" help" << endl;
    return (EXIT_FAILURE);
  }

  // create the simulator instance
  Simulator sim(logpath, backendMode, realTime, port);

  // init the platform
  Platform::getInstance().init(&sim);

  //init_agent(sim);
  Cognition* theCognition = createCognition();
  Motion* theMotion = createMotion();

  // ACHTUNG: C-Cast (!)
  ModuleManager* theCognitionManager = getModuleManager(theCognition);
  if(!theCognitionManager)
  {
    std::cerr << "ERROR: theCognition is not of type ModuleManager" << std::endl;
    return (EXIT_FAILURE);
  }

  ModuleManager* theMotionManager = getModuleManager(theMotion);
  if(!theMotionManager)
  {
    std::cerr << "ERROR: theMotion is not of type ModuleManager" << std::endl;
    return (EXIT_FAILURE);
  }

  // register a module to provide all the logged data
  ModuleCreator<LogProvider>* theLogProviderCognition = theCognitionManager->registerModule<LogProvider>(std::string("LogProvider"));
  ModuleCreator<LogProvider>* theLogProviderMotion = theMotionManager->registerModule<LogProvider>(std::string("LogProvider"));

  // register processes
  sim.registerCognition((naoth::Callable*)(theCognition));
  sim.registerMotion((naoth::Callable*)(theMotion));

  theLogProviderCognition->setEnabled(true);
  theLogProviderCognition->getModuleT()->init(sim.logFileScanner, sim.getRepresentations(), sim.getIncludedRepresentations());

  theLogProviderMotion->setEnabled(true);
  theLogProviderMotion->getModuleT()->init(sim.logFileScanner, sim.getRepresentations(), sim.getIncludedRepresentations());

  // start the execution
  sim.main(start);

  // dump some debug information
  //StopwatchManager::getInstance().dump();

  deleteCognition(theCognition);
  deleteMotion(theMotion);

  return (EXIT_SUCCESS);
}//end main

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkCenteredVersorTransformInitializerTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkVersorRigid3DTransform.h"
#include "itkCenteredVersorTransformInitializer.h"
#include "itkImage.h"

#include "itkImageRegionIterator.h"

/**
 *  This program tests the use of the CenteredVersorTransformInitializer class
 *
 *
 */

int itkCenteredVersorTransformInitializerTest(int , char* [] )
{

  bool pass = true;

  const unsigned int Dimension = 3;

  // Fixed Image Type
  typedef itk::Image<unsigned char, Dimension>      FixedImageType;

  // Moving Image Type
  typedef itk::Image<unsigned char, Dimension>       MovingImageType;

  // Size Type
  typedef FixedImageType::SizeType                 SizeType;
  typedef FixedImageType::SpacingType              SpacingType;
  typedef FixedImageType::PointType                PointType;
  typedef FixedImageType::IndexType                IndexType;
  typedef FixedImageType::RegionType               RegionType;

  // Transform Type
  typedef itk::VersorRigid3DTransform< double >     TransformType;
  typedef TransformType::ParametersType             ParametersType;

  SizeType size;
  size[0] = 100;
  size[1] = 100;
  size[2] = 150;

  PointType fixedOrigin;
  fixedOrigin[0] = 0.0;
  fixedOrigin[1] = 0.0;
  fixedOrigin[2] = 0.0;

  PointType movingOrigin;
  movingOrigin[0] = 29.0;
  movingOrigin[1] = 17.0;
  movingOrigin[2] = 13.0;

  SpacingType spacing;
  spacing[0] = 1.5;
  spacing[1] = 1.5;
  spacing[2] = 1.0;

  IndexType index;
  index[0] = 0;
  index[1] = 0;
  index[2] = 0;

  RegionType region;
  region.SetSize( size );
  region.SetIndex( index );

  FixedImageType::Pointer     fixedImage    = FixedImageType::New();
  MovingImageType::Pointer    movingImage   = MovingImageType::New();

  fixedImage->SetRegions( region );
  fixedImage->SetSpacing( spacing );
  fixedImage->SetOrigin(  fixedOrigin );
  fixedImage->Allocate();
  fixedImage->FillBuffer( 0 );

  movingImage->SetRegions( region );
  movingImage->SetSpacing( spacing );
  movingImage->SetOrigin(  movingOrigin );
  movingImage->Allocate();
  movingImage->FillBuffer( 0 );

  RegionType internalRegion;
  SizeType  internalSize;
  IndexType internalIndex;

  internalIndex[0] = index[0] + 20;
  internalIndex[1] = index[1] + 30;
  internalIndex[2] = index[2] + 10;

  internalSize[0]  = size[0] - 2 * 20;
  internalSize[1]  = size[1] - 2 * 30;
  internalSize[2]  = size[2] - 2 * 10;

  internalRegion.SetSize(  internalSize  );
  internalRegion.SetIndex( internalIndex );

  typedef itk::ImageRegionIterator< FixedImageType > FixedIterator;
  FixedIterator fi( fixedImage, internalRegion );

  fi.GoToBegin();
  while( !fi.IsAtEnd() )
    {
    fi.Set( 200 );
    ++fi;
    }

  internalIndex[0] = index[0] + 10;
  internalIndex[1] = index[1] + 20;
  internalIndex[2] = index[2] + 30;

  internalSize[0]  = size[0] - 2 * 10;
  internalSize[1]  = size[1] - 2 * 20;
  internalSize[2]  = size[2] - 2 * 30;

  internalRegion.SetSize(  internalSize  );
  internalRegion.SetIndex( internalIndex );

  typedef itk::ImageRegionIterator< MovingImageType > MovingIterator;
  MovingIterator mi( movingImage, internalRegion );

  mi.GoToBegin();
  while( !mi.IsAtEnd() )
    {
    mi.Set( 200 );
    ++mi;
    }

  TransformType::Pointer transform = TransformType::New();
  transform->SetIdentity();

  typedef itk::CenteredVersorTransformInitializer<
                                  FixedImageType,
                                  MovingImageType >
                                            InitializerType;

  InitializerType::Pointer initializer = InitializerType::New();

  initializer->SetFixedImage( fixedImage );
  initializer->SetMovingImage( movingImage );
  initializer->SetTransform( transform );

  initializer->InitializeTransform();

  TransformType::InputPointType   center2      = transform->GetCenter();
  TransformType::OutputVectorType translation2 = transform->GetTranslation();
  TransformType::OffsetType       offset2      = transform->GetOffset();

  { // Verfications
  TransformType::InputPointType   fixedCenter;
  TransformType::InputPointType   movingCenter;

  for(unsigned int j=0; j < Dimension; j++ )
    {
    fixedCenter[j]  = fixedOrigin[j]  + size[j] * spacing[j] / 2.0 ;
    movingCenter[j] = movingOrigin[j] + size[j] * spacing[j] / 2.0 ;
    }

  TransformType::InputVectorType relativeCenter = movingCenter - fixedCenter;

  const double tolerance = 1e-3;

  for(unsigned int k=0; k < Dimension; k++ )
    {
    if( vcl_fabs( translation2[k] - relativeCenter[k] ) > tolerance )
      {
      std::cerr << "Translation differs from expected value" << std::endl;
      std::cerr << "It should be " << relativeCenter << std::endl;
      std::cerr << "but it is    " << translation2 << std::endl;
      pass = false;
      break;
      }
    if( vcl_fabs( offset2[k] - relativeCenter[k] ) > tolerance )
      {
      std::cerr << "Offset differs from expected value" << std::endl;
      std::cerr << "It should be " << relativeCenter << std::endl;
      std::cerr << "but it is    " << offset2 << std::endl;
      pass = false;
      break;
      }
    }
  }

  if( !pass )
    {
    std::cout << "Test FAILED." << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Test PASSED." << std::endl;
  return EXIT_SUCCESS;

}

<commit_msg>ENH: Updating the test, now that we actually compute the rotation from the image moments.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkCenteredVersorTransformInitializerTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkVersorRigid3DTransform.h"
#include "itkCenteredVersorTransformInitializer.h"
#include "itkImage.h"

#include "itkImageRegionIterator.h"

/**
 *  This program tests the use of the CenteredVersorTransformInitializer class
 *
 *
 */

int itkCenteredVersorTransformInitializerTest(int , char* [] )
{

  bool pass = true;

  const unsigned int Dimension = 3;

  // Fixed Image Type
  typedef itk::Image<unsigned char, Dimension>      FixedImageType;

  // Moving Image Type
  typedef itk::Image<unsigned char, Dimension>       MovingImageType;

  // Size Type
  typedef FixedImageType::SizeType                 SizeType;
  typedef FixedImageType::SpacingType              SpacingType;
  typedef FixedImageType::PointType                PointType;
  typedef FixedImageType::IndexType                IndexType;
  typedef FixedImageType::RegionType               RegionType;

  // Transform Type
  typedef itk::VersorRigid3DTransform< double >     TransformType;
  typedef TransformType::ParametersType             ParametersType;

  SizeType size;
  size[0] = 100;
  size[1] = 100;
  size[2] = 150;

  PointType fixedOrigin;
  fixedOrigin[0] = 0.0;
  fixedOrigin[1] = 0.0;
  fixedOrigin[2] = 0.0;

  PointType movingOrigin;
  movingOrigin[0] = 29.0;
  movingOrigin[1] = 17.0;
  movingOrigin[2] = 13.0;

  SpacingType spacing;
  spacing[0] = 1.5;
  spacing[1] = 1.5;
  spacing[2] = 1.0;

  IndexType index;
  index[0] = 0;
  index[1] = 0;
  index[2] = 0;

  RegionType region;
  region.SetSize( size );
  region.SetIndex( index );

  FixedImageType::Pointer     fixedImage    = FixedImageType::New();
  MovingImageType::Pointer    movingImage   = MovingImageType::New();

  fixedImage->SetRegions( region );
  fixedImage->SetSpacing( spacing );
  fixedImage->SetOrigin(  fixedOrigin );
  fixedImage->Allocate();
  fixedImage->FillBuffer( 0 );

  movingImage->SetRegions( region );
  movingImage->SetSpacing( spacing );
  movingImage->SetOrigin(  movingOrigin );
  movingImage->Allocate();
  movingImage->FillBuffer( 0 );

  RegionType internalRegion;
  SizeType  internalSize;
  IndexType internalIndex;

  internalIndex[0] = index[0] + 20;
  internalIndex[1] = index[1] + 30;
  internalIndex[2] = index[2] + 10;

  internalSize[0]  = size[0] - 2 * 20;
  internalSize[1]  = size[1] - 2 * 30;
  internalSize[2]  = size[2] - 2 * 10;

  internalRegion.SetSize(  internalSize  );
  internalRegion.SetIndex( internalIndex );

  typedef itk::ImageRegionIterator< FixedImageType > FixedIterator;
  FixedIterator fi( fixedImage, internalRegion );

  fi.GoToBegin();
  while( !fi.IsAtEnd() )
    {
    fi.Set( 200 );
    ++fi;
    }

  internalIndex[0] = index[0] + 10;
  internalIndex[1] = index[1] + 20;
  internalIndex[2] = index[2] + 30;

  internalSize[0]  = size[0] - 2 * 10;
  internalSize[1]  = size[1] - 2 * 20;
  internalSize[2]  = size[2] - 2 * 30;

  internalRegion.SetSize(  internalSize  );
  internalRegion.SetIndex( internalIndex );

  typedef itk::ImageRegionIterator< MovingImageType > MovingIterator;
  MovingIterator mi( movingImage, internalRegion );

  mi.GoToBegin();
  while( !mi.IsAtEnd() )
    {
    mi.Set( 200 );
    ++mi;
    }

  TransformType::Pointer transform = TransformType::New();
  transform->SetIdentity();

  typedef itk::CenteredVersorTransformInitializer<
                                  FixedImageType,
                                  MovingImageType >
                                            InitializerType;

  InitializerType::Pointer initializer = InitializerType::New();

  initializer->SetFixedImage( fixedImage );
  initializer->SetMovingImage( movingImage );
  initializer->SetTransform( transform );

  initializer->InitializeTransform();

  TransformType::InputPointType   center2      = transform->GetCenter();
  TransformType::OutputVectorType translation2 = transform->GetTranslation();
  TransformType::OffsetType       offset2      = transform->GetOffset();

  { // Verfications
  TransformType::InputPointType   fixedCenter;
  TransformType::InputPointType   movingCenter;

  for(unsigned int j=0; j < Dimension; j++ )
    {
    fixedCenter[j]  = fixedOrigin[j]  + size[j] * spacing[j] / 2.0 ;
    movingCenter[j] = movingOrigin[j] + size[j] * spacing[j] / 2.0 ;
    }

  TransformType::InputVectorType relativeCenter = movingCenter - fixedCenter;

  const double tolerance = 1e-3;

  for(unsigned int k=0; k < Dimension; k++ )
    {
    if( vcl_fabs( translation2[k] - relativeCenter[k] ) > tolerance )
      {
      std::cerr << "Translation differs from expected value" << std::endl;
      std::cerr << "It should be " << relativeCenter << std::endl;
      std::cerr << "but it is    " << translation2 << std::endl;
      pass = false;
      break;
      }
    }

  TransformType::InputPointType mappedOrigin = transform->TransformPoint( fixedOrigin );
  TransformType::InputPointType expectedPoint;
  expectedPoint[0] = 29.0;
  expectedPoint[1] = 165.75;
  expectedPoint[2] = 13.25;

  for(unsigned int j=0; j < Dimension; j++ )
    {
    if( vcl_fabs( expectedPoint[j] - mappedOrigin[j] ) > tolerance )
      {
      std::cerr << "Mapped point differs from expected point" << std::endl;
      std::cerr << "It should be " << expectedPoint << std::endl;
      std::cerr << "but it is    " << mappedOrigin << std::endl;
      pass = false;
      break;
      }
    }

  }

  if( !pass )
    {
    std::cout << "Test FAILED." << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Test PASSED." << std::endl;
  return EXIT_SUCCESS;

}

<|endoftext|>


<commit_before>#include <iostream>
#include <sstream>
#include <string>
#include <vector>

template<typename T = char>
void
print_binary(T src, const size_t & byte_size)
{
    const char  zerobit     = 0;
    const char  nonzerobit  = 1;
          int   bpos        = 0;

    while(src != 0)
    {
        char buffer[byte_size] = { 0, };

        for(bpos = byte_size - 1; bpos >= 0; --bpos)
        {
            buffer[bpos] = ((src % 2 == 0) ? zerobit : nonzerobit);
            src = src >> 1;
        }

        if(bpos < 0)
            bpos = 0;

        for(int i = 0; i < byte_size; ++i)
        {
            if(i != 0 && i % 4 == 0)
                printf(" ");
            printf("%d", buffer[i]);
        }

        //printf("(%d) ", bpos);
        printf(" ");
    }
}

int
main(void)
{
    typedef uint32_t    CodewordType;
    typedef size_t      SizeType;
    typedef std::pair<CodewordType, SizeType>   CodewordPairType;
    typedef std::vector<CodewordPairType>       CodewordListType;

    CodewordListType    vin;

    do
    {
        CodewordType codeword;
        std::cout << "Codeword: ";
        std::cin  >> codeword;

        SizeType     size;
        std::cout << "Size: ";
        std::cin  >> size;

        vin.push_back(std::make_pair(codeword, size));
    }
    while(vin.size() < 10);

    std::cout << "Size of source: " << vin.tellg() << std::endl;

    std::ostringstream fout (std::ios::binary);

    {
        CodewordType    buffer;
        SizeType        buf_counter = 32;

        while(! vin.size > 0)
        {
            CodewordPairType    pair            = vin.peek();
            CodewordType        codeword        = pair.first();
            SizeType            codeword_len    = pair.second();

            if(vin.size() <= 0)
                break;

            buf_counter -= codeword_len;
            if(buf_counter >= 0)
                buffer << codeword_len;
            else
            {
            }

            {
                printf("[INP] %02x\n", raw);
                printf("[BUF] ");

                for(int i = 0; i < buf_counter; ++i)
                    printf("%02x ", buffer[i]);

                printf("\n");
            }

            fout.clear();
            fout.seekp(0, vout.end);
            fout.write(&raw, sizeof(int8_t));
        }

    }

    {
        printf("[FIN] ");

        for(auto ch : fout.str())
            printf("%02x ", ch);

        printf("\n");

        for(auto ch : fout.str())
        {
            printf("      %02x: ", ch);
            print_binary<int> (ch, 8);
        }

        printf("\n");
    }

    {
        fout.clear();
        fout.seekp(0, fout.end);
        std::cout << "Size of result: " << fout.tellp() << std::endl;
    }

    return 0;
}
<commit_msg>Fix the binary operation in demo_fstream<commit_after>#include <iostream>
#include <sstream>
#include <string>
#include <vector>

template<typename T = char>
void
print_binary(T src, const size_t & byte_size)
{
    const char  zerobit     = 0;
    const char  nonzerobit  = 1;
          int   bpos        = 0;

    while(src != 0)
    {
        char buffer[byte_size] = { 0, };

        for(bpos = byte_size - 1; bpos >= 0; --bpos)
        {
            buffer[bpos] = ((src % 2 == 0) ? zerobit : nonzerobit);
            src = src >> 1;
        }

        if(bpos < 0)
            bpos = 0;

        for(int i = 0; i < byte_size; ++i)
        {
            if(i != 0 && i % 4 == 0)
                printf(" ");
            printf("%d", buffer[i]);
        }

        //printf("(%d) ", bpos);
        printf(" ");
    }
}

int
main(void)
{
    typedef uint32_t    CodewordType;
    typedef size_t      SizeType;
    typedef std::pair<CodewordType, SizeType>   CodewordPairType;
    typedef std::vector<CodewordPairType>       CodewordListType;

    CodewordListType    vin;

    do
    {
        CodewordType codeword;
        std::cout << "Codeword: ";
        std::cin  >> codeword;

        SizeType     size;
        std::cout << "Size: ";
        std::cin  >> size;

        vin.push_back(std::make_pair(codeword, size));
    }
    while(vin.size() < 5);

    std::cout << "Size of source: " << vin.size() << std::endl;

    std::ostringstream fout (std::ios::binary);

    {
        fout.clear();
        fout.seekp(0, fout.beg);

        const   SizeType        buf_cnt_max     = 8;
        const   SizeType        buf_size_max    = 255;
                CodewordType    buffer          = 5;
                SizeType        buf_cnt_blank   = 3;

        while(vin.size() > 0)
        {
            CodewordPairType    pair            = vin.front();
            vin.erase(vin.begin());
            CodewordType        codeword        = pair.first;
            SizeType            codeword_len    = pair.second;

            while(codeword_len >= buf_cnt_blank)
            {
                {
                    printf("[INP] %2x (%d)\t: ", codeword, codeword_len);
                    print_binary<uint32_t> (codeword, 8);
                    printf("\n");
                }

                buffer <<= buf_cnt_blank;
                buffer += (codeword >> (codeword_len - buf_cnt_blank));
                codeword = codeword % (0x1 << codeword_len - buf_cnt_blank);
                codeword_len -= buf_cnt_blank;

                {
                    printf("[BUF] %02x (%d)\t: ", buffer, buf_cnt_blank);
                    print_binary<uint32_t> (buffer, 8);
                    printf("\n");
                }

                fout.write((char *)&buffer, buf_cnt_max);
                buffer = 0;
                buf_cnt_blank = buf_cnt_max;
            }

            {
                printf("[INP] %2x (%d)\t: ", codeword, codeword_len);
                print_binary<uint32_t> (codeword, 8);
                printf("\n");
            }

            buffer <<= codeword_len;
            buffer += codeword;
            buf_cnt_blank -= codeword_len;
        }
    }

    CodewordPairType    pair            = vin.front();
    vin.erase(vin.begin());
    CodewordType        codeword        = pair.first;
    SizeType            codeword_len    = pair.second;

    while(codeword_len >= buf_cnt_blank)
    {
        {
            printf("[INP] %2x (%d)\t: ", codeword, codeword_len);
            print_binary<uint32_t> (codeword, 8);
            printf("\n");
        }

        buffer <<= buf_cnt_blank;
        buffer += (codeword >> (codeword_len - buf_cnt_blank));
        codeword = codeword % (0x1 << codeword_len - buf_cnt_blank);
        codeword_len -= buf_cnt_blank;

        {
            printf("[BUF] %02x (%d)\t: ", buffer, buf_cnt_blank);
            print_binary<uint32_t> (buffer, 8);
            printf("\n");
        }

        fout.write((char *)&buffer, buf_cnt_max);
        buffer = 0;
        buf_cnt_blank = buf_cnt_max;
    }

    {
        printf("[INP] %2x (%d)\t: ", codeword, codeword_len);
        print_binary<uint32_t> (codeword, 8);
        printf("\n");
    }

    buffer <<= codeword_len;
    buffer += codeword;
    buf_cnt_blank -= codeword_len;

    {
        fout.clear();
        fout.seekp(0, fout.end);
        std::cout << "Size of result: " << fout.tellp() << std::endl;
    }

    return 0;
}
<|endoftext|>


<commit_before>/*    Copyright (c) 2010-2018, Delft University of Technology
 *    All rigths reserved
 *
 *    This file is part of the Tudat. Redistribution and use in source and
 *    binary forms, with or without modification, are permitted exclusively
 *    under the terms of the Modified BSD license. You should have received
 *    a copy of the license with this file. If not, please or visit:
 *    http://tudat.tudelft.nl/LICENSE.
 */

#include "Tudat/SimulationSetup/PropagationSetup/propagationTermination.h"

namespace tudat
{

namespace propagators
{

//! Function to check whether the propagation is to be be stopped
bool FixedTimePropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime )
{
    bool stopPropagation = 0;

    // Check whether stop time has been reached
    if( propagationDirectionIsPositive_ && ( time >= stopTime_ ) )
    {
        stopPropagation = 1;
    }
    else if( !propagationDirectionIsPositive_ && ( time <= stopTime_ ) )
    {
        stopPropagation = 1;
    }
    return stopPropagation;
}

//! Function to check whether the propagation is to be be stopped
bool FixedCPUTimePropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime )
{
    return cpuTime >= cpuStopTime_;
}

//! Function to check whether the propagation is to be be stopped
bool SingleVariableLimitPropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime  )
{
    bool stopPropagation = 0;
    double currentVariable = variableRetrievalFunction_( );

    if( useAsLowerBound_ && ( currentVariable < limitingValue_ ) )
    {
        stopPropagation = 1;
    }
    else if( !useAsLowerBound_ && ( currentVariable > limitingValue_ ) )
    {
        stopPropagation = 1;
    }
    return stopPropagation;
}

//! Function to check whether the propagation is to be be stopped
bool HybridPropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime )
{
    // Check if single condition is fulfilled.
    bool stopPropagation = -1;
    unsigned int stopIndex = 0;
    if( fulfillSingleCondition_ )
    {
        stopPropagation = 0;
        for( unsigned int i = 0; i < propagationTerminationCondition_.size( ); i++ )
        {
            if( propagationTerminationCondition_.at( i )->checkStopCondition( time, cpuTime ) )
            {
                stopIndex = i;
                stopPropagation = 1;
                isConditionMetWhenStopping_[ i ] = true;
                break;
            }
            else
            {
                isConditionMetWhenStopping_[ i ] = false;
            }
        }
    }
    // Check all conditions are fulfilled.
    else
    {
        stopPropagation = 1;
        for( unsigned int i = 0; i < propagationTerminationCondition_.size( ); i++ )
        {
            if( !propagationTerminationCondition_.at( i )->checkStopCondition( time, cpuTime ) )
            {
                stopIndex = i;
                stopPropagation = 0;
                isConditionMetWhenStopping_[ i ] = false;
                break;
            }
            else
            {
                isConditionMetWhenStopping_[ i ] = true;
            }
        }
    }

    // Save if conditions were met
    if( stopPropagation )
    {
        for( unsigned int i = ( stopIndex + 1 ); i < propagationTerminationCondition_.size( ); i++ )
        {
            isConditionMetWhenStopping_[ i ] = propagationTerminationCondition_.at( i )->checkStopCondition( time, cpuTime );
        }
    }

    return stopPropagation;
}

//! Function to create propagation termination conditions from associated settings
boost::shared_ptr< PropagationTerminationCondition > createPropagationTerminationConditions(
        const boost::shared_ptr< PropagationTerminationSettings > terminationSettings,
        const simulation_setup::NamedBodyMap& bodyMap,
        const double initialTimeStep )
{
    boost::shared_ptr< PropagationTerminationCondition > propagationTerminationCondition;

    // Check termination type.
    switch( terminationSettings->terminationType_ )
    {
    case time_stopping_condition:
    {
        // Create stopping time termination condition.
        boost::shared_ptr< PropagationTimeTerminationSettings > timeTerminationSettings =
                boost::dynamic_pointer_cast< PropagationTimeTerminationSettings >( terminationSettings );
        propagationTerminationCondition = boost::make_shared< FixedTimePropagationTerminationCondition >(
                    timeTerminationSettings->terminationTime_, ( initialTimeStep > 0 ),
                    timeTerminationSettings->terminateExactlyOnFinalCondition_ );
        break;
    }
    case cpu_time_stopping_condition:
    {
        // Create stopping time termination condition.
        boost::shared_ptr< PropagationCPUTimeTerminationSettings > cpuTimeTerminationSettings =
                boost::dynamic_pointer_cast< PropagationCPUTimeTerminationSettings >( terminationSettings );
        propagationTerminationCondition = boost::make_shared< FixedCPUTimePropagationTerminationCondition >(
                    cpuTimeTerminationSettings->cpuTerminationTime_ );
        break;
    }
    case dependent_variable_stopping_condition:
    {
        boost::shared_ptr< PropagationDependentVariableTerminationSettings > dependentVariableTerminationSettings =
                boost::dynamic_pointer_cast< PropagationDependentVariableTerminationSettings >( terminationSettings );

        // Get dependent variable function
        boost::function< double( ) > dependentVariableFunction;
        if( getDependentVariableSaveSize( dependentVariableTerminationSettings->dependentVariableSettings_ ) == 1 )
        {
            dependentVariableFunction =
                    getDoubleDependentVariableFunction(
                        dependentVariableTerminationSettings->dependentVariableSettings_, bodyMap );
        }
        else
        {
            throw std::runtime_error( "Error, cannot make stopping condition from vector dependent variable" );
        }

        // Create dependent variable termination condition.
        propagationTerminationCondition = boost::make_shared< SingleVariableLimitPropagationTerminationCondition >(
                    dependentVariableTerminationSettings->dependentVariableSettings_,
                    dependentVariableFunction, dependentVariableTerminationSettings->limitValue_,
                    dependentVariableTerminationSettings->useAsLowerLimit_,
                    dependentVariableTerminationSettings->terminateExactlyOnFinalCondition_,
                    dependentVariableTerminationSettings->terminationRootFinderSettings_ );
        break;
    }
    case custom_stopping_condition:
    {
        boost::shared_ptr< PropagationCustomTerminationSettings > customTerminationSettings =
                boost::dynamic_pointer_cast< PropagationCustomTerminationSettings >( terminationSettings );

        // Create dependent variable termination condition.
        propagationTerminationCondition = boost::make_shared< CustomTerminationCondition >(
                    customTerminationSettings->checkStopCondition_,
                    customTerminationSettings->terminateExactlyOnFinalCondition_ );
        break;
    }
    case hybrid_stopping_condition:
    {
        boost::shared_ptr< PropagationHybridTerminationSettings > hybridTerminationSettings =
                boost::dynamic_pointer_cast< PropagationHybridTerminationSettings >( terminationSettings );

        // Recursively create termination condition list.
        std::vector< boost::shared_ptr< PropagationTerminationCondition > > propagationTerminationConditionList;
        for( unsigned int i = 0; i < hybridTerminationSettings->terminationSettings_.size( ); i++ )
        {
            propagationTerminationConditionList.push_back(
                        createPropagationTerminationConditions(
                            hybridTerminationSettings->terminationSettings_.at( i ),
                            bodyMap, initialTimeStep ) );
        }
        propagationTerminationCondition = boost::make_shared< HybridPropagationTerminationCondition >(
                    propagationTerminationConditionList, hybridTerminationSettings->fulfillSingleCondition_,
                    hybridTerminationSettings->terminateExactlyOnFinalCondition_ );
        break;
    }
    default:
        std::string errorMessage = "Error, stopping condition type " + std::to_string(
                    terminationSettings->terminationType_ ) + " not recognized when making stopping conditions object";
        throw std::runtime_error( errorMessage );
    }
    return propagationTerminationCondition;

} // namespace propagators

} // namespace tudat

}
<commit_msg>Minor changes<commit_after>/*    Copyright (c) 2010-2018, Delft University of Technology
 *    All rigths reserved
 *
 *    This file is part of the Tudat. Redistribution and use in source and
 *    binary forms, with or without modification, are permitted exclusively
 *    under the terms of the Modified BSD license. You should have received
 *    a copy of the license with this file. If not, please or visit:
 *    http://tudat.tudelft.nl/LICENSE.
 */

#include "Tudat/SimulationSetup/PropagationSetup/propagationTermination.h"

namespace tudat
{

namespace propagators
{

//! Function to check whether the propagation is to be be stopped
bool FixedTimePropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime )
{
    bool stopPropagation = false;

    // Check whether stop time has been reached
    if( propagationDirectionIsPositive_ && ( time >= stopTime_ ) )
    {
        stopPropagation = true;
    }
    else if( !propagationDirectionIsPositive_ && ( time <= stopTime_ ) )
    {
        stopPropagation = true;
    }
    return stopPropagation;
}

//! Function to check whether the propagation is to be be stopped
bool FixedCPUTimePropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime )
{
    return cpuTime >= cpuStopTime_;
}

//! Function to check whether the propagation is to be be stopped
bool SingleVariableLimitPropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime  )
{
    bool stopPropagation = false;
    double currentVariable = variableRetrievalFunction_( );

    if( useAsLowerBound_ && ( currentVariable < limitingValue_ ) )
    {
        stopPropagation = true;
    }
    else if( !useAsLowerBound_ && ( currentVariable > limitingValue_ ) )
    {
        stopPropagation = true;
    }
    return stopPropagation;
}

//! Function to check whether the propagation is to be be stopped
bool HybridPropagationTerminationCondition::checkStopCondition( const double time, const double cpuTime )
{
    // Check if single condition is fulfilled.
    bool stopPropagation = -1;
    unsigned int stopIndex = 0;
    if( fulfillSingleCondition_ )
    {
        stopPropagation = false;
        for( unsigned int i = 0; i < propagationTerminationCondition_.size( ); i++ )
        {
            if( propagationTerminationCondition_.at( i )->checkStopCondition( time, cpuTime ) )
            {
                stopIndex = i;
                stopPropagation = true;
                isConditionMetWhenStopping_[ i ] = true;
                break;
            }
            else
            {
                isConditionMetWhenStopping_[ i ] = false;
            }
        }
    }
    // Check all conditions are fulfilled.
    else
    {
        stopPropagation = true;
        for( unsigned int i = 0; i < propagationTerminationCondition_.size( ); i++ )
        {
            if( !propagationTerminationCondition_.at( i )->checkStopCondition( time, cpuTime ) )
            {
                stopIndex = i;
                stopPropagation = false;
                isConditionMetWhenStopping_[ i ] = false;
                break;
            }
            else
            {
                isConditionMetWhenStopping_[ i ] = true;
            }
        }
    }

    // Save if conditions were met
    if( stopPropagation )
    {
        for( unsigned int i = ( stopIndex + 1 ); i < propagationTerminationCondition_.size( ); i++ )
        {
            isConditionMetWhenStopping_[ i ] = propagationTerminationCondition_.at( i )->checkStopCondition( time, cpuTime );
        }
    }

    return stopPropagation;
}

//! Function to create propagation termination conditions from associated settings
boost::shared_ptr< PropagationTerminationCondition > createPropagationTerminationConditions(
        const boost::shared_ptr< PropagationTerminationSettings > terminationSettings,
        const simulation_setup::NamedBodyMap& bodyMap,
        const double initialTimeStep )
{
    boost::shared_ptr< PropagationTerminationCondition > propagationTerminationCondition;

    // Check termination type.
    switch( terminationSettings->terminationType_ )
    {
    case time_stopping_condition:
    {
        // Create stopping time termination condition.
        boost::shared_ptr< PropagationTimeTerminationSettings > timeTerminationSettings =
                boost::dynamic_pointer_cast< PropagationTimeTerminationSettings >( terminationSettings );
        propagationTerminationCondition = boost::make_shared< FixedTimePropagationTerminationCondition >(
                    timeTerminationSettings->terminationTime_, ( initialTimeStep > 0 ),
                    timeTerminationSettings->terminateExactlyOnFinalCondition_ );
        break;
    }
    case cpu_time_stopping_condition:
    {
        // Create stopping time termination condition.
        boost::shared_ptr< PropagationCPUTimeTerminationSettings > cpuTimeTerminationSettings =
                boost::dynamic_pointer_cast< PropagationCPUTimeTerminationSettings >( terminationSettings );
        propagationTerminationCondition = boost::make_shared< FixedCPUTimePropagationTerminationCondition >(
                    cpuTimeTerminationSettings->cpuTerminationTime_ );
        break;
    }
    case dependent_variable_stopping_condition:
    {
        boost::shared_ptr< PropagationDependentVariableTerminationSettings > dependentVariableTerminationSettings =
                boost::dynamic_pointer_cast< PropagationDependentVariableTerminationSettings >( terminationSettings );

        // Get dependent variable function
        boost::function< double( ) > dependentVariableFunction;
        if( getDependentVariableSaveSize( dependentVariableTerminationSettings->dependentVariableSettings_ ) == 1 )
        {
            dependentVariableFunction =
                    getDoubleDependentVariableFunction(
                        dependentVariableTerminationSettings->dependentVariableSettings_, bodyMap );
        }
        else
        {
            throw std::runtime_error( "Error, cannot make stopping condition from vector dependent variable" );
        }

        // Create dependent variable termination condition.
        propagationTerminationCondition = boost::make_shared< SingleVariableLimitPropagationTerminationCondition >(
                    dependentVariableTerminationSettings->dependentVariableSettings_,
                    dependentVariableFunction, dependentVariableTerminationSettings->limitValue_,
                    dependentVariableTerminationSettings->useAsLowerLimit_,
                    dependentVariableTerminationSettings->terminateExactlyOnFinalCondition_,
                    dependentVariableTerminationSettings->terminationRootFinderSettings_ );
        break;
    }
    case custom_stopping_condition:
    {
        boost::shared_ptr< PropagationCustomTerminationSettings > customTerminationSettings =
                boost::dynamic_pointer_cast< PropagationCustomTerminationSettings >( terminationSettings );

        // Create dependent variable termination condition.
        propagationTerminationCondition = boost::make_shared< CustomTerminationCondition >(
                    customTerminationSettings->checkStopCondition_,
                    customTerminationSettings->terminateExactlyOnFinalCondition_ );
        break;
    }
    case hybrid_stopping_condition:
    {
        boost::shared_ptr< PropagationHybridTerminationSettings > hybridTerminationSettings =
                boost::dynamic_pointer_cast< PropagationHybridTerminationSettings >( terminationSettings );

        // Recursively create termination condition list.
        std::vector< boost::shared_ptr< PropagationTerminationCondition > > propagationTerminationConditionList;
        for( unsigned int i = 0; i < hybridTerminationSettings->terminationSettings_.size( ); i++ )
        {
            propagationTerminationConditionList.push_back(
                        createPropagationTerminationConditions(
                            hybridTerminationSettings->terminationSettings_.at( i ),
                            bodyMap, initialTimeStep ) );
        }
        propagationTerminationCondition = boost::make_shared< HybridPropagationTerminationCondition >(
                    propagationTerminationConditionList, hybridTerminationSettings->fulfillSingleCondition_,
                    hybridTerminationSettings->terminateExactlyOnFinalCondition_ );
        break;
    }
    default:
        std::string errorMessage = "Error, stopping condition type " + std::to_string(
                    terminationSettings->terminationType_ ) + " not recognized when making stopping conditions object";
        throw std::runtime_error( errorMessage );
    }
    return propagationTerminationCondition;

} // namespace propagators

} // namespace tudat

}
<|endoftext|>