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

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

#ifndef GCC
#endif

#include "objsh.hxx"
//#include "objshimp.hxx"
#include "objitem.hxx"

#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif

//====================================================================

TYPEINIT1_AUTOFACTORY(SfxObjectShellItem,SfxPoolItem)
TYPEINIT1_AUTOFACTORY(SfxObjectItem,SfxPoolItem)

//=========================================================================

int SfxObjectShellItem::operator==( const SfxPoolItem &rItem ) const
{
     return PTR_CAST(SfxObjectShellItem, &rItem)->pObjSh == pObjSh;
}

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

String SfxObjectShellItem::GetValueText() const
{
    return String();
}

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

SfxPoolItem* SfxObjectShellItem::Clone( SfxItemPool *) const
{
    return new SfxObjectShellItem( Which(), pObjSh );
}

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

sal_Bool SfxObjectShellItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE /*nMemberId*/ ) const
{
    if ( pObjSh )
    {
        // This item MUST provide a model. Please don't change this, there are UNO-based
        // implementations which need it!!
        rVal <<= pObjSh->GetModel();
    }
    else
    {
        rVal <<= ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >();
    }
    return TRUE;
}

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

sal_Bool SfxObjectShellItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE /*nMemberId*/ )
{
    // This item MUST have a model. Please don't change this, there are UNO-based
    // implementations which need it!!
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > xModel;

    if ( rVal >>= xModel )
    {
        if ( xModel.is() )
        {
            ::com::sun::star::uno::Reference< ::com::sun::star::lang::XUnoTunnel > xTunnel(
                xModel, ::com::sun::star::uno::UNO_QUERY );
            if ( xTunnel.is() )
            {
                ::com::sun::star::uno::Sequence < sal_Int8 > aSeq( (sal_Int8*) SvGlobalName( SFX_GLOBAL_CLASSID ).GetBytes(), 16 );
                sal_Int64 nHandle = xTunnel->getSomething( aSeq );
                if ( nHandle )
                {
                    pObjSh = reinterpret_cast< SfxObjectShell* >(sal::static_int_cast<sal_IntPtr>( nHandle ));
                    return TRUE;
                }
            }
        }

        pObjSh = 0;
        return TRUE;
    }

    return FALSE;
}

//=========================================================================

SfxObjectItem::SfxObjectItem( USHORT nWhichId, SfxShell *pSh )
:   SfxPoolItem( nWhichId ),
    _pSh( pSh )
{}

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

int SfxObjectItem::operator==( const SfxPoolItem &rItem ) const
{
     SfxObjectItem *pOther = PTR_CAST(SfxObjectItem, &rItem);
     return pOther->_pSh == _pSh;
}

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

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

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

#ifndef GCC
#endif

#include <sfx2/objsh.hxx>
//#include "objshimp.hxx"
#include <sfx2/objitem.hxx>

#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif

//====================================================================

TYPEINIT1_AUTOFACTORY(SfxObjectShellItem,SfxPoolItem)
TYPEINIT1_AUTOFACTORY(SfxObjectItem,SfxPoolItem)

//=========================================================================

int SfxObjectShellItem::operator==( const SfxPoolItem &rItem ) const
{
     return PTR_CAST(SfxObjectShellItem, &rItem)->pObjSh == pObjSh;
}

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

String SfxObjectShellItem::GetValueText() const
{
    return String();
}

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

SfxPoolItem* SfxObjectShellItem::Clone( SfxItemPool *) const
{
    return new SfxObjectShellItem( Which(), pObjSh );
}

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

sal_Bool SfxObjectShellItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE /*nMemberId*/ ) const
{
    if ( pObjSh )
    {
        // This item MUST provide a model. Please don't change this, there are UNO-based
        // implementations which need it!!
        rVal <<= pObjSh->GetModel();
    }
    else
    {
        rVal <<= ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >();
    }
    return TRUE;
}

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

sal_Bool SfxObjectShellItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE /*nMemberId*/ )
{
    // This item MUST have a model. Please don't change this, there are UNO-based
    // implementations which need it!!
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > xModel;

    if ( rVal >>= xModel )
    {
        if ( xModel.is() )
        {
            ::com::sun::star::uno::Reference< ::com::sun::star::lang::XUnoTunnel > xTunnel(
                xModel, ::com::sun::star::uno::UNO_QUERY );
            if ( xTunnel.is() )
            {
                ::com::sun::star::uno::Sequence < sal_Int8 > aSeq( (sal_Int8*) SvGlobalName( SFX_GLOBAL_CLASSID ).GetBytes(), 16 );
                sal_Int64 nHandle = xTunnel->getSomething( aSeq );
                if ( nHandle )
                {
                    pObjSh = reinterpret_cast< SfxObjectShell* >(sal::static_int_cast<sal_IntPtr>( nHandle ));
                    return TRUE;
                }
            }
        }

        pObjSh = 0;
        return TRUE;
    }

    return FALSE;
}

//=========================================================================

SfxObjectItem::SfxObjectItem( USHORT nWhichId, SfxShell *pSh )
:   SfxPoolItem( nWhichId ),
    _pSh( pSh )
{}

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

int SfxObjectItem::operator==( const SfxPoolItem &rItem ) const
{
     SfxObjectItem *pOther = PTR_CAST(SfxObjectItem, &rItem);
     return pOther->_pSh == _pSh;
}

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

SfxPoolItem* SfxObjectItem::Clone( SfxItemPool *) const
{
    return new SfxObjectItem( Which(), _pSh );
}
<|endoftext|>


<commit_before>#pragma once

#include "meta_utilities.hpp"
#include "refl_utilities.hpp"

namespace reflcompare {

namespace refl = jk::refl_utilities;
namespace metap = jk::metaprogramming;
#if USING_REFLEXPR
namespace meta = std::meta;

template<typename T>
bool equal(const T& a, const T& b);

template<typename ...MetaMembers>
struct compare_fold {
  template<typename T>
  static constexpr auto apply(const T& a, const T& b) {
    return (equal(
      a.*meta::get_pointer<MetaMembers>::value,
      b.*meta::get_pointer<MetaMembers>::value) && ...);
  }
};
#elif USING_CPP3K
namespace meta = cpp3k::meta;
#endif

template<typename T>
bool equal(const T& a, const T& b) {
  if constexpr (metap::is_detected<metap::equality_comparable, T>{}) {
    return a == b;
  } else if constexpr (metap::is_detected<metap::iterable, T>{}) {
    bool equals = true;
    if (a.size() != b.size()) {
      return false;
    }
    for (int i = 0; i < a.size(); ++i) {
      equals &= equal(a[i], b[i]);
    }
    return equals;
  } else {
#if USING_REFLEXPR
    using MetaT = reflexpr(T);
    static_assert(meta::Record<MetaT>,
      "Type contained a member which has no comparison operator defined.");
    return meta::unpack_sequence_t<meta::get_data_members_m<MetaT>, compare_fold>::apply(a, b);
#elif USING_CPP3K
    bool result = true;
    meta::for_each($T.member_variables(),
      [&a, &b, &result](auto&& member){
        result &= equal(a.*member.pointer(), b.*member.pointer());
      }
    );
    return result;
#endif
  }
}

}  // namespace reflcompare
<commit_msg>Clean up for for loop<commit_after>#pragma once

#include "meta_utilities.hpp"
#include "refl_utilities.hpp"

namespace reflcompare {

namespace refl = jk::refl_utilities;
namespace metap = jk::metaprogramming;
#if USING_REFLEXPR
namespace meta = std::meta;
#elif USING_CPP3K
namespace meta = cpp3k::meta;
#endif

template<typename T>
bool equal(const T& a, const T& b) {
  if constexpr (metap::is_detected<metap::equality_comparable, T>{}) {
    return a == b;
  } else if constexpr (metap::is_detected<metap::iterable, T>{}) {
    bool equals = true;
    if (a.size() != b.size()) {
      return false;
    }
    for (int i = 0; i < a.size(); ++i) {
      equals &= equal(a[i], b[i]);
    }
    return equals;
  } else {
#if USING_REFLEXPR
    using MetaT = reflexpr(T);
    static_assert(meta::Record<MetaT>,
      "Type contained a member which has no comparison operator defined.");
    bool result = true;
    meta::for_each<meta::get_data_members_m<MetaT>>(
      [&a, &b, &result](auto&& member) {
        using MetaMember = typename std::decay_t<decltype(member)>;
        constexpr auto p = meta::get_pointer<MetaMember>::value;
        result &= equal(a.*p, b.*p);
      }
    );
    return result;
#elif USING_CPP3K
    bool result = true;
    meta::for_each($T.member_variables(),
      [&a, &b, &result](auto&& member){
        result &= equal(a.*member.pointer(), b.*member.pointer());
      }
    );
    return result;
#endif
  }
}

}  // namespace reflcompare
<|endoftext|>


<commit_before>#ifndef SERVER_API_BASE_PARAMETERS_GRAMMAR_HPP
#define SERVER_API_BASE_PARAMETERS_GRAMMAR_HPP

#include "engine/api/base_parameters.hpp"

#include "engine/bearing.hpp"
#include "engine/hint.hpp"
#include "engine/polyline_compressor.hpp"

#include <boost/optional.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/include/qi.hpp>

#include <limits>
#include <string>

namespace osrm
{
namespace server
{
namespace api
{

namespace
{
namespace ph = boost::phoenix;
namespace qi = boost::spirit::qi;
}

template <typename T, char... Fmt> struct no_trailing_dot_policy : qi::real_policies<T>
{
    template <typename Iterator> static bool parse_dot(Iterator &first, Iterator const &last)
    {
        if (first == last || *first != '.')
            return false;

        static const constexpr char fmt[sizeof...(Fmt)] = {Fmt...};

        if (first + sizeof(fmt) < last && std::equal(fmt, fmt + sizeof(fmt), first + 1u))
            return false;

        ++first;
        return true;
    }

    template <typename Iterator> static bool parse_exp(Iterator &, const Iterator &)
    {
        return false;
    }

    template <typename Iterator, typename Attribute>
    static bool parse_exp_n(Iterator &, const Iterator &, Attribute &)
    {
        return false;
    }

    template <typename Iterator, typename Attribute>
    static bool parse_nan(Iterator &, const Iterator &, Attribute &)
    {
        return false;
    }

    template <typename Iterator, typename Attribute>
    static bool parse_inf(Iterator &, const Iterator &, Attribute &)
    {
        return false;
    }
};

template <typename Iterator, typename Signature>
struct BaseParametersGrammar : boost::spirit::qi::grammar<Iterator, Signature>
{
    using json_policy = no_trailing_dot_policy<double, 'j', 's', 'o', 'n'>;

    BaseParametersGrammar(qi::rule<Iterator, Signature> &root_rule)
        : BaseParametersGrammar::base_type(root_rule)
    {
        const auto add_hint = [](engine::api::BaseParameters &base_parameters, const std::string &hint_string)
        {
            if (hint_string.size() > 0)
            {
                base_parameters.hints.emplace_back(engine::Hint::FromBase64(hint_string));
            }
        };

        const auto add_bearing = [](engine::api::BaseParameters &base_parameters,
                                    boost::optional<boost::fusion::vector2<short, short>> bearing_range)
        {
            boost::optional<engine::Bearing> bearing;
            if (bearing_range)
            {
                bearing = engine::Bearing{boost::fusion::at_c<0>(*bearing_range),
                                          boost::fusion::at_c<1>(*bearing_range)};
            }
            base_parameters.bearings.push_back(std::move(bearing));
        };

        polyline_chars = qi::char_("a-zA-Z0-9_.--[]{}@?|\\%~`^");
        base64_char = qi::char_("a-zA-Z0-9--_=");
        unlimited_rule = qi::lit("unlimited")[qi::_val = std::numeric_limits<double>::infinity()];

        bearing_rule
            = (qi::short_ > ',' > qi::short_)
              [qi::_val = ph::bind([](short bearing, short range) {
                  return osrm::engine::Bearing{bearing, range};
              }, qi::_1, qi::_2)]
            ;

        location_rule
            = (double_ > qi::lit(',') > double_)
              [qi::_val = ph::bind([](double lon, double lat) {
                  return util::Coordinate(util::FixedLongitude(lon * COORDINATE_PRECISION),
                                          util::FixedLatitude(lat * COORDINATE_PRECISION));
              }, qi::_1, qi::_2)]
            ;

        polyline_rule
            = qi::as_string[qi::lit("polyline(") > +polyline_chars > ')']
              [qi::_val = ph::bind([](const std::string &polyline) {
                  return engine::decodePolyline(polyline);
              }, qi::_1)]
            ;

        query_rule
            = ((location_rule % ';') | polyline_rule)
              [ph::bind(&engine::api::BaseParameters::coordinates, qi::_r1) = qi::_1]
            ;

        radiuses_rule
            = qi::lit("radiuses=")
            > (-(qi::double_ | unlimited_rule) % ';')
              [ph::bind(&engine::api::BaseParameters::radiuses, qi::_r1) = qi::_1]
            ;

        hints_rule
            = qi::lit("hints=")
            > qi::as_string[qi::repeat(engine::ENCODED_HINT_SIZE)[base64_char]][ph::bind(add_hint, qi::_r1, qi::_1)] % ';'
            ;

        bearings_rule
            = qi::lit("bearings=") >
            (-(qi::short_ > ',' > qi::short_))[ph::bind(add_bearing, qi::_r1, qi::_1)] % ';'
            ;

        base_rule = radiuses_rule(qi::_r1) | hints_rule(qi::_r1) | bearings_rule(qi::_r1);
    }

