<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2014.  All rights reserved
 */
#ifndef _Stroika_Foundation_Traversal_Range_inl_
#define _Stroika_Foundation_Traversal_Range_inl_

#include    "../Debug/Assertions.h"
#include    "../Math/Overlap.h"

namespace   Stroika {
    namespace   Foundation {
        namespace   Traversal {

            /*
             ********************************************************************************
             RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>
             ********************************************************************************
             */
#if     qCompilerAndStdLib_constexpr_Buggy
            template    <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE>
            const T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kLowerBound   =   MIN;
            template    <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE>
            const T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kUpperBound   =   MAX;
#else
            template    <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE>
            constexpr T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kLowerBound;
            template    <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE>
            constexpr T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kUpperBound;
#endif

            /*
             ********************************************************************************
             ****************** RangeTraits::DefaultRangeTraits<T> **************************
             ********************************************************************************
             */
#if     qCompilerAndStdLib_constexpr_Buggy
            template    <typename T>
            const T RangeTraits::DefaultRangeTraits<T>::kLowerBound     =   numeric_limits<T>::lowest ();
            template    <typename T>
            const T RangeTraits::DefaultRangeTraits<T>::kUpperBound     =   numeric_limits<T>::max ();
#else
            template    <typename T>
            constexpr T RangeTraits::DefaultRangeTraits<T>::kLowerBound;
            template    <typename T>
            constexpr T RangeTraits::DefaultRangeTraits<T>::kUpperBound;
#endif

            /*
             ********************************************************************************
             ***************************** Range<T, TRAITS> *********************************
             ********************************************************************************
             */
            template    <typename T, typename TRAITS>
#if     !qCompilerAndStdLib_constexpr_Buggy
            constexpr
#endif
            inline  Range<T, TRAITS>::Range ()
                : Range (TRAITS::kLowerBoundOpenness, TRAITS::kUpperBoundOpenness)
            {
#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy
                Ensure (empty ());
#endif
            }
            template    <typename T, typename TRAITS>
            template    <typename T2, typename TRAITS2>
#if     !qCompilerAndStdLib_constexpr_Buggy
            constexpr
#endif
            inline  Range<T, TRAITS>::Range (const Range<T2, TRAITS>& src)
                : Range (src.GetLowerBound (), src.GetUpperBound (), src.GetLowerBoundOpenness (), src.GetUpperBoundOpenness ())
            {
            }
            template    <typename T, typename TRAITS>
#if     !qCompilerAndStdLib_constexpr_Buggy
            constexpr
#endif
            inline  Range<T, TRAITS>::Range (const T& begin, const T& end)
                : Range (begin, end, TRAITS::kLowerBoundOpenness, TRAITS::kUpperBoundOpenness)
            {
            }
            template    <typename T, typename TRAITS>
            inline  Range<T, TRAITS>::Range (const Memory::Optional<T>& begin, const Memory::Optional<T>& end)
                : Range (begin.IsPresent () ? *begin : TRAITS::kLowerBound, end.IsPresent () ? *end : TRAITS::kUpperBound, TRAITS::kLowerBoundOpenness, TRAITS::kUpperBoundOpenness)
            {
            }
            template    <typename T, typename TRAITS>
#if     !qCompilerAndStdLib_constexpr_Buggy
            constexpr
#endif
            inline  Range<T, TRAITS>::Range (Openness lhsOpen, Openness rhsOpen)
                : fBegin_ (TRAITS::kUpperBound)
                , fEnd_ (TRAITS::kLowerBound)
                , fBeginOpenness_ (lhsOpen)
                , fEndOpenness_ (rhsOpen)
            {
#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy
                Ensure (empty ());
#endif
            }
            template    <typename T, typename TRAITS>
#if     !qCompilerAndStdLib_constexpr_Buggy
            constexpr
#endif
            inline  Range<T, TRAITS>::Range (const T& begin, const T& end, Openness lhsOpen, Openness rhsOpen)
                : fBegin_ (begin)
                , fEnd_ (end)
                , fBeginOpenness_ (lhsOpen)
                , fEndOpenness_ (rhsOpen)
            {
#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy
                Require  (TRAITS::kLowerBound <= TRAITS::kUpperBound);    // always required for class
                Require (TRAITS::kLowerBound <= begin);
                Require (begin <= end);
                Require (end <= TRAITS::kUpperBound);
#endif
            }
            template    <typename T, typename TRAITS>
            inline  Range<T, TRAITS>::Range (const Memory::Optional<T>& begin, const Memory::Optional<T>& end, Openness lhsOpen, Openness rhsOpen)
                : Range (begin.IsPresent () ? *begin : TRAITS::kLowerBound, end.IsPresent () ? *end : TRAITS::kUpperBound, lhsOpen, rhsOpen)
            {
            }
            template    <typename T, typename TRAITS>
            inline  constexpr   Range<T, TRAITS>    Range<T, TRAITS>::FullRange ()
            {
                return Range<T, TRAITS> (
                           TraitsType::kLowerBound, TraitsType::kUpperBound,
                           TraitsType::kLowerBoundOpenness, TraitsType::kUpperBoundOpenness
                       );
            }
            template    <typename T, typename TRAITS>
            inline  constexpr   bool    Range<T, TRAITS>::empty () const
            {
#if     qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy
                return
                    fBegin_ > fEnd_ ?
                    true :
                    ((fBegin_ == fEnd_) ?
                     (fBeginOpenness_ == Openness::eOpen and fEndOpenness_ == Openness::eOpen) :
                     false
                    )
                    ;
#else
                if (fBegin_ > fEnd_) {
                    // internal hack done in Range<T, TRAITS>::Range() - empty range - otherwise not possible to create this situation
                    return true;
                }
                else if (fBegin_ == fEnd_) {
                    return fBeginOpenness_ == Openness::eOpen and fEndOpenness_ == Openness::eOpen;
                }
                return false;
#endif
            }
            template    <typename T, typename TRAITS>
            inline  constexpr   typename Range<T, TRAITS>::UnsignedDifferenceType    Range<T, TRAITS>::GetDistanceSpanned () const
            {
#if     qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy
                return
                    empty () ?
                    static_cast<UnsignedDifferenceType> (0) :
                    (fEnd_ - fBegin_)
                    ;
#else
                if (empty ()) {
                    return static_cast<UnsignedDifferenceType> (0);
                }
                return fEnd_ - fBegin_;
#endif
            }
            template    <typename T, typename TRAITS>
            inline  constexpr   T    Range<T, TRAITS>::GetMidpoint () const
            {
#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy
                Require (not empty ());
#endif
                return GetLowerBound () + GetDistanceSpanned () / 2;
            }
            template    <typename T, typename TRAITS>
            inline  constexpr   bool    Range<T, TRAITS>::Contains (const T& r) const
            {
#if     qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy
                return
                    empty () ?
                    false :
                    (
                        (fBegin_ < r and r < fEnd_) or
                        (fBeginOpenness_ == Openness::eClosed and r == fBegin_) or
                        (fEndOpenness_ == Openness::eClosed and r == fEnd_)
                    )
                    ;
#else
                if (empty ()) {
                    return false;
                }
                if (fBegin_ < r and r < fEnd_) {
                    return true;
                }
                if (fBeginOpenness_ == Openness::eClosed and r == fBegin_) {
                    return true;
                }
                if (fEndOpenness_ == Openness::eClosed and r == fEnd_) {
                    return true;
                }
                return false;
#endif
            }
            template    <typename T, typename TRAITS>
            template    <typename T2, typename TRAITS2>
            inline  bool    Range<T, TRAITS>::Equals (const Range<T2, TRAITS2>& rhs) const
            {
                if (empty ()) {
                    return rhs.empty ();
                }
                return fBegin_ == rhs.fBegin_ and fEnd_ == rhs.fEnd_ and fBeginOpenness_ == rhs.fBeginOpenness_ and fBeginOpenness_ == rhs.fBeginOpenness_;
            }
#if 0
            template    <typename T, typename TRAITS>
            bool    Range<T, TRAITS>::Overlaps (const Range<T, TRAITS>& rhs) const
            {
                /*
                 *  @todo   RETHINK - because Range has semantics of exclude end - make sure overlap usuage
                 *          here is correct??? Unsure -- LGP 2013-07-05
                 */
                return Math::Overlaps (
                           pair<T, T> (fBegin_, fEnd_),
                           pair<T, T> (rhs.fBegin_, rhs.fEnd_)
                       );
            }
#endif
            template    <typename T, typename TRAITS>
            template    <typename T2, typename TRAITS2>
            bool    Range<T, TRAITS>::Intersects (const Range<T2, TRAITS2>& rhs) const
            {
                if (empty () or rhs.empty ()) {
                    return false;
                }
                T   l   =   max (fBegin_, rhs.GetLowerBound ());
                T   r   =   min (fEnd_, rhs.GetUpperBound ());
                if (l < r) {
                    return true;
                }
                else if (l == r) {
                    // must check if the end that has 'l' for each Range that that end is closed. Contains()
                    // is a shortcut for that
                    return Contains (l) and rhs.Contains (l);
                }
                else {
                    return false;
                }
            }
            template    <typename T, typename TRAITS>
            Range<T, TRAITS> Range<T, TRAITS>::Intersection (const Range<T, TRAITS>& rhs) const
            {
                if (empty () or rhs.empty ()) {
                    return Range ();
                }
                T   l   =   max (fBegin_, rhs.fBegin_);
                T   r   =   min (fEnd_, rhs.fEnd_);
                if (l <= r) {
                    // lhs/rhs ends are closed iff BOTH lhs/rhs contains that point
                    Openness lhsO = Contains (l) and rhs.Contains (l) ? Openness::eClosed : Openness::eOpen;
                    Openness rhsO = Contains (r) and rhs.Contains (r) ? Openness::eClosed : Openness::eOpen;
                    return Range<T, TRAITS> (l, r, lhsO, rhsO);
                }
                else {
                    return Range ();
                }
            }
            template    <typename T, typename TRAITS>
            Range<T, TRAITS> Range<T, TRAITS>::UnionBounds (const Range<T, TRAITS>& rhs) const
            {
                if (empty ()) {
                    return rhs;
                }
                if (rhs.empty ()) {
                    return *this;
                }
                T   l   =   min (GetLowerBound (), rhs.GetLowerBound ());
                T   r   =   max (GetUpperBound (), rhs.GetUpperBound ());
                Range<T, TRAITS>   result;
                if (l <= r) {
                    // lhs/rhs ends are closed iff BOTH lhs/rhs contains that point
                    Openness lhsO = Contains (l) and rhs.Contains (l) ? Openness::eClosed : Openness::eOpen;
                    Openness rhsO = Contains (r) and rhs.Contains (r) ? Openness::eClosed : Openness::eOpen;
                    result = Range<T, TRAITS> (l, r, lhsO, rhsO);
                }
                Ensure (result.GetLowerBound () <= GetLowerBound ());
                Ensure (result.GetLowerBound () <= GetUpperBound ());
                Ensure (result.GetLowerBound () <= rhs.GetLowerBound ());
                Ensure (result.GetLowerBound () <= rhs.GetUpperBound ());
                Ensure (result.GetUpperBound () >= GetLowerBound ());
                Ensure (result.GetUpperBound () >= GetUpperBound ());
                Ensure (result.GetUpperBound () >= rhs.GetLowerBound ());
                Ensure (result.GetUpperBound () >= rhs.GetUpperBound ());
                return result;
            }
            template    <typename T, typename TRAITS>
            inline  constexpr   T    Range<T, TRAITS>::GetLowerBound () const
            {
#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy
                Require (not empty ());
#endif
                return fBegin_;
            }
            template    <typename T, typename TRAITS>
            inline  constexpr   Openness    Range<T, TRAITS>::GetLowerBoundOpenness () const
            {
                return fBeginOpenness_;
            }
            template    <typename T, typename TRAITS>
            inline  constexpr   T    Range<T, TRAITS>::GetUpperBound () const
            {
#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy
                Require (not empty ());
#endif
                return fEnd_;
            }
            template    <typename T, typename TRAITS>
            inline  constexpr   Openness    Range<T, TRAITS>::GetUpperBoundOpenness () const
            {
                return fEndOpenness_;
            }
            template    <typename T, typename TRAITS>
            template    <typename... ARGS>
            inline  Characters::String  Range<T, TRAITS>::Format (ARGS&& ... args) const
            {
                if (GetLowerBound () == GetUpperBound ()) {
                    return GetLowerBound ().Format (forward<ARGS> (args)...);
                }
                else {
                    return GetLowerBound ().Format (forward<ARGS> (args)...) + L" - " + GetUpperBound  ().Format (forward<ARGS> (args)...);
                }
            }
            template    <typename T, typename TRAITS>
            inline  bool    Range<T, TRAITS>::operator== (const Range<T, TRAITS>& rhs) const
            {
                return Equals (rhs);
            }
            template    <typename T, typename TRAITS>
            inline  bool    Range<T, TRAITS>::operator!= (const Range<T, TRAITS>& rhs) const
            {
                return not Equals (rhs);
            }

        }
    }
}
#endif /* _Stroika_Foundation_Traversal_Range_inl_ */
<commit_msg>fixed #defines so asserts happen in range CTOR if qCompilerAndStdLib_constexpr_Buggy<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2014.  All rights reserved
 */
