<commit_before>#ifndef LIBTEN_TASK_TASK_HH
#define LIBTEN_TASK_TASK_HH

#include "ten/task/kernel.hh"
#include "ten/optional.hh"
#include "ten/error.hh"
#include <memory>
#include <chrono>
#include <functional>
#include <thread>

namespace ten {

//! exception to unwind stack on task cancel
struct task_interrupted {};

typedef optional<std::chrono::milliseconds> optional_timeout;

namespace this_task {

//! id of the current task
uint64_t get_id();

//! allow other tasks to run
void yield();

//! sleep current task until time is reached
void sleep_until(const kernel::time_point & sleep_time);

//! sleep current task until duration has passed
template <class Rep, class Period>
    void sleep_for(std::chrono::duration<Rep, Period> sleep_duration) {
        sleep_until(kernel::now() + sleep_duration);
    }

} // end namespace this_task

//! cooperatively scheduled light-weight threads of execution
class task {
public:
    class impl;

    //! call from main() to setup task system and do boilerplate exception handling
    template <class Func>
        static int main(Func &&f) {
            kernel the_kernel;
            return task::entry(std::forward<Func>(f));
        }

private:
    std::shared_ptr<impl> _impl;

    //! task entry boilerplate exception handling
    template <class Func>
        static int entry(Func &&f) {
            try {
                f();
                return EXIT_SUCCESS;
            } catch (ten::task_interrupted &e) {
                DVLOG(5) << "task " << ten::this_task::get_id() << " interrupted ";
            } catch (ten::backtrace_exception &e) {
                LOG(ERROR) << "unhandled error: " << e.what() << "\n" << e.backtrace_str();
            } catch (std::exception &e) {
                LOG(ERROR) << "unhandled error: " << e.what();
            }
            return EXIT_FAILURE;
        }

    explicit task(const std::function<void ()> &f);
public:
    task() {}
    task(const task &) = delete;
    task &operator=(const task &) = delete;
    task(task &&) = default;
    task &operator=(task &&) = default;

    //! spawn a new task in the current thread
    template<class Function, class... Args>
        static task spawn(Function &&f, Args&&... args) {
            return task{std::bind(f, std::forward<Args>(args)...)};
        }

    //! spawn a new task in a new thread
    // returns a joinable std::thread
    template<class Function, class... Args>
        static std::thread spawn_thread(Function &&f, Args&&... args) {
            // TODO: variadic templates don't work with lambdas yet
            // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=41933
            // work around using std::function and std::bind
            std::function<void ()> fb{std::bind(f, std::forward<Args>(args)...)};
            return std::thread{[=] {
                task::entry(fb);
                kernel::wait_for_tasks();
            }};
        }

    //! id of the task
    uint64_t get_id() const;

    //! cancel the task
    void cancel();

    //! set stack size that tasks will use when spawning
    static void set_default_stacksize(size_t stacksize);
};

} // end namespace ten

#endif
<commit_msg>change to fix bug in g++-4.7 parsing<commit_after>#ifndef LIBTEN_TASK_TASK_HH
#define LIBTEN_TASK_TASK_HH

#include "ten/task/kernel.hh"
#include "ten/optional.hh"
#include "ten/error.hh"
#include <memory>
#include <chrono>
#include <functional>
#include <thread>

namespace ten {

//! exception to unwind stack on task cancel
struct task_interrupted {};

typedef optional<std::chrono::milliseconds> optional_timeout;

namespace this_task {

//! id of the current task
uint64_t get_id();

//! allow other tasks to run
void yield();

//! sleep current task until time is reached
void sleep_until(const kernel::time_point & sleep_time);

//! sleep current task until duration has passed
template <class Rep, class Period>
    void sleep_for(std::chrono::duration<Rep, Period> sleep_duration) {
        sleep_until(kernel::now() + sleep_duration);
    }

} // end namespace this_task

//! cooperatively scheduled light-weight threads of execution
class task {
public:
    class impl;

    //! call from main() to setup task system and do boilerplate exception handling
    template <class Func>
        static int main(Func &&f) {
            kernel the_kernel;
            return task::entry(std::forward<Func>(f));
        }

private:
    std::shared_ptr<impl> _impl;

    //! task entry boilerplate exception handling
    template <class Func>
        static int entry(Func &&f) {
            try {
                f();
                return EXIT_SUCCESS;
            } catch (ten::task_interrupted &e) {
                DVLOG(5) << "task " << ten::this_task::get_id() << " interrupted ";
            } catch (ten::backtrace_exception &e) {
                LOG(ERROR) << "unhandled error: " << e.what() << "\n" << e.backtrace_str();
            } catch (std::exception &e) {
                LOG(ERROR) << "unhandled error: " << e.what();
            }
            return EXIT_FAILURE;
        }

    explicit task(const std::function<void ()> &f);
public:
    task() {}
    task(const task &) = delete;
    task &operator=(const task &) = delete;
    task(task &&) = default;
    task &operator=(task &&) = default;

    //! spawn a new task in the current thread
    template<class Function, class... Args>
        static task spawn(Function &&f, Args&&... args) {
            return task{std::bind(f, std::forward<Args>(args)...)};
        }

    //! spawn a new task in a new thread
    // returns a joinable std::thread
    template<class Function, class... Args>
        static std::thread spawn_thread(Function &&f, Args&&... args) {
            // TODO: variadic templates don't work with lambdas yet
            // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=41933
            // work around using std::function and std::bind
            std::function<void ()> fb{std::bind(f, std::forward<Args>(args)...)};
            return std::thread([=] {
                task::entry(fb);
                kernel::wait_for_tasks();
            });
        }

    //! id of the task
    uint64_t get_id() const;

    //! cancel the task
    void cancel();

    //! set stack size that tasks will use when spawning
    static void set_default_stacksize(size_t stacksize);
};

} // end namespace ten

#endif
<|endoftext|>


<commit_before>#ifndef _INCLUDED_ENV_HPP
#define _INCLUDED_ENV_HPP

#include <cassert>
#include <map>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <string>
#include <vector>

#include <glog/logging.h>

#include <tudostat/Stat.hpp>

using tudostat::Stat;

#include <tudocomp/util.h>

namespace tudocomp {

//DIY lexical cast
template<typename T> T lexical_cast(const std::string& s) {
    T val;
    std::stringstream(s) >> val;
    return val;
}

class OptionValue;
class AlgorithmValue {
public:
    using ArgumentMap = std::map<std::string, OptionValue>;
    using StatMap = std::map<std::string, std::string>;
private:
    std::string m_name;
    ArgumentMap m_arguments;
    friend class OptionValue;
public:
    inline AlgorithmValue(std::string&& name, ArgumentMap&& arguments):
        m_name(std::move(name)), m_arguments(std::move(arguments)) {}

    inline const std::string& name() const {
        return m_name;
    }
    inline ArgumentMap& arguments() {
        return m_arguments;
    }
};

class OptionValue {
    bool m_is_value;
    AlgorithmValue m_value_or_algorithm;
    friend class AlgorithmValue;
public:
    inline OptionValue(): OptionValue("") {}
    inline OptionValue(std::string&& value):
        m_is_value(true),
        m_value_or_algorithm(AlgorithmValue(std::move(value), {})) {}
    inline OptionValue(AlgorithmValue&& algorithm):
        m_is_value(false),
        m_value_or_algorithm(std::move(algorithm)) {}

    inline bool value_is_algorithm() {
        return !m_is_value;
    }
    inline bool has_value() const {
        return m_value_or_algorithm.m_name != "";
    }
    inline const std::string& value_as_string() const {
        CHECK(m_is_value);
        return m_value_or_algorithm.m_name;
    }
    inline AlgorithmValue& value_as_algorithm() {
        CHECK(!m_is_value);
        return m_value_or_algorithm;
    }
    inline uint64_t value_as_integer() const {
        return lexical_cast<uint64_t>(value_as_string());
    }
};

class EnvRoot {
private:
    std::unique_ptr<AlgorithmValue> m_algo_value;

    std::stack<Stat> m_stat_stack;
    Stat m_stat_root;

public:
    inline EnvRoot() {
        begin_stat_phase("root");
    }

    inline EnvRoot(AlgorithmValue&& algo_value):
        m_algo_value(std::make_unique<AlgorithmValue>(std::move(algo_value)))  {

        begin_stat_phase("root");
    }

    ~EnvRoot() {
        finish_stats();
    }

    inline AlgorithmValue& algo_value() {
        return *m_algo_value;
    }

    /// Returns a reference to the current statistics phase.
    /// This reference is valid only until the phase is ended.
    inline Stat& stat_current() {
        return m_stat_stack.empty() ? m_stat_root : m_stat_stack.top();
    }

    /// Begins a new statistics phase
    inline void begin_stat_phase(const std::string& name) {
        m_stat_stack.push(Stat(name));
        Stat& stat = m_stat_stack.top();
        stat.begin();
    }

    /// Ends the current statistics phase.
    inline void end_stat_phase() {
        assert(!m_stat_stack.empty());

        Stat& stat_ref = m_stat_stack.top();
        stat_ref.end();

        Stat stat = stat_ref; //copy
        m_stat_stack.pop();

        if(!m_stat_stack.empty()) {
            Stat& parent = m_stat_stack.top();
            parent.add_sub(stat);
        } else {
            m_stat_root = stat;
        }
    }

    /// Ends all current statistics phases and returns the root.
    inline Stat& finish_stats() {
        while(!m_stat_stack.empty()) {
            end_stat_phase();
        }

        return m_stat_root;
    }

    /// Resets all statistics and restarts with a new root.
    inline void restart_stats(const std::string& root_name) {
        finish_stats();
        begin_stat_phase(root_name);
    }

    /// Logs a statistic
    template<class T>
    inline void log_stat(const std::string& name, const T value) {
        stat_current().add_stat(name, value);
    }
};

/// Local environment for a compression/encoding/decompression call.
///
/// Gives access to a statistic logger, and to environment
/// options that can be used to modify the default behavior of an algorithm.
class Env {
    std::shared_ptr<EnvRoot> m_root;
    AlgorithmValue* m_node;

    inline Env() = delete;

    inline AlgorithmValue& algo() {
        return *m_node;
    }

public:
    inline Env(std::shared_ptr<EnvRoot> root, AlgorithmValue& node):
        m_root(root), m_node(&node) {}

    inline std::shared_ptr<EnvRoot>& root() {
        return m_root;
    }

    /// Log an error and end the current operation
    inline void error(const std::string& msg) {
        throw std::runtime_error(msg);
    }

    /// Create the environment for a sub algorithm
    /// option.
    inline Env env_for_option(const std::string& option) {
        CHECK(algo().arguments().count(option) > 0);
        auto& a = algo().arguments()[option].value_as_algorithm();

        return Env(m_root, a);
    }

    /// Get an option of this algorithm
    inline OptionValue& option(const std::string& option) {
        return algo().arguments()[option];
    }

    /// Begins a new statistics phase
    inline void begin_stat_phase(const std::string& name) {
        DLOG(INFO) << "begin phase \"" << name << "\"";
        m_root->begin_stat_phase(name); //delegate
    }

