<commit_before>#ifndef CWRAPPER_HPP_INCLUDED
#define CWRAPPER_HPP_INCLUDED

#define HAS_STATIC_MEMBER_DETECTOR(member)                                  \
template<typename T>                                                        \
class HAS_STATIC_MEMBER_DETECTOR_CLASS_ ## member                           \
{                                                                           \
    struct two_ints_type { int two_ints_1, two_ints_2; };                   \
    template<typename U>                                                    \
    static two_ints_type has_func_helper(...) { }                           \
    template<typename U>                                                    \
    static int has_func_helper(int, decltype(U::member)* func = nullptr)    \
    { return 0; }                                                           \
public:                                                                     \
    static constexpr bool value =                                           \
        sizeof(decltype(has_func_helper<T>(0))) == sizeof(int);             \
}

#define HAS_STATIC_MEMBER(type, member)                                     \
    (HAS_STATIC_MEMBER_DETECTOR_CLASS_ ## member<type>::value)

enum class CWrapperType
{
    Implicit,
    Explicit,
    Get,
};

template<
    typename H,
    typename F,
    CWrapperType TY,
    bool C,
    typename E>
class __CWrapperHelper__
{

template<
    typename HANDLE_T,
    typename BASE,
    bool CONSTSAFE>
struct ArrowHandler
{ };

template<
    typename PTR_T,
    typename BASE>
struct ArrowHandler<PTR_T*, BASE, false>
{
    PTR_T* operator->() const
    {   return static_cast<BASE*>(this)->ptr; }
};

template<
    typename PTR_T,
    typename BASE>
struct ArrowHandler<PTR_T*, BASE, true>
{
    PTR_T* operator->()
    {   return static_cast<BASE*>(this)->ptr; }
    PTR_T const* operator->() const
    {   return static_cast<BASE*>(this)->ptr; }
};

template<
    typename HANDLE_T,
    typename BASE,
    CWrapperType TYPE,
    bool CONSTSAFE>
struct ConversionHandler : public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{ };

template<
    typename HANDLE_T,
    typename BASE,
    bool CONSTSAFE>
struct ConversionHandler<HANDLE_T, BASE, CWrapperType::Implicit, CONSTSAFE>
    : public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{
    operator HANDLE_T() const
    {   return static_cast<BASE*>(this)->ptr; }
};
template<
    typename HANDLE_T,
    typename BASE,
    bool CONSTSAFE>
struct ConversionHandler<HANDLE_T, BASE, CWrapperType::Explicit, CONSTSAFE>
    : public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{
    explicit operator HANDLE_T() const
    {   return static_cast<BASE*>(this)->ptr; }
};
template<
    typename HANDLE_T,
    typename BASE,
    bool CONSTSAFE>
struct ConversionHandler<HANDLE_T, BASE, CWrapperType::Get, CONSTSAFE>
    : public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{
    HANDLE_T get() const
    {   return static_cast<BASE*>(this)->ptr; }
};

template<
    typename PTR_T,
    typename BASE>
struct ConversionHandler<PTR_T*, BASE, CWrapperType::Implicit, true>
    : public ArrowHandler<PTR_T*, BASE, true>
{
    operator PTR_T*()
    {   return static_cast<BASE*>(this)->ptr; }
    operator PTR_T const*() const
    {   return static_cast<BASE*>(this)->ptr; }
};
template<
    typename PTR_T,
    typename BASE>
struct ConversionHandler<PTR_T*, BASE, CWrapperType::Explicit, true>
    : public ArrowHandler<PTR_T*, BASE, true>
{
    explicit operator PTR_T*()
    {   return static_cast<BASE*>(this)->ptr; }
    explicit operator PTR_T const*() const
    {   return static_cast<BASE*>(this)->ptr; }
};
template<
    typename PTR_T,
    typename BASE>
struct ConversionHandler<PTR_T*, BASE, CWrapperType::Get, true>
    : public ArrowHandler<PTR_T*, BASE, true>
{
    PTR_T* get()
    {   return static_cast<BASE*>(this)->ptr; }
    PTR_T const* get() const
    {   return static_cast<BASE*>(this)->ptr; }
};

template<
    typename HANDLE_T,
    typename FUNCTIONS,
    CWrapperType TYPE,
    bool CONSTSAFE,
    typename EXCEPTION_T>
class CWrapperBase
    : public ConversionHandler<
        HANDLE_T,
        CWrapperBase<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T>,
        TYPE,
        CONSTSAFE>
{
    friend class ConversionHandler<
        HANDLE_T,
        CWrapperBase<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T>,
        TYPE,
        CONSTSAFE>;
protected:
    HANDLE_T ptr;

public:

    explicit CWrapperBase(HANDLE_T ptr) :
        ptr{ptr}
    {
        if(!ptr)
            throw EXCEPTION_T{};
    }

    CWrapperBase(CWrapperBase const& other) :
        CWrapperBase{FUNCTIONS::copy_func(other.ptr)}
    { }

    // This one is needed to prevent variadic ctor to be called
    // when you want to copy a non-const object.
    CWrapperBase(CWrapperBase& other) :
        CWrapperBase{FUNCTIONS::copy_func(other.ptr)}
    { }

    template<typename... ARGS>
    explicit CWrapperBase(ARGS&&... args) :
        CWrapperBase{FUNCTIONS::ctor_func(std::forward<ARGS>(args)...)}
    { }

    CWrapperBase(CWrapperBase&& old) :
        CWrapperBase{old.ptr}
    {
        old.ptr = 0;
    }

    CWrapperBase& operator=(CWrapperBase&& old)
    {
        if(this != &old)
        {
            FUNCTIONS::dtor_func(ptr);
            ptr = old.ptr;
            old.ptr = 0;
        }
        return *this;
    }

    ~CWrapperBase()
    {
        FUNCTIONS::dtor_func(ptr);
    }

    CWrapperBase& operator=(CWrapperBase const& other)
    {
        if(this != &other)
        {
            HANDLE_T new_ptr = FUNCTIONS::copy_func(other.ptr);
            if(!new_ptr)
                throw EXCEPTION_T{};

            FUNCTIONS::dtor_func(ptr);
            ptr = new_ptr;
        }
        return *this;
    }
};

template<
    typename HANDLE_T,
    typename FUNCTIONS,
    CWrapperType TYPE,
    bool CONSTSAFE,
    typename EXCEPTION_T>
class CWrapperNonCopiable
    : public ConversionHandler<
        HANDLE_T,
        CWrapperNonCopiable<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T>,
        TYPE,
        CONSTSAFE>
{
    friend class ConversionHandler<
        HANDLE_T,
        CWrapperNonCopiable<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T>,
        TYPE,
        CONSTSAFE>;

protected:
    HANDLE_T ptr;

public:

    explicit CWrapperNonCopiable(HANDLE_T ptr) :
        ptr{ptr}
    {
        if(!ptr)
            throw EXCEPTION_T{};
    }

    template<typename... ARGS>
    explicit CWrapperNonCopiable(ARGS&&... args) :
        CWrapperNonCopiable{FUNCTIONS::ctor_func(std::forward<ARGS>(args)...)}
    { }

    CWrapperNonCopiable(CWrapperNonCopiable&& old) :
        CWrapperNonCopiable{old.ptr}
    {
        old.ptr = 0;
    }

    CWrapperNonCopiable& operator=(CWrapperNonCopiable&& old)
    {
        if(this != &old)
        {
            FUNCTIONS::dtor_func(ptr);
            ptr = old.ptr;
            old.ptr = 0;
        }
        return *this;
    }

    ~CWrapperNonCopiable()
    {
        FUNCTIONS::dtor_func(ptr);
    }

    // This one is needed to prevent variadic ctor to be called
    // when you want to copy a non-const object.
    CWrapperNonCopiable(CWrapperNonCopiable& other) = delete;
    CWrapperNonCopiable(CWrapperNonCopiable const& other) = delete;
    CWrapperNonCopiable& operator=(CWrapperNonCopiable const& other) = delete;
};

template<bool condition, typename TRUE_TYPE, typename FALSE_TYPE>
struct COND
{
    using type = TRUE_TYPE;
};

template<typename TRUE_TYPE, typename FALSE_TYPE>
struct COND<false, TRUE_TYPE, FALSE_TYPE>
{
    using type = FALSE_TYPE;
};

HAS_STATIC_MEMBER_DETECTOR(copy_func);

public:

    using type = typename COND< HAS_STATIC_MEMBER(F, copy_func),
        CWrapperBase<H, F, TY, C, E>,
        CWrapperNonCopiable<H, F, TY, C, E>>::type;
};

template<
    typename HANDLE_T,
    typename FUNCTIONS,
    CWrapperType TYPE = CWrapperType::Get,
    bool CONSTSAFE = true,
    typename EXCEPTION_T = std::bad_alloc>
using CWrapper = typename __CWrapperHelper__<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T>::type;

#endif // CWRAPPER_HPP_INCLUDED
<commit_msg>Exception as nested class<commit_after>#ifndef CWRAPPER_HPP_INCLUDED
#define CWRAPPER_HPP_INCLUDED

#define HAS_STATIC_MEMBER_DETECTOR(member)                                  \
template<typename T>                                                        \
class HAS_STATIC_MEMBER_DETECTOR_CLASS_ ## member                           \
{                                                                           \
    struct two_ints_type { int two_ints_1, two_ints_2; };                   \
    template<typename U>                                                    \
    static two_ints_type has_func_helper(...) { }                           \
    template<typename U>                                                    \
    static int has_func_helper(int, decltype(U::member)* func = nullptr)    \
    { return 0; }                                                           \
public:                                                                     \
    static constexpr bool value =                                           \
        sizeof(decltype(has_func_helper<T>(0))) == sizeof(int);             \
}

#define HAS_STATIC_MEMBER(type, member)                                     \
    (HAS_STATIC_MEMBER_DETECTOR_CLASS_ ## member<type>::value)

#define HAS_NESTED_TYPE_DETECTOR(member)                                    \
template<typename T>                                                        \
class HAS_NESTED_TYPE_DETECTOR_CLASS_ ## member                             \
{                                                                           \
    struct two_ints_type { int two_ints_1, two_ints_2; };                   \
    template<typename U>                                                    \
    static two_ints_type has_func_helper(...) { }                           \
    template<typename U>                                                    \
    static int has_func_helper(int, typename U::member* ty = nullptr)       \
    { return 0; }                                                           \
public:                                                                     \
    static constexpr bool value =                                           \
        sizeof(decltype(has_func_helper<T>(0))) == sizeof(int);             \
}

#define HAS_NESTED_TYPE(type, member)                                       \
    (HAS_NESTED_TYPE_DETECTOR_CLASS_ ## member<type>::value)

enum class CWrapperType
{
    Implicit,
    Explicit,
    Get,
};

template<
    typename H,
    typename F,
    CWrapperType TY,
    bool C>
class __CWrapperHelper__
{

template<
    typename HANDLE_T,
    typename BASE,
    bool CONSTSAFE>
struct ArrowHandler
{ };

template<
    typename PTR_T,
    typename BASE>
struct ArrowHandler<PTR_T*, BASE, false>
{
    PTR_T* operator->() const
    {   return static_cast<BASE*>(this)->ptr; }
};

template<
    typename PTR_T,
    typename BASE>
struct ArrowHandler<PTR_T*, BASE, true>
{
    PTR_T* operator->()
    {   return static_cast<BASE*>(this)->ptr; }
    PTR_T const* operator->() const
    {   return static_cast<BASE*>(this)->ptr; }
};

template<
    typename HANDLE_T,
    typename BASE,
    CWrapperType TYPE,
    bool CONSTSAFE>
struct ConversionHandler : public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{ };

template<
    typename HANDLE_T,
    typename BASE,
    bool CONSTSAFE>
struct ConversionHandler<HANDLE_T, BASE, CWrapperType::Implicit, CONSTSAFE>
    : public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{
    operator HANDLE_T() const
    {   return static_cast<BASE*>(this)->ptr; }
};
template<
    typename HANDLE_T,
    typename BASE,
    bool CONSTSAFE>
struct ConversionHandler<HANDLE_T, BASE, CWrapperType::Explicit, CONSTSAFE>
    : public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{
    explicit operator HANDLE_T() const
    {   return static_cast<BASE*>(this)->ptr; }
};
template<
    typename HANDLE_T,
    typename BASE,
    bool CONSTSAFE>
struct ConversionHandler<HANDLE_T, BASE, CWrapperType::Get, CONSTSAFE>
    : public ArrowHandler<HANDLE_T, BASE, CONSTSAFE>
{
    HANDLE_T get() const
    {   return static_cast<BASE*>(this)->ptr; }
};

template<
    typename PTR_T,
    typename BASE>
struct ConversionHandler<PTR_T*, BASE, CWrapperType::Implicit, true>
    : public ArrowHandler<PTR_T*, BASE, true>
{
    operator PTR_T*()
    {   return static_cast<BASE*>(this)->ptr; }
    operator PTR_T const*() const
    {   return static_cast<BASE*>(this)->ptr; }
};
template<
    typename PTR_T,
    typename BASE>
struct ConversionHandler<PTR_T*, BASE, CWrapperType::Explicit, true>
    : public ArrowHandler<PTR_T*, BASE, true>
{
    explicit operator PTR_T*()
    {   return static_cast<BASE*>(this)->ptr; }
    explicit operator PTR_T const*() const
    {   return static_cast<BASE*>(this)->ptr; }
};
template<
    typename PTR_T,
    typename BASE>
struct ConversionHandler<PTR_T*, BASE, CWrapperType::Get, true>
    : public ArrowHandler<PTR_T*, BASE, true>
{
    PTR_T* get()
    {   return static_cast<BASE*>(this)->ptr; }
    PTR_T const* get() const
    {   return static_cast<BASE*>(this)->ptr; }
};

template<
    typename HANDLE_T,
    typename FUNCTIONS,
    CWrapperType TYPE,
    bool CONSTSAFE,
    typename EXCEPTION_T>
class CWrapperBase
    : public ConversionHandler<
        HANDLE_T,
        CWrapperBase<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T>,
        TYPE,
        CONSTSAFE>
{
    friend class ConversionHandler<
        HANDLE_T,
        CWrapperBase<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T>,
        TYPE,
        CONSTSAFE>;
protected:
    HANDLE_T ptr;

public:

    explicit CWrapperBase(HANDLE_T ptr) :
        ptr{ptr}
    {
        if(!ptr)
            throw EXCEPTION_T{};
    }

    CWrapperBase(CWrapperBase const& other) :
        CWrapperBase{FUNCTIONS::copy_func(other.ptr)}
    { }

    // This one is needed to prevent variadic ctor to be called
    // when you want to copy a non-const object.
    CWrapperBase(CWrapperBase& other) :
        CWrapperBase{FUNCTIONS::copy_func(other.ptr)}
    { }

    template<typename... ARGS>
    explicit CWrapperBase(ARGS&&... args) :
        CWrapperBase{FUNCTIONS::ctor_func(std::forward<ARGS>(args)...)}
    { }

    CWrapperBase(CWrapperBase&& old) :
        CWrapperBase{old.ptr}
    {
        old.ptr = 0;
    }

    CWrapperBase& operator=(CWrapperBase&& old)
    {
        if(this != &old)
        {
            FUNCTIONS::dtor_func(ptr);
            ptr = old.ptr;
            old.ptr = 0;
        }
        return *this;
    }

    ~CWrapperBase()
    {
        FUNCTIONS::dtor_func(ptr);
    }

    CWrapperBase& operator=(CWrapperBase const& other)
    {
        if(this != &other)
        {
            HANDLE_T new_ptr = FUNCTIONS::copy_func(other.ptr);
            if(!new_ptr)
                throw EXCEPTION_T{};

            FUNCTIONS::dtor_func(ptr);
            ptr = new_ptr;
        }
        return *this;
    }
};

template<
    typename HANDLE_T,
    typename FUNCTIONS,
    CWrapperType TYPE,
    bool CONSTSAFE,
    typename EXCEPTION_T>
class CWrapperNonCopiable
    : public ConversionHandler<
        HANDLE_T,
        CWrapperNonCopiable<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T>,
        TYPE,
        CONSTSAFE>
{
    friend class ConversionHandler<
        HANDLE_T,
        CWrapperNonCopiable<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE, EXCEPTION_T>,
        TYPE,
        CONSTSAFE>;

protected:
    HANDLE_T ptr;

public:

    explicit CWrapperNonCopiable(HANDLE_T ptr) :
        ptr{ptr}
    {
        if(!ptr)
            throw EXCEPTION_T{};
    }

    template<typename... ARGS>
    explicit CWrapperNonCopiable(ARGS&&... args) :
        CWrapperNonCopiable{FUNCTIONS::ctor_func(std::forward<ARGS>(args)...)}
    { }

    CWrapperNonCopiable(CWrapperNonCopiable&& old) :
        CWrapperNonCopiable{old.ptr}
    {
        old.ptr = 0;
    }

    CWrapperNonCopiable& operator=(CWrapperNonCopiable&& old)
    {
        if(this != &old)
        {
            FUNCTIONS::dtor_func(ptr);
            ptr = old.ptr;
            old.ptr = 0;
        }
        return *this;
    }

    ~CWrapperNonCopiable()
    {
        FUNCTIONS::dtor_func(ptr);
    }

    // This one is needed to prevent variadic ctor to be called
    // when you want to copy a non-const object.
    CWrapperNonCopiable(CWrapperNonCopiable& other) = delete;
    CWrapperNonCopiable(CWrapperNonCopiable const& other) = delete;
    CWrapperNonCopiable& operator=(CWrapperNonCopiable const& other) = delete;
};

template<bool condition, typename TRUE_TYPE, typename FALSE_TYPE>
struct COND
{
    using type = TRUE_TYPE;
};

template<typename TRUE_TYPE, typename FALSE_TYPE>
struct COND<false, TRUE_TYPE, FALSE_TYPE>
{
    using type = FALSE_TYPE;
};

HAS_NESTED_TYPE_DETECTOR(exception);
HAS_STATIC_MEMBER_DETECTOR(copy_func);

template<typename TYPE, typename DEFTYPE, bool>
struct default_exception_type
{
    using type = DEFTYPE;
};

template<typename TYPE, typename DEFTYPE>
struct default_exception_type<TYPE, DEFTYPE, true>
{
    using type = typename TYPE::exception;
};

using E = typename default_exception_type<F, std::bad_alloc, HAS_NESTED_TYPE(F, exception)>::type;

public:

    using type = typename COND< HAS_STATIC_MEMBER(F, copy_func),
        CWrapperBase<H, F, TY, C, E>,
        CWrapperNonCopiable<H, F, TY, C, E>>::type;
};

template<
    typename HANDLE_T,
    typename FUNCTIONS,
    CWrapperType TYPE = CWrapperType::Get,
    bool CONSTSAFE = true>
using CWrapper = typename __CWrapperHelper__<HANDLE_T, FUNCTIONS, TYPE, CONSTSAFE>::type;

#endif // CWRAPPER_HPP_INCLUDED
<|endoftext|>


<commit_before><commit_msg>Adding the missing argument for POIs<commit_after><|endoftext|>


<commit_before>#include "Iop_Thevent.h"
#include "IopBios.h"
#include "../Log.h"

using namespace Iop;

#define LOG_NAME ("iop_thevent")

#define FUNCTION_CREATEEVENTFLAG			"CreateEventFlag"
#define FUNCTION_SETEVENTFLAG				"SetEventFlag"
#define FUNCTION_ISETEVENTFLAG				"iSetEventFlag"
#define FUNCTION_CLEAREVENTFLAG				"ClearEventFlag"
#define FUNCTION_WAITEVENTFLAG				"WaitEventFlag"
#define FUNCTION_REFEREVENTFLAGSTATUS		"ReferEventFlagStatus"

CThevent::CThevent(CIopBios& bios, uint8* ram)
: m_bios(bios)
, m_ram(ram)
{

}

CThevent::~CThevent()
{

}

std::string CThevent::GetId() const
{
	return "thevent";
}

std::string CThevent::GetFunctionName(unsigned int functionId) const
{
	switch(functionId)
	{
	case 4:
		return FUNCTION_CREATEEVENTFLAG;
		break;
	case 6:
		return FUNCTION_SETEVENTFLAG;
		break;
	case 7:
		return FUNCTION_ISETEVENTFLAG;
		break;
	case 8:
		return FUNCTION_CLEAREVENTFLAG;
		break;
	case 10:
		return FUNCTION_WAITEVENTFLAG;
		break;
	case 13:
		return FUNCTION_REFEREVENTFLAGSTATUS;
		break;
	default:
		return "unknown";
		break;
	}
}

void CThevent::Invoke(CMIPS& context, unsigned int functionId)
{
	switch(functionId)
	{
	case 4:
		context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(CreateEventFlag(
			reinterpret_cast<EVENT*>(&m_ram[context.m_State.nGPR[CMIPS::A0].nV0])
			));
		break;
	case 6:
		context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(SetEventFlag(
			context.m_State.nGPR[CMIPS::A0].nV0,
			context.m_State.nGPR[CMIPS::A1].nV0
			));
		break;
	case 7:
		context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(iSetEventFlag(
			context.m_State.nGPR[CMIPS::A0].nV0,
			context.m_State.nGPR[CMIPS::A1].nV0
			));
		break;
	case 8:
		context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(ClearEventFlag(
			context.m_State.nGPR[CMIPS::A0].nV0,
			context.m_State.nGPR[CMIPS::A1].nV0
			));
		break;
	case 10:
		context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(WaitEventFlag(
			context.m_State.nGPR[CMIPS::A0].nV0,
			context.m_State.nGPR[CMIPS::A1].nV0,
			context.m_State.nGPR[CMIPS::A2].nV0,
			context.m_State.nGPR[CMIPS::A3].nV0
			));
		break;
	case 13:
		context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(ReferEventFlagStatus(
			context.m_State.nGPR[CMIPS::A0].nV0,
			context.m_State.nGPR[CMIPS::A1].nV0
			));
		break;
	default:
		CLog::GetInstance().Print(LOG_NAME, "Unknown function (%d) called (%0.8X).\r\n", functionId, context.m_State.nPC);
		break;
	}
}

uint32 CThevent::CreateEventFlag(EVENT* eventPtr)
{
	return m_bios.CreateEventFlag(eventPtr->attributes, eventPtr->options, eventPtr->initValue);
}

uint32 CThevent::SetEventFlag(uint32 eventId, uint32 bits)
{
	return m_bios.SetEventFlag(eventId, bits, false);
}

uint32 CThevent::iSetEventFlag(uint32 eventId, uint32 bits)
{
	return m_bios.SetEventFlag(eventId, bits, true);
}

uint32 CThevent::ClearEventFlag(uint32 eventId, uint32 bits)
{
	return m_bios.ClearEventFlag(eventId, bits);
}

uint32 CThevent::WaitEventFlag(uint32 eventId, uint32 bits, uint32 mode, uint32 resultPtr)
{
	return m_bios.WaitEventFlag(eventId, bits, mode, resultPtr);
}

uint32 CThevent::ReferEventFlagStatus(uint32 eventId, uint32 infoPtr)
{
	return m_bios.ReferEventFlagStatus(eventId, infoPtr);
}
<commit_msg>Added iReferEventFlagStatus<commit_after>#include "Iop_Thevent.h"
#include "IopBios.h"
#include "../Log.h"

using namespace Iop;

#define LOG_NAME ("iop_thevent")

#define FUNCTION_CREATEEVENTFLAG			"CreateEventFlag"
#define FUNCTION_SETEVENTFLAG				"SetEventFlag"
#define FUNCTION_ISETEVENTFLAG				"iSetEventFlag"
#define FUNCTION_CLEAREVENTFLAG				"ClearEventFlag"
#define FUNCTION_WAITEVENTFLAG				"WaitEventFlag"
#define FUNCTION_REFEREVENTFLAGSTATUS		"ReferEventFlagStatus"
#define FUNCTION_IREFEREVENTFLAGSTATUS		"iReferEventFlagStatus"

CThevent::CThevent(CIopBios& bios, uint8* ram)
: m_bios(bios)
, m_ram(ram)
{

}

CThevent::~CThevent()
{

}

std::string CThevent::GetId() const
{
	return "thevent";
}

std::string CThevent::GetFunctionName(unsigned int functionId) const
{
	switch(functionId)
	{
	case 4:
		return FUNCTION_CREATEEVENTFLAG;
		break;
	case 6:
		return FUNCTION_SETEVENTFLAG;
		break;
	case 7:
		return FUNCTION_ISETEVENTFLAG;
		break;
	case 8:
		return FUNCTION_CLEAREVENTFLAG;
		break;
	case 10:
		return FUNCTION_WAITEVENTFLAG;
		break;
	case 13:
		return FUNCTION_REFEREVENTFLAGSTATUS;
		break;
	case 14:
		return FUNCTION_IREFEREVENTFLAGSTATUS;
		break;
	default:
		return "unknown";
		break;
	}
}

void CThevent::Invoke(CMIPS& context, unsigned int functionId)
{
	switch(functionId)
	{
	case 4:
		context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(CreateEventFlag(
			reinterpret_cast<EVENT*>(&m_ram[context.m_State.nGPR[CMIPS::A0].nV0])
			));
		break;
	case 6:
		context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(SetEventFlag(
			context.m_State.nGPR[CMIPS::A0].nV0,
			context.m_State.nGPR[CMIPS::A1].nV0
			));
		break;
	case 7:
		context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(iSetEventFlag(
			context.m_State.nGPR[CMIPS::A0].nV0,
			context.m_State.nGPR[CMIPS::A1].nV0
			));
		break;
	case 8:
		context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(ClearEventFlag(
			context.m_State.nGPR[CMIPS::A0].nV0,
			context.m_State.nGPR[CMIPS::A1].nV0
			));
		break;
	case 10:
		context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(WaitEventFlag(
			context.m_State.nGPR[CMIPS::A0].nV0,
			context.m_State.nGPR[CMIPS::A1].nV0,
			context.m_State.nGPR[CMIPS::A2].nV0,
			context.m_State.nGPR[CMIPS::A3].nV0
			));
		break;
	case 13:
	case 14:
		context.m_State.nGPR[CMIPS::V0].nD0 = static_cast<int32>(ReferEventFlagStatus(
			context.m_State.nGPR[CMIPS::A0].nV0,
			context.m_State.nGPR[CMIPS::A1].nV0
			));
		break;
	default:
		CLog::GetInstance().Print(LOG_NAME, "Unknown function (%d) called (%0.8X).\r\n", functionId, context.m_State.nPC);
		break;
	}
}

uint32 CThevent::CreateEventFlag(EVENT* eventPtr)
{
	return m_bios.CreateEventFlag(eventPtr->attributes, eventPtr->options, eventPtr->initValue);
}

uint32 CThevent::SetEventFlag(uint32 eventId, uint32 bits)
{
	return m_bios.SetEventFlag(eventId, bits, false);
}

uint32 CThevent::iSetEventFlag(uint32 eventId, uint32 bits)
{
	return m_bios.SetEventFlag(eventId, bits, true);
}

uint32 CThevent::ClearEventFlag(uint32 eventId, uint32 bits)
{
	return m_bios.ClearEventFlag(eventId, bits);
}

uint32 CThevent::WaitEventFlag(uint32 eventId, uint32 bits, uint32 mode, uint32 resultPtr)
{
	return m_bios.WaitEventFlag(eventId, bits, mode, resultPtr);
}

uint32 CThevent::ReferEventFlagStatus(uint32 eventId, uint32 infoPtr)
{
	return m_bios.ReferEventFlagStatus(eventId, infoPtr);
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// The Loki Library
// Copyright (c) 2005 Peter Kmmel
// Permission to use, copy, modify, distribute and sell this software 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.
// The author makes no representations about the
//     suitability of this software for any purpose. It is provided "as is"
//     without express or implied warranty.
////////////////////////////////////////////////////////////////////////////////

// $Header$

#include <loki/OrderedStatic.h>
#include <limits>

namespace Loki
{
    namespace Private
    {

        OrderedStaticCreatorFunc::OrderedStaticCreatorFunc()
        {
        }

        OrderedStaticCreatorFunc::~OrderedStaticCreatorFunc()
        {
        }

        OrderedStaticManagerClass::OrderedStaticManagerClass() :
                    staticObjects_(),
                    max_longevity_(std::numeric_limits<unsigned int>::min()),
                    min_longevity_(std::numeric_limits<unsigned int>::max())
        {
        }

        OrderedStaticManagerClass::~OrderedStaticManagerClass()
        {
        }

        void OrderedStaticManagerClass::createObjects()
        {
            for(unsigned int longevity=max_longevity_; longevity>=min_longevity_; longevity--)
            {
                for(unsigned int i=0; i<staticObjects_.size(); i++)
                {
                    Data cur = staticObjects_.at(i);
                    if(cur.longevity==longevity)
                        ( (*cur.object).*cur.creator )();
                }
            }
        }

        void OrderedStaticManagerClass::registerObject(unsigned int l, OrderedStaticCreatorFunc* o,Creator f)
        {
            staticObjects_.push_back(Data(l,o,f));

            if(l>max_longevity_) max_longevity_=l;
            if(l<min_longevity_) min_longevity_=l;
        }

        OrderedStaticManagerClass::Data::Data(unsigned int l, OrderedStaticCreatorFunc* o, Creator f)
            : longevity(l), object(o), creator(f)
        {
        }

    }//namespace Private

}//namespace Loki

// $Log$
// Revision 1.6  2006/01/18 17:21:31  lfittl
// - Compile library with -Weffc++ and -pedantic (gcc)
// - Fix most issues raised by using -Weffc++ (initialization lists)
//
// Revision 1.5  2006/01/16 20:59:53  rich_sposato
// Added cvs keywords.
//
<commit_msg>undef all min/max macros, thx to Shen Lei<commit_after>////////////////////////////////////////////////////////////////////////////////
// The Loki Library
// Copyright (c) 2005 Peter Kmmel
// Permission to use, copy, modify, distribute and sell this software 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.
// The author makes no representations about the
//     suitability of this software for any purpose. It is provided "as is"
//     without express or implied warranty.
////////////////////////////////////////////////////////////////////////////////

// $Header$

#include <loki/OrderedStatic.h>
#include <limits>

#ifdef min
#undef min
#endif

#ifdef max
#undef max
#endif

namespace Loki
{
    namespace Private
    {

        OrderedStaticCreatorFunc::OrderedStaticCreatorFunc()
        {
        }

        OrderedStaticCreatorFunc::~OrderedStaticCreatorFunc()
        {
        }

        OrderedStaticManagerClass::OrderedStaticManagerClass() :
                    staticObjects_(),
                    max_longevity_(std::numeric_limits<unsigned int>::min()),
                    min_longevity_(std::numeric_limits<unsigned int>::max())
        {
        }

        OrderedStaticManagerClass::~OrderedStaticManagerClass()
        {
        }

        void OrderedStaticManagerClass::createObjects()
        {
            for(unsigned int longevity=max_longevity_; longevity>=min_longevity_; longevity--)
            {
                for(unsigned int i=0; i<staticObjects_.size(); i++)
                {
                    Data cur = staticObjects_.at(i);
                    if(cur.longevity==longevity)
                        ( (*cur.object).*cur.creator )();
                }
            }
        }

        void OrderedStaticManagerClass::registerObject(unsigned int l, OrderedStaticCreatorFunc* o,Creator f)
        {
            staticObjects_.push_back(Data(l,o,f));

            if(l>max_longevity_) max_longevity_=l;
            if(l<min_longevity_) min_longevity_=l;
        }

        OrderedStaticManagerClass::Data::Data(unsigned int l, OrderedStaticCreatorFunc* o, Creator f)
            : longevity(l), object(o), creator(f)
        {
        }

    }//namespace Private

}//namespace Loki

// $Log$
// Revision 1.7  2006/03/27 16:09:57  syntheticpp
// undef all min/max macros, thx to Shen Lei
//
// Revision 1.6  2006/01/18 17:21:31  lfittl
// - Compile library with -Weffc++ and -pedantic (gcc)
// - Fix most issues raised by using -Weffc++ (initialization lists)
//
// Revision 1.5  2006/01/16 20:59:53  rich_sposato
// Added cvs keywords.
//
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:
  Language:  C++
  Date:
  Version:

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

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

#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight

#include "itkAcosImageFilter.h"
#include "itkAdaptImageFilter.h"
#include "itkAddImageFilter.h"
#include "itkAnisotropicDiffusionFunction.h"
#include "itkAnisotropicDiffusionImageFilter.h"
#include "itkAsinImageFilter.h"
#include "itkAtan2ImageFilter.h"
#include "itkAtanImageFilter.h"
#include "itkBSplineCenteredL2ResampleImageFilterBase.txx"
#include "itkBSplineCenteredResampleImageFilterBase.txx"
#include "itkBSplineDecompositionImageFilter.txx"
#include "itkBSplineDownsampleImageFilter.txx"
#include "itkBSplineInterpolateImageFunction.txx"
#include "itkBSplineL2ResampleImageFilterBase.txx"
#include "itkBSplineResampleImageFilterBase.txx"
#include "itkBSplineResampleImageFunction.h"
#include "itkBSplineUpsampleImageFilter.txx"
#include "itkBilateralImageFilter.txx"
#include "itkBinaryDilateImageFilter.txx"
#include "itkBinaryErodeImageFilter.txx"
#include "itkBinaryFunctorImageFilter.txx"
#include "itkBinaryMagnitudeImageFilter.h"
#include "itkBinaryMedianImageFilter.txx"
#include "itkBinaryThresholdImageFilter.txx"
#include "itkBinomialBlurImageFilter.txx"
#include "itkBloxBoundaryPointImageToBloxBoundaryProfileImageFilter.txx"
#include "itkBloxBoundaryPointToCoreAtomImageFilter.txx"
#include "itkCannyEdgeDetectionImageFilter.txx"
#include "itkCastImageFilter.h"
#include "itkChangeInformationImageFilter.txx"
#include "itkConfidenceConnectedImageFilter.txx"
#include "itkConnectedThresholdImageFilter.txx"
#include "itkConstantPadImageFilter.txx"
#include "itkCosImageFilter.h"
#include "itkCropImageFilter.txx"
#include "itkCurvatureAnisotropicDiffusionImageFilter.h"
#include "itkCurvatureNDAnisotropicDiffusionFunction.txx"
#include "itkDanielssonDistanceMapImageFilter.txx"
#include "itkDerivativeImageFilter.txx"
#include "itkDifferenceOfGaussiansGradientImageFilter.txx"
#include "itkDirectedHausdorffDistanceImageFilter.txx"
#include "itkDiscreteGaussianImageFilter.txx"
#include "itkDivideImageFilter.h"
#include "itkEdgePotentialImageFilter.h"
#include "itkEigenAnalysis2DImageFilter.txx"
#include "itkExpImageFilter.h"
#include "itkExpNegativeImageFilter.h"
#include "itkExpandImageFilter.txx"
#include "itkExtractImageFilter.txx"
#include "itkExtractImageFilterRegionCopier.h"
#include "itkFlipImageFilter.txx"
#include "itkGaussianImageSource.txx"
#include "itkGradientAnisotropicDiffusionImageFilter.h"
#include "itkGradientImageFilter.txx"
#include "itkGradientImageToBloxBoundaryPointImageFilter.txx"
#include "itkGradientMagnitudeImageFilter.txx"
#include "itkGradientMagnitudeRecursiveGaussianImageFilter.txx"
#include "itkGradientNDAnisotropicDiffusionFunction.txx"
#include "itkGradientRecursiveGaussianImageFilter.txx"
#include "itkGradientToMagnitudeImageFilter.h"
#include "itkGrayscaleDilateImageFilter.txx"
#include "itkGrayscaleErodeImageFilter.txx"
#include "itkGrayscaleFunctionDilateImageFilter.txx"
#include "itkGrayscaleFunctionErodeImageFilter.txx"
#include "itkHardConnectedComponentImageFilter.txx"
#include "itkHausdorffDistanceImageFilter.txx"
#include "itkImageToMeshFilter.txx"
#include "itkImageToParametricSpaceFilter.txx"
#include "itkImportImageFilter.txx"
#include "itkInteriorExteriorMeshFilter.txx"
#include "itkInterpolateImageFilter.txx"
#include "itkInterpolateImagePointsFilter.txx"
#include "itkIsolatedConnectedImageFilter.txx"
#include "itkJoinImageFilter.h"
#include "itkLaplacianImageFilter.txx"
#include "itkLog10ImageFilter.h"
#include "itkLogImageFilter.h"
#include "itkMaskImageFilter.h"
#include "itkMaximumImageFilter.h"
#include "itkMeanImageFilter.txx"
#include "itkMedianImageFilter.txx"
#include "itkMinimumImageFilter.h"
#include "itkMinimumMaximumImageCalculator.txx"
#include "itkMinimumMaximumImageFilter.txx"
#include "itkMirrorPadImageFilter.txx"
#include "itkMorphologyImageFilter.txx"
#include "itkMultiplyImageFilter.h"
#include "itkNaryAddImageFilter.h"
#include "itkNaryFunctorImageFilter.txx"
#include "itkNeighborhoodConnectedImageFilter.txx"
#include "itkNeighborhoodOperatorImageFilter.txx"
#include "itkNonThreadedShrinkImageFilter.txx"
#include "itkNormalizeImageFilter.txx"
#include "itkPadImageFilter.txx"
#include "itkParametricSpaceToImageSpaceMeshFilter.txx"
#include "itkPermuteAxesImageFilter.txx"
#include "itkPlaheImageFilter.txx"
#include "itkRandomImageSource.txx"
#include "itkRecursiveGaussianImageFilter.txx"
#include "itkRecursiveSeparableImageFilter.txx"
#include "itkReflectImageFilter.txx"
#include "itkReflectiveImageRegionConstIterator.txx"
#include "itkReflectiveImageRegionIterator.txx"
#include "itkResampleImageFilter.txx"
#include "itkRescaleIntensityImageFilter.txx"
#include "itkScalarAnisotropicDiffusionFunction.txx"
#include "itkScalarToArrayCastImageFilter.h"
#include "itkShiftScaleImageFilter.txx"
#include "itkShrinkImageFilter.txx"
#include "itkSimilarityIndexImageFilter.txx"
#include "itkSinImageFilter.h"
#include "itkSobelEdgeDetectionImageFilter.txx"
#include "itkSparseFieldLayer.txx"
#include "itkSparseFieldLevelSetImageFilter.txx"
#include "itkSpatialFunctionImageEvaluatorFilter.txx"
#include "itkSqrtImageFilter.h"
#include "itkStatisticsImageFilter.txx"
#include "itkStreamingImageFilter.txx"
#include "itkSubtractImageFilter.h"
#include "itkTanImageFilter.h"
#include "itkTernaryAddImageFilter.h"
#include "itkTernaryFunctorImageFilter.txx"
#include "itkTernaryMagnitudeImageFilter.h"
#include "itkTernaryMagnitudeSquaredImageFilter.h"
#include "itkThresholdImageFilter.txx"
#include "itkTobogganImageFilter.txx"
#include "itkTransformMeshFilter.txx"
#include "itkTwoOutputExampleImageFilter.txx"
#include "itkUnaryFunctorImageFilter.txx"
#include "itkVTKImageExport.txx"
#include "itkVTKImageExportBase.h"
#include "itkVTKImageImport.txx"
#include "itkVectorAnisotropicDiffusionFunction.txx"
#include "itkVectorCastImageFilter.h"
#include "itkVectorCurvatureAnisotropicDiffusionImageFilter.h"
#include "itkVectorCurvatureNDAnisotropicDiffusionFunction.txx"
#include "itkVectorExpandImageFilter.txx"
#include "itkVectorGradientAnisotropicDiffusionImageFilter.h"
#include "itkVectorGradientNDAnisotropicDiffusionFunction.txx"
#include "itkVectorIndexSelectionCastImageFilter.h"
#include "itkVectorNeighborhoodOperatorImageFilter.txx"
#include "itkWarpImageFilter.txx"
#include "itkWrapPadImageFilter.txx"
#include "itkZeroCrossingBasedEdgeDetectionImageFilter.txx"
#include "itkZeroCrossingImageFilter.txx"

int main ( int , char*  )
{

  return 0;
}

<commit_msg>ENH: Updated to latest headers<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:
  Language:  C++
  Date:
  Version:

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

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

#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight

#include "itkAcosImageFilter.h"
#include "itkAdaptImageFilter.h"
#include "itkAddImageFilter.h"
#include "itkAnisotropicDiffusionFunction.h"
#include "itkAnisotropicDiffusionImageFilter.h"
#include "itkAsinImageFilter.h"
#include "itkAtan2ImageFilter.h"
#include "itkAtanImageFilter.h"
#include "itkBSplineCenteredL2ResampleImageFilterBase.txx"
#include "itkBSplineCenteredResampleImageFilterBase.txx"
#include "itkBSplineDecompositionImageFilter.txx"
#include "itkBSplineDownsampleImageFilter.txx"
#include "itkBSplineInterpolateImageFunction.txx"
#include "itkBSplineL2ResampleImageFilterBase.txx"
#include "itkBSplineResampleImageFilterBase.txx"
#include "itkBSplineResampleImageFunction.h"
#include "itkBSplineUpsampleImageFilter.txx"
#include "itkBilateralImageFilter.txx"
#include "itkBinaryDilateImageFilter.txx"
#include "itkBinaryErodeImageFilter.txx"
#include "itkBinaryFunctorImageFilter.txx"
#include "itkBinaryMagnitudeImageFilter.h"
#include "itkBinaryMedianImageFilter.txx"
#include "itkBinaryThresholdImageFilter.txx"
#include "itkBinomialBlurImageFilter.txx"
#include "itkBloxBoundaryPointImageToBloxBoundaryProfileImageFilter.txx"
#include "itkBloxBoundaryPointToCoreAtomImageFilter.txx"
#include "itkCannyEdgeDetectionImageFilter.txx"
#include "itkCastImageFilter.h"
#include "itkChangeInformationImageFilter.txx"
#include "itkConfidenceConnectedImageFilter.txx"
#include "itkConnectedThresholdImageFilter.txx"
#include "itkConstantPadImageFilter.txx"
#include "itkCosImageFilter.h"
#include "itkCropImageFilter.txx"
#include "itkCurvatureAnisotropicDiffusionImageFilter.h"
#include "itkCurvatureNDAnisotropicDiffusionFunction.txx"
#include "itkDanielssonDistanceMapImageFilter.txx"
#include "itkDerivativeImageFilter.txx"
#include "itkDifferenceOfGaussiansGradientImageFilter.txx"
#include "itkDilateObjectMorphologyImageFilter.txx"
#include "itkDirectedHausdorffDistanceImageFilter.txx"
#include "itkDiscreteGaussianImageFilter.txx"
#include "itkDivideImageFilter.h"
#include "itkEdgePotentialImageFilter.h"
#include "itkEigenAnalysis2DImageFilter.txx"
#include "itkErodeObjectMorphologyImageFilter.txx"
#include "itkExpImageFilter.h"
#include "itkExpNegativeImageFilter.h"
#include "itkExpandImageFilter.txx"
#include "itkExtractImageFilter.txx"
#include "itkExtractImageFilterRegionCopier.h"
#include "itkFlipImageFilter.txx"
#include "itkGaussianImageSource.txx"
#include "itkGradientAnisotropicDiffusionImageFilter.h"
#include "itkGradientImageFilter.txx"
#include "itkGradientImageToBloxBoundaryPointImageFilter.txx"
#include "itkGradientMagnitudeImageFilter.txx"
#include "itkGradientMagnitudeRecursiveGaussianImageFilter.txx"
#include "itkGradientNDAnisotropicDiffusionFunction.txx"
#include "itkGradientRecursiveGaussianImageFilter.txx"
#include "itkGradientToMagnitudeImageFilter.h"
#include "itkGrayscaleDilateImageFilter.txx"
#include "itkGrayscaleErodeImageFilter.txx"
#include "itkGrayscaleFunctionDilateImageFilter.txx"
#include "itkGrayscaleFunctionErodeImageFilter.txx"
#include "itkHardConnectedComponentImageFilter.txx"
#include "itkHausdorffDistanceImageFilter.txx"
#include "itkImageToMeshFilter.txx"
#include "itkImageToParametricSpaceFilter.txx"
#include "itkImportImageFilter.txx"
#include "itkInteriorExteriorMeshFilter.txx"
#include "itkInterpolateImageFilter.txx"
#include "itkInterpolateImagePointsFilter.txx"
#include "itkIsolatedConnectedImageFilter.txx"
#include "itkJoinImageFilter.h"
#include "itkLaplacianImageFilter.txx"
#include "itkLog10ImageFilter.h"
#include "itkLogImageFilter.h"
#include "itkMaskImageFilter.h"
#include "itkMaximumImageFilter.h"
#include "itkMeanImageFilter.txx"
#include "itkMedianImageFilter.txx"
#include "itkMinimumImageFilter.h"
#include "itkMinimumMaximumImageCalculator.txx"
#include "itkMinimumMaximumImageFilter.txx"
#include "itkMirrorPadImageFilter.txx"
#include "itkMorphologyImageFilter.txx"
#include "itkMultiplyImageFilter.h"
#include "itkNaryAddImageFilter.h"
#include "itkNaryFunctorImageFilter.txx"
#include "itkNeighborhoodConnectedImageFilter.txx"
#include "itkNeighborhoodOperatorImageFilter.txx"
#include "itkNonThreadedShrinkImageFilter.txx"
#include "itkNormalizeImageFilter.txx"
#include "itkObjectMorphologyImageFilter.txx"
#include "itkPadImageFilter.txx"
#include "itkParametricSpaceToImageSpaceMeshFilter.txx"
#include "itkPermuteAxesImageFilter.txx"
#include "itkPlaheImageFilter.txx"
#include "itkRandomImageSource.txx"
#include "itkRecursiveGaussianImageFilter.txx"
#include "itkRecursiveSeparableImageFilter.txx"
#include "itkReflectImageFilter.txx"
#include "itkReflectiveImageRegionConstIterator.txx"
#include "itkReflectiveImageRegionIterator.txx"
#include "itkResampleImageFilter.txx"
#include "itkRescaleIntensityImageFilter.txx"
#include "itkScalarAnisotropicDiffusionFunction.txx"
#include "itkScalarToArrayCastImageFilter.h"
#include "itkShiftScaleImageFilter.txx"
#include "itkShrinkImageFilter.txx"
#include "itkSimilarityIndexImageFilter.txx"
#include "itkSinImageFilter.h"
#include "itkSobelEdgeDetectionImageFilter.txx"
#include "itkSparseFieldLayer.txx"
#include "itkSparseFieldLevelSetImageFilter.txx"
#include "itkSpatialFunctionImageEvaluatorFilter.txx"
#include "itkSqrtImageFilter.h"
#include "itkStatisticsImageFilter.txx"
#include "itkStreamingImageFilter.txx"
#include "itkSubtractImageFilter.h"
#include "itkTanImageFilter.h"
#include "itkTernaryAddImageFilter.h"
#include "itkTernaryFunctorImageFilter.txx"
#include "itkTernaryMagnitudeImageFilter.h"
#include "itkTernaryMagnitudeSquaredImageFilter.h"
#include "itkThresholdImageFilter.txx"
#include "itkTobogganImageFilter.txx"
#include "itkTransformMeshFilter.txx"
#include "itkTwoOutputExampleImageFilter.txx"
#include "itkUnaryFunctorImageFilter.txx"
#include "itkVTKImageExport.txx"
#include "itkVTKImageExportBase.h"
#include "itkVTKImageImport.txx"
#include "itkVectorAnisotropicDiffusionFunction.txx"
#include "itkVectorCastImageFilter.h"
#include "itkVectorCurvatureAnisotropicDiffusionImageFilter.h"
#include "itkVectorCurvatureNDAnisotropicDiffusionFunction.txx"
#include "itkVectorExpandImageFilter.txx"
#include "itkVectorGradientAnisotropicDiffusionImageFilter.h"
#include "itkVectorGradientNDAnisotropicDiffusionFunction.txx"
#include "itkVectorIndexSelectionCastImageFilter.h"
#include "itkVectorNeighborhoodOperatorImageFilter.txx"
#include "itkWarpImageFilter.txx"
#include "itkWrapPadImageFilter.txx"
#include "itkZeroCrossingBasedEdgeDetectionImageFilter.txx"
#include "itkZeroCrossingImageFilter.txx"

int main ( int , char*  )
{

  return 0;
}

<|endoftext|>


<commit_before>/**
 * @file   GRP.C
 * @author Christian Holm Christensen <cholm@nbi.dk>
 * @date   Wed Aug 20 10:00:39 2014
 *
 * @brief  Class that hold summary of GRP data.
 *
 *
 */
// #include <fstream>

/**
 * Class that hold summary of GRP data, and has methods to obtain
 * these, either from a previously dumped file, or directly from OCDB.
 *
 * This is used by the simulation setup to ensure we have the proper
 * beam settings for an anchor run.
 */
struct GRPData
{
  /**
   * A beam
   */
  struct Beam
  {
    UInt_t z;
    UInt_t a;
    /**
     * Get the per nucleon beam energy given a per charge beam energy
     *
     * @param e Per charge beam energy
     *
     * @return Per nucleon beam energy
     */
    Float_t GetEnergy(Float_t e) const
    {
      return e * sqrt(float(z)/a);
    }
    /**
     * Check if this is a proton
     *
     * @return True if z and a are 1
     */
    Bool_t IsP() const { return z == 1 && a == 1; }
    /**
     * Check if this is a nucleus
     *
     * @return true if not P
     */
    Bool_t IsA() const { return !IsP(); }
    /**
     * Get the beam type name
     *
     * @return P or A
     */
    const char* Name() { return (IsP() ? "P" : IsA() ? "A" : ""); }
    /**
     * Set the beam type from single beam spec from LHC
     *
     * @param b Beam type from LHC
     */
    void Set(UInt_t b)
    {
      z = b % 1000;
      a = b / 1000;
    }
    /**
     * Set from either a full LHC spec or from ALICE spec
     *
     * @param b Beam
     */
    void Set(const TString& b)
    {
      b.ToUpper();
      a = 0;
      z = 0;
      if (b.EqualTo("P") || b.EqualTo("PROTON")) {
	z = a = 1;
      }
      else if (b.EqualTo("A") || b.BeginsWidth("PB")) {
	z = 82;
	a = 208;
      }
    }
  };
  UInt_t  beamEnergy; // Total energy in center of mass
  UInt_t  energy; // Center of mass energy per nucleon
  TString period; // The period
  UInt_t  run;   // The run number
  Beam    beam1; // Target beam
  Beam    beam2; // Projectile beam
  /**
   * Constructor.
   *
   * @param r Run number
   */
  GRPData(UInt_t r)
    : beamEnergy(0), energy(0), period(""), beam1(), beam2(), run(r)
  {
    Info("GRP", "Will try from file %s", FileName());
    if (!ReadFromFile()) {
      Warning("GRP", "Failed to read from file, trying from OCDB");
      if (!ReadFromOCDB(run))
	Fatal("GRP", "Failed to get GRP values");
    }
    Print();
  }
  /**
   * Print information
   *
   */
  void Print()
  {
    Printf("%s run %d\n"
	   "  Beam energy: %d GeV\n"
	   "  sqrt(s_NN):  %d GeV\n"
	   "  Beam 1:      %s (%d %d)\n"
	   "  Beam 2:      %s (%d %d)",
	   period.Data(), run, beamEnergy, energy,
	   beam1.Name(), beam1.a, beam1.z,
	   beam2.Name(), beam2.a, beam2.z);
  }
  /**
   * Check if this run was a p-p run
   *
   * @return Return true if both beams are p
   */
  Bool_t IsPP() const { return beam1.IsP() && beam2.IsP(); }
  /**
   * Check if this run was a p-A run
   *
   * @return Return true beam 1 is p and 2 is A
   */
  Bool_t IsPA() const { return beam1.IsP() && beam2.IsA(); }
  /**
   * Check if this run was a A-p run
   *
   * @return Return true beam 1 is A and 2 is p
   */
  Bool_t IsAP() const { return beam1.IsA() && beam2.IsP(); }
  /**
   * Check if this run was a A-A run
   *
   * @return Return true if both beams are A
   */
  Bool_t IsAA() const { return beam1.IsA() && beam2.IsA(); }

  UInt_t CMEnergy(Bool_t calc=false) const
  {
    if (!calc) return energy;
    return UInt_t(TMath::Sqrt(Float_t(beam1.z*beam2.z)/beam1.a/beam2.a)
		  * beamEnergy);
  }
  /**
   * Get the year
   *
   * @return Year
   */
  UInt_t Year() const
  {
    TString tmp = period(3,2);
    return tmp.Atoi() + 2000;
  }
  const char* FileName() const { return "grp.dat"; }
  /**
   * Get unsigned int value from string value of TObjString
   *
   * @param o Object
   *
   * @return value
   */
  static UInt_t Obj2UInt(const TObject* o)
  {
    return (static_cast<TObjString*>(o))->String().Atoi();
  }
  /**
   * Read values from a file
   *
   * @return true on success
   */
  Bool_t ReadFromFile()
  {
    if (gSystem->AccessPathName(FileName())) {
      Info("GRP", "Cannot open file %s", FileName());
      return false;
    }

    std::ifstream* pin = new std::ifstream("grp.dat");
    std::ifstream& in  = *pin;
    TString line;
    TString env;
    do {
      line.ReadLine(in);
      if (line.IsNull()) continue;
      if (line[0] == '#') continue;
      env = line;
      break;
    } while (!in.eof());
    if (env.IsNull()) {
      Info("GRP", "No line found");
      return false;
    }
    Info("GRP", "Got the line %s", env.Data());
    TObjArray* tokens = env.Tokenize(":");
    if (tokens->GetEntries() < 8) {
      Warning("GRP", "Failed to get enough field from GRP_SUMMARY=%s",
	      env.Data());
      return false;
    }
    period     = tokens->At(0)->GetName();
    run        = Obj2UInt(tokens->At(1));
    beamEnergy = Obj2UInt(tokens->At(2));
    energy     = Obj2UInt(tokens->At(3));
    beam1.a    = Obj2UInt(tokens->At(4));
    beam1.z    = Obj2UInt(tokens->At(5));
    beam2.a    = Obj2UInt(tokens->At(6));
    beam2.z    = Obj2UInt(tokens->At(7));
    pin->close();
    delete pin;
    return true;
  }
  /**
   * Read values from OCDB.  Also dumps values to file.
   *
   * @param r run number
   *
   * @return true on success
   */
  Bool_t ReadFromOCDB(UInt_t r)
  {
     AliCDBManager* cdb = AliCDBManager::Instance();
     cdb->SetDefaultStorageFromRun(r);
     cdb->SetRun(r);
     AliCDBEntry*   ent = cdb->Get("GRP/GRP/Data");
     if (!ent) {
       Warning("GRP", "No GRP data found");
       cdb->SetRun(-1);
       return false;
     }
     // Info("GRP", "Got GRP");
     // ent->PrintMetaData();

     AliGRPObject*  obj        = static_cast<AliGRPObject*>(ent->GetObject());
     obj->Dump();
     run                       = r;
     period                    = obj->GetLHCPeriod();
     beamEnergy                = TMath::Ceil(obj->GetBeamEnergy());
     TString        beam1T     = obj->GetSingleBeamType(0);
     TString        beam2T     = obj->GetSingleBeamType(1);

     if (!beam1T.IsNull() && !beam2T.IsNull()) {
       beam1.Set(beam1T.Atoi());
       beam2.Set(beam2T.Atoi());
     }
     else {
       TString beamType = obj->GetBeamType();
       if (beamType.IsNull()) {
	 Warning("GRP", "No beam type");
	 cdb->SetRun(-1);
	 return false;
       }

       TObjArray* ab  = beamType.Tokenize("-");
       ab->ls();
       beam1T = ab->At(0)->GetName();
       beam2T = ab->At(1)->GetName();
       beam1.Set(beam1T);
       beam2.Set(beam2T);
     }
     Info("", "Energy=%d",  beamEnergy);
     if (beam1.IsA() && beam2.IsA()) {
       // Revert calculation done in AliGRPObject - sigh
       beamEnergy *= 208./82;
       Info("", "Beam energy now %d", beamEnergy);
     }
     // Massage the beam energy in case we had sqrt{s_NN} instead of
     // beam energy.
     if (TMath::Abs(beamEnergy - 1379.8) < 10 && beam1.IsA() && beam2.IsA())
       beamEnergy = 3500;
     Float_t  sNN = 2*beamEnergy *
       TMath::Sqrt(Float_t(beam1.z*beam2.z)/(beam1.a*beam2.a));
     energy = (TMath::Abs(sNN -  2760) < 10 ?  2760 :
	       TMath::Abs(sNN -  5023) < 10 ?  5023 :
	       TMath::Abs(sNN -  2360) < 10 ?  2360 :
	       TMath::Abs(sNN -   900) < 10 ?   900 :
	       TMath::Abs(sNN -  7000) < 10 ?  7000 :
	       TMath::Abs(sNN -  8000) < 10 ?  8000 :
	       TMath::Abs(sNN - 13000) < 10 ? 13000 :
	       0);

     const char* fn = FileName();
     std::ofstream* pout = new std::ofstream(fn);
     std::ofstream& out  = *pout;
     out << "# PERIOD:RUN:BEAMENERGY:ENERGY:BEAM1A:BEAM1Z:BEAM2A:BEAM2Z\n"
	 << period     << ":"
	 << run        << ":"
	 << beamEnergy << ":"
	 << energy     << ":"
	 << beam1.a    << ":"
	 << beam1.z    << ":"
	 << beam2.a    << ":"
	 << beam2.z    << "\n"
	 << "# EOF "   << std::endl;
     pout->close();
     delete pout;
     cdb->SetRun(-1);
     return true;
  }
  /**
   * Get the value of an environment variable as a unsigned int
   *
   * @param envName Enviroment variable name
   * @param def     Default value
   *
   * @return As unsigned int, or default
   */
  static UInt_t Env2UInt(const char* envName, UInt_t def)
  {
    TString val(gSystem->Getenv(envName));
    if (val.IsNull()) return def;
    return UInt_t(val.Atoll());
  }
};
GRPData* grp;
void GRP(UInt_t run=0)
{
  grp = new GRPData(run);
}
//
// EOF
//

<commit_msg>Remove dump of GRP object<commit_after>/**
 * @file   GRP.C
 * @author Christian Holm Christensen <cholm@nbi.dk>
 * @date   Wed Aug 20 10:00:39 2014
 *
 * @brief  Class that hold summary of GRP data.
 *
 *
 */
// #include <fstream>

/**
 * Class that hold summary of GRP data, and has methods to obtain
 * these, either from a previously dumped file, or directly from OCDB.
 *
 * This is used by the simulation setup to ensure we have the proper
 * beam settings for an anchor run.
 */
struct GRPData
{
  /**
   * A beam
   */
  struct Beam
  {
    UInt_t z;
    UInt_t a;
    /**
     * Get the per nucleon beam energy given a per charge beam energy
     *
     * @param e Per charge beam energy
     *
     * @return Per nucleon beam energy
     */
    Float_t GetEnergy(Float_t e) const
    {
      return e * sqrt(float(z)/a);
    }
    /**
     * Check if this is a proton
     *
     * @return True if z and a are 1
     */
    Bool_t IsP() const { return z == 1 && a == 1; }
    /**
     * Check if this is a nucleus
     *
     * @return true if not P
     */
    Bool_t IsA() const { return !IsP(); }
    /**
     * Get the beam type name
     *
     * @return P or A
     */
    const char* Name() { return (IsP() ? "P" : IsA() ? "A" : ""); }
    /**
     * Set the beam type from single beam spec from LHC
     *
     * @param b Beam type from LHC
     */
    void Set(UInt_t b)
    {
      z = b % 1000;
      a = b / 1000;
    }
    /**
     * Set from either a full LHC spec or from ALICE spec
     *
     * @param b Beam
     */
    void Set(const TString& b)
    {
      b.ToUpper();
      a = 0;
      z = 0;
      if (b.EqualTo("P") || b.EqualTo("PROTON")) {
	z = a = 1;
      }
      else if (b.EqualTo("A") || b.BeginsWidth("PB")) {
	z = 82;
	a = 208;
      }
    }
  };
  UInt_t  beamEnergy; // Total energy in center of mass
  UInt_t  energy; // Center of mass energy per nucleon
  TString period; // The period
  UInt_t  run;   // The run number
  Beam    beam1; // Target beam
  Beam    beam2; // Projectile beam
  /**
   * Constructor.
   *
   * @param r Run number
   */
  GRPData(UInt_t r)
    : beamEnergy(0), energy(0), period(""), beam1(), beam2(), run(r)
  {
    Info("GRP", "Will try from file %s", FileName());
    if (!ReadFromFile()) {
      Warning("GRP", "Failed to read from file, trying from OCDB");
      if (!ReadFromOCDB(run))
	Fatal("GRP", "Failed to get GRP values");
    }
    Print();
  }
  /**
   * Print information
   *
   */
  void Print()
  {
    Printf("%s run %d\n"
	   "  Beam energy: %d GeV\n"
	   "  sqrt(s_NN):  %d GeV\n"
	   "  Beam 1:      %s (%d %d)\n"
	   "  Beam 2:      %s (%d %d)",
	   period.Data(), run, beamEnergy, energy,
	   beam1.Name(), beam1.a, beam1.z,
	   beam2.Name(), beam2.a, beam2.z);
  }
  /**
   * Check if this run was a p-p run
   *
   * @return Return true if both beams are p
   */
  Bool_t IsPP() const { return beam1.IsP() && beam2.IsP(); }
  /**
   * Check if this run was a p-A run
   *
   * @return Return true beam 1 is p and 2 is A
   */
  Bool_t IsPA() const { return beam1.IsP() && beam2.IsA(); }
  /**
   * Check if this run was a A-p run
   *
   * @return Return true beam 1 is A and 2 is p
   */
  Bool_t IsAP() const { return beam1.IsA() && beam2.IsP(); }
  /**
   * Check if this run was a A-A run
   *
   * @return Return true if both beams are A
   */
  Bool_t IsAA() const { return beam1.IsA() && beam2.IsA(); }

  UInt_t CMEnergy(Bool_t calc=false) const
  {
    if (!calc) return energy;
    return UInt_t(TMath::Sqrt(Float_t(beam1.z*beam2.z)/beam1.a/beam2.a)
		  * beamEnergy);
  }
  /**
   * Get the year
   *
   * @return Year
   */
  UInt_t Year() const
  {
    TString tmp = period(3,2);
    return tmp.Atoi() + 2000;
  }
  const char* FileName() const { return "grp.dat"; }
  /**
   * Get unsigned int value from string value of TObjString
   *
   * @param o Object
   *
   * @return value
   */
  static UInt_t Obj2UInt(const TObject* o)
  {
    return (static_cast<TObjString*>(o))->String().Atoi();
  }
  /**
   * Read values from a file
   *
   * @return true on success
   */
  Bool_t ReadFromFile()
  {
    if (gSystem->AccessPathName(FileName())) {
      Info("GRP", "Cannot open file %s", FileName());
      return false;
    }

    std::ifstream* pin = new std::ifstream("grp.dat");
    std::ifstream& in  = *pin;
    TString line;
    TString env;
    do {
      line.ReadLine(in);
      if (line.IsNull()) continue;
      if (line[0] == '#') continue;
      env = line;
      break;
    } while (!in.eof());
    if (env.IsNull()) {
      Info("GRP", "No line found");
      return false;
    }
    Info("GRP", "Got the line %s", env.Data());
    TObjArray* tokens = env.Tokenize(":");
    if (tokens->GetEntries() < 8) {
      Warning("GRP", "Failed to get enough field from GRP_SUMMARY=%s",
	      env.Data());
      return false;
    }
    period     = tokens->At(0)->GetName();
    run        = Obj2UInt(tokens->At(1));
    beamEnergy = Obj2UInt(tokens->At(2));
    energy     = Obj2UInt(tokens->At(3));
    beam1.a    = Obj2UInt(tokens->At(4));
    beam1.z    = Obj2UInt(tokens->At(5));
    beam2.a    = Obj2UInt(tokens->At(6));
    beam2.z    = Obj2UInt(tokens->At(7));
    pin->close();
    delete pin;
    return true;
  }
  /**
   * Read values from OCDB.  Also dumps values to file.
   *
   * @param r run number
   *
   * @return true on success
   */
  Bool_t ReadFromOCDB(UInt_t r)
  {
     AliCDBManager* cdb = AliCDBManager::Instance();
     cdb->SetDefaultStorageFromRun(r);
     cdb->SetRun(r);
     AliCDBEntry*   ent = cdb->Get("GRP/GRP/Data");
     if (!ent) {
       Warning("GRP", "No GRP data found");
       cdb->SetRun(-1);
       return false;
     }
     // Info("GRP", "Got GRP");
     // ent->PrintMetaData();

     AliGRPObject*  obj        = static_cast<AliGRPObject*>(ent->GetObject());
     // obj->Dump();
     run                       = r;
     period                    = obj->GetLHCPeriod();
     beamEnergy                = TMath::Ceil(obj->GetBeamEnergy());
     TString        beam1T     = obj->GetSingleBeamType(0);
     TString        beam2T     = obj->GetSingleBeamType(1);

     if (!beam1T.IsNull() && !beam2T.IsNull()) {
       beam1.Set(beam1T.Atoi());
       beam2.Set(beam2T.Atoi());
     }
     else {
       TString beamType = obj->GetBeamType();
       if (beamType.IsNull()) {
	 Warning("GRP", "No beam type");
	 cdb->SetRun(-1);
	 return false;
       }

       TObjArray* ab  = beamType.Tokenize("-");
       ab->ls();
       beam1T = ab->At(0)->GetName();
       beam2T = ab->At(1)->GetName();
       beam1.Set(beam1T);
       beam2.Set(beam2T);
     }
     Info("", "Energy=%d",  beamEnergy);
     if (beam1.IsA() && beam2.IsA()) {
       // Revert calculation done in AliGRPObject - sigh
       beamEnergy *= 208./82;
       Info("", "Beam energy now %d", beamEnergy);
     }
     // Massage the beam energy in case we had sqrt{s_NN} instead of
     // beam energy.
     if (TMath::Abs(beamEnergy - 1379.8) < 10 && beam1.IsA() && beam2.IsA())
       beamEnergy = 3500;
     Float_t  sNN = 2*beamEnergy *
       TMath::Sqrt(Float_t(beam1.z*beam2.z)/(beam1.a*beam2.a));
     energy = (TMath::Abs(sNN -  2760) < 10 ?  2760 :
	       TMath::Abs(sNN -  5023) < 10 ?  5023 :
	       TMath::Abs(sNN -  2360) < 10 ?  2360 :
	       TMath::Abs(sNN -   900) < 10 ?   900 :
	       TMath::Abs(sNN -  7000) < 10 ?  7000 :
	       TMath::Abs(sNN -  8000) < 10 ?  8000 :
	       TMath::Abs(sNN - 13000) < 10 ? 13000 :
	       0);

     const char* fn = FileName();
     std::ofstream* pout = new std::ofstream(fn);
     std::ofstream& out  = *pout;
     out << "# PERIOD:RUN:BEAMENERGY:ENERGY:BEAM1A:BEAM1Z:BEAM2A:BEAM2Z\n"
	 << period     << ":"
	 << run        << ":"
	 << beamEnergy << ":"
	 << energy     << ":"
	 << beam1.a    << ":"
	 << beam1.z    << ":"
	 << beam2.a    << ":"
	 << beam2.z    << "\n"
	 << "# EOF "   << std::endl;
     pout->close();
     delete pout;
     cdb->SetRun(-1);
     return true;
  }
  /**
   * Get the value of an environment variable as a unsigned int
   *
   * @param envName Enviroment variable name
   * @param def     Default value
   *
   * @return As unsigned int, or default
   */
  static UInt_t Env2UInt(const char* envName, UInt_t def)
  {
    TString val(gSystem->Getenv(envName));
    if (val.IsNull()) return def;
    return UInt_t(val.Atoll());
  }
};
GRPData* grp;
void GRP(UInt_t run=0)
{
  grp = new GRPData(run);
}
//
// EOF
//

<|endoftext|>


<commit_before>/*
 * PatternLayout.cpp
 *
 * Copyright 2001, Glen Scott. All rights reserved.
 *
 * See the COPYING file for the terms of usage and distribution.
 */

#include <log4cpp/Portability.hh>

#ifdef LOG4CPP_HAVE_UNISTD_H
#include <unistd.h>
#endif

#include <string>
#include <time.h>

#ifdef LOG4CPP_HAVE_SSTREAM
#include <sstream>
#else
#include <strstream>
#endif

#include <iomanip>
//#include <ios>

#include <log4cpp/PatternLayout.hh>
#include <log4cpp/Priority.hh>
#include <log4cpp/OstringStream.hh>
#include <log4cpp/NDC.hh>
#include <log4cpp/TimeStamp.hh>

#ifdef LOG4CPP_MISSING_INT64_OSTREAM_OP
/* workaround suggested at:
   http://support.microsoft.com/default.aspx?scid=kb;EN-US;q168440
*/

#include <stdio.h>

std::ostream& operator<<(std::ostream& os, int64_t i) {
    char buf[20];
    ::sprintf(buf,"%I64d", i);
    return os << buf;
}
#endif

namespace log4cpp {

    PatternLayout::PatternLayout() {
        convPatn = "%m%n";
    }

    PatternLayout::~PatternLayout() {
    }

    std::string PatternLayout::format(const LoggingEvent& event) {
        bool success;
        return doFormat(event, convPatn, &success);
    }

    bool PatternLayout::setConversionPattern(std::string conversionPattern) {
        LoggingEvent garbageEvent("", "hi", NDC::get(), Priority::INFO);
        bool success;
        doFormat(garbageEvent, conversionPattern, &success);
        if (success)
            convPatn = conversionPattern;
        return success;
    }

    std::string PatternLayout::doFormat(const LoggingEvent& event, std::string conversionPattern, bool *success) {
        *success = true;

#ifdef LOG4CPP_HAVE_SSTREAM
        std::istringstream conversionStream(conversionPattern);
#else
        std::istrstream conversionStream(conversionPattern.c_str());
#endif

        OstringStream message;

        char ch;
        while (conversionStream.get(ch)) {
            switch (ch) {
            case '%':
                {
                    if (!conversionStream.get(ch)) {
                        *success = false;
                        return "";
                    }
                    switch (ch) {
                    case '%':
                        message << '%';
                        break;
                    case 'm':
                        message << event.message;
                        break;
                    case 'n':
                        message << std::endl;
                        break;
                    case 'c':
                        message << event.categoryName;
                        break;
                    case 'd':
                        {
                            struct tm *currentTime;
                            time_t t = event.timeStamp.getSeconds();
                            currentTime = localtime(&t);
                            std::string currentTimeOnOneLine = asctime(currentTime);
                            currentTimeOnOneLine = currentTimeOnOneLine.substr(0, currentTimeOnOneLine.length()-1);

                            message << currentTimeOnOneLine;
                        }
                        break;
                    case 'R':
                        message << event.timeStamp.getSeconds();
                        break;
                    case 'p':
                        {
                            const std::string& priorityName =
                                Priority::getPriorityName(event.priority);
                            message << priorityName;
                        }
                        break;
                    case 'r':
                        {
#ifdef LOG4CPP_HAVE_INT64_T
                            int64_t t = event.timeStamp.getSeconds() -
                                TimeStamp::getStartTime().getSeconds();
                            t *= 1000;
                            t += event.timeStamp.getMilliSeconds() -
                                TimeStamp::getStartTime().getMilliSeconds();

                            message << t;
#else
                            double t = event.timeStamp.getSeconds() -
                                TimeStamp::getStartTime().getSeconds();
                            t *= 1000;
                            t += event.timeStamp.getMilliSeconds() -
                                TimeStamp::getStartTime().getMilliSeconds();

                            message << std::setiosflags(std::ios::fixed) << std::setprecision(0) << t;
#endif
                        }
                        break;
                    case 'u':
                        message << clock();
                        break;
                    case 'x':
                        message << event.ndc;
                        break;
                    default:
                        *success = false;
                        return "";
                        break;
                    }
                };
                break;
            default:
                message << ch;
                break;
            }
        }

        return message.str();
    }
}
<commit_msg>#include <stdint.h><commit_after>/*
 * PatternLayout.cpp
 *
 * Copyright 2001, Glen Scott. All rights reserved.
 *
 * See the COPYING file for the terms of usage and distribution.
 */

#include <log4cpp/Portability.hh>

#ifdef LOG4CPP_HAVE_UNISTD_H
#include <unistd.h>
#endif

#include <string>
#include <time.h>

#ifdef LOG4CPP_HAVE_SSTREAM
#include <sstream>
#else
#include <strstream>
#endif

#include <iomanip>
//#include <ios>

#include <log4cpp/PatternLayout.hh>
#include <log4cpp/Priority.hh>
#include <log4cpp/OstringStream.hh>
#include <log4cpp/NDC.hh>
#include <log4cpp/TimeStamp.hh>

#ifdef LOG4CPP_HAVE_INT64_T
#ifdef LOG4CPP_MISSING_INT64_OSTREAM_OP
/* workaround suggested at:
   http://support.microsoft.com/default.aspx?scid=kb;EN-US;q168440
*/

#include <stdio.h>
#include <stdint.h>

std::ostream& operator<<(std::ostream& os, int64_t i) {
    char buf[20];
    ::sprintf(buf,"%I64d", i);
    return os << buf;
}
#endif // LOG4CPP_MISSING_INT64_OSTREAM_OP
#endif // LOG4CPP_HAVE_INT64_T

namespace log4cpp {

    PatternLayout::PatternLayout() {
        convPatn = "%m%n";
    }

    PatternLayout::~PatternLayout() {
    }

    std::string PatternLayout::format(const LoggingEvent& event) {
        bool success;
        return doFormat(event, convPatn, &success);
    }

    bool PatternLayout::setConversionPattern(std::string conversionPattern) {
        LoggingEvent garbageEvent("", "hi", NDC::get(), Priority::INFO);
        bool success;
        doFormat(garbageEvent, conversionPattern, &success);
        if (success)
            convPatn = conversionPattern;
        return success;
    }

    std::string PatternLayout::doFormat(const LoggingEvent& event, std::string conversionPattern, bool *success) {
        *success = true;

#ifdef LOG4CPP_HAVE_SSTREAM
        std::istringstream conversionStream(conversionPattern);
#else
        std::istrstream conversionStream(conversionPattern.c_str());
#endif

        OstringStream message;

        char ch;
        while (conversionStream.get(ch)) {
            switch (ch) {
            case '%':
                {
                    if (!conversionStream.get(ch)) {
                        *success = false;
                        return "";
                    }
                    switch (ch) {
                    case '%':
                        message << '%';
                        break;
                    case 'm':
                        message << event.message;
                        break;
                    case 'n':
                        message << std::endl;
                        break;
                    case 'c':
                        message << event.categoryName;
                        break;
                    case 'd':
                        {
                            struct tm *currentTime;
                            time_t t = event.timeStamp.getSeconds();
                            currentTime = localtime(&t);
                            std::string currentTimeOnOneLine = asctime(currentTime);
                            currentTimeOnOneLine = currentTimeOnOneLine.substr(0, currentTimeOnOneLine.length()-1);

                            message << currentTimeOnOneLine;
                        }
                        break;
                    case 'R':
                        message << event.timeStamp.getSeconds();
                        break;
                    case 'p':
                        {
                            const std::string& priorityName =
                                Priority::getPriorityName(event.priority);
                            message << priorityName;
                        }
                        break;
                    case 'r':
                        {
#ifdef LOG4CPP_HAVE_INT64_T
                            int64_t t = event.timeStamp.getSeconds() -
                                TimeStamp::getStartTime().getSeconds();
                            t *= 1000;
                            t += event.timeStamp.getMilliSeconds() -
                                TimeStamp::getStartTime().getMilliSeconds();

                            message << t;
#else
                            double t = event.timeStamp.getSeconds() -
                                TimeStamp::getStartTime().getSeconds();
                            t *= 1000;
                            t += event.timeStamp.getMilliSeconds() -
                                TimeStamp::getStartTime().getMilliSeconds();

                            message << std::setiosflags(std::ios::fixed) << std::setprecision(0) << t;
#endif
                        }
                        break;
                    case 'u':
                        message << clock();
                        break;
                    case 'x':
                        message << event.ndc;
                        break;
                    default:
                        *success = false;
                        return "";
                        break;
                    }
                };
                break;
            default:
                message << ch;
                break;
            }
        }

        return message.str();
    }
}
<|endoftext|>


<commit_before>#include "GameObject.h"
#include "Functions.h"
#include "App.h"
#include "imgui.h"
#include "Component.h"
#include "ComponentTransform.h"
#include "ComponentMesh.h"
#include "ComponentMaterial.h"
#include "ComponentCamera.h"
#include "ModuleGameObject.h"
#include "Inspector.h"
#include "ModuleRenderer3D.h"
#include "DebugDraw.h"
#include "ResourceMesh.h"
#include "ResourceTexture.h"
#include "JSONLoader.h"

#include "Glew/include/glew.h"

GameObject::GameObject(std::string _unique_id)
{
	unique_id = _unique_id;
}

GameObject::~GameObject()
{
}

void GameObject::Start()
{
	LOG_OUTPUT("Game Object Created");

	SetName("GameObject");

	AddComponent(TRANSFORM);
	transform = (ComponentTransform*)GetComponent(TRANSFORM);
}

void GameObject::Update()
{
	for (vector<Component*>::iterator it = components.begin(); it != components.end(); it++)
	{
		if((*it)->GetEnabled())
			(*it)->Update();
	}
}

void GameObject::Draw()
{
	// Push matrix
	glPushMatrix();
	glMultMatrixf(transform->GetGlobalTransform().Transposed().ptr());

	ComponentMaterial* component_material = (ComponentMaterial*)GetComponent(MATERIAL);

	if (component_material != nullptr && component_material->GetEnabled())
	{
		if (component_material->HasTexture())
		{
			glBindTexture(GL_TEXTURE_2D, component_material->GetTexture()->GetTextureId());
		}
	}

	ComponentMesh* component_mesh = (ComponentMesh*)GetComponent(MESH);

	if (component_mesh != nullptr && component_mesh->GetEnabled())
	{
		if (component_mesh->HasMesh())
		{
			// Vertex
			glEnableClientState(GL_VERTEX_ARRAY);
			glBindBuffer(GL_ARRAY_BUFFER, component_mesh->GetMesh()->GetIdVertices());
			glVertexPointer(3, GL_FLOAT, 0, NULL);

			// UV
			glEnableClientState(GL_TEXTURE_COORD_ARRAY);
			glBindBuffer(GL_ARRAY_BUFFER, component_mesh->GetMesh()->GetIdUV());
			glTexCoordPointer(3, GL_FLOAT, 0, NULL);

			// Index
			glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, component_mesh->GetMesh()->GetIdIndices());

			// Draw
			glDrawElements((GLenum)GL_TRIANGLES, component_mesh->GetMesh()->GetNumIndices(), GL_UNSIGNED_INT, NULL);

			// Disable
			glDisableClientState(GL_TEXTURE_COORD_ARRAY);
			glDisableClientState(GL_VERTEX_ARRAY);

			glBindBuffer(GL_ARRAY_BUFFER, 0);
			glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
		}
	}

	// Reset
	glBindTexture(GL_TEXTURE_2D, 0);

	// Pop matrix
	glPopMatrix();

	// Pop matrix
	glPopMatrix();

	DrawBBox();
}

void GameObject::Enable()
{
	if (!enabled)
	{
		enabled = true;
	}
}

void GameObject::Disable()
{
	if (enabled)
	{
		enabled = true;
	}
}

const bool GameObject::GetEnabled() const
{
	return enabled;
}

void GameObject::SetEnabled(const bool& set)
{
	set ? Enable() : Disable();
}

void GameObject::CleanUp()
{
	for (vector<Component*>::iterator it = components.begin(); it != components.end(); it)
	{
		(*it)->CleanUp();
		delete(*it);
		it = components.erase(it);
	}
}

void GameObject::AddComponent(ComponentType type, string unique_id)
{
	if (ContainsComponent(type))
		return;

	string new_id;

	if (new_id == "")
		new_id = GetUIDRandomHexadecimal();
	else
		new_id = unique_id;

	Component* ret = nullptr;

	switch (type)
	{
		case TRANSFORM:
		{
			ret = new ComponentTransform(this, new_id);
		}
		break;
		case MESH:
		{
			ret = new ComponentMesh(this, new_id);
		}
		break;
		case MATERIAL:
		{
			ret = new ComponentMaterial(this, new_id);
		}
		break;
		case CAMERA:
		{
			ret = new ComponentCamera(this, new_id);
		}
		break;

	default:
		break;
	}

	if (ret != nullptr)
	{
		ret->Start();
		components.push_back(ret);
	}
}

void GameObject::RemoveComponent(ComponentType type)
{
	for (vector<Component*>::iterator it = components.begin(); it != components.end(); it++)
	{
		if ((*it)->GetType() == type)
		{
			(*it)->CleanUp();
			components.erase(it);
			break;
		}
	}
}

bool GameObject::ContainsComponent(ComponentType type)
{
	bool ret = false;

	for (vector<Component*>::iterator it = components.begin(); it != components.end(); it++)
	{
		if ((*it)->GetType() == type)
		{
			ret = true;
			break;
		}
	}

	return ret;
}

std::vector<Component*> GameObject::GetComponents()
{
	return components;
}

Component * GameObject::GetComponent(ComponentType type)
{
	Component* ret = nullptr;

	for (vector<Component*>::iterator it = components.begin(); it != components.end(); it++)
	{
		if ((*it)->GetType() == type)
		{
			ret = *it;
			break;
		}
	}

	return ret;
}

const char * GameObject::GetName() const
{
	return name.c_str();
}

void GameObject::SetName(const string& set)
{
	name = set;
}

void GameObject::SetSelected(const bool& set)
{
	selected = set;
}

std::string GameObject::GetUniqueId()
{
	return unique_id;
}

const bool GameObject::GetSelected() const
{
	return selected;
}

const GameObject* GameObject::GetParent() const
{
	return parent;
}

GameObject* GameObject::GetParent()
{
	return parent;
}

const std::vector<GameObject*> GameObject::GetChilds() const
{
	return childs;
}

const uint GameObject::GetChildsCount() const
{
	return childs.size();
}

const void GameObject::SetParentToNull()
{
	parent = nullptr;
}

void GameObject::EraseChild(GameObject * child, bool send_child_to_root)
{
	for (vector<GameObject*>::iterator it = childs.begin(); it != childs.end(); ++it)
	{
		if ((*it) == child)
		{
			// Clean
			child->SetParentToNull();
			childs.erase(it);

			// Add to root
			if (send_child_to_root)
			{
				App->gameobj->GetRoot()->AddChild(child);

				child->transform->local_transform = child->transform->global_transform;
			}

			break;
		}
	}
}

void GameObject::AddChild(GameObject * child)
{
	if (child == nullptr)
		return;

	// Clean from parent
	if (child->parent != nullptr)
		child->parent->EraseChild(child, false);

	// Add new parent
	child->parent = this;
	childs.push_back(child);
}

void GameObject::RecursiveCalcGlobalTransform()
{
	if (parent != nullptr)
	{
		transform->global_transform = parent->transform->global_transform * transform->local_transform;
	}

	if (!childs.empty())
	{
		for (vector<GameObject*>::iterator it = childs.begin(); it != childs.end(); it++)
		{
			(*it)->RecursiveCalcGlobalTransform();
		}
	}
}

void GameObject::RecursiveCalcBBox()
{
	local_bbox.SetNegativeInfinity();

	for (vector<Component*>::iterator it = components.begin(); it != components.end(); it++)
		(*it)->OnGetBoundingBox(local_bbox);

	if (local_bbox.IsFinite())
	{
		local_bbox.TransformAsAABB(transform->GetGlobalTransform());

	}

	if (!childs.empty())
	{
		for (vector<GameObject*>::iterator it = childs.begin(); it != childs.end(); it++)
		{
			(*it)->RecursiveCalcBBox();
		}
	}
}

void GameObject::RecursiveTestRay(const LineSegment & segment, GameObject*& closest, float& dist)
{
	// Check if intersects with bbox
	if (local_bbox.IsFinite())
	{
		if (segment.Intersects(local_bbox))
		{
			// Get mesh
			ComponentMesh* cmesh = nullptr;
			cmesh = (ComponentMesh*)GetComponent(MESH);

			if (cmesh != nullptr)
			{
				if (cmesh->HasMesh())
				{
					// Transform segment to match mesh transform
					LineSegment segment_local_space(segment);
					segment_local_space.Transform(transform->GetGlobalTransform().Inverted());

					ResourceMesh* mesh = cmesh->GetMesh();

					// Check every triangle
					Triangle tri;
					uint* indices = mesh->GetIndices();
					float* vertices = mesh->GetVertices();
					for (int i = 0; i < mesh->GetNumIndices(); i++)
					{
						tri.a.Set(vertices[indices[i]], vertices[indices[i] + 1], vertices[indices[i] + 2]);
						tri.b.Set(vertices[indices[i] + 3], vertices[indices[i] + 4], vertices[indices[i] + 5]);
						tri.c.Set(vertices[indices[i] + 6], vertices[indices[i] + 7], vertices[indices[i] + 8]);

						float distance;
						float3 hit_point;
						if (segment_local_space.Intersects(tri, &distance, &hit_point))
						{
							if (distance < dist)
							{
								dist = distance;
								closest = this;
							}
						}
					}
				}
			}
		}
	}

	if (!childs.empty())
	{
		for (vector<GameObject*>::iterator it = childs.begin(); it != childs.end(); it++)
		{
			(*it)->RecursiveTestRay(segment, closest, dist);
		}
	}
}

bool GameObject::GetStatic()
{
	return is_static;
}

void GameObject::SetStatic(bool set)
{
	is_static = set;
}

AABB GameObject::GetBbox() const
{
	return local_bbox;
}

void GameObject::OnLoadScene(JSON_Doc * config)
{
	config->MoveToRoot();

	for (vector<Component*>::iterator it = components.begin(); it != components.end(); it++)
	{
		(*it)->OnLoadScene(config);
	}
}

void GameObject::OnSaveScene(JSON_Doc * config)
{
	// Add and move to a new secion on the gameobjects array
	config->AddSectionToArray("GameObjects");
	config->MoveToSectionFromArray("GameObjects", config->GetArrayCount("GameObjects") - 1);

	// Set the id
	config->SetString("uid", unique_id.c_str());

	// Set the name
	config->SetString("name", name.c_str());

	// Set the parent id
	if (parent != nullptr && parent != App->gameobj->GetRoot())
		config->SetString("parent", parent->GetUniqueId().c_str());
	else
		config->SetString("parent", "");

	config->MoveToRoot();

	// Save components
	for (vector<Component*>::iterator it = components.begin(); it != components.end(); it++)
	{
		// Add and move to a new section on the components array
		config->AddSectionToArray("Components");
		config->MoveToSectionFromArray("Components", config->GetArrayCount("Components") - 1);

		config->SetNumber("type", (*it)->GetType());
		config->SetString("component_id", (*it)->GetUniqueId().c_str());
		config->SetString("owner_id", (*it)->GetOwner()->GetUniqueId().c_str());

		(*it)->OnSaveScene(config);

		config->MoveToRoot();
	}
}

void GameObject::DrawBBox()
{
	if (local_bbox.IsFinite())
	{
		if(selected)
			DebugDraw(local_bbox, Red, true, 4.0f);
		else
			DebugDraw(local_bbox, Green, true, 4.0f);
	}
}

<commit_msg>Mouse picking working in most cases (something is wrong?)<commit_after>#include "GameObject.h"
#include "Functions.h"
#include "App.h"
#include "imgui.h"
#include "Component.h"
#include "ComponentTransform.h"
#include "ComponentMesh.h"
#include "ComponentMaterial.h"
#include "ComponentCamera.h"
#include "ModuleGameObject.h"
#include "Inspector.h"
#include "ModuleRenderer3D.h"
#include "DebugDraw.h"
#include "ResourceMesh.h"
#include "ResourceTexture.h"
#include "JSONLoader.h"

#include "Glew/include/glew.h"

GameObject::GameObject(std::string _unique_id)
{
	unique_id = _unique_id;
}

GameObject::~GameObject()
{
}

void GameObject::Start()
{
	LOG_OUTPUT("Game Object Created");

	SetName("GameObject");

	AddComponent(TRANSFORM);
	transform = (ComponentTransform*)GetComponent(TRANSFORM);
}

void GameObject::Update()
{
	for (vector<Component*>::iterator it = components.begin(); it != components.end(); it++)
	{
		if((*it)->GetEnabled())
			(*it)->Update();
	}
}

void GameObject::Draw()
{
	// Push matrix
	glPushMatrix();
	glMultMatrixf(transform->GetGlobalTransform().Transposed().ptr());

	ComponentMaterial* component_material = (ComponentMaterial*)GetComponent(MATERIAL);

	if (component_material != nullptr && component_material->GetEnabled())
	{
		if (component_material->HasTexture())
		{
			glBindTexture(GL_TEXTURE_2D, component_material->GetTexture()->GetTextureId());
		}
	}

	ComponentMesh* component_mesh = (ComponentMesh*)GetComponent(MESH);

	if (component_mesh != nullptr && component_mesh->GetEnabled())
	{
		if (component_mesh->HasMesh())
		{
			// Vertex
			glEnableClientState(GL_VERTEX_ARRAY);
			glBindBuffer(GL_ARRAY_BUFFER, component_mesh->GetMesh()->GetIdVertices());
			glVertexPointer(3, GL_FLOAT, 0, NULL);

			// UV
			glEnableClientState(GL_TEXTURE_COORD_ARRAY);
			glBindBuffer(GL_ARRAY_BUFFER, component_mesh->GetMesh()->GetIdUV());
			glTexCoordPointer(3, GL_FLOAT, 0, NULL);

			// Index
			glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, component_mesh->GetMesh()->GetIdIndices());

			// Draw
			glDrawElements((GLenum)GL_TRIANGLES, component_mesh->GetMesh()->GetNumIndices(), GL_UNSIGNED_INT, NULL);

			// Disable
			glDisableClientState(GL_TEXTURE_COORD_ARRAY);
			glDisableClientState(GL_VERTEX_ARRAY);

			glBindBuffer(GL_ARRAY_BUFFER, 0);
			glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
		}
	}

	// Reset
	glBindTexture(GL_TEXTURE_2D, 0);

	// Pop matrix
	glPopMatrix();

	// Pop matrix
	glPopMatrix();

	DrawBBox();
}

void GameObject::Enable()
{
	if (!enabled)
	{
		enabled = true;
	}
}

void GameObject::Disable()
{
	if (enabled)
	{
		enabled = true;
	}
}

const bool GameObject::GetEnabled() const
{
	return enabled;
}

void GameObject::SetEnabled(const bool& set)
{
	set ? Enable() : Disable();
}

void GameObject::CleanUp()
{
	for (vector<Component*>::iterator it = components.begin(); it != components.end(); it)
	{
		(*it)->CleanUp();
		delete(*it);
		it = components.erase(it);
	}
}

void GameObject::AddComponent(ComponentType type, string unique_id)
{
	if (ContainsComponent(type))
		return;

	string new_id;

	if (new_id == "")
		new_id = GetUIDRandomHexadecimal();
	else
		new_id = unique_id;

	Component* ret = nullptr;

	switch (type)
	{
		case TRANSFORM:
		{
			ret = new ComponentTransform(this, new_id);
		}
		break;
		case MESH:
		{
			ret = new ComponentMesh(this, new_id);
		}
		break;
		case MATERIAL:
		{
			ret = new ComponentMaterial(this, new_id);
		}
		break;
		case CAMERA:
		{
			ret = new ComponentCamera(this, new_id);
		}
		break;

	default:
		break;
	}

	if (ret != nullptr)
	{
		ret->Start();
		components.push_back(ret);
	}
}

void GameObject::RemoveComponent(ComponentType type)
{
	for (vector<Component*>::iterator it = components.begin(); it != components.end(); it++)
	{
		if ((*it)->GetType() == type)
		{
			(*it)->CleanUp();
			components.erase(it);
			break;
		}
	}
}

bool GameObject::ContainsComponent(ComponentType type)
{
	bool ret = false;

	for (vector<Component*>::iterator it = components.begin(); it != components.end(); it++)
	{
		if ((*it)->GetType() == type)
		{
			ret = true;
			break;
		}
	}

	return ret;
}

std::vector<Component*> GameObject::GetComponents()
{
	return components;
}

Component * GameObject::GetComponent(ComponentType type)
{
	Component* ret = nullptr;

	for (vector<Component*>::iterator it = components.begin(); it != components.end(); it++)
	{
		if ((*it)->GetType() == type)
		{
			ret = *it;
			break;
		}
	}

	return ret;
}

const char * GameObject::GetName() const
{
	return name.c_str();
}

void GameObject::SetName(const string& set)
{
	name = set;
}

void GameObject::SetSelected(const bool& set)
{
	selected = set;
}

std::string GameObject::GetUniqueId()
{
	return unique_id;
}

const bool GameObject::GetSelected() const
{
	return selected;
}

const GameObject* GameObject::GetParent() const
{
	return parent;
}

GameObject* GameObject::GetParent()
{
	return parent;
}

const std::vector<GameObject*> GameObject::GetChilds() const
{
	return childs;
}

const uint GameObject::GetChildsCount() const
{
	return childs.size();
}

const void GameObject::SetParentToNull()
{
	parent = nullptr;
}

void GameObject::EraseChild(GameObject * child, bool send_child_to_root)
{
	for (vector<GameObject*>::iterator it = childs.begin(); it != childs.end(); ++it)
	{
		if ((*it) == child)
		{
			// Clean
			child->SetParentToNull();
			childs.erase(it);

			// Add to root
			if (send_child_to_root)
			{
				App->gameobj->GetRoot()->AddChild(child);

				child->transform->local_transform = child->transform->global_transform;
			}

			break;
		}
	}
}

void GameObject::AddChild(GameObject * child)
{
	if (child == nullptr)
		return;

	// Clean from parent
	if (child->parent != nullptr)
		child->parent->EraseChild(child, false);

	// Add new parent
	child->parent = this;
	childs.push_back(child);
}

void GameObject::RecursiveCalcGlobalTransform()
{
	if (parent != nullptr)
	{
		transform->global_transform = parent->transform->global_transform * transform->local_transform;
	}

	if (!childs.empty())
	{
		for (vector<GameObject*>::iterator it = childs.begin(); it != childs.end(); it++)
		{
			(*it)->RecursiveCalcGlobalTransform();
		}
	}
}

void GameObject::RecursiveCalcBBox()
{
	local_bbox.SetNegativeInfinity();

	for (vector<Component*>::iterator it = components.begin(); it != components.end(); it++)
		(*it)->OnGetBoundingBox(local_bbox);

	if (local_bbox.IsFinite())
	{
		local_bbox.TransformAsAABB(transform->GetGlobalTransform());

	}

	if (!childs.empty())
	{
		for (vector<GameObject*>::iterator it = childs.begin(); it != childs.end(); it++)
		{
			(*it)->RecursiveCalcBBox();
		}
	}
}

void GameObject::RecursiveTestRay(const LineSegment & segment, GameObject*& closest, float& dist)
{
	// Check if intersects with bbox
	if (local_bbox.IsFinite())
	{
		if (segment.Intersects(local_bbox))
		{
			// Get mesh
			ComponentMesh* cmesh = nullptr;
			cmesh = (ComponentMesh*)GetComponent(MESH);

			if (cmesh != nullptr)
			{
				if (cmesh->HasMesh())
				{
					// Transform segment to match mesh transform
					LineSegment segment_local_space(segment);
					segment_local_space.Transform(transform->GetGlobalTransform().Inverted());

					ResourceMesh* mesh = cmesh->GetMesh();

					// Check every triangle
					Triangle tri;
					uint* indices = mesh->GetIndices();
					float* vertices = mesh->GetVertices();
					for (int i = 0; i < mesh->GetNumIndices();)
					{
						tri.a.Set(vertices[(indices[i])], vertices[(indices[i] + 1)], vertices[(indices[i] + 2)]); ++i;
						tri.b.Set(vertices[(indices[i])], vertices[(indices[i] + 1)], vertices[(indices[i] + 2)]); ++i;
						tri.c.Set(vertices[(indices[i])], vertices[(indices[i] + 1)], vertices[(indices[i] + 2)]); ++i;

						float distance;
						float3 hit_point;
						if (segment_local_space.Intersects(tri, &distance, &hit_point))
						{
							if (distance < dist)
							{
								dist = distance;
								closest = this;
							}
						}
					}
				}
			}
		}
	}

	if (!childs.empty())
	{
		for (vector<GameObject*>::iterator it = childs.begin(); it != childs.end(); it++)
		{
			(*it)->RecursiveTestRay(segment, closest, dist);
		}
	}
}

bool GameObject::GetStatic()
{
	return is_static;
}

void GameObject::SetStatic(bool set)
{
	is_static = set;
}

AABB GameObject::GetBbox() const
{
	return local_bbox;
}

void GameObject::OnLoadScene(JSON_Doc * config)
{
	config->MoveToRoot();

	for (vector<Component*>::iterator it = components.begin(); it != components.end(); it++)
	{
		(*it)->OnLoadScene(config);
	}
}

void GameObject::OnSaveScene(JSON_Doc * config)
{
	// Add and move to a new secion on the gameobjects array
	config->AddSectionToArray("GameObjects");
	config->MoveToSectionFromArray("GameObjects", config->GetArrayCount("GameObjects") - 1);

	// Set the id
	config->SetString("uid", unique_id.c_str());

	// Set the name
	config->SetString("name", name.c_str());

	// Set the parent id
	if (parent != nullptr && parent != App->gameobj->GetRoot())
		config->SetString("parent", parent->GetUniqueId().c_str());
	else
		config->SetString("parent", "");

	config->MoveToRoot();

	// Save components
	for (vector<Component*>::iterator it = components.begin(); it != components.end(); it++)
	{
		// Add and move to a new section on the components array
		config->AddSectionToArray("Components");
		config->MoveToSectionFromArray("Components", config->GetArrayCount("Components") - 1);

		config->SetNumber("type", (*it)->GetType());
		config->SetString("component_id", (*it)->GetUniqueId().c_str());
		config->SetString("owner_id", (*it)->GetOwner()->GetUniqueId().c_str());

		(*it)->OnSaveScene(config);

		config->MoveToRoot();
	}
}

void GameObject::DrawBBox()
{
	if (local_bbox.IsFinite())
	{
		if(selected)
			DebugDraw(local_bbox, Red, true, 4.0f);
		else
			DebugDraw(local_bbox, Green, true, 4.0f);
	}
}

<|endoftext|>