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

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
#include <cwctype>
#include <type_traits>

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

namespace Stroika::Foundation::Characters {

    /*
     ********************************************************************************
     *********************************** Character **********************************
     ********************************************************************************
     */
    constexpr inline Character::Character ()
        : fCharacterCode_{'\0'}
    {
    }
    constexpr inline Character::Character (char c)
        : fCharacterCode_{static_cast<wchar_t> (c)}
    {
    }
    constexpr inline Character::Character (char16_t c)
        : fCharacterCode_{c}
    {
    }
    DISABLE_COMPILER_MSC_WARNING_START (4244)
    // NB: THIS IS A REAL BUG/ISSUE. WE MUST DO WORK TO TRANSFORM. REDESIGN REQUIRED!!!
    constexpr inline Character::Character (char32_t c)
        : fCharacterCode_{static_cast<wchar_t> (c)}
    {
    }
    DISABLE_COMPILER_MSC_WARNING_END (4244)
    constexpr inline Character::Character (wchar_t wc)
        : fCharacterCode_{wc}
    {
    }
    inline char Character::GetAsciiCode () const
    {
        Require (IsASCII ());
        return static_cast<char> (fCharacterCode_);
    }
    inline wchar_t Character::GetCharacterCode () const
    {
        return fCharacterCode_;
    }
    template <>
    inline wchar_t Character::As () const
    {
        return GetCharacterCode ();
    }
    template <>
    inline char32_t Character::As () const
    {
        return GetCharacterCode ();
    }
    inline bool Character::IsASCII () const
    {
        return 0x0 <= fCharacterCode_ and fCharacterCode_ <= 0x7f;
    }
    inline bool Character::IsWhitespace () const
    {
        return !!iswspace (fCharacterCode_);
    }
    inline bool Character::IsDigit () const
    {
        return !!iswdigit (fCharacterCode_);
    }
    inline bool Character::IsHexDigit () const
    {
        return !!iswxdigit (fCharacterCode_);
    }
    inline bool Character::IsAlphabetic () const
    {
        return !!iswalpha (fCharacterCode_);
    }
    inline bool Character::IsUpperCase () const
    {
        return !!iswupper (fCharacterCode_);
    }
    inline bool Character::IsLowerCase () const
    {
        return !!iswlower (fCharacterCode_);
    }
    inline bool Character::IsAlphaNumeric () const
    {
        return !!iswalnum (fCharacterCode_);
    }
    inline bool Character::IsPunctuation () const
    {
        return !!iswpunct (fCharacterCode_);
    }
    inline bool Character::IsControl () const
    {
        return !!iswcntrl (fCharacterCode_);
    }
    inline Character Character::ToLowerCase () const
    {
        // Cannot find good spec on towlower/towupper, so not sure that this check is necessary
        if (::iswupper (fCharacterCode_)) {
            return static_cast<wchar_t> (::towlower (fCharacterCode_));
        }
        else {
            return fCharacterCode_;
        }
    }
    inline Character Character::ToUpperCase () const
    {
        if (::iswlower (fCharacterCode_)) {
            return static_cast<wchar_t> (::towupper (fCharacterCode_));
        }
        else {
            return fCharacterCode_;
        }
    }

    /*
     ********************************************************************************
     *************************** Character::EqualsComparer **************************
     ********************************************************************************
     */
    constexpr Character::EqualsComparer::EqualsComparer (CompareOptions co)
        : fCompareOptions{co}
    {
    }
    constexpr bool Character::EqualsComparer::operator() (Character lhs, Character rhs) const
    {
        using namespace Stroika::Foundation::Characters;
        switch (fCompareOptions) {
            case CompareOptions::eCaseInsensitive:
                return Character::Compare (&lhs, &lhs + 1, &rhs, &rhs + 1, CompareOptions::eCaseInsensitive) == 0;
            case CompareOptions::eWithCase:
                return lhs.GetCharacterCode () == rhs.GetCharacterCode ();
            default:
                AssertNotReached ();
                return false;
        }
    }

    /*
     ********************************************************************************
     ************************* Character::ThreeWayComparer **************************
     ********************************************************************************
     */
    constexpr Character::ThreeWayComparer::ThreeWayComparer (Stroika::Foundation::Characters::CompareOptions co)
        : fCompareOptions{co}
    {
    }
    inline auto Character::ThreeWayComparer::operator() (Stroika::Foundation::Characters::Character lhs, Stroika::Foundation::Characters::Character rhs) const
    {
        using namespace Stroika::Foundation::Characters;
        using SIGNED_WCHART_ = make_signed_t<wchar_t>;
        switch (fCompareOptions) {
            case CompareOptions::eCaseInsensitive:
                return Character::Compare (&lhs, &lhs + 1, &rhs, &rhs + 1, CompareOptions::eCaseInsensitive);
            case CompareOptions::eWithCase:
                return Common::ThreeWayCompare (static_cast<SIGNED_WCHART_> (lhs.GetCharacterCode ()), static_cast<SIGNED_WCHART_> (rhs.GetCharacterCode ()));
            default:
                AssertNotReached ();
                return Common::kEqual;
        }
    }

#if __cpp_impl_three_way_comparison < 201907
    /*
     ********************************************************************************
     ************************* Character operators **********************************
     ********************************************************************************
     */
    inline bool operator< (Character lhs, Character rhs)
    {
        return Common::ThreeWayComparer{}(lhs, rhs) < 0;
    }
    inline bool operator<= (Character lhs, Character rhs)
    {
        return Common::ThreeWayComparer{}(lhs, rhs) <= 0;
    }
    inline bool operator== (Character lhs, Character rhs)
    {
        return Common::ThreeWayComparer{}(lhs, rhs) == 0;
    }
    inline bool operator!= (Character lhs, Character rhs)
    {
        return Common::ThreeWayComparer{}(lhs, rhs) != 0;
    }
    inline bool operator>= (Character lhs, Character rhs)
    {
        return Common::ThreeWayComparer{}(lhs, rhs) >= 0;
    }
    inline bool operator> (Character lhs, Character rhs)
    {
        return Common::ThreeWayComparer{}(lhs, rhs) > 0;
    }
#endif

}

#endif /*_Stroika_Foundation_Characters_Character_inl_*/
<commit_msg>fixed recent minor ThreeWayComparer regression<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2021.  All rights reserved
 */
#ifndef _Stroika_Foundation_Characters_Character_inl_
#define _Stroika_Foundation_Characters_Character_inl_ 1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
#include <cwctype>
#include <type_traits>

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

namespace Stroika::Foundation::Characters {

    /*
     ********************************************************************************
     *********************************** Character **********************************
     ********************************************************************************
     */
    constexpr inline Character::Character ()
        : fCharacterCode_{'\0'}
    {
    }
    constexpr inline Character::Character (char c)
        : fCharacterCode_{static_cast<wchar_t> (c)}
    {
    }
    constexpr inline Character::Character (char16_t c)
        : fCharacterCode_{c}
    {
    }
    DISABLE_COMPILER_MSC_WARNING_START (4244)
    // NB: THIS IS A REAL BUG/ISSUE. WE MUST DO WORK TO TRANSFORM. REDESIGN REQUIRED!!!
    constexpr inline Character::Character (char32_t c)
        : fCharacterCode_{static_cast<wchar_t> (c)}
    {
    }
    DISABLE_COMPILER_MSC_WARNING_END (4244)
    constexpr inline Character::Character (wchar_t wc)
        : fCharacterCode_{wc}
    {
    }
    inline char Character::GetAsciiCode () const
    {
        Require (IsASCII ());
        return static_cast<char> (fCharacterCode_);
    }
    inline wchar_t Character::GetCharacterCode () const
    {
        return fCharacterCode_;
    }
    template <>
    inline wchar_t Character::As () const
    {
        return GetCharacterCode ();
    }
    template <>
    inline char32_t Character::As () const
    {
        return GetCharacterCode ();
    }
    inline bool Character::IsASCII () const
    {
        return 0x0 <= fCharacterCode_ and fCharacterCode_ <= 0x7f;
    }
    inline bool Character::IsWhitespace () const
    {
        return !!iswspace (fCharacterCode_);
    }
    inline bool Character::IsDigit () const
    {
        return !!iswdigit (fCharacterCode_);
    }
    inline bool Character::IsHexDigit () const
    {
        return !!iswxdigit (fCharacterCode_);
    }
    inline bool Character::IsAlphabetic () const
    {
        return !!iswalpha (fCharacterCode_);
    }
    inline bool Character::IsUpperCase () const
    {
        return !!iswupper (fCharacterCode_);
    }
    inline bool Character::IsLowerCase () const
    {
        return !!iswlower (fCharacterCode_);
    }
    inline bool Character::IsAlphaNumeric () const
    {
        return !!iswalnum (fCharacterCode_);
    }
    inline bool Character::IsPunctuation () const
    {
        return !!iswpunct (fCharacterCode_);
    }
    inline bool Character::IsControl () const
    {
        return !!iswcntrl (fCharacterCode_);
    }
    inline Character Character::ToLowerCase () const
    {
        // Cannot find good spec on towlower/towupper, so not sure that this check is necessary
        if (::iswupper (fCharacterCode_)) {
            return static_cast<wchar_t> (::towlower (fCharacterCode_));
        }
        else {
            return fCharacterCode_;
        }
    }
    inline Character Character::ToUpperCase () const
    {
        if (::iswlower (fCharacterCode_)) {
            return static_cast<wchar_t> (::towupper (fCharacterCode_));
        }
        else {
            return fCharacterCode_;
        }
    }

    /*
     ********************************************************************************
     *************************** Character::EqualsComparer **************************
     ********************************************************************************
     */
    constexpr Character::EqualsComparer::EqualsComparer (CompareOptions co)
        : fCompareOptions{co}
    {
    }
    constexpr bool Character::EqualsComparer::operator() (Character lhs, Character rhs) const
    {
        using namespace Stroika::Foundation::Characters;
        switch (fCompareOptions) {
            case CompareOptions::eCaseInsensitive:
                return Character::Compare (&lhs, &lhs + 1, &rhs, &rhs + 1, CompareOptions::eCaseInsensitive) == 0;
            case CompareOptions::eWithCase:
                return lhs.GetCharacterCode () == rhs.GetCharacterCode ();
            default:
                AssertNotReached ();
                return false;
        }
    }

    /*
     ********************************************************************************
     ************************* Character::ThreeWayComparer **************************
     ********************************************************************************
     */
    constexpr Character::ThreeWayComparer::ThreeWayComparer (Stroika::Foundation::Characters::CompareOptions co)
        : fCompareOptions{co}
    {
    }
    inline auto Character::ThreeWayComparer::operator() (Stroika::Foundation::Characters::Character lhs, Stroika::Foundation::Characters::Character rhs) const
    {
        using namespace Stroika::Foundation::Characters;
        using SIGNED_WCHART_ = make_signed_t<wchar_t>;
        switch (fCompareOptions) {
            case CompareOptions::eCaseInsensitive:
                return Character::Compare (&lhs, &lhs + 1, &rhs, &rhs + 1, CompareOptions::eCaseInsensitive);
            case CompareOptions::eWithCase:
                return Common::ThreeWayCompare (static_cast<SIGNED_WCHART_> (lhs.GetCharacterCode ()), static_cast<SIGNED_WCHART_> (rhs.GetCharacterCode ()));
            default:
                AssertNotReached ();
                return Common::kEqual;
        }
    }

#if __cpp_impl_three_way_comparison < 201907
    /*
     ********************************************************************************
     ************************* Character operators **********************************
     ********************************************************************************
     */
    inline bool operator< (Character lhs, Character rhs)
    {
        return Character::ThreeWayComparer{}(lhs, rhs) < 0;
    }
    inline bool operator<= (Character lhs, Character rhs)
    {
        return Character::ThreeWayComparer{}(lhs, rhs) <= 0;
    }
    inline bool operator== (Character lhs, Character rhs)
    {
        return Character::ThreeWayComparer{}(lhs, rhs) == 0;
    }
    inline bool operator!= (Character lhs, Character rhs)
    {
        return Character::ThreeWayComparer{}(lhs, rhs) != 0;
    }
    inline bool operator>= (Character lhs, Character rhs)
    {
        return Character::ThreeWayComparer{}(lhs, rhs) >= 0;
    }
    inline bool operator> (Character lhs, Character rhs)
    {
        return Character::ThreeWayComparer{}(lhs, rhs) > 0;
    }
#endif

}