    /// Ends the current statistics phase.
    inline void end_stat_phase() {
        DLOG(INFO) << "end phase \"" << m_root->stat_current().title() << "\"";
        m_root->end_stat_phase(); //delegate
    }

    /// Ends all current statistics phases and returns the root.
    inline Stat& finish_stats() {
        return m_root->finish_stats(); //delegate
    }

    /// Resets all statistics and restarts with a new root.
    inline void restart_stats(const std::string& root_name) {
        m_root->restart_stats(root_name); //delegate
    }

    /// Log a statistic.
    ///
    /// Statistics will be gathered at a central location, and
    /// can be used to judge the behavior and performance of an
    /// implementation.
    ///
    /// \param name The name of the statistic.
    /// \param value The value of the statistic as a string.
    template<class T>
    inline void log_stat(const std::string& name, const T value) {
        m_root->log_stat(name, value);
    };
};

}
#endif
<commit_msg>Move stat debug output to EnvRoot<commit_after>#ifndef _INCLUDED_ENV_HPP
#define _INCLUDED_ENV_HPP

#include <cassert>
#include <map>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <string>
#include <vector>

#include <glog/logging.h>

#include <tudostat/Stat.hpp>

using tudostat::Stat;

#include <tudocomp/util.h>

namespace tudocomp {

//DIY lexical cast
template<typename T> T lexical_cast(const std::string& s) {
    T val;
    std::stringstream(s) >> val;
    return val;
}

class OptionValue;
class AlgorithmValue {
public:
    using ArgumentMap = std::map<std::string, OptionValue>;
    using StatMap = std::map<std::string, std::string>;
private:
    std::string m_name;
    ArgumentMap m_arguments;
    friend class OptionValue;
public:
    inline AlgorithmValue(std::string&& name, ArgumentMap&& arguments):
        m_name(std::move(name)), m_arguments(std::move(arguments)) {}

    inline const std::string& name() const {
        return m_name;
    }
    inline ArgumentMap& arguments() {
        return m_arguments;
    }
};

class OptionValue {
    bool m_is_value;
    AlgorithmValue m_value_or_algorithm;
    friend class AlgorithmValue;
public:
    inline OptionValue(): OptionValue("") {}
    inline OptionValue(std::string&& value):
        m_is_value(true),
        m_value_or_algorithm(AlgorithmValue(std::move(value), {})) {}
    inline OptionValue(AlgorithmValue&& algorithm):
        m_is_value(false),
        m_value_or_algorithm(std::move(algorithm)) {}

    inline bool value_is_algorithm() {
        return !m_is_value;
    }
    inline bool has_value() const {
        return m_value_or_algorithm.m_name != "";
    }
    inline const std::string& value_as_string() const {
        CHECK(m_is_value);
        return m_value_or_algorithm.m_name;
    }
    inline AlgorithmValue& value_as_algorithm() {
        CHECK(!m_is_value);
        return m_value_or_algorithm;
    }
    inline uint64_t value_as_integer() const {
        return lexical_cast<uint64_t>(value_as_string());
    }
};

class EnvRoot {
private:
    std::unique_ptr<AlgorithmValue> m_algo_value;

    std::stack<Stat> m_stat_stack;
    Stat m_stat_root;

public:
    inline EnvRoot() {
        begin_stat_phase("root");
    }

    inline EnvRoot(AlgorithmValue&& algo_value):
        m_algo_value(std::make_unique<AlgorithmValue>(std::move(algo_value)))  {

        begin_stat_phase("root");
    }

    ~EnvRoot() {
        finish_stats();
    }

    inline AlgorithmValue& algo_value() {
        return *m_algo_value;
    }

    /// Returns a reference to the current statistics phase.
    /// This reference is valid only until the phase is ended.
    inline Stat& stat_current() {
        return m_stat_stack.empty() ? m_stat_root : m_stat_stack.top();
    }

    /// Begins a new statistics phase
    inline void begin_stat_phase(const std::string& name) {
        DLOG(INFO) << "begin phase \"" << name << "\"";

        m_stat_stack.push(Stat(name));
        Stat& stat = m_stat_stack.top();
        stat.begin();
    }

    /// Ends the current statistics phase.
    inline void end_stat_phase() {
        assert(!m_stat_stack.empty());

        Stat& stat_ref = m_stat_stack.top();
        DLOG(INFO) << "end phase \"" << stat_ref.title() << "\"";

        stat_ref.end();

        Stat stat = stat_ref; //copy
        m_stat_stack.pop();

        if(!m_stat_stack.empty()) {
            Stat& parent = m_stat_stack.top();
            parent.add_sub(stat);
        } else {
            m_stat_root = stat;
        }
    }

    /// Ends all current statistics phases and returns the root.
    inline Stat& finish_stats() {
        while(!m_stat_stack.empty()) {
            end_stat_phase();
        }

        return m_stat_root;
    }

    /// Resets all statistics and restarts with a new root.
    inline void restart_stats(const std::string& root_name) {
        finish_stats();
        begin_stat_phase(root_name);
    }

    /// Logs a statistic
    template<class T>
    inline void log_stat(const std::string& name, const T value) {
        DLOG(INFO) << "stat: " << name << " = " << value;
        stat_current().add_stat(name, value);
    }
};

/// Local environment for a compression/encoding/decompression call.
///
/// Gives access to a statistic logger, and to environment
/// options that can be used to modify the default behavior of an algorithm.
class Env {
    std::shared_ptr<EnvRoot> m_root;
    AlgorithmValue* m_node;

    inline Env() = delete;

    inline AlgorithmValue& algo() {
        return *m_node;
    }

public:
    inline Env(std::shared_ptr<EnvRoot> root, AlgorithmValue& node):
        m_root(root), m_node(&node) {}

    inline std::shared_ptr<EnvRoot>& root() {
        return m_root;
    }

    /// Log an error and end the current operation
    inline void error(const std::string& msg) {
        throw std::runtime_error(msg);
    }

    /// Create the environment for a sub algorithm
    /// option.
    inline Env env_for_option(const std::string& option) {
        CHECK(algo().arguments().count(option) > 0);
        auto& a = algo().arguments()[option].value_as_algorithm();

        return Env(m_root, a);
    }

    /// Get an option of this algorithm
    inline OptionValue& option(const std::string& option) {
        return algo().arguments()[option];
    }

    /// Begins a new statistics phase
    inline void begin_stat_phase(const std::string& name) {
        m_root->begin_stat_phase(name); //delegate
    }

    /// Ends the current statistics phase.
    inline void end_stat_phase() {
        m_root->end_stat_phase(); //delegate
    }

    /// Ends all current statistics phases and returns the root.
    inline Stat& finish_stats() {
        return m_root->finish_stats(); //delegate
    }

    /// Resets all statistics and restarts with a new root.
    inline void restart_stats(const std::string& root_name) {
        m_root->restart_stats(root_name); //delegate
    }

    /// Log a statistic.
    ///
    /// Statistics will be gathered at a central location, and
    /// can be used to judge the behavior and performance of an
    /// implementation.
    ///
    /// \param name The name of the statistic.
    /// \param value The value of the statistic as a string.
    template<class T>
    inline void log_stat(const std::string& name, const T value) {
        m_root->log_stat(name, value);
    };
};

}
#endif
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF 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 .
 */

#ifndef INCLUDED_VCL_TEXTDATA_HXX
#define INCLUDED_VCL_TEXTDATA_HXX

#include <rtl/ustring.hxx>
#include <svl/brdcst.hxx>
#include <svl/smplhint.hxx>
#include <vcl/dllapi.h>

// for Notify, if all paragraphs were deleted
#define TEXT_PARA_ALL               0xFFFFFFFF

class TextPaM
{
private:
    sal_uLong           mnPara;
    sal_uInt16          mnIndex;

public:
                    TextPaM()                               { mnPara = 0, mnIndex = 0; }
                    TextPaM( sal_uLong nPara, sal_uInt16 nIndex )   { mnPara = nPara, mnIndex = nIndex; }

    sal_uLong           GetPara() const     { return mnPara; }
    sal_uLong&          GetPara()           { return mnPara; }

    sal_uInt16          GetIndex() const    { return mnIndex; }
    sal_uInt16&         GetIndex()          { return mnIndex; }

    inline sal_Bool     operator == ( const TextPaM& rPaM ) const;
    inline sal_Bool     operator != ( const TextPaM& rPaM ) const;
    inline sal_Bool     operator < ( const TextPaM& rPaM ) const;
    inline sal_Bool     operator > ( const TextPaM& rPaM ) const;
};

inline sal_Bool TextPaM::operator == ( const TextPaM& rPaM ) const
{
    return ( ( mnPara == rPaM.mnPara ) && ( mnIndex == rPaM.mnIndex ) ) ? sal_True : sal_False;
}

inline sal_Bool TextPaM::operator != ( const TextPaM& rPaM ) const
{
    return !( *this == rPaM );
}

inline sal_Bool TextPaM::operator < ( const TextPaM& rPaM ) const
{
    return ( ( mnPara < rPaM.mnPara ) ||
             ( ( mnPara == rPaM.mnPara ) && mnIndex < rPaM.mnIndex ) ) ? sal_True : sal_False;
}

inline sal_Bool TextPaM::operator > ( const TextPaM& rPaM ) const
{
    return ( ( mnPara > rPaM.mnPara ) ||
             ( ( mnPara == rPaM.mnPara ) && mnIndex > rPaM.mnIndex ) ) ? sal_True : sal_False;
}

class VCL_DLLPUBLIC TextSelection
{
private:
    TextPaM         maStartPaM;
    TextPaM         maEndPaM;

public:
                    TextSelection();
                    TextSelection( const TextPaM& rPaM );
                    TextSelection( const TextPaM& rStart, const TextPaM& rEnd );

    const TextPaM&  GetStart() const    { return maStartPaM; }
    TextPaM&        GetStart()          { return maStartPaM; }

    const TextPaM&  GetEnd() const      { return maEndPaM; }
    TextPaM&        GetEnd()            { return maEndPaM; }

    void            Justify();

    sal_Bool            HasRange() const    { return maStartPaM != maEndPaM; }

    inline sal_Bool     operator == ( const TextSelection& rSel ) const;
    inline sal_Bool     operator != ( const TextSelection& rSel ) const;
};

inline sal_Bool TextSelection::operator == ( const TextSelection& rSel ) const
{
    return ( ( maStartPaM == rSel.maStartPaM ) && ( maEndPaM == rSel.maEndPaM ) );
}

inline sal_Bool TextSelection::operator != ( const TextSelection& rSel ) const
{
    return !( *this == rSel );
}

#define TEXT_HINT_PARAINSERTED              1
#define TEXT_HINT_PARAREMOVED               2
#define TEXT_HINT_PARACONTENTCHANGED        3
#define TEXT_HINT_TEXTHEIGHTCHANGED         4
#define TEXT_HINT_FORMATPARA                5
#define TEXT_HINT_TEXTFORMATTED             6
#define TEXT_HINT_MODIFIED                  7
#define TEXT_HINT_BLOCKNOTIFICATION_START   8
#define TEXT_HINT_BLOCKNOTIFICATION_END     9
#define TEXT_HINT_INPUT_START               10
#define TEXT_HINT_INPUT_END                 11

