<commit_before>// ***************************************************************************
//
//   Generated automatically by genwrapper.
//   Please DO NOT EDIT this file!
//
// ***************************************************************************

#include <osgIntrospection/ReflectionMacros>
#include <osgIntrospection/TypedMethodInfo>
#include <osgIntrospection/StaticMethodInfo>
#include <osgIntrospection/Attributes>

#include <osg/CopyOp>
#include <osg/Object>
#include <osgDB/ImageOptions>

// Must undefine IN and OUT macros defined in Windows headers
#ifdef IN
#undef IN
#endif
#ifdef OUT
#undef OUT
#endif

BEGIN_ENUM_REFLECTOR(osgDB::ImageOptions::ImageWindowMode)
	I_EnumLabel(osgDB::ImageOptions::ALL_IMAGE);
	I_EnumLabel(osgDB::ImageOptions::RATIO_WINDOW);
	I_EnumLabel(osgDB::ImageOptions::PIXEL_WINDOW);
END_REFLECTOR

BEGIN_ENUM_REFLECTOR(osgDB::ImageOptions::ImageSamplingMode)
	I_EnumLabel(osgDB::ImageOptions::NEAREST);
	I_EnumLabel(osgDB::ImageOptions::LINEAR);
	I_EnumLabel(osgDB::ImageOptions::CUBIC);
END_REFLECTOR

BEGIN_OBJECT_REFLECTOR(osgDB::ImageOptions)
	I_BaseType(osgDB::ReaderWriter::Options);
	I_Constructor0(____ImageOptions,
	               "",
	               "");
	I_Constructor1(IN, const std::string &, str,
	               Properties::NON_EXPLICIT,
	               ____ImageOptions__C5_std_string_R1,
	               "",
	               "");
	I_ConstructorWithDefaults2(IN, const osgDB::ImageOptions &, options, , IN, const osg::CopyOp, copyop, osg::CopyOp::SHALLOW_COPY,
	                           ____ImageOptions__C5_ImageOptions_R1__C5_osg_CopyOp,
	                           "",
	                           "");
	I_Method0(osg::Object *, cloneType,
	          Properties::VIRTUAL,
	          __osg_Object_P1__cloneType,
	          "Clone the type of an object, with Object* return type. ",
	          "Must be defined by derived classes. ");
	I_Method1(osg::Object *, clone, IN, const osg::CopyOp &, copyop,
	          Properties::VIRTUAL,
	          __osg_Object_P1__clone__C5_osg_CopyOp_R1,
	          "Clone an object, with Object* return type. ",
	          "Must be defined by derived classes. ");
	I_Method1(bool, isSameKindAs, IN, const osg::Object *, obj,
	          Properties::VIRTUAL,
	          __bool__isSameKindAs__C5_osg_Object_P1,
	          "",
	          "");
	I_Method0(const char *, libraryName,
	          Properties::VIRTUAL,
	          __C5_char_P1__libraryName,
	          "return the name of the object's library. ",
	          "Must be defined by derived classes. The OpenSceneGraph convention is that the namespace of a library is the same as the library name. ");
	I_Method0(const char *, className,
	          Properties::VIRTUAL,
	          __C5_char_P1__className,
	          "return the name of the object's class type. ",
	          "Must be defined by derived classes. ");
	I_Method0(void, init,
	          Properties::NON_VIRTUAL,
	          __void__init,
	          "",
	          "");
	I_PublicMemberProperty(osgDB::ImageOptions::ImageSamplingMode, _sourceImageSamplingMode);
	I_PublicMemberProperty(osgDB::ImageOptions::ImageWindowMode, _sourceImageWindowMode);
	I_PublicMemberProperty(osgDB::ImageOptions::RatioWindow, _sourceRatioWindow);
	I_PublicMemberProperty(osgDB::ImageOptions::PixelWindow, _sourcePixelWindow);
	I_PublicMemberProperty(osg::ref_ptr< osg::Image >, _destinationImage);
	I_PublicMemberProperty(osgDB::ImageOptions::ImageWindowMode, _destinationImageWindowMode);
	I_PublicMemberProperty(osgDB::ImageOptions::RatioWindow, _destinationRatioWindow);
	I_PublicMemberProperty(osgDB::ImageOptions::PixelWindow, _destinationPixelWindow);
	I_PublicMemberProperty(GLenum, _destinationDataType);
	I_PublicMemberProperty(GLenum, _destinationPixelFormat);
END_REFLECTOR

BEGIN_VALUE_REFLECTOR(osgDB::ImageOptions::PixelWindow)
	I_Constructor0(____PixelWindow,
	               "",
	               "");
	I_Method4(void, set, IN, unsigned int, x, IN, unsigned int, y, IN, unsigned int, w, IN, unsigned int, h,
	          Properties::NON_VIRTUAL,
	          __void__set__unsigned_int__unsigned_int__unsigned_int__unsigned_int,
	          "",
	          "");
	I_PublicMemberProperty(unsigned int, windowX);
	I_PublicMemberProperty(unsigned int, windowY);
	I_PublicMemberProperty(unsigned int, windowWidth);
	I_PublicMemberProperty(unsigned int, windowHeight);
END_REFLECTOR

BEGIN_VALUE_REFLECTOR(osgDB::ImageOptions::RatioWindow)
	I_Constructor0(____RatioWindow,
	               "",
	               "");
	I_Method4(void, set, IN, double, x, IN, double, y, IN, double, w, IN, double, h,
	          Properties::NON_VIRTUAL,
	          __void__set__double__double__double__double,
	          "",
	          "");
	I_PublicMemberProperty(double, windowX);
	I_PublicMemberProperty(double, windowY);
	I_PublicMemberProperty(double, windowWidth);
	I_PublicMemberProperty(double, windowHeight);
END_REFLECTOR

BEGIN_OBJECT_REFLECTOR(osgDB::ImageOptions::TexCoordRange)
	I_BaseType(osg::Referenced);
	I_Constructor0(____TexCoordRange,
	               "",
	               "");
	I_Method4(void, set, IN, double, x, IN, double, y, IN, double, w, IN, double, h,
	          Properties::NON_VIRTUAL,
	          __void__set__double__double__double__double,
	          "",
	          "");
	I_PublicMemberProperty(double, _x);
	I_PublicMemberProperty(double, _y);
	I_PublicMemberProperty(double, _w);
	I_PublicMemberProperty(double, _h);
END_REFLECTOR

<commit_msg>Updated wrappers<commit_after>// ***************************************************************************
//
//   Generated automatically by genwrapper.
//   Please DO NOT EDIT this file!
//
// ***************************************************************************

#include <osgIntrospection/ReflectionMacros>
#include <osgIntrospection/TypedMethodInfo>
#include <osgIntrospection/StaticMethodInfo>
#include <osgIntrospection/Attributes>

#include <osg/CopyOp>
#include <osg/Object>
#include <osgDB/ImageOptions>

// Must undefine IN and OUT macros defined in Windows headers
#ifdef IN
#undef IN
#endif
#ifdef OUT
#undef OUT
#endif

BEGIN_ENUM_REFLECTOR(osgDB::ImageOptions::ImageWindowMode)
	I_EnumLabel(osgDB::ImageOptions::ALL_IMAGE);
	I_EnumLabel(osgDB::ImageOptions::RATIO_WINDOW);
	I_EnumLabel(osgDB::ImageOptions::PIXEL_WINDOW);
END_REFLECTOR

BEGIN_ENUM_REFLECTOR(osgDB::ImageOptions::ImageSamplingMode)
	I_EnumLabel(osgDB::ImageOptions::NEAREST);
	I_EnumLabel(osgDB::ImageOptions::LINEAR);
	I_EnumLabel(osgDB::ImageOptions::CUBIC);
END_REFLECTOR

BEGIN_OBJECT_REFLECTOR(osgDB::ImageOptions)
	I_BaseType(osgDB::ReaderWriter::Options);
	I_Constructor0(____ImageOptions,
	               "",
	               "");
	I_Constructor1(IN, const std::string &, str,
	               Properties::NON_EXPLICIT,
	               ____ImageOptions__C5_std_string_R1,
	               "",
	               "");
	I_ConstructorWithDefaults2(IN, const osgDB::ImageOptions &, options, , IN, const osg::CopyOp &, copyop, osg::CopyOp::SHALLOW_COPY,
	                           ____ImageOptions__C5_ImageOptions_R1__C5_osg_CopyOp_R1,
	                           "",
	                           "");
	I_Method0(osg::Object *, cloneType,
	          Properties::VIRTUAL,
	          __osg_Object_P1__cloneType,
	          "Clone the type of an object, with Object* return type. ",
	          "Must be defined by derived classes. ");
	I_Method1(osg::Object *, clone, IN, const osg::CopyOp &, copyop,
	          Properties::VIRTUAL,
	          __osg_Object_P1__clone__C5_osg_CopyOp_R1,
	          "Clone an object, with Object* return type. ",
	          "Must be defined by derived classes. ");
	I_Method1(bool, isSameKindAs, IN, const osg::Object *, obj,
	          Properties::VIRTUAL,
	          __bool__isSameKindAs__C5_osg_Object_P1,
	          "",
	          "");
	I_Method0(const char *, libraryName,
	          Properties::VIRTUAL,
	          __C5_char_P1__libraryName,
	          "return the name of the object's library. ",
	          "Must be defined by derived classes. The OpenSceneGraph convention is that the namespace of a library is the same as the library name. ");
	I_Method0(const char *, className,
	          Properties::VIRTUAL,
	          __C5_char_P1__className,
	          "return the name of the object's class type. ",
	          "Must be defined by derived classes. ");
	I_Method0(void, init,
	          Properties::NON_VIRTUAL,
	          __void__init,
	          "",
	          "");
	I_PublicMemberProperty(osgDB::ImageOptions::ImageSamplingMode, _sourceImageSamplingMode);
	I_PublicMemberProperty(osgDB::ImageOptions::ImageWindowMode, _sourceImageWindowMode);
	I_PublicMemberProperty(osgDB::ImageOptions::RatioWindow, _sourceRatioWindow);
	I_PublicMemberProperty(osgDB::ImageOptions::PixelWindow, _sourcePixelWindow);
	I_PublicMemberProperty(osg::ref_ptr< osg::Image >, _destinationImage);
	I_PublicMemberProperty(osgDB::ImageOptions::ImageWindowMode, _destinationImageWindowMode);
	I_PublicMemberProperty(osgDB::ImageOptions::RatioWindow, _destinationRatioWindow);
	I_PublicMemberProperty(osgDB::ImageOptions::PixelWindow, _destinationPixelWindow);
	I_PublicMemberProperty(GLenum, _destinationDataType);
	I_PublicMemberProperty(GLenum, _destinationPixelFormat);
END_REFLECTOR

BEGIN_VALUE_REFLECTOR(osgDB::ImageOptions::PixelWindow)
	I_Constructor0(____PixelWindow,
	               "",
	               "");
	I_Method4(void, set, IN, unsigned int, x, IN, unsigned int, y, IN, unsigned int, w, IN, unsigned int, h,
	          Properties::NON_VIRTUAL,
	          __void__set__unsigned_int__unsigned_int__unsigned_int__unsigned_int,
	          "",
	          "");
	I_PublicMemberProperty(unsigned int, windowX);
	I_PublicMemberProperty(unsigned int, windowY);
	I_PublicMemberProperty(unsigned int, windowWidth);
	I_PublicMemberProperty(unsigned int, windowHeight);
END_REFLECTOR

BEGIN_VALUE_REFLECTOR(osgDB::ImageOptions::RatioWindow)
	I_Constructor0(____RatioWindow,
	               "",
	               "");
	I_Method4(void, set, IN, double, x, IN, double, y, IN, double, w, IN, double, h,
	          Properties::NON_VIRTUAL,
	          __void__set__double__double__double__double,
	          "",
	          "");
	I_PublicMemberProperty(double, windowX);
	I_PublicMemberProperty(double, windowY);
	I_PublicMemberProperty(double, windowWidth);
	I_PublicMemberProperty(double, windowHeight);
END_REFLECTOR

BEGIN_OBJECT_REFLECTOR(osgDB::ImageOptions::TexCoordRange)
	I_BaseType(osg::Referenced);
	I_Constructor0(____TexCoordRange,
	               "",
	               "");
	I_Method4(void, set, IN, double, x, IN, double, y, IN, double, w, IN, double, h,
	          Properties::NON_VIRTUAL,
	          __void__set__double__double__double__double,
	          "",
	          "");
	I_PublicMemberProperty(double, _x);
	I_PublicMemberProperty(double, _y);
	I_PublicMemberProperty(double, _w);
	I_PublicMemberProperty(double, _h);
END_REFLECTOR

<|endoftext|>


<commit_before>#ifndef GAPI_VERTEX_ARRAY_HPP
#define GAPI_VERTEX_ARRAY_HPP 1

#include <cstddef>
#include <type_traits>

#include "object.hpp"
#include "functions.hpp"
#include "buffer.hpp"

namespace gapi{
	class vertex_array_handle: public object{
		public:
			void set_vertex_buffer(const buffer_handle &buff, GLuint binding, GLintptr offset, GLsizei stride){
				functions::glVertexArrayVertexBuffer(handle, binding, buff.get(), offset, stride);
			}

			void set_element_buffer(const buffer_handle &buff){
				functions::glVertexArrayElementBuffer(handle, buff.get());
			}

			void enable_attrib(GLuint index) noexcept{
				functions::glEnableVertexArrayAttrib(handle, index);
			}

			void disable_attrib(GLuint index){
				functions::glDisableVertexArrayAttrib(handle, index);
			}

			void attrib_format(GLuint index, std::uint16_t size, GLenum type, GLboolean normalized, GLuint reloffset){
				functions::glVertexArrayAttribFormat(handle, index, size, type, normalized, reloffset);
			}

			void attrib_binding(GLuint attrib, GLuint binding){
				functions::glVertexArrayAttribBinding(handle, attrib, binding);
			}

			void use(){
				functions::glBindVertexArray(handle);
			}

		protected:
			vertex_array_handle() = default;

			template<std::size_t>
			friend class vertex_arrays;
	};

	class vertex_arrays_base: public object{
		public:
			virtual ~vertex_arrays_base() = default;