  protected:
    qi::rule<Iterator, Signature> base_rule;
    qi::rule<Iterator, Signature> query_rule;

  private:
    qi::rule<Iterator, Signature> bearings_rule;
    qi::rule<Iterator, Signature> radiuses_rule;
    qi::rule<Iterator, Signature> hints_rule;

    qi::rule<Iterator, osrm::engine::Bearing()> bearing_rule;
    qi::rule<Iterator, osrm::util::Coordinate()> location_rule;
    qi::rule<Iterator, std::vector<osrm::util::Coordinate>()> polyline_rule;

    qi::rule<Iterator, unsigned char()> base64_char;
    qi::rule<Iterator, std::string()> polyline_chars;
    qi::rule<Iterator, double()> unlimited_rule;
    qi::real_parser<double, json_policy> double_;
};
}
}
}

#endif
<commit_msg>Make hint values optional, fixes issue 2356<commit_after>#ifndef SERVER_API_BASE_PARAMETERS_GRAMMAR_HPP
#define SERVER_API_BASE_PARAMETERS_GRAMMAR_HPP

#include "engine/api/base_parameters.hpp"

#include "engine/bearing.hpp"
#include "engine/hint.hpp"
#include "engine/polyline_compressor.hpp"

#include <boost/optional.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/include/qi.hpp>

#include <limits>
#include <string>

namespace osrm
{
namespace server
{
namespace api
{

namespace
{
namespace ph = boost::phoenix;
namespace qi = boost::spirit::qi;
}

template <typename T, char... Fmt> struct no_trailing_dot_policy : qi::real_policies<T>
{
    template <typename Iterator> static bool parse_dot(Iterator &first, Iterator const &last)
    {
        if (first == last || *first != '.')
            return false;

        static const constexpr char fmt[sizeof...(Fmt)] = {Fmt...};

        if (first + sizeof(fmt) < last && std::equal(fmt, fmt + sizeof(fmt), first + 1u))
            return false;

        ++first;
        return true;
    }

    template <typename Iterator> static bool parse_exp(Iterator &, const Iterator &)
    {
        return false;
    }

    template <typename Iterator, typename Attribute>
    static bool parse_exp_n(Iterator &, const Iterator &, Attribute &)
    {
        return false;
    }

    template <typename Iterator, typename Attribute>
    static bool parse_nan(Iterator &, const Iterator &, Attribute &)
    {
        return false;
    }

    template <typename Iterator, typename Attribute>
    static bool parse_inf(Iterator &, const Iterator &, Attribute &)
    {
        return false;
    }
};

template <typename Iterator, typename Signature>
struct BaseParametersGrammar : boost::spirit::qi::grammar<Iterator, Signature>
{
    using json_policy = no_trailing_dot_policy<double, 'j', 's', 'o', 'n'>;

    BaseParametersGrammar(qi::rule<Iterator, Signature> &root_rule)
        : BaseParametersGrammar::base_type(root_rule)
    {
        const auto add_hint = [](engine::api::BaseParameters &base_parameters, const std::string &hint_string)
        {
            if (hint_string.size() > 0)
            {
                base_parameters.hints.emplace_back(engine::Hint::FromBase64(hint_string));
            }
        };

        const auto add_bearing = [](engine::api::BaseParameters &base_parameters,
                                    boost::optional<boost::fusion::vector2<short, short>> bearing_range)
        {
            boost::optional<engine::Bearing> bearing;
            if (bearing_range)
            {
                bearing = engine::Bearing{boost::fusion::at_c<0>(*bearing_range),
                                          boost::fusion::at_c<1>(*bearing_range)};
            }
            base_parameters.bearings.push_back(std::move(bearing));
        };

        polyline_chars = qi::char_("a-zA-Z0-9_.--[]{}@?|\\%~`^");
        base64_char = qi::char_("a-zA-Z0-9--_=");
        unlimited_rule = qi::lit("unlimited")[qi::_val = std::numeric_limits<double>::infinity()];

        bearing_rule
            = (qi::short_ > ',' > qi::short_)
              [qi::_val = ph::bind([](short bearing, short range) {
                  return osrm::engine::Bearing{bearing, range};
              }, qi::_1, qi::_2)]
            ;

        location_rule
            = (double_ > qi::lit(',') > double_)
              [qi::_val = ph::bind([](double lon, double lat) {
                  return util::Coordinate(util::FixedLongitude(lon * COORDINATE_PRECISION),
                                          util::FixedLatitude(lat * COORDINATE_PRECISION));
              }, qi::_1, qi::_2)]
            ;

        polyline_rule
            = qi::as_string[qi::lit("polyline(") > +polyline_chars > ')']
              [qi::_val = ph::bind([](const std::string &polyline) {
                  return engine::decodePolyline(polyline);
              }, qi::_1)]
            ;

        query_rule
            = ((location_rule % ';') | polyline_rule)
              [ph::bind(&engine::api::BaseParameters::coordinates, qi::_r1) = qi::_1]
            ;

        radiuses_rule
            = qi::lit("radiuses=")
            > (-(qi::double_ | unlimited_rule) % ';')
              [ph::bind(&engine::api::BaseParameters::radiuses, qi::_r1) = qi::_1]
            ;

        hints_rule
            = qi::lit("hints=")
            > -qi::as_string[qi::repeat(engine::ENCODED_HINT_SIZE)[base64_char]][ph::bind(add_hint, qi::_r1, qi::_1)] % ';'
            ;

        bearings_rule
            = qi::lit("bearings=") >
            (-(qi::short_ > ',' > qi::short_))[ph::bind(add_bearing, qi::_r1, qi::_1)] % ';'
            ;

        base_rule = radiuses_rule(qi::_r1) | hints_rule(qi::_r1) | bearings_rule(qi::_r1);
    }

  protected:
    qi::rule<Iterator, Signature> base_rule;
    qi::rule<Iterator, Signature> query_rule;

  private:
    qi::rule<Iterator, Signature> bearings_rule;
    qi::rule<Iterator, Signature> radiuses_rule;
    qi::rule<Iterator, Signature> hints_rule;

    qi::rule<Iterator, osrm::engine::Bearing()> bearing_rule;
    qi::rule<Iterator, osrm::util::Coordinate()> location_rule;
    qi::rule<Iterator, std::vector<osrm::util::Coordinate>()> polyline_rule;

    qi::rule<Iterator, unsigned char()> base64_char;
    qi::rule<Iterator, std::string()> polyline_chars;
    qi::rule<Iterator, double()> unlimited_rule;
    qi::real_parser<double, json_policy> double_;
};
}
}
}

#endif
<|endoftext|>


<commit_before>#include "perf_precomp.hpp"