#ifndef _Stroika_Foundation_Traversal_Range_inl_
#define _Stroika_Foundation_Traversal_Range_inl_

#include    "../Debug/Assertions.h"
#include    "../Math/Overlap.h"

namespace   Stroika {
    namespace   Foundation {
        namespace   Traversal {

            /*
             ********************************************************************************
             RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>
             ********************************************************************************
             */
#if     qCompilerAndStdLib_constexpr_Buggy
            template    <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE>
            const T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kLowerBound   =   MIN;
            template    <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE>
            const T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kUpperBound   =   MAX;
#else
            template    <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE>
            constexpr T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kLowerBound;
            template    <typename T, T MIN, T MAX , Openness LOWER_BOUND_OPEN, Openness UPPER_BOUND_OPEN, typename SIGNED_DIFF_TYPE, typename UNSIGNED_DIFF_TYPE>
            constexpr T RangeTraits::ExplicitRangeTraits_Integral<T, MIN, MAX, LOWER_BOUND_OPEN, UPPER_BOUND_OPEN, SIGNED_DIFF_TYPE, UNSIGNED_DIFF_TYPE>::kUpperBound;
#endif

            /*
             ********************************************************************************
             ****************** RangeTraits::DefaultRangeTraits<T> **************************
             ********************************************************************************
             */
#if     qCompilerAndStdLib_constexpr_Buggy
            template    <typename T>
            const T RangeTraits::DefaultRangeTraits<T>::kLowerBound     =   numeric_limits<T>::lowest ();
            template    <typename T>
            const T RangeTraits::DefaultRangeTraits<T>::kUpperBound     =   numeric_limits<T>::max ();
#else
            template    <typename T>
            constexpr T RangeTraits::DefaultRangeTraits<T>::kLowerBound;
            template    <typename T>
            constexpr T RangeTraits::DefaultRangeTraits<T>::kUpperBound;
#endif