#define TEXT_HINT_VIEWSCROLLED          100
#define TEXT_HINT_VIEWSELECTIONCHANGED  101

class VCL_DLLPUBLIC TextHint : public SfxSimpleHint
{
private:
    sal_uLong   mnValue;

public:
            TYPEINFO();
            TextHint( sal_uLong nId );
            TextHint( sal_uLong nId, sal_uLong nValue );

    sal_uLong   GetValue() const        { return mnValue; }
    void    SetValue( sal_uLong n )     { mnValue = n; }
};

struct TEIMEInfos
{
    OUString    aOldTextAfterStartPos;
    sal_uInt16* pAttribs;
    TextPaM     aPos;
    sal_Int32   nLen;
    bool        bCursor;
    bool        bWasCursorOverwrite;

    TEIMEInfos(const TextPaM& rPos, const OUString& rOldTextAfterStartPos);
    ~TEIMEInfos();

    void CopyAttribs(const sal_uInt16* pA, sal_Int32 nL);
    void DestroyAttribs();
};

// -----------------  Wrapper for old Tools List -------------------

#include <vector>
#include <algorithm>

template <class T> class ToolsList : public ::std::vector< T >
{
public:
    sal_uLong       Count() const { return static_cast<sal_uLong>(::std::vector< T >::size()); }
    sal_uLong       GetPos( T pObject ) const { return ( ::std::find( this->begin(), this->end(), pObject ) ) - this->begin(); }
    T               GetObject( sal_uLong nIndex ) const { return (*this)[nIndex]; }
    void            Insert( T pObject, sal_uLong nPos ) { ::std::vector< T >::insert( this->begin()+nPos, pObject ); }
    void            Remove( sal_uLong nPos ) { ::std::vector< T >::erase( this->begin()+nPos ); }
};

#endif // INCLUDED_VCL_TEXTDATA_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>sal_uLong->size_t<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF 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 .
 */

#ifndef INCLUDED_VCL_TEXTDATA_HXX
#define INCLUDED_VCL_TEXTDATA_HXX

#include <rtl/ustring.hxx>
#include <svl/brdcst.hxx>
#include <svl/smplhint.hxx>
#include <vcl/dllapi.h>

// for Notify, if all paragraphs were deleted
#define TEXT_PARA_ALL               0xFFFFFFFF

class TextPaM
{
private:
    sal_uLong           mnPara;
    sal_uInt16          mnIndex;

public:
                    TextPaM()                               { mnPara = 0, mnIndex = 0; }
                    TextPaM( sal_uLong nPara, sal_uInt16 nIndex )   { mnPara = nPara, mnIndex = nIndex; }

    sal_uLong           GetPara() const     { return mnPara; }
    sal_uLong&          GetPara()           { return mnPara; }

    sal_uInt16          GetIndex() const    { return mnIndex; }
    sal_uInt16&         GetIndex()          { return mnIndex; }

    inline sal_Bool     operator == ( const TextPaM& rPaM ) const;
    inline sal_Bool     operator != ( const TextPaM& rPaM ) const;
    inline sal_Bool     operator < ( const TextPaM& rPaM ) const;
    inline sal_Bool     operator > ( const TextPaM& rPaM ) const;
};

inline sal_Bool TextPaM::operator == ( const TextPaM& rPaM ) const
{
    return ( ( mnPara == rPaM.mnPara ) && ( mnIndex == rPaM.mnIndex ) ) ? sal_True : sal_False;
}

inline sal_Bool TextPaM::operator != ( const TextPaM& rPaM ) const
{
    return !( *this == rPaM );
}

inline sal_Bool TextPaM::operator < ( const TextPaM& rPaM ) const
{
    return ( ( mnPara < rPaM.mnPara ) ||
             ( ( mnPara == rPaM.mnPara ) && mnIndex < rPaM.mnIndex ) ) ? sal_True : sal_False;
}

inline sal_Bool TextPaM::operator > ( const TextPaM& rPaM ) const
{
    return ( ( mnPara > rPaM.mnPara ) ||
             ( ( mnPara == rPaM.mnPara ) && mnIndex > rPaM.mnIndex ) ) ? sal_True : sal_False;
}

class VCL_DLLPUBLIC TextSelection
{
private:
    TextPaM         maStartPaM;
    TextPaM         maEndPaM;

public:
                    TextSelection();
                    TextSelection( const TextPaM& rPaM );
                    TextSelection( const TextPaM& rStart, const TextPaM& rEnd );

    const TextPaM&  GetStart() const    { return maStartPaM; }
    TextPaM&        GetStart()          { return maStartPaM; }

    const TextPaM&  GetEnd() const      { return maEndPaM; }
    TextPaM&        GetEnd()            { return maEndPaM; }

    void            Justify();

    sal_Bool            HasRange() const    { return maStartPaM != maEndPaM; }

    inline sal_Bool     operator == ( const TextSelection& rSel ) const;
    inline sal_Bool     operator != ( const TextSelection& rSel ) const;
};

inline sal_Bool TextSelection::operator == ( const TextSelection& rSel ) const
{
    return ( ( maStartPaM == rSel.maStartPaM ) && ( maEndPaM == rSel.maEndPaM ) );
}

inline sal_Bool TextSelection::operator != ( const TextSelection& rSel ) const
{
    return !( *this == rSel );
}

#define TEXT_HINT_PARAINSERTED              1
#define TEXT_HINT_PARAREMOVED               2
#define TEXT_HINT_PARACONTENTCHANGED        3
#define TEXT_HINT_TEXTHEIGHTCHANGED         4
#define TEXT_HINT_FORMATPARA                5
#define TEXT_HINT_TEXTFORMATTED             6
#define TEXT_HINT_MODIFIED                  7
#define TEXT_HINT_BLOCKNOTIFICATION_START   8
#define TEXT_HINT_BLOCKNOTIFICATION_END     9
#define TEXT_HINT_INPUT_START               10
#define TEXT_HINT_INPUT_END                 11

#define TEXT_HINT_VIEWSCROLLED          100
#define TEXT_HINT_VIEWSELECTIONCHANGED  101

class VCL_DLLPUBLIC TextHint : public SfxSimpleHint
{
private:
    sal_uLong   mnValue;

public:
            TYPEINFO();
            TextHint( sal_uLong nId );
            TextHint( sal_uLong nId, sal_uLong nValue );

    sal_uLong   GetValue() const        { return mnValue; }
    void    SetValue( sal_uLong n )     { mnValue = n; }
};

struct TEIMEInfos
{
    OUString    aOldTextAfterStartPos;
    sal_uInt16* pAttribs;
    TextPaM     aPos;
    sal_Int32   nLen;
    bool        bCursor;
    bool        bWasCursorOverwrite;

    TEIMEInfos(const TextPaM& rPos, const OUString& rOldTextAfterStartPos);
    ~TEIMEInfos();

    void CopyAttribs(const sal_uInt16* pA, sal_Int32 nL);
    void DestroyAttribs();
};

// -----------------  Wrapper for old Tools List -------------------

#include <vector>
#include <algorithm>

template <class T> class ToolsList : public ::std::vector< T >
{
public:
    size_t Count() const { return ::std::vector< T >::size(); }
    size_t GetPos( T pObject ) const { return ( ::std::find( this->begin(), this->end(), pObject ) ) - this->begin(); }
    T      GetObject( size_t nIndex ) const { return (*this)[nIndex]; }
    void   Insert( T pObject, size_t nPos ) { ::std::vector< T >::insert( this->begin()+nPos, pObject ); }
    void   Remove( size_t nPos ) { ::std::vector< T >::erase( this->begin()+nPos ); }
};

#endif // INCLUDED_VCL_TEXTDATA_HXX

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


<commit_before>#include "di/Injectable.h"
#include "service/GWSDeviceServiceImpl.h"

using namespace std;
using namespace Poco;
using namespace BeeeOn;

BEEEON_OBJECT_BEGIN(BeeeOn, GWSDeviceServiceImpl)
BEEEON_OBJECT_CASTABLE(GWSDeviceService)
BEEEON_OBJECT_REF("deviceDao", &GWSDeviceServiceImpl::setDeviceDao)
BEEEON_OBJECT_REF("deviceInfoProvider", &GWSDeviceServiceImpl::setDeviceInfoProvider)
BEEEON_OBJECT_REF("transactionManager", &Transactional::setTransactionManager)
BEEEON_OBJECT_END(BeeeOn, GWSDeviceServiceImpl)

void GWSDeviceServiceImpl::setDeviceDao(DeviceDao::Ptr dao)
{
	m_deviceDao = dao;
}

void GWSDeviceServiceImpl::setDeviceInfoProvider(DeviceInfoProvider::Ptr provider)
{
	m_deviceInfoProvider = provider;
}

bool GWSDeviceServiceImpl::doRegisterDevice(Device &device,
		const string &name,
		const string &vendor,
		const Gateway &gateway)
{
	if (m_deviceDao->fetch(device, gateway)) {
		device.setLastSeen(DateTime());

		return m_deviceDao->update(device, gateway);
	}
	else {
		device.setName(name);
		device.setType(m_deviceInfoProvider->findByNameAndVendor(name, vendor));

		device.setFirstSeen(DateTime());
		device.setLastSeen(DateTime());

		device.setActiveSince(Nullable<DateTime>());

		return m_deviceDao->insert(device, gateway);
	}
}

void GWSDeviceServiceImpl::doFetchActiveWithPrefix(vector<Device> &devices,
		const Gateway &gateway,
		const DevicePrefix &prefix)
{
	m_deviceDao->fetchActiveWithPrefix(devices, gateway, prefix);
}
<commit_msg>GWSDeviceServiceImpl: check device type matches<commit_after>#include "di/Injectable.h"
#include "service/GWSDeviceServiceImpl.h"

using namespace std;
using namespace Poco;
using namespace BeeeOn;

BEEEON_OBJECT_BEGIN(BeeeOn, GWSDeviceServiceImpl)
BEEEON_OBJECT_CASTABLE(GWSDeviceService)
BEEEON_OBJECT_REF("deviceDao", &GWSDeviceServiceImpl::setDeviceDao)
BEEEON_OBJECT_REF("deviceInfoProvider", &GWSDeviceServiceImpl::setDeviceInfoProvider)
BEEEON_OBJECT_REF("transactionManager", &Transactional::setTransactionManager)
BEEEON_OBJECT_END(BeeeOn, GWSDeviceServiceImpl)

void GWSDeviceServiceImpl::setDeviceDao(DeviceDao::Ptr dao)
{
	m_deviceDao = dao;
}

void GWSDeviceServiceImpl::setDeviceInfoProvider(DeviceInfoProvider::Ptr provider)
{
	m_deviceInfoProvider = provider;
}

bool GWSDeviceServiceImpl::doRegisterDevice(Device &device,
		const string &name,
		const string &vendor,
		const Gateway &gateway)
{
	if (m_deviceDao->fetch(device, gateway)) {
		device.setLastSeen(DateTime());

		return m_deviceDao->update(device, gateway);
	}
	else {
		device.setName(name);

		auto type = m_deviceInfoProvider->findByNameAndVendor(name, vendor);
		if (type.isNull()) {
			throw NotFoundException("no such device type for "
				"'" + vendor + "' '" + name + "' specification");
		}

		device.setType(type);

		device.setFirstSeen(DateTime());
		device.setLastSeen(DateTime());

		device.setActiveSince(Nullable<DateTime>());

		return m_deviceDao->insert(device, gateway);
	}
}