#define GPU_PERF_TEST_P(fixture, name, params)  \
    class fixture##_##name : public fixture {\
     public:\
      fixture##_##name() {}\
     protected:\
             virtual void __cpu();\
        virtual void __gpu();\
      virtual void PerfTestBody();\
    };\
    TEST_P(fixture##_##name, name /*perf*/){ RunPerfTestBody(); if (runOnGpu) __gpu(); else __cpu();}\
    INSTANTIATE_TEST_CASE_P(/*none*/, fixture##_##name, params);\
    void fixture##_##name::PerfTestBody()

#define RUN_CPU(fixture, name)\
    void fixture##_##name::__cpu()

#define RUN_GPU(fixture, name)\
    void fixture##_##name::__gpu()

#define FAIL_NO_CPU(fixture, name)\
void fixture##_##name::__cpu() { FAIL() << "No such CPU implementation analogy";}

typedef std::tr1::tuple<std::string, std::string> fixture_t;
typedef perf::TestBaseWithParam<fixture_t> SoftCascadeTest;

GPU_PERF_TEST_P(SoftCascadeTest, detect,
    testing::Combine(
        testing::Values(std::string("cv/cascadeandhog/sc_cvpr_2012_to_opencv.xml")),
        testing::Values(std::string("cv/cascadeandhog/bahnhof/image_00000000_0.png"))))
{ }

RUN_GPU(SoftCascadeTest, detect)
{
    cv::Mat cpu = readImage (GET_PARAM(1));
    ASSERT_FALSE(cpu.empty());
    cv::gpu::GpuMat colored(cpu);

    cv::gpu::SoftCascade cascade;
    ASSERT_TRUE(cascade.load(perf::TestBase::getDataPath(GET_PARAM(0))));

    cv::gpu::GpuMat objectBoxes(1, 16384, CV_8UC1), rois(cascade.getRoiSize(), CV_8UC1), trois;
    rois.setTo(1);
    cv::gpu::transpose(rois, trois);

    cv::gpu::GpuMat curr = objectBoxes;
    cascade.detectMultiScale(colored, trois, curr);

    TEST_CYCLE()
    {
        curr = objectBoxes;
        cascade.detectMultiScale(colored, trois, curr);
    }
}

RUN_CPU(SoftCascadeTest, detect)
{
    cv::Mat colored = readImage(GET_PARAM(1));
    ASSERT_FALSE(colored.empty());

    cv::SoftCascade cascade;
    ASSERT_TRUE(cascade.load(getDataPath(GET_PARAM(0))));

    std::vector<cv::Rect> rois;

    typedef cv::SoftCascade::Detection Detection;
    std::vector<Detection>objectBoxes;
    cascade.detectMultiScale(colored, rois, objectBoxes);

    TEST_CYCLE()
    {
        cascade.detectMultiScale(colored, rois, objectBoxes);
    }
}

static cv::Rect getFromTable(int idx)
{
    static const cv::Rect rois[] =
    {
        cv::Rect( 65,  20,  35, 80),
        cv::Rect( 95,  35,  45, 40),
        cv::Rect( 45,  35,  45, 40),
        cv::Rect( 25,  27,  50, 45),
        cv::Rect(100,  50,  45, 40),

        cv::Rect( 60,  30,  45, 40),
        cv::Rect( 40,  55,  50, 40),
        cv::Rect( 48,  37,  72, 80),
        cv::Rect( 48,  32,  85, 58),
        cv::Rect( 48,   0,  32, 27)
    };

    return rois[idx];
}

typedef std::tr1::tuple<std::string, std::string, int> roi_fixture_t;
typedef perf::TestBaseWithParam<roi_fixture_t> SoftCascadeTestRoi;

GPU_PERF_TEST_P(SoftCascadeTestRoi, detectInRoi,
    testing::Combine(
        testing::Values(std::string("cv/cascadeandhog/sc_cvpr_2012_to_opencv.xml")),
        testing::Values(std::string("cv/cascadeandhog/bahnhof/image_00000000_0.png")),
        testing::Range(0, 5)))
{}

RUN_GPU(SoftCascadeTestRoi, detectInRoi)
{
    cv::Mat cpu = readImage (GET_PARAM(1));
    ASSERT_FALSE(cpu.empty());
    cv::gpu::GpuMat colored(cpu);

    cv::gpu::SoftCascade cascade;
    ASSERT_TRUE(cascade.load(perf::TestBase::getDataPath(GET_PARAM(0))));

    cv::gpu::GpuMat objectBoxes(1, 16384 * 20, CV_8UC1), rois(cascade.getRoiSize(), CV_8UC1);
    rois.setTo(0);

    int nroi = GET_PARAM(2);
    cv::RNG rng;
    for (int i = 0; i < nroi; ++i)
    {
        cv::Rect r = getFromTable(rng(10));
        cv::gpu::GpuMat sub(rois, r);
        sub.setTo(1);
    }

    cv::gpu::GpuMat trois;
    cv::gpu::transpose(rois, trois);

    cv::gpu::GpuMat curr = objectBoxes;
    cascade.detectMultiScale(colored, trois, curr);

    TEST_CYCLE()
    {
        curr = objectBoxes;
        cascade.detectMultiScale(colored, trois, curr);
    }
}

FAIL_NO_CPU(SoftCascadeTestRoi, detectInRoi)

GPU_PERF_TEST_P(SoftCascadeTestRoi, detectEachRoi,
    testing::Combine(
        testing::Values(std::string("cv/cascadeandhog/sc_cvpr_2012_to_opencv.xml")),
        testing::Values(std::string("cv/cascadeandhog/bahnhof/image_00000000_0.png")),
        testing::Range(0, 10)))
{}

RUN_GPU(SoftCascadeTestRoi, detectEachRoi)
{
    cv::Mat cpu = readImage (GET_PARAM(1));
    ASSERT_FALSE(cpu.empty());
    cv::gpu::GpuMat colored(cpu);

    cv::gpu::SoftCascade cascade;
    ASSERT_TRUE(cascade.load(perf::TestBase::getDataPath(GET_PARAM(0))));

    cv::gpu::GpuMat objectBoxes(1, 16384 * 20, CV_8UC1), rois(cascade.getRoiSize(), CV_8UC1);
    rois.setTo(0);

    int idx = GET_PARAM(2);
    cv::Rect r = getFromTable(idx);
    cv::gpu::GpuMat sub(rois, r);
    sub.setTo(1);

    cv::gpu::GpuMat curr = objectBoxes;
    cv::gpu::GpuMat trois;
    cv::gpu::transpose(rois, trois);

    cascade.detectMultiScale(colored, trois, curr);

    TEST_CYCLE()
    {
        curr = objectBoxes;
        cascade.detectMultiScale(colored, trois, curr);
    }
}

FAIL_NO_CPU(SoftCascadeTestRoi, detectEachRoi)<commit_msg>add sanity check to performance tests for soft cascade<commit_after>#include "perf_precomp.hpp"

#define GPU_PERF_TEST_P(fixture, name, params)  \
    class fixture##_##name : public fixture {\
     public:\
      fixture##_##name() {}\
     protected:\
        virtual void __cpu();\
        virtual void __gpu();\
      virtual void PerfTestBody();\
    };\
    TEST_P(fixture##_##name, name /*perf*/){ RunPerfTestBody(); if (runOnGpu) __gpu(); else __cpu();}\
    INSTANTIATE_TEST_CASE_P(/*none*/, fixture##_##name, params);\
    void fixture##_##name::PerfTestBody()

#define RUN_CPU(fixture, name)\
    void fixture##_##name::__cpu()

#define RUN_GPU(fixture, name)\
    void fixture##_##name::__gpu()

#define FAIL_NO_CPU(fixture, name)\
void fixture##_##name::__cpu() { FAIL() << "No such CPU implementation analogy";}

namespace {
    struct DetectionLess
    {
        bool operator()(const cv::gpu::SoftCascade::Detection& a,
            const cv::gpu::SoftCascade::Detection& b) const
        {
            if (a.x != b.x) return a.x < b.x;
            else if (a.y != b.y) return a.y < b.y;
            else if (a.w != b.w) return a.w < b.w;
            else return a.h < b.h;
        }

        bool operator()(const cv::SoftCascade::Detection& a,
            const cv::SoftCascade::Detection& b) const
        {
            const cv::Rect& ra = a.rect;
            const cv::Rect& rb = b.rect;

            if (ra.x != rb.x) return ra.x < rb.x;
            else if (ra.y != rb.y) return ra.y < rb.y;
            else if (ra.width != rb.width) return ra.width < rb.width;
            else return ra.height < rb.height;
        }
    };

    cv::Mat sortDetections(cv::gpu::GpuMat& objects)
    {
        cv::Mat detections(objects);

        typedef cv::gpu::SoftCascade::Detection Detection;
        Detection* begin = (Detection*)(detections.ptr<char>(0));
        Detection* end = (Detection*)(detections.ptr<char>(0) + detections.cols);
        std::sort(begin, end, DetectionLess());

        return detections;
    }
}

typedef std::tr1::tuple<std::string, std::string> fixture_t;
typedef perf::TestBaseWithParam<fixture_t> SoftCascadeTest;

GPU_PERF_TEST_P(SoftCascadeTest, detect,
    testing::Combine(
        testing::Values(std::string("cv/cascadeandhog/sc_cvpr_2012_to_opencv.xml")),
        testing::Values(std::string("cv/cascadeandhog/bahnhof/image_00000000_0.png"))))
{ }

RUN_GPU(SoftCascadeTest, detect)
{
    cv::Mat cpu = readImage (GET_PARAM(1));
    ASSERT_FALSE(cpu.empty());
    cv::gpu::GpuMat colored(cpu);

    cv::gpu::SoftCascade cascade;
    ASSERT_TRUE(cascade.load(perf::TestBase::getDataPath(GET_PARAM(0))));

    cv::gpu::GpuMat objectBoxes(1, 10000 * sizeof(cv::gpu::SoftCascade::Detection), CV_8UC1), rois(cascade.getRoiSize(), CV_8UC1), trois;
    rois.setTo(1);
    cv::gpu::transpose(rois, trois);

    cv::gpu::GpuMat curr = objectBoxes;
    cascade.detectMultiScale(colored, trois, curr);

    TEST_CYCLE()
    {
        curr = objectBoxes;
        cascade.detectMultiScale(colored, trois, curr);
    }

    SANITY_CHECK(sortDetections(curr));
}

RUN_CPU(SoftCascadeTest, detect)
{
    cv::Mat colored = readImage(GET_PARAM(1));
    ASSERT_FALSE(colored.empty());

    cv::SoftCascade cascade;
    ASSERT_TRUE(cascade.load(getDataPath(GET_PARAM(0))));

    std::vector<cv::Rect> rois;

    typedef cv::SoftCascade::Detection Detection;
    std::vector<Detection>objects;
    cascade.detectMultiScale(colored, rois, objects);

    TEST_CYCLE()
    {
        cascade.detectMultiScale(colored, rois, objects);
    }

    std::sort(objects.begin(), objects.end(), DetectionLess());
    SANITY_CHECK(objects);
}

static cv::Rect getFromTable(int idx)
{
    static const cv::Rect rois[] =
    {
        cv::Rect( 65,  20,  35, 80),
        cv::Rect( 95,  35,  45, 40),
        cv::Rect( 45,  35,  45, 40),
        cv::Rect( 25,  27,  50, 45),
        cv::Rect(100,  50,  45, 40),

        cv::Rect( 60,  30,  45, 40),
        cv::Rect( 40,  55,  50, 40),
        cv::Rect( 48,  37,  72, 80),
        cv::Rect( 48,  32,  85, 58),
        cv::Rect( 48,   0,  32, 27)
    };

    return rois[idx];
}

typedef std::tr1::tuple<std::string, std::string, int> roi_fixture_t;
typedef perf::TestBaseWithParam<roi_fixture_t> SoftCascadeTestRoi;

GPU_PERF_TEST_P(SoftCascadeTestRoi, detectInRoi,
    testing::Combine(
        testing::Values(std::string("cv/cascadeandhog/sc_cvpr_2012_to_opencv.xml")),
        testing::Values(std::string("cv/cascadeandhog/bahnhof/image_00000000_0.png")),
        testing::Range(0, 5)))
{}

RUN_GPU(SoftCascadeTestRoi, detectInRoi)
{
    cv::Mat cpu = readImage (GET_PARAM(1));
    ASSERT_FALSE(cpu.empty());
    cv::gpu::GpuMat colored(cpu);

    cv::gpu::SoftCascade cascade;
    ASSERT_TRUE(cascade.load(perf::TestBase::getDataPath(GET_PARAM(0))));

    cv::gpu::GpuMat objectBoxes(1, 16384 * 20, CV_8UC1), rois(cascade.getRoiSize(), CV_8UC1);
    rois.setTo(0);

    int nroi = GET_PARAM(2);
    cv::RNG rng;
    for (int i = 0; i < nroi; ++i)
    {
        cv::Rect r = getFromTable(rng(10));
        cv::gpu::GpuMat sub(rois, r);
        sub.setTo(1);
    }

    cv::gpu::GpuMat trois;
    cv::gpu::transpose(rois, trois);

    cv::gpu::GpuMat curr = objectBoxes;
    cascade.detectMultiScale(colored, trois, curr);

    TEST_CYCLE()
    {
        curr = objectBoxes;
        cascade.detectMultiScale(colored, trois, curr);
    }

    SANITY_CHECK(sortDetections(curr));
}

FAIL_NO_CPU(SoftCascadeTestRoi, detectInRoi)

GPU_PERF_TEST_P(SoftCascadeTestRoi, detectEachRoi,
    testing::Combine(
        testing::Values(std::string("cv/cascadeandhog/sc_cvpr_2012_to_opencv.xml")),
        testing::Values(std::string("cv/cascadeandhog/bahnhof/image_00000000_0.png")),
        testing::Range(0, 10)))
{}

RUN_GPU(SoftCascadeTestRoi, detectEachRoi)
{
    cv::Mat cpu = readImage (GET_PARAM(1));
    ASSERT_FALSE(cpu.empty());
    cv::gpu::GpuMat colored(cpu);

    cv::gpu::SoftCascade cascade;
    ASSERT_TRUE(cascade.load(perf::TestBase::getDataPath(GET_PARAM(0))));

    cv::gpu::GpuMat objectBoxes(1, 16384 * 20, CV_8UC1), rois(cascade.getRoiSize(), CV_8UC1);
    rois.setTo(0);

    int idx = GET_PARAM(2);
    cv::Rect r = getFromTable(idx);
    cv::gpu::GpuMat sub(rois, r);
    sub.setTo(1);

    cv::gpu::GpuMat curr = objectBoxes;
    cv::gpu::GpuMat trois;
    cv::gpu::transpose(rois, trois);

    cascade.detectMultiScale(colored, trois, curr);

    TEST_CYCLE()
    {
        curr = objectBoxes;
        cascade.detectMultiScale(colored, trois, curr);
    }

    SANITY_CHECK(sortDetections(curr));
}

FAIL_NO_CPU(SoftCascadeTestRoi, detectEachRoi)
<|endoftext|>


<commit_before>void MakeVZERORecoParam(AliRecoParam::EventSpecie_t default=AliRecoParam::kLowMult) {
//========================================================================
//
// Steering macro for VZERO reconstruction parameters
//
// Author: Brigitte Cheynis
//
//========================================================================

  const char* macroname = "MakeVZERORecoParam.C";

  // Activate CDB storage and load geometry from CDB
  AliCDBManager* cdb = AliCDBManager::Instance();
  if(!cdb->IsDefaultStorageSet()) cdb->SetDefaultStorage("local://OCDB");

  TObjArray *recoParamArray = new TObjArray();

  {
    AliVZERORecoParam * vzeroRecoParam = new AliVZERORecoParam;
    vzeroRecoParam->SetEventSpecie(AliRecoParam::kCosmic);
    recoParamArray->AddLast(vzeroRecoParam);
  }
  {
    AliVZERORecoParam * vzeroRecoParam = new AliVZERORecoParam;
    // the following two settings are needed to high lumi runs in 2011
    vzeroRecoParam->SetStartClock(9);
    vzeroRecoParam->SetEndClock(11);
    vzeroRecoParam->SetNPreClocks(1);
    vzeroRecoParam->SetNPostClocks(1);
    vzeroRecoParam->SetEventSpecie(AliRecoParam::kLowMult);
    recoParamArray->AddLast(vzeroRecoParam);
  }
  {
    AliVZERORecoParam * vzeroRecoParam = new AliVZERORecoParam;
    vzeroRecoParam->SetNPreClocks(6);
    vzeroRecoParam->SetEventSpecie(AliRecoParam::kHighMult);
    recoParamArray->AddLast(vzeroRecoParam);
  }

  // Set the default
  Bool_t defaultIsSet = kFALSE;
  for(Int_t i =0; i < recoParamArray->GetEntriesFast(); i++) {
    AliDetectorRecoParam *param = (AliDetectorRecoParam *)recoParamArray->UncheckedAt(i);
    if (!param) continue;
    if (default & param->GetEventSpecie()) {
      param->SetAsDefault();
      defaultIsSet = kTRUE;
    }
  }

  if (!defaultIsSet) {
    Error(macroname,"The default reconstruction parameters are not set! Exiting...");
    return;
  }

  // save in CDB storage
  AliCDBMetaData *md= new AliCDBMetaData();
  md->SetResponsible("Brigitte Cheynis");
  md->SetComment("Reconstruction parameters for VZERO");
  md->SetAliRootVersion(gSystem->Getenv("ARVERSION"));
  md->SetBeamPeriod(0);
  AliCDBId id("VZERO/Calib/RecoParam",0,AliCDBRunRange::Infinity());
  cdb->GetDefaultStorage()->Put(recoParamArray,id, md);

  return;
}
<commit_msg>Reducing the ADC search window for the forthcoming Pb-Pb run.<commit_after>void MakeVZERORecoParam(AliRecoParam::EventSpecie_t default=AliRecoParam::kLowMult) {
//========================================================================
//
// Steering macro for VZERO reconstruction parameters
//
// Author: Brigitte Cheynis
//
//========================================================================

  const char* macroname = "MakeVZERORecoParam.C";

  // Activate CDB storage and load geometry from CDB
  AliCDBManager* cdb = AliCDBManager::Instance();
  if(!cdb->IsDefaultStorageSet()) cdb->SetDefaultStorage("local://OCDB");

  TObjArray *recoParamArray = new TObjArray();

  {
    AliVZERORecoParam * vzeroRecoParam = new AliVZERORecoParam;
    vzeroRecoParam->SetEventSpecie(AliRecoParam::kCosmic);
    recoParamArray->AddLast(vzeroRecoParam);
  }
  {
    AliVZERORecoParam * vzeroRecoParam = new AliVZERORecoParam;
    // the following two settings are needed to high lumi runs in 2011
    vzeroRecoParam->SetStartClock(9);
    vzeroRecoParam->SetEndClock(11);
    vzeroRecoParam->SetNPreClocks(1);
    vzeroRecoParam->SetNPostClocks(1);
    vzeroRecoParam->SetEventSpecie(AliRecoParam::kLowMult);
    recoParamArray->AddLast(vzeroRecoParam);
  }
  {
    AliVZERORecoParam * vzeroRecoParam = new AliVZERORecoParam;
    vzeroRecoParam->SetStartClock(9);
    vzeroRecoParam->SetEndClock(11);
    vzeroRecoParam->SetNPreClocks(6);
    vzeroRecoParam->SetEventSpecie(AliRecoParam::kHighMult);
    recoParamArray->AddLast(vzeroRecoParam);
  }

  // Set the default
  Bool_t defaultIsSet = kFALSE;
  for(Int_t i =0; i < recoParamArray->GetEntriesFast(); i++) {
    AliDetectorRecoParam *param = (AliDetectorRecoParam *)recoParamArray->UncheckedAt(i);
    if (!param) continue;
    if (default & param->GetEventSpecie()) {
      param->SetAsDefault();
      defaultIsSet = kTRUE;
    }
  }

  if (!defaultIsSet) {
    Error(macroname,"The default reconstruction parameters are not set! Exiting...");
    return;
  }

  // save in CDB storage
  AliCDBMetaData *md= new AliCDBMetaData();
  md->SetResponsible("Brigitte Cheynis");
  md->SetComment("Reconstruction parameters for VZERO");
  md->SetAliRootVersion(gSystem->Getenv("ARVERSION"));
  md->SetBeamPeriod(0);
  AliCDBId id("VZERO/Calib/RecoParam",0,AliCDBRunRange::Infinity());
  cdb->GetDefaultStorage()->Put(recoParamArray,id, md);

  return;
}
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

/**
  \file    SystemInfo.cpp
  \author  Jens Krueger
           SCI Institute
           University of Utah
  \date    July 2008
*/

#include "SystemInfo.h"

#include "StdTuvokDefines.h"
#ifdef _WIN32
  #include <windows.h>
#else
  #ifdef DETECTED_OS_APPLE
    #include <sys/sysctl.h>
  #else
    #include <cstdio>
    #include <iostream>
    #include <sstream>
    #include <sys/resource.h>
    #include <sys/sysinfo.h>
    #include <sys/time.h>
    #include "IO/KeyValueFileParser.h"
  #endif
#endif

SystemInfo::SystemInfo(UINT64 iDefaultCPUMemSize, UINT64 iDefaultGPUMemSize) :
  m_iProgrammBitWith(sizeof(void*)*8),
  m_iUseMaxCPUMem(iDefaultCPUMemSize),
  m_iUseMaxGPUMem(iDefaultGPUMemSize),
  m_iCPUMemSize(iDefaultCPUMemSize),
  m_iGPUMemSize(iDefaultGPUMemSize),
  m_bIsCPUSizeComputed(false),
  m_bIsGPUSizeComputed(false),
  m_bIsNumberOfCPUsComputed(false),
  m_bIsDirectX10Capable(false)
{
  UINT32 iNumberOfCPUs = ComputeNumCPUs();
  if (iNumberOfCPUs > 0) {
    m_iNumberOfCPUs = iNumberOfCPUs;
    m_bIsNumberOfCPUsComputed = true;
  }

  UINT64 iCPUMemSize = ComputeCPUMemSize();
  if (iCPUMemSize > 0) {
    m_iCPUMemSize = iCPUMemSize;
    m_bIsCPUSizeComputed = true;
  }

  UINT64 iGPUMemSize = ComputeGPUMemory();  // also sets m_bIsDirectX10Capable
  if (iGPUMemSize > 0) {
    m_iGPUMemSize = iGPUMemSize;
    m_bIsGPUSizeComputed = true;
  }
}

UINT32 SystemInfo::ComputeNumCPUs() {
  #ifdef _WIN32
    SYSTEM_INFO siSysInfo;
    GetSystemInfo(&siSysInfo);
    return siSysInfo.dwNumberOfProcessors;
  #else
    #ifdef DETECTED_OS_APPLE
      return 0;
    #else
      return 0;
    #endif
  #endif
}

#ifdef __linux__

#ifndef NDEBUG
#   define DBG(str) do { std::cerr << str << std::endl; } while(0)
#else
#   define DBG(str) /* nothing */
#endif
static unsigned long lnx_mem_sysinfo() {
  struct sysinfo si;
  if(sysinfo(&si) < 0) {
    perror("sysinfo");
    return 0;
  }
  return si.totalram;
}

static UINT64 lnx_mem_rlimit() {
    struct rlimit limit;
    // RLIMIT_MEMLOCK returns 32768 (that's *bytes*) on my 6gb-RAM system, so
    // that number is worthless to us.
    // RLIMIT_DATA isn't great, because it gets the entire data segment size
    // allowable, not just the heap size ...
    if(getrlimit(RLIMIT_DATA, &limit) != 0) {
        perror("getrlimit");
        return 0;
    }
    // Frequently the information given by getrlimit(2) is essentially
    // worthless, because it assumes we don't care about swapping.
    if(limit.rlim_cur == RLIM_INFINITY || limit.rlim_max == RLIM_INFINITY) {
        DBG("getrlimit gave useless info...");
        return 0;
    }
    return limit.rlim_max;
}

static UINT64 lnx_mem_proc() {
  KeyValueFileParser meminfo("/proc/meminfo");

  if(!meminfo.FileReadable()) {
    DBG("could not open proc memory filesystem");
    return 0;
  }

  KeyValPair *mem_total = meminfo.GetData("MemTotal");
  if(mem_total == NULL) {
    DBG("proc mem fs did not have a `MemTotal' entry.");
    return 0;
  }
  std::istringstream mem_strm(mem_total->strValue);
  UINT64 mem;
  mem_strm >> mem;
  return mem * 1024;
}

static UINT64 lnx_mem() {
  UINT64 m;
  if((m = lnx_mem_proc()) == 0) {
    DBG("proc failed, falling back to rlimit");
    if((m = lnx_mem_rlimit()) == 0) {
      DBG("rlimit failed, falling back to sysinfo");
      if((m = lnx_mem_sysinfo()) == 0) {
        DBG("all memory lookups failed; pretending you have 1Gb of memory.");
        return 1024*1024*1024;
      }
    }
  }
  return m;
}
#endif

UINT64 SystemInfo::ComputeCPUMemSize() {
  #ifdef _WIN32
    MEMORYSTATUSEX statex;
    statex.dwLength = sizeof (statex);
    GlobalMemoryStatusEx (&statex);
    return statex.ullTotalPhys;
  #else
    #ifdef DETECTED_OS_APPLE
      UINT64 phys = 0;
      int mib[2] = { CTL_HW, HW_PHYSMEM };
      size_t len = sizeof(phys);
      if (sysctl(mib, 2, &phys, &len, NULL, 0) != 0) return 0;
      return phys;
    #elif defined(__linux__)
      return static_cast<UINT64>(lnx_mem());
    #else
      std::cerr << "Unknown system, can't lookup max memory.  "
                << "Using a hard setting of 10 gb." << std::endl;
      return 1024*1024*1024*10;
    #endif
  #endif
}

#if defined(_WIN32) && defined(USE_DIRECTX)
  #define INITGUID
  #include <string.h>
  #include <stdio.h>
  #include <assert.h>
  #include <d3d9.h>
  #include <multimon.h>

  #pragma comment( lib, "d3d9.lib" )

  HRESULT GetVideoMemoryViaDirectDraw( HMONITOR hMonitor, DWORD* pdwAvailableVidMem );
  HRESULT GetVideoMemoryViaDXGI( HMONITOR hMonitor, SIZE_T* pDedicatedVideoMemory, SIZE_T* pDedicatedSystemMemory, SIZE_T* pSharedSystemMemory );

  #ifndef SAFE_RELEASE
    #define SAFE_RELEASE(p)      { if (p) { (p)->Release(); (p)=NULL; } }
  #endif

  typedef IDirect3D9* ( WINAPI* LPDIRECT3DCREATE9 )( UINT  );
  LPDIRECT3DCREATE9 pDirect3DCreate9;

  UINT64 SystemInfo::ComputeGPUMemory( )
  {
    HINSTANCE hD3D9 = LoadLibrary( L"d3d9.dll" );
    if (!hD3D9) return 0;
    pDirect3DCreate9 = ( LPDIRECT3DCREATE9 )GetProcAddress( hD3D9, "Direct3DCreate9" );

    if (!pDirect3DCreate9) {
      FreeLibrary( hD3D9 );
      return 0;
    }

    IDirect3D9* pD3D9 = NULL;
    pD3D9 = pDirect3DCreate9( D3D_SDK_VERSION );
    if( pD3D9 )
    {
        UINT dwAdapterCount = pD3D9->GetAdapterCount();
        if (dwAdapterCount > 0) {
            UINT iAdapter = 0;

            HMONITOR hMonitor = pD3D9->GetAdapterMonitor( iAdapter );

            SIZE_T DedicatedVideoMemory;
            SIZE_T DedicatedSystemMemory;
            SIZE_T SharedSystemMemory;
            if( SUCCEEDED( GetVideoMemoryViaDXGI( hMonitor, &DedicatedVideoMemory, &DedicatedSystemMemory, &SharedSystemMemory ) ) )
            {
              m_bIsDirectX10Capable = true;
              SAFE_RELEASE( pD3D9 );
              return UINT64(DedicatedVideoMemory);
            } else {
              DWORD dwAvailableVidMem;
              if( SUCCEEDED( GetVideoMemoryViaDirectDraw( hMonitor, &dwAvailableVidMem ) ) ) {
                SAFE_RELEASE( pD3D9 );
                FreeLibrary( hD3D9 );
                return UINT64(DedicatedVideoMemory);
              } else {
                SAFE_RELEASE( pD3D9 );
                FreeLibrary( hD3D9 );
                return 0;
              }
            }
        }

        SAFE_RELEASE( pD3D9 );
        FreeLibrary( hD3D9 );
        return 0;
    }
    else
    {
        FreeLibrary( hD3D9 );
        return 0;
    }
  }

#else
  UINT64 SystemInfo::ComputeGPUMemory( )
  {
    #ifdef DETECTED_OS_APPLE
      return 0;
    #else // Linux
      return 0;
    #endif
  }
#endif
<commit_msg>changed StdTuvokDefines.h include to StdDefines.h include<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

/**
  \file    SystemInfo.cpp
  \author  Jens Krueger
           SCI Institute
           University of Utah
  \date    July 2008
*/

#include "SystemInfo.h"

#include "StdDefines.h"
#ifdef _WIN32
  #include <windows.h>
#else
  #ifdef DETECTED_OS_APPLE
    #include <sys/sysctl.h>
  #else
    #include <cstdio>
    #include <iostream>
    #include <sstream>
    #include <sys/resource.h>
    #include <sys/sysinfo.h>
    #include <sys/time.h>
    #include "IO/KeyValueFileParser.h"
  #endif
#endif

SystemInfo::SystemInfo(UINT64 iDefaultCPUMemSize, UINT64 iDefaultGPUMemSize) :
  m_iProgrammBitWith(sizeof(void*)*8),
  m_iUseMaxCPUMem(iDefaultCPUMemSize),
  m_iUseMaxGPUMem(iDefaultGPUMemSize),
  m_iCPUMemSize(iDefaultCPUMemSize),
  m_iGPUMemSize(iDefaultGPUMemSize),
  m_bIsCPUSizeComputed(false),
  m_bIsGPUSizeComputed(false),
  m_bIsNumberOfCPUsComputed(false),
  m_bIsDirectX10Capable(false)
{
  UINT32 iNumberOfCPUs = ComputeNumCPUs();
  if (iNumberOfCPUs > 0) {
    m_iNumberOfCPUs = iNumberOfCPUs;
    m_bIsNumberOfCPUsComputed = true;
  }

  UINT64 iCPUMemSize = ComputeCPUMemSize();
  if (iCPUMemSize > 0) {
    m_iCPUMemSize = iCPUMemSize;
    m_bIsCPUSizeComputed = true;
  }

  UINT64 iGPUMemSize = ComputeGPUMemory();  // also sets m_bIsDirectX10Capable
  if (iGPUMemSize > 0) {
    m_iGPUMemSize = iGPUMemSize;
    m_bIsGPUSizeComputed = true;
  }
}

UINT32 SystemInfo::ComputeNumCPUs() {
  #ifdef _WIN32
    SYSTEM_INFO siSysInfo;
    GetSystemInfo(&siSysInfo);
    return siSysInfo.dwNumberOfProcessors;
  #else
    #ifdef DETECTED_OS_APPLE
      return 0;
    #else
      return 0;
    #endif
  #endif
}

#ifdef __linux__

#ifndef NDEBUG
#   define DBG(str) do { std::cerr << str << std::endl; } while(0)
#else
#   define DBG(str) /* nothing */
#endif
static unsigned long lnx_mem_sysinfo() {
  struct sysinfo si;
  if(sysinfo(&si) < 0) {
    perror("sysinfo");
    return 0;
  }
  return si.totalram;
}

static UINT64 lnx_mem_rlimit() {
    struct rlimit limit;
    // RLIMIT_MEMLOCK returns 32768 (that's *bytes*) on my 6gb-RAM system, so
    // that number is worthless to us.
    // RLIMIT_DATA isn't great, because it gets the entire data segment size
    // allowable, not just the heap size ...
    if(getrlimit(RLIMIT_DATA, &limit) != 0) {
        perror("getrlimit");
        return 0;
    }
    // Frequently the information given by getrlimit(2) is essentially
    // worthless, because it assumes we don't care about swapping.
    if(limit.rlim_cur == RLIM_INFINITY || limit.rlim_max == RLIM_INFINITY) {
        DBG("getrlimit gave useless info...");
        return 0;
    }
    return limit.rlim_max;
}

static UINT64 lnx_mem_proc() {
  KeyValueFileParser meminfo("/proc/meminfo");

  if(!meminfo.FileReadable()) {
    DBG("could not open proc memory filesystem");
    return 0;
  }

  KeyValPair *mem_total = meminfo.GetData("MemTotal");
  if(mem_total == NULL) {
    DBG("proc mem fs did not have a `MemTotal' entry.");
    return 0;
  }
  std::istringstream mem_strm(mem_total->strValue);
  UINT64 mem;
  mem_strm >> mem;
  return mem * 1024;
}

static UINT64 lnx_mem() {
  UINT64 m;
  if((m = lnx_mem_proc()) == 0) {
    DBG("proc failed, falling back to rlimit");
    if((m = lnx_mem_rlimit()) == 0) {
      DBG("rlimit failed, falling back to sysinfo");
      if((m = lnx_mem_sysinfo()) == 0) {
        DBG("all memory lookups failed; pretending you have 1Gb of memory.");
        return 1024*1024*1024;
      }
    }
  }
  return m;
}
#endif

UINT64 SystemInfo::ComputeCPUMemSize() {
  #ifdef _WIN32
    MEMORYSTATUSEX statex;
    statex.dwLength = sizeof (statex);
    GlobalMemoryStatusEx (&statex);
    return statex.ullTotalPhys;
  #else
    #ifdef DETECTED_OS_APPLE
      UINT64 phys = 0;
      int mib[2] = { CTL_HW, HW_PHYSMEM };
      size_t len = sizeof(phys);
      if (sysctl(mib, 2, &phys, &len, NULL, 0) != 0) return 0;
      return phys;
    #elif defined(__linux__)
      return static_cast<UINT64>(lnx_mem());
    #else
      std::cerr << "Unknown system, can't lookup max memory.  "
                << "Using a hard setting of 10 gb." << std::endl;
      return 1024*1024*1024*10;
    #endif
  #endif
}

#if defined(_WIN32) && defined(USE_DIRECTX)
  #define INITGUID
  #include <string.h>
  #include <stdio.h>
  #include <assert.h>
  #include <d3d9.h>
  #include <multimon.h>

  #pragma comment( lib, "d3d9.lib" )

  HRESULT GetVideoMemoryViaDirectDraw( HMONITOR hMonitor, DWORD* pdwAvailableVidMem );
  HRESULT GetVideoMemoryViaDXGI( HMONITOR hMonitor, SIZE_T* pDedicatedVideoMemory, SIZE_T* pDedicatedSystemMemory, SIZE_T* pSharedSystemMemory );

  #ifndef SAFE_RELEASE
    #define SAFE_RELEASE(p)      { if (p) { (p)->Release(); (p)=NULL; } }
  #endif

  typedef IDirect3D9* ( WINAPI* LPDIRECT3DCREATE9 )( UINT  );
  LPDIRECT3DCREATE9 pDirect3DCreate9;

  UINT64 SystemInfo::ComputeGPUMemory( )
  {
    HINSTANCE hD3D9 = LoadLibrary( L"d3d9.dll" );
    if (!hD3D9) return 0;
    pDirect3DCreate9 = ( LPDIRECT3DCREATE9 )GetProcAddress( hD3D9, "Direct3DCreate9" );

    if (!pDirect3DCreate9) {
      FreeLibrary( hD3D9 );
      return 0;
    }

    IDirect3D9* pD3D9 = NULL;
    pD3D9 = pDirect3DCreate9( D3D_SDK_VERSION );
    if( pD3D9 )
    {
        UINT dwAdapterCount = pD3D9->GetAdapterCount();
        if (dwAdapterCount > 0) {
            UINT iAdapter = 0;

            HMONITOR hMonitor = pD3D9->GetAdapterMonitor( iAdapter );

            SIZE_T DedicatedVideoMemory;
            SIZE_T DedicatedSystemMemory;
            SIZE_T SharedSystemMemory;
            if( SUCCEEDED( GetVideoMemoryViaDXGI( hMonitor, &DedicatedVideoMemory, &DedicatedSystemMemory, &SharedSystemMemory ) ) )
            {
              m_bIsDirectX10Capable = true;
              SAFE_RELEASE( pD3D9 );
              return UINT64(DedicatedVideoMemory);
            } else {
              DWORD dwAvailableVidMem;
              if( SUCCEEDED( GetVideoMemoryViaDirectDraw( hMonitor, &dwAvailableVidMem ) ) ) {
                SAFE_RELEASE( pD3D9 );
                FreeLibrary( hD3D9 );
                return UINT64(DedicatedVideoMemory);
              } else {
                SAFE_RELEASE( pD3D9 );
                FreeLibrary( hD3D9 );
                return 0;
              }
            }
        }

        SAFE_RELEASE( pD3D9 );
        FreeLibrary( hD3D9 );
        return 0;
    }
    else
    {
        FreeLibrary( hD3D9 );
        return 0;
    }
  }

#else
  UINT64 SystemInfo::ComputeGPUMemory( )
  {
    #ifdef DETECTED_OS_APPLE
      return 0;
    #else // Linux
      return 0;
    #endif
  }
#endif
<|endoftext|>


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

#include <tools/link.hxx>
#include <tools/list.hxx>
#include <svtools/lstner.hxx>
#include <vcl/timer.hxx>
#include <tools/string.hxx>
#include "rtl/ref.hxx"

#include <com/sun/star/frame/XModel.hpp>

#include "bitset.hxx"

class SfxApplication;
class SvStrings;
class SfxProgress;
class SfxChildWinFactArr_Impl;
class SfxDdeDocTopics_Impl;
class DdeService;
class SfxEventConfiguration;
class SfxMacroConfig;
class SfxItemPool;
class SfxInitLinkList;
class SfxFilterMatcher;
class SvUShorts;
class ISfxTemplateCommon;
class SfxFilterMatcher;
class SfxCancelManager;
class SfxStatusDispatcher;
class SfxDdeTriggerTopic_Impl;
class SfxMiscCfg;
class SfxDocumentTemplates;
class SfxFrameArr_Impl;
class SvtSaveOptions;
class SvtUndoOptions;
class SvtHelpOptions;
class SfxObjectFactory;
class SfxObjectShell;
class ResMgr;
class Window;
class SfxTbxCtrlFactArr_Impl;
class SfxStbCtrlFactArr_Impl;
class SfxMenuCtrlFactArr_Impl;
class SfxViewFrameArr_Impl;
class SfxViewShellArr_Impl;
class SfxObjectShellArr_Impl;
class ResMgr;
class SimpleResMgr;
class SfxViewFrame;
class SfxSlotPool;
class SfxResourceManager;
class SfxDispatcher;
class SfxInterface;
class BasicManager;
class SfxBasicManagerHolder;
class SfxBasicManagerCreationListener;

namespace sfx2 { namespace appl { class ImeStatusWindow; } }

//=========================================================================
// SfxAppData_Impl
//=========================================================================

class SfxAppData_Impl
{
public:
    IndexBitSet                         aIndexBitSet;           // for counting noname documents
    Timer                               aLateInitTimer;
    String                              aLastDir;               // for IO dialog

    // DDE stuff
    DdeService*                         pDdeService;
    SfxDdeDocTopics_Impl*               pDocTopics;
    SfxDdeTriggerTopic_Impl*            pTriggerTopic;
    DdeService*                         pDdeService2;

    // single instance classes
    SfxChildWinFactArr_Impl*            pFactArr;
    SfxFrameArr_Impl*                   pTopFrames;

    // special members
    SfxInitLinkList*                    pInitLinkList;

    // application members
    SfxFilterMatcher*                   pMatcher;
    SfxCancelManager*                   pCancelMgr;
    ResMgr*                             pLabelResMgr;
    SfxStatusDispatcher*                pAppDispatch;
    SfxDocumentTemplates*               pTemplates;

    // global pointers
    SfxItemPool*                        pPool;
    SfxEventConfiguration*              pEventConfig;
    SvUShorts*                          pDisabledSlotList;
    SvStrings*                          pSecureURLs;
    SfxMiscCfg*                         pMiscConfig;
    SvtSaveOptions*                     pSaveOptions;
    SvtUndoOptions*                     pUndoOptions;
    SvtHelpOptions*                     pHelpOptions;

    // "current" functionality
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >
                                        m_xThisDocument;
    SfxProgress*                        pProgress;
    ISfxTemplateCommon*                 pTemplateCommon;

    USHORT                              nDocModalMode;              // counts documents in modal mode
    USHORT                              nAutoTabPageId;
    USHORT                              nBasicCallLevel;
    USHORT                              nRescheduleLocks;
    USHORT                              nInReschedule;
    USHORT                              nAsynchronCalls;

    rtl::Reference< sfx2::appl::ImeStatusWindow > m_xImeStatusWindow;

    SfxTbxCtrlFactArr_Impl*     pTbxCtrlFac;
    SfxStbCtrlFactArr_Impl*     pStbCtrlFac;
    SfxMenuCtrlFactArr_Impl*    pMenuCtrlFac;
    SfxViewFrameArr_Impl*       pViewFrames;
    SfxViewShellArr_Impl*       pViewShells;
    SfxObjectShellArr_Impl*     pObjShells;
    ResMgr*                     pSfxResManager;
    ResMgr*                     pOfaResMgr;
    SimpleResMgr*               pSimpleResManager;
    SfxBasicManagerHolder*      pBasicManager;
    SfxBasicManagerCreationListener*
                                pBasMgrListener;
    SfxViewFrame*               pViewFrame;
    SfxSlotPool*                pSlotPool;
    SfxResourceManager*         pResMgr;
    SfxDispatcher*              pAppDispat;     // Dispatcher falls kein Doc
    SfxInterface**              pInterfaces;

    USHORT                      nDocNo;             // Laufende Doc-Nummer (AutoName)
    USHORT                      nInterfaces;

    BOOL                        bDispatcherLocked:1;    // nichts ausf"uhren
    BOOL                        bDowning:1;   // TRUE ab Exit und danach
    BOOL                        bInQuit : 1;
    BOOL                        bInvalidateOnUnlock : 1;

                                SfxAppData_Impl( SfxApplication* );
                                ~SfxAppData_Impl();

    void                        UpdateApplicationSettings( BOOL bDontHide );
    SfxDocumentTemplates*       GetDocumentTemplates();
    DECL_STATIC_LINK(           SfxAppData_Impl, CreateDocumentTemplates, void* );
    void                        DeInitDDE();

    /** called when the Application's BasicManager has been created. This can happen
        explicitly in SfxApplication::GetBasicManager, or implicitly if a document's
        BasicManager is created before the application's BasicManager exists.
    */
    void                        OnApplicationBasicManagerCreated( BasicManager& _rManager );
};

#endif // #ifndef _SFX_APPDATA_HXX

<commit_msg>INTEGRATION: CWS odfversionwarning (1.15.34); FILE MERGED 2007/11/16 07:35:56 pb 1.15.34.1: fix: #i83653# BOOL bODFVersionWarningLater added<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: appdata.hxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: ihi $ $Date: 2007-11-26 18:24:02 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SFX_APPDATA_HXX
#define _SFX_APPDATA_HXX

#include <tools/link.hxx>
#include <tools/list.hxx>
#include <svtools/lstner.hxx>
#include <vcl/timer.hxx>
#include <tools/string.hxx>
#include "rtl/ref.hxx"

#include <com/sun/star/frame/XModel.hpp>

#include "bitset.hxx"

class SfxApplication;
class SvStrings;
class SfxProgress;
class SfxChildWinFactArr_Impl;
class SfxDdeDocTopics_Impl;
class DdeService;
class SfxEventConfiguration;
class SfxMacroConfig;
class SfxItemPool;
class SfxInitLinkList;
class SfxFilterMatcher;
class SvUShorts;
class ISfxTemplateCommon;
class SfxFilterMatcher;
class SfxCancelManager;
class SfxStatusDispatcher;
class SfxDdeTriggerTopic_Impl;
class SfxMiscCfg;
class SfxDocumentTemplates;
class SfxFrameArr_Impl;
class SvtSaveOptions;
class SvtUndoOptions;
class SvtHelpOptions;
class SfxObjectFactory;
class SfxObjectShell;
class ResMgr;
class Window;
class SfxTbxCtrlFactArr_Impl;
class SfxStbCtrlFactArr_Impl;
class SfxMenuCtrlFactArr_Impl;
class SfxViewFrameArr_Impl;
class SfxViewShellArr_Impl;
class SfxObjectShellArr_Impl;
class ResMgr;
class SimpleResMgr;
class SfxViewFrame;
class SfxSlotPool;
class SfxResourceManager;
class SfxDispatcher;
class SfxInterface;
class BasicManager;
class SfxBasicManagerHolder;
class SfxBasicManagerCreationListener;

namespace sfx2 { namespace appl { class ImeStatusWindow; } }

//=========================================================================
// SfxAppData_Impl
//=========================================================================

class SfxAppData_Impl
{
public:
    IndexBitSet                         aIndexBitSet;           // for counting noname documents
    Timer                               aLateInitTimer;
    String                              aLastDir;               // for IO dialog

    // DDE stuff
    DdeService*                         pDdeService;
    SfxDdeDocTopics_Impl*               pDocTopics;
    SfxDdeTriggerTopic_Impl*            pTriggerTopic;
    DdeService*                         pDdeService2;

    // single instance classes
    SfxChildWinFactArr_Impl*            pFactArr;
    SfxFrameArr_Impl*                   pTopFrames;

    // special members
    SfxInitLinkList*                    pInitLinkList;

    // application members
    SfxFilterMatcher*                   pMatcher;
    SfxCancelManager*                   pCancelMgr;
    ResMgr*                             pLabelResMgr;
    SfxStatusDispatcher*                pAppDispatch;
    SfxDocumentTemplates*               pTemplates;

    // global pointers
    SfxItemPool*                        pPool;
    SfxEventConfiguration*              pEventConfig;
    SvUShorts*                          pDisabledSlotList;
    SvStrings*                          pSecureURLs;
    SfxMiscCfg*                         pMiscConfig;
    SvtSaveOptions*                     pSaveOptions;
    SvtUndoOptions*                     pUndoOptions;
    SvtHelpOptions*                     pHelpOptions;

    // "current" functionality
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >
                                        m_xThisDocument;
    SfxProgress*                        pProgress;
    ISfxTemplateCommon*                 pTemplateCommon;

    USHORT                              nDocModalMode;              // counts documents in modal mode
    USHORT                              nAutoTabPageId;
    USHORT                              nBasicCallLevel;
    USHORT                              nRescheduleLocks;
    USHORT                              nInReschedule;
    USHORT                              nAsynchronCalls;

    rtl::Reference< sfx2::appl::ImeStatusWindow > m_xImeStatusWindow;

    SfxTbxCtrlFactArr_Impl*     pTbxCtrlFac;
    SfxStbCtrlFactArr_Impl*     pStbCtrlFac;
    SfxMenuCtrlFactArr_Impl*    pMenuCtrlFac;
    SfxViewFrameArr_Impl*       pViewFrames;
    SfxViewShellArr_Impl*       pViewShells;
    SfxObjectShellArr_Impl*     pObjShells;
    ResMgr*                     pSfxResManager;
    ResMgr*                     pOfaResMgr;
    SimpleResMgr*               pSimpleResManager;
    SfxBasicManagerHolder*      pBasicManager;
    SfxBasicManagerCreationListener*
                                pBasMgrListener;
    SfxViewFrame*               pViewFrame;
    SfxSlotPool*                pSlotPool;
    SfxResourceManager*         pResMgr;
    SfxDispatcher*              pAppDispat;     // Dispatcher falls kein Doc
    SfxInterface**              pInterfaces;

    USHORT                      nDocNo;             // Laufende Doc-Nummer (AutoName)
    USHORT                      nInterfaces;

    BOOL                        bDispatcherLocked:1;    // nichts ausf"uhren
    BOOL                        bDowning:1;   // TRUE ab Exit und danach
    BOOL                        bInQuit : 1;
    BOOL                        bInvalidateOnUnlock : 1;
    BOOL                        bODFVersionWarningLater : 1;

                                SfxAppData_Impl( SfxApplication* );
                                ~SfxAppData_Impl();

    void                        UpdateApplicationSettings( BOOL bDontHide );
    SfxDocumentTemplates*       GetDocumentTemplates();
    DECL_STATIC_LINK(           SfxAppData_Impl, CreateDocumentTemplates, void* );
    void                        DeInitDDE();

    /** called when the Application's BasicManager has been created. This can happen
        explicitly in SfxApplication::GetBasicManager, or implicitly if a document's
        BasicManager is created before the application's BasicManager exists.
    */
    void                        OnApplicationBasicManagerCreated( BasicManager& _rManager );
};

#endif // #ifndef _SFX_APPDATA_HXX

<|endoftext|>


<commit_before><commit_msg>Gui: [skip ci] fix bug when keyboard tracking for QuantitySpinBox is disabled and value is changed by mouse wheel or the spin buttons<commit_after><|endoftext|>


<commit_before>/*
 * Copyright 2014-2017 Jouni Roivas
 */

#include "blieng/path.h"

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <cmath>

#ifndef M_PI
#define M_PI 3.14159
#endif

using blieng::Path;

Path::Path()
{
}

Path::~Path()
{
}

std::string Path::toString() const
{
    std::string res = "";

    bool first = true;
    for (blieng::Point pt : points) {
        if (!first) res += ";";
        first = false;
        res += pt.toString();
    }
    return res;
}

void Path::addPoint(Point pt)
{
    points.push_back(pt);
}

int Path::getPointIndex(Point point)
{
    int index = 0;
    for (blieng::Point pt : points) {
        if (point == pt) return index;
        ++index;
    }
    return -1;
}

blieng::Point Path::getPointAt(unsigned int index)
{
    if (index >=0 && index < size()) {
        return points[index];
    }
    return Point();
}

void Path::updatePointAt(unsigned int index, Point new_point)
{
    if (index >= points.size()) return;

    points[index] = new_point;
}

void Path::updatePoint(Point point, Point new_point)
{
    auto pi = points.begin();
    while (pi != points.end()) {
        if ((*pi) == point) {
            (*pi).update(new_point);
        }
        ++pi;
    }
}

void Path::append(Path another)
{
    points.insert(points.end(), another.points.begin(), another.points.end());
}

Path Path::combine(Path another) const
{
    Path newpath;
    newpath.append(*this);
    newpath.append(another);

    return newpath;
}

blieng::Point Path::takeFirst()
{
    if (points.empty())
        return blieng::Point(false);

    blieng::Point res = points.front();
    points.erase(points.begin());
    return res;
}

blieng::Point Path::takeLast()
{
    if (points.empty())
        return blieng::Point(false);

    blieng::Point res = points.back();
    points.erase(points.end());
    return res;
}

blieng::Point Path::getStart()
{
    if (points.empty())
        return blieng::Point(false);

    return points.front();
}

bool Path::isValid()
{
    return !points.empty();
}

blieng::Point Path::getEnd()
{
    if (points.empty())
        return blieng::Point(false);

    return points.back();
}

void Path::reverse()
{
    std::reverse(points.begin(), points.end());
}

Path Path::copy() const
{
    Path newpath;
    for (blieng::Point pt : points) {
        newpath.addPoint(pt);
    }

    return newpath;
}

Path Path::reversed() const
{
    Path rev_path = this->copy();
    rev_path.reverse();
    return rev_path;
}

double Path::length() const
{
    double len = 0.0;

    blieng::Point f(false);
    for (blieng::Point pt : points) {
        if (f.isValid() && pt != f) {
            len += f.length(pt);
        }
        f = pt;
    }

    return len;
}

double Path::lengthGeo() const
{
    double len = 0.0;

    blieng::Point f(false);
    for (blieng::Point pt : points) {
        if (f.isValid() && pt != f) {
            len += f.lengthGeo(pt);
        }
        f = pt;
    }

    return len;
}

double Path::simpleArea() const
{
    double res = 0;
    blieng::Point f(false);
    for (blieng::Point pt : points) {
        if (f.isValid() && pt != f) {
            res += f.x * pt.y - f.y * pt.x;
        }
        f = pt;
    }

    return fabs(res) / 2.0;
}

template<typename T> std::vector<blieng::Complex> cmplxI(std::pair<blieng::Complex,blieng::Complex> s, T a, blieng::Complex b=blieng::Complex(0,1))
{
    std::vector<blieng::Complex> res;
    blieng::Complex c = s.first;
    blieng::Complex d = s.second;

    d = d - c;
    c = c - a;

    double e = (d * b.conjugate()).imag();
    double e2 = e * e;
    if (! (e && (0 <= e2 && e2 <= e*e))) {
        return res;
    }

    double t2 = (d * c.conjugate()).imag();
    blieng::Complex t3 = b / e;
    blieng::Complex t4 = t3 * t2;

    double v = e * (b * c.conjugate()).imag();
    if (e && (0 <= v && v <= e2)) {
        res.push_back(t4 + a);
    }
    return res;
}

template<typename T> std::vector<std::pair<T,T>> expandTypes(std::vector<T> inp)
{
    std::vector<std::pair<T,T>> res;
    for (unsigned int i = 0; i < inp.size(); ++i) {
        T a = inp[i];
        T b;
        if (i == inp.size() - 1) {
            b = inp[0];
        } else {
            b = inp[i + 1];
        }
        res.push_back(std::pair<T,T>(a, b));
    }
    return res;
}

double complexArea(std::vector<blieng::Complex> inp)
{
    auto P = expandTypes<blieng::Complex>(inp);
    std::vector<double> i_real;
    for (auto ab : P) {
        blieng::Complex a = ab.first;
        blieng::Complex b = ab.second;
        for (auto e : P) {
            for (auto i : cmplxI<blieng::Complex>(e, a, b - a)) {
                i_real.push_back(i.real());
            }
        }
    }
    std::sort(i_real.begin(), i_real.end());

    auto lr = expandTypes<double>(i_real);
    lr.pop_back();

    std::vector<std::pair<double,double>> bt;
    double ar = 0;
    for (auto tlr : lr) {
        std::vector<double> ij_imag;
        double l = tlr.first;
        double r = tlr.second;
        for (auto e : P) {
            for (auto i : cmplxI<double>(e, l)) {
                for (auto j : cmplxI<double>(e, r)) {
                    ij_imag.push_back(((i + j).conjugate()).imag());
                }
            }
        }
        std::sort(ij_imag.begin(), ij_imag.end());
        auto ij_pairs = expandTypes<double>(ij_imag);
        bool tock = true;
        for (auto i : ij_pairs) {
            if (tock) {
                double b = i.first;
                double t = i.second;
                ar += (t - b) * (r - l) / 2;
            }
            tock ^= true;
        }
    }

    return ar;
}

double Path::area() const
{
    if (points.size() < 3) {
        return 0;
    }
    std::vector<blieng::Complex> tmp;
    for (auto pt : points) {
        tmp.push_back(pt.toComplex());
    }
    return complexArea(tmp);
}

double Path::areaGeo() const
{
    Path tmp;
    for (auto pt : points) {
        tmp.addPoint(pt.geoToMeters());
    }
    return tmp.area();
}

bool Path::operator==(const Path &other) const
{
    size_t psize = points.size();
    if (other.points.size() != psize) return false;

    auto a = points.cbegin();
    auto b = other.points.begin();
    while (a != points.cend()) {
        if (*a != *b) return false;
        ++a;
        ++b;
    }

    return true;
}

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

unsigned int Path::size() const
{
    return points.size();
}

double Path::getPartAngle(unsigned int index) const
{
    unsigned int prev = 0;
    if (index > 0) {
        prev = index - 1;
    } else {
        prev = points.size() - 1;
    }
    unsigned int next = index + 1;
    if (next > size()) {
        return 0.0;
    }
    if (next == size()) {
        next = 0;
    }

    if (prev < 0) {
        return 0.0;
    }
    Point p1 = points[index];
    Point p2 = points[next];
    Point p3 = points[prev];

    double a1 = p1.x - p2.x;
    double a2 = p1.y - p2.y;
    double b1 = p1.x - p3.x;
    double b2 = p1.y - p3.y;
    double c1 = p3.x - p2.x;
    double c2 = p3.y - p2.y;

    double p0c = sqrt(a1 * a1 + a2 * a2);
    double p1c = sqrt(b1 * b1 + b2 * b2);
    double p0p1 = sqrt(c1 * c1 + c2 * c2);
    double angle_rad = acos(
        (p1c * p1c + p0c * p0c - p0p1 * p0p1) /
        (2 * p1c * p0c)
        );

    return angle_rad * 180 / M_PI;
}
<commit_msg>Refactor to only one PI constant<commit_after>/*
 * Copyright 2014-2017 Jouni Roivas
 */

#include "blieng/path.h"
#include "blieng/blieng.h"

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <cmath>

using blieng::Path;

Path::Path()
{
}

Path::~Path()
{
}

std::string Path::toString() const
{
    std::string res = "";

    bool first = true;
    for (blieng::Point pt : points) {
        if (!first) res += ";";
        first = false;
        res += pt.toString();
    }
    return res;
}

void Path::addPoint(Point pt)
{
    points.push_back(pt);
}

int Path::getPointIndex(Point point)
{
    int index = 0;
    for (blieng::Point pt : points) {
        if (point == pt) return index;
        ++index;
    }
    return -1;
}

blieng::Point Path::getPointAt(unsigned int index)
{
    if (index >=0 && index < size()) {
        return points[index];
    }
    return Point();
}

void Path::updatePointAt(unsigned int index, Point new_point)
{
    if (index >= points.size()) return;

    points[index] = new_point;
}

void Path::updatePoint(Point point, Point new_point)
{
    auto pi = points.begin();
    while (pi != points.end()) {
        if ((*pi) == point) {
            (*pi).update(new_point);
        }
        ++pi;
    }
}

void Path::append(Path another)
{
    points.insert(points.end(), another.points.begin(), another.points.end());
}

Path Path::combine(Path another) const
{
    Path newpath;
    newpath.append(*this);
    newpath.append(another);

    return newpath;
}

blieng::Point Path::takeFirst()
{
    if (points.empty())
        return blieng::Point(false);

    blieng::Point res = points.front();
    points.erase(points.begin());
    return res;
}

blieng::Point Path::takeLast()
{
    if (points.empty())
        return blieng::Point(false);

    blieng::Point res = points.back();
    points.erase(points.end());
    return res;
}

blieng::Point Path::getStart()
{
    if (points.empty())
        return blieng::Point(false);

    return points.front();
}

bool Path::isValid()
{
    return !points.empty();
}

blieng::Point Path::getEnd()
{
    if (points.empty())
        return blieng::Point(false);

    return points.back();
}

void Path::reverse()
{
    std::reverse(points.begin(), points.end());
}

Path Path::copy() const
{
    Path newpath;
    for (blieng::Point pt : points) {
        newpath.addPoint(pt);
    }

    return newpath;
}

Path Path::reversed() const
{
    Path rev_path = this->copy();
    rev_path.reverse();
    return rev_path;
}

double Path::length() const
{
    double len = 0.0;

    blieng::Point f(false);
    for (blieng::Point pt : points) {
        if (f.isValid() && pt != f) {
            len += f.length(pt);
        }
        f = pt;
    }

    return len;
}

double Path::lengthGeo() const
{
    double len = 0.0;

    blieng::Point f(false);
    for (blieng::Point pt : points) {
        if (f.isValid() && pt != f) {
            len += f.lengthGeo(pt);
        }
        f = pt;
    }

    return len;
}

double Path::simpleArea() const
{
    double res = 0;
    blieng::Point f(false);
    for (blieng::Point pt : points) {
        if (f.isValid() && pt != f) {
            res += f.x * pt.y - f.y * pt.x;
        }
        f = pt;
    }

    return fabs(res) / 2.0;
}

template<typename T> std::vector<blieng::Complex> cmplxI(std::pair<blieng::Complex,blieng::Complex> s, T a, blieng::Complex b=blieng::Complex(0,1))
{
    std::vector<blieng::Complex> res;
    blieng::Complex c = s.first;
    blieng::Complex d = s.second;

    d = d - c;
    c = c - a;

    double e = (d * b.conjugate()).imag();
    double e2 = e * e;
    if (! (e && (0 <= e2 && e2 <= e*e))) {
        return res;
    }

    double t2 = (d * c.conjugate()).imag();
    blieng::Complex t3 = b / e;
    blieng::Complex t4 = t3 * t2;

    double v = e * (b * c.conjugate()).imag();
    if (e && (0 <= v && v <= e2)) {
        res.push_back(t4 + a);
    }
    return res;
}

template<typename T> std::vector<std::pair<T,T>> expandTypes(std::vector<T> inp)
{
    std::vector<std::pair<T,T>> res;
    for (unsigned int i = 0; i < inp.size(); ++i) {
        T a = inp[i];
        T b;
        if (i == inp.size() - 1) {
            b = inp[0];
        } else {
            b = inp[i + 1];
        }
        res.push_back(std::pair<T,T>(a, b));
    }
    return res;
}

double complexArea(std::vector<blieng::Complex> inp)
{
    auto P = expandTypes<blieng::Complex>(inp);
    std::vector<double> i_real;
    for (auto ab : P) {
        blieng::Complex a = ab.first;
        blieng::Complex b = ab.second;
        for (auto e : P) {
            for (auto i : cmplxI<blieng::Complex>(e, a, b - a)) {
                i_real.push_back(i.real());
            }
        }
    }
    std::sort(i_real.begin(), i_real.end());

    auto lr = expandTypes<double>(i_real);
    lr.pop_back();

    std::vector<std::pair<double,double>> bt;
    double ar = 0;
    for (auto tlr : lr) {
        std::vector<double> ij_imag;
        double l = tlr.first;
        double r = tlr.second;
        for (auto e : P) {
            for (auto i : cmplxI<double>(e, l)) {
                for (auto j : cmplxI<double>(e, r)) {
                    ij_imag.push_back(((i + j).conjugate()).imag());
                }
            }
        }
        std::sort(ij_imag.begin(), ij_imag.end());
        auto ij_pairs = expandTypes<double>(ij_imag);
        bool tock = true;
        for (auto i : ij_pairs) {
            if (tock) {
                double b = i.first;
                double t = i.second;
                ar += (t - b) * (r - l) / 2;
            }
            tock ^= true;
        }
    }

    return ar;
}

double Path::area() const
{
    if (points.size() < 3) {
        return 0;
    }
    std::vector<blieng::Complex> tmp;
    for (auto pt : points) {
        tmp.push_back(pt.toComplex());
    }
    return complexArea(tmp);
}

double Path::areaGeo() const
{
    Path tmp;
    for (auto pt : points) {
        tmp.addPoint(pt.geoToMeters());
    }
    return tmp.area();
}

bool Path::operator==(const Path &other) const
{
    size_t psize = points.size();
    if (other.points.size() != psize) return false;

    auto a = points.cbegin();
    auto b = other.points.begin();
    while (a != points.cend()) {
        if (*a != *b) return false;
        ++a;
        ++b;
    }

    return true;
}

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

unsigned int Path::size() const
{
    return points.size();
}

double Path::getPartAngle(unsigned int index) const
{
    unsigned int prev = 0;
    if (index > 0) {
        prev = index - 1;
    } else {
        prev = points.size() - 1;
    }
    unsigned int next = index + 1;
    if (next > size()) {
        return 0.0;
    }
    if (next == size()) {
        next = 0;
    }

    if (prev < 0) {
        return 0.0;
    }
    Point p1 = points[index];
    Point p2 = points[next];
    Point p3 = points[prev];

    double a1 = p1.x - p2.x;
    double a2 = p1.y - p2.y;
    double b1 = p1.x - p3.x;
    double b2 = p1.y - p3.y;
    double c1 = p3.x - p2.x;
    double c2 = p3.y - p2.y;

    double p0c = sqrt(a1 * a1 + a2 * a2);
    double p1c = sqrt(b1 * b1 + b2 * b2);
    double p0p1 = sqrt(c1 * c1 + c2 * c2);
    double angle_rad = acos(
        (p1c * p1c + p0c * p0c - p0p1 * p0p1) /
        (2 * p1c * p0c)
        );

    return angle_rad * 180 / blieng::PI;
}
<|endoftext|>


<commit_before>#pragma once

#include <iostream>
#include <sstream>

#include <boost/property_tree/ptree.hpp>
#include <boost/throw_exception.hpp>

#if defined(__clang__)
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wshadow"
# include <boost/property_tree/json_parser.hpp>
# pragma clang diagnostic pop
#else
# include <boost/property_tree/json_parser.hpp>
#endif

// Source locations were added in boost 1.73.
#include <boost/version.hpp>
#if (BOOST_VERSION > 107300)
#include <boost/assert/source_location.hpp>
#endif

#include <valijson/utils/file_utils.hpp>
#include <valijson/exceptions.hpp>

#if !VALIJSON_USE_EXCEPTION

namespace boost {

// Boost requires used-defined exception throwers when exceptions are
// disabled.
BOOST_NORETURN void throw_exception(std::exception const & e ) {
 valijson::throwRuntimeError(e.what());
}

#if (BOOST_VERSION > 107300)
BOOST_NORETURN void throw_exception(std::exception const & e, boost::source_location const & loc ) {
  valijson::throwRuntimeError(e.what());
}
#endif

}  // namespace boost

#endif

namespace valijson {
namespace utils {

inline bool loadDocument(const std::string &path, boost::property_tree::ptree &document)
{
#if !defined(BOOST_NO_EXCEPTIONS)
    try {
#endif
        boost::property_tree::read_json(path, document);
#if !defined(BOOST_NO_EXCEPTIONS)
    } catch (std::exception &e) {
        std::cerr << "Boost Property Tree JSON parser failed to parse the document:" << std::endl;
        std::cerr << e.what() << std::endl;
        return false;
    }
#endif

    return true;
}

}  // namespace utils
}  // namespace valijson
<commit_msg>add version checks around BOOST_NORETURN<commit_after>#pragma once

#include <iostream>
#include <sstream>

#include <boost/property_tree/ptree.hpp>
#include <boost/throw_exception.hpp>

#if defined(__clang__)
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wshadow"
# include <boost/property_tree/json_parser.hpp>
# pragma clang diagnostic pop
#else
# include <boost/property_tree/json_parser.hpp>
#endif

// Source locations were added in boost 1.73.
#include <boost/version.hpp>
#if (BOOST_VERSION > 107300)
#include <boost/assert/source_location.hpp>
#endif

#include <valijson/utils/file_utils.hpp>
#include <valijson/exceptions.hpp>

#if !VALIJSON_USE_EXCEPTION

namespace boost {

// Boost requires used-defined exception throwers when exceptions are
// disabled.
// NOTE: BOOST_NORETURN attribute was added in 1.71.
#if (BOOST_VERSION >= 107100)
BOOST_NORETURN
#endif
void throw_exception(std::exception const & e ) {
 valijson::throwRuntimeError(e.what());
}

// Source location override was added in 1.73.
#if (BOOST_VERSION >= 107300)
BOOST_NORETURN
void throw_exception(std::exception const & e, boost::source_location const & loc ) {
  valijson::throwRuntimeError(e.what());
}
#endif

}  // namespace boost

#endif

namespace valijson {
namespace utils {

inline bool loadDocument(const std::string &path, boost::property_tree::ptree &document)
{
#if !defined(BOOST_NO_EXCEPTIONS)
    try {
#endif
        boost::property_tree::read_json(path, document);
#if !defined(BOOST_NO_EXCEPTIONS)
    } catch (std::exception &e) {
        std::cerr << "Boost Property Tree JSON parser failed to parse the document:" << std::endl;
        std::cerr << e.what() << std::endl;
        return false;
    }
#endif

    return true;
}

}  // namespace utils
}  // namespace valijson
<|endoftext|>


<commit_before>//needed for testing
#define CATCH_CONFIG_RUNNER
#include <catch.hpp>

//other stuff needed
#include <glm/vec3.hpp>
#include <cmath>
#include <iostream>

//include classes for testing
#include "shape.hpp"
#include "sphere.hpp"
#include "box.hpp"
#include "material.hpp"
#include "color.hpp"

// ----------------------------------
// SHAPE TESTS
// ----------------------------------

//karos änderung

TEST_CASE("getter shape","[shape]")
{
	Sphere s {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f},1.0f};
	REQUIRE(s.get_name() == "name");

	Material c{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f};
	REQUIRE(s.get_material() == c); //added operator == in color.hpp
}

TEST_CASE("operator<< and print shape","[shape]")
{
	Sphere es {"empty_sphere"};
	std::cout << es;

	Sphere s {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f},1.0f};
	std::cout << s;
}

// ----------------------------------
// SPHERE TESTS
// ----------------------------------

TEST_CASE("constructors of sphere","[sphere]")
{
	Sphere s1 {"name"};
	Sphere s2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f};

	REQUIRE(s1.get_center() == s2.get_center());
	REQUIRE(s1.get_radius() == s2.get_radius());
}