            /*
             ********************************************************************************
             ***************************** Range<T, TRAITS> *********************************
             ********************************************************************************
             */
            template    <typename T, typename TRAITS>
#if     !qCompilerAndStdLib_constexpr_Buggy
            constexpr
#endif
            inline  Range<T, TRAITS>::Range ()
                : Range (TRAITS::kLowerBoundOpenness, TRAITS::kUpperBoundOpenness)
            {
#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy
                Ensure (empty ());
#endif
            }
            template    <typename T, typename TRAITS>
            template    <typename T2, typename TRAITS2>
#if     !qCompilerAndStdLib_constexpr_Buggy
            constexpr
#endif
            inline  Range<T, TRAITS>::Range (const Range<T2, TRAITS>& src)
                : Range (src.GetLowerBound (), src.GetUpperBound (), src.GetLowerBoundOpenness (), src.GetUpperBoundOpenness ())
            {
            }
            template    <typename T, typename TRAITS>
#if     !qCompilerAndStdLib_constexpr_Buggy
            constexpr
#endif
            inline  Range<T, TRAITS>::Range (const T& begin, const T& end)
                : Range (begin, end, TRAITS::kLowerBoundOpenness, TRAITS::kUpperBoundOpenness)
            {
            }
            template    <typename T, typename TRAITS>
            inline  Range<T, TRAITS>::Range (const Memory::Optional<T>& begin, const Memory::Optional<T>& end)
                : Range (begin.IsPresent () ? *begin : TRAITS::kLowerBound, end.IsPresent () ? *end : TRAITS::kUpperBound, TRAITS::kLowerBoundOpenness, TRAITS::kUpperBoundOpenness)
            {
            }
            template    <typename T, typename TRAITS>
#if     !qCompilerAndStdLib_constexpr_Buggy
            constexpr
#endif
            inline  Range<T, TRAITS>::Range (Openness lhsOpen, Openness rhsOpen)
                : fBegin_ (TRAITS::kUpperBound)
                , fEnd_ (TRAITS::kLowerBound)
                , fBeginOpenness_ (lhsOpen)
                , fEndOpenness_ (rhsOpen)
            {
#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy
                Ensure (empty ());
#endif
            }
            template    <typename T, typename TRAITS>
#if     !qCompilerAndStdLib_constexpr_Buggy
            constexpr
#endif
            inline  Range<T, TRAITS>::Range (const T& begin, const T& end, Openness lhsOpen, Openness rhsOpen)
                : fBegin_ (begin)
                , fEnd_ (end)
                , fBeginOpenness_ (lhsOpen)
                , fEndOpenness_ (rhsOpen)
            {
#if     qCompilerAndStdLib_constexpr_Buggy || !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy
                Require  (TRAITS::kLowerBound <= TRAITS::kUpperBound);    // always required for class
                Require (TRAITS::kLowerBound <= begin);
                Require (begin <= end);
                Require (end <= TRAITS::kUpperBound);
#endif
            }
            template    <typename T, typename TRAITS>
            inline  Range<T, TRAITS>::Range (const Memory::Optional<T>& begin, const Memory::Optional<T>& end, Openness lhsOpen, Openness rhsOpen)
                : Range (begin.IsPresent () ? *begin : TRAITS::kLowerBound, end.IsPresent () ? *end : TRAITS::kUpperBound, lhsOpen, rhsOpen)
            {
            }
            template    <typename T, typename TRAITS>
            inline  constexpr   Range<T, TRAITS>    Range<T, TRAITS>::FullRange ()
            {
                return Range<T, TRAITS> (
                           TraitsType::kLowerBound, TraitsType::kUpperBound,
                           TraitsType::kLowerBoundOpenness, TraitsType::kUpperBoundOpenness
                       );
            }
            template    <typename T, typename TRAITS>
            inline  constexpr   bool    Range<T, TRAITS>::empty () const
            {
#if     qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy
                return
                    fBegin_ > fEnd_ ?
                    true :
                    ((fBegin_ == fEnd_) ?
                     (fBeginOpenness_ == Openness::eOpen and fEndOpenness_ == Openness::eOpen) :
                     false
                    )
                    ;
#else
                if (fBegin_ > fEnd_) {
                    // internal hack done in Range<T, TRAITS>::Range() - empty range - otherwise not possible to create this situation
                    return true;
                }
                else if (fBegin_ == fEnd_) {
                    return fBeginOpenness_ == Openness::eOpen and fEndOpenness_ == Openness::eOpen;
                }
                return false;
#endif
            }
            template    <typename T, typename TRAITS>
            inline  constexpr   typename Range<T, TRAITS>::UnsignedDifferenceType    Range<T, TRAITS>::GetDistanceSpanned () const
            {
#if     qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy
                return
                    empty () ?
                    static_cast<UnsignedDifferenceType> (0) :
                    (fEnd_ - fBegin_)
                    ;
#else
                if (empty ()) {
                    return static_cast<UnsignedDifferenceType> (0);
                }
                return fEnd_ - fBegin_;
#endif
            }
            template    <typename T, typename TRAITS>
            inline  constexpr   T    Range<T, TRAITS>::GetMidpoint () const
            {
#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy
                Require (not empty ());
#endif
                return GetLowerBound () + GetDistanceSpanned () / 2;
            }
            template    <typename T, typename TRAITS>
            inline  constexpr   bool    Range<T, TRAITS>::Contains (const T& r) const
            {
#if     qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy
                return
                    empty () ?
                    false :
                    (
                        (fBegin_ < r and r < fEnd_) or
                        (fBeginOpenness_ == Openness::eClosed and r == fBegin_) or
                        (fEndOpenness_ == Openness::eClosed and r == fEnd_)
                    )
                    ;
#else
                if (empty ()) {
                    return false;
                }
                if (fBegin_ < r and r < fEnd_) {
                    return true;
                }
                if (fBeginOpenness_ == Openness::eClosed and r == fBegin_) {
                    return true;
                }
                if (fEndOpenness_ == Openness::eClosed and r == fEnd_) {
                    return true;
                }
                return false;
#endif
            }
            template    <typename T, typename TRAITS>
            template    <typename T2, typename TRAITS2>
            inline  bool    Range<T, TRAITS>::Equals (const Range<T2, TRAITS2>& rhs) const
            {
                if (empty ()) {
                    return rhs.empty ();
                }
                return fBegin_ == rhs.fBegin_ and fEnd_ == rhs.fEnd_ and fBeginOpenness_ == rhs.fBeginOpenness_ and fBeginOpenness_ == rhs.fBeginOpenness_;
            }
#if 0
            template    <typename T, typename TRAITS>
            bool    Range<T, TRAITS>::Overlaps (const Range<T, TRAITS>& rhs) const
            {
                /*
                 *  @todo   RETHINK - because Range has semantics of exclude end - make sure overlap usuage
                 *          here is correct??? Unsure -- LGP 2013-07-05
                 */
                return Math::Overlaps (
                           pair<T, T> (fBegin_, fEnd_),
                           pair<T, T> (rhs.fBegin_, rhs.fEnd_)
                       );
            }
#endif
            template    <typename T, typename TRAITS>
            template    <typename T2, typename TRAITS2>
            bool    Range<T, TRAITS>::Intersects (const Range<T2, TRAITS2>& rhs) const
            {
                if (empty () or rhs.empty ()) {
                    return false;
                }
                T   l   =   max (fBegin_, rhs.GetLowerBound ());
                T   r   =   min (fEnd_, rhs.GetUpperBound ());
                if (l < r) {
                    return true;
                }
                else if (l == r) {
                    // must check if the end that has 'l' for each Range that that end is closed. Contains()
                    // is a shortcut for that
                    return Contains (l) and rhs.Contains (l);
                }
                else {
                    return false;
                }
            }
            template    <typename T, typename TRAITS>
            Range<T, TRAITS> Range<T, TRAITS>::Intersection (const Range<T, TRAITS>& rhs) const
            {
                if (empty () or rhs.empty ()) {
                    return Range ();
                }
                T   l   =   max (fBegin_, rhs.fBegin_);
                T   r   =   min (fEnd_, rhs.fEnd_);
                if (l <= r) {
                    // lhs/rhs ends are closed iff BOTH lhs/rhs contains that point
                    Openness lhsO = Contains (l) and rhs.Contains (l) ? Openness::eClosed : Openness::eOpen;
                    Openness rhsO = Contains (r) and rhs.Contains (r) ? Openness::eClosed : Openness::eOpen;
                    return Range<T, TRAITS> (l, r, lhsO, rhsO);
                }
                else {
                    return Range ();
                }
            }
            template    <typename T, typename TRAITS>
            Range<T, TRAITS> Range<T, TRAITS>::UnionBounds (const Range<T, TRAITS>& rhs) const
            {
                if (empty ()) {
                    return rhs;
                }
                if (rhs.empty ()) {
                    return *this;
                }
                T   l   =   min (GetLowerBound (), rhs.GetLowerBound ());
                T   r   =   max (GetUpperBound (), rhs.GetUpperBound ());
                Range<T, TRAITS>   result;
                if (l <= r) {
                    // lhs/rhs ends are closed iff BOTH lhs/rhs contains that point
                    Openness lhsO = Contains (l) and rhs.Contains (l) ? Openness::eClosed : Openness::eOpen;
                    Openness rhsO = Contains (r) and rhs.Contains (r) ? Openness::eClosed : Openness::eOpen;
                    result = Range<T, TRAITS> (l, r, lhsO, rhsO);
                }
                Ensure (result.GetLowerBound () <= GetLowerBound ());
                Ensure (result.GetLowerBound () <= GetUpperBound ());
                Ensure (result.GetLowerBound () <= rhs.GetLowerBound ());
                Ensure (result.GetLowerBound () <= rhs.GetUpperBound ());
                Ensure (result.GetUpperBound () >= GetLowerBound ());
                Ensure (result.GetUpperBound () >= GetUpperBound ());
                Ensure (result.GetUpperBound () >= rhs.GetLowerBound ());
                Ensure (result.GetUpperBound () >= rhs.GetUpperBound ());
                return result;
            }
            template    <typename T, typename TRAITS>
            inline  constexpr   T    Range<T, TRAITS>::GetLowerBound () const
            {
#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy
                Require (not empty ());
#endif
                return fBegin_;
            }
            template    <typename T, typename TRAITS>
            inline  constexpr   Openness    Range<T, TRAITS>::GetLowerBoundOpenness () const
            {
                return fBeginOpenness_;
            }
            template    <typename T, typename TRAITS>
            inline  constexpr   T    Range<T, TRAITS>::GetUpperBound () const
            {
#if     !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy
                Require (not empty ());
#endif
                return fEnd_;
            }
            template    <typename T, typename TRAITS>
            inline  constexpr   Openness    Range<T, TRAITS>::GetUpperBoundOpenness () const
            {
                return fEndOpenness_;
            }
            template    <typename T, typename TRAITS>
            template    <typename... ARGS>
            inline  Characters::String  Range<T, TRAITS>::Format (ARGS&& ... args) const
            {
                if (GetLowerBound () == GetUpperBound ()) {
                    return GetLowerBound ().Format (forward<ARGS> (args)...);
                }
                else {
                    return GetLowerBound ().Format (forward<ARGS> (args)...) + L" - " + GetUpperBound  ().Format (forward<ARGS> (args)...);
                }
            }
            template    <typename T, typename TRAITS>
            inline  bool    Range<T, TRAITS>::operator== (const Range<T, TRAITS>& rhs) const
            {
                return Equals (rhs);
            }
            template    <typename T, typename TRAITS>
            inline  bool    Range<T, TRAITS>::operator!= (const Range<T, TRAITS>& rhs) const
            {
                return not Equals (rhs);
            }

        }
    }
}
#endif /* _Stroika_Foundation_Traversal_Range_inl_ */
<|endoftext|>


<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_MATRIX_HH
#define DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_MATRIX_HH

// std includes
#include <vector>

// local includes
//#include "vector.hh"

namespace Dune {

namespace Detailed {

namespace Discretizations {

namespace Assembler {

namespace Local {

namespace Codim1 {

template <class LocalOperatorImp>
class Inner
{
public:
  typedef LocalOperatorImp LocalOperatorType;

  typedef Inner<LocalOperatorType> ThisType;

  typedef typename LocalOperatorType::RangeFieldType RangeFieldType;

  Inner(const LocalOperatorType& localOperator)
    : localOperator_(localOperator)
  {
  }

  const LocalOperatorType& localOperator() const
  {
    return localOperator_;
  }

private:
  static const unsigned int numTmpObjectsRequired_ = 4;

public:
  std::vector<unsigned int> numTmpObjectsRequired() const
  {
    std::vector<unsigned int> ret(2, 0);
    ret[0] = numTmpObjectsRequired_;
    ret[1] = localOperator_.numTmpObjectsRequired();
    return ret;
  } // std::vector< unsigned int > numTmpObjectsRequired() const

  template <class IntersectionType, class InnerAnsatzSpaceType, class InnerTestSpaceType, class OuterAnsatzSpaceType,
            class OuterTestSpaceType, class MatrixBackendType, class LocalMatrixType>
  void assembleLocal(const IntersectionType& intersection, const InnerAnsatzSpaceType& innerAnsatzSpace,
                     const InnerTestSpaceType& innerTestSpace, const OuterAnsatzSpaceType& outerAnsatzSpace,
                     const OuterTestSpaceType& outerTestSpace, MatrixBackendType& innerInnerMatrix,
                     MatrixBackendType& outerOuterMatrix, MatrixBackendType& innerOuterMatrix,
                     MatrixBackendType& outerInnerMatrix,
                     std::vector<std::vector<LocalMatrixType>>& tmpLocalMatricesContainer) const
  {
    // preparations
    assert(intersection.neighbor() && !intersection.boundary());
    typedef typename IntersectionType::EntityPointer EntityPointerType;
    typedef typename IntersectionType::Entity EntityType;
    typedef typename InnerAnsatzSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType InnerAnsatzBaseFunctionSetType;
    typedef typename InnerTestSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType InnerTestBaseFunctionSetType;
    typedef typename OuterAnsatzSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType OuterAnsatzBaseFunctionSetType;
    typedef typename OuterTestSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType OuterTestBaseFunctionSetType;
    // get inside entity and basefunctionsets
    const EntityPointerType insideEntityPtr = intersection.inside();
    const EntityType& insideEntity = *insideEntityPtr;
    const InnerAnsatzBaseFunctionSetType innerAnsatzBaseFunctionSet =
        innerAnsatzSpace.baseFunctionSet().local(insideEntity);
    const InnerTestBaseFunctionSetType innerTestBaseFunctionSet = innerTestSpace.baseFunctionSet().local(insideEntity);
    // get outside neighbor and basefunctionsets
    const EntityPointerType outsideNeighborPtr = intersection.outside();
    const EntityType& outsideNeighbor = *outsideNeighborPtr;
    const OuterAnsatzBaseFunctionSetType outerAnsatzBaseFunctionSet =
        outerAnsatzSpace.baseFunctionSet().local(outsideNeighbor);
    const OuterTestBaseFunctionSetType outerTestBaseFunctionSet =
        outerTestSpace.baseFunctionSet().local(outsideNeighbor);
    // ensure enough tmp local matrices
    assert(tmpLocalMatricesContainer.size() > 1);
    std::vector<LocalMatrixType>& tmpLocalMatrices = tmpLocalMatricesContainer[0];
    if (tmpLocalMatrices.size() < numTmpObjectsRequired_) {
      tmpLocalMatrices.resize(
          numTmpObjectsRequired_,
          LocalMatrixType(std::max(innerAnsatzSpace.map().maxLocalSize(), outerAnsatzSpace.map().maxLocalSize()),
                          std::max(innerTestSpace.map().maxLocalSize(), outerTestSpace.map().maxLocalSize()),
                          RangeFieldType(0.0)));
    } // ensure enough tmp local matrices
    // apply local operator
    localOperator_.applyLocal(innerAnsatzBaseFunctionSet,
                              innerTestBaseFunctionSet,
                              outerAnsatzBaseFunctionSet,
                              outerTestBaseFunctionSet,
                              intersection,
                              tmpLocalMatrices[0], // inside/inside
                              tmpLocalMatrices[1], // outside/outside
                              tmpLocalMatrices[2], // inside/outside
                              tmpLocalMatrices[3], // outside/inside
                              tmpLocalMatricesContainer[1]);
    // write local matrices to global (see below)
    addToMatrix(innerAnsatzSpace, innerTestSpace, insideEntity, insideEntity, tmpLocalMatrices[0], innerInnerMatrix);
    addToMatrix(
        outerAnsatzSpace, outerTestSpace, outsideNeighbor, outsideNeighbor, tmpLocalMatrices[1], outerOuterMatrix);
    addToMatrix(innerAnsatzSpace, outerTestSpace, insideEntity, outsideNeighbor, tmpLocalMatrices[2], innerOuterMatrix);
    addToMatrix(outerAnsatzSpace, innerTestSpace, outsideNeighbor, insideEntity, tmpLocalMatrices[3], outerInnerMatrix);
  } // void assembleLocal() const

private:
  //! assignment operator
  ThisType& operator=(const ThisType&);