			virtual std::size_t size() const noexcept = 0;

			virtual vertex_array_handle &operator [](std::size_t idx) noexcept = 0;
			virtual const vertex_array_handle &operator [](std::size_t idx) const noexcept = 0;
	};

	template<std::size_t N>
	class vertex_arrays: public vertex_arrays_base{
		public:
			vertex_arrays(){
				functions::glCreateVertexArrays(N, m_arrays);
				for(auto i = 0ul; i < N; i++)
					m_handles[i].handle = m_arrays[i];
			}

			virtual ~vertex_arrays(){
				functions::glDeleteVertexArrays(N, m_arrays);
			}

			std::size_t size() const noexcept{ return N; }

			template<typename T = vertex_array_handle&>
			explicit operator std::enable_if_t<N == 1, T>() noexcept{ return m_handles[0]; }

			template<typename T = vertex_array_handle&>
			explicit operator std::enable_if_t<N == 1, const T>() const noexcept{ return m_handles[0]; }

			vertex_array_handle &operator [](std::size_t idx) noexcept{ return m_handles[idx]; }
			const vertex_array_handle &operator [](std::size_t idx) const noexcept{ return m_handles[idx]; }

		protected:
			vertex_array_handle m_handles[N];
			GLuint m_arrays[N];
	};

	using vertex_array = vertex_arrays<1>;
}

#endif // GAPI_VERTEX_ARRAY_HPP

<commit_msg>added get_handle as friend to vertex_array_handle<commit_after>#ifndef GAPI_VERTEX_ARRAY_HPP
#define GAPI_VERTEX_ARRAY_HPP 1

#include <cstddef>
#include <type_traits>

#include "object.hpp"
#include "functions.hpp"
#include "buffer.hpp"

namespace gapi{
	class vertex_array_handle: public object{
		public:
			void set_vertex_buffer(const buffer_handle &buff, GLuint binding, GLintptr offset, GLsizei stride){
				functions::glVertexArrayVertexBuffer(handle, binding, buff.get(), offset, stride);
			}

			void set_element_buffer(const buffer_handle &buff){
				functions::glVertexArrayElementBuffer(handle, buff.get());
			}

			void enable_attrib(GLuint index) noexcept{
				functions::glEnableVertexArrayAttrib(handle, index);
			}

			void disable_attrib(GLuint index){
				functions::glDisableVertexArrayAttrib(handle, index);
			}

			void attrib_format(GLuint index, std::uint16_t size, GLenum type, GLboolean normalized, GLuint reloffset){
				functions::glVertexArrayAttribFormat(handle, index, size, type, normalized, reloffset);
			}

			void attrib_binding(GLuint attrib, GLuint binding){
				functions::glVertexArrayAttribBinding(handle, attrib, binding);
			}

			void use(){
				functions::glBindVertexArray(handle);
			}

		protected:
			vertex_array_handle() = default;

			template<std::size_t>
			friend class vertex_arrays;

			template<typename T>
			friend GLuint get_handle(const T&);
	};

	class vertex_arrays_base: public object{
		public:
			virtual ~vertex_arrays_base() = default;

			virtual std::size_t size() const noexcept = 0;

			virtual vertex_array_handle &operator [](std::size_t idx) noexcept = 0;
			virtual const vertex_array_handle &operator [](std::size_t idx) const noexcept = 0;
	};

	template<std::size_t N>
	class vertex_arrays: public vertex_arrays_base{
		public:
			vertex_arrays(){
				functions::glCreateVertexArrays(N, m_arrays);
				for(auto i = 0ul; i < N; i++)
					m_handles[i].handle = m_arrays[i];
			}

			virtual ~vertex_arrays(){
				functions::glDeleteVertexArrays(N, m_arrays);
			}

			std::size_t size() const noexcept{ return N; }

			template<typename T = vertex_array_handle&>
			explicit operator std::enable_if_t<N == 1, T>() noexcept{ return m_handles[0]; }

			template<typename T = vertex_array_handle&>
			explicit operator std::enable_if_t<N == 1, const T>() const noexcept{ return m_handles[0]; }

			vertex_array_handle &operator [](std::size_t idx) noexcept{ return m_handles[idx]; }
			const vertex_array_handle &operator [](std::size_t idx) const noexcept{ return m_handles[idx]; }

		protected:
			vertex_array_handle m_handles[N];
			GLuint m_arrays[N];
	};

	using vertex_array = vertex_arrays<1>;
}

#endif // GAPI_VERTEX_ARRAY_HPP

<|endoftext|>


<commit_before>#ifndef GHULBUS_LIBRARY_INCLUDE_GUARD_MATH_TRANSFORM2_HPP
#define GHULBUS_LIBRARY_INCLUDE_GUARD_MATH_TRANSFORM2_HPP

/** @file
 *
 * @brief 2D Transformations.
 * @author Andreas Weis (der_ghulbus@ghulbus-inc.de)
 */

#include <gbMath/config.hpp>

#include <gbMath/Matrix3.hpp>
#include <gbMath/NumberTypeTraits.hpp>
#include <gbMath/Vector2.hpp>

namespace GHULBUS_MATH_NAMESPACE
{

/** A homogeneous 2D transformation.
 */
template<typename T>
class Transform2
{
public:
    Matrix3<T> m;
public:
    Transform2()
        :m(identity3<T>())
    {}

    Transform2(T n11, T n12, T n13,
               T n21, T n22, T n23,
               T n31, T n32, T n33)
        :m(n11, n12, n13,
           n21, n22, n23,
           n31, n32, n33)
    {}
};

template<typename T>
Vector2<T> operator*(Transform2<T> const& t, Vector2<T> const& v) {
    Matrix3<T> const& m = t.m;
    return Vector2<T>(v.x*m.m11 + v.y*m.m12,
                      v.x*m.m21 + v.y*m.m22);
}

template<typename T>
Point2<T> operator*(Transform2<T> const& t, Point2<T> const& p) {
    Matrix3<T> const& m = t.m;
    return Point2<T>(p.x*m.m11 + p.y*m.m12 + m.m13,
                     p.x*m.m21 + p.y*m.m22 + m.m23);
}

template<typename T>
Transform2<T> make_scale(T scale_x, T scale_y)
{
    T const z = ::GHULBUS_MATH_NAMESPACE::traits::Constants<T>::Zero();
    T const o = ::GHULBUS_MATH_NAMESPACE::traits::Constants<T>::One();
    return Transform2<T>(scale_x, z,       z,
                         z,       scale_y, z,
                         z,       z,       o);
}
}

#endif
<commit_msg>fixed multiplication order in transform<commit_after>#ifndef GHULBUS_LIBRARY_INCLUDE_GUARD_MATH_TRANSFORM2_HPP
#define GHULBUS_LIBRARY_INCLUDE_GUARD_MATH_TRANSFORM2_HPP

/** @file
 *
 * @brief 2D Transformations.
 * @author Andreas Weis (der_ghulbus@ghulbus-inc.de)
 */

#include <gbMath/config.hpp>

#include <gbMath/Matrix3.hpp>
#include <gbMath/NumberTypeTraits.hpp>
#include <gbMath/Vector2.hpp>

namespace GHULBUS_MATH_NAMESPACE
{

/** A homogeneous 2D transformation.
 */
template<typename T>
class Transform2
{
public:
    Matrix3<T> m;
public:
    Transform2()
        :m(identity3<T>())
    {}

    Transform2(T n11, T n12, T n13,
               T n21, T n22, T n23,
               T n31, T n32, T n33)
        :m(n11, n12, n13,
           n21, n22, n23,
           n31, n32, n33)
    {}
};

template<typename T>
Vector2<T> operator*(Transform2<T> const& t, Vector2<T> const& v) {
    Matrix3<T> const& m = t.m;
    return Vector2<T>(m.m11*v.x + m.m12*v.y,
                      m.m21*v.x + m.m22*v.y);
}

template<typename T>
Point2<T> operator*(Transform2<T> const& t, Point2<T> const& p) {
    Matrix3<T> const& m = t.m;
    return Point2<T>(m.m11*p.x + m.m12*p.y + m.m13,
                     m.m21*p.x + m.m22*p.y + m.m23);
}

template<typename T>
Transform2<T> make_scale(T scale_x, T scale_y)
{
    T const z = ::GHULBUS_MATH_NAMESPACE::traits::Constants<T>::Zero();
    T const o = ::GHULBUS_MATH_NAMESPACE::traits::Constants<T>::One();
    return Transform2<T>(scale_x, z,       z,
                         z,       scale_y, z,
                         z,       z,       o);
}
}

#endif
<|endoftext|>


<commit_before>#ifndef JANOR_TYPE_TRAITS_HPP
#define JANOR_TYPE_TRAITS_HPP

namespace janor{
template <typename T, typename U>
	struct is_same : std::false_type{};
template <typename T>
	struct is_same<T,T> : std::true_type{};

template<typename T>
	struct is_string:
	 is_same<std::string, typename std::remove_cv<T>::type>{};

template <typename T>
	struct is_int{static const bool value = false;};
	template<>
	struct is_int<int>{static const bool value = true;};
	template<>
	struct is_int<std::size_t>{static const bool value = true;};
template <typename T>
	struct is_32bit_int{static const bool value = false;};
	template<>
	struct is_32bit_int<int>{static const bool value = true;};

template<typename T>
	struct is_64bit_int{static const bool value = false;};
	template<>
	struct is_64bit_int<std::size_t>{static const bool value = true;};
	template<>
	struct is_64bit_int<std::int64_t>{static const bool value = true;};

template<typename T>
	struct is_void{ static const bool value = false;};
	template<>
	struct is_void<void>{static const bool value =true;};

template<typename T>
	struct is_vector{static const bool value = false;};
	template <typename T>
	struct is_vector<std::vector<T>>{static const bool value = true;};

template<typename T>
	struct is_pointer :std::false_type{};
	template<typename T>
	struct is_pointer<T*> :std::true_type{};

template<typename T>
	struct is_reference{static const bool value = false;};
	template<typename T>
	struct is_reference<T&>{static const bool value = true;};

template<typename T>
	struct is_rvalue_reference{static const bool value = false;};
	template<typename T>
	struct is_rvalue_reference<T&&>{static const bool value = true;};

template<typename T>
	struct is_nullptr : is_same<T, std::nullptr_t>{};

}

#endif //JANOR_TYPE_TRAITS_HPP<commit_msg>refactor is_reference<commit_after>#ifndef JANOR_TYPE_TRAITS_HPP
#define JANOR_TYPE_TRAITS_HPP

namespace janor{
template <typename T, typename U>
	struct is_same : std::false_type{};
template <typename T>
	struct is_same<T,T> : std::true_type{};

template<typename T>
	struct is_string:
	 is_same<std::string, typename std::remove_cv<T>::type>{};

template <typename T>
	struct is_int{static const bool value = false;};
	template<>
	struct is_int<int>{static const bool value = true;};
	template<>
	struct is_int<std::size_t>{static const bool value = true;};
template <typename T>
	struct is_32bit_int{static const bool value = false;};
	template<>
	struct is_32bit_int<int>{static const bool value = true;};

template<typename T>
	struct is_64bit_int{static const bool value = false;};
	template<>
	struct is_64bit_int<std::size_t>{static const bool value = true;};
	template<>
	struct is_64bit_int<std::int64_t>{static const bool value = true;};

template<typename T>
	struct is_void{ static const bool value = false;};
	template<>
	struct is_void<void>{static const bool value =true;};

template<typename T>
	struct is_vector{static const bool value = false;};
	template <typename T>
	struct is_vector<std::vector<T>>{static const bool value = true;};

template<typename T>
	struct is_pointer :std::false_type{};
	template<typename T>
	struct is_pointer<T*> :std::true_type{};

template<typename T>
	struct is_reference : std::false_type{};
	template<typename T>
	struct is_reference<T&> : std::true_type{};

template<typename T>
	struct is_rvalue_reference{static const bool value = false;};
	template<typename T>
	struct is_rvalue_reference<T&&>{static const bool value = true;};

template<typename T>
	struct is_nullptr : is_same<T, std::nullptr_t>{};

}

#endif //JANOR_TYPE_TRAITS_HPP<|endoftext|>


<commit_before>#include <isl/set.h>
#include <isl/union_map.h>
#include <isl/union_set.h>
#include <isl/ast_build.h>
#include <isl/schedule.h>
#include <isl/schedule_node.h>

#include <DebugIR.h>
#include <IR.h>
#include <String.h>
#include <Halide.h>

int main(int argc, char **argv)
{
	isl_ctx *ctx = isl_ctx_alloc();
	IRProgram pgm("program0");
	IRFunction fct("function0");
	Schedule schedule(ctx);
	pgm.add_function(&fct);

	Halide::Internal::Stmt s0 = Halide::Internal::AssertStmt::make(Halide::Expr(0), Halide::Expr(3));
	Halide::Internal::Stmt s1 = Halide::Internal::AssertStmt::make(Halide::Expr(0), Halide::Expr(5));

	Computation computation0(ctx, s0, "{S0[i,j]: 1<=i<=1000 and 0<=j<=1000}", &fct);
	Computation computation1(ctx, s1, "{S1[i,j]: 1<=i<=1000 and 0<=j<=1000}", &fct);

	schedule.add_schedule_map("{S0[i,j]->[0, i1,i2, j]: i1=floor(i/4) and i2=i and 1<=i<=1000 and 0<=j<=1000}");
	schedule.add_schedule_map("{S1[i,j]->[1, i , j, 0]: 1<=i<=1000 and 0<=j<=1000}");
	isl_union_map *schedule_map = schedule.get_schedule_map();

	isl_union_set *time_space = create_time_space(isl_union_set_copy(pgm.get_iteration_spaces()), isl_union_map_copy(schedule_map));

	isl_ast_build *ast_build = isl_ast_build_alloc(ctx);
	isl_options_set_ast_build_atomic_upper_bound(ctx, 1);
	ast_build = isl_ast_build_set_after_each_for(ast_build, &for_halide_code_generator_after_for, NULL);
	ast_build = isl_ast_build_set_at_each_domain(ast_build, &stmt_halide_code_generator, NULL);
	isl_ast_node *program = isl_ast_build_node_from_schedule_map(ast_build, isl_union_map_copy(schedule_map));
	isl_ast_build_free(ast_build);

	isl_ast_node_dump_c_code(ctx, program);

	Halide::Internal::Stmt halide_pgm = generate_Halide_stmt_from_isl_node(program);

	pgm.dump_ISIR();
	schedule.dump();
	IF_DEBUG(str_dump("\n\nTime Space IR:\n")); IF_DEBUG(isl_union_set_dump(time_space)); IF_DEBUG(str_dump("\n\n"));
	halide_IR_dump(halide_pgm);

	Halide::Argument buffer_arg("buf", Halide::Argument::OutputBuffer, Halide::Int(32), 3);
    	std::vector<Halide::Argument> args(1);
    	args[0] = buffer_arg;
	Halide::Module::Module m("", Halide::get_host_target());
	m.append(Halide::Internal::LoweredFunc("test1", args, halide_pgm, Halide::Internal::LoweredFunc::External));

	return 0;
}
<commit_msg>Update schedule<commit_after>#include <isl/set.h>
#include <isl/union_map.h>
#include <isl/union_set.h>
#include <isl/ast_build.h>
#include <isl/schedule.h>
#include <isl/schedule_node.h>