TEST_CASE("get_center and get_radius","[sphere]")
{
	Sphere s {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f};

	REQUIRE(s.get_radius() == 1.0f);
	REQUIRE(s.get_center() == glm::vec3{0.0f});
}

TEST_CASE("area","[sphere]")
{
	Sphere s {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f};
	REQUIRE(12.566f == Approx(s.area()).epsilon(0.001));
}

TEST_CASE("volume","[sphere]")
{
	Sphere s {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f};
	REQUIRE(4.189 == Approx(s.volume()).epsilon(0.001));
}

TEST_CASE("print sphere","[sphere]")
{
	Sphere es {"empty_sphere"};
	std::cout << es;

	Sphere s {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f},1.0f};
	std::cout << s;
}

// ----------------------------------
// BOX TESTS
// ----------------------------------

TEST_CASE("constructors of box","[box]")
{
	Box b1 {"name"};
	Box b2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, glm::vec3{1.0f}};

	REQUIRE(b1.get_min() == b2.get_min());
	REQUIRE(b1.get_max() == b2.get_max());
}

TEST_CASE("get_min and get_max","[box]")
{
	Box b2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, glm::vec3{1.0f}};

	REQUIRE(b2.get_min() == glm::vec3{0.0f});
	REQUIRE(b2.get_max() == glm::vec3{1.0f});
}