  template <class AnsatzSpaceType, class TestSpaceType, class EntityType, class LocalMatrixType, class SystemMatrixType>
  void addToMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace, const EntityType& ansatzEntity,
                   const EntityType& testEntity, const LocalMatrixType& localMatrix,
                   SystemMatrixType& systemMatrix) const
  {
    unsigned int rows = ansatzSpace.baseFunctionSet().local(ansatzEntity).size();
    unsigned int cols = testSpace.baseFunctionSet().local(testEntity).size();
    for (unsigned int i = 0; i < rows; ++i) {
      for (unsigned int j = 0; j < cols; ++j) {
        const unsigned int globalI = ansatzSpace.map().toGlobal(ansatzEntity, i);
        const unsigned int globalJ = testSpace.map().toGlobal(testEntity, j);

        systemMatrix.add(globalI, globalJ, localMatrix[i][j]);
      }
    }
  } // end method addToMatrix

  const LocalOperatorType& localOperator_;
}; // end class Inner

} // end namespace Codim1

} // end namespace Local

} // end namespace Assembler

} // namespace Discretizations

} // namespace Detailed

} // end namespace Dune

#endif // DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_MATRIX_HH
<commit_msg>[assembler.local.codim1.matrix] added local boundary assembler<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_MATRIX_HH
#define DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_MATRIX_HH

// std includes
#include <vector>

// local includes
//#include "vector.hh"

namespace Dune {

namespace Detailed {

namespace Discretizations {

namespace Assembler {

namespace Local {

namespace Codim1 {

template <class LocalOperatorImp>
class Inner
{
public:
  typedef LocalOperatorImp LocalOperatorType;

  typedef Inner<LocalOperatorType> ThisType;

  typedef typename LocalOperatorType::RangeFieldType RangeFieldType;

  Inner(const LocalOperatorType& localOperator)
    : localOperator_(localOperator)
  {
  }

  const LocalOperatorType& localOperator() const
  {
    return localOperator_;
  }

private:
  static const unsigned int numTmpObjectsRequired_ = 4;

public:
  std::vector<unsigned int> numTmpObjectsRequired() const
  {
    std::vector<unsigned int> ret(2, 0);
    ret[0] = numTmpObjectsRequired_;
    ret[1] = localOperator_.numTmpObjectsRequired();
    return ret;
  } // std::vector< unsigned int > numTmpObjectsRequired() const

  template <class IntersectionType, class InnerAnsatzSpaceType, class InnerTestSpaceType, class OuterAnsatzSpaceType,
            class OuterTestSpaceType, class MatrixBackendType, class LocalMatrixType>
  void assembleLocal(const IntersectionType& intersection, const InnerAnsatzSpaceType& innerAnsatzSpace,
                     const InnerTestSpaceType& innerTestSpace, const OuterAnsatzSpaceType& outerAnsatzSpace,
                     const OuterTestSpaceType& outerTestSpace, MatrixBackendType& innerInnerMatrix,
                     MatrixBackendType& outerOuterMatrix, MatrixBackendType& innerOuterMatrix,
                     MatrixBackendType& outerInnerMatrix,
                     std::vector<std::vector<LocalMatrixType>>& tmpLocalMatricesContainer) const
  {
    // preparations
    assert(intersection.neighbor() && !intersection.boundary());
    typedef typename IntersectionType::EntityPointer EntityPointerType;
    typedef typename IntersectionType::Entity EntityType;
    typedef typename InnerAnsatzSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType InnerAnsatzBaseFunctionSetType;
    typedef typename InnerTestSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType InnerTestBaseFunctionSetType;
    typedef typename OuterAnsatzSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType OuterAnsatzBaseFunctionSetType;
    typedef typename OuterTestSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType OuterTestBaseFunctionSetType;
    // get inside entity and basefunctionsets
    const EntityPointerType insideEntityPtr = intersection.inside();
    const EntityType& insideEntity = *insideEntityPtr;
    const InnerAnsatzBaseFunctionSetType innerAnsatzBaseFunctionSet =
        innerAnsatzSpace.baseFunctionSet().local(insideEntity);
    const InnerTestBaseFunctionSetType innerTestBaseFunctionSet = innerTestSpace.baseFunctionSet().local(insideEntity);
    // get outside neighbor and basefunctionsets
    const EntityPointerType outsideNeighborPtr = intersection.outside();
    const EntityType& outsideNeighbor = *outsideNeighborPtr;
    const OuterAnsatzBaseFunctionSetType outerAnsatzBaseFunctionSet =
        outerAnsatzSpace.baseFunctionSet().local(outsideNeighbor);
    const OuterTestBaseFunctionSetType outerTestBaseFunctionSet =
        outerTestSpace.baseFunctionSet().local(outsideNeighbor);
    // ensure enough tmp local matrices
    assert(tmpLocalMatricesContainer.size() > 1);
    std::vector<LocalMatrixType>& tmpLocalMatrices = tmpLocalMatricesContainer[0];
    if (tmpLocalMatrices.size() < numTmpObjectsRequired_) {
      tmpLocalMatrices.resize(
          numTmpObjectsRequired_,
          LocalMatrixType(std::max(innerAnsatzSpace.map().maxLocalSize(), outerAnsatzSpace.map().maxLocalSize()),
                          std::max(innerTestSpace.map().maxLocalSize(), outerTestSpace.map().maxLocalSize()),
                          RangeFieldType(0.0)));
    } // ensure enough tmp local matrices
    // apply local operator
    localOperator_.applyLocal(innerAnsatzBaseFunctionSet,
                              innerTestBaseFunctionSet,
                              outerAnsatzBaseFunctionSet,
                              outerTestBaseFunctionSet,
                              intersection,
                              tmpLocalMatrices[0], // inside/inside
                              tmpLocalMatrices[1], // outside/outside
                              tmpLocalMatrices[2], // inside/outside
                              tmpLocalMatrices[3], // outside/inside
                              tmpLocalMatricesContainer[1]);
    // write local matrices to global (see below)
    addToMatrix(innerAnsatzSpace, innerTestSpace, insideEntity, insideEntity, tmpLocalMatrices[0], innerInnerMatrix);
    addToMatrix(
        outerAnsatzSpace, outerTestSpace, outsideNeighbor, outsideNeighbor, tmpLocalMatrices[1], outerOuterMatrix);
    addToMatrix(innerAnsatzSpace, outerTestSpace, insideEntity, outsideNeighbor, tmpLocalMatrices[2], innerOuterMatrix);
    addToMatrix(outerAnsatzSpace, innerTestSpace, outsideNeighbor, insideEntity, tmpLocalMatrices[3], outerInnerMatrix);
  } // void assembleLocal() const

private:
  //! assignment operator
  ThisType& operator=(const ThisType&);

  template <class AnsatzSpaceType, class TestSpaceType, class EntityType, class LocalMatrixType, class SystemMatrixType>
  void addToMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace, const EntityType& ansatzEntity,
                   const EntityType& testEntity, const LocalMatrixType& localMatrix,
                   SystemMatrixType& systemMatrix) const
  {
    unsigned int rows = ansatzSpace.baseFunctionSet().local(ansatzEntity).size();
    unsigned int cols = testSpace.baseFunctionSet().local(testEntity).size();
    for (unsigned int i = 0; i < rows; ++i) {
      for (unsigned int j = 0; j < cols; ++j) {
        const unsigned int globalI = ansatzSpace.map().toGlobal(ansatzEntity, i);
        const unsigned int globalJ = testSpace.map().toGlobal(testEntity, j);

        systemMatrix.add(globalI, globalJ, localMatrix[i][j]);
      }
    }
  } // end method addToMatrix

  const LocalOperatorType& localOperator_;
}; // end class Inner

template <class LocalOperatorImp>
class Boundary
{
public:
  typedef LocalOperatorImp LocalOperatorType;

  typedef Boundary<LocalOperatorType> ThisType;

  typedef typename LocalOperatorType::RangeFieldType RangeFieldType;

  Boundary(const LocalOperatorType& localOperator)
    : localOperator_(localOperator)
  {
  }