#endif /*_Stroika_Foundation_Characters_Character_inl_*/
<|endoftext|>


<commit_before>#include "TransferFunctionEditor.h"

TransferFunctionEditor::TransferFunctionEditor(OSPTransferFunction transferFunction)
{
    assert(transferFunction);
    transferFunction_ = transferFunction;

    // load color maps
    loadColorMaps();

    // set first available color map
    if(colorMaps_.size() > 0)
    {
        setColorMapIndex(0);
    }

    // setup UI elments
    QVBoxLayout * layout = new QVBoxLayout();
    setLayout(layout);

    // form layout
    QWidget * formWidget = new QWidget();
    QFormLayout * formLayout = new QFormLayout();
    formWidget->setLayout(formLayout);
    layout->addWidget(formWidget);

    // color map choice
    QComboBox * colorMapComboBox = new QComboBox();

    for(unsigned int i=0; i<colorMaps_.size(); i++)
    {
        colorMapComboBox->addItem(colorMaps_[i].getName().c_str());
    }

    formLayout->addRow("Color map", colorMapComboBox);

    connect(colorMapComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setColorMapIndex(int)));

    // data value range, used as the domain for both color and opacity components of the transfer function
    QDoubleSpinBox * dataValueMinSpinBox = new QDoubleSpinBox();
    QDoubleSpinBox * dataValueMaxSpinBox = new QDoubleSpinBox();
    dataValueMinSpinBox->setRange(-999999., 999999.);
    dataValueMaxSpinBox->setRange(-999999., 999999.);
    dataValueMinSpinBox->setValue(0.);
    dataValueMaxSpinBox->setValue(1.);
    formLayout->addRow("Data value min", dataValueMinSpinBox);
    formLayout->addRow("Data value max", dataValueMaxSpinBox);

    connect(dataValueMinSpinBox, SIGNAL(valueChanged(double)), this, SLOT(setDataValueMin(double)));
    connect(dataValueMaxSpinBox, SIGNAL(valueChanged(double)), this, SLOT(setDataValueMax(double)));

    // opacity transfer function widget
    layout->addWidget(&transferFunctionAlphaWidget_);

    connect(&transferFunctionAlphaWidget_, SIGNAL(transferFunctionChanged()), this, SLOT(transferFunctionAlphasChanged()));
}

void TransferFunctionEditor::transferFunctionAlphasChanged()
{
    // default to 256 discretizations of the opacities over the domain
    std::vector<float> transferFunctionAlphas = transferFunctionAlphaWidget_.getInterpolatedValuesOverInterval(256);

    OSPData transferFunctionAlphasData = ospNewData(transferFunctionAlphas.size(), OSP_FLOAT, transferFunctionAlphas.data());
    ospSetData(transferFunction_, "alphas", transferFunctionAlphasData);

    // commit and emit signal
    ospCommit(transferFunction_);
    emit transferFunctionChanged();
}

void TransferFunctionEditor::setColorMapIndex(int index)
{
    // set transfer function color properties for this color map
    std::vector<osp::vec3f> colors = colorMaps_[index].getColors();

    OSPData transferFunctionColorsData = ospNewData(colors.size(), OSP_vec3f, colors.data());
    ospSetData(transferFunction_, "colors", transferFunctionColorsData);

    // set transfer function widget background image
    transferFunctionAlphaWidget_.setBackgroundImage(colorMaps_[index].getImage());

    // commit and emit signal
    ospCommit(transferFunction_);
    emit transferFunctionChanged();
}

void TransferFunctionEditor::setDataValueMin(double value)
{
    // set as the minimum value in the domain for both color and opacity components of the transfer function
    ospSetf(transferFunction_, "colorValueMin", float(value));
    ospSetf(transferFunction_, "alphaValueMin", float(value));

    // commit and emit signal
    ospCommit(transferFunction_);
    emit transferFunctionChanged();
}

void TransferFunctionEditor::setDataValueMax(double value)
{
    // set as the maximum value in the domain for both color and opacity components of the transfer function
    ospSetf(transferFunction_, "colorValueMax", float(value));
    ospSetf(transferFunction_, "alphaValueMax", float(value));

    // commit and emit signal
    ospCommit(transferFunction_);
    emit transferFunctionChanged();
}

void TransferFunctionEditor::loadColorMaps()
{
    // default color map
    std::vector<osp::vec3f> defaultColors;
    defaultColors.push_back(osp::vec3f(0         , 1           , 0           ));
    defaultColors.push_back(osp::vec3f(0         , 0.120394    , 0.302678    ));
    defaultColors.push_back(osp::vec3f(0         , 0.216587    , 0.524575    ));
    defaultColors.push_back(osp::vec3f(0.0552529 , 0.345022    , 0.659495    ));
    defaultColors.push_back(osp::vec3f(0.128054  , 0.492592    , 0.720287    ));
    defaultColors.push_back(osp::vec3f(0.188952  , 0.641306    , 0.792096    ));
    defaultColors.push_back(osp::vec3f(0.327672  , 0.784939    , 0.873426    ));
    defaultColors.push_back(osp::vec3f(0.60824   , 0.892164    , 0.935546    ));
    defaultColors.push_back(osp::vec3f(0.881376  , 0.912184    , 0.818097    ));
    defaultColors.push_back(osp::vec3f(0.9514    , 0.835615    , 0.449271    ));
    defaultColors.push_back(osp::vec3f(0.904479  , 0.690486    , 0           ));
    defaultColors.push_back(osp::vec3f(0.854063  , 0.510857    , 0           ));
    defaultColors.push_back(osp::vec3f(0.777096  , 0.330175    , 0.000885023 ));
    defaultColors.push_back(osp::vec3f(0.672862  , 0.139086    , 0.00270085  ));
    defaultColors.push_back(osp::vec3f(0.508812  , 0           , 0           ));
    defaultColors.push_back(osp::vec3f(0.299413  , 0.000366217 , 0.000549325 ));
    // defaultColors.push_back(osp::vec3f(0.0157473 , 0.00332647  , 0           ));
    defaultColors.push_back(osp::vec3f(0.0157473 , 0.00332647  , 1           ));

    colorMaps_.push_back(ColorMap("default", defaultColors));

    // monochrome
    std::vector<osp::vec3f> monochromeColors;
    monochromeColors.push_back(osp::vec3f(0.));
    monochromeColors.push_back(osp::vec3f(1.));

    colorMaps_.push_back(ColorMap("monochrome", monochromeColors));
}
<commit_msg>new color maps available in volumeViewer.<commit_after>#include "TransferFunctionEditor.h"

TransferFunctionEditor::TransferFunctionEditor(OSPTransferFunction transferFunction)
{
    assert(transferFunction);
    transferFunction_ = transferFunction;

    // load color maps
    loadColorMaps();

    // set first available color map
    if(colorMaps_.size() > 0)
    {
        setColorMapIndex(0);
    }

    // setup UI elments
    QVBoxLayout * layout = new QVBoxLayout();
    setLayout(layout);

    // form layout
    QWidget * formWidget = new QWidget();
    QFormLayout * formLayout = new QFormLayout();
    formWidget->setLayout(formLayout);
    layout->addWidget(formWidget);

    // color map choice
    QComboBox * colorMapComboBox = new QComboBox();

    for(unsigned int i=0; i<colorMaps_.size(); i++)
    {
        colorMapComboBox->addItem(colorMaps_[i].getName().c_str());
    }

    formLayout->addRow("Color map", colorMapComboBox);

    connect(colorMapComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setColorMapIndex(int)));

    // data value range, used as the domain for both color and opacity components of the transfer function
    QDoubleSpinBox * dataValueMinSpinBox = new QDoubleSpinBox();
    QDoubleSpinBox * dataValueMaxSpinBox = new QDoubleSpinBox();
    dataValueMinSpinBox->setRange(-999999., 999999.);
    dataValueMaxSpinBox->setRange(-999999., 999999.);
    dataValueMinSpinBox->setValue(0.);
    dataValueMaxSpinBox->setValue(1.);
    formLayout->addRow("Data value min", dataValueMinSpinBox);
    formLayout->addRow("Data value max", dataValueMaxSpinBox);

    connect(dataValueMinSpinBox, SIGNAL(valueChanged(double)), this, SLOT(setDataValueMin(double)));
    connect(dataValueMaxSpinBox, SIGNAL(valueChanged(double)), this, SLOT(setDataValueMax(double)));

    // opacity transfer function widget
    layout->addWidget(&transferFunctionAlphaWidget_);

    connect(&transferFunctionAlphaWidget_, SIGNAL(transferFunctionChanged()), this, SLOT(transferFunctionAlphasChanged()));
}

void TransferFunctionEditor::transferFunctionAlphasChanged()
{
    // default to 256 discretizations of the opacities over the domain
    std::vector<float> transferFunctionAlphas = transferFunctionAlphaWidget_.getInterpolatedValuesOverInterval(256);

    OSPData transferFunctionAlphasData = ospNewData(transferFunctionAlphas.size(), OSP_FLOAT, transferFunctionAlphas.data());
    ospSetData(transferFunction_, "alphas", transferFunctionAlphasData);

    // commit and emit signal
    ospCommit(transferFunction_);
    emit transferFunctionChanged();
}

void TransferFunctionEditor::setColorMapIndex(int index)
{
    // set transfer function color properties for this color map
    std::vector<osp::vec3f> colors = colorMaps_[index].getColors();

    OSPData transferFunctionColorsData = ospNewData(colors.size(), OSP_vec3f, colors.data());
    ospSetData(transferFunction_, "colors", transferFunctionColorsData);

    // set transfer function widget background image
    transferFunctionAlphaWidget_.setBackgroundImage(colorMaps_[index].getImage());

    // commit and emit signal
    ospCommit(transferFunction_);
    emit transferFunctionChanged();
}

void TransferFunctionEditor::setDataValueMin(double value)
{
    // set as the minimum value in the domain for both color and opacity components of the transfer function
    ospSetf(transferFunction_, "colorValueMin", float(value));
    ospSetf(transferFunction_, "alphaValueMin", float(value));

    // commit and emit signal
    ospCommit(transferFunction_);
    emit transferFunctionChanged();
}

void TransferFunctionEditor::setDataValueMax(double value)
{
    // set as the maximum value in the domain for both color and opacity components of the transfer function
    ospSetf(transferFunction_, "colorValueMax", float(value));
    ospSetf(transferFunction_, "alphaValueMax", float(value));

    // commit and emit signal
    ospCommit(transferFunction_);
    emit transferFunctionChanged();
}