TEST_CASE("area of box","[box]")
{
	Box b2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, glm::vec3{1.0f}};
	REQUIRE(6.0f == Approx(b2.area()).epsilon(0.001));
}

TEST_CASE("volume of box","[box]")
{
	Box b2 {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f}, glm::vec3{0.0f}, glm::vec3{1.0f}};

	REQUIRE(1.0f == Approx(b2.volume()).epsilon(0.001));
}

TEST_CASE("print box","[box]")
{
	Box eb {"empty_box"};
	std::cout << eb;

	Box b {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f}, glm::vec3{0.0f}, glm::vec3{1.0f}};
	std::cout << b;
}

// ----------------------------------
// AUFGABE 5.6 TEST
// ----------------------------------

TEST_CASE("intersectRaySphere", "[intersect]")
{
	//Ray
	glm::vec3 ray_origin{0.0f, 0.0f, 0.0f};
	//ray direction has to be normalized !
	//you can use:
		//v = glm::normalize(some_vector);
	glm::vec3 ray_direction{0.0f, 0.0f, 1.0f};

	//Sphere
	glm::vec3 sphere_center{0.0f, 0.0f, 5.0f};
	float sphere_radius{1.0f};

	float distance{0.0f};
	auto result = glm::intersectRaySphere(
		ray_origin, ray_direction,
		sphere_center,
		sphere_radius * sphere_radius,
		distance);

	REQUIRE(distance == Approx(4.0f));

	Sphere s {"some_sphere", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},
		sphere_center, sphere_radius};

	Ray r {ray_origin,ray_direction};

	s.intersect(r,distance);

	REQUIRE(distance == Approx(4.0f));
}