  const LocalOperatorType& localOperator() const
  {
    return localOperator_;
  }

private:
  static const unsigned int numTmpObjectsRequired_ = 4;

public:
  std::vector<unsigned int> numTmpObjectsRequired() const
  {
    std::vector<unsigned int> ret(2, 0);
    ret[0] = numTmpObjectsRequired_;
    ret[1] = localOperator_.numTmpObjectsRequired();
    return ret;
  } // std::vector< unsigned int > numTmpObjectsRequired() const

  template <class IntersectionType, class AnsatzSpaceType, class TestSpaceType, class MatrixBackendType,
            class LocalMatrixType>
  void assembleLocal(const IntersectionType& intersection, const AnsatzSpaceType& ansatzSpace,
                     const TestSpaceType& testSpace, MatrixBackendType& matrix,
                     std::vector<std::vector<LocalMatrixType>>& tmpLocalMatricesContainer) const
  {
    // preparations
    assert(intersection.boundary());
    typedef typename IntersectionType::EntityPointer EntityPointerType;
    typedef typename IntersectionType::Entity EntityType;
    typedef typename AnsatzSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType LocalAnsatzBaseFunctionSetType;
    typedef typename TestSpaceType::BaseFunctionSetType::LocalBaseFunctionSetType LocalTestBaseFunctionSetType;
    // get inside entity and basefunctionsets
    const EntityPointerType entityPtr                               = intersection.inside();
    const EntityType& entity                                        = *entityPtr;
    const LocalAnsatzBaseFunctionSetType localAnsatzBaseFunctionSet = ansatzSpace.baseFunctionSet().local(entity);
    const LocalTestBaseFunctionSetType localTestBaseFunctionSet     = testSpace.baseFunctionSet().local(entity);
    // ensure enough tmp local matrices
    assert(tmpLocalMatricesContainer.size() > 1);
    std::vector<LocalMatrixType>& tmpLocalMatrices = tmpLocalMatricesContainer[0];
    if (tmpLocalMatrices.size() < numTmpObjectsRequired_) {
      tmpLocalMatrices.resize(
          numTmpObjectsRequired_,
          LocalMatrixType(ansatzSpace.map().maxLocalSize(), testSpace.map().maxLocalSize(), RangeFieldType(0.0)));
    } // ensure enough tmp local matrices
    // apply local operator
    localOperator_.applyLocal(localAnsatzBaseFunctionSet,
                              localTestBaseFunctionSet,
                              intersection,
                              tmpLocalMatrices[0],
                              tmpLocalMatricesContainer[1]);
    // write local matrices to global (see below)
    addToMatrix(ansatzSpace, testSpace, entity, entity, tmpLocalMatrices[0], matrix);
  } // void assembleLocal() const

private:
  //! assignment operator
  ThisType& operator=(const ThisType&);

  template <class AnsatzSpaceType, class TestSpaceType, class EntityType, class LocalMatrixType, class SystemMatrixType>
  void addToMatrix(const AnsatzSpaceType& ansatzSpace, const TestSpaceType& testSpace, const EntityType& ansatzEntity,
                   const EntityType& testEntity, const LocalMatrixType& localMatrix,
                   SystemMatrixType& systemMatrix) const
  {
    unsigned int rows = ansatzSpace.baseFunctionSet().local(ansatzEntity).size();
    unsigned int cols = testSpace.baseFunctionSet().local(testEntity).size();
    for (unsigned int i = 0; i < rows; ++i) {
      for (unsigned int j = 0; j < cols; ++j) {
        const unsigned int globalI = ansatzSpace.map().toGlobal(ansatzEntity, i);
        const unsigned int globalJ = testSpace.map().toGlobal(testEntity, j);

        systemMatrix.add(globalI, globalJ, localMatrix[i][j]);
      }
    }
  } // end method addToMatrix

  const LocalOperatorType& localOperator_;
}; // end class Boundary

} // end namespace Codim1

} // end namespace Local

} // end namespace Assembler

} // namespace Discretizations

} // namespace Detailed

} // end namespace Dune

#endif // DUNE_DETAILED_DISCRETIZATIONS_ASSEMLBER_LOCAL_CODIM1_MATRIX_HH
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: macrodlg.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 20:06: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 _MACRODLG_HXX
#define _MACRODLG_HXX

#ifndef _SVHEADER_HXX
#include <svheader.hxx>
#endif

#include <bastype2.hxx>
#include <bastype3.hxx>

#ifndef _BASEDLGS_HXX //autogen
#include <sfx2/basedlgs.hxx>
#endif

#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif

#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif

#define MACRO_CLOSE         10
#define MACRO_OK_RUN        11
#define MACRO_NEW           12
#define MACRO_EDIT          14
#define MACRO_ORGANIZE      15
#define MACRO_ASSIGN        16

#define MACROCHOOSER_ALL            1
#define MACROCHOOSER_CHOOSEONLY     2
#define MACROCHOOSER_RECORDING      3

class BasicManager;

class MacroChooser : public SfxModalDialog
{
private:
    FixedText               aMacroNameTxt;
    Edit                    aMacroNameEdit;
    FixedText               aMacrosInTxt;
    String                  aMacrosInTxtBaseStr;
    SvTreeListBox           aMacroBox;
    FixedText               aMacroFromTxT;
    FixedText               aMacrosSaveInTxt;
    BasicTreeListBox        aBasicBox;

    PushButton              aRunButton;
    CancelButton            aCloseButton;
    PushButton              aAssignButton;
    PushButton              aEditButton;
    PushButton              aNewDelButton;
    PushButton              aOrganizeButton;
    HelpButton              aHelpButton;
    PushButton              aNewLibButton;
    PushButton              aNewModButton;

    BOOL                bNewDelIsDel;
    BOOL                bForceStoreBasic;

    USHORT              nMode;

    DECL_LINK( MacroSelectHdl, SvTreeListBox * );
    DECL_LINK( MacroDoubleClickHdl, SvTreeListBox * );
    DECL_LINK( BasicSelectHdl, SvTreeListBox * );
    DECL_LINK( EditModifyHdl, Edit * );
    DECL_LINK( ButtonHdl, Button * );

    void                CheckButtons();
    void                SaveSetCurEntry( SvTreeListBox& rBox, SvLBoxEntry* pEntry );
    void                UpdateFields();

    void                EnableButton( Button& rButton, BOOL bEnable );

    String              GetInfo( SbxVariable* pVar );

    void                StoreMacroDescription();
    void                RestoreMacroDescription();

public:
                        MacroChooser( Window* pParent, BOOL bCreateEntries = TRUE );
                        ~MacroChooser();

    SbMethod*           GetMacro();
    void                DeleteMacro();
    SbMethod*           CreateMacro();

    virtual short       Execute();

    void                SetMode( USHORT nMode );
    USHORT              GetMode() const { return nMode; }
};

#endif  // _MACRODLG_HXX
<commit_msg>INTEGRATION: CWS basmgr02 (1.8.146); FILE MERGED 2007/01/11 10:40:03 fs 1.8.146.1: during #i73329#: proper Z-(means: tab-)order<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: macrodlg.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: obo $ $Date: 2007-03-15 15:57:16 $
 *
 *  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 _MACRODLG_HXX
#define _MACRODLG_HXX

#ifndef _SVHEADER_HXX
#include <svheader.hxx>
#endif

#include <bastype2.hxx>
#include <bastype3.hxx>

#ifndef _BASEDLGS_HXX //autogen
#include <sfx2/basedlgs.hxx>
#endif

#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif

#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif

#define MACRO_CLOSE         10
#define MACRO_OK_RUN        11
#define MACRO_NEW           12
#define MACRO_EDIT          14
#define MACRO_ORGANIZE      15
#define MACRO_ASSIGN        16

#define MACROCHOOSER_ALL            1
#define MACROCHOOSER_CHOOSEONLY     2
#define MACROCHOOSER_RECORDING      3

class BasicManager;

class MacroChooser : public SfxModalDialog
{
private:
    FixedText               aMacroNameTxt;
    Edit                    aMacroNameEdit;
    FixedText               aMacroFromTxT;
    FixedText               aMacrosSaveInTxt;
    BasicTreeListBox        aBasicBox;
    FixedText               aMacrosInTxt;
    String                  aMacrosInTxtBaseStr;
    SvTreeListBox           aMacroBox;

    PushButton              aRunButton;
    CancelButton            aCloseButton;
    PushButton              aAssignButton;
    PushButton              aEditButton;
    PushButton              aNewDelButton;
    PushButton              aOrganizeButton;
    HelpButton              aHelpButton;
    PushButton              aNewLibButton;
    PushButton              aNewModButton;

    BOOL                bNewDelIsDel;
    BOOL                bForceStoreBasic;

    USHORT              nMode;

    DECL_LINK( MacroSelectHdl, SvTreeListBox * );
    DECL_LINK( MacroDoubleClickHdl, SvTreeListBox * );
    DECL_LINK( BasicSelectHdl, SvTreeListBox * );
    DECL_LINK( EditModifyHdl, Edit * );
    DECL_LINK( ButtonHdl, Button * );

    void                CheckButtons();
    void                SaveSetCurEntry( SvTreeListBox& rBox, SvLBoxEntry* pEntry );
    void                UpdateFields();

    void                EnableButton( Button& rButton, BOOL bEnable );

    String              GetInfo( SbxVariable* pVar );

    void                StoreMacroDescription();
    void                RestoreMacroDescription();

public:
                        MacroChooser( Window* pParent, BOOL bCreateEntries = TRUE );
                        ~MacroChooser();

    SbMethod*           GetMacro();
    void                DeleteMacro();
    SbMethod*           CreateMacro();

    virtual short       Execute();

    void                SetMode( USHORT nMode );
    USHORT              GetMode() const { return nMode; }
};

#endif  // _MACRODLG_HXX
<|endoftext|>


<commit_before>#include <set>
#include <vector>

#include "entitysystem.h"
#include "cmapclient.h"
#include "cmapserver.h"
#include "connection.h"
#include "systems/chatsystem.h"
#include "systems/inventorysystem.h"
#include "systems/luasystem.h"
#include "systems/mapsystem.h"
#include "systems/movementsystem.h"
#include "systems/partysystem.h"
#include "systems/updatesystem.h"

#include "srv_npcchar.h"