void TransferFunctionEditor::loadColorMaps()
{
    // color maps based on ParaView default color maps

    std::vector<osp::vec3f> colors;

    // jet
    colors.clear();
    colors.push_back(osp::vec3f(0         , 0           , 0.562493   ));
    colors.push_back(osp::vec3f(0         , 0           , 1          ));
    colors.push_back(osp::vec3f(0         , 1           , 1          ));
    colors.push_back(osp::vec3f(0.500008  , 1           , 0.500008   ));
    colors.push_back(osp::vec3f(1         , 1           , 0          ));
    colors.push_back(osp::vec3f(1         , 0           , 0          ));
    colors.push_back(osp::vec3f(0.500008  , 0           , 0          ));
    colorMaps_.push_back(ColorMap("Jet", colors));

    // ice / fire
    colors.clear();
    colors.push_back(osp::vec3f(0         , 0           , 0           ));
    colors.push_back(osp::vec3f(0         , 0.120394    , 0.302678    ));
    colors.push_back(osp::vec3f(0         , 0.216587    , 0.524575    ));
    colors.push_back(osp::vec3f(0.0552529 , 0.345022    , 0.659495    ));
    colors.push_back(osp::vec3f(0.128054  , 0.492592    , 0.720287    ));
    colors.push_back(osp::vec3f(0.188952  , 0.641306    , 0.792096    ));
    colors.push_back(osp::vec3f(0.327672  , 0.784939    , 0.873426    ));
    colors.push_back(osp::vec3f(0.60824   , 0.892164    , 0.935546    ));
    colors.push_back(osp::vec3f(0.881376  , 0.912184    , 0.818097    ));
    colors.push_back(osp::vec3f(0.9514    , 0.835615    , 0.449271    ));
    colors.push_back(osp::vec3f(0.904479  , 0.690486    , 0           ));
    colors.push_back(osp::vec3f(0.854063  , 0.510857    , 0           ));
    colors.push_back(osp::vec3f(0.777096  , 0.330175    , 0.000885023 ));
    colors.push_back(osp::vec3f(0.672862  , 0.139086    , 0.00270085  ));
    colors.push_back(osp::vec3f(0.508812  , 0           , 0           ));
    colors.push_back(osp::vec3f(0.299413  , 0.000366217 , 0.000549325 ));
    colors.push_back(osp::vec3f(0.0157473 , 0.00332647  , 0           ));
    colorMaps_.push_back(ColorMap("Ice / Fire", colors));

    // cool to warm
    colors.clear();
    colors.push_back(osp::vec3f(0.231373  , 0.298039    , 0.752941    ));
    colors.push_back(osp::vec3f(0.865003  , 0.865003    , 0.865003    ));
    colors.push_back(osp::vec3f(0.705882  , 0.0156863   , 0.14902     ));
    colorMaps_.push_back(ColorMap("Cool to Warm", colors));

    // blue to red rainbow
    colors.clear();
    colors.push_back(osp::vec3f(0         , 0           , 1           ));
    colors.push_back(osp::vec3f(1         , 0           , 0           ));
    colorMaps_.push_back(ColorMap("Blue to Red Rainbow", colors));

    // grayscale
    colors.clear();
    colors.push_back(osp::vec3f(0.));
    colors.push_back(osp::vec3f(1.));
    colorMaps_.push_back(ColorMap("Grayscale", colors));
}
<|endoftext|>


<commit_before>// Copyright (C) 2012-2014 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "HasForwardOnlyType.hpp"

class CommonUseCasesTest:
  public testing::Test
{};

class CUCTSample {};

// This file contains common use cases that have been observed often in the wild,
// and are therefore patterns that must be supported.  Adjustment of this file should
// only take place with great attention paid to a proper deprecation strategy.
TEST_F(CommonUseCasesTest, AutowiredForwardType) {
  HasForwardOnlyType f;
}

TEST_F(CommonUseCasesTest, CanMultiInject) {
  AutoCurrentContext ctxt;
  ctxt->Inject<CUCTSample, CUCTSample, CUCTSample, CUCTSample>();
}<commit_msg>Eliminating a now-deprecated function call<commit_after>// Copyright (C) 2012-2014 Leap Motion, Inc. All rights reserved.
#include "stdafx.h"
#include "HasForwardOnlyType.hpp"

class CommonUseCasesTest:
  public testing::Test
{};

class CUCTSample {};

// This file contains common use cases that have been observed often in the wild,
// and are therefore patterns that must be supported.  Adjustment of this file should
// only take place with great attention paid to a proper deprecation strategy.
TEST_F(CommonUseCasesTest, AutowiredForwardType) {
  HasForwardOnlyType f;
}
<|endoftext|>


<commit_before>#include "level_generator.hpp"

#include "room_template.hpp"

#include "../../core/utils/astar.hpp"
#include "../../core/utils/string_utils.hpp"

#include <sf2/sf2.hpp>
#include <sf2/FileParser.hpp>

#include <algorithm>
#include <random>
#include <glm/glm.hpp>

using namespace mo::util;

namespace {
	template<typename T>
	struct Range {
		T min;
		T max;
	};
	using IntRange = Range<int>;
	sf2_structDef(IntRange, sf2_member(min), sf2_member(max))

	struct Dungeon_cfg {
		IntRange room_size;
		IntRange rooms;
		int max_width, max_height;
		float split_prop_factor;
	};
	sf2_structDef(Dungeon_cfg,
		sf2_member(room_size),
		sf2_member(rooms),
		sf2_member(max_width),
		sf2_member(max_height),
		sf2_member(split_prop_factor)
	)

	struct Dungeon_cfg_map {
		std::unordered_map<int, Dungeon_cfg> levels;
	};
	sf2_structDef(Dungeon_cfg_map, sf2_member(levels))
}

namespace mo {
namespace asset {

	template<>
	struct Loader<Dungeon_cfg_map> {
		using T = Dungeon_cfg_map;
		static auto load(istream in) throw(Loading_failed) -> std::shared_ptr<T> {
			auto i = std::make_shared<T>();
			sf2::parseStream(in, *i);
			return i;
		}
		static void store(ostream out, T& asset) throw(Loading_failed);
	};

}

namespace level {
	namespace {
		Dungeon_cfg load_cfg(asset::Asset_manager& assets, int depth) {
			auto opts = assets.load<Dungeon_cfg_map>("cfg:dungeons"_aid);
			auto cfg_iter = opts->levels.find(depth);
			INVARIANT(cfg_iter!=opts->levels.end(), "You delved too greedily and too deep. Level="+to_string(depth));

			return cfg_iter->second;
		}

		struct Room_blueprint : public Room {
			std::vector<std::size_t> connections;
			asset::Ptr<Room_template> room_template;

			Room_blueprint(int top, int left, int right, int bottom)
				: Room(top, left, right, bottom) {}

			Room_blueprint split(int new_width, int new_height) {
				Room_blueprint r {
					top + new_height,
					left + new_width,
					right,
					bottom
				};

				if(new_width>0)
					right = left + new_width;

				if(new_height>0)
					bottom = top + new_height;

				return r;
			}
		};

		template<class T>
		std::vector<T> join(std::vector<T>&& a, std::vector<T>&& b) {
			a.reserve( a.size() + b.size() );
			std::move(b.begin(), b.end(), std::back_inserter(a));
			return a;
		}

		using Room_list = std::vector<Room_blueprint>;

		auto process_room(int depth, Room_blueprint room,
		                  std::bernoulli_distribution& split_dist,
		                  std::mt19937& rng, const Dungeon_cfg& cfg) -> Room_list;
		auto filter_rooms(Room_list rooms, std::mt19937& rng, const Dungeon_cfg& cfg) -> Room_list;
		void connect_rooms(Room_list& rooms, std::mt19937& rng, const Dungeon_cfg& cfg);
		auto build_level(Room_list& rooms, int width, int height) -> Level;
		void dig_corridors(Level& level, const Room_list& rooms);
	}

	Level generate_level(asset::Asset_manager& assets, uint64_t seed,
	                     int depth, int difficulty) {
		const auto cfg = load_cfg(assets, depth);

		std::mt19937 rng(seed+depth*7+difficulty*31);

		// 1. map zufällig an größter Achse trennen (rekursiv für die beiden neuen Zellen wiederholen)
		std::bernoulli_distribution split_dist(0.1);
		auto rooms = process_room(1, Room_blueprint{0,0, cfg.max_width, cfg.max_height}, split_dist, rng, cfg);

		// 2. zufällig Zellen verwerfen bis nur noch N übrig
		rooms = filter_rooms(rooms, rng, cfg);

		// 3. Graph/ Pfad aus den Zellen bauen (minimum-spanning tree)
		connect_rooms(rooms, rng, cfg);

		// 4. Rollenzuweisung anhand des Pfades

		// 5. Templates anhand der Rollen zuweisen

		// 6. Räume in Level konvertieren
		Level level = build_level(rooms, cfg.max_width, cfg.max_height);

		// 7. Tunnel für vorgesehene Pfade graben
		dig_corridors(level, rooms);

		// 8. Objekte erstellen

		return level;
	}

	namespace {

		auto process_room(int depth, Room_blueprint room, std::bernoulli_distribution& split_dist,
									  std::mt19937& rng, const Dungeon_cfg& cfg) -> Room_list {
			bool split = (room.height()>=cfg.room_size.min || room.width()>=cfg.room_size.min) &&
						 (room.height()>cfg.room_size.max  || room.width()>cfg.room_size.max ||
							std::bernoulli_distribution(std::min(std::max(cfg.split_prop_factor/depth, 0.1f), 1.f))(rng));

			if(split) {
				bool split_x = room.width() >= room.height();

				auto b = room.split(
					!split_x ? 0 : std::uniform_int_distribution<int>(1, room.width() -1)(rng),
					split_x  ? 0 : std::uniform_int_distribution<int>(1, room.height()-1)(rng)
				);

				return join(
					process_room(depth+1, room, split_dist, rng, cfg),
					process_room(depth+1, b, split_dist, rng, cfg)
				);

			} else {
				return {room};
			}
		}

		auto filter_rooms(Room_list rooms, std::mt19937& rng, const Dungeon_cfg& cfg) -> Room_list {
			rooms.erase(std::remove_if(rooms.begin(), rooms.end(), [&](auto& r){
				return r.height()<=cfg.room_size.min || r.width()<cfg.room_size.min;
			}), rooms.end());

			auto target_room_count = std::uniform_int_distribution<std::size_t>(cfg.rooms.min, cfg.rooms.max)(rng);

			while(rooms.size()>target_room_count) {
				auto i = std::uniform_int_distribution<std::size_t>(0, rooms.size())(rng);
				rooms[i] = rooms.back();
				rooms.pop_back();
			}

			return rooms;
		}

		template<class T, class Func>
		std::size_t find_min(std::vector<T>& c, Func weight_func) {
			assert(!c.empty());

			if(c.size()==1)
				return 0;

			std::size_t min = 0;
			auto weight = weight_func(c[0]);
			for(std::size_t i=1; i<c.size(); ++i) {
				auto nw = weight_func(c[i]);
				if(nw<weight) {
					min = i;
					weight = nw;
				}
			}

			return min;
		}
		template<class T>
		T fast_erase(std::vector<T>& c, std::size_t i) {
			T tmp = c[i];
			c[i] = c.back();
			c.pop_back();
			return tmp;
		}

		template<class T, class Func>
		T pop_min(std::vector<T>& c, Func weight_func) {
			return fast_erase(c, find_min(c, weight_func));
		}
		template<class T>
		T pop_random(std::vector<T>& c, std::mt19937& rng) {
			return fast_erase(c, std::uniform_int_distribution<std::size_t>(0, c.size()-1)(rng));
		}

		void connect_rooms(Room_list& rooms, std::mt19937& rng, const Dungeon_cfg& cfg) {
			std::vector<std::size_t> open_list(rooms.size());
			std::iota(open_list.begin(), open_list.end(), 0);

			auto last_room = pop_random(open_list, rng);
			rooms.at(last_room).type = Room_type::start;

			const auto closest_room_w = [&last_room, &rooms](std::size_t rIdx){
				auto dist_x = std::abs(rooms.at(rIdx).center().x-rooms.at(last_room).center().x);
				auto dist_y = std::abs(rooms.at(rIdx).center().y-rooms.at(last_room).center().y);

				if( std::abs(dist_x-dist_y)<10 ) // TODO: impl better heuristic
					return std::min(dist_x, dist_y);
				else
					return dist_x + dist_y;
			};

			while(!open_list.empty()) {
				auto closest = pop_min(open_list, closest_room_w);

				rooms.at(last_room).connections.push_back(closest);

				last_room = closest;
			}

			rooms.at(last_room).type = Room_type::end;
		}