// ----------------------------------
// AUFGABE 5.8 TEST
// ----------------------------------

TEST_CASE("virtual", "[Destructors]")
{

	std::cout << "\ntesting virtual and non-virtual construction and destruction\n";

	Color c_red {255.0f, 0.0f, 0.0f};
	Material red {"", c_red, c_red, c_red, 0.0f};

	glm::vec3 position {0.0f,0.0f,0.0f};

	std::cout << "Create s1\n";
	Sphere* s1 = new Sphere("sphere0",red,position,1.2f);
	std::cout << "Create s2\n";
	Shape* s2 = new Sphere("sphere1",red,position,1.2f);

	std::cout << "Printing objects: \n";
	std::cout << *s1;
	std::cout << *s2 << "\n";

	std::cout << "Delete s1\n";
	delete s1;
	std::cout << "Delete s2\n";
	delete s2;
}

// ----------------------------------
// MATERIAL Tests
// ----------------------------------

TEST_CASE("material in place of color struct", "Material")
{
	Color c{0.0f,0.0f,0.0f};
	Material mate1 {};
	std::cout << mate1;

	Material mate2 {"some material",c,c,c,0.0f};
	std::cout << mate2;
}

int main(int argc, char *argv[])
{
  return Catch::Session().run(argc, argv);
}
<commit_msg>:heart:<commit_after>//needed for testing
#define CATCH_CONFIG_RUNNER
#include <catch.hpp>