using namespace RoseCommon;
EntitySystem::EntitySystem(CMapServer *server) : systemManager_(*this), server_(server) {
  systemManager_.add<Systems::MovementSystem>();
  systemManager_.add<Systems::UpdateSystem>();
  systemManager_.add<Systems::ChatSystem>();
  systemManager_.add<Systems::InventorySystem>();
  systemManager_.add<Systems::PartySystem>();
  systemManager_.add<Systems::MapSystem>();
  systemManager_.add<Systems::LuaSystem>();
}
EntityManager& EntitySystem::getEntityManager() { return entityManager_; }

Entity EntitySystem::buildItemEntity(Entity creator, RoseCommon::Item&& item) {
  Entity e = create();
  e.assign<Item>(std::move(item));
  auto pos = creator.component<Position>();
  e.assign<Position>(pos->x_, pos->y_, pos->map_, 0);
  auto basic = e.assign<BasicInfo>();
  basic->ownerId_ = creator.component<BasicInfo>()->id_;
  basic->id_ = id_manager_.get_free_id();
  itemToEntity_[basic->id_] = e;
  return e;
}

void EntitySystem::registerEntity(Entity entity) {
  if (!entity) return;
  auto basic = entity.component<BasicInfo>();
  if (!basic || basic->name_ == "" || !basic->id_) return;
  nameToEntity_[basic->name_] = entity;
  idToEntity_[basic->id_] = entity;
}

Entity EntitySystem::getItemEntity(uint32_t id) { return itemToEntity_[id]; }

Entity EntitySystem::getEntity(const std::string& name) { return nameToEntity_[name]; }

Entity EntitySystem::getEntity(uint32_t charId) { return idToEntity_[charId]; }

void EntitySystem::update(double dt) {
  std::lock_guard<std::mutex> lock(access_);
  for (auto& it : create_commands_) {
    it->execute(*this);
  }
  create_commands_.clear();
  while (toDispatch_.size()) {
    auto tmp = std::move(toDispatch_.front());
    systemManager_.dispatch(tmp.first, *tmp.second);
    toDispatch_.pop();
  }
  systemManager_.update(dt);
  for (auto& it : delete_commands_) {
    it->execute(*this);
  }
  delete_commands_.clear();
}

void EntitySystem::destroy(Entity entity) {
  if (!entity) return;
  std::unique_ptr<CommandBase> ptr{new Command([this, entity] (EntitySystem &) mutable {
      if (!entity) return;
      if (!entity.component<Warpgate>()) {
          if (auto client = getClient(entity); client)
            SendPacket(client, CMapServer::eSendType::EVERYONE_BUT_ME,
                               *makePacket<ePacketType::PAKWC_REMOVE_OBJECT>(entity));
          else
            SendPacket(std::shared_ptr<CMapClient>{}, CMapServer::eSendType::EVERYONE,
                           *makePacket<ePacketType::PAKWC_REMOVE_OBJECT>(entity));
      if (!entity.component<Npc>()) {
          saveCharacter(entity.component<CharacterInfo>()->charId_, entity);
          auto basic = entity.component<BasicInfo>();
          nameToEntity_.erase(basic->name_);
          idToEntity_.erase(basic->id_);
          id_manager_.release_id(basic->id_);
      }
      }
      entity.destroy();
    })};
  std::lock_guard<std::mutex> lock(access_);
  delete_commands_.emplace_back(std::move(ptr));
}

Entity EntitySystem::create() { return entityManager_.create(); }

bool EntitySystem::isNearby(Entity a, Entity b) {
    return systemManager_.get<Systems::MovementSystem>()->is_nearby(a, b);
}

bool EntitySystem::dispatch(Entity entity, std::unique_ptr<RoseCommon::CRosePacket> packet) {
  if (!entity) return false;
  if (systemManager_.wouldDispatch(*packet)) {
    std::lock_guard<std::mutex> lock(access_);
    toDispatch_.emplace(std::make_pair(entity, std::move(packet)));
    return true;
  }
  return false;
}

Entity EntitySystem::loadCharacter(uint32_t charId, bool platinium) {
  auto conn = Core::connectionPool.getConnection(Core::osirose);
  Core::CharacterTable characters{};
  Core::InventoryTable inventoryTable{};
  Core::SkillTable skillsTable{};

  auto charRes = conn(sqlpp::select(sqlpp::count(characters.id), sqlpp::all_of(characters))
                          .from(characters)
                          .where(characters.id == charId));

  std::lock_guard<std::mutex> lock(access_);
  auto entity = create();
  if (static_cast<long>(charRes.front().count) != 1L) {
    entity.destroy();
    return Entity();
  }
  const auto& charRow = charRes.front();

  entity.assign<Position>(charRow);
  entity.assign<BasicInfo>(charRow, id_manager_.get_free_id());
  entity.assign<Stats>(charRow);
  entity.assign<AdvancedInfo>(charRow);
  entity.assign<CharacterGraphics>(charRow);
  entity.assign<CharacterInfo>(charRow, platinium, charId);

  // TODO : write the pat initialization code
  auto skills = entity.assign<Skills>();
  auto skillRes =
      conn(sqlpp::select(skillsTable.id, skillsTable.level).from(skillsTable).where(skillsTable.charId == charId));
  skills->loadFromResult(skillRes);

  // TODO : write the hotbar table and loading code
  entity.assign<Hotbar>();
  entity.assign<StatusEffects>();
  entity.assign<RidingItems>();
  entity.assign<BulletItems>();

  // TODO : write the inventory code
  // auto luaSystem = systemManager_.get<Systems::LuaSystem>();
  auto inventory = entity.assign<Inventory>();

  auto invRes =
      conn(sqlpp::select(sqlpp::all_of(inventoryTable)).from(inventoryTable).where(inventoryTable.charId == charId));
  inventory->loadFromResult(invRes, get<Systems::InventorySystem>());

  Systems::UpdateSystem::calculateSpeed(entity);

  entity.assign<Quests>();

  Core::WishTable wish{};
  auto wishRes = conn(sqlpp::select(sqlpp::all_of(wish)).from(wish).where(wish.charId == charId));
  auto wishlist = entity.assign<Wishlist>();
  wishlist->loadFromResult(wishRes, get<Systems::InventorySystem>());

  // auto lua = entity.assign<EntityAPI>();

  // luaSystem->loadScript(entity, "function onInit()\ndisplay('test')\nend");
  // lua->onInit();

  registerEntity(entity);
  return entity;
}

void EntitySystem::saveCharacter(uint32_t charId, Entity entity) {
  if (!entity) return;
  auto conn = Core::connectionPool.getConnection(Core::osirose);
  Core::CharacterTable characters{};

  using sqlpp::parameter;

  auto update = sqlpp::dynamic_update(conn.get(), characters).dynamic_set().where(characters.id == charId);
  entity.component<Position>()->commitToUpdate<decltype(characters)>(update);
  entity.component<BasicInfo>()->commitToUpdate<decltype(characters)>(update);
  entity.component<Stats>()->commitToUpdate<decltype(characters)>(update);
  entity.component<AdvancedInfo>()->commitToUpdate<decltype(characters)>(update);
  // entity.component<CharacterGraphics>()->commitToUpdate(update);
  entity.component<CharacterInfo>()->commitToUpdate<decltype(characters)>(update);
  // entity.component<Hotbar>()->commitToUpdate(update);
  // entity.component<StatusEffects>()->commitToUpdate(update);
  // entity.component<RidingItems>()->commitToUpdate(update);
  // entity.component<BulletItems>()->commitToUpdate(update);

  conn->run(update);

  // entity.component<Skills>()->commitToUpdate(updateSkills);

  Core::InventoryTable inv{};
  auto invRes = conn(sqlpp::select(sqlpp::all_of(inv)).from(inv).where(inv.charId == charId));

  const auto& items = entity.component<Inventory>()->items_;

  std::vector<size_t> toDelete;
  std::vector<size_t> toUpdate;
  std::set<size_t> modified;
  std::vector<size_t> toInsert;

  for (const auto& row : invRes) {
    if (row.slot >= Inventory::maxItems)
      toDelete.emplace_back(row.slot);  // FIXME: that should never happen
    else if (!items[row.slot])
      toDelete.emplace_back(row.slot);
    else if (items[row.slot] != Item(row))
      toUpdate.emplace_back(row.slot);
    modified.insert(row.slot);
  }
  size_t i = 0;
  for (const auto& item : items) {
    if (item && modified.find(i) == modified.end()) toInsert.emplace_back(i);
    ++i;
  }

  for (auto it : toDelete) conn(sqlpp::remove_from(inv).where(inv.charId == charId and inv.slot == it));
  for (auto it : toUpdate) {
    auto update = sqlpp::dynamic_update(conn.get(), inv).dynamic_set().where(inv.charId == charId and inv.slot == it);
    items[it].commitToUpdate<decltype(inv)>(update);
    conn->run(update);
  }
  for (auto it : toInsert) {
    auto insert = sqlpp::dynamic_insert_into(conn.get(), inv).dynamic_set();
    items[it].commitToInsert<decltype(inv)>(insert);
    insert.insert_list.add(inv.slot = it);
    insert.insert_list.add(inv.charId = charId);
    conn->run(insert);
  }
}

Entity EntitySystem::create_warpgate(std::string alias, int dest_map_id, float dest_x, float dest_y, float dest_z,
                    int map_id, float x, float y, float z, float angle,
                    float x_scale, float y_scale, float z_scale) {
    Entity e = create();
    std::unique_ptr<CommandBase> ptr{new Command([alias, dest_map_id, dest_x, dest_y, dest_z,
                                                  map_id, x, y, z, angle, x_scale, y_scale, z_scale,
                                                  e] (EntitySystem &es) mutable {
      if (!e) return;
      e.assign<BasicInfo>(es.id_manager_.get_free_id());

      auto pos = e.assign<Position>(x * 100, y * 100, map_id, 0);

      pos->z_ = static_cast<uint16_t>(z);
      pos->angle_ = angle;

      auto dest = e.assign<Destination>(dest_x * 100, dest_y * 100, dest_map_id);
      dest->z_ = static_cast<uint16_t>(dest_z);
    })};
    create_commands_.emplace_back(std::move(ptr));
    return e;
}