		Level build_level(Room_list& rooms, int width, int height) {
			constexpr int border = 5;
			int min_x = std::numeric_limits<int>::max();
			int min_y = std::numeric_limits<int>::max();
			int max_x = std::numeric_limits<int>::min();
			int max_y = std::numeric_limits<int>::min();

			for(Room& r : rooms) {
				min_y = std::min(min_y, r.top);
				max_y = std::max(max_y, r.bottom);
				min_x = std::min(min_x, r.left);
				max_x = std::max(max_x, r.right);
			}

			int level_width  = max_x-min_x+border*2;
			int level_height = max_y-min_y+border*2;

			auto level_rooms = std::vector<Room>();
			level_rooms.reserve(rooms.size());
			int rid=0;
			for(auto& r : rooms) {
				level_rooms.emplace_back(
				            r.top - min_y +border,
				            r.left- min_x +border,
				            r.right - min_x +border,
				            r.bottom - min_y +border,
				            r.type,
				            rid++
				);
			}

			Level level(Tile_type::wall_dirt, level_width, level_height, level_rooms);

			for(auto& r : rooms) {
				for(int x=0; x<r.width(); ++x) {
					auto ex = border+x+r.left-min_x;

					level.get(ex, border+r.top-min_y).type = Tile_type::wall_tile;
					level.get(ex, border+r.top-min_y+r.height()-1).type = Tile_type::wall_tile;

					for(int y=1; y<r.height()-1; ++y) {
						if(x==0 || x==r.width()-1)
							level.get(ex, border+y +r.top-min_y).type = Tile_type::wall_tile;
						else
							level.get(ex, border+y +r.top-min_y).type = Tile_type::floor_tile;
					}
				}
				r.left-=min_x-border;
				r.top-=min_y-border;
				r.right-=min_x-border;
				r.bottom-=min_y-border;
			}

			return level;
		}

		void dig_path(Level& level, util::path&& path) {
			for(const auto& node : path) {
				auto& tile = level.get(node.x, node.y);

				if(tile.solid())
					tile.type = Tile_type::floor_tile; // TODO: use doors, etc. from template

				for(int y=std::max(node.y-1, 0); y<=std::min(node.y+1, level.height()-1); ++y)
					for(int x=std::max(node.x-1, 0); x<=std::min(node.x+1, level.width()-1); ++x) {
						auto& btile = level.get(x, y);
						if(btile.solid())
							btile.type = Tile_type::wall_tile;
					}
			}
		}

		void dig_corridors(Level& level, const Room_list& rooms) {
			using namespace util;

			auto path_scorer = [&](position pprev, position prev, position node, position goal) {
				auto costs = std::sqrt((node.x-goal.x)*(node.x-goal.x) + (node.y-goal.y)*(node.y-goal.y));

				if(pprev.x!=node.x && pprev.y!=node.y)
					costs+=5;

				if(level.get(node.x, node.y).solid())
					costs+=100;

				return costs;
			};

			auto path_finder = create_path_finder({level.width(), level.height()}, path_scorer);

			for(auto& room : rooms) {
				for(auto c : room.connections) {
					dig_path(level, path_finder.search(
							{room.center().x, room.center().y},
							{rooms[c].center().x, rooms[c].center().y} ));
				}
			}
		}

	}
}
}
<commit_msg>fixed stupid out-of-range access in level_generator.cpp<commit_after>#include "level_generator.hpp"

#include "room_template.hpp"

#include "../../core/utils/astar.hpp"
#include "../../core/utils/string_utils.hpp"

#include <sf2/sf2.hpp>
#include <sf2/FileParser.hpp>

#include <algorithm>
#include <random>
#include <glm/glm.hpp>

using namespace mo::util;

namespace {
	template<typename T>
	struct Range {
		T min;
		T max;
	};
	using IntRange = Range<int>;
	sf2_structDef(IntRange, sf2_member(min), sf2_member(max))

	struct Dungeon_cfg {
		IntRange room_size;
		IntRange rooms;
		int max_width, max_height;
		float split_prop_factor;
	};
	sf2_structDef(Dungeon_cfg,
		sf2_member(room_size),
		sf2_member(rooms),
		sf2_member(max_width),
		sf2_member(max_height),
		sf2_member(split_prop_factor)
	)

	struct Dungeon_cfg_map {
		std::unordered_map<int, Dungeon_cfg> levels;
	};
	sf2_structDef(Dungeon_cfg_map, sf2_member(levels))
}

namespace mo {
namespace asset {

	template<>
	struct Loader<Dungeon_cfg_map> {
		using T = Dungeon_cfg_map;
		static auto load(istream in) throw(Loading_failed) -> std::shared_ptr<T> {
			auto i = std::make_shared<T>();
			sf2::parseStream(in, *i);
			return i;
		}
		static void store(ostream out, T& asset) throw(Loading_failed);
	};

}

namespace level {
	namespace {
		Dungeon_cfg load_cfg(asset::Asset_manager& assets, int depth) {
			auto opts = assets.load<Dungeon_cfg_map>("cfg:dungeons"_aid);
			auto cfg_iter = opts->levels.find(depth);
			INVARIANT(cfg_iter!=opts->levels.end(), "You delved too greedily and too deep. Level="+to_string(depth));

			return cfg_iter->second;
		}

		struct Room_blueprint : public Room {
			std::vector<std::size_t> connections;
			asset::Ptr<Room_template> room_template;

			Room_blueprint(int top, int left, int right, int bottom)
				: Room(top, left, right, bottom) {}

			Room_blueprint split(int new_width, int new_height) {
				Room_blueprint r {
					top + new_height,
					left + new_width,
					right,
					bottom
				};

				if(new_width>0)
					right = left + new_width;

				if(new_height>0)
					bottom = top + new_height;

				return r;
			}
		};

		template<class T>
		std::vector<T> join(std::vector<T>&& a, std::vector<T>&& b) {
			a.reserve( a.size() + b.size() );
			std::move(b.begin(), b.end(), std::back_inserter(a));
			return a;
		}

		using Room_list = std::vector<Room_blueprint>;

		auto process_room(int depth, Room_blueprint room,
		                  std::bernoulli_distribution& split_dist,
		                  std::mt19937& rng, const Dungeon_cfg& cfg) -> Room_list;
		auto filter_rooms(Room_list rooms, std::mt19937& rng, const Dungeon_cfg& cfg) -> Room_list;
		void connect_rooms(Room_list& rooms, std::mt19937& rng, const Dungeon_cfg& cfg);
		auto build_level(Room_list& rooms, int width, int height) -> Level;
		void dig_corridors(Level& level, const Room_list& rooms);
	}

	Level generate_level(asset::Asset_manager& assets, uint64_t seed,
	                     int depth, int difficulty) {
		const auto cfg = load_cfg(assets, depth);

		std::mt19937 rng(seed+depth*7+difficulty*31);

		// 1. map zufällig an größter Achse trennen (rekursiv für die beiden neuen Zellen wiederholen)
		std::bernoulli_distribution split_dist(0.1);
		auto rooms = process_room(1, Room_blueprint{0,0, cfg.max_width, cfg.max_height}, split_dist, rng, cfg);

		// 2. zufällig Zellen verwerfen bis nur noch N übrig
		rooms = filter_rooms(rooms, rng, cfg);

		// 3. Graph/ Pfad aus den Zellen bauen (minimum-spanning tree)
		connect_rooms(rooms, rng, cfg);

		// 4. Rollenzuweisung anhand des Pfades

		// 5. Templates anhand der Rollen zuweisen

		// 6. Räume in Level konvertieren
		Level level = build_level(rooms, cfg.max_width, cfg.max_height);

		// 7. Tunnel für vorgesehene Pfade graben
		dig_corridors(level, rooms);

		// 8. Objekte erstellen

		return level;
	}

	namespace {

		auto process_room(int depth, Room_blueprint room, std::bernoulli_distribution& split_dist,
									  std::mt19937& rng, const Dungeon_cfg& cfg) -> Room_list {
			bool split = (room.height()>=cfg.room_size.min || room.width()>=cfg.room_size.min) &&
						 (room.height()>cfg.room_size.max  || room.width()>cfg.room_size.max ||
							std::bernoulli_distribution(std::min(std::max(cfg.split_prop_factor/depth, 0.1f), 1.f))(rng));

			if(split) {
				bool split_x = room.width() >= room.height();

				auto b = room.split(
					!split_x ? 0 : std::uniform_int_distribution<int>(1, room.width() -1)(rng),
					split_x  ? 0 : std::uniform_int_distribution<int>(1, room.height()-1)(rng)
				);

				return join(
					process_room(depth+1, room, split_dist, rng, cfg),
					process_room(depth+1, b, split_dist, rng, cfg)
				);

			} else {
				return {room};
			}
		}

		auto filter_rooms(Room_list rooms, std::mt19937& rng, const Dungeon_cfg& cfg) -> Room_list {
			rooms.erase(std::remove_if(rooms.begin(), rooms.end(), [&](auto& r){
				return r.height()<=cfg.room_size.min || r.width()<cfg.room_size.min;
			}), rooms.end());

			auto target_room_count = std::uniform_int_distribution<std::size_t>(cfg.rooms.min, cfg.rooms.max)(rng);

			while(rooms.size()>target_room_count) {
                auto i = std::uniform_int_distribution<std::size_t>(0, rooms.size()-1)(rng);
                if(i<rooms.size()-1)
                    rooms[i] = rooms.back();

				rooms.pop_back();
			}

			return rooms;
		}

		template<class T, class Func>
		std::size_t find_min(std::vector<T>& c, Func weight_func) {
			assert(!c.empty());

			if(c.size()==1)
				return 0;

			std::size_t min = 0;
			auto weight = weight_func(c[0]);
			for(std::size_t i=1; i<c.size(); ++i) {
				auto nw = weight_func(c[i]);
				if(nw<weight) {
					min = i;
					weight = nw;
				}
			}

			return min;
		}
		template<class T>
		T fast_erase(std::vector<T>& c, std::size_t i) {
			T tmp = c[i];
			c[i] = c.back();
			c.pop_back();
			return tmp;
		}

		template<class T, class Func>
		T pop_min(std::vector<T>& c, Func weight_func) {
			return fast_erase(c, find_min(c, weight_func));
		}
		template<class T>
		T pop_random(std::vector<T>& c, std::mt19937& rng) {
			return fast_erase(c, std::uniform_int_distribution<std::size_t>(0, c.size()-1)(rng));
		}

		void connect_rooms(Room_list& rooms, std::mt19937& rng, const Dungeon_cfg& cfg) {
			std::vector<std::size_t> open_list(rooms.size());
			std::iota(open_list.begin(), open_list.end(), 0);

			auto last_room = pop_random(open_list, rng);
			rooms.at(last_room).type = Room_type::start;

			const auto closest_room_w = [&last_room, &rooms](std::size_t rIdx){
				auto dist_x = std::abs(rooms.at(rIdx).center().x-rooms.at(last_room).center().x);
				auto dist_y = std::abs(rooms.at(rIdx).center().y-rooms.at(last_room).center().y);

				if( std::abs(dist_x-dist_y)<10 ) // TODO: impl better heuristic
					return std::min(dist_x, dist_y);
				else
					return dist_x + dist_y;
			};

			while(!open_list.empty()) {
				auto closest = pop_min(open_list, closest_room_w);

				rooms.at(last_room).connections.push_back(closest);

				last_room = closest;
			}

			rooms.at(last_room).type = Room_type::end;
		}