void GWSDeviceServiceImpl::doFetchActiveWithPrefix(vector<Device> &devices,
		const Gateway &gateway,
		const DevicePrefix &prefix)
{
	m_deviceDao->fetchActiveWithPrefix(devices, gateway, prefix);
}
<|endoftext|>


<commit_before>#include <gmock/gmock.h>

#include "script/LuaItemScript.hpp"
#include "Character.hpp"
#include "World.hpp"
#include "Container.hpp"

class MockCharacter : public Character {
public:
    MOCK_CONST_METHOD0(getId, TYPE_OF_CHARACTER_ID());
    MOCK_CONST_METHOD0(getType, unsigned short());
    MOCK_CONST_METHOD0(to_string, std::string());
    MOCK_CONST_METHOD2(inform, void(const std::string &, informType));
    MOCK_CONST_METHOD3(inform, void(const std::string &, const std::string &, informType));
    MOCK_CONST_METHOD0(GetBackPack, Container *());
};

class MockWorld : public World {
public:
    MockWorld() {
        World::_self = this;
    }

    MOCK_METHOD2(getItemName, std::string(TYPE_OF_ITEM_ID itemid, uint8_t language));
    MOCK_METHOD1(findCharacter, Character*(TYPE_OF_CHARACTER_ID id));
};

class MockContainer : public Container {
public:
    MockContainer() : Container(0) {}

    MOCK_CONST_METHOD2(countItem, int(Item::id_type, script_data_exchangemap const *));
    MOCK_METHOD3(eraseItem, int(Item::id_type, Item::number_type, script_data_exchangemap const *));
};

using ::testing::Return;
using ::testing::AtLeast;
using ::testing::_;
using ::testing::Pointee;

class world_bindings : public ::testing::Test {
public:
    MockWorld world;
    MockCharacter player;
    ScriptItem item;
    CommonStruct itemdef;
    MockContainer container;

    ~world_bindings() {
        LuaScript::shutdownLua();
    }

    world_bindings() {
        ON_CALL(player, getId()).WillByDefault(Return(1));
        EXPECT_CALL(player, getId()).Times(AtLeast(0));
	    ON_CALL(world, findCharacter(player.getId())).WillByDefault(Return(&player));
        EXPECT_CALL(world, findCharacter(player.getId())).Times(AtLeast(0));
    }
};

TEST_F(world_bindings, LookAtItem) {
    LuaItemScript script {"function LookAtItem(player, item)\n"
                          "local lookAt = ItemLookAt()\n"
                          "lookAt.name = world:getItemName(item.id,Player.english)\n"
                          "return lookAt\n"
                          "end",
                          "lookat_test", itemdef
                         };

    ItemLookAt lookAt;
    lookAt.setName("itemname");
    EXPECT_CALL(world, getItemName(item.getId(), static_cast<uint8_t>(Language::english))).Times(1).WillOnce(Return("itemname"));
    ItemLookAt result = script.LookAtItem(&player, item);
    EXPECT_EQ(lookAt, result);
}

TEST_F(world_bindings, UseItem) {
    LuaItemScript script {"function UseItem(User, SourceItem, ltstate)\n"
                          "User:inform(\"You have used the item with the name '\"..world:getItemName(SourceItem.id,Player.english)..\"' and the ID \"..tonumber(SourceItem.id)..\".\")\n"
                          "end",
                          "useitem_test", itemdef
                         };

    EXPECT_CALL(world, getItemName(item.getId(), _)).Times(1).WillOnce(Return("itemname"));
    EXPECT_CALL(player, inform(_,_)).Times(1);
    script.UseItem(&player, item, 1);
}

TEST_F(world_bindings, ContainerCountItem) {
    LuaItemScript script {"function UseItem(User, SourceItem, ltstate)\n"
                          "local container = User:getBackPack()\n"
                          "container:countItem(1, {key1 = \"value1\", key2 = \"value2\"})"
                          "end",
                          "container_countitem_test", itemdef
                         };
    const script_data_exchangemap data {{"key1", "value1"}, {"key2", "value2"}};

    EXPECT_CALL(player, GetBackPack()).Times(1).WillOnce(Return(&container));
    EXPECT_CALL(container, countItem(1, Pointee(data))).Times(1);
    script.UseItem(&player, item, 1);
}

TEST_F(world_bindings, ContainerEraseItem) {
    LuaItemScript script {"function UseItem(User, SourceItem, ltstate)\n"
                          "local container = User:getBackPack()\n"
                          "container:eraseItem(1, 1, {key1 = \"value1\", key2 = \"value2\"})"
                          "end",
                          "container_eraseitem_test", itemdef
                         };
    const script_data_exchangemap data {{"key1", "value1"}, {"key2", "value2"}};

    EXPECT_CALL(player, GetBackPack()).Times(1).WillOnce(Return(&container));
    EXPECT_CALL(container, eraseItem(1, 1, Pointee(data))).Times(1);
    script.UseItem(&player, item, 1);
}

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

<commit_msg>Fix tests with potentially unordered Lua table<commit_after>#include <gmock/gmock.h>

#include "script/LuaItemScript.hpp"
#include "Character.hpp"
#include "World.hpp"
#include "Container.hpp"

class MockCharacter : public Character {
public:
    MOCK_CONST_METHOD0(getId, TYPE_OF_CHARACTER_ID());
    MOCK_CONST_METHOD0(getType, unsigned short());
    MOCK_CONST_METHOD0(to_string, std::string());
    MOCK_CONST_METHOD2(inform, void(const std::string &, informType));
    MOCK_CONST_METHOD3(inform, void(const std::string &, const std::string &, informType));
    MOCK_CONST_METHOD0(GetBackPack, Container *());
};

class MockWorld : public World {
public:
    MockWorld() {
        World::_self = this;
    }

    MOCK_METHOD2(getItemName, std::string(TYPE_OF_ITEM_ID itemid, uint8_t language));
    MOCK_METHOD1(findCharacter, Character*(TYPE_OF_CHARACTER_ID id));
};

class MockContainer : public Container {
public:
    MockContainer() : Container(0) {}

    MOCK_CONST_METHOD2(countItem, int(Item::id_type, script_data_exchangemap const *));
    MOCK_METHOD3(eraseItem, int(Item::id_type, Item::number_type, script_data_exchangemap const *));
};

using ::testing::Return;
using ::testing::AtLeast;
using ::testing::_;
using ::testing::Pointee;
using ::testing::AnyOf;

class world_bindings : public ::testing::Test {
public:
    MockWorld world;
    MockCharacter player;
    ScriptItem item;
    CommonStruct itemdef;
    MockContainer container;

    ~world_bindings() {
        LuaScript::shutdownLua();
    }

    world_bindings() {
        ON_CALL(player, getId()).WillByDefault(Return(1));
        EXPECT_CALL(player, getId()).Times(AtLeast(0));
	    ON_CALL(world, findCharacter(player.getId())).WillByDefault(Return(&player));
        EXPECT_CALL(world, findCharacter(player.getId())).Times(AtLeast(0));
    }
};

TEST_F(world_bindings, LookAtItem) {
    LuaItemScript script {"function LookAtItem(player, item)\n"
                          "local lookAt = ItemLookAt()\n"
                          "lookAt.name = world:getItemName(item.id,Player.english)\n"
                          "return lookAt\n"
                          "end",
                          "lookat_test", itemdef
                         };

    ItemLookAt lookAt;
    lookAt.setName("itemname");
    EXPECT_CALL(world, getItemName(item.getId(), static_cast<uint8_t>(Language::english))).Times(1).WillOnce(Return("itemname"));
    ItemLookAt result = script.LookAtItem(&player, item);
    EXPECT_EQ(lookAt, result);
}

TEST_F(world_bindings, UseItem) {
    LuaItemScript script {"function UseItem(User, SourceItem, ltstate)\n"
                          "User:inform(\"You have used the item with the name '\"..world:getItemName(SourceItem.id,Player.english)..\"' and the ID \"..tonumber(SourceItem.id)..\".\")\n"
                          "end",
                          "useitem_test", itemdef
                         };

    EXPECT_CALL(world, getItemName(item.getId(), _)).Times(1).WillOnce(Return("itemname"));
    EXPECT_CALL(player, inform(_,_)).Times(1);
    script.UseItem(&player, item, 1);
}

TEST_F(world_bindings, ContainerCountItem) {
    LuaItemScript script {"function UseItem(User, SourceItem, ltstate)\n"
                          "local container = User:getBackPack()\n"
                          "container:countItem(1, {key1 = \"value1\", key2 = \"value2\"})"
                          "end",
                          "container_countitem_test", itemdef
                         };
    const script_data_exchangemap data1 {{"key1", "value1"}, {"key2", "value2"}};
    const script_data_exchangemap data2 {{"key2", "value2"}, {"key1", "value1"}};

    EXPECT_CALL(player, GetBackPack()).Times(1).WillOnce(Return(&container));
    EXPECT_CALL(container, countItem(1, Pointee(AnyOf(data1, data2)))).Times(1);
    script.UseItem(&player, item, 1);
}

TEST_F(world_bindings, ContainerEraseItem) {
    LuaItemScript script {"function UseItem(User, SourceItem, ltstate)\n"
                          "local container = User:getBackPack()\n"
                          "container:eraseItem(1, 1, {key1 = \"value1\", key2 = \"value2\"})"
                          "end",
                          "container_eraseitem_test", itemdef
                         };
    const script_data_exchangemap data1 {{"key1", "value1"}, {"key2", "value2"}};
    const script_data_exchangemap data2 {{"key2", "value2"}, {"key1", "value1"}};

    EXPECT_CALL(player, GetBackPack()).Times(1).WillOnce(Return(&container));
    EXPECT_CALL(container, eraseItem(1, 1, Pointee(AnyOf(data1, data2)))).Times(1);
    script.UseItem(&player, item, 1);
}

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

<|endoftext|>


<commit_before>// Copyright (c) 2015, Ming Wen

#include "fys.hpp"
#include "util.hpp"
#include "json_base.hpp"
#include "json_images.hpp"
#include "json_features.hpp"
#include "test.hpp"

using namespace std;
using namespace cv;