Entity EntitySystem::create_npc(std::string npc_lua, int npc_id, int map_id, float x, float y, float z, float angle) {
    Entity e = create();
    std::unique_ptr<CommandBase> ptr{new Command([npc_lua, npc_id, map_id, x, y, z, angle, e] (EntitySystem &es) mutable {
      if (!e) return;
      e.assign<BasicInfo>(es.id_manager_.get_free_id());
      e.assign<AdvancedInfo>();
      e.assign<CharacterInfo>();

      uint16_t dialog_id = 0;
      if (!npc_lua.empty()) {
        dialog_id = std::stoi(npc_lua);
      }
      e.assign<Npc>(npc_id, dialog_id);
      auto pos = e.assign<Position>(x * 100, y * 100, map_id, 0);

      pos->z_ = static_cast<uint16_t>(z);
      pos->angle_ = angle;
      //e.assign<EntityApi>();
      // we send the new NPC to the existing clients
      es.SendPacket(std::shared_ptr<CMapClient>{}, CMapServer::eSendType::EVERYONE,
              *makePacket<ePacketType::PAKWC_NPC_CHAR>(e));
    })};
    create_commands_.emplace_back(std::move(ptr));
    return e;
}

Entity EntitySystem::create_spawner(std::string alias, int mob_id, int mob_count,
                   int spawner_limit, int spawner_interval, int spawner_range,
                   int map_id, float x, float y, float z) {
  return {};
}

void EntitySystem::bulk_destroy(const std::vector<Entity>& s) {
  std::unique_ptr<CommandBase> ptr{new Command([this, s] (EntitySystem &) mutable {
    for (auto entity : s) {
        if (!entity) continue;
        if (!entity.component<Warpgate>())
            SendPacket(std::shared_ptr<CMapClient>{}, CMapServer::eSendType::EVERYONE,
                       *makePacket<ePacketType::PAKWC_REMOVE_OBJECT>(entity));
        entity.destroy();
    }
  })};
  std::lock_guard<std::mutex> lock(access_);
  delete_commands_.emplace_back(std::move(ptr));
}

LuaScript::ScriptLoader& EntitySystem::get_script_loader() noexcept {
  return server_->get_script_loader();
}

void EntitySystem::SendPacket(const std::shared_ptr<CMapClient>& sender, CMapServer::eSendType type,
                            CRosePacket& _buffer) {
  server_->SendPacket(sender, type, _buffer);
}

void EntitySystem::SendPacket(const CMapClient& sender, CMapServer::eSendType type, CRosePacket& _buffer) {
  server_->SendPacket(sender, type, _buffer);
}
<commit_msg>Removed unecessary stuff<commit_after>#include <set>
#include <vector>

#include "entitysystem.h"
#include "cmapclient.h"
#include "cmapserver.h"
#include "connection.h"
#include "systems/chatsystem.h"
#include "systems/inventorysystem.h"
#include "systems/luasystem.h"
#include "systems/mapsystem.h"
#include "systems/movementsystem.h"
#include "systems/partysystem.h"
#include "systems/updatesystem.h"

#include "srv_npcchar.h"

using namespace RoseCommon;
EntitySystem::EntitySystem(CMapServer *server) : systemManager_(*this), server_(server) {
  systemManager_.add<Systems::MovementSystem>();
  systemManager_.add<Systems::UpdateSystem>();
  systemManager_.add<Systems::ChatSystem>();
  systemManager_.add<Systems::InventorySystem>();
  systemManager_.add<Systems::PartySystem>();
  systemManager_.add<Systems::MapSystem>();
  systemManager_.add<Systems::LuaSystem>();
}
EntityManager& EntitySystem::getEntityManager() { return entityManager_; }

Entity EntitySystem::buildItemEntity(Entity creator, RoseCommon::Item&& item) {
  Entity e = create();
  e.assign<Item>(std::move(item));
  auto pos = creator.component<Position>();
  e.assign<Position>(pos->x_, pos->y_, pos->map_, 0);
  auto basic = e.assign<BasicInfo>();
  basic->ownerId_ = creator.component<BasicInfo>()->id_;
  basic->id_ = id_manager_.get_free_id();
  itemToEntity_[basic->id_] = e;
  return e;
}

void EntitySystem::registerEntity(Entity entity) {
  if (!entity) return;
  auto basic = entity.component<BasicInfo>();
  if (!basic || basic->name_ == "" || !basic->id_) return;
  nameToEntity_[basic->name_] = entity;
  idToEntity_[basic->id_] = entity;
}

Entity EntitySystem::getItemEntity(uint32_t id) { return itemToEntity_[id]; }

Entity EntitySystem::getEntity(const std::string& name) { return nameToEntity_[name]; }

Entity EntitySystem::getEntity(uint32_t charId) { return idToEntity_[charId]; }

void EntitySystem::update(double dt) {
  std::lock_guard<std::mutex> lock(access_);
  for (auto& it : create_commands_) {
    it->execute(*this);
  }
  create_commands_.clear();
  while (toDispatch_.size()) {
    auto tmp = std::move(toDispatch_.front());
    systemManager_.dispatch(tmp.first, *tmp.second);
    toDispatch_.pop();
  }
  systemManager_.update(dt);
  for (auto& it : delete_commands_) {
    it->execute(*this);
  }
  delete_commands_.clear();
}

void EntitySystem::destroy(Entity entity) {
  if (!entity) return;
  std::unique_ptr<CommandBase> ptr{new Command([entity] (EntitySystem &es) mutable {
      if (!entity) return;
      if (!entity.component<Warpgate>()) {
          if (auto client = getClient(entity); client)
            es.SendPacket(client, CMapServer::eSendType::EVERYONE_BUT_ME,
                               *makePacket<ePacketType::PAKWC_REMOVE_OBJECT>(entity));
          else
            es.SendPacket(std::shared_ptr<CMapClient>{}, CMapServer::eSendType::EVERYONE,
                           *makePacket<ePacketType::PAKWC_REMOVE_OBJECT>(entity));
      if (!entity.component<Npc>()) {
          es.saveCharacter(entity.component<CharacterInfo>()->charId_, entity);
          auto basic = entity.component<BasicInfo>();
          es.nameToEntity_.erase(basic->name_);
          es.idToEntity_.erase(basic->id_);
          es.id_manager_.release_id(basic->id_);
      }
      }
      entity.destroy();
    })};
  std::lock_guard<std::mutex> lock(access_);
  delete_commands_.emplace_back(std::move(ptr));
}

Entity EntitySystem::create() { return entityManager_.create(); }

bool EntitySystem::isNearby(Entity a, Entity b) {
    return systemManager_.get<Systems::MovementSystem>()->is_nearby(a, b);
}

bool EntitySystem::dispatch(Entity entity, std::unique_ptr<RoseCommon::CRosePacket> packet) {
  if (!entity) return false;
  if (systemManager_.wouldDispatch(*packet)) {
    std::lock_guard<std::mutex> lock(access_);
    toDispatch_.emplace(std::make_pair(entity, std::move(packet)));
    return true;
  }
  return false;
}

Entity EntitySystem::loadCharacter(uint32_t charId, bool platinium) {
  auto conn = Core::connectionPool.getConnection(Core::osirose);
  Core::CharacterTable characters{};
  Core::InventoryTable inventoryTable{};
  Core::SkillTable skillsTable{};

  auto charRes = conn(sqlpp::select(sqlpp::count(characters.id), sqlpp::all_of(characters))
                          .from(characters)
                          .where(characters.id == charId));

  std::lock_guard<std::mutex> lock(access_);
  auto entity = create();
  if (static_cast<long>(charRes.front().count) != 1L) {
    entity.destroy();
    return Entity();
  }
  const auto& charRow = charRes.front();

  entity.assign<Position>(charRow);
  entity.assign<BasicInfo>(charRow, id_manager_.get_free_id());
  entity.assign<Stats>(charRow);
  entity.assign<AdvancedInfo>(charRow);
  entity.assign<CharacterGraphics>(charRow);
  entity.assign<CharacterInfo>(charRow, platinium, charId);

  // TODO : write the pat initialization code
  auto skills = entity.assign<Skills>();
  auto skillRes =
      conn(sqlpp::select(skillsTable.id, skillsTable.level).from(skillsTable).where(skillsTable.charId == charId));
  skills->loadFromResult(skillRes);

  // TODO : write the hotbar table and loading code
  entity.assign<Hotbar>();
  entity.assign<StatusEffects>();
  entity.assign<RidingItems>();
  entity.assign<BulletItems>();

  // TODO : write the inventory code
  // auto luaSystem = systemManager_.get<Systems::LuaSystem>();
  auto inventory = entity.assign<Inventory>();

  auto invRes =
      conn(sqlpp::select(sqlpp::all_of(inventoryTable)).from(inventoryTable).where(inventoryTable.charId == charId));
  inventory->loadFromResult(invRes, get<Systems::InventorySystem>());

  Systems::UpdateSystem::calculateSpeed(entity);

  entity.assign<Quests>();

  Core::WishTable wish{};
  auto wishRes = conn(sqlpp::select(sqlpp::all_of(wish)).from(wish).where(wish.charId == charId));
  auto wishlist = entity.assign<Wishlist>();
  wishlist->loadFromResult(wishRes, get<Systems::InventorySystem>());

  // auto lua = entity.assign<EntityAPI>();

  // luaSystem->loadScript(entity, "function onInit()\ndisplay('test')\nend");
  // lua->onInit();

  registerEntity(entity);
  return entity;
}