		Level build_level(Room_list& rooms, int width, int height) {
			constexpr int border = 5;
			int min_x = std::numeric_limits<int>::max();
			int min_y = std::numeric_limits<int>::max();
			int max_x = std::numeric_limits<int>::min();
			int max_y = std::numeric_limits<int>::min();

			for(Room& r : rooms) {
				min_y = std::min(min_y, r.top);
				max_y = std::max(max_y, r.bottom);
				min_x = std::min(min_x, r.left);
				max_x = std::max(max_x, r.right);
			}

			int level_width  = max_x-min_x+border*2;
			int level_height = max_y-min_y+border*2;

			auto level_rooms = std::vector<Room>();
			level_rooms.reserve(rooms.size());
			int rid=0;
			for(auto& r : rooms) {
				level_rooms.emplace_back(
				            r.top - min_y +border,
				            r.left- min_x +border,
				            r.right - min_x +border,
				            r.bottom - min_y +border,
				            r.type,
				            rid++
				);
			}

			Level level(Tile_type::wall_dirt, level_width, level_height, level_rooms);

			for(auto& r : rooms) {
				for(int x=0; x<r.width(); ++x) {
					auto ex = border+x+r.left-min_x;

					level.get(ex, border+r.top-min_y).type = Tile_type::wall_tile;
					level.get(ex, border+r.top-min_y+r.height()-1).type = Tile_type::wall_tile;

					for(int y=1; y<r.height()-1; ++y) {
						if(x==0 || x==r.width()-1)
							level.get(ex, border+y +r.top-min_y).type = Tile_type::wall_tile;
						else
							level.get(ex, border+y +r.top-min_y).type = Tile_type::floor_tile;
					}
				}
				r.left-=min_x-border;
				r.top-=min_y-border;
				r.right-=min_x-border;
				r.bottom-=min_y-border;
			}

			return level;
		}

		void dig_path(Level& level, util::path&& path) {
			for(const auto& node : path) {
				auto& tile = level.get(node.x, node.y);

				if(tile.solid())
					tile.type = Tile_type::floor_tile; // TODO: use doors, etc. from template

				for(int y=std::max(node.y-1, 0); y<=std::min(node.y+1, level.height()-1); ++y)
					for(int x=std::max(node.x-1, 0); x<=std::min(node.x+1, level.width()-1); ++x) {
						auto& btile = level.get(x, y);
						if(btile.solid())
							btile.type = Tile_type::wall_tile;
					}
			}
		}

		void dig_corridors(Level& level, const Room_list& rooms) {
			using namespace util;

			auto path_scorer = [&](position pprev, position prev, position node, position goal) {
				auto costs = std::sqrt((node.x-goal.x)*(node.x-goal.x) + (node.y-goal.y)*(node.y-goal.y));

				if(pprev.x!=node.x && pprev.y!=node.y)
					costs+=5;

				if(level.get(node.x, node.y).solid())
					costs+=100;

				return costs;
			};

			auto path_finder = create_path_finder({level.width(), level.height()}, path_scorer);

			for(auto& room : rooms) {
				for(auto c : room.connections) {
					dig_path(level, path_finder.search(
							{room.center().x, room.center().y},
							{rooms[c].center().x, rooms[c].center().y} ));
				}
			}
		}

	}
}
}
<|endoftext|>


<commit_before><commit_msg>fix MC sorting<commit_after><|endoftext|>


<commit_before>#include "stdafx.h"

#include "SendIpUpdate.h"

#include "MiscUtil.h"
#include "Http.h"
#include "JsonParser.h"
#include "Prefs.h"
#include "StrUtil.h"

char* SendIpUpdate()
{
	assert(CanSendIPUpdates());
	if (!CanSendIPUpdates())
		return NULL;

	char *res = NULL;

	// host = updates.opendns.com or website.dev6.sfo.opendns.com
	// url: /nic/update?token=mytoken&api_key=mykey?hostname=
	// responses:
	//  "badauth"
	//  "nohost"
	//  "good ${ip-addr}"
	if (!g_pref_token)
		return NULL;
	assert(g_pref_hostname);

	const char *urlTxt = GetIpUpdateUrl(TRUE);
	const char *host = GetIpUpdateHost();

	HttpResult *httpResult = HttpGet(host, urlTxt, true);
	free((void*)urlTxt);
	if (httpResult && httpResult->IsValid()) {
		res = (char*)httpResult->data.getData(NULL);
	}
	delete httpResult;
	return res;
}

char *SendDnsOmaticUpdate()
{
	assert(CanSendIPUpdates());
	if (!CanSendIPUpdates())
		return NULL;

	char *res = NULL;

	// TODO: do I need to append the following in url from GetIpUpdateUrl()?
	/*URL$ = SetURLPart(URL$, "myip", ip$)
	URL$ = SetURLPart(URL$, "wildcard", "NOCHG")
	URL$ = SetURLPart(URL$, "mx", "NOCHG")
	URL$ = SetURLPart(URL$, "backmx", "NOCHG")*/

	const char *urlTxt = GetIpUpdateUrl(TRUE);
	const char *host = GetIpUpdateDnsOMaticHost();

	HttpResult *httpResult = HttpGet(host, urlTxt, true);
	free((void*)urlTxt);
	if (httpResult && httpResult->IsValid()) {
		res = (char*)httpResult->data.getData(NULL);
	}
	delete httpResult;
	return res;
}

IpUpdateResult IpUpdateResultFromString(const char *s)
{
	if (StrStartsWithI(s, "The service is not available"))
		return IpUpdateNotAvailable;
	if (StrStartsWithI(s, "good"))
		return IpUpdateOk;
	if (StrStartsWithI(s, "nochg"))
		return IpUpdateOk;
	if (StrStartsWithI(s, "!yours"))
		return IpUpdateNotYours;
	if (StrStartsWithI(s, "badauth"))
		return IpUpdateBadAuth;
	if (StrStartsWithI(s, "nohost"))
		return IpUpdateNoHost;

	// not sure if those really happen, they're supported by 1.3 client
	if (StrStartsWithI(s, "dnserr"))
		return IpUpdateDnsErr;

	if (StrStartsWithI(s, "911"))
		return IpUpdateDnsErr;

	if (StrStartsWithI(s, "abuse"))
		return IpUpdateMiscErr;

	if (StrStartsWithI(s, "notfqdn"))
		return IpUpdateMiscErr;

	if (StrStartsWithI(s, "numhost"))
		return IpUpdateMiscErr;

	if (StrStartsWithI(s, "badagent"))
		return IpUpdateMiscErr;

	if (StrStartsWithI(s, "!donator"))
		return IpUpdateMiscErr;

	assert(0);
	return IpUpdateOk;
}

#if 0
// another way is to use username/password and http basic auth
char* SendIpUpdate()
{
	// host = "updates.opendns.com"
	// url = "/nic/update?hostname=" + network
	// responses:
	//  "badauth"
	//  "nohost"
	//  "good ${ip-addr}"
	const char *userName = "";
	const char *pwd = "";
	HttpResult *httpResult = HttpGetWithBasicAuth("updates.opendns.com", "/nic/update", userName, pwd, true);
	if (httpResult && httpResult->IsValid()) {
		DWORD dataLen;
		char *data = (char*)httpResult->data.getData(&dataLen);
		free(data);
	}
	delete httpResult;
}
#endif

TCHAR *DownloadUpdateIfNotDownloaded(const char *url)
{
	const TCHAR *filePathStr = NULL;
	const char *fileName = StrFindLastChar(url, '/');
	if (!fileName)
		return NULL;
	++fileName;
	CString filePath = AppDataDir();
	filePath += PATH_SEP_STR;
	filePath += fileName;

	filePathStr = filePath;
	if (FileOrDirExists(filePathStr))
		return tstrdup(filePathStr);

	HttpResult *httpResult = HttpGet(url);
	if (!httpResult || !httpResult->IsValid())
		goto Error;

	DWORD size;
	void *s = httpResult->data.getData(&size);
	if (!s)
		goto Error;

	BOOL ok = FileWriteAll(filePathStr, (const char*)s, size);
	if (!ok)
		goto Error;

	return tstrdup(filePathStr);
Error:
	free((void*)filePathStr);
	return NULL;
}

// sends auto-update check. Returns url of the new version to download
// if an update is available or NULL if update is not available
// (or there was an error getting the upgrade info)
// Caller needs to free() the result.
// TODO: we ignore (and don't propagate) 'force' field in json response
char *GetUpdateUrl(const TCHAR *version, VersionUpdateCheckType type)
{
	char *downloadUrl = NULL;
	JsonEl *json = NULL;

	char *typeStr = "c";
	if (UpdateCheckInstall == type)
		typeStr = "i";
	else if (UpdateCheckUninstall == type)
		typeStr = "u";
	else if (UpdateCheckVersionCheck == type)
		typeStr = "c";
	else
		assert(0);

	CString url = AutoUpdateUrl(version, typeStr);
	HttpResult *res = HttpGet(AUTO_UPDATE_HOST, url, false /* https */);
	if (!res || !res->IsValid())
		return NULL;
	char *s = (char *)res->data.getData(NULL);
	json = ParseJsonToDoc(s);
	JsonEl *upgradeAvailable = GetMapElByName(json, "upgrade");
	JsonElBool *upgradeAvailableBool = JsonElAsBool(upgradeAvailable);
	if (!upgradeAvailableBool || !upgradeAvailableBool->boolVal)
		goto Exit;
	JsonEl *updateUrl = GetMapElByName(json, "download");
	if (!updateUrl)
		goto Exit;
	downloadUrl = StrDupSafe(JsonElAsStringVal(updateUrl));
Exit:
	JsonElFree(json);
	free(s);
	return downloadUrl;
}
<commit_msg>update HttpGet() callers to pass port instead of https flag<commit_after>#include "stdafx.h"

#include "SendIpUpdate.h"

#include "MiscUtil.h"
#include "Http.h"
#include "JsonParser.h"
#include "Prefs.h"
#include "StrUtil.h"

char* SendIpUpdate()
{
	assert(CanSendIPUpdates());
	if (!CanSendIPUpdates())
		return NULL;

	char *res = NULL;

	// host = updates.opendns.com or website.dev6.sfo.opendns.com
	// url: /nic/update?token=mytoken&api_key=mykey?hostname=
	// responses:
	//  "badauth"
	//  "nohost"
	//  "good ${ip-addr}"
	if (!g_pref_token)
		return NULL;
	assert(g_pref_hostname);

	const char *urlTxt = GetIpUpdateUrl(TRUE);
	const char *host = GetIpUpdateHost();

	HttpResult *httpResult = HttpGet(host, urlTxt, INTERNET_DEFAULT_HTTPS_PORT);
	free((void*)urlTxt);
	if (httpResult && httpResult->IsValid()) {
		res = (char*)httpResult->data.getData(NULL);
	}
	delete httpResult;
	return res;
}

char *SendDnsOmaticUpdate()
{
	assert(CanSendIPUpdates());
	if (!CanSendIPUpdates())
		return NULL;

	char *res = NULL;

	// TODO: do I need to append the following in url from GetIpUpdateUrl()?
	/*URL$ = SetURLPart(URL$, "myip", ip$)
	URL$ = SetURLPart(URL$, "wildcard", "NOCHG")
	URL$ = SetURLPart(URL$, "mx", "NOCHG")
	URL$ = SetURLPart(URL$, "backmx", "NOCHG")*/

	const char *urlTxt = GetIpUpdateUrl(TRUE);
	const char *host = GetIpUpdateDnsOMaticHost();

	HttpResult *httpResult = HttpGet(host, urlTxt, INTERNET_DEFAULT_HTTPS_PORT);
	free((void*)urlTxt);
	if (httpResult && httpResult->IsValid()) {
		res = (char*)httpResult->data.getData(NULL);
	}
	delete httpResult;
	return res;
}

IpUpdateResult IpUpdateResultFromString(const char *s)
{
	if (StrStartsWithI(s, "The service is not available"))
		return IpUpdateNotAvailable;
	if (StrStartsWithI(s, "good"))
		return IpUpdateOk;
	if (StrStartsWithI(s, "nochg"))
		return IpUpdateOk;
	if (StrStartsWithI(s, "!yours"))
		return IpUpdateNotYours;
	if (StrStartsWithI(s, "badauth"))
		return IpUpdateBadAuth;
	if (StrStartsWithI(s, "nohost"))
		return IpUpdateNoHost;

	// not sure if those really happen, they're supported by 1.3 client
	if (StrStartsWithI(s, "dnserr"))
		return IpUpdateDnsErr;

	if (StrStartsWithI(s, "911"))
		return IpUpdateDnsErr;

	if (StrStartsWithI(s, "abuse"))
		return IpUpdateMiscErr;

	if (StrStartsWithI(s, "notfqdn"))
		return IpUpdateMiscErr;

	if (StrStartsWithI(s, "numhost"))
		return IpUpdateMiscErr;

	if (StrStartsWithI(s, "badagent"))
		return IpUpdateMiscErr;

	if (StrStartsWithI(s, "!donator"))
		return IpUpdateMiscErr;

	assert(0);
	return IpUpdateOk;
}