namespace fys {

void testSIFT(string featuresFile, string imagesFile)
{
    std::cout << "==== Test Start: SIFT Demo ====" << std::endl;

    Mat query = imread("../OneWaySignal/1.jpg", 0); // read gray image
    Mat test1 = imread("../OneWaySignal/2.jpg", 0);
    Mat test2 = imread("../OneWaySignal/5.jpg", 0);
    Mat test3 = imread("../OneWaySignal/9.jpg", 0);

    JsonFeatures jf(featuresFile);
    SIFT detectAndExtractor(jf.genSIFT());

    // Read images json file
    JsonImages ji(imagesFile);
    ImageObject ob = ji.getObjectByID(ji.doc, TRAIN_TYPE, 0, 0);

    vector<KeyPoint> queryKeys;
    vector<KeyPoint> testKeys;
    vector<KeyPoint> reducedKeys;
    Mat queryDescriptors, testDescriptors;
    BFMatcher matcher(jf.genBFMatcher());
    vector<DMatch> matches;
    Mat output;
    ImageRegion reg;
    Scalar color(0, 0, 255);

    detectAndExtractor.detect(query, queryKeys);

    // Delete the points outside the object region
    queryKeys = pointsInObject(queryKeys, ob);
    detectAndExtractor.compute(query, queryKeys, queryDescriptors);

    detectAndExtractor.detect(test1, testKeys);
    detectAndExtractor.compute(test1, testKeys, testDescriptors);

    matcher.match(queryDescriptors, testDescriptors, matches);

    // Delete unmatched points in train image
    reducedKeys = matchedPoints(testKeys, matches, TRAIN_PART_TYPE);
    reg = locateDenseRegion(reducedKeys, 0.05);

    drawMatches(query, queryKeys, test1, testKeys, matches, output);
    rectangle(output, Point(reg.xmin + query.cols, reg.ymin), Point(reg.xmax + query.cols, reg.ymax), color, 2);

#if 0
    imwrite("1-2.jpg", output);

    detectAndExtractor.detect(test2, testKeys);
    detectAndExtractor.compute(test2, testKeys, testDescriptors);

    matcher.match(queryDescriptors, testDescriptors, matches);

    drawMatches(query, queryKeys, test2, testKeys, matches, output);
    imwrite("1-5.jpg", output);

    detectAndExtractor.detect(test3, testKeys);
    detectAndExtractor.compute(test3, testKeys, testDescriptors);

    matcher.match(queryDescriptors, testDescriptors, matches);

    drawMatches(query, queryKeys, test3, testKeys, matches, output);
    imwrite("1-9.jpg", output);
#endif

    namedWindow("window");
    imshow("window", output);
    waitKey(0);

    std::cout << "==== Test End: SIFT Demo ====" << std::endl;
}

}

<commit_msg>update parameters and save to image files<commit_after>// Copyright (c) 2015, Ming Wen

#include "fys.hpp"
#include "util.hpp"
#include "json_base.hpp"
#include "json_images.hpp"
#include "json_features.hpp"
#include "test.hpp"

using namespace std;
using namespace cv;

namespace fys {

void testSIFT(string featuresFile, string imagesFile)
{
    std::cout << "==== Test Start: SIFT Demo ====" << std::endl;

    Mat query = imread("../OneWaySignal/1.jpg", 0); // read gray image
    Mat test1 = imread("../OneWaySignal/2.jpg", 0);
    Mat test2 = imread("../OneWaySignal/5.jpg", 0);
    Mat test3 = imread("../OneWaySignal/9.jpg", 0);

    JsonFeatures jf(featuresFile);
    SIFT detectAndExtractor(jf.genSIFT());

    // Read images json file
    JsonImages ji(imagesFile);
    ImageObject ob = ji.getObjectByID(ji.doc, TRAIN_TYPE, 0, 0);

    vector<KeyPoint> queryKeys;
    vector<KeyPoint> testKeys;
    vector<KeyPoint> reducedKeys;
    Mat queryDescriptors, testDescriptors;
    BFMatcher matcher(jf.genBFMatcher());
    vector<DMatch> matches;
    Mat output;
    ImageRegion reg;
    Scalar color(0, 0, 255);

    detectAndExtractor.detect(query, queryKeys);

    // Delete the points outside the object region
    queryKeys = pointsInObject(queryKeys, ob);
    detectAndExtractor.compute(query, queryKeys, queryDescriptors);

    detectAndExtractor.detect(test1, testKeys);
    detectAndExtractor.compute(test1, testKeys, testDescriptors);

    matcher.match(queryDescriptors, testDescriptors, matches);

    // Delete unmatched points in train image
    reducedKeys = matchedPoints(testKeys, matches, TRAIN_PART_TYPE);
    reg = locateDenseRegion(reducedKeys, 0.2);

    drawMatches(query, queryKeys, test1, testKeys, matches, output);
    rectangle(output, Point(reg.xmin + query.cols, reg.ymin), Point(reg.xmax + query.cols, reg.ymax), color, 2);

    imwrite("1-2.jpg", output);

    detectAndExtractor.detect(test2, testKeys);
    detectAndExtractor.compute(test2, testKeys, testDescriptors);

    matcher.match(queryDescriptors, testDescriptors, matches);
    reducedKeys = matchedPoints(testKeys, matches, TRAIN_PART_TYPE);
    reg = locateDenseRegion(reducedKeys, 0.2);

    drawMatches(query, queryKeys, test2, testKeys, matches, output);
    rectangle(output, Point(reg.xmin + query.cols, reg.ymin), Point(reg.xmax + query.cols, reg.ymax), color, 2);
    imwrite("1-5.jpg", output);

    detectAndExtractor.detect(test3, testKeys);
    detectAndExtractor.compute(test3, testKeys, testDescriptors);

    matcher.match(queryDescriptors, testDescriptors, matches);
    reducedKeys = matchedPoints(testKeys, matches, TRAIN_PART_TYPE);
    reg = locateDenseRegion(reducedKeys, 0.2);

    drawMatches(query, queryKeys, test3, testKeys, matches, output);
    rectangle(output, Point(reg.xmin + query.cols, reg.ymin), Point(reg.xmax + query.cols, reg.ymax), color, 2);
    imwrite("1-9.jpg", output);

    //namedWindow("window");
    //imshow("window", output);
    //waitKey(0);

    std::cout << "==== Test End: SIFT Demo ====" << std::endl;
}

}

<|endoftext|>


<commit_before>
//------------------------------------------------------------------------------
// File : SkyTextureState.cpp
//------------------------------------------------------------------------------
// SkyWorks : Copyright 2002 Mark J. Harris and
//						The University of North Carolina at Chapel Hill
//------------------------------------------------------------------------------
// Permission to use, copy, modify, distribute and sell this software and its
// documentation for any purpose is hereby granted without fee, provided that
// the above copyright notice appear in all copies and that both that copyright
// notice and this permission notice appear in supporting documentation.
// Binaries may be compiled with this software without any royalties or
// restrictions.
//
// The author(s) and The University of North Carolina at Chapel Hill make no
// representations about the suitability of this software for any purpose.
// It is provided "as is" without express or
// implied warranty.
/**
 * @file SkyTextureState.cpp
 *
 * Implementation of class SkyTextureState, which encapsulates OpenGL texture state.
 */
#include "SkyTextureState.hpp"
//#include "glvu.hpp"

//------------------------------------------------------------------------------
// Static initializations.
//------------------------------------------------------------------------------
unsigned int SkyTextureState::s_iNumTextureUnits = 0;

//------------------------------------------------------------------------------
// Function     	  : SkyTextureState::SkyTextureState
// Description	    :
//------------------------------------------------------------------------------
/**
* @fn SkyTextureState::SkyTextureState()
* @brief Constructor.
*/
SkyTextureState::SkyTextureState()
{
  if (0 == s_iNumTextureUnits)
  {
    int iNumTextureUnits = 0;
#ifdef GL_ARB_multitexture
    glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, &iNumTextureUnits);
    if (iNumTextureUnits > 0)
      s_iNumTextureUnits = iNumTextureUnits;
    else
      s_iNumTextureUnits = 1;
#endif
  }

  _pTextureUnitState = new TexState[s_iNumTextureUnits];
}

//------------------------------------------------------------------------------
// Function     	  : SkyTextureState::~SkyTextureState
// Description	    :
//------------------------------------------------------------------------------
/**
* @fn SkyTextureState::~SkyTextureState()
* @brief Destructor.
*/
SkyTextureState::~SkyTextureState()
{
  SAFE_DELETE(_pTextureUnitState);
}

//------------------------------------------------------------------------------
// Function     	  : SkyTextureState::Activate
// Description	    :
//------------------------------------------------------------------------------
/**
 * @fn SkyTextureState::Activate()
 * @brief @todo <WRITE BRIEF SkyTextureState::Activate DOCUMENTATION>
 *
 * @todo <WRITE EXTENDED SkyTextureState::Activate FUNCTION DOCUMENTATION>
 */
SKYRESULT SkyTextureState::Activate()
{
  SkyTextureState *pCurrent = GraphicsContext::InstancePtr()->GetCurrentTextureState();
  assert(NULL != pCurrent);
  //GLVU::CheckForGLError("SkyTextureState::Activate(8)");
  for (unsigned int i = 0; i < s_iNumTextureUnits; ++i)
  {
#ifdef GL_ARB_multitexture
    if (s_iNumTextureUnits > 1)
      glActiveTextureARB(GL_TEXTURE0_ARB + i);
#endif
    bool bEnabled = IsTextureEnabled(i);
    if (pCurrent->IsTextureEnabled(i) != bEnabled)
    {
      FAIL_RETURN(pCurrent->EnableTexture(i, bEnabled));
      //GLVU::CheckForGLError("SkyTextureState::Activate(7)");
      if (bEnabled)
        glEnable(GetActiveTarget(i));
      else
        glDisable(GetActiveTarget(i));
    }
    //GLVU::CheckForGLError("SkyTextureState::Activate(6)");
    if (bEnabled)
    {
      GLenum eTarget    = GetActiveTarget(i);
      unsigned int iID  = GetTextureID(i);
      // if ((pCurrent->GetActiveTarget(i) != eTarget) ||
      //     (pCurrent->GetTextureID(i)    != iID))
      // {
        FAIL_RETURN(pCurrent->SetTexture(i, eTarget, iID));
        glBindTexture(eTarget, iID);
      // }
      //GLVU::CheckForGLError("SkyTextureState::Activate(5)");
      GLenum paramValue = GetTextureParameter(i, GL_TEXTURE_WRAP_S);
      if (pCurrent->GetTextureParameter(i, GL_TEXTURE_WRAP_S) != paramValue)
      {
        FAIL_RETURN(pCurrent->SetTextureParameter(i, GL_TEXTURE_WRAP_S, paramValue));
        glTexParameteri(eTarget, GL_TEXTURE_WRAP_S, paramValue);
      }
      //GLVU::CheckForGLError("SkyTextureState::Activate(4)");
      paramValue = GetTextureParameter(i, GL_TEXTURE_WRAP_T);
      if (pCurrent->GetTextureParameter(i, GL_TEXTURE_WRAP_T) != paramValue)
      {
        FAIL_RETURN(pCurrent->SetTextureParameter(i, GL_TEXTURE_WRAP_T, paramValue));
        glTexParameteri(eTarget, GL_TEXTURE_WRAP_T, paramValue);
      }
      //GLVU::CheckForGLError("SkyTextureState::Activate(3)");
      paramValue = GetTextureParameter(i, GL_TEXTURE_WRAP_R);
      if (pCurrent->GetTextureParameter(i, GL_TEXTURE_WRAP_R) != paramValue)
      {
        FAIL_RETURN(pCurrent->SetTextureParameter(i, GL_TEXTURE_WRAP_R, paramValue));
        glTexParameteri(eTarget, GL_TEXTURE_WRAP_R, paramValue);
      }
      //GLVU::CheckForGLError("SkyTextureState::Activate(2)");
      paramValue = GetTextureParameter(i, GL_TEXTURE_MIN_FILTER);
      if (pCurrent->GetTextureParameter(i, GL_TEXTURE_MIN_FILTER) != paramValue)
      {
        FAIL_RETURN(pCurrent->SetTextureParameter(i, GL_TEXTURE_MIN_FILTER, paramValue));
        glTexParameteri(eTarget, GL_TEXTURE_MIN_FILTER, paramValue);
      }
       //GLVU::CheckForGLError("SkyTextureState::Activate(1)");
      paramValue = GetTextureParameter(i, GL_TEXTURE_MAG_FILTER);
      if (pCurrent->GetTextureParameter(i, GL_TEXTURE_MAG_FILTER) != paramValue)
      {
        FAIL_RETURN(pCurrent->SetTextureParameter(i, GL_TEXTURE_MAG_FILTER, paramValue));
        glTexParameteri(eTarget, GL_TEXTURE_MAG_FILTER, paramValue);
      }
      //GLVU::CheckForGLError("SkyTextureState::Activate()");
    }
#ifdef GL_ARB_multitexture
    if (s_iNumTextureUnits > 1)
      glActiveTextureARB(GL_TEXTURE0_ARB);
#endif
  }
  return SKYRESULT_OK;
}