void EntitySystem::saveCharacter(uint32_t charId, Entity entity) {
  if (!entity) return;
  auto conn = Core::connectionPool.getConnection(Core::osirose);
  Core::CharacterTable characters{};

  using sqlpp::parameter;

  auto update = sqlpp::dynamic_update(conn.get(), characters).dynamic_set().where(characters.id == charId);
  entity.component<Position>()->commitToUpdate<decltype(characters)>(update);
  entity.component<BasicInfo>()->commitToUpdate<decltype(characters)>(update);
  entity.component<Stats>()->commitToUpdate<decltype(characters)>(update);
  entity.component<AdvancedInfo>()->commitToUpdate<decltype(characters)>(update);
  // entity.component<CharacterGraphics>()->commitToUpdate(update);
  entity.component<CharacterInfo>()->commitToUpdate<decltype(characters)>(update);
  // entity.component<Hotbar>()->commitToUpdate(update);
  // entity.component<StatusEffects>()->commitToUpdate(update);
  // entity.component<RidingItems>()->commitToUpdate(update);
  // entity.component<BulletItems>()->commitToUpdate(update);

  conn->run(update);

  // entity.component<Skills>()->commitToUpdate(updateSkills);

  Core::InventoryTable inv{};
  auto invRes = conn(sqlpp::select(sqlpp::all_of(inv)).from(inv).where(inv.charId == charId));

  const auto& items = entity.component<Inventory>()->items_;

  std::vector<size_t> toDelete;
  std::vector<size_t> toUpdate;
  std::set<size_t> modified;
  std::vector<size_t> toInsert;

  for (const auto& row : invRes) {
    if (row.slot >= Inventory::maxItems)
      toDelete.emplace_back(row.slot);  // FIXME: that should never happen
    else if (!items[row.slot])
      toDelete.emplace_back(row.slot);
    else if (items[row.slot] != Item(row))
      toUpdate.emplace_back(row.slot);
    modified.insert(row.slot);
  }
  size_t i = 0;
  for (const auto& item : items) {
    if (item && modified.find(i) == modified.end()) toInsert.emplace_back(i);
    ++i;
  }

  for (auto it : toDelete) conn(sqlpp::remove_from(inv).where(inv.charId == charId and inv.slot == it));
  for (auto it : toUpdate) {
    auto update = sqlpp::dynamic_update(conn.get(), inv).dynamic_set().where(inv.charId == charId and inv.slot == it);
    items[it].commitToUpdate<decltype(inv)>(update);
    conn->run(update);
  }
  for (auto it : toInsert) {
    auto insert = sqlpp::dynamic_insert_into(conn.get(), inv).dynamic_set();
    items[it].commitToInsert<decltype(inv)>(insert);
    insert.insert_list.add(inv.slot = it);
    insert.insert_list.add(inv.charId = charId);
    conn->run(insert);
  }
}

Entity EntitySystem::create_warpgate(std::string alias, int dest_map_id, float dest_x, float dest_y, float dest_z,
                    int map_id, float x, float y, float z, float angle,
                    float x_scale, float y_scale, float z_scale) {
    Entity e = create();
    std::unique_ptr<CommandBase> ptr{new Command([alias, dest_map_id, dest_x, dest_y, dest_z,
                                                  map_id, x, y, z, angle, x_scale, y_scale, z_scale,
                                                  e] (EntitySystem &es) mutable {
      if (!e) return;
      e.assign<BasicInfo>(es.id_manager_.get_free_id());

      auto pos = e.assign<Position>(x * 100, y * 100, map_id, 0);

      pos->z_ = static_cast<uint16_t>(z);
      pos->angle_ = angle;

      auto dest = e.assign<Destination>(dest_x * 100, dest_y * 100, dest_map_id);
      dest->z_ = static_cast<uint16_t>(dest_z);
    })};
    create_commands_.emplace_back(std::move(ptr));
    return e;
}

Entity EntitySystem::create_npc(std::string npc_lua, int npc_id, int map_id, float x, float y, float z, float angle) {
    Entity e = create();
    std::unique_ptr<CommandBase> ptr{new Command([npc_lua, npc_id, map_id, x, y, z, angle, e] (EntitySystem &es) mutable {
      if (!e) return;
      e.assign<BasicInfo>(es.id_manager_.get_free_id());
      e.assign<AdvancedInfo>();
      e.assign<CharacterInfo>();

      uint16_t dialog_id = 0;
      if (!npc_lua.empty()) {
        dialog_id = std::stoi(npc_lua);
      }
      e.assign<Npc>(npc_id, dialog_id);
      auto pos = e.assign<Position>(x * 100, y * 100, map_id, 0);

      pos->z_ = static_cast<uint16_t>(z);
      pos->angle_ = angle;
      //e.assign<EntityApi>();
      // we send the new NPC to the existing clients
      es.SendPacket(std::shared_ptr<CMapClient>{}, CMapServer::eSendType::EVERYONE,
              *makePacket<ePacketType::PAKWC_NPC_CHAR>(e));
    })};
    create_commands_.emplace_back(std::move(ptr));
    return e;
}

Entity EntitySystem::create_spawner(std::string alias, int mob_id, int mob_count,
                   int spawner_limit, int spawner_interval, int spawner_range,
                   int map_id, float x, float y, float z) {
  return {};
}

void EntitySystem::bulk_destroy(const std::vector<Entity>& s) {
  std::unique_ptr<CommandBase> ptr{new Command([s] (EntitySystem &es) mutable {
    for (auto entity : s) {
        if (!entity) continue;
        if (!entity.component<Warpgate>())
            es.SendPacket(std::shared_ptr<CMapClient>{}, CMapServer::eSendType::EVERYONE,
                         *makePacket<ePacketType::PAKWC_REMOVE_OBJECT>(entity));
        entity.destroy();
    }
  })};
  std::lock_guard<std::mutex> lock(access_);
  delete_commands_.emplace_back(std::move(ptr));
}

LuaScript::ScriptLoader& EntitySystem::get_script_loader() noexcept {
  return server_->get_script_loader();
}

void EntitySystem::SendPacket(const std::shared_ptr<CMapClient>& sender, CMapServer::eSendType type,
                            CRosePacket& _buffer) {
  server_->SendPacket(sender, type, _buffer);
}

void EntitySystem::SendPacket(const CMapClient& sender, CMapServer::eSendType type, CRosePacket& _buffer) {
  server_->SendPacket(sender, type, _buffer);
}
<|endoftext|>


<commit_before>#include "ReverbModule.h"
#include "../Random.h"
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include "SDL.h"

ReverbModule::ReverbModule(ModularSynth& synth)
	:SynthModule(synth, moduleId, 2, 1, 0), mHead(0), mBuffer(NULL)
{
	Random rnd;
	rnd.seed(rand());

	for (int i = 0 ; i < numTaps ; ++i)
	{
		mTap[i].gain = 1.0f / (1 + i);
		mTap[i].delay = static_cast<float>(i) / numTaps + rnd.rndf() * 0.9f / numTaps + 0.01f;
	}
}

ReverbModule::~ReverbModule()
{
	if (mBuffer != NULL)
	{
		delete[] mBuffer;
	}
}

void ReverbModule::cycle()
{
	mBuffer[mHead] = getInput(0);

	float delay = std::max(0.0f, getInput(1));
	float sum = 0;

	for (int i = 0 ; i < numTaps ; ++i)
	{
		sum += mBuffer[static_cast<int>(mHead - delay * mTap[i].delay * mSampleRate + mMaxBufferSize) % mMaxBufferSize] * mTap[i].gain;
	}

	setOutput(0, sum);

	++mHead;

	if (mHead >= mMaxBufferSize)
		mHead = 0;
}

const char * ReverbModule::getInputName(int input) const
{
	static const char *names[] = {"Input"};
	return names[input];
}

const char * ReverbModule::getOutputName(int output) const
{
	static const char *names[] = {"Output"};
	return names[output];
}

const char * ReverbModule::getName() const
{
	return "Reverb";
}

SynthModule * ReverbModule::createModule(ModularSynth& synth)
{
	return new ReverbModule(synth);
}

void ReverbModule::setSampleRate(int newRate)
{
	SynthModule::setSampleRate(newRate);

	if (mBuffer != NULL)
		delete[] mBuffer;

	mMaxBufferSize = std::max(1, maxBufferSizeMs * newRate / 1000);

	printf("mMaxBufferSize = %d\n", mMaxBufferSize);

	mBuffer = new float[mMaxBufferSize];
	SDL_memset(mBuffer, 0, mMaxBufferSize * sizeof(mBuffer[0]));

	mHead = 0;
}
<commit_msg>ReverbModule dry out<commit_after>#include "ReverbModule.h"
#include "../Random.h"
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include "SDL.h"

ReverbModule::ReverbModule(ModularSynth& synth)
	:SynthModule(synth, moduleId, 2, 2, 0), mHead(0), mBuffer(NULL)
{
	Random rnd;
	rnd.seed(rand());

	for (int i = 0 ; i < numTaps ; ++i)
	{
		mTap[i].gain = 1.0f / (1 + i);
		mTap[i].delay = static_cast<float>(i) / numTaps + rnd.rndf() * 0.9f / numTaps + 0.01f;
	}
}

ReverbModule::~ReverbModule()
{
	if (mBuffer != NULL)
	{
		delete[] mBuffer;
	}
}

void ReverbModule::cycle()
{
	mBuffer[mHead] = getInput(0);

	float delay = std::min(static_cast<float>(maxBufferSizeMs) / 1000, std::max(0.0f, getInput(1)));
	float sum = 0;

	for (int i = 0 ; i < numTaps ; ++i)
	{
		sum += mBuffer[static_cast<int>(mHead - delay * mTap[i].delay * mSampleRate + mMaxBufferSize) % mMaxBufferSize] * mTap[i].gain;
	}

	setOutput(0, sum);
	setOutput(1, getInput(0));

	++mHead;

	if (mHead >= mMaxBufferSize)
		mHead = 0;
}

const char * ReverbModule::getInputName(int input) const
{
	static const char *names[] = {"Input", "Length"};
	return names[input];
}

const char * ReverbModule::getOutputName(int output) const
{
	static const char *names[] = {"Reverb out", "Dry out"};
	return names[output];
}

const char * ReverbModule::getName() const
{
	return "Reverb";
}

SynthModule * ReverbModule::createModule(ModularSynth& synth)
{
	return new ReverbModule(synth);
}

void ReverbModule::setSampleRate(int newRate)
{
	SynthModule::setSampleRate(newRate);

	if (mBuffer != NULL)
		delete[] mBuffer;

	mMaxBufferSize = std::max(1, maxBufferSizeMs * newRate / 1000);

	mBuffer = new float[mMaxBufferSize];
	SDL_memset(mBuffer, 0, mMaxBufferSize * sizeof(mBuffer[0]));

	mHead = 0;
}
<|endoftext|>