#if 0
// another way is to use username/password and http basic auth
char* SendIpUpdate()
{
	// host = "updates.opendns.com"
	// url = "/nic/update?hostname=" + network
	// responses:
	//  "badauth"
	//  "nohost"
	//  "good ${ip-addr}"
	const char *userName = "";
	const char *pwd = "";
	HttpResult *httpResult = HttpGetWithBasicAuth("updates.opendns.com", "/nic/update", userName, pwd, true);
	if (httpResult && httpResult->IsValid()) {
		DWORD dataLen;
		char *data = (char*)httpResult->data.getData(&dataLen);
		free(data);
	}
	delete httpResult;
}
#endif

TCHAR *DownloadUpdateIfNotDownloaded(const char *url)
{
	const TCHAR *filePathStr = NULL;
	const char *fileName = StrFindLastChar(url, '/');
	if (!fileName)
		return NULL;
	++fileName;
	CString filePath = AppDataDir();
	filePath += PATH_SEP_STR;
	filePath += fileName;

	filePathStr = filePath;
	if (FileOrDirExists(filePathStr))
		return tstrdup(filePathStr);

	HttpResult *httpResult = HttpGet(url);
	if (!httpResult || !httpResult->IsValid())
		goto Error;

	DWORD size;
	void *s = httpResult->data.getData(&size);
	if (!s)
		goto Error;

	BOOL ok = FileWriteAll(filePathStr, (const char*)s, size);
	if (!ok)
		goto Error;

	return tstrdup(filePathStr);
Error:
	free((void*)filePathStr);
	return NULL;
}

// sends auto-update check. Returns url of the new version to download
// if an update is available or NULL if update is not available
// (or there was an error getting the upgrade info)
// Caller needs to free() the result.
// TODO: we ignore (and don't propagate) 'force' field in json response
char *GetUpdateUrl(const TCHAR *version, VersionUpdateCheckType type)
{
	char *downloadUrl = NULL;
	JsonEl *json = NULL;

	char *typeStr = "c";
	if (UpdateCheckInstall == type)
		typeStr = "i";
	else if (UpdateCheckUninstall == type)
		typeStr = "u";
	else if (UpdateCheckVersionCheck == type)
		typeStr = "c";
	else
		assert(0);

	CString url = AutoUpdateUrl(version, typeStr);
	HttpResult *res = HttpGet(AUTO_UPDATE_HOST, url);
	if (!res || !res->IsValid())
		return NULL;
	char *s = (char *)res->data.getData(NULL);
	json = ParseJsonToDoc(s);
	JsonEl *upgradeAvailable = GetMapElByName(json, "upgrade");
	JsonElBool *upgradeAvailableBool = JsonElAsBool(upgradeAvailable);
	if (!upgradeAvailableBool || !upgradeAvailableBool->boolVal)
		goto Exit;
	JsonEl *updateUrl = GetMapElByName(json, "download");
	if (!updateUrl)
		goto Exit;
	downloadUrl = StrDupSafe(JsonElAsStringVal(updateUrl));
Exit:
	JsonElFree(json);
	free(s);
	return downloadUrl;
}
<|endoftext|>


<commit_before>/*****************************************************************************
* MediaCX.hpp: Media API
*****************************************************************************
* Copyright  2014 the VideoLAN team
*
* Authors: Hugo Beauze-Luyssen <hugo@beauzee.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/

#pragma once

#include "structuresCX.hpp"
#include <collection.h>
#include <vlcpp/vlc.hpp>

namespace libVLCX
{
    ref class MediaEventManager;
    ref class Instance;

    public enum class MediaState
    {
        NothingSpecial = 0,
        Opening,
        Buffering,
        Playing,
        Paused,
        Stopped,
        Ended,
        Error
    };

    public enum class MediaMeta
    {
        Title,
        Artist,
        Genre,
        Copyright,
        Album,
        TrackNumber,
        Description,
        Rating,
        Date,
        Setting,
        URL,
        Language,
        NowPlaying,
        Publisher,
        EncodedBy,
        ArtworkURL,
        TrackID,
        TrackTotal,
        Director,
        Season,
        Episode,
        ShowName,
        Actors
    };

    public enum class FromType
    {
        FromPath,
        FromLocation,
        AsNode,
    };

    public ref class Media sealed
    {
    public:
        Media(Instance^ instance, Platform::String^ location, FromType from_type);

        /**
        * Add an option to the media.
        *
        * This option will be used to determine how the media_player will read
        * the media. This allows to use VLC's advanced reading/streaming options
        * on a per-media basis.
        *
        * \note The options are listed in 'vlc long-help' from the command line,
        * e.g. "-sout-all". Keep in mind that available options and their
        * semantics vary across LibVLC versions and builds.
        *
        * \warning Not all options affects libvlc_media_t objects: Specifically,
        * due to architectural issues most audio and video options, such as text
        * renderer options, have no effects on an individual media. These
        * options must be set through Instance::Instance() instead.
        *
        * \param psz_options  the options (as a string)
        */
        void addOption(Platform::String^ psz_options);

        /**
        * Add an option to the media with configurable flags.
        *
        * This option will be used to determine how the media_player will read
        * the media. This allows to use VLC's advanced reading/streaming options
        * on a per-media basis.
        *
        * The options are detailed in vlc long-help, for instance "--sout-all".
        * Note that all options are not usable on medias: specifically, due to
        * architectural issues, video-related options such as text renderer
        * options cannot be set on a single media. They must be set on the whole
        * libvlc instance instead.
        *
        * \param psz_options  the options (as a string)
        *
        * \param i_flags  the flags for this option
        */
        void addOptionFlag(Platform::String^ psz_options, unsigned i_flags);

        /**
        * Get the media resource locator (mrl) from a media descriptor object
        *
        * \return string with mrl of media descriptor object
        */
        Platform::String^ mrl();

        /**
        * Duplicate a media descriptor object.
        */
        Media^ duplicate();

        /**
        * Read the meta of the media.
        *
        * If the media has not yet been parsed this will return NULL.
        *
        * This methods automatically calls Media::parseAsync() , so after
        * calling it you may receive a libvlc_MediaMetaChanged event. If you
        * prefer a synchronous version ensure that you call Media::parse()
        * before get_meta().
        *
        * \see Media::parse()
        *
        * \see Media::parseAsync()
        *
        * \see libvlc_MediaMetaChanged
        *
        * \param e_meta  the meta to read
        *
        * \return the media's meta
        */
        Platform::String^ meta(MediaMeta e_meta);

        /**
        * Set the meta of the media (this function will not save the meta, call
        * libvlc_media_save_meta in order to save the meta)
        *
        * \param e_meta  the meta to write
        *
        * \param psz_value  the media's meta
        */
        void setMeta(MediaMeta e_meta, Platform::String^ psz_value);

        /**
        * Save the meta previously set
        *
        * \return true if the write operation was successful
        */
        int saveMeta();

        /**
        * Get current state of media descriptor object. Possible media states
        * are defined in libvlc_structures.c ( libvlc_NothingSpecial=0,
        * libvlc_Opening, libvlc_Buffering, libvlc_Playing, libvlc_Paused,
        * libvlc_Stopped, libvlc_Ended, libvlc_Error).
        *
        * \see libvlc_state_t
        *
        * \return state of media descriptor object
        */
        MediaState state();

        /**
        * Get the current statistics about the media
        *
        * \param p_stats  structure that contain the statistics about the media
        * (this structure must be allocated by the caller)
        *
        * \return true if the statistics are available, false otherwise
        */
        //bool stats(libvlc_media_stats_t * p_stats);

        /**
        * Get event manager from media descriptor object. NOTE: this function
        * doesn't increment reference counting.
        *
        * \return event manager object
        */
        MediaEventManager^ eventManager();

        /**
        * Get duration (in ms) of media descriptor object item.
        *
        * \return duration of media item or -1 on error
        */
        libvlc_time_t duration();

        /**
        * Parse a media.
        *
        * This fetches (local) meta data and tracks information. The method is
        * synchronous.
        *
        * \see Media::parseAsync()
        *
        * \see Media::meta()
        *
        * \see Media::tracksInfo()
        */
        void parse();

        /**
        * Parse a media.
        *
        * This fetches (local) meta data and tracks information. The method is
        * the asynchronous of Media::parse() .
        *
        * To track when this is over you can listen to libvlc_MediaParsedChanged
        * event. However if the media was already parsed you will not receive
        * this event.
        *
        * \see Media::parse()
        *
        * \see libvlc_MediaParsedChanged
        *
        * \see Media::meta()
        *
        * \see Media::tracks()
        */
        void parseAsync();

        /**
        * Get Parsed status for media descriptor object.
        *
        * \see libvlc_MediaParsedChanged
        *
        * \return true if media object has been parsed otherwise it returns
        * false
        */
        bool isParsed();

        /**
        * Get media descriptor's elementary streams description
        *
        * Note, you need to call Media::parse() or play the media at least once
        * before calling this function. Not doing this will result in an empty
        * array.
        *
        * \version LibVLC 2.1.0 and later.
        *
        * \return a vector containing all tracks
        */
        Windows::Foundation::Collections::IVector<MediaTrack^>^ tracks();

    private:
        ~Media(){}

    internal:
        Media(const VLC::Media& media);
        Media(VLC::Media&& media);
        VLC::Media m_media;

    private:
        MediaEventManager^ m_eventManager;
    };

} // namespace libVLCX