#include <DebugIR.h>
#include <IR.h>
#include <String.h>
#include <Halide.h>

int main(int argc, char **argv)
{
	isl_ctx *ctx = isl_ctx_alloc();
	IRProgram pgm("program0");
	IRFunction fct("function0");
	Schedule schedule(ctx);
	pgm.add_function(&fct);

	Halide::Internal::Stmt s0 = Halide::Internal::AssertStmt::make(Halide::Expr(0), Halide::Expr(3));
	Halide::Internal::Stmt s1 = Halide::Internal::AssertStmt::make(Halide::Expr(0), Halide::Expr(5));

	Computation computation0(ctx, s0, "{S0[i,j]: 0<=i<=1000 and 0<=j<=1000}", &fct);
	Computation computation1(ctx, s1, "{S1[i,j]: 0<=i<=1000 and 0<=j<=1000}", &fct);

	schedule.add_schedule_map("{S0[i,j]->[0,i1,j1,i,j]: i1=floor(i/32) and j1=floor(j/32) and 0<=i<=1000 and 0<=j<=1000}");
	schedule.add_schedule_map("{S1[i,j]->[1,i1,j1,i,j]: i1=floor(i/32) and j1=floor(j/32) and 0<=i<=1000 and 0<=j<=1000}");
	isl_union_map *schedule_map = schedule.get_schedule_map();

	isl_union_set *time_space = create_time_space(isl_union_set_copy(pgm.get_iteration_spaces()), isl_union_map_copy(schedule_map));

	isl_ast_build *ast_build = isl_ast_build_alloc(ctx);
	isl_options_set_ast_build_atomic_upper_bound(ctx, 1);
	ast_build = isl_ast_build_set_after_each_for(ast_build, &for_halide_code_generator_after_for, NULL);
	ast_build = isl_ast_build_set_at_each_domain(ast_build, &stmt_halide_code_generator, NULL);
	isl_ast_node *program = isl_ast_build_node_from_schedule_map(ast_build, isl_union_map_copy(schedule_map));
	isl_ast_build_free(ast_build);

	isl_ast_node_dump_c_code(ctx, program);

	Halide::Internal::Stmt halide_pgm = generate_Halide_stmt_from_isl_node(program);

	pgm.dump_ISIR();
	schedule.dump();
	IF_DEBUG(str_dump("\n\nTime Space IR:\n")); IF_DEBUG(isl_union_set_dump(time_space)); IF_DEBUG(str_dump("\n\n"));
	halide_IR_dump(halide_pgm);

	Halide::Argument buffer_arg("buf", Halide::Argument::OutputBuffer, Halide::Int(32), 3);
    	std::vector<Halide::Argument> args(1);
    	args[0] = buffer_arg;
	Halide::Module::Module m("", Halide::get_host_target());
	m.append(Halide::Internal::LoweredFunc("test1", args, halide_pgm, Halide::Internal::LoweredFunc::External));

	return 0;
}
<|endoftext|>


<commit_before>#include <QSettings>
#include <QTime>
#include <QCloseEvent>
#include <QClipboard>
#include "batchwindow.h"
#include "ui_batchwindow.h"
#include "functions.h"

#define SAMPLES 100

batchWindow::batchWindow(QWidget *parent)
	: QDialog(), ui(new Ui::batchWindow), m_imagesCount(0), m_items(0), m_images(0), m_maxSpeeds(0), m_lastDownloading(0), m_cancel(false), m_paused(false)
{
	ui->setupUi(this);
	ui->tableWidget->resizeColumnToContents(0);
	m_currentSize = size();

	QSettings settings(savePath("settings.ini"), QSettings::IniFormat);
	restoreGeometry(settings.value("Batch/geometry").toByteArray());
	ui->buttonDetails->setChecked(settings.value("Batch/details", true).toBool());
	on_buttonDetails_clicked(settings.value("Batch/details", true).toBool());
	ui->comboEnd->setCurrentIndex(settings.value("Batch/end", 0).toInt());
	ui->checkRemove->setChecked(settings.value("Batch/remove", false).toBool());
	ui->checkScrollToDownload->setChecked(settings.value("Batch/scrollToDownload", true).toBool());

	m_speeds = QMap<QString, int>();
	m_urls = QStringList();

	m_time = new QTime;
	m_time->start();
	m_start = new QTime;

	#ifdef Q_OS_WIN
		m_taskBarButton = new QWinTaskbarButton(parent);
		m_taskBarButton->setWindow(parent->windowHandle());

		m_taskBarProgress = m_taskBarButton->progress();
		m_taskBarProgress->setVisible(false);
		m_taskBarProgress->setMinimum(0);
		m_taskBarProgress->setMaximum(0);
		m_taskBarProgress->setValue(0);
	#endif
}

batchWindow::~batchWindow()
{
	delete ui;

	#ifdef Q_OS_WIN
		m_taskBarButton->deleteLater();
		m_taskBarProgress->deleteLater();
	#endif
}
void batchWindow::closeEvent(QCloseEvent *e)
{
	QSettings settings(savePath("settings.ini"), QSettings::IniFormat);
	settings.setValue("Batch/geometry", saveGeometry());
	settings.setValue("Batch/details", ui->buttonDetails->isChecked());
	settings.setValue("Batch/end", ui->comboEnd->currentIndex());
	settings.setValue("Batch/remove", ui->checkRemove->isChecked());
	settings.setValue("Batch/scrollToDownload", ui->checkScrollToDownload->isChecked());
	settings.sync();

	if (m_images < m_imagesCount)
	{
		cancel();
		emit rejected();
	}
	else
	{ clear(); }

	#ifdef Q_OS_WIN
		m_taskBarProgress->setVisible(false);
	#endif

	emit closed();
	e->accept();
}
void batchWindow::pause()
{
	m_paused = !m_paused;
	ui->labelSpeed->setText(m_paused ? tr("En pause") : "");
	ui->buttonPause->setText(m_paused ? tr("Reprendre") : tr("Pause"));

	#ifdef Q_OS_WIN
		m_taskBarProgress->setPaused(m_paused);
	#endif

	emit paused();
}
void batchWindow::skip()
{
	emit skipped();
}
void batchWindow::cancel()
{
	m_cancel = true;

	#ifdef Q_OS_WIN
		m_taskBarProgress->setVisible(false);
	#endif
}
bool batchWindow::cancelled()
{ return m_cancel; }
void batchWindow::clear()
{
	m_cancel = false;
	m_paused = false;

	m_items = 0;
	m_value = 0;
	m_imagesCount = 0;
	m_images = 0;
	m_maxSpeeds = 0;
	m_lastDownloading = 0;

	m_time->restart();
	m_start->restart();

	ui->tableWidget->clearContents();
	ui->tableWidget->setRowCount(0);
	ui->labelMessage->setText("");
	ui->progressBar->setValue(0);
	ui->progressBar->setMaximum(100);
	ui->labelImages->setText("0/0");
	ui->labelSpeed->setText("");
	ui->cancelButton->setText(tr("Annuler"));

	qDeleteAll(m_progressBars);
	m_progressBars.clear();
	m_speeds.clear();
	m_urls.clear();
	m_mean.clear();

	#ifdef Q_OS_WIN
		m_taskBarProgress->setMinimum(0);
		m_taskBarProgress->setMaximum(0);
		m_taskBarProgress->setValue(0);
		m_taskBarProgress->setVisible(true);
	#endif
}
void batchWindow::copyToClipboard()
{
	QList<QTableWidgetItem *> selected = ui->tableWidget->selectedItems();
	int count = selected.size();
	QStringList urls = QStringList();
	if (count < 1)
	{
		count = ui->tableWidget->rowCount();
		for (int i = 0; i < count; i++)
		{ urls.append(ui->tableWidget->item(i, 2)->text()); }
	}
	else
	{
		for (int i = 0; i < count; i++)
		{
			if (selected.at(i)->icon().isNull())
			{ urls.append(selected.at(i)->text()); }
		}
	}
	qApp->clipboard()->setText(urls.join("\n"));
}

void batchWindow::setCount(int cnt)
{ ui->tableWidget->setRowCount(cnt); }
void batchWindow::addImage(QString url, int batch, float size)
{
	m_urls.append(url);
	QTableWidgetItem *id = new QTableWidgetItem(QString::number(m_items+1));
	id->setIcon(QIcon(":/images/colors/black.png"));
	ui->tableWidget->setItem(m_items, 0, id);
	ui->tableWidget->setItem(m_items, 1, new QTableWidgetItem(QString::number(batch)));
	ui->tableWidget->setItem(m_items, 2, new QTableWidgetItem(url));
	QString unit = getUnit(&size);
	ui->tableWidget->setItem(m_items, 3, new QTableWidgetItem(size != 0 ? QLocale::system().toString(size, 'f', size < 10 ? 2 : 0)+" "+unit : ""));
	ui->tableWidget->setItem(m_items, 4, new QTableWidgetItem());
	ui->tableWidget->setItem(m_items, 5, new QTableWidgetItem("0 %"));
	/* QProgressBar *prog = new QProgressBar(this);
	prog->setTextVisible(false);
	m_progressBars.append(prog);
	ui->tableWidget->setCellWidget(m_items, 5, prog); */
	m_items++;
}
void batchWindow::updateColumns()
{
	QHeaderView *headerView = ui->tableWidget->horizontalHeader();
	headerView->setSectionResizeMode(QHeaderView::Interactive);
	headerView->resizeSection(0, 60);
	headerView->resizeSection(1, 40);
	headerView->resizeSection(2, 80);
	headerView->setSectionResizeMode(2, QHeaderView::Stretch);
	headerView->resizeSection(3, 80);
	headerView->resizeSection(4, 80);
	headerView->resizeSection(5, 80);
	ui->tableWidget->resizeColumnToContents(0);
	ui->tableWidget->repaint();
}
int batchWindow::indexOf(QString url)
{
	int i = m_urls.indexOf(url);
	if (i < 0 || ui->tableWidget->item(i, 1) == NULL)
		return -1;
	return i;
}
int batchWindow::batch(QString url)
{
	int i = indexOf(url);
	if (i == -1)
		return -1;
	return ui->tableWidget->item(i, 1)->text().toInt();
}
void batchWindow::loadingImage(QString url)
{
	if (m_start->isNull())
		m_start->start();
	m_speeds.insert(url, 0);
	if (m_speeds.size() > m_maxSpeeds)
		m_maxSpeeds = m_speeds.size();

	int i = indexOf(url);
	if (i != -1)
	{
		ui->tableWidget->item(i, 0)->setIcon(QIcon(":/images/colors/blue.png"));

		// Go to downloading image
		if (ui->checkScrollToDownload->isChecked() && i >= m_lastDownloading)
		{
			ui->tableWidget->scrollToItem(ui->tableWidget->item(i, 0));
			m_lastDownloading = i;
		}
	}
}
void batchWindow::imageUrlChanged(QString before, QString after)
{
	int i = indexOf(before);
	if (i != -1)
	{
		m_urls[i] = after;
		ui->tableWidget->item(i, 2)->setText(after);
		ui->tableWidget->item(i, 3)->setText("");
		ui->tableWidget->item(i, 4)->setText("");
		ui->tableWidget->item(i, 5)->setText("0 %");
	}
}
void batchWindow::statusImage(QString url, int percent)
{
	int i = indexOf(url);
	if (i != -1)
		ui->tableWidget->item(i, 5)->setText(QString::number(percent)+" %");
}
void batchWindow::speedImage(QString url, float speed)
{
	m_speeds[url] = (int)speed;
	QString unit = getUnit(&speed)+"/s";

	int i = indexOf(url);
	if (i != -1)
		ui->tableWidget->item(i, 4)->setText(QLocale::system().toString(speed, 'f', speed < 10 ? 2 : 0)+" "+unit);

	drawSpeed();
}
void batchWindow::sizeImage(QString url, float size)
{
	int i = indexOf(url);
	if (i != -1)
	{
		QString unit = getUnit(&size);
		ui->tableWidget->setItem(i, 3, new QTableWidgetItem(size != 0 ? QLocale::system().toString(size, 'f', size < 10 ? 2 : 0)+" "+unit : ""));
	}
}
void batchWindow::loadedImage(QString url)
{
	m_speeds.remove(url);
	drawSpeed();

	int i = indexOf(url);
	if (i != -1)
	{
		ui->tableWidget->item(i, 0)->setIcon(QIcon(":/images/colors/green.png"));
		ui->tableWidget->item(i, 4)->setText("");
		ui->tableWidget->item(i, 5)->setText("100 %");
	}
}
void batchWindow::errorImage(QString url)
{
	m_speeds.remove(url);

	int i = indexOf(url);
	if (i != -1)
	{
		ui->tableWidget->item(i, 0)->setIcon(QIcon(":/images/colors/red.png"));
		ui->tableWidget->item(i, 4)->setText("");
	}
}