//------------------------------------------------------------------------------
// Function     	  : SkyTextureState::Force
// Description	    :
//------------------------------------------------------------------------------
/**
 * @fn SkyTextureState::Force()
 * @brief @todo <WRITE BRIEF SkyTextureState::Activate DOCUMENTATION>
 *
 * @todo <WRITE EXTENDED SkyTextureState::Activate FUNCTION DOCUMENTATION>
 */
SKYRESULT SkyTextureState::Force()
{
  SkyTextureState *pCurrent = GraphicsContext::InstancePtr()->GetCurrentTextureState();
  assert(NULL != pCurrent);
  //GLVU::CheckForGLError("SkyTextureState::Activate(8)");
  for (unsigned int i = 0; i < s_iNumTextureUnits; ++i)
  {
#ifdef GL_ARB_multitexture
    if (s_iNumTextureUnits > 1)
      glActiveTextureARB(GL_TEXTURE0_ARB + i);
#endif
    bool bEnabled = IsTextureEnabled(i);
    FAIL_RETURN(pCurrent->EnableTexture(i, bEnabled));
    //GLVU::CheckForGLError("SkyTextureState::Activate(7)");
    if (bEnabled)
        glEnable(GetActiveTarget(i));
    else
        glDisable(GetActiveTarget(i));

    //GLVU::CheckForGLError("SkyTextureState::Activate(6)");
    GLenum eTarget    = GetActiveTarget(i);
    unsigned int iID  = GetTextureID(i);

    FAIL_RETURN(pCurrent->SetTexture(i, eTarget, iID));
    glBindTexture(eTarget, iID);

    //GLVU::CheckForGLError("SkyTextureState::Activate(5)");
    GLenum paramValue = GetTextureParameter(i, GL_TEXTURE_WRAP_S);
    FAIL_RETURN(pCurrent->SetTextureParameter(i, GL_TEXTURE_WRAP_S, paramValue));
    glTexParameteri(eTarget, GL_TEXTURE_WRAP_S, paramValue);

    //GLVU::CheckForGLError("SkyTextureState::Activate(4)");
    paramValue = GetTextureParameter(i, GL_TEXTURE_WRAP_T);
    FAIL_RETURN(pCurrent->SetTextureParameter(i, GL_TEXTURE_WRAP_T, paramValue));
    glTexParameteri(eTarget, GL_TEXTURE_WRAP_T, paramValue);

    //GLVU::CheckForGLError("SkyTextureState::Activate(3)");
    paramValue = GetTextureParameter(i, GL_TEXTURE_WRAP_R);
    FAIL_RETURN(pCurrent->SetTextureParameter(i, GL_TEXTURE_WRAP_R, paramValue));
    glTexParameteri(eTarget, GL_TEXTURE_WRAP_R, paramValue);

    //GLVU::CheckForGLError("SkyTextureState::Activate(2)");
    paramValue = GetTextureParameter(i, GL_TEXTURE_MIN_FILTER);
    FAIL_RETURN(pCurrent->SetTextureParameter(i, GL_TEXTURE_MIN_FILTER, paramValue));
    glTexParameteri(eTarget, GL_TEXTURE_MIN_FILTER, paramValue);

    //GLVU::CheckForGLError("SkyTextureState::Activate(1)");
    paramValue = GetTextureParameter(i, GL_TEXTURE_MAG_FILTER);
    FAIL_RETURN(pCurrent->SetTextureParameter(i, GL_TEXTURE_MAG_FILTER, paramValue));
    glTexParameteri(eTarget, GL_TEXTURE_MIN_FILTER, paramValue);

#ifdef GL_ARB_multitexture
    if (s_iNumTextureUnits > 1)
      glActiveTextureARB(GL_TEXTURE0_ARB);
#endif
  }
  return SKYRESULT_OK;
}

//------------------------------------------------------------------------------
// Function     	  : SkyTextureState::SetTexture
// Description	    :
//------------------------------------------------------------------------------
/**
 * @fn SkyTextureState::SetTexture(unsigned int iTextureUnit, GLenum eTarget, SkyTexture&  texture)
 * @brief @todo <WRITE BRIEF SkyTextureState::BindTexture DOCUMENTATION>
 *
 * @todo <WRITE EXTENDED SkyTextureState::BindTexture FUNCTION DOCUMENTATION>
 */
SKYRESULT SkyTextureState::SetTexture(unsigned int iTextureUnit,
                                      GLenum       eTarget,
                                      SkyTexture&  texture)
{
  if (iTextureUnit >= s_iNumTextureUnits)
  {
    FAIL_RETURN_MSG(SKYRESULT_FAIL, "SkyTextureState::BindTexture(): Invalid texture unit.");
  }

  _pTextureUnitState[iTextureUnit].eActiveTarget = eTarget;
  _pTextureUnitState[iTextureUnit].iBoundTexture = texture.GetID();

  return SKYRESULT_OK;
}

//------------------------------------------------------------------------------
// Function     	  : SkyTextureState::SetTexture
// Description	    :
//------------------------------------------------------------------------------
/**
 * @fn SkyTextureState::SetTexture(unsigned int iTextureUnit, GLenum eTarget, unsigned int iTextureID)
 * @brief @todo <WRITE BRIEF SkyTextureState::SetTexture DOCUMENTATION>
 *
 * @todo <WRITE EXTENDED SkyTextureState::SetTexture FUNCTION DOCUMENTATION>
 */
SKYRESULT SkyTextureState::SetTexture(unsigned int iTextureUnit,
                                      GLenum       eTarget,
                                      unsigned int iTextureID)
{
  if (iTextureUnit >= s_iNumTextureUnits)
  {
    FAIL_RETURN_MSG(SKYRESULT_FAIL, "SkyTextureState::BindTexture(): Invalid texture unit.");
  }

  _pTextureUnitState[iTextureUnit].eActiveTarget = eTarget;
  _pTextureUnitState[iTextureUnit].iBoundTexture = iTextureID;

  return SKYRESULT_OK;
}

//------------------------------------------------------------------------------
// Function     	  : SkyTextureState::EnableTexture
// Description	    :
//------------------------------------------------------------------------------
/**
 * @fn SkyTextureState::EnableTexture(unsigned int iTextureUnit, bool bEnable)
 * @brief @todo <WRITE BRIEF SkyTextureState::EnableTexture DOCUMENTATION>
 *
 * @todo <WRITE EXTENDED SkyTextureState::EnableTexture FUNCTION DOCUMENTATION>
 */
SKYRESULT SkyTextureState::EnableTexture(unsigned int iTextureUnit, bool bEnable)
{
  if (iTextureUnit >= s_iNumTextureUnits)
  {
    FAIL_RETURN_MSG(SKYRESULT_FAIL, "SkyTextureState::EnableTexture(): Invalid texture unit.");
  }

  _pTextureUnitState[iTextureUnit].bEnabled = bEnable;

  return SKYRESULT_OK;
}

//------------------------------------------------------------------------------
// Function     	  : SkyTextureState::SetTextureParameter
// Description	    :
//------------------------------------------------------------------------------
/**
 * @fn SkyTextureState::SetTextureParameter(unsigned int iTextureUnit, GLenum eParameter, GLenum eMode)
 * @brief @todo <WRITE BRIEF SkyTextureState::SetTextureParameter DOCUMENTATION>
 *
 * @todo <WRITE EXTENDED SkyTextureState::SetTextureParameter FUNCTION DOCUMENTATION>
 */
SKYRESULT SkyTextureState::SetTextureParameter(unsigned int iTextureUnit,
                                               GLenum       eParameter,
                                               GLenum       eMode)
{
  if (iTextureUnit >= s_iNumTextureUnits)
  {
    FAIL_RETURN_MSG(SKYRESULT_FAIL, "SkyTextureState::SetTextureParameter(): Invalid texture unit.");
  }

  switch (eParameter)
  {
  case GL_TEXTURE_WRAP_S:
    _pTextureUnitState[iTextureUnit].eWrapMode[TexState::SKY_TEXCOORD_S] = eMode;
    break;
  case GL_TEXTURE_WRAP_T:
    _pTextureUnitState[iTextureUnit].eWrapMode[TexState::SKY_TEXCOORD_T] = eMode;
    break;
  case GL_TEXTURE_WRAP_R:
    _pTextureUnitState[iTextureUnit].eWrapMode[TexState::SKY_TEXCOORD_R] = eMode;
    break;
  case GL_TEXTURE_MIN_FILTER:
    _pTextureUnitState[iTextureUnit].eFilterMode[TexState::SKY_FILTER_MIN] = eMode;
    break;
  case GL_TEXTURE_MAG_FILTER:
    _pTextureUnitState[iTextureUnit].eFilterMode[TexState::SKY_FILTER_MAG] = eMode;
    break;
  default:
    FAIL_RETURN_MSG(SKYRESULT_FAIL, "SkyTExtureState::SetTextureParameter(): Invalid parameter.");
    break;
  }

  return SKYRESULT_OK;
}

<commit_msg>Add dynamic glMultiTextureARB detection<commit_after>
//------------------------------------------------------------------------------
// File : SkyTextureState.cpp
//------------------------------------------------------------------------------
// SkyWorks : Copyright 2002 Mark J. Harris and
//						The University of North Carolina at Chapel Hill
//------------------------------------------------------------------------------
// Permission to use, copy, modify, distribute and sell this software and its
// documentation for any purpose is hereby granted without fee, provided that
// the above copyright notice appear in all copies and that both that copyright
// notice and this permission notice appear in supporting documentation.
// Binaries may be compiled with this software without any royalties or
// restrictions.
//
// The author(s) and The University of North Carolina at Chapel Hill make no
// representations about the suitability of this software for any purpose.
// It is provided "as is" without express or
// implied warranty.
/**
 * @file SkyTextureState.cpp
 *
 * Implementation of class SkyTextureState, which encapsulates OpenGL texture state.
 */
#include "SkyTextureState.hpp"
//#include "glvu.hpp"

#include <simgear/screen/extensions.hxx>

glActiveTextureProc glActiveTexturePtr = 0;
bool glActiveTextureIsSupported = false;