<commit_msg>fix compilation of latest WinRT<commit_after>/*****************************************************************************
* MediaCX.hpp: Media API
*****************************************************************************
* Copyright  2014 the VideoLAN team
*
* Authors: Hugo Beauze-Luyssen <hugo@beauzee.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/

#pragma once

#include "structuresCX.hpp"
#include <collection.h>
#include <vlcpp/vlc.hpp>

namespace libVLCX
{
    ref class MediaEventManager;
    ref class Instance;

    public enum class MediaState
    {
        NothingSpecial = 0,
        Opening,
        Buffering,
        Playing,
        Paused,
        Stopped,
        Ended,
        Error
    };

    public enum class MediaMeta
    {
        Title,
        Artist,
        Genre,
        Copyright,
        Album,
        TrackNumber,
        Description,
        Rating,
        Date,
        Setting,
        URL,
        Language,
        NowPlaying,
        Publisher,
        EncodedBy,
        ArtworkURL,
        TrackID,
        TrackTotal,
        Director,
        Season,
        Episode,
        ShowName,
        Actors,
        AlbumArtist,
        DiscNumber
    };

    public enum class FromType
    {
        FromPath,
        FromLocation,
        AsNode,
    };

    public ref class Media sealed
    {
    public:
        Media(Instance^ instance, Platform::String^ location, FromType from_type);

        /**
        * Add an option to the media.
        *
        * This option will be used to determine how the media_player will read
        * the media. This allows to use VLC's advanced reading/streaming options
        * on a per-media basis.
        *
        * \note The options are listed in 'vlc long-help' from the command line,
        * e.g. "-sout-all". Keep in mind that available options and their
        * semantics vary across LibVLC versions and builds.
        *
        * \warning Not all options affects libvlc_media_t objects: Specifically,
        * due to architectural issues most audio and video options, such as text
        * renderer options, have no effects on an individual media. These
        * options must be set through Instance::Instance() instead.
        *
        * \param psz_options  the options (as a string)
        */
        void addOption(Platform::String^ psz_options);

        /**
        * Add an option to the media with configurable flags.
        *
        * This option will be used to determine how the media_player will read
        * the media. This allows to use VLC's advanced reading/streaming options
        * on a per-media basis.
        *
        * The options are detailed in vlc long-help, for instance "--sout-all".
        * Note that all options are not usable on medias: specifically, due to
        * architectural issues, video-related options such as text renderer
        * options cannot be set on a single media. They must be set on the whole
        * libvlc instance instead.
        *
        * \param psz_options  the options (as a string)
        *
        * \param i_flags  the flags for this option
        */
        void addOptionFlag(Platform::String^ psz_options, unsigned i_flags);

        /**
        * Get the media resource locator (mrl) from a media descriptor object
        *
        * \return string with mrl of media descriptor object
        */
        Platform::String^ mrl();

        /**
        * Duplicate a media descriptor object.
        */
        Media^ duplicate();

        /**
        * Read the meta of the media.
        *
        * If the media has not yet been parsed this will return NULL.
        *
        * This methods automatically calls Media::parseAsync() , so after
        * calling it you may receive a libvlc_MediaMetaChanged event. If you
        * prefer a synchronous version ensure that you call Media::parse()
        * before get_meta().
        *
        * \see Media::parse()
        *
        * \see Media::parseAsync()
        *
        * \see libvlc_MediaMetaChanged
        *
        * \param e_meta  the meta to read
        *
        * \return the media's meta
        */
        Platform::String^ meta(MediaMeta e_meta);

        /**
        * Set the meta of the media (this function will not save the meta, call
        * libvlc_media_save_meta in order to save the meta)
        *
        * \param e_meta  the meta to write
        *
        * \param psz_value  the media's meta
        */
        void setMeta(MediaMeta e_meta, Platform::String^ psz_value);

        /**
        * Save the meta previously set
        *
        * \return true if the write operation was successful
        */
        int saveMeta();

        /**
        * Get current state of media descriptor object. Possible media states
        * are defined in libvlc_structures.c ( libvlc_NothingSpecial=0,
        * libvlc_Opening, libvlc_Buffering, libvlc_Playing, libvlc_Paused,
        * libvlc_Stopped, libvlc_Ended, libvlc_Error).
        *
        * \see libvlc_state_t
        *
        * \return state of media descriptor object
        */
        MediaState state();

        /**
        * Get the current statistics about the media
        *
        * \param p_stats  structure that contain the statistics about the media
        * (this structure must be allocated by the caller)
        *
        * \return true if the statistics are available, false otherwise
        */
        //bool stats(libvlc_media_stats_t * p_stats);

        /**
        * Get event manager from media descriptor object. NOTE: this function
        * doesn't increment reference counting.
        *
        * \return event manager object
        */
        MediaEventManager^ eventManager();

        /**
        * Get duration (in ms) of media descriptor object item.
        *
        * \return duration of media item or -1 on error
        */
        libvlc_time_t duration();

        /**
        * Parse a media.
        *
        * This fetches (local) meta data and tracks information. The method is
        * synchronous.
        *
        * \see Media::parseAsync()
        *
        * \see Media::meta()
        *
        * \see Media::tracksInfo()
        */
        void parse();

        /**
        * Parse a media.
        *
        * This fetches (local) meta data and tracks information. The method is
        * the asynchronous of Media::parse() .
        *
        * To track when this is over you can listen to libvlc_MediaParsedChanged
        * event. However if the media was already parsed you will not receive
        * this event.
        *
        * \see Media::parse()
        *
        * \see libvlc_MediaParsedChanged
        *
        * \see Media::meta()
        *
        * \see Media::tracks()
        */
        void parseAsync();

        /**
        * Get Parsed status for media descriptor object.
        *
        * \see libvlc_MediaParsedChanged
        *
        * \return true if media object has been parsed otherwise it returns
        * false
        */
        bool isParsed();

        /**
        * Get media descriptor's elementary streams description
        *
        * Note, you need to call Media::parse() or play the media at least once
        * before calling this function. Not doing this will result in an empty
        * array.
        *
        * \version LibVLC 2.1.0 and later.
        *
        * \return a vector containing all tracks
        */
        Windows::Foundation::Collections::IVector<MediaTrack^>^ tracks();

    private:
        ~Media(){}

    internal:
        Media(const VLC::Media& media);
        Media(VLC::Media&& media);
        VLC::Media m_media;

    private:
        MediaEventManager^ m_eventManager;
    };

} // namespace libVLCX

<|endoftext|>


<commit_before>#include "TutorialSettings.h"
#include "../Exceptions/JsonContentException.h"

void TutorialSettings::init(std::string configFilename, std::string saveFilename)
{
	Settings::init(configFilename);
	this->saveFilename = saveFilename;
	tryReadingTutoSaveFile();
	save();
}

void TutorialSettings::save()
{
	Json::StyledWriter writer;
	std::string outputSave = writer.write(tutorialStates);
	std::string path = fileUtils->getWritablePath() + saveFilename;

	bool succeed = fileUtils->writeStringToFile(outputSave, path);
	if (succeed) {
		cocos2d::log("Saved File in %s", path.c_str());
	}
	else {
		cocos2d::log("error saving file %s", path.c_str());
	}
}

void TutorialSettings::startTutorial(std::string name) {
	tutorialStates[name]["state"] = "running";
	save();
}

void TutorialSettings::completeTutorial(std::string name) {
	tutorialStates[name]["state"] = "complete";
	save();
}

bool TutorialSettings::isTutorialRunning(std::string name)
{
	return tutorialStates[name]["state"].asString() == "running";
}

bool TutorialSettings::isTutorialComplete(std::string name)
{
	return tutorialStates[name]["state"].asString() == "complete";
}

void TutorialSettings::tryReadingTutoSaveFile()
{
	bool parsingSaveSuccessful = reader->parse(fileUtils->getStringFromFile(saveFilename), tutorialStates, false);
	if (!parsingSaveSuccessful) {
		createNewTutorialSave();
	}
	else {
		resetTutorialsState();
	}
}

void TutorialSettings::resetTutorialsState()
{
	auto tutos = tutorialStates.getMemberNames();
	for (unsigned int j(0); j < tutorialStates.getMemberNames().size(); ++j) {
		if (tutorialStates[tutos[j]]["state"].asString() == "running") {
			tutorialStates[tutos[j]]["state"] = "uncompleted";
		}
	}
}

void TutorialSettings::createNewTutorialSave()
{
	std::vector<std::string> tuto_names = settingsMap.getMemberNames();
	for (unsigned int i(0); i < tuto_names.size(); ++i) {
		tutorialStates[tuto_names[i]]["state"] = settingsMap[tuto_names[i]]["state"];
	}
}<commit_msg>debug tutorialSettings that was never read correctly<commit_after>#include "TutorialSettings.h"
#include "../Exceptions/JsonContentException.h"

void TutorialSettings::init(std::string configFilename, std::string saveFilename)
{
	Settings::init(configFilename);
	this->saveFilename = saveFilename;
	tryReadingTutoSaveFile();
	save();
}

void TutorialSettings::save()
{
	Json::StyledWriter writer;
	std::string outputSave = writer.write(tutorialStates);
	std::string path = fileUtils->getWritablePath() + saveFilename;

	bool succeed = fileUtils->writeStringToFile(outputSave, path);
	if (succeed) {
		cocos2d::log("Saved File in %s", path.c_str());
	}
	else {
		cocos2d::log("error saving file %s", path.c_str());
	}
}

void TutorialSettings::startTutorial(std::string name) {
	tutorialStates[name]["state"] = "running";
	save();
}

void TutorialSettings::completeTutorial(std::string name) {
	tutorialStates[name]["state"] = "complete";
	save();
}

bool TutorialSettings::isTutorialRunning(std::string name)
{
	return tutorialStates[name]["state"].asString() == "running";
}

bool TutorialSettings::isTutorialComplete(std::string name)
{
	return tutorialStates[name]["state"].asString() == "complete";
}

void TutorialSettings::tryReadingTutoSaveFile()
{
	bool parsingSaveSuccessful = reader->parse(fileUtils->getStringFromFile(cocos2d::FileUtils::getInstance()->getWritablePath() + saveFilename), tutorialStates, false);
	if (!parsingSaveSuccessful) {
		createNewTutorialSave();
	}
	else {
		resetTutorialsState();
	}
}

void TutorialSettings::resetTutorialsState()
{
	auto tutos = tutorialStates.getMemberNames();
	for (unsigned int j(0); j < tutorialStates.getMemberNames().size(); ++j) {
		if (tutorialStates[tutos[j]]["state"].asString() == "running") {
			tutorialStates[tutos[j]]["state"] = "uncompleted";
		}
	}
}

void TutorialSettings::createNewTutorialSave()
{
	std::vector<std::string> tuto_names = settingsMap.getMemberNames();
	for (unsigned int i(0); i < tuto_names.size(); ++i) {
		tutorialStates[tuto_names[i]]["state"] = settingsMap[tuto_names[i]]["state"];
	}
}<|endoftext|>


<commit_before>/*****************************************************************************
 * Licensed to Qualys, Inc. (QUALYS) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * QUALYS licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ****************************************************************************/

/**
 * @file
 * @brief IronBee --- Core tests that don't fit elsewhere.
 *
 */

#include <gtest/gtest.h>
#include "base_fixture.h"

#include "core_private.h"

class CoreTest : public BaseTransactionFixture {
};

TEST_F(CoreTest, BlockingMode) {
    ib_core_cfg_t *corecfg;
    ib_module_t   *module;

    std::string config =
        std::string(
            "LogLevel INFO\n"
            "SensorId B9C1B52B-C24A-4309-B9F9-0EF4CD577A3E\n"
            "SensorName UnitTesting\n"
            "SensorHostname unit-testing.sensor.tld\n"
            "BlockingMethod status=200\n"
            "<Site test-site>\n"
            "   SiteId AAAABBBB-1111-2222-3333-000000000000\n"
            "   Hostname UnitTest\n"
            "</Site>\n"
        );

    configureIronBeeByString(config.c_str());

    ASSERT_EQ(IB_OK, ib_engine_module_get(ib_engine, "core", &module));

    ASSERT_EQ(
        IB_OK,
        ib_context_module_config(ib_context_main(ib_engine), module, &corecfg));

    ASSERT_EQ(200, corecfg->block_status);
    ASSERT_EQ(IB_BLOCK_METHOD_STATUS, corecfg->block_method);
}

TEST_F(CoreTest, BlockingMode2) {
    ib_core_cfg_t *corecfg;
    ib_module_t   *module;

    std::string config =
        std::string(
            "LogLevel INFO\n"
            "SensorId B9C1B52B-C24A-4309-B9F9-0EF4CD577A3E\n"
            "SensorName UnitTesting\n"
            "SensorHostname unit-testing.sensor.tld\n"
            "<Site test-site>\n"
            "   BlockingMethod status=403\n"
            "   SiteId AAAABBBB-1111-2222-3333-000000000000\n"
            "   Hostname UnitTest\n"
            "</Site>\n"
        );

    configureIronBeeByString(config.c_str());

    ASSERT_EQ(IB_OK, ib_engine_module_get(ib_engine, "core", &module));

    ASSERT_EQ(
        IB_OK,
        ib_context_module_config(ib_context_main(ib_engine), module, &corecfg));

    ASSERT_EQ(403, corecfg->block_status);
    ASSERT_EQ(IB_BLOCK_METHOD_STATUS, corecfg->block_method);
}