void batchWindow::drawSpeed()
{
	if (m_time->elapsed() < 1000)
	{ return; }
	m_time->restart();

	int speed = 0;
	for (int sp : m_speeds.values())
	{ speed += sp; }
	if (m_speeds.size() == m_maxSpeeds)
	{ m_mean.append(speed); }
	QString unit = getUnit(&speed)+"/s";

	int speedMean = 0, count = qMin(m_mean.count(), 60);
	if (count > 0)
	{
		for (int i = m_mean.count() - count; i < m_mean.count() - 1; i++)
		{ speedMean += m_mean[i]; }
		speedMean = (int)(speedMean/count);
	}
	QString unitMean = getUnit(&speedMean)+"/s";

	int elapsed = m_start->elapsed();
	int remaining = m_images > 0 ? (int)((elapsed * m_imagesCount) / m_images) : 0;
	QTime tElapsed, tRemaining;
	tElapsed = tElapsed.addMSecs(elapsed);
	tRemaining = tRemaining.addMSecs(remaining);
	QString fElapsed = elapsed > 3600000 ? tr("h 'h' m 'm' s 's'") : (elapsed > 60000 ? tr("m 'm' s 's'") : tr("s 's'"));
	QString fRemaining = remaining > 3600000 ? tr("h 'h' m 'm' s 's'") : (remaining > 60000 ? tr("m 'm' s 's'") : tr("s 's'"));

	ui->labelSpeed->setText(QLocale::system().toString((float)speed, 'f', speed < 10 ? 2 : 0)+" "+unit);
	ui->labelSpeed->setToolTip(tr("Vitesse moyenne : %1 %2

Temps écoulé : %3
Temps restant : %4").arg(QLocale::system().toString((float)speedMean, 'f', speedMean < 10 ? 2 : 0), unitMean, tElapsed.toString(fElapsed), tRemaining.toString(fRemaining)));
}

void batchWindow::on_buttonDetails_clicked(bool visible)
{
	if (ui->details->isHidden() || visible)
	{
		ui->details->show();
		resize(m_currentSize);
	}
	else
	{
		ui->details->hide();
		m_currentSize = size();
		resize(QSize(300, 0));
	}
}

void batchWindow::setText(QString text)
{ ui->labelMessage->setText(text); }
void batchWindow::setValue(int value)
{
	m_value = value;
	ui->progressBar->setValue(m_value);
	if (ui->progressBar->maximum() <= m_value)
	{ ui->cancelButton->setText(tr("Fermer")); }

	#ifdef Q_OS_WIN
		m_taskBarProgress->setValue(value);
	#endif
}
void batchWindow::setLittleValue(int)
{ /*ui->progressBar->setValue(m_value + value);*/ }
void batchWindow::setMaximum(int value)
{
	ui->progressBar->setMaximum(value);

	#ifdef Q_OS_WIN
		m_taskBarProgress->setMaximum(value);
	#endif
}
void batchWindow::setImagesCount(int value)
{
	m_imagesCount = value;
	ui->labelImages->setText(QString("0/%2").arg(m_imagesCount));
	ui->progressBar->setMaximum(value);

	#ifdef Q_OS_WIN
		m_taskBarProgress->setMaximum(value);
	#endif
}
void batchWindow::setImages(int value)
{
	m_images = value;
	ui->labelImages->setText(QString("%1/%2").arg(m_images).arg(m_imagesCount));
	ui->progressBar->setValue(value);

	#ifdef Q_OS_WIN
		m_taskBarProgress->setValue(value);
	#endif
}

int batchWindow::value()		{ return m_value;						}
int batchWindow::maximum()		{ return ui->progressBar->maximum();	}
int batchWindow::images()		{ return m_images;						}
int batchWindow::count()		{ return m_imagesCount;					}
int batchWindow::endAction()	{ return ui->comboEnd->currentIndex();	}
bool batchWindow::endRemove()	{ return ui->checkRemove->isChecked();	}
bool batchWindow::isPaused()	{ return m_paused;						}
<commit_msg>Add minimize button to batch window (fix #587)<commit_after>#include <QSettings>
#include <QTime>
#include <QCloseEvent>
#include <QClipboard>
#include "batchwindow.h"
#include "ui_batchwindow.h"
#include "functions.h"

#define SAMPLES 100

batchWindow::batchWindow(QWidget *parent)
	: QDialog(), ui(new Ui::batchWindow), m_imagesCount(0), m_items(0), m_images(0), m_maxSpeeds(0), m_lastDownloading(0), m_cancel(false), m_paused(false)
{
	ui->setupUi(this);
	ui->tableWidget->resizeColumnToContents(0);
	m_currentSize = size();

	QSettings settings(savePath("settings.ini"), QSettings::IniFormat);
	restoreGeometry(settings.value("Batch/geometry").toByteArray());
	ui->buttonDetails->setChecked(settings.value("Batch/details", true).toBool());
	on_buttonDetails_clicked(settings.value("Batch/details", true).toBool());
	ui->comboEnd->setCurrentIndex(settings.value("Batch/end", 0).toInt());
	ui->checkRemove->setChecked(settings.value("Batch/remove", false).toBool());
	ui->checkScrollToDownload->setChecked(settings.value("Batch/scrollToDownload", true).toBool());

	m_speeds = QMap<QString, int>();
	m_urls = QStringList();

	m_time = new QTime;
	m_time->start();
	m_start = new QTime;

	#ifdef Q_OS_WIN
		m_taskBarButton = new QWinTaskbarButton(parent);
		m_taskBarButton->setWindow(parent->windowHandle());

		m_taskBarProgress = m_taskBarButton->progress();
		m_taskBarProgress->setVisible(false);
		m_taskBarProgress->setMinimum(0);
		m_taskBarProgress->setMaximum(0);
		m_taskBarProgress->setValue(0);
	#endif

	// Allow dialog minimization
	setWindowFlags(windowFlags() | Qt::WindowMinimizeButtonHint);
}

batchWindow::~batchWindow()
{
	delete ui;

	#ifdef Q_OS_WIN
		m_taskBarButton->deleteLater();
		m_taskBarProgress->deleteLater();
	#endif
}
void batchWindow::closeEvent(QCloseEvent *e)
{
	QSettings settings(savePath("settings.ini"), QSettings::IniFormat);
	settings.setValue("Batch/geometry", saveGeometry());
	settings.setValue("Batch/details", ui->buttonDetails->isChecked());
	settings.setValue("Batch/end", ui->comboEnd->currentIndex());
	settings.setValue("Batch/remove", ui->checkRemove->isChecked());
	settings.setValue("Batch/scrollToDownload", ui->checkScrollToDownload->isChecked());
	settings.sync();

	if (m_images < m_imagesCount)
	{
		cancel();
		emit rejected();
	}
	else
	{ clear(); }

	#ifdef Q_OS_WIN
		m_taskBarProgress->setVisible(false);
	#endif

	emit closed();
	e->accept();
}
void batchWindow::pause()
{
	m_paused = !m_paused;
	ui->labelSpeed->setText(m_paused ? tr("En pause") : "");
	ui->buttonPause->setText(m_paused ? tr("Reprendre") : tr("Pause"));

	#ifdef Q_OS_WIN
		m_taskBarProgress->setPaused(m_paused);
	#endif

	emit paused();
}
void batchWindow::skip()
{
	emit skipped();
}
void batchWindow::cancel()
{
	m_cancel = true;

	#ifdef Q_OS_WIN
		m_taskBarProgress->setVisible(false);
	#endif
}
bool batchWindow::cancelled()
{ return m_cancel; }
void batchWindow::clear()
{
	m_cancel = false;
	m_paused = false;

	m_items = 0;
	m_value = 0;
	m_imagesCount = 0;
	m_images = 0;
	m_maxSpeeds = 0;
	m_lastDownloading = 0;

	m_time->restart();
	m_start->restart();

	ui->tableWidget->clearContents();
	ui->tableWidget->setRowCount(0);
	ui->labelMessage->setText("");
	ui->progressBar->setValue(0);
	ui->progressBar->setMaximum(100);
	ui->labelImages->setText("0/0");
	ui->labelSpeed->setText("");
	ui->cancelButton->setText(tr("Annuler"));

	qDeleteAll(m_progressBars);
	m_progressBars.clear();
	m_speeds.clear();
	m_urls.clear();
	m_mean.clear();

	#ifdef Q_OS_WIN
		m_taskBarProgress->setMinimum(0);
		m_taskBarProgress->setMaximum(0);
		m_taskBarProgress->setValue(0);
		m_taskBarProgress->setVisible(true);
	#endif
}
void batchWindow::copyToClipboard()
{
	QList<QTableWidgetItem *> selected = ui->tableWidget->selectedItems();
	int count = selected.size();
	QStringList urls = QStringList();
	if (count < 1)
	{
		count = ui->tableWidget->rowCount();
		for (int i = 0; i < count; i++)
		{ urls.append(ui->tableWidget->item(i, 2)->text()); }
	}
	else
	{
		for (int i = 0; i < count; i++)
		{
			if (selected.at(i)->icon().isNull())
			{ urls.append(selected.at(i)->text()); }
		}
	}
	qApp->clipboard()->setText(urls.join("\n"));
}

void batchWindow::setCount(int cnt)
{ ui->tableWidget->setRowCount(cnt); }
void batchWindow::addImage(QString url, int batch, float size)
{
	m_urls.append(url);
	QTableWidgetItem *id = new QTableWidgetItem(QString::number(m_items+1));
	id->setIcon(QIcon(":/images/colors/black.png"));
	ui->tableWidget->setItem(m_items, 0, id);
	ui->tableWidget->setItem(m_items, 1, new QTableWidgetItem(QString::number(batch)));
	ui->tableWidget->setItem(m_items, 2, new QTableWidgetItem(url));
	QString unit = getUnit(&size);
	ui->tableWidget->setItem(m_items, 3, new QTableWidgetItem(size != 0 ? QLocale::system().toString(size, 'f', size < 10 ? 2 : 0)+" "+unit : ""));
	ui->tableWidget->setItem(m_items, 4, new QTableWidgetItem());
	ui->tableWidget->setItem(m_items, 5, new QTableWidgetItem("0 %"));
	/* QProgressBar *prog = new QProgressBar(this);
	prog->setTextVisible(false);
	m_progressBars.append(prog);
	ui->tableWidget->setCellWidget(m_items, 5, prog); */
	m_items++;
}
void batchWindow::updateColumns()
{
	QHeaderView *headerView = ui->tableWidget->horizontalHeader();
	headerView->setSectionResizeMode(QHeaderView::Interactive);
	headerView->resizeSection(0, 60);
	headerView->resizeSection(1, 40);
	headerView->resizeSection(2, 80);
	headerView->setSectionResizeMode(2, QHeaderView::Stretch);
	headerView->resizeSection(3, 80);
	headerView->resizeSection(4, 80);
	headerView->resizeSection(5, 80);
	ui->tableWidget->resizeColumnToContents(0);
	ui->tableWidget->repaint();
}
int batchWindow::indexOf(QString url)
{
	int i = m_urls.indexOf(url);
	if (i < 0 || ui->tableWidget->item(i, 1) == NULL)
		return -1;
	return i;
}
int batchWindow::batch(QString url)
{
	int i = indexOf(url);
	if (i == -1)
		return -1;
	return ui->tableWidget->item(i, 1)->text().toInt();
}
void batchWindow::loadingImage(QString url)
{
	if (m_start->isNull())
		m_start->start();
	m_speeds.insert(url, 0);
	if (m_speeds.size() > m_maxSpeeds)
		m_maxSpeeds = m_speeds.size();

	int i = indexOf(url);
	if (i != -1)
	{
		ui->tableWidget->item(i, 0)->setIcon(QIcon(":/images/colors/blue.png"));

		// Go to downloading image
		if (ui->checkScrollToDownload->isChecked() && i >= m_lastDownloading)
		{
			ui->tableWidget->scrollToItem(ui->tableWidget->item(i, 0));
			m_lastDownloading = i;
		}
	}
}
void batchWindow::imageUrlChanged(QString before, QString after)
{
	int i = indexOf(before);
	if (i != -1)
	{
		m_urls[i] = after;
		ui->tableWidget->item(i, 2)->setText(after);
		ui->tableWidget->item(i, 3)->setText("");
		ui->tableWidget->item(i, 4)->setText("");
		ui->tableWidget->item(i, 5)->setText("0 %");
	}
}
void batchWindow::statusImage(QString url, int percent)
{
	int i = indexOf(url);
	if (i != -1)
		ui->tableWidget->item(i, 5)->setText(QString::number(percent)+" %");
}
void batchWindow::speedImage(QString url, float speed)
{
	m_speeds[url] = (int)speed;
	QString unit = getUnit(&speed)+"/s";

	int i = indexOf(url);
	if (i != -1)
		ui->tableWidget->item(i, 4)->setText(QLocale::system().toString(speed, 'f', speed < 10 ? 2 : 0)+" "+unit);

	drawSpeed();
}
void batchWindow::sizeImage(QString url, float size)
{
	int i = indexOf(url);
	if (i != -1)
	{
		QString unit = getUnit(&size);
		ui->tableWidget->setItem(i, 3, new QTableWidgetItem(size != 0 ? QLocale::system().toString(size, 'f', size < 10 ? 2 : 0)+" "+unit : ""));
	}
}
void batchWindow::loadedImage(QString url)
{
	m_speeds.remove(url);
	drawSpeed();

	int i = indexOf(url);
	if (i != -1)
	{
		ui->tableWidget->item(i, 0)->setIcon(QIcon(":/images/colors/green.png"));
		ui->tableWidget->item(i, 4)->setText("");
		ui->tableWidget->item(i, 5)->setText("100 %");
	}
}
void batchWindow::errorImage(QString url)
{
	m_speeds.remove(url);

	int i = indexOf(url);
	if (i != -1)
	{
		ui->tableWidget->item(i, 0)->setIcon(QIcon(":/images/colors/red.png"));
		ui->tableWidget->item(i, 4)->setText("");
	}
}

void batchWindow::drawSpeed()
{
	if (m_time->elapsed() < 1000)
	{ return; }
	m_time->restart();

	int speed = 0;
	for (int sp : m_speeds.values())
	{ speed += sp; }
	if (m_speeds.size() == m_maxSpeeds)
	{ m_mean.append(speed); }
	QString unit = getUnit(&speed)+"/s";

	int speedMean = 0, count = qMin(m_mean.count(), 60);
	if (count > 0)
	{
		for (int i = m_mean.count() - count; i < m_mean.count() - 1; i++)
		{ speedMean += m_mean[i]; }
		speedMean = (int)(speedMean/count);
	}
	QString unitMean = getUnit(&speedMean)+"/s";

	int elapsed = m_start->elapsed();
	int remaining = m_images > 0 ? (int)((elapsed * m_imagesCount) / m_images) : 0;
	QTime tElapsed, tRemaining;
	tElapsed = tElapsed.addMSecs(elapsed);
	tRemaining = tRemaining.addMSecs(remaining);
	QString fElapsed = elapsed > 3600000 ? tr("h 'h' m 'm' s 's'") : (elapsed > 60000 ? tr("m 'm' s 's'") : tr("s 's'"));
	QString fRemaining = remaining > 3600000 ? tr("h 'h' m 'm' s 's'") : (remaining > 60000 ? tr("m 'm' s 's'") : tr("s 's'"));

	ui->labelSpeed->setText(QLocale::system().toString((float)speed, 'f', speed < 10 ? 2 : 0)+" "+unit);
	ui->labelSpeed->setToolTip(tr("Vitesse moyenne : %1 %2

Temps écoulé : %3
Temps restant : %4").arg(QLocale::system().toString((float)speedMean, 'f', speedMean < 10 ? 2 : 0), unitMean, tElapsed.toString(fElapsed), tRemaining.toString(fRemaining)));
}

void batchWindow::on_buttonDetails_clicked(bool visible)
{
	if (ui->details->isHidden() || visible)
	{
		ui->details->show();
		resize(m_currentSize);
	}
	else
	{
		ui->details->hide();
		m_currentSize = size();
		resize(QSize(300, 0));
	}
}

void batchWindow::setText(QString text)
{ ui->labelMessage->setText(text); }
void batchWindow::setValue(int value)
{
	m_value = value;
	ui->progressBar->setValue(m_value);
	if (ui->progressBar->maximum() <= m_value)
	{ ui->cancelButton->setText(tr("Fermer")); }

	#ifdef Q_OS_WIN
		m_taskBarProgress->setValue(value);
	#endif
}
void batchWindow::setLittleValue(int)
{ /*ui->progressBar->setValue(m_value + value);*/ }
void batchWindow::setMaximum(int value)
{
	ui->progressBar->setMaximum(value);

	#ifdef Q_OS_WIN
		m_taskBarProgress->setMaximum(value);
	#endif
}
void batchWindow::setImagesCount(int value)
{
	m_imagesCount = value;
	ui->labelImages->setText(QString("0/%2").arg(m_imagesCount));
	ui->progressBar->setMaximum(value);

	#ifdef Q_OS_WIN
		m_taskBarProgress->setMaximum(value);
	#endif
}
void batchWindow::setImages(int value)
{
	m_images = value;
	ui->labelImages->setText(QString("%1/%2").arg(m_images).arg(m_imagesCount));
	ui->progressBar->setValue(value);

	#ifdef Q_OS_WIN
		m_taskBarProgress->setValue(value);
	#endif
}

int batchWindow::value()		{ return m_value;						}
int batchWindow::maximum()		{ return ui->progressBar->maximum();	}
int batchWindow::images()		{ return m_images;						}
int batchWindow::count()		{ return m_imagesCount;					}
int batchWindow::endAction()	{ return ui->comboEnd->currentIndex();	}
bool batchWindow::endRemove()	{ return ui->checkRemove->isChecked();	}
bool batchWindow::isPaused()	{ return m_paused;						}
<|endoftext|>


<commit_before>//===-- MipsRegisterInfo.cpp - MIPS Register Information -== --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the MIPS implementation of the TargetRegisterInfo class.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "mips-reg-info"

#include "MipsRegisterInfo.h"
#include "Mips.h"
#include "MipsAnalyzeImmediate.h"
#include "MipsSubtarget.h"
#include "MipsMachineFunction.h"
#include "llvm/Constants.h"
#include "llvm/Type.h"
#include "llvm/Function.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/Target/TargetFrameLowering.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/DebugInfo.h"

#define GET_REGINFO_TARGET_DESC
#include "MipsGenRegisterInfo.inc"

using namespace llvm;

MipsRegisterInfo::MipsRegisterInfo(const MipsSubtarget &ST,
                                   const TargetInstrInfo &tii)
  : MipsGenRegisterInfo(Mips::RA), Subtarget(ST), TII(tii) {}

unsigned MipsRegisterInfo::getPICCallReg() { return Mips::T9; }

//===----------------------------------------------------------------------===//
// Callee Saved Registers methods
//===----------------------------------------------------------------------===//

/// Mips Callee Saved Registers
const uint16_t* MipsRegisterInfo::
getCalleeSavedRegs(const MachineFunction *MF) const
{
  if (Subtarget.isSingleFloat())
    return CSR_SingleFloatOnly_SaveList;
  else if (!Subtarget.hasMips64())
    return CSR_O32_SaveList;
  else if (Subtarget.isABI_N32())
    return CSR_N32_SaveList;

  assert(Subtarget.isABI_N64());
  return CSR_N64_SaveList;
}

const uint32_t*
MipsRegisterInfo::getCallPreservedMask(CallingConv::ID) const
{
  if (Subtarget.isSingleFloat())
    return CSR_SingleFloatOnly_RegMask;
  else if (!Subtarget.hasMips64())
    return CSR_O32_RegMask;
  else if (Subtarget.isABI_N32())
    return CSR_N32_RegMask;

  assert(Subtarget.isABI_N64());
  return CSR_N64_RegMask;
}

BitVector MipsRegisterInfo::
getReservedRegs(const MachineFunction &MF) const {
  static const uint16_t ReservedCPURegs[] = {
    Mips::ZERO, Mips::AT, Mips::K0, Mips::K1,
    Mips::SP, Mips::RA
  };

  static const uint16_t ReservedCPU64Regs[] = {
    Mips::ZERO_64, Mips::AT_64, Mips::K0_64, Mips::K1_64,
    Mips::SP_64, Mips::RA_64
  };

  BitVector Reserved(getNumRegs());
  typedef TargetRegisterClass::const_iterator RegIter;

  for (unsigned I = 0; I < array_lengthof(ReservedCPURegs); ++I)
    Reserved.set(ReservedCPURegs[I]);

  if (Subtarget.hasMips64()) {
    for (unsigned I = 0; I < array_lengthof(ReservedCPU64Regs); ++I)
      Reserved.set(ReservedCPU64Regs[I]);

    // Reserve all registers in AFGR64.
    for (RegIter Reg = Mips::AFGR64RegClass.begin(),
         EReg = Mips::AFGR64RegClass.end(); Reg != EReg; ++Reg)
      Reserved.set(*Reg);
  } else {
    // Reserve all registers in CPU64Regs & FGR64.
    for (RegIter Reg = Mips::CPU64RegsRegClass.begin(),
         EReg = Mips::CPU64RegsRegClass.end(); Reg != EReg; ++Reg)
      Reserved.set(*Reg);

    for (RegIter Reg = Mips::FGR64RegClass.begin(),
         EReg = Mips::FGR64RegClass.end(); Reg != EReg; ++Reg)
      Reserved.set(*Reg);
  }

  // If GP is dedicated as a global base register, reserve it.
  if (MF.getInfo<MipsFunctionInfo>()->globalBaseRegFixed()) {
    Reserved.set(Mips::GP);
    Reserved.set(Mips::GP_64);
  }

  // If this function has dynamic allocas, reserve FP.
  if (MF.getTarget().getFrameLowering()->hasFP(MF)) {
    Reserved.set(Mips::FP);
    Reserved.set(Mips::FP_64);
  }

  // Reserve hardware registers.
  Reserved.set(Mips::HWR29);
  Reserved.set(Mips::HWR29_64);

  return Reserved;
}

bool
MipsRegisterInfo::requiresRegisterScavenging(const MachineFunction &MF) const {
  return true;
}

bool
MipsRegisterInfo::trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
  return true;
}

// This function eliminate ADJCALLSTACKDOWN,
// ADJCALLSTACKUP pseudo instructions
void MipsRegisterInfo::
eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
                              MachineBasicBlock::iterator I) const {
  // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
  MBB.erase(I);
}

// FrameIndex represent objects inside a abstract stack.
// We must replace FrameIndex with an stack/frame pointer
// direct reference.
void MipsRegisterInfo::
eliminateFrameIndex(MachineBasicBlock::iterator II, int SPAdj,
                    RegScavenger *RS) const {
  MachineInstr &MI = *II;
  MachineFunction &MF = *MI.getParent()->getParent();
  MachineFrameInfo *MFI = MF.getFrameInfo();
  MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();

  unsigned i = 0;
  while (!MI.getOperand(i).isFI()) {
    ++i;
    assert(i < MI.getNumOperands() &&
           "Instr doesn't have FrameIndex operand!");
  }

  DEBUG(errs() << "\nFunction : " << MF.getFunction()->getName() << "\n";
        errs() << "<--------->\n" << MI);

  int FrameIndex = MI.getOperand(i).getIndex();
  uint64_t stackSize = MF.getFrameInfo()->getStackSize();
  int64_t spOffset = MF.getFrameInfo()->getObjectOffset(FrameIndex);

  DEBUG(errs() << "FrameIndex : " << FrameIndex << "\n"
               << "spOffset   : " << spOffset << "\n"
               << "stackSize  : " << stackSize << "\n");

  const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
  int MinCSFI = 0;
  int MaxCSFI = -1;

  if (CSI.size()) {
    MinCSFI = CSI[0].getFrameIdx();
    MaxCSFI = CSI[CSI.size() - 1].getFrameIdx();
  }

  // The following stack frame objects are always referenced relative to $sp:
  //  1. Outgoing arguments.
  //  2. Pointer to dynamically allocated stack space.
  //  3. Locations for callee-saved registers.
  // Everything else is referenced relative to whatever register
  // getFrameRegister() returns.
  unsigned FrameReg;

  if (MipsFI->isOutArgFI(FrameIndex) || MipsFI->isDynAllocFI(FrameIndex) ||
      (FrameIndex >= MinCSFI && FrameIndex <= MaxCSFI))
    FrameReg = Subtarget.isABI_N64() ? Mips::SP_64 : Mips::SP;
  else
    FrameReg = getFrameRegister(MF);

  // Calculate final offset.
  // - There is no need to change the offset if the frame object is one of the
  //   following: an outgoing argument, pointer to a dynamically allocated
  //   stack space or a $gp restore location,
  // - If the frame object is any of the following, its offset must be adjusted
  //   by adding the size of the stack:
  //   incoming argument, callee-saved register location or local variable.
  int64_t Offset;

  if (MipsFI->isOutArgFI(FrameIndex) || MipsFI->isGPFI(FrameIndex) ||
      MipsFI->isDynAllocFI(FrameIndex))
    Offset = spOffset;
  else
    Offset = spOffset + (int64_t)stackSize;

  Offset    += MI.getOperand(i+1).getImm();

  DEBUG(errs() << "Offset     : " << Offset << "\n" << "<--------->\n");

  // If MI is not a debug value, make sure Offset fits in the 16-bit immediate
  // field.
  if (!MI.isDebugValue() && !isInt<16>(Offset)) {
    MachineBasicBlock &MBB = *MI.getParent();
    DebugLoc DL = II->getDebugLoc();
    MipsAnalyzeImmediate AnalyzeImm;
    unsigned Size = Subtarget.isABI_N64() ? 64 : 32;
    unsigned LUi = Subtarget.isABI_N64() ? Mips::LUi64 : Mips::LUi;
    unsigned ADDu = Subtarget.isABI_N64() ? Mips::DADDu : Mips::ADDu;
    unsigned ZEROReg = Subtarget.isABI_N64() ? Mips::ZERO_64 : Mips::ZERO;
    unsigned ATReg = Subtarget.isABI_N64() ? Mips::AT_64 : Mips::AT;
    const MipsAnalyzeImmediate::InstSeq &Seq =
      AnalyzeImm.Analyze(Offset, Size, true /* LastInstrIsADDiu */);
    MipsAnalyzeImmediate::InstSeq::const_iterator Inst = Seq.begin();

    MipsFI->setEmitNOAT();

    // The first instruction can be a LUi, which is different from other
    // instructions (ADDiu, ORI and SLL) in that it does not have a register
    // operand.
    if (Inst->Opc == LUi)
      BuildMI(MBB, II, DL, TII.get(LUi), ATReg)
        .addImm(SignExtend64<16>(Inst->ImmOpnd));
    else
      BuildMI(MBB, II, DL, TII.get(Inst->Opc), ATReg).addReg(ZEROReg)
        .addImm(SignExtend64<16>(Inst->ImmOpnd));

    // Build the remaining instructions in Seq except for the last one.
    for (++Inst; Inst != Seq.end() - 1; ++Inst)
      BuildMI(MBB, II, DL, TII.get(Inst->Opc), ATReg).addReg(ATReg)
        .addImm(SignExtend64<16>(Inst->ImmOpnd));

    BuildMI(MBB, II, DL, TII.get(ADDu), ATReg).addReg(FrameReg).addReg(ATReg);

    FrameReg = ATReg;
    Offset = SignExtend64<16>(Inst->ImmOpnd);
  }

  MI.getOperand(i).ChangeToRegister(FrameReg, false);
  MI.getOperand(i+1).ChangeToImmediate(Offset);
}

unsigned MipsRegisterInfo::
getFrameRegister(const MachineFunction &MF) const {
  const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
  bool IsN64 = Subtarget.isABI_N64();

  return TFI->hasFP(MF) ? (IsN64 ? Mips::FP_64 : Mips::FP) :
                          (IsN64 ? Mips::SP_64 : Mips::SP);
}

unsigned MipsRegisterInfo::
getEHExceptionRegister() const {
  llvm_unreachable("What is the exception register");
}

unsigned MipsRegisterInfo::
getEHHandlerRegister() const {
  llvm_unreachable("What is the exception handler register");
}
<commit_msg>Fix a misleading comment.<commit_after>//===-- MipsRegisterInfo.cpp - MIPS Register Information -== --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the MIPS implementation of the TargetRegisterInfo class.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "mips-reg-info"

#include "MipsRegisterInfo.h"
#include "Mips.h"
#include "MipsAnalyzeImmediate.h"
#include "MipsSubtarget.h"
#include "MipsMachineFunction.h"
#include "llvm/Constants.h"
#include "llvm/Type.h"
#include "llvm/Function.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/Target/TargetFrameLowering.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/DebugInfo.h"

#define GET_REGINFO_TARGET_DESC
#include "MipsGenRegisterInfo.inc"

using namespace llvm;

MipsRegisterInfo::MipsRegisterInfo(const MipsSubtarget &ST,
                                   const TargetInstrInfo &tii)
  : MipsGenRegisterInfo(Mips::RA), Subtarget(ST), TII(tii) {}

unsigned MipsRegisterInfo::getPICCallReg() { return Mips::T9; }

//===----------------------------------------------------------------------===//
// Callee Saved Registers methods
//===----------------------------------------------------------------------===//

/// Mips Callee Saved Registers
const uint16_t* MipsRegisterInfo::
getCalleeSavedRegs(const MachineFunction *MF) const
{
  if (Subtarget.isSingleFloat())
    return CSR_SingleFloatOnly_SaveList;
  else if (!Subtarget.hasMips64())
    return CSR_O32_SaveList;
  else if (Subtarget.isABI_N32())
    return CSR_N32_SaveList;

  assert(Subtarget.isABI_N64());
  return CSR_N64_SaveList;
}

const uint32_t*
MipsRegisterInfo::getCallPreservedMask(CallingConv::ID) const
{
  if (Subtarget.isSingleFloat())
    return CSR_SingleFloatOnly_RegMask;
  else if (!Subtarget.hasMips64())
    return CSR_O32_RegMask;
  else if (Subtarget.isABI_N32())
    return CSR_N32_RegMask;

  assert(Subtarget.isABI_N64());
  return CSR_N64_RegMask;
}

BitVector MipsRegisterInfo::
getReservedRegs(const MachineFunction &MF) const {
  static const uint16_t ReservedCPURegs[] = {
    Mips::ZERO, Mips::AT, Mips::K0, Mips::K1,
    Mips::SP, Mips::RA
  };

  static const uint16_t ReservedCPU64Regs[] = {
    Mips::ZERO_64, Mips::AT_64, Mips::K0_64, Mips::K1_64,
    Mips::SP_64, Mips::RA_64
  };

  BitVector Reserved(getNumRegs());
  typedef TargetRegisterClass::const_iterator RegIter;

  for (unsigned I = 0; I < array_lengthof(ReservedCPURegs); ++I)
    Reserved.set(ReservedCPURegs[I]);

  if (Subtarget.hasMips64()) {
    for (unsigned I = 0; I < array_lengthof(ReservedCPU64Regs); ++I)
      Reserved.set(ReservedCPU64Regs[I]);

    // Reserve all registers in AFGR64.
    for (RegIter Reg = Mips::AFGR64RegClass.begin(),
         EReg = Mips::AFGR64RegClass.end(); Reg != EReg; ++Reg)
      Reserved.set(*Reg);
  } else {
    // Reserve all registers in CPU64Regs & FGR64.
    for (RegIter Reg = Mips::CPU64RegsRegClass.begin(),
         EReg = Mips::CPU64RegsRegClass.end(); Reg != EReg; ++Reg)
      Reserved.set(*Reg);

    for (RegIter Reg = Mips::FGR64RegClass.begin(),
         EReg = Mips::FGR64RegClass.end(); Reg != EReg; ++Reg)
      Reserved.set(*Reg);
  }

  // If GP is dedicated as a global base register, reserve it.
  if (MF.getInfo<MipsFunctionInfo>()->globalBaseRegFixed()) {
    Reserved.set(Mips::GP);
    Reserved.set(Mips::GP_64);
  }

  // Reserve FP if this function should have a dedicated frame pointer register.
  if (MF.getTarget().getFrameLowering()->hasFP(MF)) {
    Reserved.set(Mips::FP);
    Reserved.set(Mips::FP_64);
  }

  // Reserve hardware registers.
  Reserved.set(Mips::HWR29);
  Reserved.set(Mips::HWR29_64);

  return Reserved;
}

bool
MipsRegisterInfo::requiresRegisterScavenging(const MachineFunction &MF) const {
  return true;
}

bool
MipsRegisterInfo::trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
  return true;
}

// This function eliminate ADJCALLSTACKDOWN,
// ADJCALLSTACKUP pseudo instructions
void MipsRegisterInfo::
eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
                              MachineBasicBlock::iterator I) const {
  // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
  MBB.erase(I);
}

// FrameIndex represent objects inside a abstract stack.
// We must replace FrameIndex with an stack/frame pointer
// direct reference.
void MipsRegisterInfo::
eliminateFrameIndex(MachineBasicBlock::iterator II, int SPAdj,
                    RegScavenger *RS) const {
  MachineInstr &MI = *II;
  MachineFunction &MF = *MI.getParent()->getParent();
  MachineFrameInfo *MFI = MF.getFrameInfo();
  MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();

  unsigned i = 0;
  while (!MI.getOperand(i).isFI()) {
    ++i;
    assert(i < MI.getNumOperands() &&
           "Instr doesn't have FrameIndex operand!");
  }

  DEBUG(errs() << "\nFunction : " << MF.getFunction()->getName() << "\n";
        errs() << "<--------->\n" << MI);

  int FrameIndex = MI.getOperand(i).getIndex();
  uint64_t stackSize = MF.getFrameInfo()->getStackSize();
  int64_t spOffset = MF.getFrameInfo()->getObjectOffset(FrameIndex);

  DEBUG(errs() << "FrameIndex : " << FrameIndex << "\n"
               << "spOffset   : " << spOffset << "\n"
               << "stackSize  : " << stackSize << "\n");

  const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
  int MinCSFI = 0;
  int MaxCSFI = -1;

  if (CSI.size()) {
    MinCSFI = CSI[0].getFrameIdx();
    MaxCSFI = CSI[CSI.size() - 1].getFrameIdx();
  }

  // The following stack frame objects are always referenced relative to $sp:
  //  1. Outgoing arguments.
  //  2. Pointer to dynamically allocated stack space.
  //  3. Locations for callee-saved registers.
  // Everything else is referenced relative to whatever register
  // getFrameRegister() returns.
  unsigned FrameReg;

  if (MipsFI->isOutArgFI(FrameIndex) || MipsFI->isDynAllocFI(FrameIndex) ||
      (FrameIndex >= MinCSFI && FrameIndex <= MaxCSFI))
    FrameReg = Subtarget.isABI_N64() ? Mips::SP_64 : Mips::SP;
  else
    FrameReg = getFrameRegister(MF);

  // Calculate final offset.
  // - There is no need to change the offset if the frame object is one of the
  //   following: an outgoing argument, pointer to a dynamically allocated
  //   stack space or a $gp restore location,
  // - If the frame object is any of the following, its offset must be adjusted
  //   by adding the size of the stack:
  //   incoming argument, callee-saved register location or local variable.
  int64_t Offset;

  if (MipsFI->isOutArgFI(FrameIndex) || MipsFI->isGPFI(FrameIndex) ||
      MipsFI->isDynAllocFI(FrameIndex))
    Offset = spOffset;
  else
    Offset = spOffset + (int64_t)stackSize;

  Offset    += MI.getOperand(i+1).getImm();

  DEBUG(errs() << "Offset     : " << Offset << "\n" << "<--------->\n");

  // If MI is not a debug value, make sure Offset fits in the 16-bit immediate
  // field.
  if (!MI.isDebugValue() && !isInt<16>(Offset)) {
    MachineBasicBlock &MBB = *MI.getParent();
    DebugLoc DL = II->getDebugLoc();
    MipsAnalyzeImmediate AnalyzeImm;
    unsigned Size = Subtarget.isABI_N64() ? 64 : 32;
    unsigned LUi = Subtarget.isABI_N64() ? Mips::LUi64 : Mips::LUi;
    unsigned ADDu = Subtarget.isABI_N64() ? Mips::DADDu : Mips::ADDu;
    unsigned ZEROReg = Subtarget.isABI_N64() ? Mips::ZERO_64 : Mips::ZERO;
    unsigned ATReg = Subtarget.isABI_N64() ? Mips::AT_64 : Mips::AT;
    const MipsAnalyzeImmediate::InstSeq &Seq =
      AnalyzeImm.Analyze(Offset, Size, true /* LastInstrIsADDiu */);
    MipsAnalyzeImmediate::InstSeq::const_iterator Inst = Seq.begin();

    MipsFI->setEmitNOAT();

    // The first instruction can be a LUi, which is different from other
    // instructions (ADDiu, ORI and SLL) in that it does not have a register
    // operand.
    if (Inst->Opc == LUi)
      BuildMI(MBB, II, DL, TII.get(LUi), ATReg)
        .addImm(SignExtend64<16>(Inst->ImmOpnd));
    else
      BuildMI(MBB, II, DL, TII.get(Inst->Opc), ATReg).addReg(ZEROReg)
        .addImm(SignExtend64<16>(Inst->ImmOpnd));

    // Build the remaining instructions in Seq except for the last one.
    for (++Inst; Inst != Seq.end() - 1; ++Inst)
      BuildMI(MBB, II, DL, TII.get(Inst->Opc), ATReg).addReg(ATReg)
        .addImm(SignExtend64<16>(Inst->ImmOpnd));

    BuildMI(MBB, II, DL, TII.get(ADDu), ATReg).addReg(FrameReg).addReg(ATReg);

    FrameReg = ATReg;
    Offset = SignExtend64<16>(Inst->ImmOpnd);
  }

  MI.getOperand(i).ChangeToRegister(FrameReg, false);
  MI.getOperand(i+1).ChangeToImmediate(Offset);
}

unsigned MipsRegisterInfo::
getFrameRegister(const MachineFunction &MF) const {
  const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
  bool IsN64 = Subtarget.isABI_N64();

  return TFI->hasFP(MF) ? (IsN64 ? Mips::FP_64 : Mips::FP) :
                          (IsN64 ? Mips::SP_64 : Mips::SP);
}

unsigned MipsRegisterInfo::
getEHExceptionRegister() const {
  llvm_unreachable("What is the exception register");
}

unsigned MipsRegisterInfo::
getEHHandlerRegister() const {
  llvm_unreachable("What is the exception handler register");
}
<|endoftext|>


<commit_before>//===- TextStubCommon.cpp -------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Implememts common Text Stub YAML mappings.
//
//===----------------------------------------------------------------------===//

#include "TextStubCommon.h"
#include "TextAPIContext.h"

using namespace llvm::MachO;

namespace llvm {
namespace yaml {

void ScalarTraits<FlowStringRef>::output(const FlowStringRef &Value, void *Ctx,
                                         raw_ostream &OS) {
  ScalarTraits<StringRef>::output(Value, Ctx, OS);
}
StringRef ScalarTraits<FlowStringRef>::input(StringRef Value, void *Ctx,
                                             FlowStringRef &Out) {
  return ScalarTraits<StringRef>::input(Value, Ctx, Out.value);
}
QuotingType ScalarTraits<FlowStringRef>::mustQuote(StringRef Name) {
  return ScalarTraits<StringRef>::mustQuote(Name);
}

void ScalarEnumerationTraits<ObjCConstraintType>::enumeration(
    IO &IO, ObjCConstraintType &Constraint) {
  IO.enumCase(Constraint, "none", ObjCConstraintType::None);
  IO.enumCase(Constraint, "retain_release", ObjCConstraintType::Retain_Release);
  IO.enumCase(Constraint, "retain_release_for_simulator",
              ObjCConstraintType::Retain_Release_For_Simulator);
  IO.enumCase(Constraint, "retain_release_or_gc",
              ObjCConstraintType::Retain_Release_Or_GC);
  IO.enumCase(Constraint, "gc", ObjCConstraintType::GC);
}

void ScalarTraits<PlatformSet>::output(const PlatformSet &Values, void *IO,
                                       raw_ostream &OS) {

  const auto *Ctx = reinterpret_cast<TextAPIContext *>(IO);
  assert((!Ctx || Ctx && Ctx->FileKind != FileType::Invalid) &&
         "File type is not set in context");

  if ( Ctx && Ctx->FileKind == TBD_V3 && Values.count(PlatformKind::macOS) &&
      Values.count(PlatformKind::macCatalyst) ) {
    OS << "zippered";
    return;
  }

  assert(Values.size() == 1U);
  switch (*Values.begin()) {
  default:
    llvm_unreachable("unexpected platform");
    break;
  case PlatformKind::macOS:
    OS << "macosx";
    break;
  case PlatformKind::iOS:
    OS << "ios";
    break;
  case PlatformKind::watchOS:
    OS << "watchos";
    break;
  case PlatformKind::tvOS:
    OS << "tvos";
    break;
  case PlatformKind::bridgeOS:
    OS << "bridgeos";
    break;
  }
}

StringRef ScalarTraits<PlatformSet>::input(StringRef Scalar, void *IO,
                                           PlatformSet &Values) {
  const auto *Ctx = reinterpret_cast<TextAPIContext *>(IO);
  assert((!Ctx || Ctx && Ctx->FileKind != FileType::Invalid) &&
         "File type is not set in context");

  if (Scalar == "zippered") {
    if (Ctx && Ctx->FileKind == FileType::TBD_V3) {
      Values.insert(PlatformKind::macOS);
      Values.insert(PlatformKind::macCatalyst);
      return {};
    }
    return "invalid platform";
  }

  auto Platform = StringSwitch<PlatformKind>(Scalar)
                      .Case("unknown", PlatformKind::unknown)
                      .Case("macosx", PlatformKind::macOS)
                      .Case("ios", PlatformKind::iOS)
                      .Case("watchos", PlatformKind::watchOS)
                      .Case("tvos", PlatformKind::tvOS)
                      .Case("bridgeos", PlatformKind::bridgeOS)
                      .Case("iosmac", PlatformKind::macCatalyst)
                      .Default(PlatformKind::unknown);

  if (Platform == PlatformKind::macCatalyst)
    if (Ctx && Ctx->FileKind != FileType::TBD_V3)
      return "invalid platform";

  if (Platform == PlatformKind::unknown)
    return "unknown platform";

  Values.insert(Platform);
  return {};
}

QuotingType ScalarTraits<PlatformSet>::mustQuote(StringRef) {
  return QuotingType::None;
}

void ScalarBitSetTraits<ArchitectureSet>::bitset(IO &IO,
                                                 ArchitectureSet &Archs) {
#define ARCHINFO(arch, type, subtype)                                          \
  IO.bitSetCase(Archs, #arch, 1U << static_cast<int>(AK_##arch));
#include "llvm/TextAPI/MachO/Architecture.def"
#undef ARCHINFO
}

void ScalarTraits<Architecture>::output(const Architecture &Value, void *,
                                        raw_ostream &OS) {
  OS << Value;
}
StringRef ScalarTraits<Architecture>::input(StringRef Scalar, void *,
                                            Architecture &Value) {
  Value = getArchitectureFromName(Scalar);
  return {};
}
QuotingType ScalarTraits<Architecture>::mustQuote(StringRef) {
  return QuotingType::None;
}

void ScalarTraits<PackedVersion>::output(const PackedVersion &Value, void *,
                                         raw_ostream &OS) {
  OS << Value;
}
StringRef ScalarTraits<PackedVersion>::input(StringRef Scalar, void *,
                                             PackedVersion &Value) {
  if (!Value.parse32(Scalar))
    return "invalid packed version string.";
  return {};
}
QuotingType ScalarTraits<PackedVersion>::mustQuote(StringRef) {
  return QuotingType::None;
}

void ScalarTraits<SwiftVersion>::output(const SwiftVersion &Value, void *,
                                        raw_ostream &OS) {
  switch (Value) {
  case 1:
    OS << "1.0";
    break;
  case 2:
    OS << "1.1";
    break;
  case 3:
    OS << "2.0";
    break;
  case 4:
    OS << "3.0";
    break;
  default:
    OS << (unsigned)Value;
    break;
  }
}
StringRef ScalarTraits<SwiftVersion>::input(StringRef Scalar, void *,
                                            SwiftVersion &Value) {
  Value = StringSwitch<SwiftVersion>(Scalar)
              .Case("1.0", 1)
              .Case("1.1", 2)
              .Case("2.0", 3)
              .Case("3.0", 4)
              .Default(0);
  if (Value != SwiftVersion(0))
    return {};

  if (Scalar.getAsInteger(10, Value))
    return "invalid Swift ABI version.";

  return StringRef();
}
QuotingType ScalarTraits<SwiftVersion>::mustQuote(StringRef) {
  return QuotingType::None;
}

void ScalarTraits<UUID>::output(const UUID &Value, void *, raw_ostream &OS) {
  OS << Value.first << ": " << Value.second;
}
StringRef ScalarTraits<UUID>::input(StringRef Scalar, void *, UUID &Value) {
  auto Split = Scalar.split(':');
  auto Arch = Split.first.trim();
  auto UUID = Split.second.trim();
  if (UUID.empty())
    return "invalid uuid string pair";
  Value.second = UUID;
  Value.first = Target{getArchitectureFromName(Arch), PlatformKind::unknown};
  return {};
}

QuotingType ScalarTraits<UUID>::mustQuote(StringRef) {
  return QuotingType::Single;
}

} // end namespace yaml.
} // end namespace llvm.
<commit_msg>[TextAPI] Remove redundant checking causing warnings. NFC.<commit_after>//===- TextStubCommon.cpp -------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Implememts common Text Stub YAML mappings.
//
//===----------------------------------------------------------------------===//

#include "TextStubCommon.h"
#include "TextAPIContext.h"

using namespace llvm::MachO;

namespace llvm {
namespace yaml {

void ScalarTraits<FlowStringRef>::output(const FlowStringRef &Value, void *Ctx,
                                         raw_ostream &OS) {
  ScalarTraits<StringRef>::output(Value, Ctx, OS);
}
StringRef ScalarTraits<FlowStringRef>::input(StringRef Value, void *Ctx,
                                             FlowStringRef &Out) {
  return ScalarTraits<StringRef>::input(Value, Ctx, Out.value);
}
QuotingType ScalarTraits<FlowStringRef>::mustQuote(StringRef Name) {
  return ScalarTraits<StringRef>::mustQuote(Name);
}

void ScalarEnumerationTraits<ObjCConstraintType>::enumeration(
    IO &IO, ObjCConstraintType &Constraint) {
  IO.enumCase(Constraint, "none", ObjCConstraintType::None);
  IO.enumCase(Constraint, "retain_release", ObjCConstraintType::Retain_Release);
  IO.enumCase(Constraint, "retain_release_for_simulator",
              ObjCConstraintType::Retain_Release_For_Simulator);
  IO.enumCase(Constraint, "retain_release_or_gc",
              ObjCConstraintType::Retain_Release_Or_GC);
  IO.enumCase(Constraint, "gc", ObjCConstraintType::GC);
}

void ScalarTraits<PlatformSet>::output(const PlatformSet &Values, void *IO,
                                       raw_ostream &OS) {

  const auto *Ctx = reinterpret_cast<TextAPIContext *>(IO);
  assert((!Ctx || Ctx->FileKind != FileType::Invalid) &&
         "File type is not set in context");

  if (Ctx && Ctx->FileKind == TBD_V3 && Values.count(PlatformKind::macOS) &&
      Values.count(PlatformKind::macCatalyst)) {
    OS << "zippered";
    return;
  }

  assert(Values.size() == 1U);
  switch (*Values.begin()) {
  default:
    llvm_unreachable("unexpected platform");
    break;
  case PlatformKind::macOS:
    OS << "macosx";
    break;
  case PlatformKind::iOS:
    OS << "ios";
    break;
  case PlatformKind::watchOS:
    OS << "watchos";
    break;
  case PlatformKind::tvOS:
    OS << "tvos";
    break;
  case PlatformKind::bridgeOS:
    OS << "bridgeos";
    break;
  }
}

StringRef ScalarTraits<PlatformSet>::input(StringRef Scalar, void *IO,
                                           PlatformSet &Values) {
  const auto *Ctx = reinterpret_cast<TextAPIContext *>(IO);
  assert((!Ctx || Ctx->FileKind != FileType::Invalid) &&
         "File type is not set in context");

  if (Scalar == "zippered") {
    if (Ctx && Ctx->FileKind == FileType::TBD_V3) {
      Values.insert(PlatformKind::macOS);
      Values.insert(PlatformKind::macCatalyst);
      return {};
    }
    return "invalid platform";
  }

  auto Platform = StringSwitch<PlatformKind>(Scalar)
                      .Case("unknown", PlatformKind::unknown)
                      .Case("macosx", PlatformKind::macOS)
                      .Case("ios", PlatformKind::iOS)
                      .Case("watchos", PlatformKind::watchOS)
                      .Case("tvos", PlatformKind::tvOS)
                      .Case("bridgeos", PlatformKind::bridgeOS)
                      .Case("iosmac", PlatformKind::macCatalyst)
                      .Default(PlatformKind::unknown);

  if (Platform == PlatformKind::macCatalyst)
    if (Ctx && Ctx->FileKind != FileType::TBD_V3)
      return "invalid platform";

  if (Platform == PlatformKind::unknown)
    return "unknown platform";

  Values.insert(Platform);
  return {};
}

QuotingType ScalarTraits<PlatformSet>::mustQuote(StringRef) {
  return QuotingType::None;
}

void ScalarBitSetTraits<ArchitectureSet>::bitset(IO &IO,
                                                 ArchitectureSet &Archs) {
#define ARCHINFO(arch, type, subtype)                                          \
  IO.bitSetCase(Archs, #arch, 1U << static_cast<int>(AK_##arch));
#include "llvm/TextAPI/MachO/Architecture.def"
#undef ARCHINFO
}

void ScalarTraits<Architecture>::output(const Architecture &Value, void *,
                                        raw_ostream &OS) {
  OS << Value;
}
StringRef ScalarTraits<Architecture>::input(StringRef Scalar, void *,
                                            Architecture &Value) {
  Value = getArchitectureFromName(Scalar);
  return {};
}
QuotingType ScalarTraits<Architecture>::mustQuote(StringRef) {
  return QuotingType::None;
}

void ScalarTraits<PackedVersion>::output(const PackedVersion &Value, void *,
                                         raw_ostream &OS) {
  OS << Value;
}
StringRef ScalarTraits<PackedVersion>::input(StringRef Scalar, void *,
                                             PackedVersion &Value) {
  if (!Value.parse32(Scalar))
    return "invalid packed version string.";
  return {};
}
QuotingType ScalarTraits<PackedVersion>::mustQuote(StringRef) {
  return QuotingType::None;
}

void ScalarTraits<SwiftVersion>::output(const SwiftVersion &Value, void *,
                                        raw_ostream &OS) {
  switch (Value) {
  case 1:
    OS << "1.0";
    break;
  case 2:
    OS << "1.1";
    break;
  case 3:
    OS << "2.0";
    break;
  case 4:
    OS << "3.0";
    break;
  default:
    OS << (unsigned)Value;
    break;
  }
}
StringRef ScalarTraits<SwiftVersion>::input(StringRef Scalar, void *,
                                            SwiftVersion &Value) {
  Value = StringSwitch<SwiftVersion>(Scalar)
              .Case("1.0", 1)
              .Case("1.1", 2)
              .Case("2.0", 3)
              .Case("3.0", 4)
              .Default(0);
  if (Value != SwiftVersion(0))
    return {};

  if (Scalar.getAsInteger(10, Value))
    return "invalid Swift ABI version.";

  return StringRef();
}
QuotingType ScalarTraits<SwiftVersion>::mustQuote(StringRef) {
  return QuotingType::None;
}

void ScalarTraits<UUID>::output(const UUID &Value, void *, raw_ostream &OS) {
  OS << Value.first << ": " << Value.second;
}
StringRef ScalarTraits<UUID>::input(StringRef Scalar, void *, UUID &Value) {
  auto Split = Scalar.split(':');
  auto Arch = Split.first.trim();
  auto UUID = Split.second.trim();
  if (UUID.empty())
    return "invalid uuid string pair";
  Value.second = UUID;
  Value.first = Target{getArchitectureFromName(Arch), PlatformKind::unknown};
  return {};
}

QuotingType ScalarTraits<UUID>::mustQuote(StringRef) {
  return QuotingType::Single;
}

} // end namespace yaml.
} // end namespace llvm.
<|endoftext|>


<commit_before>#include <ncurses.h>
#include <iostream>
#include <unistd.h>
#include <algorithm>

#include "display/Screen.h"
#include "display/Window.h"
#include "display/WindowManager.h"
#include "map/Level.h"
#include "map/filters/DrunkardsWalkFilter.h"
#include "actor/Actor.h"
#include "core/Rand.h"

void pause_curses(Screen& screen)
{
	screen.pause();

	std::cout << "Paused ncurses..." << std::endl;

	sleep(4);

	std::cout << "Resuming..." << std::endl;

	sleep(1);
}

bool move_pc(Actor& pc, Level& level, int& pc_x, int& pc_y, int dx, int dy)
{
	int new_x = pc_x + dx;
	int new_y = pc_y + dy;

	//Make sure it's in bounds
	if(0 <= new_x && new_x < level.getWidth() && 0 <= new_y && new_y < level.getHeight())
	{
		//Make sure it's passable terrain
		if(level[new_x][new_y].getPassable())
		{
			//Remove the PC from its old position
			level[pc_x][pc_y].removeActor();

			//Adjust PC's x,y coordinates
			pc_x += dx;
			pc_y += dy;

			//Place the PC at the new x,y coordinates
			level[pc_x][pc_y].addActor(&pc);

			return true;
		}
	}
	return false;
}

void spawn_npc(Actor& npc, Level& level, int& npc_x, int& npc_y, int pc_x, int pc_y, int max_dist = 35)
{
	Rand rand(time(NULL));

	int min_x = std::max(0, pc_x - max_dist);
	int max_x = std::min(level.getWidth()-1, pc_x + max_dist);

	int min_y = std::max(0, pc_y - max_dist);
	int max_y = std::min(level.getHeight()-1, pc_y + max_dist);

	do {
		npc_x = rand.randInt(min_x, max_x);
		npc_y = rand.randInt(min_y, max_y);
	} while(level[npc_x][npc_y] != FloorTile);
	level[npc_x][npc_y].addActor(&npc);
}

int main()
{
	Screen screen;

	int screen_y = screen.getHeight();
	int screen_x = screen.getWidth();

	//Make a map double the screen size
	int map_y = screen_y * 2;
	int map_x = screen_x * 2;
	//Generate a map
	Level cave(map_x, map_y);
	DrunkardsWalkFilter walk;
	walk.setSeed(time(NULL));
	walk.apply(cave);
	//Find a random FloorTile to put our PC on
	int pc_x, pc_y;
	Actor pc('@', "PC", 0x01);
	Rand rand(time(NULL));
	do {
		pc_x = rand.randInt(0, cave.getWidth()-1);
		pc_y = rand.randInt(0, cave.getHeight()-1);
	} while(cave[pc_x][pc_y] != FloorTile);
	cave[pc_x][pc_y].addActor(&pc);
	//Now put the map into our map window...
	Window level_window(&cave);
	//...and create a viewport looking into it.
	Window map(&level_window, screen_x-20, screen_y-3, 20, 3);

	Window top(screen_x, 3, 0, 0);
	Window left(20, screen_y-2, 0, 2);

	top.addBorder();
	left.addBorder();
	//map.addBorder(); //Dare I try it?
	//Push our windows into our WindowManager
	WindowManager wm;
	wm.addWindow(&top);
	wm.addWindow(&left);
	wm.addWindow(&map);

	wm.getWindow(0)->add(1, 0, "Message Panel");
	wm.getWindow(1)->add(1, 0, "Stat Panel");

	//Center the map viewport on the PC
	map.center(pc_x, pc_y);

	//Let's display some map display stats
	//Display our view's X and Y coordinates
	wm.getWindow(1)->add(1, 2, "View Position:");
	wm.getWindow(1)->add(1, 3, "X:     ");
	wm.getWindow(1)->addInt(4, 3, map.getViewX());
	wm.getWindow(1)->add(1, 4, "Y:     ");
	wm.getWindow(1)->addInt(4, 4, map.getViewY());

	//Display map size
	wm.getWindow(1)->add(1, 6, "Map Size:");
	wm.getWindow(1)->add(1, 7, "W:");
	wm.getWindow(1)->addInt(4, 7, cave.getWidth());
	wm.getWindow(1)->add(1, 8, "H:");
	wm.getWindow(1)->addInt(4, 8, cave.getHeight());

	//Display viewport size
	wm.getWindow(1)->add(1, 9, "View Size:");
	wm.getWindow(1)->add(1, 10, "W:");
	wm.getWindow(1)->addInt(4, 10, map.getViewWidth());
	wm.getWindow(1)->add(1, 11, "H:");
	wm.getWindow(1)->addInt(4, 11, map.getViewHeight());

	//Display PC's location
	wm.getWindow(1)->add(1, 12, "PC Position:");
	wm.getWindow(1)->add(1, 13, "X:     ");
	wm.getWindow(1)->addInt(4, 13, pc_x);
	wm.getWindow(1)->add(1, 14, "Y:     ");
	wm.getWindow(1)->addInt(4, 14, pc_y);

	//Find a random FloorTile to put our kobold on
	int npc_x, npc_y;
	Actor npc('k', "kobold", 0x00);
	spawn_npc(npc, cave, npc_x, npc_y, pc_x, pc_y, 50);

	//Now display everything
	wm.refresh();

	//Now we enter the "game loop"
	int ch;
	int key_pos = 8;
	int last_key_pos;
	int dx, dy;
	bool run = true;
	while(run)
	{
		ch = getch();

		//Display the key code
		wm.getWindow(0)->add(key_pos, 1, "                                    ");
		wm.getWindow(0)->addInt(key_pos, 1, ch);

		dx = 0;
		dy = 0;

		wm.getWindow(0)->add(1, 1, "     ");
		last_key_pos = key_pos;
		key_pos = 8;
		switch(ch)
		{
			//Viewport movement
			case KEY_UP:
				wm.getWindow(0)->add(1, 1, "Up");
				dy = -1;
				break;
			case KEY_DOWN:
				wm.getWindow(0)->add(1, 1, "Down");
				dy = 1;
				break;
			case KEY_LEFT:
				wm.getWindow(0)->add(1, 1, "Left");
				dx = -1;
				break;
			case KEY_RIGHT:
				wm.getWindow(0)->add(1, 1, "Right");
				dx = 1;
				break;
			//Orthogonal movement
			case '8':
			case 'k':
				move_pc(pc, cave, pc_x, pc_y, 0, -1);
				break;
			case '2':
			case 'j':
				move_pc(pc, cave, pc_x, pc_y, 0, 1);
				break;
			case '4':
			case 'h':
				move_pc(pc, cave, pc_x, pc_y, -1, 0);
				break;
			case '6':
			case 'l':
				move_pc(pc, cave, pc_x, pc_y, 1, 0);
				break;
			//Diagonal movement
			case '7':
			case 'y':
				move_pc(pc, cave, pc_x, pc_y, -1, -1);
				break;
			case '9':
			case 'u':
				move_pc(pc, cave, pc_x, pc_y, 1, -1);
				break;
			case '1':
			case 'b':
				move_pc(pc, cave, pc_x, pc_y, -1, 1);
				break;
			case '3':
			case 'n':
				move_pc(pc, cave, pc_x, pc_y, 1, 1);
				break;
			//Other commands
			case 'c':
			case 'C':
				//Center the view on the PC
				wm.getWindow(2)->center(pc_x, pc_y);
				break;
			case 'p':
			case 'P':
				//Pause ncurses (just a useless demo of the ability)
				pause_curses(screen);
				break;
			case 'q':
			case 'Q':
				//Quit
				run = false;
				break;
			default:
				key_pos = last_key_pos + 4;
				if(key_pos > wm.getWindow(0)->getWidth())
				{
					key_pos = 8;
				}
				break;
		}

		//If the PC "killed" the kobold, spawn another
		if(npc_x == pc_x && npc_y == pc_y)
		{
			spawn_npc(npc, cave, npc_x, npc_y, pc_x, pc_y);
		}

		//Move the viewport
		map.moveBy(dx, dy);

		//Display our view's X and Y coordinates
		wm.getWindow(1)->add(1, 3, "X:     ");
		wm.getWindow(1)->addInt(4, 3, map.getViewX());
		wm.getWindow(1)->add(1, 4, "Y:     ");
		wm.getWindow(1)->addInt(4, 4, map.getViewY());

		//Re-display PC's position
		wm.getWindow(1)->add(1, 13, "X:     ");
		wm.getWindow(1)->addInt(4, 13, pc_x);
		wm.getWindow(1)->add(1, 14, "Y:     ");
		wm.getWindow(1)->addInt(4, 14, pc_y);

		//Display NPC's position
		wm.getWindow(1)->add(1, 15, "NPC Position:");
		wm.getWindow(1)->add(1, 16, "X:     ");
		wm.getWindow(1)->addInt(4, 16, npc_x);
		wm.getWindow(1)->add(1, 17, "Y:     ");
		wm.getWindow(1)->addInt(4, 17, npc_y);

		//Refresh the display
		wm.refresh();
	}
}
<commit_msg>InterfaceTest updated to use isPassable.<commit_after>#include <ncurses.h>
#include <iostream>
#include <unistd.h>
#include <algorithm>

#include "display/Screen.h"
#include "display/Window.h"
#include "display/WindowManager.h"
#include "map/Level.h"
#include "map/filters/DrunkardsWalkFilter.h"
#include "actor/Actor.h"
#include "core/Rand.h"

void pause_curses(Screen& screen)
{
	screen.pause();

	std::cout << "Paused ncurses..." << std::endl;

	sleep(4);

	std::cout << "Resuming..." << std::endl;

	sleep(1);
}

bool move_pc(Actor& pc, Level& level, int& pc_x, int& pc_y, int dx, int dy)
{
	int new_x = pc_x + dx;
	int new_y = pc_y + dy;

	//Make sure it's in bounds
	if(0 <= new_x && new_x < level.getWidth() && 0 <= new_y && new_y < level.getHeight())
	{
		//Make sure it's passable terrain
		if(level[new_x][new_y].isPassable())
		{
			//Remove the PC from its old position
			level[pc_x][pc_y].removeActor();

			//Adjust PC's x,y coordinates
			pc_x += dx;
			pc_y += dy;

			//Place the PC at the new x,y coordinates
			level[pc_x][pc_y].addActor(&pc);

			return true;
		}
	}
	return false;
}

void spawn_npc(Actor& npc, Level& level, int& npc_x, int& npc_y, int pc_x, int pc_y, int max_dist = 35)
{
	Rand rand(time(NULL));

	int min_x = std::max(0, pc_x - max_dist);
	int max_x = std::min(level.getWidth()-1, pc_x + max_dist);

	int min_y = std::max(0, pc_y - max_dist);
	int max_y = std::min(level.getHeight()-1, pc_y + max_dist);

	do {
		npc_x = rand.randInt(min_x, max_x);
		npc_y = rand.randInt(min_y, max_y);
	} while(level[npc_x][npc_y] != FloorTile);
	level[npc_x][npc_y].addActor(&npc);
}

int main()
{
	Screen screen;

	int screen_y = screen.getHeight();
	int screen_x = screen.getWidth();

	//Make a map double the screen size
	int map_y = screen_y * 2;
	int map_x = screen_x * 2;
	//Generate a map
	Level cave(map_x, map_y);
	DrunkardsWalkFilter walk;
	walk.setSeed(time(NULL));
	walk.apply(cave);
	//Find a random FloorTile to put our PC on
	int pc_x, pc_y;
	Actor pc('@', "PC", 0x01);
	Rand rand(time(NULL));
	do {
		pc_x = rand.randInt(0, cave.getWidth()-1);
		pc_y = rand.randInt(0, cave.getHeight()-1);
	} while(cave[pc_x][pc_y] != FloorTile);
	cave[pc_x][pc_y].addActor(&pc);
	//Now put the map into our map window...
	Window level_window(&cave);
	//...and create a viewport looking into it.
	Window map(&level_window, screen_x-20, screen_y-3, 20, 3);

	Window top(screen_x, 3, 0, 0);
	Window left(20, screen_y-2, 0, 2);

	top.addBorder();
	left.addBorder();
	//map.addBorder(); //Dare I try it?
	//Push our windows into our WindowManager
	WindowManager wm;
	wm.addWindow(&top);
	wm.addWindow(&left);
	wm.addWindow(&map);

	wm.getWindow(0)->add(1, 0, "Message Panel");
	wm.getWindow(1)->add(1, 0, "Stat Panel");

	//Center the map viewport on the PC
	map.center(pc_x, pc_y);

	//Let's display some map display stats
	//Display our view's X and Y coordinates
	wm.getWindow(1)->add(1, 2, "View Position:");
	wm.getWindow(1)->add(1, 3, "X:     ");
	wm.getWindow(1)->addInt(4, 3, map.getViewX());
	wm.getWindow(1)->add(1, 4, "Y:     ");
	wm.getWindow(1)->addInt(4, 4, map.getViewY());

	//Display map size
	wm.getWindow(1)->add(1, 6, "Map Size:");
	wm.getWindow(1)->add(1, 7, "W:");
	wm.getWindow(1)->addInt(4, 7, cave.getWidth());
	wm.getWindow(1)->add(1, 8, "H:");
	wm.getWindow(1)->addInt(4, 8, cave.getHeight());

	//Display viewport size
	wm.getWindow(1)->add(1, 9, "View Size:");
	wm.getWindow(1)->add(1, 10, "W:");
	wm.getWindow(1)->addInt(4, 10, map.getViewWidth());
	wm.getWindow(1)->add(1, 11, "H:");
	wm.getWindow(1)->addInt(4, 11, map.getViewHeight());

	//Display PC's location
	wm.getWindow(1)->add(1, 12, "PC Position:");
	wm.getWindow(1)->add(1, 13, "X:     ");
	wm.getWindow(1)->addInt(4, 13, pc_x);
	wm.getWindow(1)->add(1, 14, "Y:     ");
	wm.getWindow(1)->addInt(4, 14, pc_y);

	//Find a random FloorTile to put our kobold on
	int npc_x, npc_y;
	Actor npc('k', "kobold", 0x00);
	spawn_npc(npc, cave, npc_x, npc_y, pc_x, pc_y, 50);

	//Now display everything
	wm.refresh();

	//Now we enter the "game loop"
	int ch;
	int key_pos = 8;
	int last_key_pos;
	int dx, dy;
	bool run = true;
	while(run)
	{
		ch = getch();

		//Display the key code
		wm.getWindow(0)->add(key_pos, 1, "                                    ");
		wm.getWindow(0)->addInt(key_pos, 1, ch);

		dx = 0;
		dy = 0;

		wm.getWindow(0)->add(1, 1, "     ");
		last_key_pos = key_pos;
		key_pos = 8;
		switch(ch)
		{
			//Viewport movement
			case KEY_UP:
				wm.getWindow(0)->add(1, 1, "Up");
				dy = -1;
				break;
			case KEY_DOWN:
				wm.getWindow(0)->add(1, 1, "Down");
				dy = 1;
				break;
			case KEY_LEFT:
				wm.getWindow(0)->add(1, 1, "Left");
				dx = -1;
				break;
			case KEY_RIGHT:
				wm.getWindow(0)->add(1, 1, "Right");
				dx = 1;
				break;
			//Orthogonal movement
			case '8':
			case 'k':
				move_pc(pc, cave, pc_x, pc_y, 0, -1);
				break;
			case '2':
			case 'j':
				move_pc(pc, cave, pc_x, pc_y, 0, 1);
				break;
			case '4':
			case 'h':
				move_pc(pc, cave, pc_x, pc_y, -1, 0);
				break;
			case '6':
			case 'l':
				move_pc(pc, cave, pc_x, pc_y, 1, 0);
				break;
			//Diagonal movement
			case '7':
			case 'y':
				move_pc(pc, cave, pc_x, pc_y, -1, -1);
				break;
			case '9':
			case 'u':
				move_pc(pc, cave, pc_x, pc_y, 1, -1);
				break;
			case '1':
			case 'b':
				move_pc(pc, cave, pc_x, pc_y, -1, 1);
				break;
			case '3':
			case 'n':
				move_pc(pc, cave, pc_x, pc_y, 1, 1);
				break;
			//Other commands
			case 'c':
			case 'C':
				//Center the view on the PC
				wm.getWindow(2)->center(pc_x, pc_y);
				break;
			case 'p':
			case 'P':
				//Pause ncurses (just a useless demo of the ability)
				pause_curses(screen);
				break;
			case 'q':
			case 'Q':
				//Quit
				run = false;
				break;
			default:
				key_pos = last_key_pos + 4;
				if(key_pos > wm.getWindow(0)->getWidth())
				{
					key_pos = 8;
				}
				break;
		}

		//If the PC "killed" the kobold, spawn another
		if(npc_x == pc_x && npc_y == pc_y)
		{
			spawn_npc(npc, cave, npc_x, npc_y, pc_x, pc_y);
		}

		//Move the viewport
		map.moveBy(dx, dy);

		//Display our view's X and Y coordinates
		wm.getWindow(1)->add(1, 3, "X:     ");
		wm.getWindow(1)->addInt(4, 3, map.getViewX());
		wm.getWindow(1)->add(1, 4, "Y:     ");
		wm.getWindow(1)->addInt(4, 4, map.getViewY());

		//Re-display PC's position
		wm.getWindow(1)->add(1, 13, "X:     ");
		wm.getWindow(1)->addInt(4, 13, pc_x);
		wm.getWindow(1)->add(1, 14, "Y:     ");
		wm.getWindow(1)->addInt(4, 14, pc_y);

		//Display NPC's position
		wm.getWindow(1)->add(1, 15, "NPC Position:");
		wm.getWindow(1)->add(1, 16, "X:     ");
		wm.getWindow(1)->addInt(4, 16, npc_x);
		wm.getWindow(1)->add(1, 17, "Y:     ");
		wm.getWindow(1)->addInt(4, 17, npc_y);

		//Refresh the display
		wm.refresh();
	}
}
<|endoftext|>