//------------------------------------------------------------------------------
// Static initializations.
//------------------------------------------------------------------------------
unsigned int SkyTextureState::s_iNumTextureUnits = 0;

//------------------------------------------------------------------------------
// Function     	  : SkyTextureState::SkyTextureState
// Description	    :
//------------------------------------------------------------------------------
/**
* @fn SkyTextureState::SkyTextureState()
* @brief Constructor.
*/
SkyTextureState::SkyTextureState()
{
  if (0 == s_iNumTextureUnits)
  {
    int iNumTextureUnits = 0;
    if (SGIsOpenGLExtensionSupported("GL_ARB_multitexture")) {
       glActiveTextureIsSupported = true;

       glActiveTexturePtr = (glActiveTextureProc)
                            SGLookupFunction("glActiveTextureARB");

    }

    glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, &iNumTextureUnits);
    if (iNumTextureUnits > 0)
      s_iNumTextureUnits = iNumTextureUnits;
    else
      s_iNumTextureUnits = 1;
  }

  _pTextureUnitState = new TexState[s_iNumTextureUnits];
}

//------------------------------------------------------------------------------
// Function     	  : SkyTextureState::~SkyTextureState
// Description	    :
//------------------------------------------------------------------------------
/**
* @fn SkyTextureState::~SkyTextureState()
* @brief Destructor.
*/
SkyTextureState::~SkyTextureState()
{
  SAFE_DELETE(_pTextureUnitState);
}

//------------------------------------------------------------------------------
// Function     	  : SkyTextureState::Activate
// Description	    :
//------------------------------------------------------------------------------
/**
 * @fn SkyTextureState::Activate()
 * @brief @todo <WRITE BRIEF SkyTextureState::Activate DOCUMENTATION>
 *
 * @todo <WRITE EXTENDED SkyTextureState::Activate FUNCTION DOCUMENTATION>
 */
SKYRESULT SkyTextureState::Activate()
{
  SkyTextureState *pCurrent = GraphicsContext::InstancePtr()->GetCurrentTextureState();
  assert(NULL != pCurrent);
  //GLVU::CheckForGLError("SkyTextureState::Activate(8)");
  for (unsigned int i = 0; i < s_iNumTextureUnits; ++i)
  {
    if (glActiveTextureIsSupported && (s_iNumTextureUnits > 1))
      glActiveTexturePtr(GL_TEXTURE0_ARB + i);

    bool bEnabled = IsTextureEnabled(i);
    if (pCurrent->IsTextureEnabled(i) != bEnabled)
    {
      FAIL_RETURN(pCurrent->EnableTexture(i, bEnabled));
      //GLVU::CheckForGLError("SkyTextureState::Activate(7)");
      if (bEnabled)
        glEnable(GetActiveTarget(i));
      else
        glDisable(GetActiveTarget(i));
    }
    //GLVU::CheckForGLError("SkyTextureState::Activate(6)");
    if (bEnabled)
    {
      GLenum eTarget    = GetActiveTarget(i);
      unsigned int iID  = GetTextureID(i);
      // if ((pCurrent->GetActiveTarget(i) != eTarget) ||
      //     (pCurrent->GetTextureID(i)    != iID))
      // {
        FAIL_RETURN(pCurrent->SetTexture(i, eTarget, iID));
        glBindTexture(eTarget, iID);
      // }
      //GLVU::CheckForGLError("SkyTextureState::Activate(5)");
      GLenum paramValue = GetTextureParameter(i, GL_TEXTURE_WRAP_S);
      if (pCurrent->GetTextureParameter(i, GL_TEXTURE_WRAP_S) != paramValue)
      {
        FAIL_RETURN(pCurrent->SetTextureParameter(i, GL_TEXTURE_WRAP_S, paramValue));
        glTexParameteri(eTarget, GL_TEXTURE_WRAP_S, paramValue);
      }
      //GLVU::CheckForGLError("SkyTextureState::Activate(4)");
      paramValue = GetTextureParameter(i, GL_TEXTURE_WRAP_T);
      if (pCurrent->GetTextureParameter(i, GL_TEXTURE_WRAP_T) != paramValue)
      {
        FAIL_RETURN(pCurrent->SetTextureParameter(i, GL_TEXTURE_WRAP_T, paramValue));
        glTexParameteri(eTarget, GL_TEXTURE_WRAP_T, paramValue);
      }
      //GLVU::CheckForGLError("SkyTextureState::Activate(3)");
      paramValue = GetTextureParameter(i, GL_TEXTURE_WRAP_R);
      if (pCurrent->GetTextureParameter(i, GL_TEXTURE_WRAP_R) != paramValue)
      {
        FAIL_RETURN(pCurrent->SetTextureParameter(i, GL_TEXTURE_WRAP_R, paramValue));
        glTexParameteri(eTarget, GL_TEXTURE_WRAP_R, paramValue);
      }
      //GLVU::CheckForGLError("SkyTextureState::Activate(2)");
      paramValue = GetTextureParameter(i, GL_TEXTURE_MIN_FILTER);
      if (pCurrent->GetTextureParameter(i, GL_TEXTURE_MIN_FILTER) != paramValue)
      {
        FAIL_RETURN(pCurrent->SetTextureParameter(i, GL_TEXTURE_MIN_FILTER, paramValue));
        glTexParameteri(eTarget, GL_TEXTURE_MIN_FILTER, paramValue);
      }
       //GLVU::CheckForGLError("SkyTextureState::Activate(1)");
      paramValue = GetTextureParameter(i, GL_TEXTURE_MAG_FILTER);
      if (pCurrent->GetTextureParameter(i, GL_TEXTURE_MAG_FILTER) != paramValue)
      {
        FAIL_RETURN(pCurrent->SetTextureParameter(i, GL_TEXTURE_MAG_FILTER, paramValue));
        glTexParameteri(eTarget, GL_TEXTURE_MAG_FILTER, paramValue);
      }
      //GLVU::CheckForGLError("SkyTextureState::Activate()");
    }
    if (glActiveTextureIsSupported && (s_iNumTextureUnits > 1))
      glActiveTexturePtr(GL_TEXTURE0_ARB);
  }
  return SKYRESULT_OK;
}

//------------------------------------------------------------------------------
// Function     	  : SkyTextureState::Force
// Description	    :
//------------------------------------------------------------------------------
/**
 * @fn SkyTextureState::Force()
 * @brief @todo <WRITE BRIEF SkyTextureState::Activate DOCUMENTATION>
 *
 * @todo <WRITE EXTENDED SkyTextureState::Activate FUNCTION DOCUMENTATION>
 */
SKYRESULT SkyTextureState::Force()
{
  SkyTextureState *pCurrent = GraphicsContext::InstancePtr()->GetCurrentTextureState();
  assert(NULL != pCurrent);
  //GLVU::CheckForGLError("SkyTextureState::Activate(8)");
  for (unsigned int i = 0; i < s_iNumTextureUnits; ++i)
  {
    if (glActiveTextureIsSupported && (s_iNumTextureUnits > 1))
      glActiveTexturePtr(GL_TEXTURE0_ARB + i);

    bool bEnabled = IsTextureEnabled(i);
    FAIL_RETURN(pCurrent->EnableTexture(i, bEnabled));
    //GLVU::CheckForGLError("SkyTextureState::Activate(7)");
    if (bEnabled)
        glEnable(GetActiveTarget(i));
    else
        glDisable(GetActiveTarget(i));

    //GLVU::CheckForGLError("SkyTextureState::Activate(6)");
    GLenum eTarget    = GetActiveTarget(i);
    unsigned int iID  = GetTextureID(i);

    FAIL_RETURN(pCurrent->SetTexture(i, eTarget, iID));
    glBindTexture(eTarget, iID);

    //GLVU::CheckForGLError("SkyTextureState::Activate(5)");
    GLenum paramValue = GetTextureParameter(i, GL_TEXTURE_WRAP_S);
    FAIL_RETURN(pCurrent->SetTextureParameter(i, GL_TEXTURE_WRAP_S, paramValue));
    glTexParameteri(eTarget, GL_TEXTURE_WRAP_S, paramValue);

    //GLVU::CheckForGLError("SkyTextureState::Activate(4)");
    paramValue = GetTextureParameter(i, GL_TEXTURE_WRAP_T);
    FAIL_RETURN(pCurrent->SetTextureParameter(i, GL_TEXTURE_WRAP_T, paramValue));
    glTexParameteri(eTarget, GL_TEXTURE_WRAP_T, paramValue);

    //GLVU::CheckForGLError("SkyTextureState::Activate(3)");
    paramValue = GetTextureParameter(i, GL_TEXTURE_WRAP_R);
    FAIL_RETURN(pCurrent->SetTextureParameter(i, GL_TEXTURE_WRAP_R, paramValue));
    glTexParameteri(eTarget, GL_TEXTURE_WRAP_R, paramValue);

    //GLVU::CheckForGLError("SkyTextureState::Activate(2)");
    paramValue = GetTextureParameter(i, GL_TEXTURE_MIN_FILTER);
    FAIL_RETURN(pCurrent->SetTextureParameter(i, GL_TEXTURE_MIN_FILTER, paramValue));
    glTexParameteri(eTarget, GL_TEXTURE_MIN_FILTER, paramValue);

    //GLVU::CheckForGLError("SkyTextureState::Activate(1)");
    paramValue = GetTextureParameter(i, GL_TEXTURE_MAG_FILTER);
    FAIL_RETURN(pCurrent->SetTextureParameter(i, GL_TEXTURE_MAG_FILTER, paramValue));
    glTexParameteri(eTarget, GL_TEXTURE_MIN_FILTER, paramValue);

    if(glActiveTextureIsSupported && (s_iNumTextureUnits > 1))
      glActiveTexturePtr(GL_TEXTURE0_ARB);
  }
  return SKYRESULT_OK;
}

//------------------------------------------------------------------------------
// Function     	  : SkyTextureState::SetTexture
// Description	    :
//------------------------------------------------------------------------------
/**
 * @fn SkyTextureState::SetTexture(unsigned int iTextureUnit, GLenum eTarget, SkyTexture&  texture)
 * @brief @todo <WRITE BRIEF SkyTextureState::BindTexture DOCUMENTATION>
 *
 * @todo <WRITE EXTENDED SkyTextureState::BindTexture FUNCTION DOCUMENTATION>
 */
SKYRESULT SkyTextureState::SetTexture(unsigned int iTextureUnit,
                                      GLenum       eTarget,
                                      SkyTexture&  texture)
{
  if (iTextureUnit >= s_iNumTextureUnits)
  {
    FAIL_RETURN_MSG(SKYRESULT_FAIL, "SkyTextureState::BindTexture(): Invalid texture unit.");
  }

  _pTextureUnitState[iTextureUnit].eActiveTarget = eTarget;
  _pTextureUnitState[iTextureUnit].iBoundTexture = texture.GetID();

  return SKYRESULT_OK;
}