TEST_F(CoreTest, TfnFirst) {
    std::string config =
        std::string(
            "LogLevel INFO\n"
            "SensorId B9C1B52B-C24A-4309-B9F9-0EF4CD577A3E\n"
            "SensorName UnitTesting\n"
            "SensorHostname unit-testing.sensor.tld\n"
            "LoadModule ibmod_rules.so\n"
            "Action id:1 rev:1 phase:REQUEST_HEADER "
            "    setvar:list:element1=1\n"
            "Action id:2 rev:1 phase:REQUEST_HEADER "
            "    setvar:list:element2=2\n"
            "Rule list.first() @eq 1 id:3 rev:1 phase:REQUEST_HEADER "
            "    setvar:results:result1=1\n"
            "Rule list.last() @eq 2 id:4 rev:1 phase:REQUEST_HEADER "
            "    setvar:results:result2=2\n"
            "<Site default>\n"
            "   SiteId AAAABBBB-1111-2222-3333-000000000000\n"
            "   Hostname *\n"
            "   Service *:*\n"
            "   RuleEnable all\n"
            "</Site>\n"
        );

    configureIronBeeByString(config.c_str());
    performTx();

    /* Validation code */
    ib_var_target_t      *target;
    const ib_list_t      *list;
    const ib_list_node_t *node;
    const ib_field_t     *field;
    ib_num_t              num;

    ASSERT_EQ(
        IB_OK,
        ib_var_target_acquire_from_string(
            &target,
            ib_tx->mp,
            ib_engine_var_config_get(ib_engine),
            IB_S2SL("results:result1"),
            NULL,
            NULL));
    ASSERT_EQ(
        IB_OK,
        ib_var_target_get_const(
            target,
            &list,
            ib_tx->mp,
            ib_tx->var_store));
    ASSERT_EQ(1UL, ib_list_elements(list));

    node = ib_list_first_const(list);
    ASSERT_TRUE(node);
    field = (const ib_field_t *)ib_list_node_data_const(node);
    ASSERT_TRUE(field);
    ASSERT_EQ(
        IB_OK,
        ib_field_value_type(field, ib_ftype_num_out(&num), IB_FTYPE_NUM));
    ASSERT_EQ(1L, num);
}

TEST_F(CoreTest, TfnLast) {
    std::string config =
        std::string(
            "LogLevel INFO\n"
            "SensorId B9C1B52B-C24A-4309-B9F9-0EF4CD577A3E\n"
            "SensorName UnitTesting\n"
            "SensorHostname unit-testing.sensor.tld\n"
            "LoadModule ibmod_rules.so\n"
            "Action id:1 rev:1 phase:REQUEST_HEADER "
            "    setvar:list:element1=1\n"
            "Action id:2 rev:1 phase:REQUEST_HEADER "
            "    setvar:list:element2=2\n"
            "Rule list.first() @eq 1 id:3 rev:1 phase:REQUEST_HEADER "
            "    setvar:results:result1=1\n"
            "Rule list.last() @eq 2 id:4 rev:1 phase:REQUEST_HEADER "
            "    setvar:results:result2=2\n"
            "<Site default>\n"
            "   SiteId AAAABBBB-1111-2222-3333-000000000000\n"
            "   Hostname *\n"
            "   Service *:*\n"
            "   RuleEnable all\n"
            "</Site>\n"
        );

    configureIronBeeByString(config.c_str());
    performTx();

    /* Validation code */
    ib_var_target_t      *target;
    const ib_list_t      *list;
    const ib_list_node_t *node;
    const ib_field_t     *field;
    ib_num_t              num;

    ASSERT_EQ(
        IB_OK,
        ib_var_target_acquire_from_string(
            &target,
            ib_tx->mp,
            ib_engine_var_config_get(ib_engine),
            IB_S2SL("results:result2"),
            NULL,
            NULL));
    ASSERT_EQ(
        IB_OK,
        ib_var_target_get_const(
            target,
            &list,
            ib_tx->mp,
            ib_tx->var_store));
    ASSERT_EQ(1UL, ib_list_elements(list));

    node = ib_list_first_const(list);
    ASSERT_TRUE(node);
    field = (const ib_field_t *)ib_list_node_data_const(node);
    ASSERT_TRUE(field);
    ASSERT_EQ(
        IB_OK,
        ib_field_value_type(field, ib_ftype_num_out(&num), IB_FTYPE_NUM));
    ASSERT_EQ(2L, num);
}
<commit_msg>engine/tests/test_core.cpp: Strip whitespace.<commit_after>/*****************************************************************************
 * Licensed to Qualys, Inc. (QUALYS) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * QUALYS licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ****************************************************************************/

/**
 * @file
 * @brief IronBee --- Core tests that don't fit elsewhere.
 *
 */

#include <gtest/gtest.h>
#include "base_fixture.h"

#include "core_private.h"

class CoreTest : public BaseTransactionFixture {
};

TEST_F(CoreTest, BlockingMode) {
    ib_core_cfg_t *corecfg;
    ib_module_t   *module;

    std::string config =
        std::string(
            "LogLevel INFO\n"
            "SensorId B9C1B52B-C24A-4309-B9F9-0EF4CD577A3E\n"
            "SensorName UnitTesting\n"
            "SensorHostname unit-testing.sensor.tld\n"
            "BlockingMethod status=200\n"
            "<Site test-site>\n"
            "   SiteId AAAABBBB-1111-2222-3333-000000000000\n"
            "   Hostname UnitTest\n"
            "</Site>\n"
        );

    configureIronBeeByString(config.c_str());

    ASSERT_EQ(IB_OK, ib_engine_module_get(ib_engine, "core", &module));

    ASSERT_EQ(
        IB_OK,
        ib_context_module_config(ib_context_main(ib_engine), module, &corecfg));

    ASSERT_EQ(200, corecfg->block_status);
    ASSERT_EQ(IB_BLOCK_METHOD_STATUS, corecfg->block_method);
}

TEST_F(CoreTest, BlockingMode2) {
    ib_core_cfg_t *corecfg;
    ib_module_t   *module;

    std::string config =
        std::string(
            "LogLevel INFO\n"
            "SensorId B9C1B52B-C24A-4309-B9F9-0EF4CD577A3E\n"
            "SensorName UnitTesting\n"
            "SensorHostname unit-testing.sensor.tld\n"
            "<Site test-site>\n"
            "   BlockingMethod status=403\n"
            "   SiteId AAAABBBB-1111-2222-3333-000000000000\n"
            "   Hostname UnitTest\n"
            "</Site>\n"
        );

    configureIronBeeByString(config.c_str());

    ASSERT_EQ(IB_OK, ib_engine_module_get(ib_engine, "core", &module));

    ASSERT_EQ(
        IB_OK,
        ib_context_module_config(ib_context_main(ib_engine), module, &corecfg));

    ASSERT_EQ(403, corecfg->block_status);
    ASSERT_EQ(IB_BLOCK_METHOD_STATUS, corecfg->block_method);
}

TEST_F(CoreTest, TfnFirst) {
    std::string config =
        std::string(
            "LogLevel INFO\n"
            "SensorId B9C1B52B-C24A-4309-B9F9-0EF4CD577A3E\n"
            "SensorName UnitTesting\n"
            "SensorHostname unit-testing.sensor.tld\n"
            "LoadModule ibmod_rules.so\n"
            "Action id:1 rev:1 phase:REQUEST_HEADER "
            "    setvar:list:element1=1\n"
            "Action id:2 rev:1 phase:REQUEST_HEADER "
            "    setvar:list:element2=2\n"
            "Rule list.first() @eq 1 id:3 rev:1 phase:REQUEST_HEADER "
            "    setvar:results:result1=1\n"
            "Rule list.last() @eq 2 id:4 rev:1 phase:REQUEST_HEADER "
            "    setvar:results:result2=2\n"
            "<Site default>\n"
            "   SiteId AAAABBBB-1111-2222-3333-000000000000\n"
            "   Hostname *\n"
            "   Service *:*\n"
            "   RuleEnable all\n"
            "</Site>\n"
        );

    configureIronBeeByString(config.c_str());
    performTx();

    /* Validation code */
    ib_var_target_t      *target;
    const ib_list_t      *list;
    const ib_list_node_t *node;
    const ib_field_t     *field;
    ib_num_t              num;

    ASSERT_EQ(
        IB_OK,
        ib_var_target_acquire_from_string(
            &target,
            ib_tx->mp,
            ib_engine_var_config_get(ib_engine),
            IB_S2SL("results:result1"),
            NULL,
            NULL));
    ASSERT_EQ(
        IB_OK,
        ib_var_target_get_const(
            target,
            &list,
            ib_tx->mp,
            ib_tx->var_store));
    ASSERT_EQ(1UL, ib_list_elements(list));

    node = ib_list_first_const(list);
    ASSERT_TRUE(node);
    field = (const ib_field_t *)ib_list_node_data_const(node);
    ASSERT_TRUE(field);
    ASSERT_EQ(
        IB_OK,
        ib_field_value_type(field, ib_ftype_num_out(&num), IB_FTYPE_NUM));
    ASSERT_EQ(1L, num);
}

TEST_F(CoreTest, TfnLast) {
    std::string config =
        std::string(
            "LogLevel INFO\n"
            "SensorId B9C1B52B-C24A-4309-B9F9-0EF4CD577A3E\n"
            "SensorName UnitTesting\n"
            "SensorHostname unit-testing.sensor.tld\n"
            "LoadModule ibmod_rules.so\n"
            "Action id:1 rev:1 phase:REQUEST_HEADER "
            "    setvar:list:element1=1\n"
            "Action id:2 rev:1 phase:REQUEST_HEADER "
            "    setvar:list:element2=2\n"
            "Rule list.first() @eq 1 id:3 rev:1 phase:REQUEST_HEADER "
            "    setvar:results:result1=1\n"
            "Rule list.last() @eq 2 id:4 rev:1 phase:REQUEST_HEADER "
            "    setvar:results:result2=2\n"
            "<Site default>\n"
            "   SiteId AAAABBBB-1111-2222-3333-000000000000\n"
            "   Hostname *\n"
            "   Service *:*\n"
            "   RuleEnable all\n"
            "</Site>\n"
        );

    configureIronBeeByString(config.c_str());
    performTx();

    /* Validation code */
    ib_var_target_t      *target;
    const ib_list_t      *list;
    const ib_list_node_t *node;
    const ib_field_t     *field;
    ib_num_t              num;

    ASSERT_EQ(
        IB_OK,
        ib_var_target_acquire_from_string(
            &target,
            ib_tx->mp,
            ib_engine_var_config_get(ib_engine),
            IB_S2SL("results:result2"),
            NULL,
            NULL));
    ASSERT_EQ(
        IB_OK,
        ib_var_target_get_const(
            target,
            &list,
            ib_tx->mp,
            ib_tx->var_store));
    ASSERT_EQ(1UL, ib_list_elements(list));

    node = ib_list_first_const(list);
    ASSERT_TRUE(node);
    field = (const ib_field_t *)ib_list_node_data_const(node);
    ASSERT_TRUE(field);
    ASSERT_EQ(
        IB_OK,
        ib_field_value_type(field, ib_ftype_num_out(&num), IB_FTYPE_NUM));
    ASSERT_EQ(2L, num);
}
<|endoftext|>


<commit_before>/*
 * Deck.cpp
 *
 *  Created on: Nov 23, 2017
 *      Author: lowji
 */

#include "Deck.h"
#include <stack>
#include "Card.h"
using namespace std;

Deck::Deck(){
	deck=new stack<Card>();
}

void Deck::add(Card newCard){
	deck->push(newCard);
}

Card Deck::withdraw(){
	Card temp=deck->top();
	deck->pop();
	return temp;
}

stack<Card> Deck::getDeck(){
	return *deck;
}

<commit_msg>Delete Deck.cpp<commit_after><|endoftext|>


<commit_before>
// --Tested--
#define CRB_CIVILIANS
//#define CRB_CROWS
#define CRB_DOGS
#define CRB_EMERGENCY
//#define CRB_FLIES
//#define CRB_SANDSTORM
#define CRB_SHEPHERDS
#define RMM_CTP
#define TUP_AIRTRAFFIC
#define TUP_SEATRAFFIC
#define CRB_DESTROYCITY
#define AEG
<commit_msg>- Turn off Destroy City by default<commit_after>
// --Tested--
#define CRB_CIVILIANS
//#define CRB_CROWS
#define CRB_DOGS
#define CRB_EMERGENCY
//#define CRB_FLIES
//#define CRB_SANDSTORM
#define CRB_SHEPHERDS
#define RMM_CTP
#define TUP_AIRTRAFFIC
#define TUP_SEATRAFFIC
//#define CRB_DESTROYCITY
#define AEG
<|endoftext|>