//other stuff needed
#include <glm/vec3.hpp>
#include <cmath>
#include <iostream>

//include classes for testing
#include "shape.hpp"
#include "sphere.hpp"
#include "box.hpp"
#include "material.hpp"
#include "color.hpp"

// ----------------------------------
// SHAPE TESTS
// ----------------------------------

//karos änderung

TEST_CASE("getter shape","[shape]")
{
	Sphere s {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f},1.0f};
	REQUIRE(s.get_name() == "name");

	Material c{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f};
	REQUIRE(s.get_material() == c); //added operator == in color.hpp
}

TEST_CASE("operator<< and print shape","[shape]")
{
	Sphere es {"empty_sphere"};
	std::cout << es;

	Sphere s {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f},1.0f};
	std::cout << s;
}

// ----------------------------------
// SPHERE TESTS
// ----------------------------------

TEST_CASE("constructors of sphere","[sphere]")
{
	Sphere s1 {"name"};
	Sphere s2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f};

	REQUIRE(s1.get_center() == s2.get_center());
	REQUIRE(s1.get_radius() == s2.get_radius());
}

TEST_CASE("get_center and get_radius","[sphere]")
{
	Sphere s {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f};

	REQUIRE(s.get_radius() == 1.0f);
	REQUIRE(s.get_center() == glm::vec3{0.0f});
}