//------------------------------------------------------------------------------
// Function     	  : SkyTextureState::SetTexture
// Description	    :
//------------------------------------------------------------------------------
/**
 * @fn SkyTextureState::SetTexture(unsigned int iTextureUnit, GLenum eTarget, unsigned int iTextureID)
 * @brief @todo <WRITE BRIEF SkyTextureState::SetTexture DOCUMENTATION>
 *
 * @todo <WRITE EXTENDED SkyTextureState::SetTexture FUNCTION DOCUMENTATION>
 */
SKYRESULT SkyTextureState::SetTexture(unsigned int iTextureUnit,
                                      GLenum       eTarget,
                                      unsigned int iTextureID)
{
  if (iTextureUnit >= s_iNumTextureUnits)
  {
    FAIL_RETURN_MSG(SKYRESULT_FAIL, "SkyTextureState::BindTexture(): Invalid texture unit.");
  }

  _pTextureUnitState[iTextureUnit].eActiveTarget = eTarget;
  _pTextureUnitState[iTextureUnit].iBoundTexture = iTextureID;

  return SKYRESULT_OK;
}

//------------------------------------------------------------------------------
// Function     	  : SkyTextureState::EnableTexture
// Description	    :
//------------------------------------------------------------------------------
/**
 * @fn SkyTextureState::EnableTexture(unsigned int iTextureUnit, bool bEnable)
 * @brief @todo <WRITE BRIEF SkyTextureState::EnableTexture DOCUMENTATION>
 *
 * @todo <WRITE EXTENDED SkyTextureState::EnableTexture FUNCTION DOCUMENTATION>
 */
SKYRESULT SkyTextureState::EnableTexture(unsigned int iTextureUnit, bool bEnable)
{
  if (iTextureUnit >= s_iNumTextureUnits)
  {
    FAIL_RETURN_MSG(SKYRESULT_FAIL, "SkyTextureState::EnableTexture(): Invalid texture unit.");
  }

  _pTextureUnitState[iTextureUnit].bEnabled = bEnable;

  return SKYRESULT_OK;
}

//------------------------------------------------------------------------------
// Function     	  : SkyTextureState::SetTextureParameter
// Description	    :
//------------------------------------------------------------------------------
/**
 * @fn SkyTextureState::SetTextureParameter(unsigned int iTextureUnit, GLenum eParameter, GLenum eMode)
 * @brief @todo <WRITE BRIEF SkyTextureState::SetTextureParameter DOCUMENTATION>
 *
 * @todo <WRITE EXTENDED SkyTextureState::SetTextureParameter FUNCTION DOCUMENTATION>
 */
SKYRESULT SkyTextureState::SetTextureParameter(unsigned int iTextureUnit,
                                               GLenum       eParameter,
                                               GLenum       eMode)
{
  if (iTextureUnit >= s_iNumTextureUnits)
  {
    FAIL_RETURN_MSG(SKYRESULT_FAIL, "SkyTextureState::SetTextureParameter(): Invalid texture unit.");
  }

  switch (eParameter)
  {
  case GL_TEXTURE_WRAP_S:
    _pTextureUnitState[iTextureUnit].eWrapMode[TexState::SKY_TEXCOORD_S] = eMode;
    break;
  case GL_TEXTURE_WRAP_T:
    _pTextureUnitState[iTextureUnit].eWrapMode[TexState::SKY_TEXCOORD_T] = eMode;
    break;
  case GL_TEXTURE_WRAP_R:
    _pTextureUnitState[iTextureUnit].eWrapMode[TexState::SKY_TEXCOORD_R] = eMode;
    break;
  case GL_TEXTURE_MIN_FILTER:
    _pTextureUnitState[iTextureUnit].eFilterMode[TexState::SKY_FILTER_MIN] = eMode;
    break;
  case GL_TEXTURE_MAG_FILTER:
    _pTextureUnitState[iTextureUnit].eFilterMode[TexState::SKY_FILTER_MAG] = eMode;
    break;
  default:
    FAIL_RETURN_MSG(SKYRESULT_FAIL, "SkyTExtureState::SetTextureParameter(): Invalid parameter.");
    break;
  }

  return SKYRESULT_OK;
}

<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2013-2020 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include "data_cache.hpp"

using namespace budget;

std::vector<earning> & data_cache::earnings() {
    if (earnings_.empty()) {
        earnings_ = all_earnings();
    }

    return earnings_;
}

std::vector<debt> & data_cache::debts() {
    if (debts_.empty()) {
        debts_ = all_debts();
    }

    return debts_;
}

std::vector<fortune> & data_cache::fortunes() {
    if (fortunes_.empty()) {
        fortunes_ = all_fortunes();
    }

    return fortunes_;
}

std::vector<asset_value> & data_cache::asset_values() {
    if (asset_values_.empty()) {
        asset_values_ = all_asset_values();
    }

    return asset_values_;
}

std::vector<asset_value> & data_cache::sorted_asset_values() {
    if (sorted_asset_values_.empty()) {
        sorted_asset_values_ = all_asset_values();

        std::sort(sorted_asset_values_.begin(), sorted_asset_values_.end(), [](auto& lhs, auto& rhs) {
            return lhs.set_date < rhs.set_date;
        });
    }

    return sorted_asset_values_;
}

std::unordered_map<size_t, std::vector<asset_value>> & data_cache::sorted_group_asset_values() {
    if (sorted_group_asset_values_.empty()) {
        for (auto & asset_value : sorted_asset_values()) {
            sorted_group_asset_values_[asset_value.asset_id].push_back(asset_value);
        }
    }

    return sorted_group_asset_values_;
}

std::vector<liability> & data_cache::liabilities() {
    if (liabilities_.empty()) {
        liabilities_ = all_liabilities();
    }

    return liabilities_;
}

std::vector<recurring> & data_cache::recurrings() {
    if (recurrings_.empty()) {
        recurrings_ = all_recurrings();
    }

    return recurrings_;
}

std::vector<income> & data_cache::incomes() {
    if (incomes_.empty()) {
        incomes_ = all_incomes();
    }

    return incomes_;
}

std::vector<account> & data_cache::accounts() {
    if (accounts_.empty()) {
        accounts_ = all_accounts();
    }

    return accounts_;
}

std::vector<asset_share> & data_cache::asset_shares() {
    if (asset_shares_.empty()) {
        asset_shares_ = all_asset_shares();
    }

    return asset_shares_;
}

std::vector<asset_class> & data_cache::asset_classes() {
    if (asset_classes_.empty()) {
        asset_classes_ = all_asset_classes();
    }

    return asset_classes_;
}

std::vector<objective> & data_cache::objectives() {
    if (objectives_.empty()) {
        objectives_ = all_objectives();
    }

    return objectives_;
}

std::vector<expense> & data_cache::expenses() {
    if (expenses_.empty()) {
        expenses_ = all_expenses();
    }

    return expenses_;
}

std::vector<expense> & data_cache::sorted_expenses() {
    if (sorted_expenses_.empty()) {
        sorted_expenses_ = all_expenses();

        std::sort(sorted_expenses_.begin(), sorted_expenses_.end(), [](auto& lhs, auto& rhs) {
            return lhs.date < rhs.date;
        });
    }

    return sorted_expenses_;
}

std::vector<asset> & data_cache::assets() {
    if (assets_.empty()) {
        assets_ = all_assets();
    }

    return assets_;
}

std::vector<asset> & data_cache::user_assets() {
    if (user_assets_.empty()) {
        for (auto & asset : assets()) {
            if (asset.name != "DESIRED") {
                user_assets_.push_back(asset);
            }
        }
    }

    return user_assets_;
}

std::vector<wish> & data_cache::wishes() {
    if (wishes_.empty()) {
        wishes_ = all_wishes();
    }

    return wishes_;
}

<commit_msg>Fix bug with asset values order<commit_after>//=======================================================================
// Copyright (c) 2013-2020 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include "data_cache.hpp"

using namespace budget;

std::vector<earning> & data_cache::earnings() {
    if (earnings_.empty()) {
        earnings_ = all_earnings();
    }

    return earnings_;
}

std::vector<debt> & data_cache::debts() {
    if (debts_.empty()) {
        debts_ = all_debts();
    }

    return debts_;
}

std::vector<fortune> & data_cache::fortunes() {
    if (fortunes_.empty()) {
        fortunes_ = all_fortunes();
    }

    return fortunes_;
}

std::vector<asset_value> & data_cache::asset_values() {
    if (asset_values_.empty()) {
        asset_values_ = all_asset_values();
    }

    return asset_values_;
}

std::vector<asset_value> & data_cache::sorted_asset_values() {
    if (sorted_asset_values_.empty()) {
        sorted_asset_values_ = all_asset_values();

        std::stable_sort(sorted_asset_values_.begin(), sorted_asset_values_.end(), [](auto& lhs, auto& rhs) {
            return lhs.set_date < rhs.set_date;
        });
    }

    return sorted_asset_values_;
}

std::unordered_map<size_t, std::vector<asset_value>> & data_cache::sorted_group_asset_values() {
    if (sorted_group_asset_values_.empty()) {
        for (auto & asset_value : sorted_asset_values()) {
            sorted_group_asset_values_[asset_value.asset_id].push_back(asset_value);
        }
    }

    return sorted_group_asset_values_;
}

std::vector<liability> & data_cache::liabilities() {
    if (liabilities_.empty()) {
        liabilities_ = all_liabilities();
    }

    return liabilities_;
}

std::vector<recurring> & data_cache::recurrings() {
    if (recurrings_.empty()) {
        recurrings_ = all_recurrings();
    }

    return recurrings_;
}

std::vector<income> & data_cache::incomes() {
    if (incomes_.empty()) {
        incomes_ = all_incomes();
    }

    return incomes_;
}

std::vector<account> & data_cache::accounts() {
    if (accounts_.empty()) {
        accounts_ = all_accounts();
    }

    return accounts_;
}

std::vector<asset_share> & data_cache::asset_shares() {
    if (asset_shares_.empty()) {
        asset_shares_ = all_asset_shares();
    }

    return asset_shares_;
}

std::vector<asset_class> & data_cache::asset_classes() {
    if (asset_classes_.empty()) {
        asset_classes_ = all_asset_classes();
    }

    return asset_classes_;
}

std::vector<objective> & data_cache::objectives() {
    if (objectives_.empty()) {
        objectives_ = all_objectives();
    }

    return objectives_;
}

std::vector<expense> & data_cache::expenses() {
    if (expenses_.empty()) {
        expenses_ = all_expenses();
    }

    return expenses_;
}

std::vector<expense> & data_cache::sorted_expenses() {
    if (sorted_expenses_.empty()) {
        sorted_expenses_ = all_expenses();

        std::sort(sorted_expenses_.begin(), sorted_expenses_.end(), [](auto& lhs, auto& rhs) {
            return lhs.date < rhs.date;
        });
    }

    return sorted_expenses_;
}

std::vector<asset> & data_cache::assets() {
    if (assets_.empty()) {
        assets_ = all_assets();
    }

    return assets_;
}

std::vector<asset> & data_cache::user_assets() {
    if (user_assets_.empty()) {
        for (auto & asset : assets()) {
            if (asset.name != "DESIRED") {
                user_assets_.push_back(asset);
            }
        }
    }

    return user_assets_;
}

std::vector<wish> & data_cache::wishes() {
    if (wishes_.empty()) {
        wishes_ = all_wishes();
    }

    return wishes_;
}

<|endoftext|>