TEST_CASE("area","[sphere]")
{
	Sphere s {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f};
	REQUIRE(12.566f == Approx(s.area()).epsilon(0.001));
}

TEST_CASE("volume","[sphere]")
{
	Sphere s {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, 1.0f};
	REQUIRE(4.189 == Approx(s.volume()).epsilon(0.001));
}

TEST_CASE("print sphere","[sphere]")
{
	Sphere es {"empty_sphere"};
	std::cout << es;

	Sphere s {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f},1.0f};
	std::cout << s;
}

// ----------------------------------
// BOX TESTS
// ----------------------------------

TEST_CASE("constructors of box","[box]")
{
	Box b1 {"name"};
	Box b2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, glm::vec3{1.0f}};

	REQUIRE(b1.get_min() == b2.get_min());
	REQUIRE(b1.get_max() == b2.get_max());
}

TEST_CASE("get_min and get_max","[box]")
{
	Box b2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, glm::vec3{1.0f}};

	REQUIRE(b2.get_min() == glm::vec3{0.0f});
	REQUIRE(b2.get_max() == glm::vec3{1.0f});
}

TEST_CASE("area of box","[box]")
{
	Box b2 {"name",Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},glm::vec3{0.0f}, glm::vec3{1.0f}};
	REQUIRE(6.0f == Approx(b2.area()).epsilon(0.001));
}

TEST_CASE("volume of box","[box]")
{
	Box b2 {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f}, glm::vec3{0.0f}, glm::vec3{1.0f}};

	REQUIRE(1.0f == Approx(b2.volume()).epsilon(0.001));
}

TEST_CASE("print box","[box]")
{
	Box eb {"empty_box"};
	std::cout << eb;

	Box b {"name", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f}, glm::vec3{0.0f}, glm::vec3{1.0f}};
	std::cout << b;
}

// ----------------------------------
// AUFGABE 5.6 TEST
// ----------------------------------

TEST_CASE("intersectRaySphere", "[intersect]")
{
	//Ray
	glm::vec3 ray_origin{0.0f, 0.0f, 0.0f};
	//ray direction has to be normalized !
	//you can use:
		//v = glm::normalize(some_vector);
	glm::vec3 ray_direction{0.0f, 0.0f, 1.0f};

	//Sphere
	glm::vec3 sphere_center{0.0f, 0.0f, 5.0f};
	float sphere_radius{1.0f};

	float distance{0.0f};
	auto result = glm::intersectRaySphere(
		ray_origin, ray_direction,
		sphere_center,
		sphere_radius * sphere_radius,
		distance);

	REQUIRE(distance == Approx(4.0f));

	Sphere s {"some_sphere", Material{"",Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},Color{0.0f,0.0f,0.0f},0.0f},
		sphere_center, sphere_radius};

	Ray r {ray_origin,ray_direction};

	s.intersect(r,distance);

	REQUIRE(distance == Approx(4.0f));
}

// ----------------------------------
// AUFGABE 5.8 TEST
// ----------------------------------

TEST_CASE("virtual", "[Destructors]")
{

	std::cout << "\ntesting virtual and non-virtual construction and destruction\n";

	Color c_red {255.0f, 0.0f, 0.0f};
	Material red {"", c_red, c_red, c_red, 0.0f};

	glm::vec3 position {0.0f,0.0f,0.0f};

	std::cout << "Create s1\n";
	Sphere* s1 = new Sphere("sphere0",red,position,1.2f);
	std::cout << "Create s2\n";
	Shape* s2 = new Sphere("sphere1",red,position,1.2f);

	std::cout << "Printing objects: \n";
	std::cout << *s1;
	std::cout << *s2 << "\n";

	std::cout << "Delete s1\n";
	delete s1;
	std::cout << "Delete s2\n";
	delete s2;
}

// ----------------------------------
// MATERIAL Tests
// ----------------------------------

TEST_CASE("material in place of color struct", "Material")
{
	Color c{0.0f,0.0f,0.0f};
	Material mate1 {};
	std::cout << mate1;

	Material mate2 {"some material",c,c,c,0.0f};
	std::cout << mate2;
}

int main(int argc, char *argv[])
{
  return Catch::Session().run(argc, argv);
}

//lissylissylissy <33333
<|endoftext|>