repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
prophecy/Pillar
Dependencies/Include/cml/matrix/determinant.h
/* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief Compute the determinant of a square matrix using LU factorization. * * @todo This should be specialized on the matrix size for small matrices. */ #ifndef determinant_h #define determinant_h #include <cml/matrix/lu.h> namespace cml { namespace detail { /* Need to use a functional, since template functions cannot be * specialized. N is used to differentiate dimension only, so this can be * used for any matrix size type: */ template<typename MatT, int N> struct determinant_f; /* 2x2 determinant. Despite being marked for fixed_size matrices, this can * be used for dynamic-sized ones also: */ template<typename MatT> struct determinant_f<MatT,2> { typename MatT::value_type operator()(const MatT& M) const { return M(0,0)*M(1,1) - M(1,0)*M(0,1); } }; /* 3x3 determinant. Despite being marked for fixed_size matrices, this can * be used for dynamic-sized ones also: */ template<typename MatT> struct determinant_f<MatT,3> { /* [00 01 02] * M = [10 11 12] * [20 21 22] */ typename MatT::value_type operator()(const MatT& M) const { return M(0,0)*(M(1,1)*M(2,2) - M(1,2)*M(2,1)) + M(0,1)*(M(1,2)*M(2,0) - M(1,0)*M(2,2)) + M(0,2)*(M(1,0)*M(2,1) - M(1,1)*M(2,0)); } }; /* 4x4 determinant. Despite being marked for fixed_size matrices, this can * be used for dynamic-sized ones also: */ template<typename MatT> struct determinant_f<MatT,4> { /* [00 01 02 03] * M = [10 11 12 13] * [20 21 22 23] * [30 31 32 33] * * |11 12 13| |10 12 13| * C00 = |21 22 23| C01 = |20 22 23| * |31 32 33| |30 32 33| * * |10 11 13| |10 11 12| * C02 = |20 21 23| C03 = |20 21 22| * |30 31 33| |30 31 32| * * d00 = 11 * (22*33 - 23*32) d01 = 10 * (22*33 - 23*32) * + 12 * (23*31 - 21*33) + 12 * (23*30 - 20*33) * + 13 * (21*32 - 22*31) + 13 * (20*32 - 22*30) * * d02 = 10 * (21*33 - 23*31) d03 = 10 * (21*32 - 22*31) * + 11 * (23*30 - 20*33) + 11 * (22*30 - 20*32) * + 13 * (20*31 - 21*30) + 12 * (20*31 - 21*30) */ typename MatT::value_type operator()(const MatT& M) const { /* Shorthand. */ typedef typename MatT::value_type value_type; /* Common cofactors: */ value_type m_22_33_23_32 = M(2,2)*M(3,3) - M(2,3)*M(3,2); value_type m_23_30_20_33 = M(2,3)*M(3,0) - M(2,0)*M(3,3); value_type m_20_31_21_30 = M(2,0)*M(3,1) - M(2,1)*M(3,0); value_type m_21_32_22_31 = M(2,1)*M(3,2) - M(2,2)*M(3,1); value_type m_23_31_21_33 = M(2,3)*M(3,1) - M(2,1)*M(3,3); value_type m_20_32_22_30 = M(2,0)*M(3,2) - M(2,2)*M(3,0); value_type d00 = M(0,0)*( M(1,1) * m_22_33_23_32 + M(1,2) * m_23_31_21_33 + M(1,3) * m_21_32_22_31); value_type d01 = M(0,1)*( M(1,0) * m_22_33_23_32 + M(1,2) * m_23_30_20_33 + M(1,3) * m_20_32_22_30); value_type d02 = M(0,2)*( M(1,0) * - m_23_31_21_33 + M(1,1) * m_23_30_20_33 + M(1,3) * m_20_31_21_30); value_type d03 = M(0,3)*( M(1,0) * m_21_32_22_31 + M(1,1) * - m_20_32_22_30 + M(1,2) * m_20_31_21_30); return d00 - d01 + d02 - d03; } }; /* General NxN determinant by LU factorization: */ template<typename MatT, int N> struct determinant_f { typename MatT::value_type operator()(const MatT& M) const { /* Compute the LU factorization: */ typename MatT::temporary_type LU = lu(M); /* The product of the diagonal entries is the determinant: */ typename MatT::value_type det = LU(0,0); for(size_t i = 1; i < LU.rows(); ++ i) det *= LU(i,i); return det; } }; /* Generator for the determinant functional for fixed-size matrices: */ template<typename MatT> typename MatT::value_type determinant(const MatT& M, fixed_size_tag) { /* Require a square matrix: */ cml::et::CheckedSquare(M, fixed_size_tag()); return determinant_f<MatT,MatT::array_rows>()(M); } /* Generator for the determinant functional for dynamic-size matrices: */ template<typename MatT> typename MatT::value_type determinant(const MatT& M, dynamic_size_tag) { /* Require a square matrix: */ cml::et::CheckedSquare(M, dynamic_size_tag()); /* Dispatch based upon the matrix dimension: */ switch(M.rows()) { case 2: return determinant_f<MatT,2>()(M); case 3: return determinant_f<MatT,3>()(M); case 4: return determinant_f<MatT,4>()(M); default: return determinant_f<MatT,0>()(M); // > 4x4. } } } // namespace detail /** Determinant of a matrix. */ template<typename E, class AT, class BO, class L> inline E determinant(const matrix<E,AT,BO,L>& M) { typedef typename matrix<E,AT,BO,L>::size_tag size_tag; return detail::determinant(M,size_tag()); } /** Determinant of a matrix expression. */ template<typename XprT> inline typename XprT::value_type determinant(const et::MatrixXpr<XprT>& e) { typedef typename et::MatrixXpr<XprT>::size_tag size_tag; return detail::determinant(e,size_tag()); } } // namespace cml #endif // ------------------------------------------------------------------------- // vim:ft=cpp
prophecy/Pillar
Dependencies/Include/cml/core/fixed_1D.h
/* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief */ #ifndef fixed_1D_h #define fixed_1D_h #include <cml/core/common.h> #include <cml/core/cml_meta.h> #include <cml/core/cml_assert.h> #include <cml/fixed.h> namespace cml { /** Statically-allocated array. * * @note This class is designed to have the same size as a C array with the * same length. It's therefore possible (but not recommended!) to coerce * a normal C array into a fixed_1D<> like this: * * typedef fixed_1D<double,10> array; * double c_array[10]; * array& array_object = *((array*)&c_array); * double e1 = array_object[1]; * * It's also possible to do this with a pointer to an array of values (e.g. a * double*), whether or not it was actually declared as a fixed C array. This * is HIGHLY DISCOURAGED, though. It's relatively straightforward to implement * a separate class to take a C array (or pointer) and turn it into an array * object. * * @sa cml::fixed * * @internal Do <em>not</em> add the empty constructor and destructor; at * least one compiler (Intel C++ 9.0) fails to optimize them away, and they * aren't needed anyway here. */ template<typename Element, int Size> class fixed_1D { public: /* Require Size > 0: */ CML_STATIC_REQUIRE(Size > 0); /* Record the generator: */ typedef fixed<Size,-1> generator_type; /* Standard: */ typedef Element value_type; typedef Element* pointer; typedef Element& reference; typedef const Element& const_reference; typedef const Element* const_pointer; /* Array implementation: */ typedef value_type array_impl[Size]; /* For matching by memory type: */ typedef fixed_memory_tag memory_tag; /* For matching by size type: */ typedef fixed_size_tag size_tag; /* For matching by resizability: */ typedef not_resizable_tag resizing_tag; /* For matching by dimensions: */ typedef oned_tag dimension_tag; public: /** The length as an enumerated value. */ enum { array_size = Size }; public: /** Return the number of elements in the array. */ size_t size() const { return size_t(array_size); } /** Access to the data as a C array. * * @param i a size_t index into the array. * @return a mutable reference to the array value at i. * * @note This function does not range-check the argument. */ reference operator[](size_t i) { return m_data[i]; } /** Const access to the data as a C array. * * @param i a size_t index into the array. * @return a const reference to the array value at i. * * @note This function does not range-check the argument. */ const_reference operator[](size_t i) const { return m_data[i]; } /** Return access to the data as a raw pointer. */ pointer data() { return &m_data[0]; } /** Return access to the data as a raw pointer. */ const_pointer data() const { return &m_data[0]; } protected: fixed_1D() {} protected: array_impl m_data; }; } // namespace cml #endif // ------------------------------------------------------------------------- // vim:ft=cpp
prophecy/Pillar
Src/Foundation/Utility/Memory/Memory.h
/* * This source file is part of Wonderland, the C++ Cross-platform middleware for game * * For the latest information, see https://github.com/prophecy/Wonderland * * The MIT License (MIT) * Copyright (c) 2015 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #ifndef __MEMORY_H__ #define __MEMORY_H__ #define DEBUG_MEMORY #include "Utility/Types.h" #include "Utility/Singleton.h" #include "MemoryHandle.h" class Memory : public Singleton<Memory> { private: u32 _handleId; // This map is between code and handle std::map< u32, MemoryHandle<u32> > _codeHandleMap; // This is an additional map between pointer and handle std::map< u32*, MemoryHandle<u32> > _addressHandleMap; public: template <typename T> MemoryHandle<T>* Alloc() { // Naive alloc mode1 MemoryHandle<T>* handle = new MemoryHandle<T>(); // <<< keep this in organized place T* ptr = new T(); handle->code = _handleId; handle->ptr = ptr; // Increment ++_handleId; // Add to map // u32 is an address which is converted from T MemoryHandle<u32> hMap; hMap.code = handle->code; hMap.ptr = (u32*)handle->ptr; _codeHandleMap.insert(std::pair< u32, MemoryHandle<u32> >(hMap.code, hMap)); // Create additional map for searching _addressHandleMap.insert(std::pair< u32*, MemoryHandle<u32> >(hMap.ptr, hMap)); // Return handle return handle; } template <typename T> void Free(MemoryHandle<T>* handle) { // Erase address handle _addressHandleMap.erase((u32*)handle->ptr); // Naive alloc mode delete handle->ptr; handle->ptr = NULL; // Erase from map _codeHandleMap.erase(handle->code); } void FreeAll() { std::map< u32, MemoryHandle<u32> >::iterator it = _codeHandleMap.begin(); while (it != _codeHandleMap.end()) { MemoryHandle<u32> handle = (*it).second; // Naive alloc mode delete handle.ptr; handle.ptr = NULL; // Erase from map _codeHandleMap.erase(it++); } // Clear all address handle _addressHandleMap.clear(); } u64 GetMemoryCounter() { return _codeHandleMap.size(); } template <typename T> MemoryHandle<T>* GetHandle(u64 address) { return (MemoryHandle<T>*)&_addressHandleMap[(u32*)address]; } }; #endif // __MEMORY_H__
prophecy/Pillar
Dependencies/Include/cml/core/cml_assert.h
/* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief * * Macros and template metaprogramming to implement compile- and run-time * assertions. */ #ifndef cml_assert_h #define cml_assert_h #include <cml/core/cml_meta.h> namespace cml { /* Join preprocessor macros into a new preprocessor macro: */ #define CML_JOIN(X,Y) CML_DO_JOIN(X,Y) #define CML_DO_JOIN(X,Y) CML_DO_JOIN2(X,Y) #define CML_DO_JOIN2(X,Y) X##Y /* Change a macro value into a string: */ #define TO_STRING(X) TO_STRING2(X) #define TO_STRING2(X) #X /** Default undefined compile-time assertion struct. */ template<bool T> struct STATIC_ASSERTION_FAILURE; /** Struct instantiated when a true assertion is made at compile-time. */ template<> struct STATIC_ASSERTION_FAILURE<true> { typedef true_type result; enum { value = true }; }; /** Create a compile-time assertion. * * @note Compile-time assertions must be expressions that can be evaluated at * comile time. This means that the expression must only rely on constants, * enums, and/or template parameters, not variables having run-time storage * requirements. * * @warning Enclose expressions that have commas with parens, otherwise the * preprocessor will parse the commas as macro argument separators! * * @sa STATIC_ASSERTION_FAILURE */ #define CML_STATIC_REQUIRE(_E_) \ typedef typename STATIC_ASSERTION_FAILURE<(_E_)>::result \ CML_JOIN(__cml_assert_test_typedef_, __LINE__) /** A more meaningful compile-time assertion struct. * * The parameter M is a struct type which has been declared but not * defined; e.g. struct this_is_an_error. * * When used with CML_STATIC_REQUIRE_M(<expr>,M), the compiler errors will * contain the struct name at the point of the error. */ template<bool T, typename M> struct STATIC_ASSERTION_FAILURE_M { typename M::bogus result; }; /** Instantiated for true assertions. */ template<typename M> struct STATIC_ASSERTION_FAILURE_M<true,M> { typedef true_type result; enum { value = true }; }; /** Create a compile-time assertion with a message. * * @note Compile-time assertions must be expressions that can be evaluated at * comile time. This means that the expression must only rely on constants, * enums, and/or template parameters, not variables having run-time storage * requirements. * * @warning Enclose expressions that have commas with parens, otherwise the * preprocessor will parse the commas as macro argument separators! * * @sa STATIC_ASSERTION_FAILURE_M */ #define CML_STATIC_REQUIRE_M(_E_, _M_) \ typedef typename STATIC_ASSERTION_FAILURE_M<(_E_),_M_> \ ::result CML_JOIN(__bogus_assert_type_, __LINE__) } // namespace cml #endif // ------------------------------------------------------------------------- // vim:ft=cpp
prophecy/Pillar
Build/iOSMac/WonderlandMacLib/WonderlandMacLib.h
// // WonderlandMacLib.h // WonderlandMacLib // // Created by <NAME> on 8/11/2559 BE. // Copyright © 2559 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> @interface WonderlandMacLib : NSObject @end
prophecy/Pillar
Dependencies/Include/cml/mathlib/epsilon.h
/* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief */ #ifndef epsilon_h #define epsilon_h namespace cml { /* @todo: epsilon and tolerance handling. * * @note This is a placeholder for a more sophisticated epsilon/tolerance * system. */ template < typename Real > struct epsilon { typedef Real value_type; private: /** For convenience */ typedef value_type T; public: static T placeholder() { /* Completely arbitrary placeholder value: */ return T(0.0001); } }; } // namespace cml #endif
prophecy/Pillar
Dependencies/Include/cml/core/cml_meta.h
/* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief A few simple metaprogramming tools. */ #ifndef cml_meta_h #define cml_meta_h /* Include all of the template metaprogramming tools: */ #include <cml/core/meta/common.h> #include <cml/core/meta/if.h> #include <cml/core/meta/switch.h> #endif // ------------------------------------------------------------------------- // vim:ft=cpp
prophecy/Pillar
Dependencies/Include/cml/mathlib/vector_misc.h
<filename>Dependencies/Include/cml/mathlib/vector_misc.h /* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief */ #ifndef vector_misc_h #define vector_misc_h #include <cml/mathlib/coord_conversion.h> /* Miscellaneous vector functions. */ namespace cml { /* Function to project a vector v onto a hyperplane specified by a unit-length * normal n. * * @todo: Clean up promotion code. */ template < class VecT_1, class VecT_2 > typename detail::CrossPromote<VecT_1,VecT_2>::promoted_vector project_to_hplane(const VecT_1& v, const VecT_2& n) { typedef typename detail::CrossPromote<VecT_1,VecT_2>::promoted_vector result_type; result_type result; et::detail::Resize(result, v.size()); result = v - dot(v,n) * n; return result; } /* Return a vector perpendicular (CCW) to a 2D vector. */ template < class VecT > vector< typename VecT::value_type, fixed<2> > perp(const VecT& v) { typedef vector< typename VecT::value_type, fixed<2> > temporary_type; /* Checking */ detail::CheckVec2(v); return temporary_type(-v[1],v[0]); } /* @todo: unit_cross() and cross_cardinal() should probably go in * vector_products.h, but I'm trying to avoid modifying the existing codebase * for now. */ /** Return normalized cross product of two vectors */ template< class LeftT, class RightT > typename detail::CrossPromote<LeftT,RightT>::promoted_vector unit_cross(const LeftT& left, const RightT& right) { /* @todo: This will probably break with dynamic<> vectors */ return normalize(cross(left,right)); } /** Return the cross product of v and the i'th cardinal basis vector */ template < class VecT > vector< typename VecT::value_type, fixed<3> > cross_cardinal(const VecT& v, size_t i) { typedef vector< typename VecT::value_type, fixed<3> > vector_type; typedef typename vector_type::value_type value_type; /* Checking */ detail::CheckVec3(v); detail::CheckIndex3(i); size_t j, k; cyclic_permutation(i, i, j, k); vector_type result; result[i] = value_type(0); result[j] = v[k]; result[k] = -v[j]; return result; } /** Return the cross product of the i'th cardinal basis vector and v */ template < class VecT > vector< typename VecT::value_type, fixed<3> > cross_cardinal(size_t i, const VecT& v) { typedef vector< typename VecT::value_type, fixed<3> > vector_type; typedef typename vector_type::value_type value_type; /* Checking */ detail::CheckVec3(v); detail::CheckIndex3(i); size_t j, k; cyclic_permutation(i, i, j, k); vector_type result; result[i] = value_type(0); result[j] = -v[k]; result[k] = v[j]; return result; } /** Rotate a 3D vector v about a unit-length vector n. */ template< class VecT_1, class VecT_2, typename Real > vector< typename et::ScalarPromote< typename VecT_1::value_type, typename VecT_2::value_type >::type, fixed<3> > rotate_vector(const VecT_1& v, const VecT_2& n, Real angle) { typedef vector< typename et::ScalarPromote< typename VecT_1::value_type, typename VecT_2::value_type >::type, fixed<3> > result_type; /* Checking */ detail::CheckVec3(v); detail::CheckVec3(n); result_type parallel = dot(v,n)*n; return ( std::cos(angle)*(v-parallel) + std::sin(angle)*cross(n,v) + parallel ); } /** Rotate a 2D vector v about a unit-length vector n. */ template< class VecT, typename Real > vector< typename VecT::value_type, fixed<2> > rotate_vector_2D(const VecT& v, Real angle) { typedef vector< typename VecT::value_type, fixed<2> > result_type; typedef typename result_type::value_type value_type; /* Checking */ detail::CheckVec2(v); value_type s = std::sin(angle); value_type c = std::cos(angle); return result_type(c * v[0] - s * v[1], s * v[0] + c * v[1]); } /** Random unit 3D or 2D vector * * @todo: This is just placeholder code for what will be a more thorough * 'random unit' implementation: * * - All dimensions will be handled uniformly if practical, perhaps through * a normal distrubution PRNG. * * - Failing that (or perhaps even in this case), dimensions 2 and 3 will be * dispatched to special-case code, most likely implementing the algorithms * below. * * - Like the utility random functions, the option of using one's own PRGN * will be made available. * * @todo: Once N-d random vectors are supported, add a 'random unit * quaternion' function that wraps a call to random_unit() with a 4D vector as * the argument. */ template < typename E, class A > void random_unit(vector<E,A>& v) { typedef vector<E,A> vector_type; typedef typename vector_type::value_type value_type; switch (v.size()) { case 3: { vector< E, fixed<3> > temp; spherical_to_cartesian( value_type(1), value_type(random_unit() * constants<value_type>::two_pi()), acos_safe(random_real(value_type(-1),value_type(1))), 2, colatitude, temp ); v[0] = temp[0]; v[1] = temp[1]; v[2] = temp[2]; break; } case 2: { vector< E, fixed<2> > temp; polar_to_cartesian( value_type(1), value_type(random_unit() * constants<value_type>::two_pi()), temp ); v[0] = temp[0]; v[1] = temp[1]; break; } default: throw std::invalid_argument( "random_unit() for N-d vectors not implemented yet"); break; } } /* Random vector within a given angle of a unit-length axis, i.e. in a cone * (3D) or wedge (2D). * * The same notes the appear above apply here too, more or less. One * difference is that this is really only useful in 2D and 3D (presumably), so * we'll probably just do a compile- or run-time dispatch as appropriate. * * Also, there may be a better algorithm for generating a random unit vector * in a cone; need to look into that. * * All of this 'temp' stuff is because there's no compile-time dispatch for * 3D and 2D vectors, but that'll be fixed soon. */ template < typename E, class A, class VecT > void random_unit(vector<E,A>& v, const VecT& axis, E theta) { typedef vector<E,A> vector_type; typedef typename vector_type::value_type value_type; switch (v.size()) { case 3: { vector< E, fixed<3> > temp, n, temp_axis; temp_axis[0] = axis[0]; temp_axis[1] = axis[1]; temp_axis[2] = axis[2]; /* @todo: Function for finding 'any perpendicular vector'? */ n = axis_3D(cml::index_of_min_abs(axis[0],axis[1],axis[2])); n = cross(n,temp_axis); /* Rotate v 'away from' the axis by a random angle in the range * [-theta,theta] */ temp = rotate_vector(temp_axis,n,random_real(-theta,theta)); /* Rotate v about the axis by a random angle in the range [-pi,pi] */ temp = rotate_vector( temp, temp_axis, random_real( -constants<value_type>::pi(), constants<value_type>::pi() ) ); v[0] = temp[0]; v[1] = temp[1]; v[2] = temp[2]; break; } case 2: { vector< E, fixed<2> > temp, temp_axis; temp_axis[0] = axis[0]; temp_axis[1] = axis[1]; temp = rotate_vector_2D(temp_axis, random_real(-theta,theta)); v[0] = temp[0]; v[1] = temp[1]; break; } default: throw std::invalid_argument( "random_unit(v,axis,theta) only implemented for 2D and 3D"); break; } } /* NEW: Manhattan distance */ template< class VecT_1, class VecT_2 > typename detail::DotPromote< VecT_1, VecT_2 >::promoted_scalar manhattan_distance(const VecT_1& v1, const VecT_2& v2) { /* Check that a promotion exists */ typedef typename et::VectorPromote< VecT_1,VecT_2>::temporary_type promoted_vector; typedef typename detail::DotPromote< VecT_1, VecT_2 >::promoted_scalar scalar_type; scalar_type sum = scalar_type(0); for (size_t i = 0; i < v1.size(); ++i) { sum += std::fabs(v2[i]-v1[i]); } return sum; } } // namespace cml #endif
prophecy/Pillar
Dependencies/Include/cml/matrix/matrix_promotions.h
<gh_stars>10-100 /* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief * * Defines promotions for matrices used in matrix/matrix or matrix/scalar * expressions. * * @sa UnaryMat4_TOp * @sa BinaryMat4_TOp */ #ifndef matrix_promotions_h #define matrix_promotions_h #include <cml/core/cml_meta.h> #include <cml/et/scalar_promotions.h> #include <cml/et/array_promotions.h> #include <cml/fixed.h> #include <cml/dynamic.h> /* This is used below to create a more meaningful compile-time error when * either argument to OuterPromote has the wrong orientation. */ struct outer_promote_expects_properly_oriented_args_error; namespace cml { namespace et { /** Promote two types to a matrixt type. */ template<typename LeftT, typename RightT> struct MatrixPromote { /* Default matrix type promotion template. */ template<typename M1, typename M2> struct MatrixPromoteHelper; /** Type promotion for two matrix types. * * @note This always uses the basis orientation of the left-hand matrix. * @bug This always uses the basis orientation of the left-hand matrix, * which is not always correct. */ template<typename E1, class AT1, typename L1, typename BO1, typename E2, class AT2, typename L2, typename BO2> struct MatrixPromoteHelper< cml::matrix<E1,AT1,BO1,L1>, cml::matrix<E2,AT2,BO2,L2> > { /* Promote the arrays: */ typedef typename ArrayPromote< typename cml::matrix<E1,AT1,BO1,L1>::array_type, typename cml::matrix<E2,AT2,BO2,L2>::array_type >::type promoted_array; /* The deduced matrix result type: */ typedef cml::matrix< typename promoted_array::value_type, typename promoted_array::generator_type, BO1, typename promoted_array::layout > type; /* The deduced temporary type: */ typedef typename type::temporary_type temporary_type; }; /** Type promotion for a matrix and a scalar. */ template<typename E, class AT, typename BO, typename L, typename S> struct MatrixPromoteHelper<cml::matrix<E,AT,BO,L>, S> { /* The deduced matrix result type (the array type is the same): */ typedef cml::matrix<typename ScalarPromote<E,S>::type, AT, BO, L> type; /* The deduced temporary type: */ typedef typename type::temporary_type temporary_type; }; /** Type promotion for a scalar and a matrix. */ template<typename S, typename E, class AT, typename BO, typename L> struct MatrixPromoteHelper<S, cml::matrix<E,AT,BO,L> > { /* The deduced matrix result type (the array type is the same): */ typedef cml::matrix<typename ScalarPromote<S,E>::type, AT, BO, L> type; /* The deduced temporary type: */ typedef typename type::temporary_type temporary_type; }; /** Type promotion for outer product. */ template<typename E1, class AT1, typename E2, class AT2> struct MatrixPromoteHelper< cml::vector<E1,AT1>, cml::vector<E2,AT2> > { typedef cml::vector<E1,AT1> left_type; typedef cml::vector<E2,AT2> right_type; typedef CML_DEFAULT_BASIS_ORIENTATION basis_orient; /* Get matrix size: */ enum { array_rows = left_type::array_size, array_cols = right_type::array_size }; /* Deduce the corresponding matrix types for the vectors: */ typedef CML_DEFAULT_ARRAY_LAYOUT layout; typedef typename select_if< array_rows == -1, dynamic<>, fixed<array_rows,1> >::result left_storage; typedef cml::matrix<E1,left_storage,basis_orient,layout> left_matrix; typedef typename select_if< array_cols == -1, dynamic<>, fixed<1,array_cols> >::result right_storage; typedef cml::matrix<E2,right_storage,basis_orient,layout> right_matrix; /* Finally, promote the matrix types to get the result: */ typedef typename et::MatrixPromote<left_matrix,right_matrix>::type type; typedef typename type::temporary_type temporary_type; }; /** Remove const and & from the to-be-promoted types. */ typedef typename remove_const< typename remove_reference<LeftT>::type>::type LeftBaseT; typedef typename remove_const< typename remove_reference<RightT>::type>::type RightBaseT; typedef typename MatrixPromoteHelper<LeftBaseT,RightBaseT>::type type; typedef typename type::temporary_type temporary_type; }; /** * NOTE: MatrixPromote* are somewhat ad hoc, and were added to * simplify the code for matrix slerp/squad/etc. */ /** Type promotion for two matrix types. */ template < class Mat1_T, class Mat2_T > struct MatrixPromote2 { typedef typename MatrixPromote< typename Mat1_T::temporary_type, typename Mat2_T::temporary_type >::temporary_type temporary_type; typedef typename temporary_type::value_type value_type; }; /** Type promotion for three matrix types. */ template < class Mat1_T, class Mat2_T, class Mat3_T > struct MatrixPromote3 { typedef typename MatrixPromote< typename Mat1_T::temporary_type, typename MatrixPromote< typename Mat2_T::temporary_type, typename Mat3_T::temporary_type >::temporary_type >::temporary_type temporary_type; typedef typename temporary_type::value_type value_type; }; /** Type promotion for four matrix types. */ template < class Mat1_T, class Mat2_T, class Mat3_T, class Mat4_T > struct MatrixPromote4 { typedef typename MatrixPromote< typename Mat1_T::temporary_type, typename MatrixPromote< typename Mat2_T::temporary_type, typename MatrixPromote< typename Mat3_T::temporary_type, typename Mat4_T::temporary_type >::temporary_type >::temporary_type >::temporary_type temporary_type; typedef typename temporary_type::value_type value_type; }; } // namespace et } // namespace cml #endif // ------------------------------------------------------------------------- // vim:ft=cpp
prophecy/Pillar
Build/iOSMac/WonderlandIosLib/WonderlandIosLib.h
<gh_stars>1-10 // // WonderlandIosLib.h // WonderlandIosLib // // Created by <NAME> on 8/11/2559 BE. // Copyright © 2559 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> @interface WonderlandIosLib : NSObject @end
prophecy/Pillar
Src/Foundation/IScene.h
/* * This source file is part of Wonderland, the C++ Cross-platform middleware for game * * For the latest information, see https://github.com/prophecy/Wonderland * * The MIT License (MIT) * Copyright (c) 2015 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #ifndef __ISCENE_H__ #define __ISCENE_H__ #include "IBase.h" #include "ITaskManager.h" #include "IEventManager.h" #include "IEntity.h" class ISceneManager; class IScene : public IBase { public: virtual void Create() = 0; virtual void Destroy() = 0; virtual void Start() = 0; virtual void Stop() = 0; virtual void Resume() = 0; virtual void Pause() = 0; // todo: consider to move "AddEntity" to be in "Entity manager" virtual void AddEntity(WonderPtr<IEntity> entity) { std::vector< WonderPtr<IEntity> > entitiesDepth; entitiesDepth.push_back(entity); std::vector< std::vector< WonderPtr<IEntity> > > entitiesDepthList; std::vector< WonderPtr<IEntity> > rootEntityAsList; rootEntityAsList.push_back(entity); entitiesDepthList.push_back(rootEntityAsList); // depth search while ( true ) { // Found brunch if ( ! entitiesDepth.back()->entities.empty() ) { // Initiate sub brunches/entities AT index 0 entitiesDepthList.push_back(entitiesDepth.back()->entities); // Initiate tasks _AddTasks(entitiesDepth.back()); // Add the index 0 for the next depth entitiesDepth.push_back(*entitiesDepthList.back().begin()); } // Found leaf else { // Initiate tasks _AddTasks(entitiesDepth.back()); // Next entity in the same tree depth level, // If the index is AT end(), pop_back, and next entity in higher level _Next(entitiesDepth, entitiesDepthList); } // if root is pop, end this tree if ( entitiesDepth.empty() ) break; } } virtual void DisplayFps(void) { } virtual void BindTask(WonderPtr<ITask> task) { task->scene = this; taskManager->AddTask(task); taskManager->StartTask(task); } private: void _Next( std::vector< WonderPtr<IEntity> >& entitiesDepth, std::vector< std::vector< WonderPtr<IEntity> > > entitiesDepthList) { // Searth bool isFound = false; WonderPtr<IEntity> entity = entitiesDepth.back(); std::vector< WonderPtr<IEntity> > list = entitiesDepthList.back(); //std::vector< WonderPtr<IEntity> >::iterator it = list.begin(); u32 index = 0; for (; index < list.size(); ++index) { if (list[index] == entity) isFound = true; } if ( isFound ) { if ( index >= entitiesDepthList.back().size() ) { // Last element, pop_back 1 level entitiesDepth.pop_back(); entitiesDepthList.pop_back(); // if entities depth is 0, early return if ( entitiesDepth.empty() ) return; // End point of recursive stack // Next the upper level _Next(entitiesDepth, entitiesDepthList); } else { // Next entity entitiesDepth.pop_back(); entitiesDepth.push_back(list[index]); } } else { Log::GetPtr()->LogDebug("entitiesDepth not found in entitiesDepthList!"); } } void _AddTasks(WonderPtr<IEntity> entity) { // Add all tasks of entity std::vector<WonderPtr<ITask>> tasks = entity->tasks; std::vector<WonderPtr<ITask>>::iterator it; for ( it = tasks.begin(); it != tasks.end(); ++it ) { (*it)->scene = this; taskManager->AddTask(*it); taskManager->StartTask(*it); } } public: WonderPtr<ISceneManager> sceneManager; WonderPtr<ITaskManager> taskManager; WonderPtr<IEventManager> eventManager; }; #endif // __ISCENE_H__
prophecy/Pillar
Dependencies/Include/cml/vector/vector_promotions.h
<filename>Dependencies/Include/cml/vector/vector_promotions.h<gh_stars>10-100 /* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief * * Defines promotions for vectors used in vector/vector or vector/scalar * expressions. * * @sa BinaryVectorOp */ #ifndef vector_promotions_h #define vector_promotions_h #include <cml/et/scalar_promotions.h> #include <cml/et/array_promotions.h> namespace cml { namespace et { /* Default vector type promotion template. */ template<class LeftT, class RightT> struct VectorPromote; /** Type promotion for two vector types. */ template<typename E1, class AT1, typename E2, class AT2> struct VectorPromote< cml::vector<E1,AT1>, cml::vector<E2,AT2> > { typedef typename ArrayPromote< typename cml::vector<E1,AT1>::array_type, typename cml::vector<E2,AT2>::array_type >::type promoted_array; /* The deduced vector result type: */ typedef cml::vector< typename promoted_array::value_type, typename promoted_array::generator_type > type; /* The deduced temporary type: */ typedef typename type::temporary_type temporary_type; }; /** Type promotion for a vector and a scalar. */ template<typename E, class AT, typename S> struct VectorPromote<cml::vector<E,AT>, S> { /* The deduced vector result type (the array type is the same): */ typedef cml::vector<typename ScalarPromote<E,S>::type, AT> type; /* The deduced temporary type: */ typedef typename type::temporary_type temporary_type; }; /** Type promotion for a scalar and a vector. */ template<typename S, typename E, class AT> struct VectorPromote<S, cml::vector<E,AT> > { /* The deduced vector result type (the array type is the same): */ typedef cml::vector<typename ScalarPromote<S,E>::type, AT> type; /* The deduced temporary type: */ typedef typename type::temporary_type temporary_type; }; } // namespace et } // namespace cml #endif // ------------------------------------------------------------------------- // vim:ft=cpp
prophecy/Pillar
Dependencies/Include/Rocket/Core/Core.h
/* * This source file is part of libRocket, the HTML/CSS Interface Middleware * * For the latest information, see http://www.librocket.com * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #ifndef ROCKETCORECORE_H #define ROCKETCORECORE_H #include "Types.h" #include "Math.h" #include "Header.h" #include "Box.h" #include "Context.h" #include "ContextInstancer.h" #include "Decorator.h" #include "DecoratorInstancer.h" #include "Element.h" #include "ElementDocument.h" #include "ElementInstancer.h" #include "ElementInstancerGeneric.h" #include "ElementReference.h" #include "ElementScroll.h" #include "ElementText.h" #include "ElementUtilities.h" #include "Event.h" #include "EventInstancer.h" #include "EventListener.h" #include "EventListenerInstancer.h" #include "Factory.h" #include "FileInterface.h" #include "Font.h" #include "FontDatabase.h" #include "FontEffect.h" #include "FontGlyph.h" #include "Geometry.h" #include "GeometryUtilities.h" #include "Input.h" #include "Log.h" #include "Plugin.h" #include "Property.h" #include "PropertyDefinition.h" #include "PropertyDictionary.h" #include "PropertyParser.h" #include "PropertySpecification.h" #include "RenderInterface.h" #include "String.h" #include "StyleSheet.h" #include "StyleSheetKeywords.h" #include "StyleSheetSpecification.h" #include "SystemInterface.h" #include "Texture.h" #include "Types.h" #include "Vertex.h" #include "XMLNodeHandler.h" #include "XMLParser.h" namespace Rocket { namespace Core { class Plugin; /** Rocket library core API. @author <NAME> */ /// Initialises Rocket. ROCKETCORE_API bool Initialise(); /// Shutdown Rocket. ROCKETCORE_API void Shutdown(); /// Returns the version of this Rocket library. /// @return The version number. ROCKETCORE_API String GetVersion(); /// Sets the interface through which all system requests are made. This must be called before Initialise(). /// @param[in] system_interface The application-specified logging interface. ROCKETCORE_API void SetSystemInterface(SystemInterface* system_interface); /// Returns Rocket's system interface. /// @return Rocket's system interface. ROCKETCORE_API SystemInterface* GetSystemInterface(); /// Sets the interface through which all rendering requests are made. This is not required to be called, but if it is /// it must be called before Initialise(). If no render interface is specified, then all contexts must have a custom /// render interface. /// @param[in] render_interface Render interface implementation. ROCKETCORE_API void SetRenderInterface(RenderInterface* render_interface); /// Returns Rocket's default's render interface. /// @return Rocket's render interface. ROCKETCORE_API RenderInterface* GetRenderInterface(); /// Sets the interface through which all file I/O requests are made. This is not required to be called, but if it is it /// must be called before Initialise(). /// @param[in] file_interface The application-specified file interface ROCKETCORE_API void SetFileInterface(FileInterface* file_interface); /// Returns Rocket's file interface. /// @return Rocket's file interface. ROCKETCORE_API FileInterface* GetFileInterface(); /// Creates a new element context. /// @param[in] name The new name of the context. This must be unique. /// @param[in] dimensions The initial dimensions of the new context. /// @param[in] render_interface The custom render interface to use, or NULL to use the default. /// @return The new context, or NULL if the context could not be created. ROCKETCORE_API Context* CreateContext(const String& name, const Vector2i& dimensions, RenderInterface* render_interface = NULL); /// Fetches a previously constructed context by name. /// @param[in] name The name of the desired context. /// @return The desired context, or NULL if no context exists with the given name. ROCKETCORE_API Context* GetContext(const String& name); /// Fetches a context by index. /// @param[in] index The index of the desired context. If this is outside of the valid range of contexts, it will be clamped. /// @return The requested context, or NULL if no contexts exist. ROCKETCORE_API Context* GetContext(int index); /// Returns the number of active contexts. /// @return The total number of active Rocket contexts. ROCKETCORE_API int GetNumContexts(); /// Registers a generic Rocket plugin. ROCKETCORE_API void RegisterPlugin(Plugin* plugin); /// Forces all compiled geometry handles generated by libRocket to be released. ROCKETCORE_API void ReleaseCompiledGeometries(); /// Forces all texture handles loaded and generated by libRocket to be released. ROCKETCORE_API void ReleaseTextures(); } } #endif
prophecy/Pillar
Dependencies/Include/cml/matrix/matrix_ops.h
<filename>Dependencies/Include/cml/matrix/matrix_ops.h /* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief Defines matrix operators. */ #ifndef matrix_ops_h #define matrix_ops_h #include <cml/et/scalar_ops.h> #include <cml/matrix/matrix_expr.h> #include <cml/matrix/matop_macros.h> namespace cml { CML_MAT_UNIOP( operator+, et::OpPos) CML_MATXPR_UNIOP( operator+, et::OpPos) CML_MAT_UNIOP( operator-, et::OpNeg) CML_MATXPR_UNIOP( operator-, et::OpNeg) CML_MAT_MAT_BINOP( operator+, et::OpAdd) CML_MATXPR_MAT_BINOP( operator+, et::OpAdd) CML_MAT_MATXPR_BINOP( operator+, et::OpAdd) CML_MATXPR_MATXPR_BINOP( operator+, et::OpAdd) CML_MAT_MAT_BINOP( operator-, et::OpSub) CML_MATXPR_MAT_BINOP( operator-, et::OpSub) CML_MAT_MATXPR_BINOP( operator-, et::OpSub) CML_MATXPR_MATXPR_BINOP( operator-, et::OpSub) CML_MAT_SCALAR_BINOP( operator*, et::OpMul) CML_SCALAR_MAT_BINOP( operator*, et::OpMul) CML_MATXPR_SCALAR_BINOP( operator*, et::OpMul) CML_SCALAR_MATXPR_BINOP( operator*, et::OpMul) CML_MAT_SCALAR_BINOP( operator/, et::OpDiv) CML_MATXPR_SCALAR_BINOP( operator/, et::OpDiv) } // namespace cml #endif // ------------------------------------------------------------------------- // vim:ft=cpp
prophecy/Pillar
Src/Foundation/Utility/Types.h
<reponame>prophecy/Pillar /* * This source file is part of Wonderland, the C++ Cross-platform middleware for game * * For the latest information, see https://github.com/prophecy/Wonderland * * The MIT License (MIT) * Copyright (c) 2015 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #ifndef __TYPES_H__ #define __TYPES_H__ #define WONDERLAND_PLATFORM_NONE 0 #define WONDERLAND_PLATFORM_WINDOWS 1 #define WONDERLAND_PLATFORM_IOS 2 #define WONDERLAND_PLATFORM_ANDROID 3 #define WONDERLAND_PLATFORM_MAC 4 #define WONDERLAND_ACTIVE_PLATFORM WONDERLAND_PLATFORM_NONE #define MEM_POOL_DEBUG #if defined( __APPLE_CC__) # include "TargetConditionals.h" /* // Complicated way to detect iOS devices # if __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ >= 50000 || __IPHONE_OS_VERSION_MIN_REQUIRED >= 30000 # undef WONDERLAND_ACTIVE_PLATFORM # define WONDERLAND_ACTIVE_PLATFORM WONDERLAND_PLATFORM_IOS */ # if TARGET_IPHONE_SIMULATOR || TARGET_OS_IPHONE # define WONDERLAND_ACTIVE_PLATFORM WONDERLAND_PLATFORM_IOS # elif TARGET_OS_MAC # undef WONDERLAND_ACTIVE_PLATFORM # define WONDERLAND_ACTIVE_PLATFORM WONDERLAND_PLATFORM_MAC # endif #elif defined( __WIN32__ ) || defined( _WIN32 ) # undef WONDERLAND_ACTIVE_PLATFORM # define WONDERLAND_ACTIVE_PLATFORM WONDERLAND_PLATFORM_WINDOWS #elif defined( __ANDROID__ ) # undef WONDERLAND_ACTIVE_PLATFORM # define WONDERLAND_ACTIVE_PLATFORM WONDERLAND_PLATFORM_ANDROID #endif // Include # include <string> # include <vector> # include <deque> # include <map> # include <set> # include <list> // Include for Windows #if WONDERLAND_ACTIVE_PLATFORM == WONDERLAND_PLATFORM_WINDOWS # include <windows.h> #endif // Typedef #if WONDERLAND_ACTIVE_PLATFORM == WONDERLAND_PLATFORM_WINDOWS # if _WIN64 typedef unsigned __int64 addr; # else typedef unsigned __int32 addr; # endif typedef __int8 s8; typedef __int16 s16; typedef __int32 s32; typedef __int64 s64; typedef unsigned __int8 u8; typedef unsigned __int16 u16; typedef unsigned __int32 u32; typedef unsigned __int64 u64; typedef volatile u8 vu8; typedef volatile u16 vu16; typedef volatile u32 vu32; typedef volatile u64 vu64; typedef volatile s8 vs8; typedef volatile s16 vs16; typedef volatile s32 vs32; typedef volatile s64 vs64; typedef float f32; typedef double f64; typedef volatile f32 vf32; typedef volatile f64 vf64; typedef size_t size_t; #elif WONDERLAND_ACTIVE_PLATFORM == WONDERLAND_PLATFORM_IOS || WONDERLAND_ACTIVE_PLATFORM == WONDERLAND_PLATFORM_MAC # if __x86_64__ || __ppc64__ || __LP64__ typedef unsigned long addr; # else typedef unsigned int addr; # endif typedef unsigned char s8; typedef short int s16; typedef int s32; typedef long long s64; typedef unsigned char u8; typedef unsigned short int u16; typedef unsigned int u32; typedef unsigned long long u64; typedef volatile u8 vu8; typedef volatile u16 vu16; typedef volatile u32 vu32; typedef volatile u64 vu64; typedef volatile s8 vs8; typedef volatile s16 vs16; typedef volatile s32 vs32; typedef volatile s64 vs64; typedef float f32; typedef double f64; typedef volatile f32 vf32; typedef volatile f64 vf64; typedef size_t size_t; #elif WONDERLAND_ACTIVE_PLATFORM == WONDERLAND_PLATFORM_ANDROID typedef unsigned char s8; typedef short int s16; typedef int s32; typedef long long s64; typedef unsigned char u8; typedef unsigned short int u16; typedef unsigned int u32; typedef unsigned long long u64; typedef volatile u8 vu8; typedef volatile u16 vu16; typedef volatile u32 vu32; typedef volatile u64 vu64; typedef volatile s8 vs8; typedef volatile s16 vs16; typedef volatile s32 vs32; typedef volatile s64 vs64; typedef float f32; typedef double f64; typedef volatile f32 vf32; typedef volatile f64 vf64; typedef size_t size_t; #endif // TRUE #ifndef TRUE # define TRUE 1 #endif // TRUE // FALSE #ifndef FALSE # define FALSE 0 #endif // FALSE // INVALID #ifndef INVALID # define INVALID -1 #endif // INVALID #ifndef NULL # ifdef __cplusplus # define NULL 0 # else // __cplusplus # define NULL ((void *)0) # endif // __cplusplus #endif // NULL // Constance const f32 PI = 3.14159265358979323846f; const f32 PI_2 = 1.57079632679489661923f; const f32 PI_4 = 0.785398163397448309616f; #endif // __TYPES_H__
prophecy/Pillar
Dependencies/Include/Rocket/Core/Input.h
<gh_stars>100-1000 /* * This source file is part of libRocket, the HTML/CSS Interface Middleware * * For the latest information, see http://www.librocket.com * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #ifndef ROCKETCOREINPUT_H #define ROCKETCOREINPUT_H namespace Rocket { namespace Core { /* Enumerants for sending input events into Rocket. @author <NAME> */ namespace Input { enum KeyIdentifier { KI_UNKNOWN = 0, KI_SPACE = 1, KI_0 = 2, KI_1 = 3, KI_2 = 4, KI_3 = 5, KI_4 = 6, KI_5 = 7, KI_6 = 8, KI_7 = 9, KI_8 = 10, KI_9 = 11, KI_A = 12, KI_B = 13, KI_C = 14, KI_D = 15, KI_E = 16, KI_F = 17, KI_G = 18, KI_H = 19, KI_I = 20, KI_J = 21, KI_K = 22, KI_L = 23, KI_M = 24, KI_N = 25, KI_O = 26, KI_P = 27, KI_Q = 28, KI_R = 29, KI_S = 30, KI_T = 31, KI_U = 32, KI_V = 33, KI_W = 34, KI_X = 35, KI_Y = 36, KI_Z = 37, KI_OEM_1 = 38, // US standard keyboard; the ';:' key. KI_OEM_PLUS = 39, // Any region; the '=+' key. KI_OEM_COMMA = 40, // Any region; the ',<' key. KI_OEM_MINUS = 41, // Any region; the '-_' key. KI_OEM_PERIOD = 42, // Any region; the '.>' key. KI_OEM_2 = 43, // Any region; the '/?' key. KI_OEM_3 = 44, // Any region; the '`~' key. KI_OEM_4 = 45, // US standard keyboard; the '[{' key. KI_OEM_5 = 46, // US standard keyboard; the '\|' key. KI_OEM_6 = 47, // US standard keyboard; the ']}' key. KI_OEM_7 = 48, // US standard keyboard; the ''"' key. KI_OEM_8 = 49, KI_OEM_102 = 50, // RT 102-key keyboard; the '<>' or '\|' key. KI_NUMPAD0 = 51, KI_NUMPAD1 = 52, KI_NUMPAD2 = 53, KI_NUMPAD3 = 54, KI_NUMPAD4 = 55, KI_NUMPAD5 = 56, KI_NUMPAD6 = 57, KI_NUMPAD7 = 58, KI_NUMPAD8 = 59, KI_NUMPAD9 = 60, KI_NUMPADENTER = 61, KI_MULTIPLY = 62, // Asterisk on the numeric keypad. KI_ADD = 63, // Plus on the numeric keypad. KI_SEPARATOR = 64, KI_SUBTRACT = 65, // Minus on the numeric keypad. KI_DECIMAL = 66, // Period on the numeric keypad. KI_DIVIDE = 67, // Forward Slash on the numeric keypad. /* * NEC PC-9800 kbd definitions */ KI_OEM_NEC_EQUAL = 68, // Equals key on the numeric keypad. KI_BACK = 69, // Backspace key. KI_TAB = 70, // Tab key. KI_CLEAR = 71, KI_RETURN = 72, KI_PAUSE = 73, KI_CAPITAL = 74, // Capslock key. KI_KANA = 75, // IME Kana mode. KI_HANGUL = 76, // IME Hangul mode. KI_JUNJA = 77, // IME Junja mode. KI_FINAL = 78, // IME final mode. KI_HANJA = 79, // IME Hanja mode. KI_KANJI = 80, // IME Kanji mode. KI_ESCAPE = 81, // Escape key. KI_CONVERT = 82, // IME convert. KI_NONCONVERT = 83, // IME nonconvert. KI_ACCEPT = 84, // IME accept. KI_MODECHANGE = 85, // IME mode change request. KI_PRIOR = 86, // Page Up key. KI_NEXT = 87, // Page Down key. KI_END = 88, KI_HOME = 89, KI_LEFT = 90, // Left Arrow key. KI_UP = 91, // Up Arrow key. KI_RIGHT = 92, // Right Arrow key. KI_DOWN = 93, // Down Arrow key. KI_SELECT = 94, KI_PRINT = 95, KI_EXECUTE = 96, KI_SNAPSHOT = 97, // Print Screen key. KI_INSERT = 98, KI_DELETE = 99, KI_HELP = 100, KI_LWIN = 101, // Left Windows key. KI_RWIN = 102, // Right Windows key. KI_APPS = 103, // Applications key. KI_POWER = 104, KI_SLEEP = 105, KI_WAKE = 106, KI_F1 = 107, KI_F2 = 108, KI_F3 = 109, KI_F4 = 110, KI_F5 = 111, KI_F6 = 112, KI_F7 = 113, KI_F8 = 114, KI_F9 = 115, KI_F10 = 116, KI_F11 = 117, KI_F12 = 118, KI_F13 = 119, KI_F14 = 120, KI_F15 = 121, KI_F16 = 122, KI_F17 = 123, KI_F18 = 124, KI_F19 = 125, KI_F20 = 126, KI_F21 = 127, KI_F22 = 128, KI_F23 = 129, KI_F24 = 130, KI_NUMLOCK = 131, // Numlock key. KI_SCROLL = 132, // Scroll Lock key. /* * Fujitsu/OASYS kbd definitions */ KI_OEM_FJ_JISHO = 133, // 'Dictionary' key. KI_OEM_FJ_MASSHOU = 134, // 'Unregister word' key. KI_OEM_FJ_TOUROKU = 135, // 'Register word' key. KI_OEM_FJ_LOYA = 136, // 'Left OYAYUBI' key. KI_OEM_FJ_ROYA = 137, // 'Right OYAYUBI' key. KI_LSHIFT = 138, KI_RSHIFT = 139, KI_LCONTROL = 140, KI_RCONTROL = 141, KI_LMENU = 142, KI_RMENU = 143, KI_BROWSER_BACK = 144, KI_BROWSER_FORWARD = 145, KI_BROWSER_REFRESH = 146, KI_BROWSER_STOP = 147, KI_BROWSER_SEARCH = 148, KI_BROWSER_FAVORITES = 149, KI_BROWSER_HOME = 150, KI_VOLUME_MUTE = 151, KI_VOLUME_DOWN = 152, KI_VOLUME_UP = 153, KI_MEDIA_NEXT_TRACK = 154, KI_MEDIA_PREV_TRACK = 155, KI_MEDIA_STOP = 156, KI_MEDIA_PLAY_PAUSE = 157, KI_LAUNCH_MAIL = 158, KI_LAUNCH_MEDIA_SELECT = 159, KI_LAUNCH_APP1 = 160, KI_LAUNCH_APP2 = 161, /* * Various extended or enhanced keyboards */ KI_OEM_AX = 162, KI_ICO_HELP = 163, KI_ICO_00 = 164, KI_PROCESSKEY = 165, // IME Process key. KI_ICO_CLEAR = 166, KI_ATTN = 167, KI_CRSEL = 168, KI_EXSEL = 169, KI_EREOF = 170, KI_PLAY = 171, KI_ZOOM = 172, KI_PA1 = 173, KI_OEM_CLEAR = 174, KI_LMETA = 175, KI_RMETA = 176 }; enum KeyModifier { KM_CTRL = 1 << 0, // Set if at least one Ctrl key is depressed. KM_SHIFT = 1 << 1, // Set if at least one Shift key is depressed. KM_ALT = 1 << 2, // Set if at least one Alt key is depressed. KM_META = 1 << 3, // Set if at least one Meta key (the command key) is depressed. KM_CAPSLOCK = 1 << 4, // Set if caps lock is enabled. KM_NUMLOCK = 1 << 5, // Set if num lock is enabled. KM_SCROLLLOCK = 1 << 6 // Set if scroll lock is enabled. }; } } } #endif
prophecy/Pillar
Dependencies/Include/cml/dynamic.h
/* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief */ #ifndef dynamic_h #define dynamic_h #include <cml/defaults.h> namespace cml { /** This is a selector for dynamic 1D and 2D arrays. * * The dynamic<> struct has no implementation; it is used only to select a * 1D or 2D array type as the base class of a vector or matrix. * * @sa fixed * @sa external */ template<class Alloc = CML_DEFAULT_ARRAY_ALLOC> struct dynamic; } // namespace cml #endif // ------------------------------------------------------------------------- // vim:ft=cpp
prophecy/Pillar
Dependencies/Include/cml/et/tags.h
/* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief */ #ifndef et_tags_h #define et_tags_h namespace cml { namespace et { /** Tag an expression as returning a scalar. */ struct scalar_result_tag {}; /** Tag an expression as returning a vector. */ struct vector_result_tag {}; /** Tag an expression as returning a matrix. */ struct matrix_result_tag {}; /** Tag an expression as returning a quaternion. */ struct quaternion_result_tag {}; /** Marker for unary expression ops. */ struct unary_expression {}; /** Marker for biary expression ops. */ struct binary_expression {}; /** Marker for expression tree operator nodes. */ struct expr_node_tag {}; /** Marker for expression tree terminals (leaves). */ struct expr_leaf_tag {}; /** Marker for assignable types. */ struct assignable_tag {}; /** Marker for assignable types. */ struct not_assignable_tag {}; } // namespace et } // namespace cml #endif // ------------------------------------------------------------------------- // vim:ft=cpp
prophecy/Pillar
Dependencies/Include/Rocket/Core/ElementDocument.h
/* * This source file is part of libRocket, the HTML/CSS Interface Middleware * * For the latest information, see http://www.librocket.com * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #ifndef ROCKETCOREELEMENTDOCUMENT_H #define ROCKETCOREELEMENTDOCUMENT_H #include "Element.h" namespace Rocket { namespace Core { class Stream; } } namespace Rocket { namespace Core { class Context; class DocumentHeader; class ElementText; class StyleSheet; /** Represents a document in the dom tree. @author <NAME> */ class ROCKETCORE_API ElementDocument : public Element { public: ElementDocument(const String& tag); virtual ~ElementDocument(); /// Process given document header void ProcessHeader(const DocumentHeader* header); /// Returns itself as the current document virtual ElementDocument* GetOwnerDocument(); /// Returns the document's context. /// @return The context this document exists within. Context* GetContext(); /// Sets the document's title. /// @param[in] title The new title of the document. void SetTitle(const String& title); /// Returns the title of this document. /// @return The document's title. const String& GetTitle() const; /// Returns the source address of this document. /// @return The source of this document, usually a file name. const String& GetSourceURL() const; /// Sets the style sheet this document, and all of its children, uses. /// @param[in] style_sheet The style sheet to set on the document. void SetStyleSheet(StyleSheet* style_sheet); /// Returns the document's style sheet. /// @return The document's style sheet. virtual StyleSheet* GetStyleSheet() const; /// Brings the document to the front of the document stack. void PullToFront(); /// Sends the document to the back of the document stack. void PushToBack(); /** Flags used for displaying the document. */ enum FocusFlags { NONE = 0, FOCUS = (1 << 1), MODAL = (1 << 2) }; /// Show the document. /// @param[in] focus_flags Flags controlling the changing of focus. Leave as FOCUS to switch focus to the document. void Show(int focus_flags = FOCUS); /// Hide the document. void Hide(); /// Close the document. void Close(); /// Creates the named element. /// @param[in] name The tag name of the element. Element* CreateElement(const String& name); /// Create a text element with the given text content. /// @param[in] text The text content of the text element. ElementText* CreateTextNode(const String& text); /// Does the document have modal display set. /// @return True if the document is hogging focus. bool IsModal() const; /// Load a script into the document. Note that the base implementation does nothing, scripting language addons hook /// this method. /// @param[in] stream Stream of code to process. /// @param[in] source_name Name of the the script the source comes from, useful for debug information. virtual void LoadScript(Stream* stream, const String& source_name); /// Updates the layout if necessary. inline void UpdateLayout() { if (layout_dirty && lock_layout == 0) _UpdateLayout(); } /// Updates the position of the document based on the style properties. void UpdatePosition(); /// Increment/Decrement the layout lock void LockLayout(bool lock); protected: /// Refreshes the document layout if required. virtual void OnUpdate(); /// Repositions the document if necessary. virtual void OnPropertyChange(const PropertyNameList& changed_properties); /// Sets the dirty flag on the layout so the document will format its children before the next render. virtual void DirtyLayout(); /// Returns true if the document has been marked as needing a re-layout. virtual bool IsLayoutDirty(); /// Processes the 'onpropertychange' event, checking for a change in position or size. virtual void ProcessEvent(Event& event); private: // Find the next element to focus, starting at the current element bool FocusNextTabElement(Element* current_element, bool forward); /// Searches forwards or backwards for a focusable element in the given substree bool SearchFocusSubtree(Element* element, bool forward); // Title of the document String title; // The original path this document came from String source_url; // The document's style sheet. StyleSheet* style_sheet; Context* context; // Is the current display modal bool modal; // Is the layout dirty? bool layout_dirty; int lock_layout; friend class Context; friend class Factory; void _UpdateLayout(); }; } } #endif
prophecy/Pillar
Dependencies/Include/SDL_image/IMG_xpm.c
/* SDL_image: An example image loading library for use with SDL Copyright (C) 1997-2013 <NAME> <<EMAIL>> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /* * XPM (X PixMap) image loader: * * Supports the XPMv3 format, EXCEPT: * - hotspot coordinates are ignored * - only colour ('c') colour symbols are used * - rgb.txt is not used (for portability), so only RGB colours * are recognized (#rrggbb etc) - only a few basic colour names are * handled * * The result is an 8bpp indexed surface if possible, otherwise 32bpp. * The colourkey is correctly set if transparency is used. * * Besides the standard API, also provides * * SDL_Surface *IMG_ReadXPMFromArray(char **xpm) * * that reads the image data from an XPM file included in the C source. * * TODO: include rgb.txt here. The full table (from solaris 2.6) only * requires about 13K in binary form. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include "SDL_image.h" #ifdef LOAD_XPM /* See if an image is contained in a data source */ int IMG_isXPM(SDL_RWops *src) { Sint64 start; int is_XPM; char magic[9]; if ( !src ) return 0; start = SDL_RWtell(src); is_XPM = 0; if ( SDL_RWread(src, magic, sizeof(magic), 1) ) { if ( SDL_memcmp(magic, "/* XPM */", sizeof(magic)) == 0 ) { is_XPM = 1; } } SDL_RWseek(src, start, RW_SEEK_SET); return(is_XPM); } /* Hash table to look up colors from pixel strings */ #define STARTING_HASH_SIZE 256 struct hash_entry { char *key; Uint32 color; struct hash_entry *next; }; struct color_hash { struct hash_entry **table; struct hash_entry *entries; /* array of all entries */ struct hash_entry *next_free; int size; int maxnum; }; static int hash_key(const char *key, int cpp, int size) { int hash; hash = 0; while ( cpp-- > 0 ) { hash = hash * 33 + *key++; } return hash & (size - 1); } static struct color_hash *create_colorhash(int maxnum) { int bytes, s; struct color_hash *hash; /* we know how many entries we need, so we can allocate everything here */ hash = (struct color_hash *)SDL_malloc(sizeof *hash); if(!hash) return NULL; /* use power-of-2 sized hash table for decoding speed */ for(s = STARTING_HASH_SIZE; s < maxnum; s <<= 1) ; hash->size = s; hash->maxnum = maxnum; bytes = hash->size * sizeof(struct hash_entry **); hash->entries = NULL; /* in case malloc fails */ hash->table = (struct hash_entry **)SDL_malloc(bytes); if(!hash->table) { SDL_free(hash); return NULL; } memset(hash->table, 0, bytes); hash->entries = (struct hash_entry *)SDL_malloc(maxnum * sizeof(struct hash_entry)); if(!hash->entries) { SDL_free(hash->table); SDL_free(hash); return NULL; } hash->next_free = hash->entries; return hash; } static int add_colorhash(struct color_hash *hash, char *key, int cpp, Uint32 color) { int index = hash_key(key, cpp, hash->size); struct hash_entry *e = hash->next_free++; e->color = color; e->key = key; e->next = hash->table[index]; hash->table[index] = e; return 1; } /* fast lookup that works if cpp == 1 */ #define QUICK_COLORHASH(hash, key) ((hash)->table[*(Uint8 *)(key)]->color) static Uint32 get_colorhash(struct color_hash *hash, const char *key, int cpp) { struct hash_entry *entry = hash->table[hash_key(key, cpp, hash->size)]; while(entry) { if(SDL_memcmp(key, entry->key, cpp) == 0) return entry->color; entry = entry->next; } return 0; /* garbage in - garbage out */ } static void free_colorhash(struct color_hash *hash) { if(hash) { if(hash->table) SDL_free(hash->table); if(hash->entries) SDL_free(hash->entries); SDL_free(hash); } } /* * convert colour spec to RGB (in 0xrrggbb format). * return 1 if successful. */ static int color_to_rgb(char *spec, int speclen, Uint32 *rgb) { /* poor man's rgb.txt */ static struct { char *name; Uint32 rgb; } known[] = { { "none", 0xFFFFFF }, { "black", 0x000000 }, { "white", 0xFFFFFF }, { "red", 0xFF0000 }, { "green", 0x00FF00 }, { "blue", 0x0000FF }, /* This table increases the size of the library by 40K, so it's disabled by default */ #ifdef EXTENDED_XPM_COLORS { "aliceblue", 0xf0f8ff }, { "antiquewhite", 0xfaebd7 }, { "antiquewhite1", 0xffefdb }, { "antiquewhite2", 0xeedfcc }, { "antiquewhite3", 0xcdc0b0 }, { "antiquewhite4", 0x8b8378 }, { "aqua", 0x00ffff }, { "aquamarine", 0x7fffd4 }, { "aquamarine1", 0x7fffd4 }, { "aquamarine2", 0x76eec6 }, { "aquamarine3", 0x66cdaa }, { "aquamarine4", 0x458b74 }, { "azure", 0xf0ffff }, { "azure1", 0xf0ffff }, { "azure2", 0xe0eeee }, { "azure3", 0xc1cdcd }, { "azure4", 0x838b8b }, { "beige", 0xf5f5dc }, { "bisque", 0xffe4c4 }, { "bisque1", 0xffe4c4 }, { "bisque2", 0xeed5b7 }, { "bisque3", 0xcdb79e }, { "bisque4", 0x8b7d6b }, { "black", 0x000000 }, { "blanchedalmond", 0xffebcd }, { "blue", 0x0000ff }, { "blue1", 0x0000ff }, { "blue2", 0x0000ee }, { "blue3", 0x0000cd }, { "blue4", 0x00008B }, { "blueviolet", 0x8a2be2 }, { "brown", 0xA52A2A }, { "brown1", 0xFF4040 }, { "brown2", 0xEE3B3B }, { "brown3", 0xCD3333 }, { "brown4", 0x8B2323 }, { "burlywood", 0xDEB887 }, { "burlywood1", 0xFFD39B }, { "burlywood2", 0xEEC591 }, { "burlywood3", 0xCDAA7D }, { "burlywood4", 0x8B7355 }, { "cadetblue", 0x5F9EA0 }, { "cadetblue", 0x5f9ea0 }, { "cadetblue1", 0x98f5ff }, { "cadetblue2", 0x8ee5ee }, { "cadetblue3", 0x7ac5cd }, { "cadetblue4", 0x53868b }, { "chartreuse", 0x7FFF00 }, { "chartreuse1", 0x7FFF00 }, { "chartreuse2", 0x76EE00 }, { "chartreuse3", 0x66CD00 }, { "chartreuse4", 0x458B00 }, { "chocolate", 0xD2691E }, { "chocolate1", 0xFF7F24 }, { "chocolate2", 0xEE7621 }, { "chocolate3", 0xCD661D }, { "chocolate4", 0x8B4513 }, { "coral", 0xFF7F50 }, { "coral1", 0xFF7256 }, { "coral2", 0xEE6A50 }, { "coral3", 0xCD5B45 }, { "coral4", 0x8B3E2F }, { "cornflowerblue", 0x6495ed }, { "cornsilk", 0xFFF8DC }, { "cornsilk1", 0xFFF8DC }, { "cornsilk2", 0xEEE8CD }, { "cornsilk3", 0xCDC8B1 }, { "cornsilk4", 0x8B8878 }, { "crimson", 0xDC143C }, { "cyan", 0x00FFFF }, { "cyan1", 0x00FFFF }, { "cyan2", 0x00EEEE }, { "cyan3", 0x00CDCD }, { "cyan4", 0x008B8B }, { "darkblue", 0x00008b }, { "darkcyan", 0x008b8b }, { "darkgoldenrod", 0xb8860b }, { "darkgoldenrod1", 0xffb90f }, { "darkgoldenrod2", 0xeead0e }, { "darkgoldenrod3", 0xcd950c }, { "darkgoldenrod4", 0x8b6508 }, { "darkgray", 0xa9a9a9 }, { "darkgreen", 0x006400 }, { "darkgrey", 0xa9a9a9 }, { "darkkhaki", 0xbdb76b }, { "darkmagenta", 0x8b008b }, { "darkolivegreen", 0x556b2f }, { "darkolivegreen1", 0xcaff70 }, { "darkolivegreen2", 0xbcee68 }, { "darkolivegreen3", 0xa2cd5a }, { "darkolivegreen4", 0x6e8b3d }, { "darkorange", 0xff8c00 }, { "darkorange1", 0xff7f00 }, { "darkorange2", 0xee7600 }, { "darkorange3", 0xcd6600 }, { "darkorange4", 0x8b4500 }, { "darkorchid", 0x9932cc }, { "darkorchid1", 0xbf3eff }, { "darkorchid2", 0xb23aee }, { "darkorchid3", 0x9a32cd }, { "darkorchid4", 0x68228b }, { "darkred", 0x8b0000 }, { "darksalmon", 0xe9967a }, { "darkseagreen", 0x8fbc8f }, { "darkseagreen1", 0xc1ffc1 }, { "darkseagreen2", 0xb4eeb4 }, { "darkseagreen3", 0x9bcd9b }, { "darkseagreen4", 0x698b69 }, { "darkslateblue", 0x483d8b }, { "darkslategray", 0x2f4f4f }, { "darkslategray1", 0x97ffff }, { "darkslategray2", 0x8deeee }, { "darkslategray3", 0x79cdcd }, { "darkslategray4", 0x528b8b }, { "darkslategrey", 0x2f4f4f }, { "darkturquoise", 0x00ced1 }, { "darkviolet", 0x9400D3 }, { "darkviolet", 0x9400d3 }, { "deeppink", 0xff1493 }, { "deeppink1", 0xff1493 }, { "deeppink2", 0xee1289 }, { "deeppink3", 0xcd1076 }, { "deeppink4", 0x8b0a50 }, { "deepskyblue", 0x00bfff }, { "deepskyblue1", 0x00bfff }, { "deepskyblue2", 0x00b2ee }, { "deepskyblue3", 0x009acd }, { "deepskyblue4", 0x00688b }, { "dimgray", 0x696969 }, { "dimgrey", 0x696969 }, { "dodgerblue", 0x1e90ff }, { "dodgerblue1", 0x1e90ff }, { "dodgerblue2", 0x1c86ee }, { "dodgerblue3", 0x1874cd }, { "dodgerblue4", 0x104e8b }, { "firebrick", 0xB22222 }, { "firebrick1", 0xFF3030 }, { "firebrick2", 0xEE2C2C }, { "firebrick3", 0xCD2626 }, { "firebrick4", 0x8B1A1A }, { "floralwhite", 0xfffaf0 }, { "forestgreen", 0x228b22 }, { "fractal", 0x808080 }, { "fuchsia", 0xFF00FF }, { "gainsboro", 0xDCDCDC }, { "ghostwhite", 0xf8f8ff }, { "gold", 0xFFD700 }, { "gold1", 0xFFD700 }, { "gold2", 0xEEC900 }, { "gold3", 0xCDAD00 }, { "gold4", 0x8B7500 }, { "goldenrod", 0xDAA520 }, { "goldenrod1", 0xFFC125 }, { "goldenrod2", 0xEEB422 }, { "goldenrod3", 0xCD9B1D }, { "goldenrod4", 0x8B6914 }, { "gray", 0x7E7E7E }, { "gray", 0xBEBEBE }, { "gray0", 0x000000 }, { "gray1", 0x030303 }, { "gray10", 0x1A1A1A }, { "gray100", 0xFFFFFF }, { "gray11", 0x1C1C1C }, { "gray12", 0x1F1F1F }, { "gray13", 0x212121 }, { "gray14", 0x242424 }, { "gray15", 0x262626 }, { "gray16", 0x292929 }, { "gray17", 0x2B2B2B }, { "gray18", 0x2E2E2E }, { "gray19", 0x303030 }, { "gray2", 0x050505 }, { "gray20", 0x333333 }, { "gray21", 0x363636 }, { "gray22", 0x383838 }, { "gray23", 0x3B3B3B }, { "gray24", 0x3D3D3D }, { "gray25", 0x404040 }, { "gray26", 0x424242 }, { "gray27", 0x454545 }, { "gray28", 0x474747 }, { "gray29", 0x4A4A4A }, { "gray3", 0x080808 }, { "gray30", 0x4D4D4D }, { "gray31", 0x4F4F4F }, { "gray32", 0x525252 }, { "gray33", 0x545454 }, { "gray34", 0x575757 }, { "gray35", 0x595959 }, { "gray36", 0x5C5C5C }, { "gray37", 0x5E5E5E }, { "gray38", 0x616161 }, { "gray39", 0x636363 }, { "gray4", 0x0A0A0A }, { "gray40", 0x666666 }, { "gray41", 0x696969 }, { "gray42", 0x6B6B6B }, { "gray43", 0x6E6E6E }, { "gray44", 0x707070 }, { "gray45", 0x737373 }, { "gray46", 0x757575 }, { "gray47", 0x787878 }, { "gray48", 0x7A7A7A }, { "gray49", 0x7D7D7D }, { "gray5", 0x0D0D0D }, { "gray50", 0x7F7F7F }, { "gray51", 0x828282 }, { "gray52", 0x858585 }, { "gray53", 0x878787 }, { "gray54", 0x8A8A8A }, { "gray55", 0x8C8C8C }, { "gray56", 0x8F8F8F }, { "gray57", 0x919191 }, { "gray58", 0x949494 }, { "gray59", 0x969696 }, { "gray6", 0x0F0F0F }, { "gray60", 0x999999 }, { "gray61", 0x9C9C9C }, { "gray62", 0x9E9E9E }, { "gray63", 0xA1A1A1 }, { "gray64", 0xA3A3A3 }, { "gray65", 0xA6A6A6 }, { "gray66", 0xA8A8A8 }, { "gray67", 0xABABAB }, { "gray68", 0xADADAD }, { "gray69", 0xB0B0B0 }, { "gray7", 0x121212 }, { "gray70", 0xB3B3B3 }, { "gray71", 0xB5B5B5 }, { "gray72", 0xB8B8B8 }, { "gray73", 0xBABABA }, { "gray74", 0xBDBDBD }, { "gray75", 0xBFBFBF }, { "gray76", 0xC2C2C2 }, { "gray77", 0xC4C4C4 }, { "gray78", 0xC7C7C7 }, { "gray79", 0xC9C9C9 }, { "gray8", 0x141414 }, { "gray80", 0xCCCCCC }, { "gray81", 0xCFCFCF }, { "gray82", 0xD1D1D1 }, { "gray83", 0xD4D4D4 }, { "gray84", 0xD6D6D6 }, { "gray85", 0xD9D9D9 }, { "gray86", 0xDBDBDB }, { "gray87", 0xDEDEDE }, { "gray88", 0xE0E0E0 }, { "gray89", 0xE3E3E3 }, { "gray9", 0x171717 }, { "gray90", 0xE5E5E5 }, { "gray91", 0xE8E8E8 }, { "gray92", 0xEBEBEB }, { "gray93", 0xEDEDED }, { "gray94", 0xF0F0F0 }, { "gray95", 0xF2F2F2 }, { "gray96", 0xF5F5F5 }, { "gray97", 0xF7F7F7 }, { "gray98", 0xFAFAFA }, { "gray99", 0xFCFCFC }, { "green", 0x008000 }, { "green", 0x00FF00 }, { "green1", 0x00FF00 }, { "green2", 0x00EE00 }, { "green3", 0x00CD00 }, { "green4", 0x008B00 }, { "greenyellow", 0xadff2f }, { "grey", 0xBEBEBE }, { "grey0", 0x000000 }, { "grey1", 0x030303 }, { "grey10", 0x1A1A1A }, { "grey100", 0xFFFFFF }, { "grey11", 0x1C1C1C }, { "grey12", 0x1F1F1F }, { "grey13", 0x212121 }, { "grey14", 0x242424 }, { "grey15", 0x262626 }, { "grey16", 0x292929 }, { "grey17", 0x2B2B2B }, { "grey18", 0x2E2E2E }, { "grey19", 0x303030 }, { "grey2", 0x050505 }, { "grey20", 0x333333 }, { "grey21", 0x363636 }, { "grey22", 0x383838 }, { "grey23", 0x3B3B3B }, { "grey24", 0x3D3D3D }, { "grey25", 0x404040 }, { "grey26", 0x424242 }, { "grey27", 0x454545 }, { "grey28", 0x474747 }, { "grey29", 0x4A4A4A }, { "grey3", 0x080808 }, { "grey30", 0x4D4D4D }, { "grey31", 0x4F4F4F }, { "grey32", 0x525252 }, { "grey33", 0x545454 }, { "grey34", 0x575757 }, { "grey35", 0x595959 }, { "grey36", 0x5C5C5C }, { "grey37", 0x5E5E5E }, { "grey38", 0x616161 }, { "grey39", 0x636363 }, { "grey4", 0x0A0A0A }, { "grey40", 0x666666 }, { "grey41", 0x696969 }, { "grey42", 0x6B6B6B }, { "grey43", 0x6E6E6E }, { "grey44", 0x707070 }, { "grey45", 0x737373 }, { "grey46", 0x757575 }, { "grey47", 0x787878 }, { "grey48", 0x7A7A7A }, { "grey49", 0x7D7D7D }, { "grey5", 0x0D0D0D }, { "grey50", 0x7F7F7F }, { "grey51", 0x828282 }, { "grey52", 0x858585 }, { "grey53", 0x878787 }, { "grey54", 0x8A8A8A }, { "grey55", 0x8C8C8C }, { "grey56", 0x8F8F8F }, { "grey57", 0x919191 }, { "grey58", 0x949494 }, { "grey59", 0x969696 }, { "grey6", 0x0F0F0F }, { "grey60", 0x999999 }, { "grey61", 0x9C9C9C }, { "grey62", 0x9E9E9E }, { "grey63", 0xA1A1A1 }, { "grey64", 0xA3A3A3 }, { "grey65", 0xA6A6A6 }, { "grey66", 0xA8A8A8 }, { "grey67", 0xABABAB }, { "grey68", 0xADADAD }, { "grey69", 0xB0B0B0 }, { "grey7", 0x121212 }, { "grey70", 0xB3B3B3 }, { "grey71", 0xB5B5B5 }, { "grey72", 0xB8B8B8 }, { "grey73", 0xBABABA }, { "grey74", 0xBDBDBD }, { "grey75", 0xBFBFBF }, { "grey76", 0xC2C2C2 }, { "grey77", 0xC4C4C4 }, { "grey78", 0xC7C7C7 }, { "grey79", 0xC9C9C9 }, { "grey8", 0x141414 }, { "grey80", 0xCCCCCC }, { "grey81", 0xCFCFCF }, { "grey82", 0xD1D1D1 }, { "grey83", 0xD4D4D4 }, { "grey84", 0xD6D6D6 }, { "grey85", 0xD9D9D9 }, { "grey86", 0xDBDBDB }, { "grey87", 0xDEDEDE }, { "grey88", 0xE0E0E0 }, { "grey89", 0xE3E3E3 }, { "grey9", 0x171717 }, { "grey90", 0xE5E5E5 }, { "grey91", 0xE8E8E8 }, { "grey92", 0xEBEBEB }, { "grey93", 0xEDEDED }, { "grey94", 0xF0F0F0 }, { "grey95", 0xF2F2F2 }, { "grey96", 0xF5F5F5 }, { "grey97", 0xF7F7F7 }, { "grey98", 0xFAFAFA }, { "grey99", 0xFCFCFC }, { "honeydew", 0xF0FFF0 }, { "honeydew1", 0xF0FFF0 }, { "honeydew2", 0xE0EEE0 }, { "honeydew3", 0xC1CDC1 }, { "honeydew4", 0x838B83 }, { "hotpink", 0xff69b4 }, { "hotpink1", 0xff6eb4 }, { "hotpink2", 0xee6aa7 }, { "hotpink3", 0xcd6090 }, { "hotpink4", 0x8b3a62 }, { "indianred", 0xcd5c5c }, { "indianred1", 0xff6a6a }, { "indianred2", 0xee6363 }, { "indianred3", 0xcd5555 }, { "indianred4", 0x8b3a3a }, { "indigo", 0x4B0082 }, { "ivory", 0xFFFFF0 }, { "ivory1", 0xFFFFF0 }, { "ivory2", 0xEEEEE0 }, { "ivory3", 0xCDCDC1 }, { "ivory4", 0x8B8B83 }, { "khaki", 0xF0E68C }, { "khaki1", 0xFFF68F }, { "khaki2", 0xEEE685 }, { "khaki3", 0xCDC673 }, { "khaki4", 0x8B864E }, { "lavender", 0xE6E6FA }, { "lavenderblush", 0xfff0f5 }, { "lavenderblush1", 0xfff0f5 }, { "lavenderblush2", 0xeee0e5 }, { "lavenderblush3", 0xcdc1c5 }, { "lavenderblush4", 0x8b8386 }, { "lawngreen", 0x7cfc00 }, { "lemonchiffon", 0xfffacd }, { "lemonchiffon1", 0xfffacd }, { "lemonchiffon2", 0xeee9bf }, { "lemonchiffon3", 0xcdc9a5 }, { "lemonchiffon4", 0x8b8970 }, { "lightblue", 0xadd8e6 }, { "lightblue1", 0xbfefff }, { "lightblue2", 0xb2dfee }, { "lightblue3", 0x9ac0cd }, { "lightblue4", 0x68838b }, { "lightcoral", 0xf08080 }, { "lightcyan", 0xe0ffff }, { "lightcyan1", 0xe0ffff }, { "lightcyan2", 0xd1eeee }, { "lightcyan3", 0xb4cdcd }, { "lightcyan4", 0x7a8b8b }, { "lightgoldenrod", 0xeedd82 }, { "lightgoldenrod1", 0xffec8b }, { "lightgoldenrod2", 0xeedc82 }, { "lightgoldenrod3", 0xcdbe70 }, { "lightgoldenrod4", 0x8b814c }, { "lightgoldenrodyellow", 0xfafad2 }, { "lightgray", 0xd3d3d3 }, { "lightgreen", 0x90ee90 }, { "lightgrey", 0xd3d3d3 }, { "lightpink", 0xffb6c1 }, { "lightpink1", 0xffaeb9 }, { "lightpink2", 0xeea2ad }, { "lightpink3", 0xcd8c95 }, { "lightpink4", 0x8b5f65 }, { "lightsalmon", 0xffa07a }, { "lightsalmon1", 0xffa07a }, { "lightsalmon2", 0xee9572 }, { "lightsalmon3", 0xcd8162 }, { "lightsalmon4", 0x8b5742 }, { "lightseagreen", 0x20b2aa }, { "lightskyblue", 0x87cefa }, { "lightskyblue1", 0xb0e2ff }, { "lightskyblue2", 0xa4d3ee }, { "lightskyblue3", 0x8db6cd }, { "lightskyblue4", 0x607b8b }, { "lightslateblue", 0x8470ff }, { "lightslategray", 0x778899 }, { "lightslategrey", 0x778899 }, { "lightsteelblue", 0xb0c4de }, { "lightsteelblue1", 0xcae1ff }, { "lightsteelblue2", 0xbcd2ee }, { "lightsteelblue3", 0xa2b5cd }, { "lightsteelblue4", 0x6e7b8b }, { "lightyellow", 0xffffe0 }, { "lightyellow1", 0xffffe0 }, { "lightyellow2", 0xeeeed1 }, { "lightyellow3", 0xcdcdb4 }, { "lightyellow4", 0x8b8b7a }, { "lime", 0x00FF00 }, { "limegreen", 0x32cd32 }, { "linen", 0xFAF0E6 }, { "magenta", 0xFF00FF }, { "magenta1", 0xFF00FF }, { "magenta2", 0xEE00EE }, { "magenta3", 0xCD00CD }, { "magenta4", 0x8B008B }, { "maroon", 0x800000 }, { "maroon", 0xB03060 }, { "maroon1", 0xFF34B3 }, { "maroon2", 0xEE30A7 }, { "maroon3", 0xCD2990 }, { "maroon4", 0x8B1C62 }, { "mediumaquamarine", 0x66cdaa }, { "mediumblue", 0x0000cd }, { "mediumforestgreen", 0x32814b }, { "mediumgoldenrod", 0xd1c166 }, { "mediumorchid", 0xba55d3 }, { "mediumorchid1", 0xe066ff }, { "mediumorchid2", 0xd15fee }, { "mediumorchid3", 0xb452cd }, { "mediumorchid4", 0x7a378b }, { "mediumpurple", 0x9370db }, { "mediumpurple1", 0xab82ff }, { "mediumpurple2", 0x9f79ee }, { "mediumpurple3", 0x8968cd }, { "mediumpurple4", 0x5d478b }, { "mediumseagreen", 0x3cb371 }, { "mediumslateblue", 0x7b68ee }, { "mediumspringgreen", 0x00fa9a }, { "mediumturquoise", 0x48d1cc }, { "mediumvioletred", 0xc71585 }, { "midnightblue", 0x191970 }, { "mintcream", 0xf5fffa }, { "mistyrose", 0xffe4e1 }, { "mistyrose1", 0xffe4e1 }, { "mistyrose2", 0xeed5d2 }, { "mistyrose3", 0xcdb7b5 }, { "mistyrose4", 0x8b7d7b }, { "moccasin", 0xFFE4B5 }, { "navajowhite", 0xffdead }, { "navajowhite1", 0xffdead }, { "navajowhite2", 0xeecfa1 }, { "navajowhite3", 0xcdb38b }, { "navajowhite4", 0x8b795e }, { "navy", 0x000080 }, { "navyblue", 0x000080 }, { "none", 0x0000FF }, { "oldlace", 0xfdf5e6 }, { "olive", 0x808000 }, { "olivedrab", 0x6b8e23 }, { "olivedrab1", 0xc0ff3e }, { "olivedrab2", 0xb3ee3a }, { "olivedrab3", 0x9acd32 }, { "olivedrab4", 0x698b22 }, { "opaque", 0x000000 }, { "orange", 0xFFA500 }, { "orange1", 0xFFA500 }, { "orange2", 0xEE9A00 }, { "orange3", 0xCD8500 }, { "orange4", 0x8B5A00 }, { "orangered", 0xff4500 }, { "orangered1", 0xff4500 }, { "orangered2", 0xee4000 }, { "orangered3", 0xcd3700 }, { "orangered4", 0x8b2500 }, { "orchid", 0xDA70D6 }, { "orchid1", 0xFF83FA }, { "orchid2", 0xEE7AE9 }, { "orchid3", 0xCD69C9 }, { "orchid4", 0x8B4789 }, { "palegoldenrod", 0xeee8aa }, { "palegreen", 0x98fb98 }, { "palegreen1", 0x9aff9a }, { "palegreen2", 0x90ee90 }, { "palegreen3", 0x7ccd7c }, { "palegreen4", 0x548b54 }, { "paleturquoise", 0xafeeee }, { "paleturquoise1", 0xbbffff }, { "paleturquoise2", 0xaeeeee }, { "paleturquoise3", 0x96cdcd }, { "paleturquoise4", 0x668b8b }, { "palevioletred", 0xdb7093 }, { "palevioletred1", 0xff82ab }, { "palevioletred2", 0xee799f }, { "palevioletred3", 0xcd6889 }, { "palevioletred4", 0x8b475d }, { "papayawhip", 0xffefd5 }, { "peachpuff", 0xffdab9 }, { "peachpuff1", 0xffdab9 }, { "peachpuff2", 0xeecbad }, { "peachpuff3", 0xcdaf95 }, { "peachpuff4", 0x8b7765 }, { "peru", 0xCD853F }, { "pink", 0xFFC0CB }, { "pink1", 0xFFB5C5 }, { "pink2", 0xEEA9B8 }, { "pink3", 0xCD919E }, { "pink4", 0x8B636C }, { "plum", 0xDDA0DD }, { "plum1", 0xFFBBFF }, { "plum2", 0xEEAEEE }, { "plum3", 0xCD96CD }, { "plum4", 0x8B668B }, { "powderblue", 0xb0e0e6 }, { "purple", 0x800080 }, { "purple", 0xA020F0 }, { "purple1", 0x9B30FF }, { "purple2", 0x912CEE }, { "purple3", 0x7D26CD }, { "purple4", 0x551A8B }, { "red", 0xFF0000 }, { "red1", 0xFF0000 }, { "red2", 0xEE0000 }, { "red3", 0xCD0000 }, { "red4", 0x8B0000 }, { "rosybrown", 0xbc8f8f }, { "rosybrown1", 0xffc1c1 }, { "rosybrown2", 0xeeb4b4 }, { "rosybrown3", 0xcd9b9b }, { "rosybrown4", 0x8b6969 }, { "royalblue", 0x4169e1 }, { "royalblue1", 0x4876ff }, { "royalblue2", 0x436eee }, { "royalblue3", 0x3a5fcd }, { "royalblue4", 0x27408b }, { "saddlebrown", 0x8b4513 }, { "salmon", 0xFA8072 }, { "salmon1", 0xFF8C69 }, { "salmon2", 0xEE8262 }, { "salmon3", 0xCD7054 }, { "salmon4", 0x8B4C39 }, { "sandybrown", 0xf4a460 }, { "seagreen", 0x2e8b57 }, { "seagreen1", 0x54ff9f }, { "seagreen2", 0x4eee94 }, { "seagreen3", 0x43cd80 }, { "seagreen4", 0x2e8b57 }, { "seashell", 0xFFF5EE }, { "seashell1", 0xFFF5EE }, { "seashell2", 0xEEE5DE }, { "seashell3", 0xCDC5BF }, { "seashell4", 0x8B8682 }, { "sienna", 0xA0522D }, { "sienna1", 0xFF8247 }, { "sienna2", 0xEE7942 }, { "sienna3", 0xCD6839 }, { "sienna4", 0x8B4726 }, { "silver", 0xC0C0C0 }, { "skyblue", 0x87ceeb }, { "skyblue1", 0x87ceff }, { "skyblue2", 0x7ec0ee }, { "skyblue3", 0x6ca6cd }, { "skyblue4", 0x4a708b }, { "slateblue", 0x6a5acd }, { "slateblue1", 0x836fff }, { "slateblue2", 0x7a67ee }, { "slateblue3", 0x6959cd }, { "slateblue4", 0x473c8b }, { "slategray", 0x708090 }, { "slategray1", 0xc6e2ff }, { "slategray2", 0xb9d3ee }, { "slategray3", 0x9fb6cd }, { "slategray4", 0x6c7b8b }, { "slategrey", 0x708090 }, { "snow", 0xFFFAFA }, { "snow1", 0xFFFAFA }, { "snow2", 0xEEE9E9 }, { "snow3", 0xCDC9C9 }, { "snow4", 0x8B8989 }, { "springgreen", 0x00ff7f }, { "springgreen1", 0x00ff7f }, { "springgreen2", 0x00ee76 }, { "springgreen3", 0x00cd66 }, { "springgreen4", 0x008b45 }, { "steelblue", 0x4682b4 }, { "steelblue1", 0x63b8ff }, { "steelblue2", 0x5cacee }, { "steelblue3", 0x4f94cd }, { "steelblue4", 0x36648b }, { "tan", 0xD2B48C }, { "tan1", 0xFFA54F }, { "tan2", 0xEE9A49 }, { "tan3", 0xCD853F }, { "tan4", 0x8B5A2B }, { "teal", 0x008080 }, { "thistle", 0xD8BFD8 }, { "thistle1", 0xFFE1FF }, { "thistle2", 0xEED2EE }, { "thistle3", 0xCDB5CD }, { "thistle4", 0x8B7B8B }, { "tomato", 0xFF6347 }, { "tomato1", 0xFF6347 }, { "tomato2", 0xEE5C42 }, { "tomato3", 0xCD4F39 }, { "tomato4", 0x8B3626 }, { "transparent", 0x0000FF }, { "turquoise", 0x40E0D0 }, { "turquoise1", 0x00F5FF }, { "turquoise2", 0x00E5EE }, { "turquoise3", 0x00C5CD }, { "turquoise4", 0x00868B }, { "violet", 0xEE82EE }, { "violetred", 0xd02090 }, { "violetred1", 0xff3e96 }, { "violetred2", 0xee3a8c }, { "violetred3", 0xcd3278 }, { "violetred4", 0x8b2252 }, { "wheat", 0xF5DEB3 }, { "wheat1", 0xFFE7BA }, { "wheat2", 0xEED8AE }, { "wheat3", 0xCDBA96 }, { "wheat4", 0x8B7E66 }, { "white", 0xFFFFFF }, { "whitesmoke", 0xf5f5f5 }, { "yellow", 0xFFFF00 }, { "yellow1", 0xFFFF00 }, { "yellow2", 0xEEEE00 }, { "yellow3", 0xCDCD00 }, { "yellow4", 0x8B8B00 }, { "yellowgreen", 0x9acd32 }, #endif /* EXTENDED_XPM_COLORS */ {"none", 0xFFFFFF} }; if(spec[0] == '#') { char buf[7]; switch(speclen) { case 4: buf[0] = buf[1] = spec[1]; buf[2] = buf[3] = spec[2]; buf[4] = buf[5] = spec[3]; break; case 7: SDL_memcpy(buf, spec + 1, 6); break; case 13: buf[0] = spec[1]; buf[1] = spec[2]; buf[2] = spec[5]; buf[3] = spec[6]; buf[4] = spec[9]; buf[5] = spec[10]; break; } buf[6] = '\0'; *rgb = strtol(buf, NULL, 16); return 1; } else { int i; for(i = 0; i < SDL_arraysize(known); i++) if(SDL_strncasecmp(known[i].name, spec, speclen) == 0) { *rgb = known[i].rgb; return 1; } return 0; } } #ifndef MAX #define MAX(a, b) ((a) > (b) ? (a) : (b)) #endif static char *linebuf; static int buflen; static char *error; /* * Read next line from the source. * If len > 0, it's assumed to be at least len chars (for efficiency). * Return NULL and set error upon EOF or parse error. */ static char *get_next_line(char ***lines, SDL_RWops *src, int len) { char *linebufnew; if(lines) { return *(*lines)++; } else { char c; int n; do { if(SDL_RWread(src, &c, 1, 1) <= 0) { error = "Premature end of data"; return NULL; } } while(c != '"'); if(len) { len += 4; /* "\",\n\0" */ if(len > buflen){ buflen = len; linebufnew = (char *)SDL_realloc(linebuf, buflen); if(!linebufnew) { SDL_free(linebuf); error = "Out of memory"; return NULL; } linebuf = linebufnew; } if(SDL_RWread(src, linebuf, len - 1, 1) <= 0) { error = "Premature end of data"; return NULL; } n = len - 2; } else { n = 0; do { if(n >= buflen - 1) { if(buflen == 0) buflen = 16; buflen *= 2; linebufnew = (char *)SDL_realloc(linebuf, buflen); if(!linebufnew) { SDL_free(linebuf); error = "Out of memory"; return NULL; } linebuf = linebufnew; } if(SDL_RWread(src, linebuf + n, 1, 1) <= 0) { error = "Premature end of data"; return NULL; } } while(linebuf[n++] != '"'); n--; } linebuf[n] = '\0'; return linebuf; } } #define SKIPSPACE(p) \ do { \ while(SDL_isspace((unsigned char)*(p))) \ ++(p); \ } while(0) #define SKIPNONSPACE(p) \ do { \ while(!SDL_isspace((unsigned char)*(p)) && *p) \ ++(p); \ } while(0) /* read XPM from either array or RWops */ static SDL_Surface *load_xpm(char **xpm, SDL_RWops *src) { Sint64 start = 0; SDL_Surface *image = NULL; int index; int x, y; int w, h, ncolors, cpp; int indexed; Uint8 *dst; struct color_hash *colors = NULL; SDL_Color *im_colors = NULL; char *keystrings = NULL, *nextkey; char *line; char ***xpmlines = NULL; int pixels_len; error = NULL; linebuf = NULL; buflen = 0; if ( src ) start = SDL_RWtell(src); if(xpm) xpmlines = &xpm; line = get_next_line(xpmlines, src, 0); if(!line) goto done; /* * The header string of an XPMv3 image has the format * * <width> <height> <ncolors> <cpp> [ <hotspot_x> <hotspot_y> ] * * where the hotspot coords are intended for mouse cursors. * Right now we don't use the hotspots but it should be handled * one day. */ if(SDL_sscanf(line, "%d %d %d %d", &w, &h, &ncolors, &cpp) != 4 || w <= 0 || h <= 0 || ncolors <= 0 || cpp <= 0) { error = "Invalid format description"; goto done; } keystrings = (char *)SDL_malloc(ncolors * cpp); if(!keystrings) { error = "Out of memory"; goto done; } nextkey = keystrings; /* Create the new surface */ if(ncolors <= 256) { indexed = 1; image = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, 8, 0, 0, 0, 0); im_colors = image->format->palette->colors; image->format->palette->ncolors = ncolors; } else { indexed = 0; image = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, 32, 0xff0000, 0x00ff00, 0x0000ff, 0); } if(!image) { /* Hmm, some SDL error (out of memory?) */ goto done; } /* Read the colors */ colors = create_colorhash(ncolors); if (!colors) { error = "Out of memory"; goto done; } for(index = 0; index < ncolors; ++index ) { char *p; line = get_next_line(xpmlines, src, 0); if(!line) goto done; p = line + cpp + 1; /* parse a colour definition */ for(;;) { char nametype; char *colname; Uint32 rgb, pixel; SKIPSPACE(p); if(!*p) { error = "colour parse error"; goto done; } nametype = *p; SKIPNONSPACE(p); SKIPSPACE(p); colname = p; SKIPNONSPACE(p); if(nametype == 's') continue; /* skip symbolic colour names */ if(!color_to_rgb(colname, p - colname, &rgb)) continue; SDL_memcpy(nextkey, line, cpp); if(indexed) { SDL_Color *c = im_colors + index; c->r = (Uint8)(rgb >> 16); c->g = (Uint8)(rgb >> 8); c->b = (Uint8)(rgb); pixel = index; } else pixel = rgb; add_colorhash(colors, nextkey, cpp, pixel); nextkey += cpp; if(rgb == 0xffffffff) SDL_SetColorKey(image, SDL_TRUE, pixel); break; } } /* Read the pixels */ pixels_len = w * cpp; dst = (Uint8 *)image->pixels; for(y = 0; y < h; y++) { line = get_next_line(xpmlines, src, pixels_len); if(indexed) { /* optimization for some common cases */ if(cpp == 1) for(x = 0; x < w; x++) dst[x] = (Uint8)QUICK_COLORHASH(colors, line + x); else for(x = 0; x < w; x++) dst[x] = (Uint8)get_colorhash(colors, line + x * cpp, cpp); } else { for (x = 0; x < w; x++) ((Uint32*)dst)[x] = get_colorhash(colors, line + x * cpp, cpp); } dst += image->pitch; } done: if(error) { if ( src ) SDL_RWseek(src, start, RW_SEEK_SET); if ( image ) { SDL_FreeSurface(image); image = NULL; } IMG_SetError(error); } if (keystrings) SDL_free(keystrings); free_colorhash(colors); if (linebuf) SDL_free(linebuf); return(image); } /* Load a XPM type image from an RWops datasource */ SDL_Surface *IMG_LoadXPM_RW(SDL_RWops *src) { if ( !src ) { /* The error message has been set in SDL_RWFromFile */ return NULL; } return load_xpm(NULL, src); } SDL_Surface *IMG_ReadXPMFromArray(char **xpm) { return load_xpm(xpm, NULL); } #else /* not LOAD_XPM */ /* See if an image is contained in a data source */ int IMG_isXPM(SDL_RWops *src) { return(0); } /* Load a XPM type image from an SDL datasource */ SDL_Surface *IMG_LoadXPM_RW(SDL_RWops *src) { return(NULL); } SDL_Surface *IMG_ReadXPMFromArray(char **xpm) { return NULL; } #endif /* not LOAD_XPM */
prophecy/Pillar
Dependencies/Include/cml/quaternion/quaternion_functions.h
<reponame>prophecy/Pillar<filename>Dependencies/Include/cml/quaternion/quaternion_functions.h /* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief Functions on quaternions. * * @todo The functions that return quaternions and vectors should be changed * to return quaternion expression nodes, as should the corresponding * class methods. */ #ifndef quaternion_functions_h #define quaternion_functions_h #include <cml/mathlib/checking.h> // For CheckQuat() #include <cml/mathlib/epsilon.h> #include <cml/util.h> // For acos_safe() namespace cml { /** Returns the real part of the quaternion. */ template<typename E, class AT, class OT, class CT> inline typename quaternion<E,AT,OT,CT>::value_type real(const quaternion<E,AT,OT,CT>& q) { return q.real(); } /** Returns the real (scalar) part of the QuaternionXpr. */ template<typename XprT> inline typename et::QuaternionXpr<XprT>::value_type real(const et::QuaternionXpr<XprT>& e) { return e.real(); } /** Returns the imaginary (vector) part of the quaternion. */ template<typename E, class AT, class OT, class CT> inline typename quaternion<E,AT,OT,CT>::imaginary_type imaginary(const quaternion<E,AT,OT,CT>& q) { return q.imaginary(); } /** Returns the imaginary (vector) part of the QuaternionXpr. */ template<typename XprT> //inline typename et::QuaternionXpr<XprT>::temporary_type inline typename et::QuaternionXpr<XprT>::imaginary_type imaginary(const et::QuaternionXpr<XprT>& e) { return e.imaginary(); } /** Cayley norm of a quaternion. */ template<typename E, class AT, class OT, class CT> inline typename quaternion<E,AT,OT,CT>::value_type norm(const quaternion<E,AT,OT,CT>& arg) { return arg.length_squared(); } /** Cayley norm of a QuaternionXpr. */ template<typename XprT> inline typename XprT::value_type norm(QUATXPR_ARG_TYPE arg) { return arg.length_squared(); } /** Squared length of a quaternion. */ template<typename E, class AT, class OT, class CT> inline typename quaternion<E,AT,OT,CT>::value_type length_squared(const quaternion<E,AT,OT,CT>& arg) { return arg.length_squared(); } /** Squared length of a quaternion expr. */ template<typename XprT> inline typename XprT::value_type length_squared(QUATXPR_ARG_TYPE arg) { return arg.length_squared(); } /** Length of a quaternion. */ template<typename E, class AT, class OT, class CT> inline typename quaternion<E,AT,OT,CT>::value_type length(const quaternion<E,AT,OT,CT>& arg) { return arg.length(); } /** Length of a quaternion expr. */ template<typename XprT> inline typename XprT::value_type length(QUATXPR_ARG_TYPE arg) { return arg.length(); } /** Normalize a quaternion. * * The input quaternion is not changed. */ template<typename E, class AT, class OT, class CT> inline quaternion<E,AT,OT,CT> normalize(const quaternion<E,AT,OT,CT>& arg) { typename quaternion<E,AT,OT,CT>::temporary_type result(arg); result.normalize(); return result; } /** Normalize a quaternion expr. */ template<typename XprT> inline typename XprT::temporary_type normalize(QUATXPR_ARG_TYPE arg) { return arg.normalize(); } /** Set a quaternion to the multiplicative identity. * * The input quaternion is not changed. */ template<typename E, class AT, class OT, class CT> inline quaternion<E,AT,OT,CT> identity(const quaternion<E,AT,OT,CT>& arg) { typename quaternion<E,AT,OT,CT>::temporary_type result(arg); result.identity(); return result; } /** Log of a quaternion or quaternion expression. */ template < class QuatT > typename QuatT::temporary_type log( const QuatT& q, typename QuatT::value_type tolerance = epsilon<typename QuatT::value_type>::placeholder()) { detail::CheckQuat(q); return q.log(); } /** Exponential function of a quaternion or quaternion expression. */ template < class QuatT > typename QuatT::temporary_type exp( const QuatT& q, typename QuatT::value_type tolerance = epsilon<typename QuatT::value_type>::placeholder()) { detail::CheckQuat(q); return q.exp(); } } // namespace cml #endif // ------------------------------------------------------------------------- // vim:ft=cpp
prophecy/Pillar
Dependencies/Include/cml/mathlib/misc.h
/* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief */ #ifndef misc_h #define misc_h #include <cml/mathlib/checking.h> /* A few miscellaneous functions and helper classes. * * @note: This is somewhat ad-hoc and will probably all be replaced in a future * version of the CML (I don't think I even bothered to document these functions * on the website). */ namespace cml { ////////////////////////////////////////////////////////////////////////////// // N-d functions ////////////////////////////////////////////////////////////////////////////// /** Return an N-d zero vector */ template < size_t N > vector< double, fixed<N> > zero() { typedef vector< double, fixed<N> > vector_type; vector_type result; result.zero(); return result; } /** Return an N-d cardinal axis by index */ template < size_t N > vector< double, fixed<N> > axis(size_t i) { /* Checking */ detail::CheckValidArg(i < N); typedef vector< double, fixed<N> > vector_type; vector_type result; result.cardinal(i); return result; } /** Return an NxM zero matrix */ template < size_t N, size_t M > matrix< double, fixed<N,M>, row_basis, row_major > zero() { typedef matrix< double, fixed<N,M>, row_basis, row_major > matrix_type; matrix_type result; result.zero(); return result; } /** Return an NxN identity matrix */ template < size_t N > matrix< double, fixed<N,N>, row_basis, row_major > identity() { typedef matrix< double, fixed<N,N>, row_basis, row_major > matrix_type; matrix_type result; result.identity(); return result; } /** Return an NxM identity transform */ template < size_t N, size_t M > matrix< double, fixed<N,M>, row_basis, row_major > identity_transform() { typedef matrix< double, fixed<N,M>, row_basis, row_major > matrix_type; matrix_type result; identity_transform(result); return result; } ////////////////////////////////////////////////////////////////////////////// // Zero vector ////////////////////////////////////////////////////////////////////////////// /** Return the 2D zero vector */ inline vector< double, fixed<2> > zero_2D() { return zero<2>(); } /** Return the 3D zero vector */ inline vector< double, fixed<3> > zero_3D() { return zero<3>(); } /** Return the 4D zero vector */ inline vector< double, fixed<4> > zero_4D() { return zero<4>(); } ////////////////////////////////////////////////////////////////////////////// // Cardinal axis ////////////////////////////////////////////////////////////////////////////// /** Return a 2D cardinal axis by index */ inline vector< double, fixed<2> > axis_2D(size_t i) { return axis<2>(i); } /** Return a 3D cardinal axis by index */ inline vector< double, fixed<3> > axis_3D(size_t i) { return axis<3>(i); } /** Return a the 2D x cardinal axis */ inline vector< double, fixed<2> > x_axis_2D() { return axis_2D(0); } /** Return a the 2D y cardinal axis */ inline vector< double, fixed<2> > y_axis_2D() { return axis_2D(1); } /** Return a the 3D x cardinal axis */ inline vector< double, fixed<3> > x_axis_3D() { return axis_3D(0); } /** Return a the 3D y cardinal axis */ inline vector< double, fixed<3> > y_axis_3D() { return axis_3D(1); } /** Return a the 3D z cardinal axis */ inline vector< double, fixed<3> > z_axis_3D() { return axis_3D(2); } ////////////////////////////////////////////////////////////////////////////// // Zero matrix ////////////////////////////////////////////////////////////////////////////// /** Return the 2x2 zero matrix */ inline matrix< double, fixed<2,2>, row_basis, row_major > zero_2x2() { return zero<2,2>(); } /** Return the 3x3 zero matrix */ inline matrix< double, fixed<3,3>, row_basis, row_major > zero_3x3() { return zero<3,3>(); } /** Return the 4x4 zero matrix */ inline matrix< double, fixed<4,4>, row_basis, row_major > zero_4x4() { return zero<4,4>(); } ////////////////////////////////////////////////////////////////////////////// // Identity matrix ////////////////////////////////////////////////////////////////////////////// /** Return the 2x2 identity matrix */ inline matrix< double, fixed<2,2>, row_basis, row_major > identity_2x2() { return identity<2>(); } /** Return the 3x3 identity matrix */ inline matrix< double, fixed<3,3>, row_basis, row_major > identity_3x3() { return identity<3>(); } /** Return the 4x4 identity matrix */ inline matrix< double, fixed<4,4>, row_basis, row_major > identity_4x4() { return identity<4>(); } ////////////////////////////////////////////////////////////////////////////// // Identity transform matrix ////////////////////////////////////////////////////////////////////////////// /** Return a 3x2 identity transform */ inline matrix< double,fixed<3,2>,row_basis,row_major > identity_transform_3x2() { return identity_transform<3,2>(); } /** Return a 2x3 identity transform */ inline matrix< double,fixed<2,3>,col_basis,col_major > identity_transform_2x3() { return identity_transform<2,3>(); } /** Return a 4x3 identity transform */ inline matrix< double,fixed<4,3>,row_basis,row_major > identity_transform_4x3() { return identity_transform<4,3>(); } /** Return a 3x4 identity transform */ inline matrix< double,fixed<3,4>,col_basis,col_major > identity_transform_3x4() { return identity_transform<3,4>(); } } // namespace cml #endif
prophecy/Pillar
Dependencies/Include/cml/quaternion/conjugate.h
/* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief Defines an operator for quaternion conjugation. */ #ifndef conjugate_h #define conjugate_h #include <cml/quaternion/quaternion_expr.h> namespace cml { namespace et { /** An expression node for conjugating a quaternion. */ template<class ExprT> class ConjugateOp { public: typedef ConjugateOp<ExprT> expr_type; /* Record ary-ness of the expression: */ typedef unary_expression expr_ary; /* Copy the expression by value into higher-up expressions: */ typedef expr_type expr_const_reference; typedef typename ExprT::value_type value_type; typedef quaternion_result_tag result_tag; typedef typename ExprT::size_tag size_tag; /* Store the expression traits for the subexpression: */ typedef ExprTraits<ExprT> expr_traits; /* Reference type for the subexpression: */ typedef typename expr_traits::const_reference expr_reference; /* Get the result type (same as for subexpression): */ typedef typename expr_traits::result_type result_type; /* For matching by assignability: */ typedef cml::et::not_assignable_tag assignable_tag; /* Get the temporary type: */ typedef typename result_type::temporary_type temporary_type; /* Get the vector type: */ typedef typename result_type::vector_type vector_type; /* Get the imaginary part type: */ typedef typename vector_type::subvector_type imaginary_type; /* Record the order type: */ typedef typename result_type::order_type order_type; public: /** Record result size as an enum. */ enum { array_size = ExprT::array_size }; /** Localize the ordering as an enum. */ enum { W = order_type::W, X = order_type::X, Y = order_type::Y, Z = order_type::Z }; public: /** Return the real part of the expression. */ value_type real() const { return m_expr.real(); } /** Return the vector part of the expression. */ imaginary_type imaginary() const { return -m_expr.imaginary(); } /** Return the Cayley norm of the expression. */ value_type norm() const { return length_squared(); } /** Return square of the quaternion length. */ value_type length_squared() const { return dot( QuaternionXpr<expr_type>(*this), QuaternionXpr<expr_type>(*this)); } /** Return the quaternion length. */ value_type length() const { return std::sqrt(length_squared()); } /** Return the result as a normalized quaternion. */ temporary_type normalize() const { temporary_type q(QuaternionXpr<expr_type>(*this)); return q.normalize(); } /** Compute conjugated result at index i. * * The conjugate of quaternion s + v is s - v. */ value_type operator[](size_t i) const { return (i == W) ? m_expr[W] : - m_expr[i] ; } public: /** Return size of this expression (same as argument's size). */ size_t size() const { return m_expr.size(); } /** Return reference to contained expression. */ expr_reference expression() const { return m_expr; } public: /** Construct from the subexpression. */ explicit ConjugateOp(expr_reference expr) : m_expr(expr) {} /** Copy constructor. */ ConjugateOp(const expr_type& e) : m_expr(e.m_expr) {} protected: expr_reference m_expr; private: /* Cannot be assigned to: */ expr_type& operator=(const expr_type&); }; /** Expression traits class for ConjugateOp<>. */ template<class ExprT> struct ExprTraits< ConjugateOp<ExprT> > { typedef ConjugateOp<ExprT> expr_type; typedef ExprT arg_type; typedef typename expr_type::value_type value_type; typedef typename expr_type::expr_const_reference const_reference; typedef typename expr_type::result_tag result_tag; typedef typename expr_type::size_tag size_tag; typedef typename expr_type::result_type result_type; typedef typename expr_type::assignable_tag assignable_tag; typedef expr_node_tag node_tag; value_type get(const expr_type& v, size_t i) const { return v[i]; } size_t size(const expr_type& e) const { return e.size(); } }; } // namespace et /** Conjugation of a quaternion. */ template<typename E, class AT, class OT, class CT> inline et::QuaternionXpr< et::ConjugateOp< quaternion<E,AT,OT,CT> > > conjugate(const quaternion<E,AT,OT,CT>& arg) { typedef et::ConjugateOp< quaternion<E,AT,OT,CT> > ExprT; return et::QuaternionXpr<ExprT>(ExprT(arg)); } /** Conjugation of a QuaternionXpr. */ template<class XprT> inline et::QuaternionXpr< et::ConjugateOp<XprT> > conjugate(QUATXPR_ARG_TYPE arg) { typedef et::ConjugateOp<XprT> ExprT; return et::QuaternionXpr<ExprT>(ExprT(arg.expression())); } } // namespace cml #endif // ------------------------------------------------------------------------- // vim:ft=cpp
prophecy/Pillar
Dependencies/Include/cml/util.h
<gh_stars>10-100 /* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief */ #ifndef cml_util_h #define cml_util_h #include <algorithm> // For std::min and std::max. #include <cstdlib> // For std::rand. #include <cml/constants.h> #if defined(_MSC_VER) #pragma push_macro("min") #pragma push_macro("max") #undef min #undef max #endif namespace cml { /** Sign of input value as double. */ template < typename T > double sign(T value) { return value < T(0) ? -1.0 : (value > T(0) ? 1.0 : 0.0); } /** Clamp input value to the range [min, max]. */ template < typename T > T clamp(T value, T min, T max) { return std::max(std::min(value, max), min); } /** Test input value for inclusion in [min, max]. */ template < typename T > bool in_range(T value, T min, T max) { return !(value < min) && !(value > max); } /** Map input value from [min1, max1] to [min2, max2]. */ template < typename T > T map_range(T value, T min1, T max1, T min2, T max2) { return min2 + ((value - min1) / (max1 - min1)) * (max2 - min2); } /** Wrap std::acos() and clamp argument to [-1, 1]. */ template < typename T > T acos_safe(T theta) { return T(std::acos(clamp(theta, T(-1.0), T(1.0)))); } /** Wrap std::asin() and clamp argument to [-1, 1]. */ template < typename T > T asin_safe(T theta) { return T(std::asin(clamp(theta, T(-1.0), T(1.0)))); } /** Wrap std::sqrt() and clamp argument to [0, inf). */ template < typename T > T sqrt_safe(T value) { return T(std::sqrt(std::max(value, T(0.0)))); } /** Square a value. */ template < typename T > T sqr(T value) { return value * value; } /** Cube a value. */ template < typename T > T cub(T value) { return value * value * value; } /** Inverse square root. */ template < typename T > T inv_sqrt(T value) { return T(1.0 / std::sqrt(value)); } /* The next few functions deal with indexing. next() and prev() are useful * for operations involving the vertices of a polygon or other cyclic set, * and cyclic_permutation() is used by various functions that deal with * axes or basis vectors in a generic way. As these functions are only * relevant for unsigned integer types, I've just used size_t, but there * may be reasons I haven't thought of that they should be templated. */ /** Return next, with cycling, in a series of N non-negative integers. */ inline size_t next(size_t i, size_t N) { return (i + 1) % N; } /** Return previous, with cycling, in a series of N non-negative integers. */ inline size_t prev(size_t i, size_t N) { return i ? (i - 1) : (N - 1); } /** Cyclic permutation of the set { 0, 1 }, starting with 'first'. */ inline void cyclic_permutation(size_t first, size_t& i, size_t& j) { i = first; j = next(i, 2); } /** Cyclic permutation of the set { 0, 1, 2 }, starting with 'first'. */ inline void cyclic_permutation(size_t first, size_t& i, size_t& j, size_t& k) { i = first; j = next(i, 3); k = next(j, 3); } /** Cyclic permutation of the set { 0, 1, 2, 3 }, starting with 'first'. */ inline void cyclic_permutation( size_t first, size_t& i, size_t& j, size_t& k, size_t& l) { i = first; j = next(i, 4); k = next(j, 4); l = next(k, 4); } /** Convert radians to degrees. */ template < typename T > T deg(T theta) { return theta * constants<T>::deg_per_rad(); } /** Convert degrees to radians. */ template < typename T > T rad(T theta) { return theta * constants<T>::rad_per_deg(); } /* Note: Moving interpolation functions to interpolation.h */ #if 0 /** Linear interpolation of 2 values. * * @note The data points are assumed to be sampled at u = 0 and u = 1, so * for interpolation u must lie between 0 and 1. */ template <typename T, typename Scalar> T lerp(const T& f0, const T& f1, Scalar u) { return (Scalar(1.0) - u) * f0 + u * f1; } #endif #if 0 /** Bilinear interpolation of 4 values. * * @note The data points are assumed to be sampled at the corners of a unit * square, so for interpolation u and v must lie between 0 and 1, */ template <typename T, typename Scalar> T bilerp(const T& f00, const T& f10, const T& f01, const T& f11, Scalar u, Scalar v) { Scalar uv = u * v; return ( (Scalar(1.0) - u - v + uv) * f00 + (u - uv) * f10 + (v - uv) * f01 + uv * f11 ); } #endif #if 0 /** Trilinear interpolation of 8 values. * * @note The data values are assumed to be sampled at the corners of a unit * cube, so for interpolation, u, v, and w must lie between 0 and 1. */ template <typename T, typename Scalar> T trilerp(const T& f000, const T& f100, const T& f010, const T& f110, const T& f001, const T& f101, const T& f011, const T& f111, Scalar u, Scalar v, Scalar w) { Scalar uv = u * v; Scalar vw = v * w; Scalar wu = w * u; Scalar uvw = uv * w; return ( (Scalar(1.0) - u - v - w + uv + vw + wu - uvw) * f000 + (u - uv - wu + uvw) * f100 + (v - uv - vw + uvw) * f010 + (uv - uvw) * f110 + (w - vw - wu + uvw) * f001 + (wu - uvw) * f101 + (vw - uvw) * f011 + uvw * f111 ); } #endif /** Random binary (0,1) value. */ inline size_t random_binary() { return std::rand() % 2; } /** Random polar (-1,1) value. */ inline int random_polar() { return random_binary() ? 1 : -1; } /** Random real in [0,1]. */ inline double random_unit() { return double(std::rand()) / double(RAND_MAX); } /* Random integer in the range [min, max] */ inline long random_integer(long min, long max) { return min + std::rand() % (max - min + 1); } /* Random real number in the range [min, max] */ template < typename T > T random_real(T min, T max) { return min + random_unit() * (max - min); } /** Squared length in R2. */ template < typename T > T length_squared(T x, T y) { return x * x + y * y; } /** Squared length in R3. */ template < typename T > T length_squared(T x, T y, T z) { return x * x + y * y + z * z; } /** Length in R2. */ template < typename T > T length(T x, T y) { return std::sqrt(length_squared(x,y)); } /** Length in R3. */ template < typename T > T length(T x, T y, T z) { return std::sqrt(length_squared(x,y,z)); } /** Index of maximum of 2 values. */ template < typename T > size_t index_of_max(T a, T b) { return a > b ? 0 : 1; } /** Index of maximum of 2 values by magnitude. */ template < typename T > size_t index_of_max_abs(T a, T b) { return index_of_max(std::fabs(a),std::fabs(b)); } /** Index of minimum of 2 values. */ template < typename T > size_t index_of_min(T a, T b) { return a < b ? 0 : 1; } /** Index of minimum of 2 values by magnitude. */ template < typename T > size_t index_of_min_abs(T a, T b) { return index_of_min(std::fabs(a),std::fabs(b)); } /** Index of maximum of 3 values. */ template < typename T > size_t index_of_max(T a, T b, T c) { return a > b ? (c > a ? 2 : 0) : (b > c ? 1 : 2); } /** Index of maximum of 3 values by magnitude. */ template < typename T > size_t index_of_max_abs(T a, T b, T c) { return index_of_max(std::fabs(a),std::fabs(b),std::fabs(c)); } /** Index of minimum of 3 values. */ template < typename T > size_t index_of_min(T a, T b, T c) { return a < b ? (c < a ? 2 : 0) : (b < c ? 1 : 2); } /** Index of minimum of 3 values by magnitude. */ template < typename T > size_t index_of_min_abs(T a, T b, T c) { return index_of_min(std::fabs(a),std::fabs(b),std::fabs(c)); } /** Wrap input value to the range [min,max]. */ template < typename T > T wrap(T value, T min, T max) { max -= min; value = std::fmod(value - min, max); if (value < T(0)) { value += max; } return min + value; } /** Convert horizontal field of view to vertical field of view. */ template < typename T > T xfov_to_yfov(T xfov, T aspect) { return T(2.0 * std::atan(std::tan(xfov * T(.5)) / double(aspect))); } /** Convert vertical field of view to horizontal field of view. */ template < typename T > T yfov_to_xfov(T yfov, T aspect) { return T(2.0 * std::atan(std::tan(yfov * T(.5)) * double(aspect))); } /** Convert horizontal zoom to vertical zoom. */ template < typename T > T xzoom_to_yzoom(T xzoom, T aspect) { return xzoom * aspect; } /** Convert vertical zoom to horizontal zoom. */ template < typename T > T yzoom_to_xzoom(T yzoom, T aspect) { return yzoom / aspect; } /** Convert zoom factor to field of view. */ template < typename T > T zoom_to_fov(T zoom) { return T(2) * T(std::atan(T(1) / zoom)); } /** Convert field of view to zoom factor. */ template < typename T > T fov_to_zoom(T fov) { return T(1) / T(std::tan(fov * T(.5))); } } // namespace cml #if defined(_MSC_VER) #pragma pop_macro("min") #pragma pop_macro("max") #endif #endif // ------------------------------------------------------------------------- // vim:ft=cpp
prophecy/Pillar
Dependencies/Include/cml/matrix/inverse.h
/* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief Compute the inverse of a matrix by LU factorization. */ #ifndef matrix_inverse_h #define matrix_inverse_h #include <vector> #include <cml/matrix/lu.h> namespace cml { namespace detail { /* Need to use a functional, since template functions cannot be * specialized. _tag is used to specialize based upon dimension: */ template<typename MatT, int _tag> struct inverse_f; /* @todo: Reciprocal optimization for division by determinant. */ /* 2x2 inverse. Despite being marked for fixed_size matrices, this can * be used for dynamic-sized ones also: */ template<typename MatT> struct inverse_f<MatT,2> { typename MatT::temporary_type operator()(const MatT& M) const { typedef typename MatT::temporary_type temporary_type; typedef typename temporary_type::value_type value_type; /* Matrix containing the inverse: */ temporary_type Z; cml::et::detail::Resize(Z,2,2); /* Compute determinant and inverse: */ value_type D = value_type(1) / (M(0,0)*M(1,1) - M(0,1)*M(1,0)); Z(0,0) = M(1,1)*D; Z(0,1) = - M(0,1)*D; Z(1,0) = - M(1,0)*D; Z(1,1) = M(0,0)*D; return Z; } }; /* 3x3 inverse. Despite being marked for fixed_size matrices, this can * be used for dynamic-sized ones also: */ template<typename MatT> struct inverse_f<MatT,3> { /* [00 01 02] * M = [10 11 12] * [20 21 22] */ typename MatT::temporary_type operator()(const MatT& M) const { /* Shorthand. */ typedef typename MatT::value_type value_type; /* Compute cofactors for each entry: */ value_type m_00 = M(1,1)*M(2,2) - M(1,2)*M(2,1); value_type m_01 = M(1,2)*M(2,0) - M(1,0)*M(2,2); value_type m_02 = M(1,0)*M(2,1) - M(1,1)*M(2,0); value_type m_10 = M(0,2)*M(2,1) - M(0,1)*M(2,2); value_type m_11 = M(0,0)*M(2,2) - M(0,2)*M(2,0); value_type m_12 = M(0,1)*M(2,0) - M(0,0)*M(2,1); value_type m_20 = M(0,1)*M(1,2) - M(0,2)*M(1,1); value_type m_21 = M(0,2)*M(1,0) - M(0,0)*M(1,2); value_type m_22 = M(0,0)*M(1,1) - M(0,1)*M(1,0); /* Compute determinant from the minors: */ value_type D = value_type(1) / (M(0,0)*m_00 + M(0,1)*m_01 + M(0,2)*m_02); /* Matrix containing the inverse: */ typename MatT::temporary_type Z; cml::et::detail::Resize(Z,3,3); /* Assign the inverse as (1/D) * (cofactor matrix)^T: */ Z(0,0) = m_00*D; Z(0,1) = m_10*D; Z(0,2) = m_20*D; Z(1,0) = m_01*D; Z(1,1) = m_11*D; Z(1,2) = m_21*D; Z(2,0) = m_02*D; Z(2,1) = m_12*D; Z(2,2) = m_22*D; return Z; } }; /* 4x4 inverse. Despite being marked for fixed_size matrices, this can * be used for dynamic-sized ones also: */ template<typename MatT> struct inverse_f<MatT,4> { /* [00 01 02 03] * M = [10 11 12 13] * [20 21 22 23] * [30 31 32 33] * * |11 12 13| |10 12 13| * C00 = |21 22 23| C01 = |20 22 23| * |31 32 33| |30 32 33| * * |10 11 13| |10 11 12| * C02 = |20 21 23| C03 = |20 21 22| * |30 31 33| |30 31 32| */ typename MatT::temporary_type operator()(const MatT& M) const { /* Shorthand. */ typedef typename MatT::value_type value_type; /* Common cofactors, rows 0,1: */ value_type m_22_33_23_32 = M(2,2)*M(3,3) - M(2,3)*M(3,2); value_type m_23_30_20_33 = M(2,3)*M(3,0) - M(2,0)*M(3,3); value_type m_20_31_21_30 = M(2,0)*M(3,1) - M(2,1)*M(3,0); value_type m_21_32_22_31 = M(2,1)*M(3,2) - M(2,2)*M(3,1); value_type m_23_31_21_33 = M(2,3)*M(3,1) - M(2,1)*M(3,3); value_type m_20_32_22_30 = M(2,0)*M(3,2) - M(2,2)*M(3,0); /* Compute minors: */ value_type d00 = M(1,1)*m_22_33_23_32+M(1,2)*m_23_31_21_33+M(1,3)*m_21_32_22_31; value_type d01 = M(1,0)*m_22_33_23_32+M(1,2)*m_23_30_20_33+M(1,3)*m_20_32_22_30; value_type d02 = M(1,0)*-m_23_31_21_33+M(1,1)*m_23_30_20_33+M(1,3)*m_20_31_21_30; value_type d03 = M(1,0)*m_21_32_22_31+M(1,1)*-m_20_32_22_30+M(1,2)*m_20_31_21_30; /* Compute minors: */ value_type d10 = M(0,1)*m_22_33_23_32+M(0,2)*m_23_31_21_33+M(0,3)*m_21_32_22_31; value_type d11 = M(0,0)*m_22_33_23_32+M(0,2)*m_23_30_20_33+M(0,3)*m_20_32_22_30; value_type d12 = M(0,0)*-m_23_31_21_33+M(0,1)*m_23_30_20_33+M(0,3)*m_20_31_21_30; value_type d13 = M(0,0)*m_21_32_22_31+M(0,1)*-m_20_32_22_30+M(0,2)*m_20_31_21_30; /* Common cofactors, rows 2,3: */ value_type m_02_13_03_12 = M(0,2)*M(1,3) - M(0,3)*M(1,2); value_type m_03_10_00_13 = M(0,3)*M(1,0) - M(0,0)*M(1,3); value_type m_00_11_01_10 = M(0,0)*M(1,1) - M(0,1)*M(1,0); value_type m_01_12_02_11 = M(0,1)*M(1,2) - M(0,2)*M(1,1); value_type m_03_11_01_13 = M(0,3)*M(1,1) - M(0,1)*M(1,3); value_type m_00_12_02_10 = M(0,0)*M(1,2) - M(0,2)*M(1,0); /* Compute minors (uses row 3 as the multipliers instead of row 0, * which uses the same signs as row 0): */ value_type d20 = M(3,1)*m_02_13_03_12+M(3,2)*m_03_11_01_13+M(3,3)*m_01_12_02_11; value_type d21 = M(3,0)*m_02_13_03_12+M(3,2)*m_03_10_00_13+M(3,3)*m_00_12_02_10; value_type d22 = M(3,0)*-m_03_11_01_13+M(3,1)*m_03_10_00_13+M(3,3)*m_00_11_01_10; value_type d23 = M(3,0)*m_01_12_02_11+M(3,1)*-m_00_12_02_10+M(3,2)*m_00_11_01_10; /* Compute minors: */ value_type d30 = M(2,1)*m_02_13_03_12+M(2,2)*m_03_11_01_13+M(2,3)*m_01_12_02_11; value_type d31 = M(2,0)*m_02_13_03_12+M(2,2)*m_03_10_00_13+M(2,3)*m_00_12_02_10; value_type d32 = M(2,0)*-m_03_11_01_13+M(2,1)*m_03_10_00_13+M(2,3)*m_00_11_01_10; value_type d33 = M(2,0)*m_01_12_02_11+M(2,1)*-m_00_12_02_10+M(2,2)*m_00_11_01_10; /* Finally, compute determinant from the minors, and assign the * inverse as (1/D) * (cofactor matrix)^T: */ typename MatT::temporary_type Z; cml::et::detail::Resize(Z,4,4); value_type D = value_type(1) / (M(0,0)*d00 - M(0,1)*d01 + M(0,2)*d02 - M(0,3)*d03); Z(0,0) = +d00*D; Z(0,1) = -d10*D; Z(0,2) = +d20*D; Z(0,3) = -d30*D; Z(1,0) = -d01*D; Z(1,1) = +d11*D; Z(1,2) = -d21*D; Z(1,3) = +d31*D; Z(2,0) = +d02*D; Z(2,1) = -d12*D; Z(2,2) = +d22*D; Z(2,3) = -d32*D; Z(3,0) = -d03*D; Z(3,1) = +d13*D; Z(3,2) = -d23*D; Z(3,3) = +d33*D; return Z; } }; /* If more extensive general linear algebra functionality is offered in * future versions it may be useful to make the elementary row and column * operations separate functions. For now they're simply performed in place, * but the commented-out lines of code show where the calls to these functions * should go if and when they become available. */ /* @todo: In-place version, and address memory allocation for pivot vector. */ /* General NxN inverse by Gauss-Jordan elimination with full pivoting: */ template<typename MatT, int _tag> struct inverse_f { typename MatT::temporary_type operator()(const MatT& M) const { /* Shorthand. */ typedef typename MatT::value_type value_type; /* Size of matrix */ size_t N = M.rows(); /* Matrix containing the inverse: */ typename MatT::temporary_type Z; cml::et::detail::Resize(Z,N,N); Z = M; /* For tracking pivots */ std::vector<size_t> row_index(N); std::vector<size_t> col_index(N); std::vector<size_t> pivoted(N,0); /* For each column */ for (size_t i = 0; i < N; ++i) { /* Find the pivot */ size_t row = 0, col = 0; value_type max = value_type(0); for (size_t j = 0; j < N; ++j) { if (!pivoted[j]) { for (size_t k = 0; k < N; ++k) { if (!pivoted[k]) { value_type mag = std::fabs(Z(j,k)); if (mag > max) { max = mag; row = j; col = k; } } } } } /* TODO: Check max against epsilon here to catch singularity */ row_index[i] = row; col_index[i] = col; /* Swap rows if necessary */ if (row != col) { /*Z.row_op_swap(row,col);*/ for (size_t j = 0; j < Z.cols(); ++j) { std::swap(Z(row,j),Z(col,j)); } } /* Process pivot row */ pivoted[col] = true; value_type pivot = Z(col,col); Z(col,col) = value_type(1); /*Z.row_op_mult(col,value_type(1)/pivot);*/ value_type k = value_type(1)/pivot; for (size_t j = 0; j < Z.cols(); ++j) { Z(col,j) *= k; } /* Process other rows */ for (size_t j = 0; j < N; ++j) { if (j != col) { value_type mult = -Z(j,col); Z(j,col) = value_type(0); /*Z.row_op_add_mult(col,j,mult);*/ for (size_t k = 0; k < Z.cols(); ++k) { Z(j,k) += mult * Z(col,k); } } } } /* Swap columns if necessary */ for (int i = N-1; i >= 0; --i) { if (row_index[i] != col_index[i]) { /*Z.col_op_swap(row_index[i],col_index[i]);*/ for (size_t j = 0; j < Z.rows(); ++j) { std::swap(Z(j,row_index[i]),Z(j,col_index[i])); } } } /* Return result */ return Z; } }; /* Inversion by LU factorization is turned off for now due to lack of * pivoting in the implementation, but we may switch back to it at some future * time. */ #if 0 /* General NxN inverse by LU factorization: */ template<typename MatT, int _tag> struct inverse_f { typename MatT::temporary_type operator()(const MatT& M) const { /* Shorthand. */ typedef typename MatT::value_type value_type; /* Compute LU factorization: */ size_t N = M.rows(); typename MatT::temporary_type LU; cml::et::detail::Resize(LU,N,N); LU = lu(M); /* Matrix containing the inverse: */ typename MatT::temporary_type Z; cml::et::detail::Resize(Z,N,N); typename MatT::col_vector_type v, x; cml::et::detail::Resize(v,N); cml::et::detail::Resize(x,N); for(size_t i = 0; i < N; ++i) v[i] = value_type(0); /* XXX Need a fill() function here. */ /* Use lu_solve to solve M*x = v for x, where v = [0 ... 1 ... 0]^T: */ for(size_t i = 0; i < N; ++i) { v[i] = 1.; x = lu_solve(LU,v); /* x is column i of the inverse of LU: */ for(size_t k = 0; k < N; ++ k) { Z(k,i) = x[k]; } v[i] = 0.; } return Z; } }; #endif /* Note: force_NxN is for checking general NxN inversion against the special- * case 2x2, 3x3 and 4x4 code. I'm leaving it in for now since we may need to * test the NxN code further if the implementation changes. At some future * time when the implementation is stable, everything related to force_NxN can * be taken out. */ /* Note: Commenting the force_NxN stuff out, but leaving the code here in * case we need to do more testing in the future. */ /* Generator for the inverse functional for fixed-size matrices: */ template<typename MatT> typename MatT::temporary_type inverse(const MatT& M, fixed_size_tag/*, bool force_NxN*/) { /* Require a square matrix: */ cml::et::CheckedSquare(M, fixed_size_tag()); /* if (force_NxN) { return inverse_f<MatT,0>()(M); } else { */ return inverse_f<MatT,MatT::array_rows>()(M); /* } */ } /* Generator for the inverse functional for dynamic-size matrices: */ template<typename MatT> typename MatT::temporary_type inverse(const MatT& M, dynamic_size_tag/*, bool force_NxN*/) { /* Require a square matrix: */ cml::et::CheckedSquare(M, dynamic_size_tag()); /* if (force_NxN) { return inverse_f<MatT,0>()(M); } else { */ /* Dispatch based upon the matrix dimension: */ switch(M.rows()) { case 2: return inverse_f<MatT,2>()(M); // 2x2 case 3: return inverse_f<MatT,3>()(M); // 3x3 case 4: return inverse_f<MatT,4>()(M); // 4x4 default: return inverse_f<MatT,0>()(M); // > 4x4 (or 1x1) } /* } */ } } // namespace detail /** Inverse of a matrix. */ template<typename E, class AT, typename BO, typename L> inline typename matrix<E,AT,BO,L>::temporary_type inverse(const matrix<E,AT,BO,L>& M/*, bool force_NxN = false*/) { typedef typename matrix<E,AT,BO,L>::size_tag size_tag; return detail::inverse(M,size_tag()/*,force_NxN*/); } /** Inverse of a matrix expression. */ template<typename XprT> inline typename et::MatrixXpr<XprT>::temporary_type inverse(const et::MatrixXpr<XprT>& e/*, bool force_NxN = false*/) { typedef typename et::MatrixXpr<XprT>::size_tag size_tag; return detail::inverse(e,size_tag()/*,force_NxN*/); } } // namespace cml #endif // ------------------------------------------------------------------------- // vim:ft=cpp
prophecy/Pillar
Dependencies/Include/Rocket/Core/FontDatabase.h
<reponame>prophecy/Pillar /* * This source file is part of libRocket, the HTML/CSS Interface Middleware * * For the latest information, see http://www.librocket.com * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #ifndef ROCKETCOREFONTDATABASE_H #define ROCKETCOREFONTDATABASE_H #include "StringUtilities.h" #include "Header.h" #include "Font.h" namespace Rocket { namespace Core { class FontEffect; class FontFamily; class FontFaceHandle; class PropertyDictionary; /** The font database contains all font families currently in use by Rocket. @author <NAME> */ class ROCKETCORE_API FontDatabase { public: static bool Initialise(); static void Shutdown(); /// Adds a new font face to the database. The face's family, style and weight will be determined from the face itself. /// @param[in] file_name The file to load the face from. /// @return True if the face was loaded successfully, false otherwise. static bool LoadFontFace(const String& file_name); /// Adds a new font face to the database, ignoring any family, style and weight information stored in the face itself. /// @param[in] file_name The file to load the face from. /// @param[in] family The family to add the face to. /// @param[in] style The style of the face (normal or italic). /// @param[in] weight The weight of the face (normal or bold). /// @return True if the face was loaded successfully, false otherwise. static bool LoadFontFace(const String& file_name, const String& family, Font::Style style, Font::Weight weight); /// Adds a new font face to the database, loading from memory. The face's family, style and weight will be determined from the face itself. /// @param[in] data The font data. /// @param[in] data_length Length of the data. /// @return True if the face was loaded successfully, false otherwise. static bool LoadFontFace(const byte* data, int data_length); /// Adds a new font face to the database, loading from memory. /// @param[in] data The font data. /// @param[in] data_length Length of the data. /// @param[in] family The family to add the face to. /// @param[in] style The style of the face (normal or italic). /// @param[in] weight The weight of the face (normal or bold). /// @return True if the face was loaded successfully, false otherwise. static bool LoadFontFace(const byte* data, int data_length, const String& family, Font::Style style, Font::Weight weight); /// Returns a handle to a font face that can be used to position and render text. This will return the closest match /// it can find, but in the event a font family is requested that does not exist, NULL will be returned instead of a /// valid handle. /// @param[in] family The family of the desired font handle. /// @param[in] charset The set of characters required in the font face, as a comma-separated list of unicode ranges. /// @param[in] style The style of the desired font handle. /// @param[in] weight The weight of the desired font handle. /// @param[in] size The size of desired handle, in points. /// @return A valid handle if a matching (or closely matching) font face was found, NULL otherwise. static FontFaceHandle* GetFontFaceHandle(const String& family, const String& charset, Font::Style style, Font::Weight weight, int size); /// Returns a font effect, either a newly-instanced effect from the factory or an identical /// shared effect. /// @param[in] name The name of the desired font effect type. /// @param[in] properties The properties associated with the font effect. /// @return The requested font effect, or NULL if the font effect could not be found or instanced. static FontEffect* GetFontEffect(const String& name, const PropertyDictionary& properties); /// Removes a font effect from the font database's cache. /// @param[in] The effect to release. static void ReleaseFontEffect(const FontEffect* effect); private: FontDatabase(void); ~FontDatabase(void); // Adds a loaded face to the appropriate font family. bool AddFace(void* face, const String& family, Font::Style style, Font::Weight weight, bool release_stream); // Loads a FreeType face. void* LoadFace(const String& file_name); // Loads a FreeType face from memory. void* LoadFace(const byte* data, int data_length, const String& source, bool local_data); typedef std::map< String, FontFamily*, StringUtilities::StringComparei > FontFamilyMap; FontFamilyMap font_families; static FontDatabase* instance; }; } } #endif
prophecy/Pillar
Dependencies/Include/cml/core/meta/common.h
/* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief */ #ifndef core_meta_common_h #define core_meta_common_h namespace cml { /** Type of a true statement. */ struct true_type {}; /** Type of a false statement. */ struct false_type {}; template<bool B> struct is_true { typedef false_type result; }; template<> struct is_true<true> { typedef true_type result; }; /** A "type pair". */ template<typename T1, typename T2> struct type_pair { typedef T1 first; typedef T2 second; }; /** A "type quadruple". */ template<typename T1, typename T2, typename T3, typename T4> struct type_quad { typedef T1 first; typedef T2 second; typedef T3 third; typedef T3 fourth; }; /** Match any type (for use with same_type<> and select_switch<>). */ struct any_type {}; /** Determine if two types are the same. * * Defaults to false. */ template<typename T, typename U> struct same_type { typedef false_type result; enum { is_true = false, is_false = true }; }; /** Match the same type for both of same_type's template arguments. */ template<typename T> struct same_type<T,T> { typedef true_type result; enum { is_true = true, is_false = false }; }; /** Match a type and any_type. */ template<typename T> struct same_type<T,any_type> { typedef true_type result; enum { is_true = true, is_false = false }; }; /** Match a type and any_type. */ template<typename T> struct same_type<any_type,T> { typedef true_type result; enum { is_true = true, is_false = false }; }; /** Disambiguate pair of any_type's. */ template<> struct same_type<any_type,any_type> { typedef true_type result; enum { is_true = true, is_false = false }; }; /** Remove a reference qualifier from a type. */ template<typename T> struct remove_reference { template<typename Q, typename Dummy> struct helper { typedef Q type; }; template<typename Q> struct helper<Q&, void> { typedef Q type; }; template<typename Q> struct helper<const Q&, void> { typedef const Q type; }; typedef typename helper<T,void>::type type; }; /** Remove a const qualifier from a type. */ template<typename T> struct remove_const { template<typename Q, typename Dummy> struct helper { typedef Q type; }; template<typename Q> struct helper<const Q, void> { typedef Q type; }; typedef typename helper<T,void>::type type; }; } // namespace cml #endif // ------------------------------------------------------------------------- // vim:ft=cpp
prophecy/Pillar
Dependencies/Include/Rocket/Core/Python/ConverterScriptObject.h
/* * This source file is part of libRocket, the HTML/CSS Interface Middleware * * For the latest information, see http://www.librocket.com * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #ifndef ROCKETCOREPYTHONCONVERTERSCRIPTOBJECT_H #define ROCKETCOREPYTHONCONVERTERSCRIPTOBJECT_H #include "Python.h" namespace Rocket { namespace Core { namespace Python { /** Templated class for converting from a script object to a python object Simply construct this class in your application start up and it will do the necessary registration of the object with the boost type conversion repository. @author <NAME> */ template <typename T> struct ConverterScriptObject { ConverterScriptObject() { // Register custom RKTElement to python converter boost::python::to_python_converter< T*, ConverterScriptObject< T > >(); } static PyObject* convert(T* object) { PyObject* pyobject = Py_None; if (object) { PyObject* script_object = (PyObject*)object->GetScriptObject(); if (script_object) { pyobject = script_object; } } Py_INCREF(pyobject); return pyobject; } }; } } } #endif
prophecy/Pillar
Dependencies/Include/cml/et/size_checking.h
/* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief * * Define matrix and vector linear expression size-checking classes. */ #ifndef size_checking_h #define size_checking_h #include <stdexcept> #include <cml/core/cml_meta.h> #include <cml/core/cml_assert.h> #include <cml/core/fwd.h> #include <cml/et/traits.h> #if defined(_MSC_VER) && _MSC_VER < 1400 #pragma warning(push) #pragma warning(disable:4348) // XXX This is a terrible hack for VC7.1, and should really be fixed by // separating out the "impl" templates from GetCheckedSize. #endif /* This is used below to create a more meaningful compile-time error when * fixed-size vector arguments don't match at compile time: */ struct incompatible_expression_size_error; /* This is used below to create a more meaningful compile-time error when a * function is not provided with a square matrix or MatrixExpr argument: */ struct square_matrix_arg_expected_error; namespace cml { namespace et { namespace detail { } // namespace detail /* Forward declare for specialization below: */ template<typename LeftT, typename RightT, typename SizeT> struct GetCheckedSize; /* Checking for fixed-size expression: */ template<typename LeftT, typename RightT> struct GetCheckedSize<LeftT,RightT,fixed_size_tag> { /* Record argument traits: */ typedef ExprTraits<LeftT> left_traits; typedef ExprTraits<RightT> right_traits; /* Result types: */ typedef typename left_traits::result_tag left_result; typedef typename right_traits::result_tag right_result; /* For specialization below: */ template<typename LR, typename RR, class X = void> struct impl; /* Check for two matrices (linear operators only): */ template<class X> struct impl<matrix_result_tag,matrix_result_tag,X> { typedef matrix_size size_type; CML_STATIC_REQUIRE_M( (size_t)LeftT::array_rows == (size_t)RightT::array_rows && (size_t)LeftT::array_cols == (size_t)RightT::array_cols, incompatible_expression_size_error); /* Record the array size as a constant: */ enum { array_rows = LeftT::array_rows, array_cols = LeftT::array_cols }; /* Return the matrix size: */ size_type size() const { return size_type(array_rows,array_cols); } }; /* Check for a matrix and a vector: */ template<class X> struct impl<matrix_result_tag,vector_result_tag,X> { typedef size_t size_type; CML_STATIC_REQUIRE_M( (size_t)LeftT::array_cols == (size_t)RightT::array_size, incompatible_expression_size_error); /* Record the array size as a constant: */ enum { array_size = LeftT::array_rows }; /* Return the vector size: */ size_type size() const { return size_type(array_size); } }; /* Check for a vector and a matrix: */ template<class X> struct impl<vector_result_tag,matrix_result_tag,X> { typedef size_t size_type; CML_STATIC_REQUIRE_M( (size_t)LeftT::array_size == (size_t)RightT::array_rows, incompatible_expression_size_error); /* Record the array size as a constant: */ enum { array_size = RightT::array_cols }; /* Return the vector size: */ size_type size() const { return size_type(array_size); } }; /* Check for a matrix and a scalar: */ template<class X> struct impl<matrix_result_tag,scalar_result_tag,X> { typedef matrix_size size_type; /* Record the array size as a constant: */ enum { array_rows = LeftT::array_rows, array_cols = LeftT::array_cols }; /* Return the matrix size: */ size_type size() const { return size_type(array_rows,array_cols); } }; /* Check for a scalar and a matrix: */ template<class X> struct impl<scalar_result_tag,matrix_result_tag,X> { typedef matrix_size size_type; /* Record the array size as a constant: */ enum { array_rows = RightT::array_rows, array_cols = RightT::array_cols }; /* Return the matrix size: */ size_type size() const { return size_type(array_rows,array_cols); } }; /* Check for two vectors: */ template<class X> struct impl<vector_result_tag,vector_result_tag,X> { typedef size_t size_type; CML_STATIC_REQUIRE_M( (size_t)LeftT::array_size == (size_t)RightT::array_size, incompatible_expression_size_error); /* Record the array size as a constant: */ enum { array_size = LeftT::array_size }; /* Return the vector size: */ size_type size() const { return size_type(array_size); } }; /* Check for a vector and a scalar: */ template<class X> struct impl<vector_result_tag,scalar_result_tag,X> { typedef size_t size_type; /* Record the array size as a constant: */ enum { array_size = LeftT::array_size }; /* Return the vector size: */ size_type size() const { return size_type(array_size); } }; /* Check for a scalar and a vector: */ template<class X> struct impl<scalar_result_tag,vector_result_tag,X> { typedef size_t size_type; /* Record the array size as a constant: */ enum { array_size = RightT::array_size }; /* Return the vector size: */ size_type size() const { return size_type(array_size); } }; /* Check for two quaternions: */ template<class X> struct impl<quaternion_result_tag,quaternion_result_tag,X> { typedef size_t size_type; /* Record the quaternion size as a constant: */ enum { array_size = 4 }; /* Return the quaternion size: */ size_type size() const { return size_type(array_size); } }; /* Check for a quaternion and a vector: */ template<class X> struct impl<quaternion_result_tag,vector_result_tag,X> { typedef size_t size_type; CML_STATIC_REQUIRE_M( RightT::array_size == 4, incompatible_expression_size_error); /* Record the quaternion size as a constant: */ enum { array_size = 4 }; /* Return the quaternion size: */ size_type size() const { return size_type(array_size); } }; /* Check for a vector and a quaternion: */ template<class X> struct impl<vector_result_tag,quaternion_result_tag,X> { typedef size_t size_type; CML_STATIC_REQUIRE_M( LeftT::array_size == 4, incompatible_expression_size_error); /* Record the quaternion size as a constant: */ enum { array_size = 4 }; /* Return the quaternion size: */ size_type size() const { return size_type(array_size); } }; /* Check for a quaternion and a scalar: */ template<class X> struct impl<quaternion_result_tag,scalar_result_tag,X> { typedef size_t size_type; /* Record the quaternion size as a constant: */ enum { array_size = 4 }; /* Return the quaternion size: */ size_type size() const { return size_type(array_size); } }; /* Check for a scalar and a quaternion: */ template<class X> struct impl<scalar_result_tag,quaternion_result_tag,X> { typedef size_t size_type; /* Record the array size as a constant: */ enum { array_size = 4 }; /* Return the quaternion size: */ size_type size() const { return size_type(array_size); } }; /* Record the type of the checker: */ typedef impl<left_result,right_result> check_type; typedef typename check_type::size_type size_type; /* The implementation: */ size_type operator()(const LeftT&, const RightT&) const { return check_type().size(); } }; /* Checking for resizeable expression: */ template<typename LeftT, typename RightT> struct GetCheckedSize<LeftT,RightT,dynamic_size_tag> { /* Type of the size checker (for calling equal_or_fail): */ typedef GetCheckedSize<LeftT,RightT,dynamic_size_tag> self; /* Record argument traits: */ typedef ExprTraits<LeftT> left_traits; typedef ExprTraits<RightT> right_traits; /* Result types: */ typedef typename left_traits::result_tag left_result; typedef typename right_traits::result_tag right_result; /* For specialization below: */ template<typename LR, typename RR, class X = void> struct impl; /* Return the size if the same, or fail if different: */ template<typename V> V equal_or_fail(V left, V right) const { if(left != right) throw std::invalid_argument( "expressions have incompatible sizes."); return left; } /* Check for two matrices (linear operators only): */ template<class X> struct impl<matrix_result_tag,matrix_result_tag,X> { typedef matrix_size size_type; /* Return the matrix size, or fail if incompatible: */ size_type size(const LeftT& left, const RightT& right) const { #if defined(CML_CHECK_MATRIX_EXPR_SIZES) return self().equal_or_fail(left.size(), right.size()); #else return left.size(); #endif } }; /* Check for a matrix and a vector: */ template<class X> struct impl<matrix_result_tag,vector_result_tag,X> { typedef size_t size_type; /* Return the vector size: */ size_type size(const LeftT& left, const RightT& right) const { #if defined(CML_CHECK_MATVEC_EXPR_SIZES) self().equal_or_fail(left.cols(), right.size()); #endif return left.rows(); } }; /* Check for a vector and a matrix: */ template<class X> struct impl<vector_result_tag,matrix_result_tag,X> { typedef size_t size_type; /* Return the vector size: */ size_type size(const LeftT& left, const RightT& right) const { #if defined(CML_CHECK_MATVEC_EXPR_SIZES) self().equal_or_fail(left.size(), right.rows()); #endif return right.cols(right); } }; /* Check for a matrix and a scalar: */ template<class X> struct impl<matrix_result_tag,scalar_result_tag,X> { typedef matrix_size size_type; /* Return the matrix size: */ size_type size(const LeftT& left, const RightT&) const { return left.size(); } }; /* Check for a scalar and a matrix: */ template<class X> struct impl<scalar_result_tag,matrix_result_tag,X> { typedef matrix_size size_type; /* Return the matrix size: */ size_type size(const LeftT&, const RightT& right) const { return right.size(); } }; /* Check for two vectors: */ template<class X> struct impl<vector_result_tag,vector_result_tag,X> { typedef size_t size_type; /* Return the vector size: */ size_type size(const LeftT& left, const RightT& right) const { #if defined(CML_CHECK_VECTOR_EXPR_SIZES) return self().equal_or_fail(left.size(), right.size()); #else return left.size(); #endif } }; /* Check for a vector and a scalar: */ template<class X> struct impl<vector_result_tag,scalar_result_tag,X> { typedef size_t size_type; /* Return the vector size: */ size_type size(const LeftT& left, const RightT&) const { return left.size(); } }; /* Check for a scalar and a vector: */ template<class X> struct impl<scalar_result_tag,vector_result_tag,X> { typedef size_t size_type; /* Return the vector size: */ size_type size(const LeftT&, const RightT& right) const { return right.size(); } }; /* Record the type of the checker: */ typedef impl<left_result,right_result> check_type; typedef typename check_type::size_type size_type; /* The implementation: */ size_type operator()(const LeftT& left, const RightT& right) const { return check_type().size(left,right); } }; /** Generator for GetCheckedSize. */ template<typename LeftT, typename RightT, typename SizeTag> inline typename et::GetCheckedSize<LeftT,RightT,SizeTag>::size_type CheckedSize(const LeftT& left, const RightT& right, SizeTag) { return et::GetCheckedSize<LeftT,RightT,SizeTag>()(left,right); } /** Verify the sizes of the argument matrices for matrix multiplication. * * @returns a the size of the resulting matrix. */ template<typename MatT> inline size_t CheckedSquare(const MatT&, fixed_size_tag) { CML_STATIC_REQUIRE_M( ((size_t)MatT::array_rows == (size_t)MatT::array_cols), square_matrix_arg_expected_error); return (size_t)MatT::array_rows; } /** Verify the sizes of the argument matrices for matrix multiplication. * * @returns the size of the resulting matrix. */ template<typename MatT> inline size_t CheckedSquare(const MatT& m, dynamic_size_tag) { matrix_size N = m.size(); et::GetCheckedSize<MatT,MatT,dynamic_size_tag>() .equal_or_fail(N.first, N.second); return N.first; } } // namespace et } // namespace cml #if defined(_MSC_VER) && _MSC_VER < 1400 #pragma warning(pop) #endif #endif // ------------------------------------------------------------------------- // vim:ft=cpp
prophecy/Pillar
Dependencies/Include/Rocket/Controls/ElementFormControl.h
<filename>Dependencies/Include/Rocket/Controls/ElementFormControl.h /* * This source file is part of libRocket, the HTML/CSS Interface Middleware * * For the latest information, see http://www.librocket.com * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #ifndef ROCKETCONTROLSELEMENTFORMCONTROL_H #define ROCKETCONTROLSELEMENTFORMCONTROL_H #include "../Core/Element.h" #include "Header.h" namespace Rocket { namespace Controls { /** A generic specialisation of the generic Core::Element for all input controls. @author <NAME> */ class ROCKETCONTROLS_API ElementFormControl : public Core::Element { public: /// Constructs a new ElementFormControl. This should not be called directly; use the Factory /// instead. /// @param[in] tag The tag the element was declared as in RML. ElementFormControl(const Rocket::Core::String& tag); virtual ~ElementFormControl(); /// Returns the name of the form control. This is not guaranteed to be unique, and in the case of some form /// controls (such as radio buttons) most likely will not be. /// @return The name of the form control. Rocket::Core::String GetName() const; /// Sets the name of the form control. /// @param[in] name The new name of the form control. void SetName(const Rocket::Core::String& name); /// Returns a string representation of the current value of the form control. /// @return The value of the form control. virtual Rocket::Core::String GetValue() const = 0; /// Sets the current value of the form control. /// @param[in] value The new value of the form control. virtual void SetValue(const Rocket::Core::String& value) = 0; /// Returns if this value should be submitted with the form. /// @return True if the value should be be submitted with the form, false otherwise. virtual bool IsSubmitted(); /// Returns the disabled status of the form control. /// @return True if the element is disabled, false otherwise. bool IsDisabled() const; /// Sets the disabled status of the form control. /// @param[in] disable True to disable the element, false to enable. void SetDisabled(bool disable); protected: /// Checks for changes to the 'disabled' attribute. /// @param[in] changed_attributes List of changed attributes on the element. virtual void OnAttributeChange(const Core::AttributeNameList& changed_attributes); }; } } #endif
prophecy/Pillar
Dependencies/Include/cml/quaternion/quaternion_promotions.h
/* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief */ #ifndef quaternion_promotions_h #define quaternion_promotions_h #include <cml/et/scalar_promotions.h> #include <cml/vector/vector_promotions.h> namespace cml { namespace et { /* Default quaternion type promotion templates. */ template<class LeftT, class RightT> struct QuaternionPromote; /** Type promotion for two quaternion types. */ template<typename E1, class AT1, typename E2, class AT2, class OT, class CT> struct QuaternionPromote< cml::quaternion<E1,AT1,OT,CT>, cml::quaternion<E2,AT2,OT,CT> > { /* The deduced vector type: */ typedef typename VectorPromote< typename cml::quaternion<E1,AT1,OT,CT>::vector_type, typename cml::quaternion<E2,AT2,OT,CT>::vector_type >::type promoted_vector; /* The deduced element and storage types: */ typedef typename promoted_vector::value_type value_type; typedef typename promoted_vector::storage_type storage_type; /* The deduced quaternion result type: */ typedef cml::quaternion<value_type,storage_type,OT,CT> type; /* The temporary type: */ typedef typename type::temporary_type temporary_type; }; /** * NOTE: QuaternionPromote* are somewhat ad hoc, and were added to * simplify the code for quaternion slerp/squad/etc. */ /** Type promotion for two quaternion types. */ template < class Quat1_T, class Quat2_T > struct QuaternionPromote2 { typedef typename QuaternionPromote< typename Quat1_T::temporary_type, typename Quat2_T::temporary_type >::temporary_type temporary_type; typedef typename temporary_type::value_type value_type; }; /** Type promotion for three quaternion types. */ template < class Quat1_T, class Quat2_T, class Quat3_T > struct QuaternionPromote3 { typedef typename QuaternionPromote< typename Quat1_T::temporary_type, typename QuaternionPromote< typename Quat2_T::temporary_type, typename Quat3_T::temporary_type >::temporary_type >::temporary_type temporary_type; typedef typename temporary_type::value_type value_type; }; /** Type promotion for four quaternion types. */ template < class Quat1_T, class Quat2_T, class Quat3_T, class Quat4_T > struct QuaternionPromote4 { typedef typename QuaternionPromote< typename Quat1_T::temporary_type, typename QuaternionPromote< typename Quat2_T::temporary_type, typename QuaternionPromote< typename Quat3_T::temporary_type, typename Quat4_T::temporary_type >::temporary_type >::temporary_type >::temporary_type temporary_type; typedef typename temporary_type::value_type value_type; }; /** Type promotion for a quaternion and a scalar. */ template<typename E, class AT, class OT, class CT, typename S> struct QuaternionPromote<cml::quaternion<E,AT,OT,CT>, S> { /* The deduced vector type: */ typedef typename VectorPromote< typename quaternion<E,AT,OT,CT>::vector_type, S >::type promoted_vector; /* The deduced element and storage types: */ typedef typename promoted_vector::value_type value_type; typedef typename promoted_vector::storage_type storage_type; /* The deduced quaternion result type: */ typedef cml::quaternion<value_type,storage_type,OT,CT> type; /* The temporary type: */ typedef typename type::temporary_type temporary_type; }; /** Type promotion for a scalar and a quaternion. */ template<class S, typename E, class AT, class OT, class CT> struct QuaternionPromote<S, cml::quaternion<E,AT,OT,CT> > { /* The deduced vector type: */ typedef typename VectorPromote< S, typename quaternion<E,AT,OT,CT>::vector_type >::type promoted_vector; /* The deduced element and storage types: */ typedef typename promoted_vector::value_type value_type; typedef typename promoted_vector::storage_type storage_type; /* The deduced quaternion result type: */ typedef cml::quaternion<value_type,storage_type,OT,CT> type; /* The temporary type: */ typedef typename type::temporary_type temporary_type; }; } // namespace et } // namespace cml #endif // ------------------------------------------------------------------------- // vim:ft=cpp
prophecy/Pillar
Dependencies/Include/cml/quaternion/quaternion_mul.h
<gh_stars>10-100 /* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief Multiplication of two quaternions, p*q. * * This uses the expression tree, since the result is closed-form and can be * computed by index. */ #ifndef quaternion_mul_h #define quaternion_mul_h #include <cml/mathlib/checking.h> #include <cml/quaternion/quaternion_promotions.h> namespace cml { namespace detail { template < class CrossType, class Real > struct SumOp; template < class Real > struct SumOp< positive_cross, Real > { Real operator()(Real a, Real b) const { return a + b; } }; template < class Real > struct SumOp< negative_cross, Real > { Real operator()(Real a, Real b) const { return a - b; } }; template < class Quat1_T, class Quat2_T > typename et::QuaternionPromote< typename Quat1_T::temporary_type, typename Quat2_T::temporary_type >::temporary_type QuaternionMult(const Quat1_T& q1, const Quat2_T& q2) { detail::CheckQuat(q1); detail::CheckQuat(q2); typedef typename et::QuaternionPromote< typename Quat1_T::temporary_type, typename Quat2_T::temporary_type >::temporary_type temporary_type; typedef typename temporary_type::value_type value_type; typedef typename temporary_type::order_type order_type; typedef typename temporary_type::cross_type cross_type; typedef detail::SumOp<cross_type, value_type> sum_op; enum { W = order_type::W, X = order_type::X, Y = order_type::Y, Z = order_type::Z }; temporary_type result; /* s1*s2-dot(v1,v2): */ result[W] = q1[W]*q2[W] - q1[X]*q2[X] - q1[Y]*q2[Y] - q1[Z]*q2[Z]; /* (s1*v2 + s2*v1 + v1^v2) i: */ result[X] = sum_op()(q1[W]*q2[X] + q2[W]*q1[X], q1[Y]*q2[Z] - q1[Z]*q2[Y]); /* (s1*v2 + s2*v1 + v1^v2) j: */ result[Y] = sum_op()(q1[W]*q2[Y] + q2[W]*q1[Y], q1[Z]*q2[X] - q1[X]*q2[Z]); /* (s1*v2 + s2*v1 + v1^v2) k: */ result[Z] = sum_op()(q1[W]*q2[Z] + q2[W]*q1[Z], q1[X]*q2[Y] - q1[Y]*q2[X]); return result; } } // namespace detail /** Declare mul taking two quaternion operands. */ template<typename E1, class AT1, typename E2, class AT2, class OT, class CT> inline typename et::QuaternionPromote< typename quaternion<E1,AT1,OT,CT>::temporary_type, typename quaternion<E2,AT2,OT,CT>::temporary_type >::temporary_type operator*( const quaternion<E1,AT1,OT,CT>& left, const quaternion<E2,AT2,OT,CT>& right) { return detail::QuaternionMult(left, right); } /** Declare mul taking a quaternion and a et::QuaternionXpr. */ template<typename E, class AT, class OT, class CT, class XprT> inline typename et::QuaternionPromote< typename quaternion<E,AT,OT,CT>::temporary_type, typename XprT::temporary_type >::temporary_type operator*( const quaternion<E,AT,OT,CT>& left, QUATXPR_ARG_TYPE right) { return detail::QuaternionMult(left, right); } /** Declare mul taking an et::QuaternionXpr and a quaternion. */ template<class XprT, typename E, class AT, class OT, class CT> inline typename et::QuaternionPromote< typename XprT::temporary_type, typename quaternion<E,AT,OT,CT>::temporary_type >::temporary_type operator*( QUATXPR_ARG_TYPE left, const quaternion<E,AT,OT,CT>& right) { return detail::QuaternionMult(left, right); } /** Declare mul taking two et::QuaternionXpr operands. */ template<class XprT1, class XprT2> inline typename et::QuaternionPromote< typename XprT1::temporary_type, typename XprT2::temporary_type >::temporary_type operator*( QUATXPR_ARG_TYPE_N(1) left, QUATXPR_ARG_TYPE_N(2) right) { return detail::QuaternionMult(left, right); } } // namespace cml #endif // ------------------------------------------------------------------------- // vim:ft=cpp
prophecy/Pillar
Dependencies/Include/cml/vector/vector_functions.h
/* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief */ #ifndef vector_functions_h #define vector_functions_h namespace cml { /** Squared length of a vector. */ template<typename E, class AT> inline typename vector<E,AT>::value_type length_squared(const vector<E,AT>& arg) { return arg.length_squared(); } /** Squared length of a vector expr. */ template<typename XprT> inline typename XprT::value_type length_squared(VECXPR_ARG_TYPE arg) { return arg.length_squared(); } /** Length of a vector. */ template<typename E, class AT> inline typename vector<E,AT>::value_type length(const vector<E,AT>& arg) { return arg.length(); } /** Length of a vector expr. */ template<typename XprT> inline typename XprT::value_type length(VECXPR_ARG_TYPE arg) { return arg.length(); } /** Normalize a vector. */ template<typename E, class AT> inline vector<E, AT> normalize(const vector<E,AT>& arg) { vector<E, AT> result(arg); result.normalize(); return result; } /** Normalize a vector expr. */ template<typename XprT> inline typename XprT::result_type normalize(VECXPR_ARG_TYPE arg) { return arg.normalize(); } } // namespace cml #endif // ------------------------------------------------------------------------- // vim:ft=cpp
prophecy/Pillar
Dependencies/Include/cml/matvec/matvec_mul.h
<reponame>prophecy/Pillar<filename>Dependencies/Include/cml/matvec/matvec_mul.h /* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief Multiply a matrix and a vector. * * @todo Implement smarter temporary generation. * * @todo Does it make sense to put mat-vec multiplication as a node into the * expression tree? * * @internal This does not need to return an expression type, since the * temporary generation for the matrix result is handled automatically by the * compiler. i.e. when used in an expression, the result is automatically * included in the expression tree as a temporary by the compiler. */ #ifndef matvec_mul_h #define matvec_mul_h #include <cml/core/cml_meta.h> #include <cml/vector/vector_expr.h> #include <cml/matrix/matrix_expr.h> #include <cml/matvec/matvec_promotions.h> /* This is used below to create a more meaningful compile-time error when * mat-vec mul is not provided with the right arguments: */ struct mvmul_expects_one_matrix_and_one_vector_arg_error; struct mvmul_expects_one_vector_and_one_matrix_arg_error; namespace cml { namespace detail { /* For choosing the proper multiplication order: */ typedef true_type mul_Ax; typedef false_type mul_xA; /** Compute y = A*x. */ template<typename LeftT, typename RightT> inline typename et::MatVecPromote< typename et::ExprTraits<LeftT>::result_type, typename et::ExprTraits<RightT>::result_type >::temporary_type mul(const LeftT& A, const RightT& x, mul_Ax) { /* Shorthand: */ typedef et::ExprTraits<LeftT> left_traits; typedef et::ExprTraits<RightT> right_traits; typedef typename left_traits::result_tag left_result; typedef typename right_traits::result_tag right_result; /* mul()[A*x] requires a matrix and a vector expression: */ CML_STATIC_REQUIRE_M( (same_type<left_result, et::matrix_result_tag>::is_true && same_type<right_result, et::vector_result_tag>::is_true), mvmul_expects_one_matrix_and_one_vector_arg_error); /* Note: parens are required here so that the preprocessor ignores the * commas. */ /* Get result type: */ typedef typename et::MatVecPromote< typename left_traits::result_type, typename right_traits::result_type >::temporary_type result_type; /* Record size type: */ typedef typename result_type::size_tag size_tag; /* Check the size: */ size_t N = et::CheckedSize(A, x, size_tag()); /* Initialize the new vector: */ result_type y; cml::et::detail::Resize(y, N); /* Compute y = A*x: */ typedef typename result_type::value_type sum_type; for(size_t i = 0; i < N; ++i) { /* XXX This should be unrolled. */ sum_type sum(A(i,0)*x[0]); for(size_t k = 1; k < x.size(); ++k) { sum += (A(i,k)*x[k]); } y[i] = sum; } return y; } /** Compute y = x*A. */ template<typename LeftT, typename RightT> inline typename et::MatVecPromote< typename et::ExprTraits<LeftT>::result_type, typename et::ExprTraits<RightT>::result_type >::temporary_type mul(const LeftT& x, const RightT& A, mul_xA) { /* Shorthand: */ typedef et::ExprTraits<LeftT> left_traits; typedef et::ExprTraits<RightT> right_traits; typedef typename left_traits::result_tag left_result; typedef typename right_traits::result_tag right_result; /* mul()[x*A] requires a vector and a matrix expression: */ CML_STATIC_REQUIRE_M( (same_type<left_result, et::vector_result_tag>::is_true && same_type<right_result, et::matrix_result_tag>::is_true), mvmul_expects_one_vector_and_one_matrix_arg_error); /* Note: parens are required here so that the preprocessor ignores the * commas. */ /* Get result type: */ typedef typename et::MatVecPromote< typename left_traits::result_type, typename right_traits::result_type >::temporary_type result_type; /* Record size type: */ typedef typename result_type::size_tag size_tag; /* Check the size: */ size_t N = et::CheckedSize(x, A, size_tag()); /* Initialize the new vector: */ result_type y; cml::et::detail::Resize(y, N); /* Compute y = x*A: */ typedef typename result_type::value_type sum_type; for(size_t i = 0; i < N; ++i) { /* XXX This should be unrolled. */ sum_type sum(x[0]*A(0,i)); for(size_t k = 1; k < x.size(); ++k) { sum += (x[k]*A(k,i)); } y[i] = sum; } return y; } } // namespace detail /** operator*() for a matrix and a vector. */ template<typename E1, class AT1, typename BO, class L, typename E2, class AT2> inline typename et::MatVecPromote< matrix<E1,AT1,BO,L>, vector<E2,AT2> >::temporary_type operator*(const matrix<E1,AT1,BO,L>& left, const vector<E2,AT2>& right) { return detail::mul(left,right,detail::mul_Ax()); } /** operator*() for a matrix and a VectorXpr. */ template<typename E, class AT, class L, typename BO, typename XprT> inline typename et::MatVecPromote< matrix<E,AT,BO,L>, typename XprT::result_type >::temporary_type operator*(const matrix<E,AT,BO,L>& left, const et::VectorXpr<XprT>& right) { /* Generate a temporary, and compute the right-hand expression: */ typename et::VectorXpr<XprT>::temporary_type right_tmp; cml::et::detail::Resize(right_tmp,right.size()); right_tmp = right; return detail::mul(left,right_tmp,detail::mul_Ax()); } /** operator*() for a MatrixXpr and a vector. */ template<typename XprT, typename E, class AT> inline typename et::MatVecPromote< typename XprT::result_type, vector<E,AT> >::temporary_type operator*(const et::MatrixXpr<XprT>& left, const vector<E,AT>& right) { /* Generate a temporary, and compute the left-hand expression: */ typename et::MatrixXpr<XprT>::temporary_type left_tmp; cml::et::detail::Resize(left_tmp,left.rows(),left.cols()); left_tmp = left; return detail::mul(left_tmp,right,detail::mul_Ax()); } /** operator*() for a MatrixXpr and a VectorXpr. */ template<typename XprT1, typename XprT2> inline typename et::MatVecPromote< typename XprT1::result_type, typename XprT2::result_type >::temporary_type operator*(const et::MatrixXpr<XprT1>& left, const et::VectorXpr<XprT2>& right) { /* Generate a temporary, and compute the left-hand expression: */ typename et::MatrixXpr<XprT1>::temporary_type left_tmp; cml::et::detail::Resize(left_tmp,left.rows(),left.cols()); left_tmp = left; /* Generate a temporary, and compute the right-hand expression: */ typename et::VectorXpr<XprT2>::temporary_type right_tmp; cml::et::detail::Resize(right_tmp,right.size()); right_tmp = right; return detail::mul(left_tmp,right_tmp,detail::mul_Ax()); } /** operator*() for a vector and a matrix. */ template<typename E1, class AT1, typename E2, class AT2, typename BO, class L> inline typename et::MatVecPromote< vector<E1,AT1>, matrix<E2,AT2,BO,L> >::temporary_type operator*(const vector<E1,AT1>& left, const matrix<E2,AT2,BO,L>& right) { return detail::mul(left,right,detail::mul_xA()); } /** operator*() for a vector and a MatrixXpr. */ template<typename XprT, typename E, class AT> inline typename et::MatVecPromote< typename XprT::result_type, vector<E,AT> >::temporary_type operator*(const vector<E,AT>& left, const et::MatrixXpr<XprT>& right) { /* Generate a temporary, and compute the right-hand expression: */ typename et::MatrixXpr<XprT>::temporary_type right_tmp; cml::et::detail::Resize(right_tmp,right.rows(),right.cols()); right_tmp = right; return detail::mul(left,right_tmp,detail::mul_xA()); } /** operator*() for a VectorXpr and a matrix. */ template<typename XprT, typename E, class AT, typename BO, class L> inline typename et::MatVecPromote< typename XprT::result_type, matrix<E,AT,BO,L> >::temporary_type operator*(const et::VectorXpr<XprT>& left, const matrix<E,AT,BO,L>& right) { /* Generate a temporary, and compute the left-hand expression: */ typename et::VectorXpr<XprT>::temporary_type left_tmp; cml::et::detail::Resize(left_tmp,left.size()); left_tmp = left; return detail::mul(left_tmp,right,detail::mul_xA()); } /** operator*() for a VectorXpr and a MatrixXpr. */ template<typename XprT1, typename XprT2> inline typename et::MatVecPromote< typename XprT1::result_type, typename XprT2::result_type >::temporary_type operator*(const et::VectorXpr<XprT1>& left, const et::MatrixXpr<XprT2>& right) { /* Generate a temporary, and compute the left-hand expression: */ typename et::VectorXpr<XprT1>::temporary_type left_tmp; cml::et::detail::Resize(left_tmp,left.size()); left_tmp = left; /* Generate a temporary, and compute the right-hand expression: */ typename et::MatrixXpr<XprT2>::temporary_type right_tmp; cml::et::detail::Resize(right_tmp,right.rows(),right.cols()); right_tmp = right; return detail::mul(left_tmp,right_tmp,detail::mul_xA()); } } // namespace cml #endif // ------------------------------------------------------------------------- // vim:ft=cpp
prophecy/Pillar
Dependencies/Include/Rocket/Core/RenderInterface.h
<gh_stars>100-1000 /* * This source file is part of libRocket, the HTML/CSS Interface Middleware * * For the latest information, see http://www.librocket.com * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #ifndef ROCKETCORERENDERINTERFACE_H #define ROCKETCORERENDERINTERFACE_H #include "ReferenceCountable.h" #include "Header.h" #include "Texture.h" #include "Vertex.h" namespace Rocket { namespace Core { class Context; /** The abstract base class for application-specific rendering implementation. Your application must provide a concrete implementation of this class and install it through Core::SetRenderInterface() in order for anything to be rendered. @author <NAME> */ class ROCKETCORE_API RenderInterface : public ReferenceCountable { public: RenderInterface(); virtual ~RenderInterface(); /// Called by Rocket when it wants to render geometry that the application does not wish to optimise. Note that /// Rocket renders everything as triangles. /// @param[in] vertices The geometry's vertex data. /// @param[in] num_vertices The number of vertices passed to the function. /// @param[in] indices The geometry's index data. /// @param[in] num_indices The number of indices passed to the function. This will always be a multiple of three. /// @param[in] texture The texture to be applied to the geometry. This may be NULL, in which case the geometry is untextured. /// @param[in] translation The translation to apply to the geometry. virtual void RenderGeometry(Vertex* vertices, int num_vertices, int* indices, int num_indices, TextureHandle texture, const Vector2f& translation) = 0; /// Called by Rocket when it wants to compile geometry it believes will be static for the forseeable future. /// If supported, this should be return a pointer to an optimised, application-specific version of the data. If /// not, do not override the function or return NULL; the simpler RenderGeometry() will be called instead. /// @param[in] vertices The geometry's vertex data. /// @param[in] num_vertices The number of vertices passed to the function. /// @param[in] indices The geometry's index data. /// @param[in] num_indices The number of indices passed to the function. This will always be a multiple of three. /// @param[in] texture The texture to be applied to the geometry. This may be NULL, in which case the geometry is untextured. /// @return The application-specific compiled geometry. Compiled geometry will be stored and rendered using RenderCompiledGeometry() in future calls, and released with ReleaseCompiledGeometry() when it is no longer needed. virtual CompiledGeometryHandle CompileGeometry(Vertex* vertices, int num_vertices, int* indices, int num_indices, TextureHandle texture); /// Called by Rocket when it wants to render application-compiled geometry. /// @param[in] geometry The application-specific compiled geometry to render. /// @param[in] translation The translation to apply to the geometry. virtual void RenderCompiledGeometry(CompiledGeometryHandle geometry, const Vector2f& translation); /// Called by Rocket when it wants to release application-compiled geometry. /// @param[in] geometry The application-specific compiled geometry to release. virtual void ReleaseCompiledGeometry(CompiledGeometryHandle geometry); /// Called by Rocket when it wants to enable or disable scissoring to clip content. /// @param[in] enable True if scissoring is to enabled, false if it is to be disabled. virtual void EnableScissorRegion(bool enable) = 0; /// Called by Rocket when it wants to change the scissor region. /// @param[in] x The left-most pixel to be rendered. All pixels to the left of this should be clipped. /// @param[in] y The top-most pixel to be rendered. All pixels to the top of this should be clipped. /// @param[in] width The width of the scissored region. All pixels to the right of (x + width) should be clipped. /// @param[in] height The height of the scissored region. All pixels to below (y + height) should be clipped. virtual void SetScissorRegion(int x, int y, int width, int height) = 0; /// Called by Rocket when a texture is required by the library. /// @param[out] texture_handle The handle to write the texture handle for the loaded texture to. /// @param[out] texture_dimensions The variable to write the dimensions of the loaded texture. /// @param[in] source The application-defined image source, joined with the path of the referencing document. /// @return True if the load attempt succeeded and the handle and dimensions are valid, false if not. virtual bool LoadTexture(TextureHandle& texture_handle, Vector2i& texture_dimensions, const String& source); /// Called by Rocket when a texture is required to be built from an internally-generated sequence of pixels. /// @param[out] texture_handle The handle to write the texture handle for the generated texture to. /// @param[in] source The raw 8-bit texture data. Each pixel is made up of four 8-bit values, indicating red, green, blue and alpha in that order. /// @param[in] source_dimensions The dimensions, in pixels, of the source data. /// @return True if the texture generation succeeded and the handle is valid, false if not. virtual bool GenerateTexture(TextureHandle& texture_handle, const byte* source, const Vector2i& source_dimensions); /// Called by Rocket when a loaded texture is no longer required. /// @param texture The texture handle to release. virtual void ReleaseTexture(TextureHandle texture); /// Returns the native horizontal texel offset for the renderer. /// @return The renderer's horizontal texel offset. The default implementation returns 0. virtual float GetHorizontalTexelOffset(); /// Returns the native vertical texel offset for the renderer. /// @return The renderer's vertical texel offset. The default implementation returns 0. virtual float GetVerticalTexelOffset(); /// Returns the number of pixels per inch. /// @returns The number of pixels per inch. The default implementation returns 100. virtual float GetPixelsPerInch(); /// Called when this render interface is released. virtual void Release(); /// Get the context currently being rendered. This is only valid during RenderGeometry, /// CompileGeometry, RenderCompiledGeometry, EnableScissorRegion and SetScissorRegion. Context* GetContext() const; protected: virtual void OnReferenceDeactivate(); private: Context* context; friend class Context; }; } } #endif
prophecy/Pillar
Dependencies/Include/cml/mathlib/checking.h
/* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief */ #ifndef checking_h #define checking_h #include <cml/vector/vector_expr.h> #include <cml/matrix/matrix_expr.h> #include <cml/quaternion/quaternion_expr.h> /* Run- and compile-time checking of argument types, values and sizes. */ struct function_expects_vector_arg_error; struct function_expects_matrix_arg_error; struct function_expects_quaternion_arg_error; struct function_expects_2D_vector_arg_error; struct function_expects_3D_vector_arg_error; struct function_expects_4D_vector_arg_error; struct function_expects_2D_or_3D_vector_arg_error; struct function_expects_2x2_matrix_arg_error; struct function_expects_3x3_matrix_arg_error; struct function_expects_4x4_matrix_arg_error; struct function_expects_square_matrix_arg_error; struct matrix_arg_fails_minimum_size_requirement; namespace cml { namespace detail { ////////////////////////////////////////////////////////////////////////////// // Vector argument checking ////////////////////////////////////////////////////////////////////////////// /** Compile-time check for a vector argument */ template< class VecT > inline void CheckVec(const VecT&) { typedef et::ExprTraits<VecT> vector_traits; typedef typename vector_traits::result_tag result_type; CML_STATIC_REQUIRE_M( (same_type<result_type, et::vector_result_tag>::is_true), function_expects_vector_arg_error); } /** Compile-time check for a vector of size N */ template< class VecT, size_t N, class ErrorT > inline void CheckVecN(const VecT& v, fixed_size_tag) { CheckVec(v); CML_STATIC_REQUIRE_M(((size_t)VecT::array_size == N), ErrorT); } /** Run-time check for a vector of size N */ template< class VecT, size_t N, class /*ErrorT*/ > inline void CheckVecN(const VecT& v, dynamic_size_tag) { CheckVec(v); et::GetCheckedSize<VecT,VecT,dynamic_size_tag>() .equal_or_fail(v.size(),size_t(N)); } /** Check for a vector of size N */ template< class VecT, size_t N, class ErrorT > inline void CheckVecN(const VecT& v) { typedef et::ExprTraits<VecT> vector_traits; typedef typename vector_traits::size_tag size_tag; detail::CheckVecN<VecT,N,ErrorT>(v, size_tag()); } /** Check for a vector of size 2 */ template< class VecT > inline void CheckVec2(const VecT& v) { detail::CheckVecN<VecT,2,function_expects_2D_vector_arg_error>(v); } /** Check for a vector of size 3 */ template< class VecT > inline void CheckVec3(const VecT& v) { detail::CheckVecN<VecT,3,function_expects_3D_vector_arg_error>(v); } /** Check for a vector of size 4 */ template< class VecT > inline void CheckVec4(const VecT& v) { CheckVecN<VecT,4,function_expects_4D_vector_arg_error>(v); } /** Compile-time check for a vector of size 2 or 3 */ template< class VecT > inline void CheckVec2Or3(const VecT& v, fixed_size_tag) { CheckVec(v); CML_STATIC_REQUIRE_M( (VecT::array_size == 2 || VecT::array_size == 3), function_expects_2D_or_3D_vector_arg_error); } /** Run-time check for a vector of size 2 or 3 */ template< class VecT > inline void CheckVec2Or3(const VecT& v, dynamic_size_tag) { CheckVec(v); if (v.size() != 2 && v.size() != 3) { throw std::invalid_argument("2d or 3d vector arg expected"); } } /** Check for a vector of size 2 or 3 */ template< class VecT > inline void CheckVec2Or3(const VecT& v) { typedef et::ExprTraits<VecT> vector_traits; typedef typename vector_traits::size_tag size_tag; detail::CheckVec2Or3(v, size_tag()); } ////////////////////////////////////////////////////////////////////////////// // Matrix argument checking ////////////////////////////////////////////////////////////////////////////// /** Compile-time check for a matrix argument */ template< class MatT > inline void CheckMat(const MatT&) { typedef et::ExprTraits<MatT> matrix_traits; typedef typename matrix_traits::result_tag result_type; CML_STATIC_REQUIRE_M( (same_type<result_type, et::matrix_result_tag>::is_true), function_expects_matrix_arg_error); } /** Compile-time check for a matrix of size NxM */ template< class MatT, size_t N, size_t M, class ErrorT > inline void CheckMatNxM(const MatT& m, fixed_size_tag) { CheckMat(m); CML_STATIC_REQUIRE_M( (MatT::array_rows == N && MatT::array_cols == M), ErrorT); } /** Run-time check for a matrix of size NxM */ template< class MatT, size_t N, size_t M, class /*ErrorT*/ > inline void CheckMatNxM(const MatT& m, dynamic_size_tag) { CheckMat(m); et::GetCheckedSize<MatT,MatT,dynamic_size_tag>() .equal_or_fail(m.rows(),N); et::GetCheckedSize<MatT,MatT,dynamic_size_tag>() .equal_or_fail(m.cols(),M); } /** Check for a matrix of size NxM */ template< class MatT, size_t N, size_t M, class ErrorT > inline void CheckMatNxM(const MatT& m) { typedef et::ExprTraits<MatT> matrix_traits; typedef typename matrix_traits::size_tag size_tag; CheckMatNxM<MatT,N,M,ErrorT>(m, size_tag()); } /** Check for a square matrix of size NxN */ template< class MatT, size_t N, class ErrorT > inline void CheckMatN(const MatT& m) { CheckMatNxM<MatT,N,N,ErrorT>(m); } /** Check for a square matrix of size 2x2 */ template< class MatT > inline void CheckMat2x2(const MatT& m) { CheckMatN<MatT,2,function_expects_2x2_matrix_arg_error>(m); } /** Check for a square matrix of size 3x3 */ template< class MatT > inline void CheckMat3x3(const MatT& m) { CheckMatN<MatT,3,function_expects_3x3_matrix_arg_error>(m); } /** Check for a square matrix of size 4x4 */ template< class MatT > inline void CheckMat4x4(const MatT& m) { CheckMatN<MatT,4,function_expects_4x4_matrix_arg_error>(m); } /** Compile-time check for a matrix with minimum dimensions NxM */ template< class MatT, size_t N, size_t M, class ErrorT > inline void CheckMatMinNxM(const MatT& m, fixed_size_tag) { CheckMat(m); CML_STATIC_REQUIRE_M( (MatT::array_rows >= N && MatT::array_cols >= M), ErrorT); } /** Run-time check for a matrix with minimum dimensions NxM */ template< class MatT, size_t N, size_t M, class /*ErrorT*/ > inline void CheckMatMinNxM(const MatT& m, dynamic_size_tag) { CheckMat(m); if (m.rows() < N || m.cols() < M) { throw std::invalid_argument( "matrix does not meet minimum size requirement"); } } /** Check for a matrix with minimum dimensions NxM */ template< class MatT, size_t N, size_t M, class ErrorT > inline void CheckMatMinNxM(const MatT& m) { typedef et::ExprTraits<MatT> matrix_traits; typedef typename matrix_traits::size_tag size_tag; CheckMatMinNxM<MatT,N,M,ErrorT>(m, size_tag()); } /** Check for a matrix with minimum dimensions NxN */ template< class MatT, size_t N, class ErrorT > inline void CheckMatMinN(const MatT& m) { CheckMatMinNxM<MatT,N,N,ErrorT>(m); } /** Check for a matrix with minimum dimensions 2x2 */ template< class MatT > inline void CheckMatMin2x2(const MatT& m) { CheckMatMinN<MatT,2,matrix_arg_fails_minimum_size_requirement>(m); } /** Check for a matrix with minimum dimensions 3x3 */ template< class MatT > inline void CheckMatMin3x3(const MatT& m) { CheckMatMinN<MatT,3,matrix_arg_fails_minimum_size_requirement>(m); } /** Check for a matrix with minimum dimensions 4x4 */ template< class MatT > inline void CheckMatMin4x4(const MatT& m) { CheckMatMinN<MatT,4,matrix_arg_fails_minimum_size_requirement>(m); } /** Check for a matrix that can represent a 3D linear transform */ template< class MatT > inline void CheckMatLinear3D(const MatT& m) { CheckMatMin3x3(m); } /** Check for a matrix that can represent a 2D linear transform */ template< class MatT > inline void CheckMatLinear2D(const MatT& m) { CheckMatMin2x2(m); } /** Check for a matrix that can represent a 3D row-basis affine transform */ template< class MatT > inline void CheckMatAffine3D(const MatT& m, row_basis) { CheckMatMinNxM<MatT,4,3,matrix_arg_fails_minimum_size_requirement>(m); } /** Check for a matrix that can represent a 3D col-basis affine transform */ template< class MatT > inline void CheckMatAffine3D(const MatT& m, col_basis) { CheckMatMinNxM<MatT,3,4,matrix_arg_fails_minimum_size_requirement>(m); } /** Check for a matrix that can represent a 2D row-basis affine transform */ template< class MatT > inline void CheckMatAffine2D(const MatT& m, row_basis) { CheckMatMinNxM<MatT,3,2,matrix_arg_fails_minimum_size_requirement>(m); } /** Check for a matrix that can represent a 2D col-basis affine transform */ template< class MatT > inline void CheckMatAffine2D(const MatT& m, col_basis) { CheckMatMinNxM<MatT,2,3,matrix_arg_fails_minimum_size_requirement>(m); } /** Check for a matrix that can represent a 3D affine transform */ template< class MatT > inline void CheckMatAffine3D(const MatT& m) { CheckMatAffine3D(m, typename MatT::basis_orient()); } /** Check for a matrix that can represent a 2D affine transform */ template< class MatT > inline void CheckMatAffine2D(const MatT& m) { CheckMatAffine2D(m, typename MatT::basis_orient()); } /** Check for a matrix that can represent a 3D homogenous transform */ template< class MatT > inline void CheckMatHomogeneous3D(const MatT& m) { CheckMatMin4x4(m); } /** Compile-time check for a square matrix */ template< class MatT, class ErrorT> inline void CheckMatSquare(const MatT& m, fixed_size_tag) { CheckMat(m); CML_STATIC_REQUIRE_M( (MatT::array_rows == MatT::array_cols), ErrorT); } /** Run-time check for a square matrix */ template< class MatT, class /*ErrorT*/ > inline void CheckMatSquare(const MatT& m, dynamic_size_tag) { CheckMat(m); if (m.rows() != m.cols()) { throw std::invalid_argument( "function expects square matrix as argument"); } } /** Check for a square matrix */ template< class MatT > inline void CheckMatSquare(const MatT& m) { typedef et::ExprTraits<MatT> matrix_traits; typedef typename matrix_traits::size_tag size_tag; detail::CheckMatSquare< MatT,function_expects_square_matrix_arg_error>(m, size_tag()); } ////////////////////////////////////////////////////////////////////////////// // Quaternion argument checking ////////////////////////////////////////////////////////////////////////////// /** Compile-time check for a quaternion argument*/ template< class QuatT > inline void CheckQuat(const QuatT& /*q*/) { typedef et::ExprTraits<QuatT> quaternion_traits; typedef typename quaternion_traits::result_tag result_type; CML_STATIC_REQUIRE_M( (same_type<result_type, et::quaternion_result_tag>::is_true), function_expects_quaternion_arg_error); } ////////////////////////////////////////////////////////////////////////////// // Index argument checking ////////////////////////////////////////////////////////////////////////////// /** Run-time check for a valid argument */ inline void CheckValidArg(bool valid) { if (!valid) { throw std::invalid_argument("invalid function argument"); } } /** Check for a valid integer index with value < N */ template < size_t N > inline void CheckIndexN(size_t index) { CheckValidArg(index < N); } /** Check for a valid integer index with value < 2 */ inline void CheckIndex2(size_t index) { CheckIndexN<2>(index); } /** Check for a valid integer index with value < 3 */ inline void CheckIndex3(size_t index) { CheckIndexN<3>(index); } } // namespace detail } // namespace cml #endif
prophecy/Pillar
Dependencies/Include/cml/vector/vector_products.h
<gh_stars>10-100 /* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief Defines vector dot and outer products. * * @todo Figure out if the source or destination size type should trigger * unrolling. May need a per-compiler compile-time option for this. */ #ifndef vector_products_h #define vector_products_h #include <cml/core/cml_assert.h> #include <cml/et/scalar_promotions.h> #include <cml/et/size_checking.h> #include <cml/vector/vector_unroller.h> #include <cml/vector/vector_expr.h> #include <cml/matrix/matrix_expr.h> /* This is used below to create a more meaningful compile-time error when * dot() is not provided with vector or VectorExpr arguments: */ struct dot_expects_vector_args_error; /* This is used below to create a more meaningful compile-time error when * perp_dot() is not provided with 2D vector or VectorExpr arguments: */ struct perp_dot_expects_vector_args_error; struct perp_dot_expects_2D_vector_args_error; /* This is used below to create a more meaningful compile-time error when * outer() is not provided with vector or VectorExpr arguments: */ struct outer_expects_vector_args_error; /* This is used below to create a more meaningful compile-time error when * cross() is not provided with 3D vector or VectorExpr arguments: */ struct cross_expects_vector_args_error; struct cross_expects_3D_vector_args_error; namespace cml { namespace detail { template<typename LeftT, typename RightT> struct DotPromote { /* Shorthand: */ typedef et::ExprTraits<LeftT> left_traits; typedef et::ExprTraits<RightT> right_traits; typedef typename left_traits::value_type left_value; typedef typename right_traits::value_type right_value; /* Deduce the promoted scalar type: */ typedef et::OpMul<left_value, right_value> op_mul; typedef typename et::OpAdd< typename op_mul::value_type, typename op_mul::value_type> op_add; typedef typename op_add::value_type promoted_scalar; }; template<typename LeftT, typename RightT> struct CrossPromote { /* Shorthand: */ typedef et::ExprTraits<LeftT> left_traits; typedef et::ExprTraits<RightT> right_traits; typedef typename left_traits::result_type left_type; typedef typename right_traits::result_type right_type; /* Deduce the matrix result type: */ typedef typename et::VectorPromote< left_type,right_type>::temporary_type promoted_vector; }; template<typename LeftT, typename RightT> struct OuterPromote { /* Shorthand: */ typedef et::ExprTraits<LeftT> left_traits; typedef et::ExprTraits<RightT> right_traits; typedef typename left_traits::result_type left_type; typedef typename right_traits::result_type right_type; /* Deduce the matrix result type: */ typedef typename et::MatrixPromote< left_type,right_type>::temporary_type promoted_matrix; }; /** Construct a dot unroller for fixed-size arrays. * * @note This should only be called for vectors. * * @sa cml::dot */ template<typename LeftT, typename RightT> inline typename DotPromote<LeftT,RightT>::promoted_scalar UnrollDot(const LeftT& left, const RightT& right, fixed_size_tag) { /* Shorthand: */ typedef DotPromote<LeftT,RightT> dot_helper; /* Compile-type vector size check: */ typedef typename et::GetCheckedSize<LeftT,RightT,fixed_size_tag> ::check_type check_sizes; /* Get the fixed array size using the helper: */ enum { Len = check_sizes::array_size }; /* Record the unroller type: */ typedef typename dot_helper::op_mul op_mul; typedef typename dot_helper::op_add op_add; typedef typename et::detail::VectorAccumulateUnroller< op_add,op_mul,LeftT,RightT>::template Eval<0, Len-1, (Len <= CML_VECTOR_DOT_UNROLL_LIMIT)> Unroller; /* Note: Len is the array size, so Len-1 is the last element. */ /* Now, call the unroller: */ return Unroller()(left,right); } /** Use a loop to compute the dot product for dynamic arrays. * * @note This should only be called for vectors. * * @sa cml::dot */ template<typename LeftT, typename RightT> inline typename DotPromote<LeftT,RightT>::promoted_scalar UnrollDot(const LeftT& left, const RightT& right, dynamic_size_tag) { /* Shorthand: */ typedef DotPromote<LeftT,RightT> dot_helper; typedef et::ExprTraits<LeftT> left_traits; typedef et::ExprTraits<RightT> right_traits; typedef typename dot_helper::op_mul op_mul; typedef typename dot_helper::op_add op_add; /* Record the return type: */ typedef typename dot_helper::promoted_scalar sum_type; /* Verify expression sizes: */ const size_t N = et::CheckedSize(left,right,dynamic_size_tag()); /* Initialize the sum. Left and right must be vector expressions, so * it's okay to use array notation here: */ sum_type sum(op_mul().apply(left[0],right[0])); for(size_t i = 1; i < N; ++i) { /* XXX This might not be optimized properly by some compilers. * but to do anything else requires changing the requirements * of a scalar operator, or requires defining a new class of scalar * <op>= operators. */ sum = op_add().apply(sum, op_mul().apply(left[i], right[i])); /* Note: we don't need get(), since both arguments are required to * be vector expressions. */ } return sum; } /** For cross(): compile-time check for a 3D vector. */ template<typename VecT> inline void Require3D(const VecT&, fixed_size_tag) { CML_STATIC_REQUIRE_M( ((size_t)VecT::array_size == 3), cross_expects_3D_vector_args_error); } /** For cross(): run-time check for a 3D vector. */ template<typename VecT> inline void Require3D(const VecT& v, dynamic_size_tag) { et::GetCheckedSize<VecT,VecT,dynamic_size_tag>() .equal_or_fail(v.size(),size_t(3)); } /** For perp_dot(): compile-time check for a 2D vector. */ template<typename VecT> inline void Require2D(const VecT& v, fixed_size_tag) { CML_STATIC_REQUIRE_M( ((size_t)VecT::array_size == 2), perp_dot_expects_2D_vector_args_error); } /** For perp_dot(): run-time check for a 2D vector. */ template<typename VecT> inline void Require2D(const VecT& v, dynamic_size_tag) { et::GetCheckedSize<VecT,VecT,dynamic_size_tag>() .equal_or_fail(v.size(),size_t(2)); } } // namespace detail /** Vector dot (inner) product implementation. */ template<typename LeftT, typename RightT> inline typename detail::DotPromote<LeftT,RightT>::promoted_scalar dot(const LeftT& left, const RightT& right) { /* Shorthand: */ typedef detail::DotPromote<LeftT,RightT> dot_helper; typedef et::ExprTraits<LeftT> left_traits; typedef et::ExprTraits<RightT> right_traits; typedef typename left_traits::result_type left_type; typedef typename right_traits::result_type right_type; typedef typename left_traits::size_tag left_size; typedef typename right_traits::size_tag right_size; /* dot() requires vector expressions: */ CML_STATIC_REQUIRE_M( (et::VectorExpressions<LeftT,RightT>::is_true), dot_expects_vector_args_error); /* Note: parens are required here so that the preprocessor ignores the * commas: */ /* Figure out the unroller to use (fixed or dynamic): */ typedef typename et::VectorPromote< left_type, right_type>::temporary_type promoted_vector; typedef typename promoted_vector::size_tag size_tag; /* Call unroller: */ return detail::UnrollDot(left,right,size_tag()); } /** perp_dot() */ template<typename LeftT, typename RightT> inline typename detail::DotPromote<LeftT,RightT>::promoted_scalar perp_dot(const LeftT& left, const RightT& right) { /* Shorthand: */ typedef et::ExprTraits<LeftT> left_traits; typedef et::ExprTraits<RightT> right_traits; typedef typename left_traits::result_tag left_result; typedef typename right_traits::result_tag right_result; /* perp_dot() requires vector expressions: */ CML_STATIC_REQUIRE_M( (same_type<left_result, et::vector_result_tag>::is_true && same_type<right_result, et::vector_result_tag>::is_true), perp_dot_expects_vector_args_error); /* Note: parens are required here so that the preprocessor ignores the * commas. */ /* Make sure arguments are 2D vectors: */ detail::Require2D(left, typename left_traits::size_tag()); detail::Require2D(right, typename right_traits::size_tag()); /* Get result type: */ typedef typename detail::DotPromote< LeftT,RightT>::promoted_scalar result_type; /* Compute and return: */ return result_type(left[0]*right[1]-left[1]*right[0]); } template<typename LeftT, typename RightT> inline typename detail::CrossPromote<LeftT,RightT>::promoted_vector cross(const LeftT& left, const RightT& right) { /* Shorthand: */ typedef et::ExprTraits<LeftT> left_traits; typedef et::ExprTraits<RightT> right_traits; typedef typename left_traits::result_tag left_result; typedef typename right_traits::result_tag right_result; /* outer() requires vector expressions: */ CML_STATIC_REQUIRE_M( (same_type<left_result, et::vector_result_tag>::is_true && same_type<right_result, et::vector_result_tag>::is_true), cross_expects_vector_args_error); /* Note: parens are required here so that the preprocessor ignores the * commas. */ /* Make sure arguments are 3D vectors: */ detail::Require3D(left, typename left_traits::size_tag()); detail::Require3D(right, typename right_traits::size_tag()); /* Get result type: */ typedef typename detail::CrossPromote< LeftT,RightT>::promoted_vector result_type; /* Now, compute and return the cross product: */ result_type result( left[1]*right[2] - left[2]*right[1], left[2]*right[0] - left[0]*right[2], left[0]*right[1] - left[1]*right[0] ); return result; } /** Return the triple product of three 3D vectors. * * No checking is done here, as dot() and cross() will catch any size or * type errors. */ template < class VecT_1, class VecT_2, class VecT_3 > typename detail::DotPromote< VecT_1, typename detail::CrossPromote< VecT_2, VecT_3 >::promoted_vector >::promoted_scalar triple_product(const VecT_1& v1, const VecT_2& v2, const VecT_3& v3) { return dot(v1,cross(v2,v3)); } template<typename LeftT, typename RightT> inline typename detail::OuterPromote<LeftT,RightT>::promoted_matrix outer(const LeftT& left, const RightT& right) { /* Shorthand: */ typedef et::ExprTraits<LeftT> left_traits; typedef et::ExprTraits<RightT> right_traits; typedef typename left_traits::result_tag left_result; typedef typename right_traits::result_tag right_result; /* outer() requires vector expressions: */ CML_STATIC_REQUIRE_M( (same_type<left_result, et::vector_result_tag>::is_true && same_type<right_result, et::vector_result_tag>::is_true), dot_expects_vector_args_error); /* Note: parens are required here so that the preprocessor ignores the * commas. */ /* Create a matrix with the right size (resize() is a no-op for * fixed-size matrices): */ typename detail::OuterPromote<LeftT,RightT>::promoted_matrix C; cml::et::detail::Resize(C, left.size(), right.size()); /* Now, compute the outer product: */ for(size_t i = 0; i < left.size(); ++i) { for(size_t j = 0; j < right.size(); ++j) { C(i,j) = left[i]*right[j]; /* Note: both arguments are vectors, so array notation * is okay here. */ } } return C; } } // namespace cml #endif // ------------------------------------------------------------------------- // vim:ft=cpp
prophecy/Pillar
Dependencies/Include/Rocket/Core/ElementUtilities.h
/* * This source file is part of libRocket, the HTML/CSS Interface Middleware * * For the latest information, see http://www.librocket.com * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #ifndef ROCKETCOREELEMENTUTILITIES_H #define ROCKETCOREELEMENTUTILITIES_H #include "Header.h" #include "Box.h" #include "WString.h" #include "Types.h" namespace Rocket { namespace Core { class Context; class FontFaceHandle; class RenderInterface; /** Utility functions for dealing with elements. @author <NAME> */ class ROCKETCORE_API ElementUtilities { public: enum PositionAnchor { TOP = 1 << 0, BOTTOM = 1 << 1, LEFT = 1 << 2, RIGHT = 1 << 3, TOP_LEFT = TOP | LEFT, TOP_RIGHT = TOP | RIGHT, BOTTOM_LEFT = BOTTOM | LEFT, BOTTOM_RIGHT = BOTTOM | RIGHT }; /// Get the element with the given id. /// @param[in] root_element First element to check. /// @param[in] id ID of the element to look for. static Element* GetElementById(Element* root_element, const String& id); /// Get all elements with the given tag. /// @param[out] elements Resulting elements. /// @param[in] root_element First element to check. /// @param[in] tag Tag to search for. static void GetElementsByTagName(ElementList& elements, Element* root_element, const String& tag); /// Get all elements with the given class set on them. /// @param[out] elements Resulting elements. /// @param[in] root_element First element to check. /// @param[in] tag Class name to search for. static void GetElementsByClassName(ElementList& elements, Element* root_element, const String& class_name); /// Returns an element's font face. /// @param[in] element The element to determine the font face for. /// @return The element's font face. This will be NULL if no valid RCSS font styles have been set up for this element. static FontFaceHandle* GetFontFaceHandle(Element* element); /// Returns an element's font size, if it has a font defined. /// @param[in] element The element to determine the font size for. /// @return The font size as determined by the element's font, or 0 if it has no font specified. static int GetFontSize(Element* element); /// Returns an element's line height, if it has a font defined. /// @param[in] element The element to determine the line height for. /// @return The line height as specified by the element's font and line height styles. static int GetLineHeight(Element* element); /// Returns the width of a string rendered within the context of the given element. /// @param[in] element The element to measure the string from. /// @param[in] string The string to measure. /// @return The string width, in pixels. static int GetStringWidth(Element* element, const WString& string); /// Bind and instance all event attributes on the given element onto the element /// @param element Element to bind events on static void BindEventAttributes(Element* element); /// Generates the clipping region for an element. /// @param[out] clip_origin The origin, in context coordinates, of the origin of the element's clipping window. /// @param[out] clip_dimensions The size, in context coordinates, of the element's clipping window. /// @param[in] element The element to generate the clipping region for. /// @return True if a clipping region exists for the element and clip_origin and clip_window were set, false if not. static bool GetClippingRegion(Vector2i& clip_origin, Vector2i& clip_dimensions, Element* element); /// Sets the clipping region from an element and its ancestors. /// @param[in] element The element to generate the clipping region from. /// @param[in] context The context of the element; if this is not supplied, it will be derived from the element. /// @return The visibility of the given element within its clipping region. static bool SetClippingRegion(Element* element, Context* context = NULL); /// Applies the clip region from the render interface to the renderer /// @param[in] context The context to read the clip region from /// @param[in] render_interface The render interface to update. static void ApplyActiveClipRegion(Context* context, RenderInterface* render_interface); /// Formats the contents of an element. This does not need to be called for ordinary elements, but can be useful /// for non-DOM elements of custom elements. /// @param[in] element The element to lay out. /// @param[in] containing_block The size of the element's containing block. static bool FormatElement(Element* element, const Vector2f& containing_block); /// Generates the box for an element. /// @param[out] box The box to be built. /// @param[in] containing_block The dimensions of the content area of the block containing the element. /// @param[in] element The element to build the box for. /// @param[in] inline_element True if the element is placed in an inline context, false if not. static void BuildBox(Box& box, const Vector2f& containing_block, Element* element, bool inline_element = false); /// Sizes and positions an element within its parent. Any relative values will be evaluated against the size of the /// element parent's content area. /// @param element[in] The element to size and position. /// @param offset[in] The offset of the element inside its parent's content area. static bool PositionElement(Element* element, const Vector2f& offset); /// Sizes an element, and positions it within its parent offset from the borders of its content area. Any relative /// values will be evaluated against the size of the element parent's content area. /// @param element[in] The element to size and position. /// @param offset[in] The offset from the parent's borders. /// @param anchor[in] Defines which corner or edge the border is to be positioned relative to. static bool PositionElement(Element* element, const Vector2f& offset, PositionAnchor anchor); }; } } #endif
prophecy/Pillar
Samples/PillarTestSolution/EmptyProject/WonderApp.h
#ifndef __WONDER_APP_H__ #define __WONDER_APP_H__ #include "IApplication.h" class WonderApp : public IApplication { virtual void Create(); virtual void Destroy(); virtual void Start(); virtual void Stop(); virtual void Resume(); virtual void Pause(); }; #endif // __WONDER_APP_H__
prophecy/Pillar
Dependencies/Include/SDL_image/showimage.c
#include "SDL.h" #include "SDL_image.h" #define bool char #define true 1 #define false 0 int main(int argc, char ** argv) { bool quit = false; SDL_Event event; SDL_Init(SDL_INIT_VIDEO); int imgInitCode = IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG); SDL_Window * window = SDL_CreateWindow("SDL2 Displaying Image", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0); SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0); //SDL_Surface * image = SDL_LoadBMP("enemy.bmp"); SDL_Surface * image = IMG_Load("enemy.bmp"); //SDL_Surface * image = IMG_Load("nice.jpg"); //SDL_Surface * image = IMG_Load("taylor.jpg"); //SDL_Surface * image = IMG_Load("sprite.png"); SDL_Texture * texture = SDL_CreateTextureFromSurface(renderer, image); while (!quit) { SDL_WaitEvent(&event); switch(event.type) { case SDL_QUIT: quit = true; break; } SDL_RenderCopy(renderer, texture, NULL, NULL); SDL_RenderPresent(renderer); } SDL_DestroyTexture(texture); SDL_FreeSurface(image); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); IMG_Quit(); SDL_Quit(); return 0; }
prophecy/Pillar
Dependencies/Include/cml/core/meta/if.h
<reponame>prophecy/Pillar /* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief */ #ifndef meta_if_h #define meta_if_h #include <cml/core/meta/common.h> namespace cml { /** Select argument type based upon truth value. */ template<bool yn, typename TrueT, typename FalseT> struct select_if; /** Result is TrueT if true. */ template<typename TrueT, typename FalseT> struct select_if<true,TrueT,FalseT> { typedef TrueT result; enum { is_true = true }; }; /** Result is FalseT if false. */ template<typename TrueT, typename FalseT> struct select_if<false,TrueT,FalseT> { typedef FalseT result; enum { is_true = false }; }; } // namespace cml #endif // ------------------------------------------------------------------------- // vim:ft=cpp
prophecy/Pillar
Dependencies/Include/cml/matrix/class_ops.h
<gh_stars>10-100 /* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief * * @note GCC4 requires a copy constructor to elide---it won't elide a * compiler-generated copy constructor! */ #ifndef matrix_class_ops_h #define matrix_class_ops_h #if defined(_MSC_VER) && _MSC_VER < 1400 #pragma warning(disable:4003) // XXX Horrible hack to turn off warnings about "not enough actual params" // for the macros below. #endif /* This is to circumvent the problem of commas in a macro argument. It's * used to instantiate CML_ACCUMULATED_MATRIX_MULT: */ #define TEMPLATED_MATRIX_MACRO matrix<E,AT,BO,L> /* XXX HACK!!! This is a hack to resize in the assign() functions only when * auto resizing is turned off. */ #if !defined(CML_MATRIX_RESIZE_ON_ASSIGNMENT) #define _DO_MATRIX_SET_RESIZE(_R_,_C_) cml::et::detail::Resize(*this,_R_,_C_) #else #define _DO_MATRIX_SET_RESIZE(_R_,_C_) #endif /** Set a matrix from 2x2 values. * * The layout assumed for the values is that of the matrix being assigned. */ #define CML_ASSIGN_MAT_22 \ matrix_type& \ set( \ ELEMENT_ARG_TYPE e00, ELEMENT_ARG_TYPE e01, \ ELEMENT_ARG_TYPE e10, ELEMENT_ARG_TYPE e11 \ ) \ { \ _DO_MATRIX_SET_RESIZE(2,2); \ /* This is overkill, but simplifies size checking: */ \ value_type v[2][2] = {{e00,e01},{e10,e11}}; \ typedef et::OpAssign<Element,Element> OpT; \ typedef const value_type element; \ cml::matrix<element, external<2,2>, basis_orient, row_major> \ src(&v[0][0]); \ et::UnrollAssignment<OpT>(*this,src); \ return *this; \ } /** Create a matrix from 3x3 values. * * The layout assumed for the values is that of the matrix being assigned. */ #define CML_ASSIGN_MAT_33 \ matrix_type& \ set( \ ELEMENT_ARG_TYPE e00, ELEMENT_ARG_TYPE e01, ELEMENT_ARG_TYPE e02, \ ELEMENT_ARG_TYPE e10, ELEMENT_ARG_TYPE e11, ELEMENT_ARG_TYPE e12, \ ELEMENT_ARG_TYPE e20, ELEMENT_ARG_TYPE e21, ELEMENT_ARG_TYPE e22 \ ) \ { \ _DO_MATRIX_SET_RESIZE(3,3); \ /* This is overkill, but simplifies size checking: */ \ value_type v[3][3] = { \ {e00,e01,e02}, \ {e10,e11,e12}, \ {e20,e21,e22} \ }; \ typedef et::OpAssign<Element,Element> OpT; \ typedef const value_type element; \ cml::matrix<element, external<3,3>, basis_orient, row_major> \ src(&v[0][0]); \ et::UnrollAssignment<OpT>(*this,src); \ return *this; \ } /** Create a matrix from 4x4 values. * * The layout assumed for the values is that of the matrix being assigned. */ #define CML_ASSIGN_MAT_44 \ matrix_type& \ set( \ ELEMENT_ARG_TYPE e00, ELEMENT_ARG_TYPE e01, \ ELEMENT_ARG_TYPE e02, ELEMENT_ARG_TYPE e03, \ ELEMENT_ARG_TYPE e10, ELEMENT_ARG_TYPE e11, \ ELEMENT_ARG_TYPE e12, ELEMENT_ARG_TYPE e13, \ ELEMENT_ARG_TYPE e20, ELEMENT_ARG_TYPE e21, \ ELEMENT_ARG_TYPE e22, ELEMENT_ARG_TYPE e23, \ ELEMENT_ARG_TYPE e30, ELEMENT_ARG_TYPE e31, \ ELEMENT_ARG_TYPE e32, ELEMENT_ARG_TYPE e33 \ ) \ { \ _DO_MATRIX_SET_RESIZE(4,4); \ /* This is overkill, but simplifies size checking: */ \ value_type v[4][4] = { \ {e00,e01,e02,e03}, \ {e10,e11,e12,e13}, \ {e20,e21,e22,e23}, \ {e30,e31,e32,e33} \ }; \ typedef et::OpAssign<Element,Element> OpT; \ typedef const value_type element; \ cml::matrix<element, external<4,4>, basis_orient, row_major> \ src(&v[0][0]); \ et::UnrollAssignment<OpT>(*this,src); \ return *this; \ } /** Create a matrix from 2x2 values. * * The layout assumed for the values is that of the matrix being assigned. */ #define CML_CONSTRUCT_MAT_22 \ matrix( \ ELEMENT_ARG_TYPE e00, ELEMENT_ARG_TYPE e01, \ ELEMENT_ARG_TYPE e10, ELEMENT_ARG_TYPE e11 \ ) \ { \ set( \ e00,e01, \ e10,e11 \ ); \ } /** Create a matrix from 3x3 values. * * The layout assumed for the values is that of the matrix being assigned. */ #define CML_CONSTRUCT_MAT_33 \ matrix( \ ELEMENT_ARG_TYPE e00, ELEMENT_ARG_TYPE e01, ELEMENT_ARG_TYPE e02, \ ELEMENT_ARG_TYPE e10, ELEMENT_ARG_TYPE e11, ELEMENT_ARG_TYPE e12, \ ELEMENT_ARG_TYPE e20, ELEMENT_ARG_TYPE e21, ELEMENT_ARG_TYPE e22 \ ) \ { \ set( \ e00,e01,e02, \ e10,e11,e12, \ e20,e21,e22 \ ); \ } /** Create a matrix from 4x4 values. * * The layout assumed for the values is that of the matrix being assigned. */ #define CML_CONSTRUCT_MAT_44 \ matrix( \ ELEMENT_ARG_TYPE e00, ELEMENT_ARG_TYPE e01, \ ELEMENT_ARG_TYPE e02, ELEMENT_ARG_TYPE e03, \ ELEMENT_ARG_TYPE e10, ELEMENT_ARG_TYPE e11, \ ELEMENT_ARG_TYPE e12, ELEMENT_ARG_TYPE e13, \ ELEMENT_ARG_TYPE e20, ELEMENT_ARG_TYPE e21, \ ELEMENT_ARG_TYPE e22, ELEMENT_ARG_TYPE e23, \ ELEMENT_ARG_TYPE e30, ELEMENT_ARG_TYPE e31, \ ELEMENT_ARG_TYPE e32, ELEMENT_ARG_TYPE e33 \ ) \ { \ set( \ e00,e01,e02,e03, \ e10,e11,e12,e13, \ e20,e21,e22,e23, \ e30,e31,e32,e33 \ ); \ } /** Copy-construct a matrix from a fixed-size array of values. */ #define CML_MAT_COPY_FROM_FIXED_ARRAY(_R_,_C_) \ matrix(const value_type m[_R_][_C_]) { \ typedef et::OpAssign<Element,Element> OpT; \ cml::matrix<const value_type, external<_R_,_C_>, \ basis_orient, row_major> src(&m[0][0]); \ et::UnrollAssignment<OpT>(*this,src); \ } /** Copy-construct a matrix from a runtime-sized array of values. */ #define CML_MAT_COPY_FROM_ARRAY(_add_) \ matrix(const value_type* const v, size_t R, size_t C) _add_ { \ typedef et::OpAssign<Element,Element> OpT; \ cml::matrix<value_type, external<>, basis_orient, \ row_major > src(const_cast<value_type*>(v),R,C); \ et::UnrollAssignment<OpT>(*this,src); \ } /** Copy this matrix from another using the given elementwise op. * * @internal This is required for GCC4, since it won't elide the default * copy constructor. */ #define CML_MAT_COPY_FROM_MATTYPE \ matrix(const matrix_type& m) : array_type() { \ typedef et::OpAssign <Element,Element> OpT; \ et::UnrollAssignment<OpT>(*this,m); \ } /** Copy this matrix from another using the given elementwise op. * * This allows copies from arbitrary matrix types. */ #define CML_MAT_COPY_FROM_MAT \ template<typename E, class AT, typename BO, typename L> \ matrix(const TEMPLATED_MATRIX_MACRO& m) { \ typedef et::OpAssign <Element,E> OpT; \ et::UnrollAssignment<OpT>(*this,m); \ } /** Declare a function to copy this matrix from a matrix expression. */ #define CML_MAT_COPY_FROM_MATXPR \ template<class XprT> \ matrix(MATXPR_ARG_TYPE e) { \ /* Verify that a promotion exists at compile time: */ \ typedef typename et::MatrixPromote< \ matrix_type, typename XprT::result_type>::type result_type; \ typedef typename XprT::value_type src_value_type; \ typedef et::OpAssign <Element,src_value_type> OpT; \ et::UnrollAssignment<OpT>(*this,e); \ } #if defined(CML_USE_GENERATED_MATRIX_ASSIGN_OP) #define CML_MAT_ASSIGN_FROM_MATTYPE #else /** Assign from the same matrix type. * * @param m the matrix to copy from. * * @note This is required for GCC4, otherwise it generates a slow * assignment operator using memcpy. * * @note ICC9/Linux-x86 seems to prefer its own assignment operator (need * to figure out why). */ #define CML_MAT_ASSIGN_FROM_MATTYPE \ matrix_type& operator=(const matrix_type& m) { \ typedef et::OpAssign<Element,Element> OpT; \ et::UnrollAssignment<OpT>(*this,m); \ return *this; \ } #endif /** Assign this matrix from another using the given elementwise op. * * This allows assignment from arbitrary matrix types. * * @param _op_ the operator (e.g. +=) * @param _op_name_ the op functor (e.g. et::OpAssign) */ #define CML_MAT_ASSIGN_FROM_MAT(_op_, _op_name_) \ template<typename E, class AT, typename BO, typename L> matrix_type& \ operator _op_ (const TEMPLATED_MATRIX_MACRO& m) { \ typedef _op_name_ <Element,E> OpT; \ et::UnrollAssignment<OpT>(*this,m); \ return *this; \ } /** Declare a function to assign this matrix from a matrix expression. * * @param _op_ the operator (e.g. +=) * @param _op_name_ the op functor (e.g. et::OpAssign) */ #define CML_MAT_ASSIGN_FROM_MATXPR(_op_, _op_name_) \ template<class XprT> matrix_type& \ operator _op_ (MATXPR_ARG_TYPE e) { \ /* Verify that a promotion exists at compile time: */ \ typedef typename et::MatrixPromote< \ matrix_type, typename XprT::result_type>::type result_type; \ typedef typename XprT::value_type src_value_type; \ typedef _op_name_ <Element,src_value_type> OpT; \ et::UnrollAssignment<OpT>(*this,e); \ return *this; \ } /** Declare a function to assign this matrix from a scalar. * * @param _op_ the operator (e.g. +=) * @param _op_name_ the op functor (e.g. et::OpAssign) * * @internal This shouldn't be used for ops, like +=, which aren't * defined in vector algebra. */ #define CML_MAT_ASSIGN_FROM_SCALAR(_op_, _op_name_) \ matrix_type& operator _op_ (ELEMENT_ARG_TYPE s) { \ typedef _op_name_ <Element,value_type> OpT; \ et::UnrollAssignment<OpT>(*this,s); \ return *this; \ } /** Accumulated matrix multiplication. * * @throws std::invalid_argument if the matrices are not square. */ #define CML_ACCUMULATED_MATRIX_MULT(_arg_type_) \ matrix_type& operator*=(_arg_type_ m) { \ typedef typename et::MatrixPromote< \ matrix_type, _arg_type_>::type result_type; \ cml::et::CheckedSquare(*this, typename result_type::size_tag()); \ return (*this = (*this)*m); \ } /* These should only be used for testing: */ #define CML_MATRIX_BRACE_OPERATORS \ template<class Matrix> struct row_ref { \ typedef typename Matrix::reference reference; \ reference operator[](size_t col) { return m(row,col); } \ Matrix& m; \ size_t row; \ }; \ \ template<class Matrix> struct const_row_ref { \ typedef typename Matrix::const_reference const_reference; \ const_reference operator[](size_t col) const { return m(row,col); } \ const Matrix& m; \ size_t row; \ }; \ \ row_ref<matrix_type> operator[](size_t row) { \ row_ref<matrix_type> ref = { *this, row }; return ref; \ } \ \ const_row_ref<matrix_type> operator[](size_t row) const { \ const_row_ref<matrix_type> ref = { *this, row }; return ref; \ } #endif // ------------------------------------------------------------------------- // vim:ft=cpp
prophecy/Pillar
Dependencies/Include/cml/vector/vector_ops.h
/* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief Defines vector operators. */ #ifndef vector_ops_h #define vector_ops_h #include <cml/et/scalar_ops.h> #include <cml/vector/vector_expr.h> #include <cml/vector/vecop_macros.h> namespace cml { CML_VEC_UNIOP( operator+, et::OpPos) CML_VECXPR_UNIOP( operator+, et::OpPos) CML_VEC_UNIOP( operator-, et::OpNeg) CML_VECXPR_UNIOP( operator-, et::OpNeg) CML_VEC_VEC_BINOP( operator+, et::OpAdd) CML_VECXPR_VEC_BINOP( operator+, et::OpAdd) CML_VEC_VECXPR_BINOP( operator+, et::OpAdd) CML_VECXPR_VECXPR_BINOP( operator+, et::OpAdd) CML_VEC_VEC_BINOP( operator-, et::OpSub) CML_VECXPR_VEC_BINOP( operator-, et::OpSub) CML_VEC_VECXPR_BINOP( operator-, et::OpSub) CML_VECXPR_VECXPR_BINOP( operator-, et::OpSub) CML_VEC_SCALAR_BINOP( operator*, et::OpMul) CML_SCALAR_VEC_BINOP( operator*, et::OpMul) CML_VECXPR_SCALAR_BINOP( operator*, et::OpMul) CML_SCALAR_VECXPR_BINOP( operator*, et::OpMul) CML_VEC_SCALAR_BINOP( operator/, et::OpDiv) CML_VECXPR_SCALAR_BINOP( operator/, et::OpDiv) } // namespace cml #endif // ------------------------------------------------------------------------- // vim:ft=cpp
prophecy/Pillar
Src/Foundation/Utility/Utility.h
/* * This source file is part of Wonderland, the C++ Cross-platform middleware for game * * For the latest information, see https://github.com/prophecy/Wonderland * * The MIT License (MIT) * Copyright (c) 2015 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #ifndef __UTILITY_H__ #define __UTILITY_H__ // Math #include <cml/cml.h> typedef cml::vector2i vector2s; typedef cml::vector2i point2s; typedef cml::vector2i size2s; struct rect2s { point2s origin; size2s size; }; typedef cml::vector3i vector3s; typedef cml::vector3i point3s; typedef cml::vector3i size3s; struct rect3s { point3s origin; size3s size; }; typedef cml::vector2f vector2f; typedef cml::vector2f point2f; typedef cml::vector2f size2f; struct rect2f { point2f origin; size2f size; }; typedef cml::vector3f vector3f; typedef cml::vector3f point3f; typedef cml::vector3f size3f; struct rect3f { point3f origin; size3f size; }; // Types #include "Types.h" // Memory #define ALLOC(T) Memory::GetPtr()->Alloc<T>() #define FREE(h) Memory::GetPtr()->Free(h) #include "Memory/Memory.h" #include "Memory/WonderPtr.h" // Log #include "Log/Log.h" template<class T> std::string ToStdString(T i) { std::stringstream ss; std::string s; ss << i; s = ss.str(); return s; } #define TO_STR(var) ToStdString(var) #define APPEND_STR(str) + std::string(str) // String concat #define CONCAT(a,b) a ## b #define CONCAT_SPACE(str1,str2) #str1 " " #str2 #define MACRO_STR(str) #str #endif // __UTILITY_H__
prophecy/Pillar
Dependencies/Include/cml/mathlib/typedef.h
<gh_stars>10-100 /* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief */ #ifndef typedef_h #define typedef_h #include <cml/vector.h> #include <cml/matrix.h> #include <cml/quaternion.h> #include <cml/constants.h> #include <cml/mathlib/epsilon.h> namespace cml { /* fixed-size vectors */ typedef vector< int, fixed<2> > vector2i; typedef vector< float, fixed<2> > vector2f; typedef vector< double, fixed<2> > vector2d; typedef vector< int, fixed<3> > vector3i; typedef vector< float, fixed<3> > vector3f; typedef vector< double, fixed<3> > vector3d; typedef vector< int, fixed<4> > vector4i; typedef vector< float, fixed<4> > vector4f; typedef vector< double, fixed<4> > vector4d; /* fixed-size matrices */ typedef matrix< int, fixed<2,2> > matrix22i; typedef matrix< float, fixed<2,2> > matrix22f; typedef matrix< double, fixed<2,2> > matrix22d; typedef matrix< int, fixed<2,2>, row_basis, row_major > matrix22i_r; typedef matrix< int, fixed<2,2>, col_basis, col_major > matrix22i_c; typedef matrix< float, fixed<2,2>, row_basis, row_major > matrix22f_r; typedef matrix< float, fixed<2,2>, col_basis, col_major > matrix22f_c; typedef matrix< double, fixed<2,2>, row_basis, row_major > matrix22d_r; typedef matrix< double, fixed<2,2>, col_basis, col_major > matrix22d_c; typedef matrix< int, fixed<3,3> > matrix33i; typedef matrix< float, fixed<3,3> > matrix33f; typedef matrix< double, fixed<3,3> > matrix33d; typedef matrix< int, fixed<3,3>, row_basis, row_major > matrix33i_r; typedef matrix< int, fixed<3,3>, col_basis, col_major > matrix33i_c; typedef matrix< float, fixed<3,3>, row_basis, row_major > matrix33f_r; typedef matrix< float, fixed<3,3>, col_basis, col_major > matrix33f_c; typedef matrix< double, fixed<3,3>, row_basis, row_major > matrix33d_r; typedef matrix< double, fixed<3,3>, col_basis, col_major > matrix33d_c; typedef matrix< int, fixed<4,4> > matrix44i; typedef matrix< float, fixed<4,4> > matrix44f; typedef matrix< double, fixed<4,4> > matrix44d; typedef matrix< int, fixed<4,4>, row_basis, row_major > matrix44i_r; typedef matrix< int, fixed<4,4>, col_basis, col_major > matrix44i_c; typedef matrix< float, fixed<4,4>, row_basis, row_major > matrix44f_r; typedef matrix< float, fixed<4,4>, col_basis, col_major > matrix44f_c; typedef matrix< double, fixed<4,4>, row_basis, row_major > matrix44d_r; typedef matrix< double, fixed<4,4>, col_basis, col_major > matrix44d_c; typedef matrix< int, fixed<3,2>, row_basis, row_major > matrix32i_r; typedef matrix< float, fixed<3,2>, row_basis, row_major > matrix32f_r; typedef matrix< double, fixed<3,2>, row_basis, row_major > matrix32d_r; typedef matrix< int, fixed<2,3>, col_basis, col_major > matrix23i_c; typedef matrix< float, fixed<2,3>, col_basis, col_major > matrix23f_c; typedef matrix< double, fixed<2,3>, col_basis, col_major > matrix23d_c; typedef matrix< int, fixed<4,3>, row_basis, row_major > matrix43i_r; typedef matrix< float, fixed<4,3>, row_basis, row_major > matrix43f_r; typedef matrix< double, fixed<4,3>, row_basis, row_major > matrix43d_r; typedef matrix< int, fixed<3,4>, col_basis, col_major > matrix34i_c; typedef matrix< float, fixed<3,4>, col_basis, col_major > matrix34f_c; typedef matrix< double, fixed<3,4>, col_basis, col_major > matrix34d_c; /* quaternions */ typedef quaternion<float, fixed<>,vector_first,negative_cross> quaternionf_n; typedef quaternion<float, fixed<>,vector_first,positive_cross> quaternionf_p; typedef quaternion<double,fixed<>,vector_first,negative_cross> quaterniond_n; typedef quaternion<double,fixed<>,vector_first,positive_cross> quaterniond_p; typedef quaternion<float> quaternionf; typedef quaternion<double> quaterniond; /* dynamically resizable vectors */ typedef vector< int, dynamic<> > vectori; typedef vector< float, dynamic<> > vectorf; typedef vector< double, dynamic<> > vectord; /* dynamically resizable matrices */ typedef matrix< int, dynamic<> > matrixi; typedef matrix< float, dynamic<> > matrixf; typedef matrix< double, dynamic<> > matrixd; typedef matrix< int, dynamic<>, row_basis, row_major > matrixi_r; typedef matrix< int, dynamic<>, col_basis, col_major > matrixi_c; typedef matrix< float, dynamic<>, row_basis, row_major > matrixf_r; typedef matrix< float, dynamic<>, col_basis, col_major > matrixf_c; typedef matrix< double, dynamic<>, row_basis, row_major > matrixd_r; typedef matrix< double, dynamic<>, col_basis, col_major > matrixd_c; /* constants */ typedef constants<float> constantsf; typedef constants<double> constantsd; /* epsilon/tolerance values (placeholder) */ typedef epsilon<float> epsilonf; typedef epsilon<double> epsilond; } // namespace cml #endif
prophecy/Pillar
Src/Foundation/Utility/Memory/WonderPtr.h
#/* * This source file is part of Wonderland, the C++ Cross-platform middleware for game * * For the latest information, see https://github.com/prophecy/Wonderland * * The MIT License (MIT) * Copyright (c) 2015 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #ifndef __WONDER_PTR_H__ #define __WONDER_PTR_H__ #include "MemoryHandle.h" #include "Utility/Utility.h" #include "Utility/Types.h" template <typename T> class WonderPtr { private: MemoryHandle<T>* handle; // The handle can be set by operator overloading "=" public: WonderPtr<T>() { // Set handle to NULL addr data; data = 0x0; memcpy((u8*)this, (u8*)&data, sizeof(WonderPtr)); } WonderPtr<T>(MemoryHandle<T>* handle) { this->handle = handle; } template <typename From> WonderPtr<T>(From& from) { memcpy((u8*)this, (u8*)&from, sizeof( WonderPtr)); } void Alloc() { handle = ALLOC(T); } void Free() { FREE(handle); } bool IsValid() { return this->handle != NULL; } T* Ptr() { return handle->ptr; } template <typename To> WonderPtr<To> To() { WonderPtr<To> to; to = handle; return to; } // -------------------------------------------------------------------------- // Overloaded operators // Access to handle T* operator->() { return handle->ptr; } template <typename From> WonderPtr<T> operator= (From& from) { memcpy((u8*)this, (u8*)&from, sizeof(WonderPtr)); return *((WonderPtr<T>*)&from); } template <typename From> inline bool operator==(const From& from) { WonderPtr<T> ptr; ptr = from; return (addr)this->handle == (addr)ptr.handle; } template <typename From> inline bool operator!=(const From& from) { WonderPtr<T> ptr; ptr = from; return (addr)this->handle != (addr)ptr.handle; } }; #endif // __WONDER_PTR_H__
prophecy/Pillar
Src/Foundation/IEntity.h
/* * This source file is part of Wonderland, the C++ Cross-platform middleware for game * * For the latest information, see https://github.com/prophecy/Wonderland * * The MIT License (MIT) * Copyright (c) 2015 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #ifndef __I_ENTITY_H__ #define __I_ENTITY_H__ #include "IElement.h" #include "ITask.h" class IEntity : public IElement { public: static RTTI rtti; public: IEntity() { isVisible = true; } void BindTask(WonderPtr<ITask> task) { WonderPtr<IEntity> ent = Memory::GetPtr()->GetHandle<IEntity>((addr)this); task->entities.push_back(ent); tasks.push_back(task); } std::vector<WonderPtr<IEntity>> entities; std::vector<WonderPtr<ITask>> tasks; point2f position; point2f pivot; f32 radian; f32 scale; size2f size; bool isVisible; }; #endif // __I_ENTITY_H__
prophecy/Pillar
Dependencies/Include/cml/mathlib/vector_transform.h
/* -*- C++ -*- ------------------------------------------------------------ Copyright (c) 2007 <NAME> and <NAME> http://cmldev.net/ The Configurable Math Library (CML) is distributed under the terms of the Boost Software License, v1.0 (see cml/LICENSE for details). *-----------------------------------------------------------------------*/ /** @file * @brief */ #ifndef vector_transform_h #define vector_transform_h #include <cml/mathlib/checking.h> /* Functions for transforming a vector, representing a geometric point or * or vector, by an affine transfom. * * Note: This functionality may be provisional, depending on what architecture * we settle on for the higher-level math functions. If we do keep these * functions, then this code may ending up being a placeholder for expression * template code. */ namespace cml { /** A fixed-size temporary 4D vector */ #define TEMP_VEC4 vector< \ typename et::ScalarPromote< \ typename MatT::value_type, \ typename VecT::value_type \ >::type, \ fixed<4> \ > /** A fixed-size temporary 3D vector */ #define TEMP_VEC3 vector< \ typename et::ScalarPromote< \ typename MatT::value_type, \ typename VecT::value_type \ >::type, \ fixed<3> \ > /** A fixed-size temporary 2D vector */ #define TEMP_VEC2 vector< \ typename et::ScalarPromote< \ typename MatT::value_type, \ typename VecT::value_type \ >::type, \ fixed<2> \ > namespace detail { template < class MatT, class VecT > TEMP_VEC4 transform_vector_4D(const MatT& m, const VecT& v, row_basis) { return v*m; } template < class MatT, class VecT > TEMP_VEC4 transform_vector_4D(const MatT& m, const VecT& v, col_basis) { return m*v; } } // namespace detail /** Apply a 4x4 homogeneous transform matrix to a 4D vector */ template < class MatT, class VecT > TEMP_VEC4 transform_vector_4D(const MatT& m, const VecT& v) { return detail::transform_vector_4D(m,v,typename MatT::basis_orient()); } /** Apply a 3D affine transform to a 3D point */ template < class MatT, class VecT > TEMP_VEC3 transform_point(const MatT& m, const VecT& v) { typedef TEMP_VEC3 vector_type; /* Checking */ detail::CheckMatAffine3D(m); detail::CheckVec3(v); return vector_type( m.basis_element(0,0)*v[0]+m.basis_element(1,0)*v[1]+ m.basis_element(2,0)*v[2]+m.basis_element(3,0), m.basis_element(0,1)*v[0]+m.basis_element(1,1)*v[1]+ m.basis_element(2,1)*v[2]+m.basis_element(3,1), m.basis_element(0,2)*v[0]+m.basis_element(1,2)*v[1]+ m.basis_element(2,2)*v[2]+m.basis_element(3,2) ); } /** Apply a 3D affine transform to a 3D vector */ template < class MatT, class VecT > TEMP_VEC3 transform_vector(const MatT& m, const VecT& v) { typedef TEMP_VEC3 vector_type; /* Checking */ detail::CheckMatLinear3D(m); detail::CheckVec3(v); return vector_type( m.basis_element(0,0)*v[0]+m.basis_element(1,0)*v[1]+ m.basis_element(2,0)*v[2], m.basis_element(0,1)*v[0]+m.basis_element(1,1)*v[1]+ m.basis_element(2,1)*v[2], m.basis_element(0,2)*v[0]+m.basis_element(1,2)*v[1]+ m.basis_element(2,2)*v[2] ); } /** Apply a 2D affine transform to a 2D point */ template < class MatT, class VecT > TEMP_VEC2 transform_point_2D(const MatT& m, const VecT& v) { typedef TEMP_VEC2 vector_type; /* Checking */ detail::CheckMatAffine2D(m); detail::CheckVec2(v); return vector_type( m.basis_element(0,0)*v[0]+m.basis_element(1,0)*v[1]+ m.basis_element(2,0), m.basis_element(0,1)*v[0]+m.basis_element(1,1)*v[1]+ m.basis_element(2,1) ); } /** Apply a 2D affine transform to a 2D vector */ template < class MatT, class VecT > TEMP_VEC2 transform_vector_2D(const MatT& m, const VecT& v) { typedef TEMP_VEC2 vector_type; /* Checking */ detail::CheckMatLinear2D(m); detail::CheckVec2(v); return vector_type( m.basis_element(0,0)*v[0] + m.basis_element(1,0)*v[1], m.basis_element(0,1)*v[0] + m.basis_element(1,1)*v[1] ); } #undef TEMP_VEC4 #undef TEMP_VEC3 #undef TEMP_VEC2 } // namespace cml #endif
AlexanderArgyriou/SortingLibrary
ArraySorter.h
#pragma once #include <iostream> using namespace std; namespace MyAlgorithms { template <typename T> class ArraySorter { private: T *Array; int NumOfElements; protected: inline void swap(const int &index1, const int &index2) noexcept; //swap //QuickSort O(N*logN) inline const int partitionIt(const int &Left, const int &Right, const T &Pivot) noexcept; //partitionit inline void RecQuickSort(const int &Left, const int &Right) noexcept; //RecQuickShort //MergeShort O(N*logN) inline void merge(T *Workspace, const int &Low, const int &High, const int &Upperbound) noexcept; inline void RecMergeSort(T *Workspace , const int &Lowerbound, const int &Upperbound) noexcept; //RecMergeSort inline T GetMax() const noexcept; //GetMax RadixSort inline void CountSort(const int &exp) noexcept; //count For RadixSort public: inline ArraySorter(const int &Size) noexcept { Array = new T[Size]; NumOfElements = Size; }//default constructor inline ArraySorter(const ArraySorter &obj) noexcept { if (this == &obj) { return; } //if Array = new T[obj.NumOfElements]; NumOfElements = obj.NumOfElements; for (register int i = 0; i < NumOfElements; i++) { Array[i] = obj.Array[i]; }//for }//copy constructor //just in case of inheritance cause dynamic allocation for int Array inline virtual ~ArraySorter() noexcept { delete[] Array; Array = nullptr; NumOfElements = 0; }//destructor inline bool putElement(const int &index, const T &newElement) noexcept; //putElement inline bool setArray(const T *newArray) noexcept; //setArray inline const int &getNumOfElements() const noexcept; //getNumOfElements inline const T &getElement(const size_t &index) const noexcept; //getElement inline void QuickSort() noexcept; //QuickShort O(N*logN) inline void MergeSort() noexcept; //MergeSort O(N*logN) inline void BubbleSort() noexcept; //BubbleSort O(N^2) inline void SelectionSort() noexcept; //SelectonSort O(N^2) //faster than bubble , ligoteres antimetatheseis inline void InsertionSort() noexcept; //InsertionSort O(N^2) //a bit faster than Selection inline void ShellSort() noexcept; //ShellSort O(N*logN) //good choice for medium Arrays around size = 1000 inline void RadixSort() noexcept; //RadixSort inline bool IsSorted() const noexcept; //IsSorted inline void Write() const noexcept; //Write };//class interface template<typename T> inline bool ArraySorter<T>::putElement(const int &index, const T &newElement) noexcept { if (index >= 0 && index < NumOfElements) { Array[index] = newElement; return true; } //if else { cout << "Out of bounds"; return false; } //else }//putElement template<typename T> inline bool ArraySorter<T>::setArray(const T *newArray) noexcept { for (register size_t i = 0; i < NumOfElements; ++i) { Array[i] = newArray[i]; }//for return true; }//setArray template<typename T> inline const int &ArraySorter<T>::getNumOfElements() const noexcept { return NumOfElements; }//getNumOfElements template<typename T> inline const T &ArraySorter<T>::getElement(const size_t &index) const noexcept { return (Array[index]); }//getElement template<typename T> inline bool ArraySorter<T>::IsSorted() const noexcept { bool Sorted = true; for (register int count = 0; count < NumOfElements - 1; count++) { if (Array[count] > Array[count + 1]) { return !Sorted; }//if else { continue; } //else }//for return Sorted; }//IsSorted template<typename T> inline void ArraySorter<T>::Write() const noexcept { for (register int count = 0; count < NumOfElements; count++) { cout << Array[count] << " "; }//for const char *answer = (IsSorted()) ? "Sorted" : "Unsorted"; cout << endl << answer << endl << endl; }//Write template<typename T> inline void ArraySorter<T>::swap(const int &index1, const int &index2) noexcept { T temp = Array[index1]; Array[index1] = Array[index2]; Array[index2] = temp; //return true; }//swap template<typename T> inline const int ArraySorter<T>::partitionIt(const int &Left, const int &Right, const T &Pivot) noexcept { //analutika sto xarti int LeftCountPtr = Left - 1; int RightCountPtr = Right; while (true) { while (Array[++LeftCountPtr] < Pivot); while (RightCountPtr > 0 && Array[--RightCountPtr] > Pivot); if (LeftCountPtr >= RightCountPtr) { break; }//if else { swap(LeftCountPtr, RightCountPtr); }//else } //while(true) swap(LeftCountPtr, Right); return LeftCountPtr; }//partitionIt template<typename T> inline void ArraySorter<T>::RecQuickSort(const int &Left, const int &Right) noexcept { if (Right - Left <= 0) { return; }//if else { T Pivot = Array[Right]; int partition = partitionIt(Left, Right, Pivot); RecQuickSort(Left, partition - 1); RecQuickSort(partition + 1, Right); }//else }//RecQuickShort template<typename T> inline void ArraySorter<T>::QuickSort() noexcept { RecQuickSort(0, NumOfElements - 1); }//QuickSort template<typename T> inline void ArraySorter<T>::MergeSort() noexcept { T *WorkSpace = new T[NumOfElements]; RecMergeSort(WorkSpace , 0 , NumOfElements-1); delete[] WorkSpace; }//MergeSort template<typename T> inline void ArraySorter<T>::RecMergeSort(T *Workspace, const int &Lowerbound, const int &Upperbound) noexcept //RecMergeSort { if (Lowerbound == Upperbound) { return; }//if else { int mid = (Lowerbound + Upperbound) / 2; //middle of array RecMergeSort(Workspace, Lowerbound, mid); RecMergeSort(Workspace, mid + 1, Upperbound); merge(Workspace, Lowerbound, mid + 1, Upperbound); } }//RecMergeSort template<typename T> inline void ArraySorter<T>::merge(T *Workspace, const int &Low, const int &High, const int &Upperbound) noexcept { int count = 0; int Lowerbound = Low; int mid = High - 1; int Elements = Upperbound - Lowerbound + 1; int Lowptr = Low; int Hightptr = High; while (Lowptr <= mid && Hightptr <= Upperbound) { if (Array[Lowptr] < Array[Hightptr]) { Workspace[count++] = Array[Lowptr++]; }//if else { Workspace[count++] = Array[Hightptr++]; }//else }//while while (Lowptr <= mid) { Workspace[count++] = Array[Lowptr++]; }//while while (Hightptr <= Upperbound) { Workspace[count++] = Array[Hightptr++]; }//while for (count = 0; count < Elements; count++) { Array[Lowerbound + count] = Workspace[count]; }//for }//merge template<typename T> inline void ArraySorter<T>::BubbleSort() noexcept { for (register int out = NumOfElements - 1; out > 1; out--) { for (register int in = 0; in < out; in++) { if (Array[in] > Array[in + 1]) { swap(in, in + 1); }//if }//for }//for }//BubbleSort template<typename T> inline void ArraySorter<T>::SelectionSort() noexcept { int min = 0; for (register int out = 0; out < NumOfElements - 1; out++) { min = out; for (register int in = out + 1; in < NumOfElements; in++) { if (Array[in] < Array[min]) { min = in; //new min }//if }//for swap(out, min); }//for }//SelectionSort template<typename T> inline void ArraySorter<T>::InsertionSort() noexcept { T temp = 0; int in; for (register int out = 1; out < NumOfElements; out++) { temp = Array[out]; in = out; while (in > 0 && Array[in - 1] >= temp) { Array[in] = Array[in - 1]; --in; }//while Array[in] = temp; }//for }//InsertionSort template<typename T> inline void ArraySorter<T>::ShellSort() noexcept { int inner, outer; T temp; int h = 1; while (h < NumOfElements / 3) { h = h * 3 + 1; } //while while (h > 0) { for (outer = h; outer < NumOfElements; ++outer) { temp = Array[outer]; inner = outer; while (inner > h - 1 && Array[inner - h] >= temp) { Array[inner] = Array[inner - h]; inner -= h; } Array[inner] = temp; } //for h = (h - 1) / 3; } //while } //Shellsort() template <typename T> inline T ArraySorter<T>::GetMax() const noexcept { T max = Array[0]; for (register int i = 1; i < NumOfElements; i++) { if (Array[i] > max) { max = Array[i]; } //if } //for return max; } //GetMax() template <typename T> void ArraySorter<T>::CountSort(const int &exp) noexcept { T *output = new T[NumOfElements]; register int i; T count[10] = { 0 }; for (i = 0; i < NumOfElements; i++) { count[(Array[i] / exp) % 10]++; } //for for (i = 1; i < 10; i++) { count[i] += count[i - 1]; } //for // Build the output array for (i = NumOfElements - 1; i >= 0; i--) { output[count[(Array[i] / exp) % 10] - 1] = Array[i]; count[(Array[i] / exp) % 10]--; } //for for (i = 0; i < NumOfElements; i++) { Array[i] = output[i]; } //for delete[] output; } //CountSort() template <typename T> inline void ArraySorter<T>::RadixSort() noexcept { // Find the maximum number to know number of digits int max = GetMax(); register int NewExp; for (NewExp = 1; max / NewExp > 0; NewExp *= 10) { CountSort(NewExp); }//for } //RadixSort }//namespace
AlexanderArgyriou/SortingLibrary
WorkThread.h
#pragma once #include "ArraySorter.h" #include <ctime> #include <random> using namespace MyAlgorithms; //same namespace namespace Work { template<typename T> class WorkThread { protected: ArraySorter<T> *test; float *result; public: WorkThread(ArraySorter<T> *newTest , float *newResult) noexcept : test(newTest) , result(newResult) {} //constructor ~WorkThread() noexcept { test = nullptr; result = nullptr; }//destructor virtual void operator()() noexcept = 0; };//abstract class interface template<typename T> class WorkThreadQuick : public WorkThread<T> { public: WorkThreadQuick(ArraySorter<T> *newQuickTest , float *newResult) noexcept : WorkThread<T>(newQuickTest , newResult) {}//constructor , calls base class constructor ~WorkThreadQuick() noexcept { this->test = nullptr; //this is must this->result = nullptr; //this is must }//destructor virtual void operator()() noexcept override { volatile clock_t begin = clock(); this->test->QuickSort(); //this is must volatile clock_t end = clock(); float time = (float)(end - begin) / CLOCKS_PER_SEC; float *help = WorkThread<T>::result; //maybe theres a better solution like *help = time; //save result //WorkThread<T>::*result = time help = nullptr; //or this->*result = time (both dont work) }//operator () }; //WorkThreadQuick interface template<typename T> class WorkThreadMerge : public WorkThread<T> { public: WorkThreadMerge(ArraySorter<T> *newMergeTest , float *newResult) noexcept : WorkThread<T>(newMergeTest , newResult) {}//constructor , calls base class constructor ~WorkThreadMerge() noexcept { this->test = nullptr; //this is must this->result = nullptr; //this is must }//destructor virtual void operator()() noexcept override { volatile clock_t begin = clock(); this->test->MergeSort(); volatile clock_t end = clock(); float time = (float)(end - begin) / CLOCKS_PER_SEC; float *help = WorkThread<T>::result; *help = time; //save result help = nullptr; }//operator () }; //WorkThreadMerge interface template<typename T> class WorkThreadBubble : public WorkThread<T> { public: WorkThreadBubble(ArraySorter<int> *newBubbleTest , float *newResult) noexcept : WorkThread<T>(newBubbleTest , newResult) {}//constructor , calls base class constructor ~WorkThreadBubble() noexcept { this->test = nullptr; //this is must this->result = nullptr; //this is must }//destructor virtual void operator()() noexcept override { volatile clock_t begin = clock(); this->test->BubbleSort(); volatile clock_t end = clock(); float time = (float)(end - begin) / CLOCKS_PER_SEC; float *help = WorkThread<T>::result; *help = time; //save result help = nullptr; }//operator () }; //WorkThreadBubble interface template<typename T> class WorkThreadSelection : public WorkThread<T> { public: WorkThreadSelection(ArraySorter<T> *newSelectionTest , float *newResult) noexcept : WorkThread<T>(newSelectionTest , newResult) {}//constructor , calls base class constructor ~WorkThreadSelection() noexcept { this->test = nullptr; //this is must this->result = nullptr; //this is must }//destructor virtual void operator()() noexcept override { volatile clock_t begin = clock(); this->test->SelectionSort(); volatile clock_t end = clock(); float time = (float)(end - begin) / CLOCKS_PER_SEC; float *help = WorkThread<T>::result; *help = time; //save result help = nullptr; }//operator () }; //WorkThreadSelection interface template<typename T> class WorkThreadInsertion : public WorkThread<T> { public: WorkThreadInsertion(ArraySorter<T> *newInsertionTest , float *newResult) noexcept : WorkThread<T>(newInsertionTest , newResult) {}//constructor , calls base class constructor ~WorkThreadInsertion() noexcept { this->test = nullptr; //this is must this->result = nullptr; //this is must }//destructor virtual void operator()() noexcept override { volatile clock_t begin = clock(); this->test->InsertionSort(); volatile clock_t end = clock(); float time = (float)(end - begin) / CLOCKS_PER_SEC; float *help = WorkThread<T>::result; *help = time; //save result help = nullptr; }//operator () }; //WorkThreadInsertion interface template<typename T> class WorkThreadShell : public WorkThread<T> { public: WorkThreadShell(ArraySorter<T> *newShellTest, float *newResult) noexcept : WorkThread<T>(newShellTest, newResult) {}//constructor , calls base class constructor ~WorkThreadShell() noexcept { this->test = nullptr; //this is must this->result = nullptr; //this is must }//destructor virtual void operator()() noexcept override { volatile clock_t begin = clock(); this->test->ShellSort(); //this is must volatile clock_t end = clock(); float time = (float)(end - begin) / CLOCKS_PER_SEC; float *help = WorkThread<T>::result; //maybe theres a better solution like *help = time; //save result //WorkThread<T>::*result = time help = nullptr; //or this->*result = time (both dont work) }//operator () }; //WorkThreadShell interface template<typename T> class WorkThreadRadix : public WorkThread<T> { public: WorkThreadRadix(ArraySorter<T> *newRadixTest, float *newResult) noexcept : WorkThread<T>(newRadixTest, newResult) {}//constructor , calls base class constructor ~WorkThreadRadix() noexcept { this->test = nullptr; //this is must this->result = nullptr; //this is must }//destructor virtual void operator()() noexcept override { volatile clock_t begin = clock(); this->test->RadixSort(); volatile clock_t end = clock(); float time = (float)(end - begin) / CLOCKS_PER_SEC; float *help = WorkThread<T>::result; *help = time; //save result help = nullptr; }//operator () }; //WorkThreadRadix interface template<typename T> class FillArray { private: ArraySorter<T> *FillArrayptr; int Random; int Size; public: FillArray(ArraySorter<T> *newFillArray, const int &newSize) noexcept { Random = 0; FillArrayptr = newFillArray; Size = newSize; }//constructor ~FillArray() noexcept { FillArrayptr = nullptr; Random = 0; Size = 0; }//destructor void operator()() noexcept { for (register int i = 0; i < Size; i++) { //C++11 way mt19937 rng; rng.seed(random_device()()); uniform_int_distribution<mt19937::result_type> dist(1, 10000); //range Random = dist(rng); FillArrayptr->putElement(i , Random); }//operator() } };//FillArray interface template<typename T> class FillWithCopy { private: ArraySorter<T> *FullArrayptr; ArraySorter<T> *FillArrayptr; public: FillWithCopy(ArraySorter<T> *newFullArrayptr, ArraySorter<T> *newFillArrayptr) noexcept { FullArrayptr = newFullArrayptr; FillArrayptr = newFillArrayptr; }//constructor ~FillWithCopy() noexcept { FullArrayptr = nullptr; FillArrayptr = nullptr; }//destructor void operator()() noexcept { for (register int i = 0; i < FullArrayptr->getNumOfElements(); i++) { FillArrayptr->putElement(i, FullArrayptr->getElement(i)); }//for }//run() };//FillwithCopyInterface }//namespace
shinyblink/ff-glitch
ff-glitch.c
// ┳━┓┳━┓ ┏━┓┳ o┏┓┓┏━┓┳ ┳ // ┣━ ┣━ ━━┃ ┳┃ ┃ ┃ ┃ ┃━┫ // ┇ ┇ ┇━┛┇━┛┇ ┇ ┗━┛┇ ┻ // ff-glitch: the farbfeld glitcher. // usage: <farbfeld source> | ff-glitch | <farbfeld sink> // thanks to xero for the idea! you rock. // made by vifino. ISC (C) vifino 2018 #include <stdio.h> #include <string.h> #include <stdint.h> #include <stdlib.h> #include <sys/time.h> #include <arpa/inet.h> // TODO: replace ntohl static uint32_t w, h; static unsigned char buf[8] = {0}; static unsigned char img; static struct timeval tv; typedef struct { unsigned short r, g, b, a; } pixel; // IO helpers. static inline void bread(int bytes) { if (!fread(buf, bytes, 1, stdin)) { fprintf(stderr, "wanted more bytes, didn't get any?\n"); exit(1); } } static inline void bwrite(unsigned char* buffer, size_t bytes) { if (!fwrite(buffer, bytes, 1, stdout)) { fprintf(stderr, "write failed.\n"); exit(1); } } // random helper, random from 0-n, inclusive. // tries to get evenly spread out random. unsigned int randn(unsigned int n) { if (!n) return 0; if (n == RAND_MAX) return rand(); n++; long end = RAND_MAX / n; end *= n; int r; while ((r = rand()) >= end); return r % n; } // Glitch a short. #define GLITCHPX() randn(2 * UINT8_MAX) int main(int argc, char* argv[]) { // TODO: parse argv[1] for range; unsigned int glitches = 40 + randn(50); bread(8); if (strncmp(buf, "farbfeld", 8) != 0) { fprintf(stderr, "stdin is not a farbfeld image?\n"); return 1; } bwrite(buf, 8); // seed like a dumbass. if (gettimeofday(&tv, NULL)) { fprintf(stderr, "failed to get the time? that's messed up.\n"); return 2; } srand(tv.tv_usec); // parse width and height bread(8); uint32_t w = ntohl(*(uint32_t*)buf); uint32_t h = ntohl(*((uint32_t*)(buf + 4))); if (!w && !h) { fprintf(stderr, "image size has zero dimension? %i*%i\n", w, h); return 1; } bwrite(buf, 8); unsigned int pxn; unsigned int end = w*h; unsigned int trash = 0; unsigned int skipped = 0; int glitchpx = 0; unsigned short gv; unsigned char gp = 0; pixel glitchp; for(pxn = 0; pxn < end; pxn++) { if (randn(end / glitches) == 0) { // glitch it. glitch it hard. trash = randn(end / 10 / glitches); if (randn(1) == 0) { glitchpx = randn((end * 4) / glitches); gp = randn(2); gv = GLITCHPX(); } } if (trash) { // trash it. pxn = pxn + trash - 1; while (trash > 1) { if (randn(1) == 0) { bread(8); // throw away } else { skipped++; } pixel* px = (pixel*) buf; px->r = GLITCHPX(); px->g = GLITCHPX(); px->b = GLITCHPX(); trash--; bwrite(buf, 8); } } bread(8); if (glitchpx) { pixel* px = (pixel*) buf; if ((glitchpx - 1) >= 0) { switch (gp) { case 0: px->r = gv; break; case 1: px->g = gv; break; case 2: px->b = gv; break; } glitchpx--; } if (glitchpx < 0) glitchpx = 0; } bwrite(buf, 8); } for (; skipped > 0; skipped--) bread(8); return 0; }
shinyblink/ff-glitch
ff-glitch2.c
// ┳━┓┳━┓ ┏━┓┳ o┏┓┓┏━┓┳ ┳ // ┣━ ┣━ ━━┃ ┳┃ ┃ ┃ ┃ ┃━┫ // ┇ ┇ ┇━┛┇━┛┇ ┇ ┗━┛┇ ┻ // ff-glitch: the farbfeld glitcher. // usage: <farbfeld source> | ff-glitch | <farbfeld sink> // thanks to xero for the idea! you rock. // made by vifino. ISC (C) vifino 2018 #include <stdio.h> #include <string.h> #include <stdint.h> #include <stdlib.h> #include <sys/time.h> #include <arpa/inet.h> // TODO: replace ntohl static uint32_t w, h; static unsigned char buf[8] = {0}; static unsigned char img; static struct timeval tv; typedef struct { unsigned short r, g, b, a; } pixel; // IO helpers. static inline void bread(int bytes) { if (!fread(buf, bytes, 1, stdin)) { fprintf(stderr, "wanted more bytes, didn't get any?\n"); exit(1); } } static inline void bwrite(unsigned char* buffer, size_t bytes) { if (!fwrite(buffer, bytes, 1, stdout)) { fprintf(stderr, "write failed.\n"); exit(1); } } // random helper, random from 0-n, inclusive. // tries to get evenly spread out random. unsigned int randn(unsigned int n) { if (!n) return 0; if (n == RAND_MAX) return rand(); n++; long end = RAND_MAX / n; end *= n; int r; while ((r = rand()) >= end); return r % n; } // Glitch a short. #define SH16MAX (2 * UINT8_MAX) #define GLITCHPX() randn(SH16MAX) #define INVERT(v) htons(SH16MAX - ntohs(v)) // Probability. // TODO: Figure out how to make the number of glitching related // to the amount of pixels. #define GLITCHES() (20 + randn(30)) #define GLITCH_INVERT 10 #define GLITCH_INVERT_PXM 1 #define GLITCH_SKIP 70 #define GLITCH_SKIP_PXM 1 #define GLITCH_CORRUPT 50 #define GLITCH_CORRUPT_PXM 4 #define GLITCH_SWAP 20 #define GLITCH_SWAP_PXM 4 #define GLITCHN (GLITCH_INVERT + GLITCH_SKIP + GLITCH_CORRUPT + GLITCH_SWAP) #define SEL(i, name) if (n < (name)) return (i); n -= (name) static inline unsigned int selglitch() { unsigned int n = randn(GLITCHN); SEL(0, GLITCH_INVERT); SEL(1, GLITCH_SKIP); SEL(2, GLITCH_CORRUPT); return 3; } #define MIN(x, y) (((x) < (y)) ? (x) : (y)) #define MAX(x, y) (((x) > (y)) ? (x) : (y)) int main(int argc, char* argv[]) { // TODO: parse argv[1] for range; unsigned int glitches = GLITCHES(); bread(8); if (strncmp(buf, "farbfeld", 8) != 0) { fprintf(stderr, "stdin is not a farbfeld image?\n"); return 1; } bwrite(buf, 8); // seed like a dumbass. if (gettimeofday(&tv, NULL)) { fprintf(stderr, "failed to get the time? that's messed up.\n"); return 2; } srand(tv.tv_usec); // parse width and height bread(8); uint32_t w = ntohl(*(uint32_t*)buf); uint32_t h = ntohl(*((uint32_t*)(buf + 4))); if (!w && !h) { fprintf(stderr, "image size has zero dimension? %i*%i\n", w, h); return 1; } bwrite(buf, 8); unsigned int pxn; unsigned int end = w*h; unsigned int skipped = 0; int glitchpx = 0; unsigned int gt = 0; pixel* px = (pixel*) buf; unsigned int glm; // selector // corrupter unsigned short gv = GLITCHPX(); unsigned char gp = randn(2); // swapper unsigned short gs = randn(2); for(pxn = 0; pxn < end; pxn++) { if (randn(end / glitches) == 0) { // glitch it. glitch it hard. gt = selglitch(); switch (gt) { case 0: // invert glm = GLITCH_INVERT_PXM; break; case 1: // skip glm = GLITCH_SKIP_PXM; break; case 2: // corrupt glm = GLITCH_CORRUPT_PXM; break; case 3: // swap glm = GLITCH_SWAP_PXM; break; } glitchpx = randn((end * glm) / glitches) + 1; } if (glitchpx) { switch (gt) { case 0: // invert bread(8); px->r = INVERT(px->r); px->g = INVERT(px->g); px->b = INVERT(px->b); bwrite(buf, 8); glitchpx--; break; case 1: // skip reading and trash skipped++; px->r = GLITCHPX(); px->g = GLITCHPX(); px->b = GLITCHPX(); bwrite(buf, 8); glitchpx--; break; case 2: // glitch glitchpx--; if (!glitchpx) { // randomize next gp = randn(2); gv = GLITCHPX(); } bread(8); switch (gp) { case 0: px->r = gv; break; case 1: px->g = gv; break; case 2: px->b = gv; break; } bwrite(buf, 8); break; case 3: // swap glitchpx--; if (!glitchpx) { // randomize next gs = randn(2); } bread(8); pixel tpx = *px; switch (gs) { case 0: // swap r with g; px->r = tpx.g; px->g = tpx.r; case 1: // swap r with b; px->r = tpx.b; px->b = tpx.r; case 2: // swap b with g; px->g = tpx.b; px->b = tpx.g; } bwrite(buf, 8); break; } continue; } // copy and compensate. bread(8); bwrite(buf, 8); } // read skipped things for (; skipped > 0; skipped--) { bread(8); } return 0; }
dark0ghost/FractalCryptGUI
core/fractalcryptcore.h
<reponame>dark0ghost/FractalCryptGUI #ifndef FRACTALCRYPTCORE_H #define FRACTALCRYPTCORE_H #include <QObject> #include <QFile> #include <QDataStream> #include <QCryptographicHash> #include <QDir> #include <QMap> #include <openssl/conf.h> #include <openssl/evp.h> #include <openssl/err.h> #include "core/quazipfunctions.h" #include "core/aes.h" #include "core/noizecreator.hpp" #include "widgets/progressdialog.h" class FractalCryptCore { QEventLoop *loop; ProgressDialog *progressDialog; NoizeCreator *noizeCreator; AES *aes; FractalCryptCore(); ~FractalCryptCore(); FractalCryptCore(const FractalCryptCore&); FractalCryptCore& operator=(const FractalCryptCore&); public: enum StatusCode { OK, ContainerUnavailable, SignatureInvalid, HeaderSizeInvalid, NotEnoughSpace, ZipError, EncryptionError, NewSizeTooSmall }; static const constexpr char signature[8] = "fractal"; static FractalCryptCore& Instance(); void createNoize(QIODevice *iodevice, qint64 bytes); static const QString& getCodeDescription(StatusCode statusCode); StatusCode writeLayer(QString containerPath, QStringList files, QStringList directories, QStringList passwords, QString newPassword); StatusCode readLayer(QString containerPath, QString filePath, QStringList passwords); StatusCode removeLayer(QString containerPath, QStringList passwords); StatusCode encryptFile(QIODevice *file, QStringList passwords, const QVector<qint64> &offsets); StatusCode decryptFile(QIODevice *file, QStringList passwords, QVector<qint64> &offsets); StatusCode resizeFile(QString path, QStringList passwords, qint64 newSize); static void writeHeader(QIODevice *file, qint64 offset, quint64 size); static StatusCode readHeader(QIODevice *file, qint64 offset, qint64 &size); }; #endif // FRACTALCRYPTCORE_H
dark0ghost/FractalCryptGUI
core/quazipfunctions.h
<gh_stars>100-1000 #ifndef QUAZIPFUNCTIONS_H #define QUAZIPFUNCTIONS_H #include "quazip/quazip.h" #include "quazip/quazipfile.h" #include "quazip/quazipdir.h" #include "quazip/JlCompress.h" class QuazipFunctions { class CountingFile; static bool compressSubDir(QuaZip* zip, QString dir, QString origDir, quint32 &fileCount); public: static bool writeZip(QString containerPath, quint64 offset, const QStringList &files, const QStringList &directories, qint64 &bytesWritten); static bool readZip(QIODevice &file, quint64 offset, quint64 end, QString destination); }; #endif // QUAZIPFUNCTIONS_H
dark0ghost/FractalCryptGUI
widgets/archivewindow.h
#ifndef ARCHIVEWINDOW_H #define ARCHIVEWINDOW_H #include <QWidget> #include <QDialog> #include <QFileDialog> #include <QMessageBox> #include <QThreadPool> #include "core/fractalcryptcore.h" #include "core/directorysizecalculator.h" namespace Ui { class ArchiveWindow; } class ArchiveWindow : public QDialog { Q_OBJECT public: explicit ArchiveWindow(QWidget *parent = nullptr); ~ArchiveWindow(); void exec(QString containerPath, QStringList passwords); private: Ui::ArchiveWindow *ui; qint64 getDirectorySize(QString path); QString getFormattedSize(qint64 size); QString containerPath; QStringList passwords; QMessageBox *confirmBox; private slots: void addFileButton(); void addDirectoryButton(); void removeButton(); void clearButton(); void createLayerButton(); void visibleCheckBoxStateChanged(int newState); }; #endif // ARCHIVEWINDOW_H
dark0ghost/FractalCryptGUI
widgets/resizecontainerwindow.h
<filename>widgets/resizecontainerwindow.h #ifndef RESIZECONTAINERWINDOW_H #define RESIZECONTAINERWINDOW_H #include <QWidget> #include <QFile> #include <QtMath> #include <QMessageBox> #include "core/fractalcryptcore.h" namespace Ui { class ResizeContainerWindow; } class ResizeContainerWindow : public QDialog { Q_OBJECT QString containerPath; QStringList passwords; QMessageBox *confirmBox; public: explicit ResizeContainerWindow(QWidget *parent = nullptr); ~ResizeContainerWindow(); int exec(QString containerPath, QStringList passwords); private slots: void resizeButtonClicked(); private: Ui::ResizeContainerWindow *ui; }; #endif // RESIZECONTAINERWINDOW_H
dark0ghost/FractalCryptGUI
widgets/progressdialog.h
#ifndef PROGRESSDIALOG_H #define PROGRESSDIALOG_H #include <QDialog> #include <QRunnable> #include <QEventLoop> #include <QThreadPool> #include <QCloseEvent> namespace Ui { class ProgressDialog; } class ProgressDialog : public QDialog { Q_OBJECT bool finished; public: explicit ProgressDialog(QWidget *parent = nullptr); ~ProgressDialog(); virtual void closeEvent(QCloseEvent *event); public slots: void start(); void setMaximum(int); void setValue(int); void setText(QString); void quit(); private: Ui::ProgressDialog *ui; }; #endif // PROGRESSDIALOG_H
dark0ghost/FractalCryptGUI
widgets/mainwindow.h
<reponame>dark0ghost/FractalCryptGUI #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QFileDialog> #include "createcontainerwindow.h" #include "archivewindow.h" #include "resizecontainerwindow.h" QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); void show(QString path); CreateContainerWindow createContainerWindow; private: Ui::MainWindow *ui; ArchiveWindow archiveWindow; ResizeContainerWindow resizeContainerWindow; QString containerPath; QAction *createFileAction; QAction *openFileAction; QAction *resizeAction; QMessageBox *confirmBox; QStringList getPasswords(); private slots: void createButtonClicked(); void openButtonClicked(); void resizeButtonClicked(); void getFilesButtonClicked(); void createLayerButtonClicked(); void removeLayerButtonClicked(); void passwordsTextChanged(); }; #endif // MAINWINDOW_H
dark0ghost/FractalCryptGUI
core/directorysizecalculator.h
#ifndef DIRECTORYSIZECALCULATOR_H #define DIRECTORYSIZECALCULATOR_H #include <QObject> #include <QRunnable> #include <QThread> #include <QDir> #include <QStack> class DirectorySizeCalculator : public QObject, public QRunnable { Q_OBJECT public: QString directoryPath; DirectorySizeCalculator(QString path); void run(); signals: void calculated(QString directory, qint64 size); }; #endif // DIRECTORYSIZECALCULATOR_H
dark0ghost/FractalCryptGUI
widgets/startwindow.h
<filename>widgets/startwindow.h #ifndef STARTWINDOW_H #define STARTWINDOW_H #include <QWidget> #include <QFileDialog> #include "createcontainerwindow.h" #include "mainwindow.h" namespace Ui { class StartWindow; } class StartWindow : public QWidget { Q_OBJECT public: explicit StartWindow(QWidget *parent = nullptr); ~StartWindow(); private: Ui::StartWindow *ui; MainWindow mainWindow; private slots: void createButtonClicked(); void openButtonClicked(); }; #endif // STARTWINDOW_H
dark0ghost/FractalCryptGUI
widgets/createcontainerwindow.h
<gh_stars>100-1000 #ifndef CREATECONTAINERWINDOW_H #define CREATECONTAINERWINDOW_H #include <QWidget> #include <QDialog> #include <QFileDialog> #include <QMessageBox> #include <QtMath> #include "core/fractalcryptcore.h" namespace Ui { class CreateContainerWindow; } class CreateContainerWindow : public QDialog { Q_OBJECT public: explicit CreateContainerWindow(QWidget *parent = nullptr); ~CreateContainerWindow(); int exec(); bool containerSelected; QString containerPath; private: Ui::CreateContainerWindow *ui; private slots: void createButtonClicked(); void selectPathButtonClicked(); }; #endif // CREATECONTAINERWINDOW_H
aiuno/WingOS
libs/utils/wstring.h
#ifndef WSTRING_H #define WSTRING_H #include <stdio.h> #include <string.h> #include <utils/io/memory_io.h> namespace utils { class string; template <typename V> string to_str(V value); template <> string to_str<const char *>(const char *value); class string : protected memory_io { protected: char null_return = 0; size_t string_length; public: string() : memory_io(16) { string_length = 0; } string(const char *value) : memory_io(strlen(value) + 16) { this->seek(0); this->write(value, strlen(value) + 1); string_length = strlen(value); } string(const char value) : memory_io(16) { this->seek(0); put_back<const char>(value); this->seek(1); put_back<const char>(0); string_length = 1; } string(const char *value, size_t length) : memory_io(length + 16) { this->seek(0); this->write(value, length); string_length = length; } string(const string &value) : memory_io((value.length()) + 16) { this->seek(0); this->write(value.data(), value.length() + 1); string_length = value.length(); } string(string &value) : memory_io((value.length()) + 16) { this->seek(0); this->write(value.data(), value.length() + 1); string_length = value.length(); } ~string() { } template <typename V> string(V value) : string(to_str<V>(value)) { } size_t length() const { return string_length; }; char &operator[](size_t v) { return *((char *)this->data() + v); } char operator[](size_t v) const { return *((char *)this->data() + v); } char &get(size_t v) { if (v > length()) { return null_return; } return *((char *)this->data() + v); } char get(size_t v) const { if (v > length()) { return null_return; } return *((char *)this->data() + v); } const char *c_str() const { return (const char *)data(); } void append(const string &value) { size_t added_length = value.length(); resize(string_length + added_length + 1); seek(string_length); write(value.data(), value.length() + 1); string_length += added_length; } bool has(const string &str) { if (str.length() > length()) { return false; } for (size_t i = 0; i < (length()); i++) { bool contained = true; for (size_t y = 0; y < str.length(); y++) { if (i + y > length()) { return false; } if (get(i + y) != str.get(y)) { contained = false; break; } } if (contained) { return true; } } return false; } string &operator+=(const string &v) { append(v); return *this; } bool operator==(const string &v) const; bool operator!=(const string &v) const { return !(*this == v); }; bool empty() const { return string_length == 0; } }; } // namespace utils #endif // STRING_H
aiuno/WingOS
libs/utils/module_flags.h
<reponame>aiuno/WingOS #ifndef MODULE_FLAGS_H #define MODULE_FLAGS_H // this is useless if you are not a module :^( #include <stddef.h> #include <stdint.h> #endif // MODULE_FLAGS_H
aiuno/WingOS
libs/utils/unicode.h
<gh_stars>100-1000 #ifndef UNICODE_H #define UNICODE_H #include <stddef.h> #include <stdint.h> namespace utils { typedef uint32_t unicode_codepoint; constexpr bool is_unicode_digit(const unicode_codepoint point) { if (point <= U'9' && point >= U'0') { return true; } return false; } constexpr bool is_unicode_alpha(const unicode_codepoint point) { if (point <= U'a' && point >= U'z') { return true; } else if (point <= U'A' && point >= U'Z') { return true; } return false; } constexpr bool is_unicode_alnum(const unicode_codepoint point) { return is_unicode_digit(point) || is_unicode_alpha(point); } constexpr int utf8_from_codepoint(const unicode_codepoint target, char *target_buffer) { if (target < 0x80) { target_buffer[0] = (char)target; target_buffer[1] = 0; return 1; } else if (target < 0x800) { target_buffer[0] = (char)(((target >> 6) & 0x1F) | 0xC0); target_buffer[1] = (char)(((target)&0x3F) | 0x80); target_buffer[2] = 0; return 2; } else if (target < 0x10000) { target_buffer[0] = (char)(((target >> 12) & 0x0F) | 0xE0); target_buffer[1] = (char)(((target >> 6) & 0x3F) | 0x80); target_buffer[2] = (char)(((target >> 0) & 0x3F) | 0x80); target_buffer[3] = 0; return 3; } else if (target < 0x110000) { target_buffer[0] = (char)(((target >> 18) & 0x07) | 0xF0); target_buffer[1] = (char)(((target >> 12) & 0x3F) | 0x80); target_buffer[2] = (char)(((target >> 6) & 0x3F) | 0x80); target_buffer[3] = (char)(((target >> 0) & 0x3F) | 0x80); target_buffer[4] = 0; return 4; } else { target_buffer[0] = '?'; target_buffer[1] = 0; } return 0; } constexpr int codepoint_from_utf8(unicode_codepoint *target, const char *target_buffer) { *target = 0; if ((target_buffer[0] & 0xf8) == 0xf0) { *target |= ((0x07 & target_buffer[0]) << 18); *target |= ((0x3f & target_buffer[1]) << 12); *target |= ((0x3f & target_buffer[2]) << 6); *target |= ((0x3f & target_buffer[3])); return 4; } else if ((target_buffer[0] & 0xf0) == 0xe0) { *target |= ((0x0f & target_buffer[0]) << 12); *target |= ((0x3f & target_buffer[1]) << 6); *target |= ((0x3f & target_buffer[2])); return 3; } else if ((target_buffer[0] & 0xe0) == 0xc0) { *target |= ((0x1f & target_buffer[0]) << 6); *target |= ((0x3f & target_buffer[1])); return 2; } else { *target = target_buffer[0]; return 1; } } template <typename T> class character_code { public: character_code(){}; character_code(character_code &copy) { from_code_point(copy.to_codepoint()); } character_code(const character_code &copy) { from_code_point(copy.to_codepoint()); } virtual T get() const { return 0; }; virtual bool is_null() const { return true; }; virtual unicode_codepoint to_codepoint() const { return 0; }; virtual void from_code_point(const unicode_codepoint v){}; character_code &operator=(const character_code &v) { this->from_code_point(v.to_codepoint()); return *this; } operator char() { char target[5]; auto v = to_codepoint(); utf8_from_codepoint(v, target); return target[0]; } }; class ascii_character_code : public character_code<char> { uint16_t value; public: ascii_character_code() { value = 0; } virtual char get() const { return value; }; bool is_null() const { return value == 0; }; virtual unicode_codepoint to_codepoint() const { unicode_codepoint ret; codepoint_from_utf8(&ret, (const char *)&value); return ret; }; virtual void from_code_point(const unicode_codepoint v) { utf8_from_codepoint(v, (char *)&value); }; }; class utf8_character_code : public character_code<unicode_codepoint> { unicode_codepoint value; public: utf8_character_code() { value = 0; } virtual unicode_codepoint get() const { return value; }; bool is_null() const { return value == 0; }; virtual unicode_codepoint to_codepoint() const { unicode_codepoint ret; codepoint_from_utf8(&ret, (const char *)&value); return ret; }; virtual void from_code_point(const unicode_codepoint v) { utf8_from_codepoint(v, (char *)&value); }; }; class unicode_character_code : public character_code<uint32_t> { uint32_t value; public: virtual uint32_t get() const { return value; }; unicode_character_code() { value = 0; } bool is_null() const { return value == 0; }; virtual unicode_codepoint to_codepoint() const { return value; }; virtual void from_code_point(const unicode_codepoint v) { value = v; }; }; template <typename v> char to_char(const v value) { ascii_character_code ascii; ascii.from_code_point(value.to_codepoint()); return ascii.get(); } template <typename v> size_t u_strlen(const v *value) { size_t string_length = 0; while (!value[string_length].is_null()) { string_length++; } return string_length; } } // namespace utils #endif // UNICODE_H
aiuno/WingOS
libs/utils/attribute.h
#ifndef ATTRIBUTE_H #define ATTRIBUTE_H #define FORCE_INLINE __attribute__((always_inline)) #define NO_RETURN [[noreturn]] #define ASM_FUNCTION extern "C" #endif //ATTRIBUTE_H
aiuno/WingOS
kernel/arch/x86_64/device/mboot_module.h
<reponame>aiuno/WingOS #ifndef MBOOT_MODULE_H #define MBOOT_MODULE_H #include <stivale_struct.h> class mboot_module { stivale2_struct *stistruct; stivale2_module *modules[50]; // that's an array of pointer rip public: mboot_module(); void init(stivale2_struct *main_struct); stivale2_module *get_fs_module(); static mboot_module *the(); }; #endif // MBOOT_MODULE_H
aiuno/WingOS
libs/utils/memory/smart_ptr.h
<filename>libs/utils/memory/smart_ptr.h #ifndef SMART_PTR_H #define SMART_PTR_H #include <stddef.h> namespace utils { template <typename type> class unique_ptr { type *raw; public: unique_ptr() : raw(nullptr){}; unique_ptr(type *d) : raw(d){}; unique_ptr(unique_ptr &&move) : raw(move.release()){}; type &get() { return *raw; } type get() const { return *raw; } const type *get_raw() const { return raw; } type *get_raw() { return raw; } template <typename ret_t> ret_t as() { return reinterpret_cast<ret_t>(raw); } type *operator->() { return raw; } const type *operator->() const { return raw; } unique_ptr &operator=(unique_ptr &&val) { raw = val.release(); return *this; } type &operator[](size_t idx) { return *(raw + idx); } operator bool() { return raw != nullptr; } type *release() { type *old = raw; raw = nullptr; return old; } void reset(type *newval) { type *old = raw; raw = newval; if (old) { delete old; } } ~unique_ptr() { if (raw) { delete raw; raw = nullptr; } } }; template <typename type, typename... Args> unique_ptr<type> make_unique(Args... arg) { return unique_ptr<type>(new type(arg...)); } } // namespace utils #endif // SMART_PTR_H
aiuno/WingOS
libs/libc/sys/types.h
#ifndef SYS_TYPES_H #define SYS_TYPES_H #include <stddef.h> typedef long ssize_t; // signed size_t typedef long blkcnt_t; // block count typedef size_t blksize_t; // block size typedef blkcnt_t fsblkcnt_t; // file system block count typedef size_t clock_t; // clock tick typedef long clockid_t; // clock id typedef unsigned long id_t; // generic id typedef int gid_t; // group id typedef long pid_t; // process & process group id typedef unsigned long uid_t; // user id typedef long suseconds_t; // time in microsecond typedef long time_t; // time in second typedef unsigned long timer_t; // timer id #endif
aiuno/WingOS
unit-test/src/math_check.h
#pragma once int min_check_utils(); int max_check_utils();
aiuno/WingOS
kernel/arch/x86_64/interrupt.h
<reponame>aiuno/WingOS<filename>kernel/arch/x86_64/interrupt.h<gh_stars>100-1000 #pragma once #include <arch.h> #include <gdt.h> #include <stdint.h> #define IDT_ENTRY_COUNT 256 #define INTGATE 0x8e #define TRAPGATE 0xeF #define INT_USER 0x60 enum class interrupt_error_types : int { DIVIDED_BY_ZERO = 0, DEBUG_CALL = 1, NMI_INTERRUPT = 2, BREAKPOINT = 3, INVALID_OPCODE = 6, DOUBLE_FAULT = 8, INVALID_TSS = 10, NON_PRESENT_SEGMENT = 11, INVALID_STACK_SEGMENT = 12, GENERAL_PROTECTION_FAULT = 13, PAGE_FAULT = 14, }; typedef void (*irq_handler_func)(unsigned int irq); class idt_entry { uint16_t offset_low16; uint16_t cs; uint8_t ist; uint8_t attributes; uint16_t offset_mid16; uint32_t offset_high32; uint32_t zero; public: idt_entry(){}; idt_entry(void *idt_handler, uint8_t idt_ist, uint8_t idt_type) { zero = 0; cs = gdt_selector::KERNEL_CODE; ist = idt_ist; attributes = idt_type; uintptr_t target_handler = (uintptr_t)idt_handler; offset_low16 = (uint16_t)target_handler; offset_mid16 = (uint16_t)(target_handler >> 16); offset_high32 = (uint32_t)(target_handler >> 32); }; } __attribute__((packed)); struct idtr { uint16_t size; // size of the IDT table uintptr_t offset; // address of the IDT table } __attribute__((packed)); void init_idt(); void dump_backtrace(const char *msg, uint64_t *array); void dumpregister(InterruptStackFrame *stck); void add_irq_handler(irq_handler_func func, uint8_t irq_target);
aiuno/WingOS
libs/utils/io/memory_io.h
<reponame>aiuno/WingOS<gh_stars>100-1000 #ifndef MEMORY_IO_H #define MEMORY_IO_H #include <utils/io/io.h> #include <utils/memory/smart_ptr.h> namespace utils { class memory_io : public reader, public writer, public basic_seeker_implementation // seeker { void *_data; size_t _size; size_t _data_size; void update_size(size_t new_size); void destroy() { if (_data) { _size = 0; _data_size = 0; free(_data); } _data = nullptr; } public: memory_io() : _data(nullptr), _size(0), _data_size(0) { _send = (0); _scur = (0); }; memory_io(size_t preallocated_size); memory_io(const memory_io &from); // copy memory_io(const memory_io &&from); // move size_t read(void *target, size_t count) final; size_t read(void *target, size_t count) const; size_t write(const void *target, size_t count) final; size_t size() final { return _size; }; void resize(size_t new_size); void *release() { void *saved_data = _data; _data = nullptr; _size = 0; _data_size = 0; return saved_data; }; void *data() { return _data; }; const void *data() const { return _data; }; virtual ~memory_io() { destroy(); } uint8_t &operator[](size_t val) { #ifdef DEBUG if (val > _size) { printf("oob access of memory io 0x%x > 0x%x \n", val, _size); } #endif return ((uint8_t *)_data)[val]; } uint8_t operator[](size_t val) const { #ifdef DEBUG if (val > _size) { printf("oob access of memory io 0x%x > 0x%x \n", val, _size); } #endif return ((uint8_t *)_data)[val]; } memory_io &operator=(const memory_io &&from); memory_io &operator=(const memory_io &from); }; } // namespace utils #endif // MEMORY_IO_H
aiuno/WingOS
libs/libc/math.h
#ifndef MATH_H #define MATH_H #include <stddef.h> #ifdef __SSE__ #define PI 3.141592654 double pow(double x, double y); float powf(float x, float y); #ifdef X87 long double powl(long double x, long double y); #endif #define isinf(v) __builtin_isinf_sign(v) #define isnan(v) __builtin_isnan(v) double trunc(double x); double floor(double x); double ceil(double x); double fabs(double x); double sin(double x); double cos(double x); double ldexp(double x, int exp); float ldexpf(float x, int exp); long double ldexpl(long double x, int exp); #else #warning trying to use math library without sse support #endif #endif
aiuno/WingOS
kernel/arch/x86_64/sse.h
<filename>kernel/arch/x86_64/sse.h<gh_stars>100-1000 #pragma once #include <stddef.h> #include <stdint.h> enum xsave_reg { x87_XSAVE_REG = (1 << 0), SSE_XSAVE_REG = (1 << 1), AVX_XSAVE_REG = (1 << 2), }; #define SSE_LOW_LEVEL_FUNC __attribute__((optimize("O2"))) SSE_LOW_LEVEL_FUNC bool has_xsave(); SSE_LOW_LEVEL_FUNC bool has_avx(); uint32_t get_sse_size(); void init_sse(); void save_sse_context(uint8_t *context); void load_sse_context(uint8_t *context);
aiuno/WingOS
unit-test/src/memory_check.h
#ifndef MEMORY_CHECK_H #define MEMORY_CHECK_H int memory_creation_test(); int memory_destroy_check(); int memory_owner_check(); int memory_compare_check(); int memory_set_check(); int memory_move_check(); int memory_copy_check(); #endif // MEMORY_CHECK_H
aiuno/WingOS
unit-test/src/string_check.h
<reponame>aiuno/WingOS #pragma once int strlen_check_0(); int strnlen_check_0(); int strnlen_check_1(); int strcmp_check_true(); int strcmp_check_false(); int memcmp_check_true(); int memcmp_check_false(); int memset_check_0();
aiuno/WingOS
app/graphic_service/graphic_system_service.h
#ifndef GRAPHIC_SYSTEM_SERVICE_H #define GRAPHIC_SYSTEM_SERVICE_H #include <stdint.h> void update_window_focus(uint32_t from, uint32_t to); #endif // GRAPHIC_SYSTEM_SERVICE_H
aiuno/WingOS
libs/libc/pthread.h
<gh_stars>100-1000 #ifndef __PTHREAD_H__ #define __PTHREAD_H__ #endif /* __PTHREAD_H__ */
aiuno/WingOS
app/graphic_service/raw_window.h
#ifndef RAW_WINDOW_H #define RAW_WINDOW_H #include <gui/graphic_system.h> #include <gui/raw_graphic.h> #include <stdint.h> #include <sys/types.h> #include <utils/container/wvector.h> #define MAX_WINDOW 255 struct raw_window_data { uint64_t wid; pid_t pid; uint64_t px; uint64_t py; uint64_t width; uint64_t height; uint64_t allocated_size; char *window_name; gui::color *window_front_buffer; gui::color *window_back_buffer; bool used; bool background; bool should_redraw; uint64_t depth; }; void init_raw_windows(); utils::vector<raw_window_data> get_window_list(); uint64_t get_window_list_count(); void set_window_on_top(uint64_t wid); void set_window_background(uint64_t wid); void set_window_top_background(uint64_t wid); uint64_t create_window(gui::graphic_system_service_protocol *request, pid_t pid); raw_window_data *get_top_window(); bool valid_window(uint64_t target_wid, pid_t pid); raw_window_data *get_window(uint64_t target_wid); uint64_t get_window_back_buffer(gui::graphic_system_service_protocol *request, pid_t pid); uint64_t window_swap_buffer(gui::graphic_system_service_protocol *request, pid_t pid); uint64_t get_window_position(gui::graphic_system_service_protocol *request, pid_t pid); uint64_t set_window_position(gui::graphic_system_service_protocol *request, pid_t pid); uint64_t window_depth_action(gui::graphic_system_service_protocol *request, pid_t pid); uint64_t resize_window(gui::graphic_system_service_protocol *request, pid_t pid); void update_mouse_in_window(); void draw_all_window(); #endif // RAW_WINDOW_H
aiuno/WingOS
kernel/arch/x86_64/device/disk/ata_driver.h
#pragma once #include <device/io_device.h> #include <stdint.h> enum ATA_IO { ATA_PRIMARY = 0x1F0, ATA_SECONDARY = 0x170, ATA_PRIMARY_DCR = 0x3F6, ATA_SECONDARY_DCR = 0x376 }; enum ATA_drive_type { ATA_PRIMARY_MASTER = 1, ATA_PRIMARY_SLAVE = 2, ATA_SECONDARY_MASTER = 3, ATA_SECONDARY_SLAVE = 4 }; enum ATA_register { ATA_reg_data = 0, ATA_reg_error_feature = 1, ATA_reg_sector_count = 2, ATA_reg_lba0 = 3, ATA_reg_lba1 = 4, ATA_reg_lba2 = 5, ATA_reg_selector = 6, ATA_reg_command_status = 7, ATA_reg_sector_count2 = 8, ATA_reg_lba3 = 9, ATA_reg_lba4 = 10, ATA_reg_lba5 = 11, ATA_reg_control_status = 12, ATA_reg_dev_address = 13 }; enum ATA_data { ATA_type_master = 0xA0, ATA_type_slave = 0xB0, ATA_state_busy = 0x80, ATA_state_fault = 0x20, ATA_state_sr_drq = 0x08, ATA_state_error = 0x01 }; enum ATA_command { ATA_cmd_identify = 0xEC, ATA_cmd_read = 0x24, }; class ata_driver : public generic_io_device { ATA_drive_type current_selected_drive; static void ata_write(bool primary, uint16_t ata_register, uint16_t whattowrite); static uint8_t ata_read(bool primary, uint16_t ata_register); static bool get_ata_status(); uint8_t ide_temp_buf[256]; void read(uint64_t where, uint32_t count, uint8_t *buffer); public: ata_driver(); static bool has_ata_device(); inline void wait(uint8_t time) { for (int i = 0; i < time; i++) { ata_read(true, ATA_reg_command_status); } } inline uint8_t poll_status() { uint8_t status = ata_read(true, ATA_reg_command_status); while ((status & 0x80)) { status = ata_read(true, ATA_reg_command_status); asm volatile("pause"); } return status; } void irq_handle(uint64_t irq_handle_num); void init(); io_rw_output read(uint8_t *data, uint64_t count, uint64_t cursor) override { read(cursor, count, data); return io_rw_output::io_OK; } io_rw_output write(uint8_t *data, uint64_t count, uint64_t cursor) override { read(cursor, count, data); return io_rw_output::io_OK; } const char *get_name() const final { return "pio ata"; } };
aiuno/WingOS
libs/libc/bits/stdc++.h
#ifndef STD_CPP_H #define STD_CPP_H #include <stddef.h> typedef decltype(alignof(int)) align_value; namespace std { enum class align_val_t : align_value { }; } void *operator new(size_t size); void *operator new[](size_t size); void *operator new(size_t size, std::align_val_t align); void *operator new[](size_t size, std::align_val_t align); void operator delete(void *p); void operator delete[](void *p); void operator delete(void *p); void operator delete[](void *p); inline void *operator new(size_t, void *p) throw() { return p; } inline void *operator new[](size_t, void *p) throw() { return p; } inline void operator delete(void *, void *) throw(){}; inline void operator delete[](void *, void *) throw(){}; #endif
aiuno/WingOS
libs/libc/lcxxabi.h
#ifndef LCXXABI_H #define LCXXABI_H #ifndef UNIT_TEST #include <utils/lock.h> extern "C" { #define ATEXIT_MAX_FUNCS 128 typedef unsigned uarch_t; struct atexit_func_entry_t { void (*destructor)(void *); void *target; void *dso_handle; }; int __cxa_atexit(void (*destructor)(void *), void *target, void *dso_handle); void __cxa_finalize(void *targ); } namespace __cxxabiv1 { __extension__ typedef int __guard __attribute__((mode(__DI__))); extern "C" int __cxa_guard_acquire(__guard *); extern "C" void __cxa_guard_release(__guard *); extern "C" void __cxa_guard_abort(__guard *); } // namespace __cxxabiv1 #endif #endif // LCXXABI_H
aiuno/WingOS
unit-test/src/alloc_array_check.h
#pragma once int alloc_array_creation_test(); int alloc_array_creation_fill_test(); int alloc_array_alloc_test(); int alloc_array_free_test(); int alloc_array_foreachentry_test();
aiuno/WingOS
app/graphic_service/raw_graphic_system.h
#ifndef RAW_GRAPHIC_SYSTEM_H #define RAW_GRAPHIC_SYSTEM_H #include "raw_window.h" #include <stdint.h> struct graphic_request_return { bool should_return; uint64_t raw_val; }; void init_raw_graphic_system(); uint64_t get_scr_width(); uint64_t get_scr_height(); void draw_mouse(uint64_t x, uint64_t y); void graphic_system_update(); void draw_window(raw_window_data window); #endif // RAW_GRAPHIC_SYSTEM_H
aiuno/WingOS
unit-test/src/utils_string_check.h
<reponame>aiuno/WingOS #ifndef UTILS_STRING_CHECK_H #define UTILS_STRING_CHECK_H #endif // UTILS_STRING_CHECK_H
aiuno/WingOS
libs/libc/stdlib.h
<reponame>aiuno/WingOS #ifndef STDLIB_H #define STDLIB_H #include <stddef.h> #include <stdint.h> typedef struct { int quot; int rem; } div_t; typedef struct { long quot; long rem; } ldiv_t; typedef struct { long long quot; long long rem; } lldiv_t; div_t div(int numerator, int denominator); ldiv_t ldiv(long numerator, long denominator); lldiv_t lldiv(long long numerator, long long denominator); int abs(int j); long labs(long j); long long llabs(long long j); #ifdef __SSE__ double strtod(const char *nptr, char **endptr); #endif long long strtoll(const char *nptr, char **endptr, int base); long strtol(const char *nptr, char **endptr, int base); #ifdef __SSE__ double atof(const char *s); #endif long atoi(const char *s); #define RAND_MAX 32767 int rand(void); void srand(uint32_t seed); void *malloc(size_t size); void free(void *ptr); void *realloc(void *ptr, size_t size); void exit(int status); #endif
aiuno/WingOS
libs/libc/plug/system_plug.h
<gh_stars>100-1000 #pragma once #include <stddef.h> #include <stdint.h> void plug_init(); uintptr_t plug_allocate_page(size_t count); int plug_free_page(uintptr_t addr, size_t count); void plug_debug_out(const char *str, size_t length); int plug_open(const char *path_name, int flags, int mode); int plug_close(int fd); size_t plug_lseek(int fd, size_t offset, int whence); size_t plug_read(int fd, void *buffer, size_t count); void plug_exit(int s); int plug_error_quit(int code);
aiuno/WingOS
kernel/arch/x86_64/device/ps_keyboard.h
<filename>kernel/arch/x86_64/device/ps_keyboard.h #pragma once #include <device/general_device.h> #include <filesystem/userspace_fs.h> #include <stdint.h> #define KEY_COUNT 128 static const char asciiDefault[58] = { 0, 0, // ESC 49, // 1 50, 51, 52, 53, 54, 55, 56, 57, // 9 48, // 0 45, // - 61, // = 8, 0, 113, // q 119, 101, 114, 116, 121, 117, 105, 111, 112, // p 91, // [ 93, // ] '\n', 10, // return 97, // a 115, 100, 102, 103, 104, 106, 107, 108, // l 59, // ; 39, // ' 96, // ` 0, 92, // BACKSLASH 122, // z 120, 99, 118, 98, 110, 109, // m 44, // , 46, // . 47, // / 0, 42, // * 0, 32, // SPACE }; static const char asciiShift[] = { 0, 0, // ESC 33, // ! 64, // @ 35, // # 36, // $ 37, // % 94, // ^ 38, // & 42, // * 40, // ( 41, // ) 95, // _ 43, // + 0, 0, 81, // Q 87, 69, 82, 84, 89, 85, 73, 79, 80, // P 123, // { 125, // } 0, 10, 65, // A 83, 68, 70, 71, 72, 74, 75, 76, // L 58, // : 34, // " 126, // ~ 0, 124, // | 90, // Z 88, 67, 86, 66, 78, 77, // M 60, // < 62, // > 63, // ? 0, 0, 0, 32, // SPACE }; class ps_keyboard : general_keyboard { void wait(bool is_signal); int32_t mouse_x_offset = 0; int32_t mouse_y_offset = 0; int32_t mouse_x = 0; int32_t mouse_y = 0; uint8_t mouse_cycle = 0; uint8_t last_keypress = 0; bool key_pressed[KEY_COUNT]; uint8_t *ptr_to_update; public: ps_keyboard(); void write(uint8_t data); uint8_t read(); void init(); void interrupt_handler(); void set_key(bool state, uint8_t keycode); bool get_key(uint8_t keycode) const; uint8_t get_last_keypress() const { return asciiDefault[last_keypress]; } void set_ptr_to_update(uint32_t *d); const char *get_name() const final { return "ps2 keyboard"; }; };
aiuno/WingOS
kernel/arch/x86_64/device/network/ethernet_protocol.h
#ifndef ETHERNET_PROTOCOL_H #define ETHERNET_PROTOCOL_H #include <stdint.h> struct mac_address { uint8_t mac[6]; } __attribute__((packed)); enum ethernet_types : uint16_t { ET_ARP = 0x0806, ET_IP4 = 0x0800, ET_IP6 = 0x86DD, }; typedef uint32_t ip_addr; struct ethernet_protocol { mac_address destination; mac_address source; uint16_t ethernet_type; uint8_t payload[]; } __attribute__((packed)); enum arp_commands : uint16_t { ARP_REQUEST = 1, ARP_REPLY = 2, RARP_REQUEST = 3, RARP_REPLY = 4, }; struct address_resolution_protocol { uint16_t link_layer_type; uint16_t protocol_type; uint8_t link_layer_size; uint8_t protocol_size; uint16_t message; uint8_t data[]; } __attribute__((packed)); struct ip_header { uint8_t version : 4; uint8_t internet_header_length : 4; uint8_t type_of_service; uint16_t length; uint16_t id; uint16_t flags : 3; uint16_t fragment_offset : 13; uint8_t time_to_live; uint8_t proto; uint16_t check_sum; ip_addr source_addr; ip_addr target_addr; } __attribute__((packed)); struct arp_ipv4_header { mac_address sender; ip_addr sender_ip; mac_address receiver; ip_addr receiver_ip; } __attribute__((packed)); struct udp_header { uint16_t source_port; uint16_t target_port; uint16_t length; uint16_t checksum; } __attribute__((packed)); struct icmp_v4 { uint8_t type; uint8_t code; uint16_t check_sum; uint8_t data[]; } __attribute__((packed)); #endif // ETHERNET_PROTOCOL_H
aiuno/WingOS
kernel/arch/x86_64/device/pci_device_code.h
<gh_stars>100-1000 #ifndef PCI_STR_CONVERT_H #define PCI_STR_CONVERT_H #include <stdint.h> enum class device_class_code : uint8_t { MASS_STORAGE_CONTROLLER = 1, NETWORK_CONTROLLER = 2, DISPLAY_CONTROLLER = 3, MULTIMEDIA_CONTROLLER = 4, MEMORY_CONTROLLER = 5, BRIDGE_DEVICE = 6, BASE_SYSTEM_PERIPHERAL = 8, SERIAL_BUS_CONTROLLER = 0xC, }; const char *device_code_to_string(uint8_t class_code, uint8_t subclass, uint8_t prog_if); // -------------------------- MASS_STORAGE_CONTROLLER -------------------------- enum class mass_storage_device_subclass : uint8_t { SCSI_BUS_CONTROLLER = 0, IDE_CONTROLLER = 1, FLOPPY_DISK_CONTROLLER = 2, IPI_BUS_CONTROLLER = 3, RAID_CONTROLLER = 4, ATA_CONTROLLER = 5, SATA_CONTROLLER = 6, SERIAL_SCSI_CONTROLLER = 7, NVM_CONTROLLER = 8, }; enum class mass_storage_device_SATA : uint8_t { SPECIFIC_SATA_CONTROLLER = 0, AHCI_SATA_CONTROLLER = 1, SERIAL_SATA_CONTROLLER = 2, }; enum class mass_storage_device_NVM : uint8_t { NVMHCI_CONTROLLER = 1, NVMe_CONTROLLER = 2, }; const char *mass_storage_device_str(uint8_t subclass, uint8_t prog_if); // -------------------------- NETWORK_CONTROLLER -------------------------- enum class network_device_subclass : uint8_t { ETHERNET_CONTROLLER = 0, TOKEN_RING_CONTROLLER = 1, FDDI_CONTROLLER = 2, ATM_CONTROLLER = 3, ISDN_CONTROLLER = 4, WorldFip_CONTROLLER = 5, PICMG_CONTROLLER = 6, INFINIBAND_CONTROLLER = 7, FABRIC_CONTROLLER = 8, }; const char *network_device_str(uint8_t subclass, uint8_t prog_if); // -------------------------- DISPLAY_CONTROLLER -------------------------- enum class display_controller_subclass : uint8_t { VGA_CONTROLLER = 0, XGA_CONTROLLER = 1, D3D_CONTROLLER = 2, }; const char *display_device_str(uint8_t subclass, uint8_t prog_if); // -------------------------- BRIDGE_DEVICE -------------------------- enum class bridge_device_subclass : uint8_t { HOST_BRIDGE = 0, ISA_BRIDGE = 1, EISA_BRIDGE = 2, MCA_BRIDGE = 3, PCI2PCI_BRIDGE = 4, PCMCIA_BRIDGE = 5, NUBUS_BRIDGE = 6, CARDBUS_BRIDGE = 7, RACEWAY_BRIDGE = 8, SEMIT_RANSPARENT_PCI2PCI_BRIDGE = 9, INFINIBAND2PCI_HOST_BRIDGE = 10, }; const char *bridge_device_str(uint8_t subclass, uint8_t prog_if); // -------------------------- BASE_SYSTEM_PERIPHERAL -------------------------- enum class base_system_peripheral_subclass : uint8_t { INTERRUPT_CONTROLLER = 0, DMA_CONTROLLER = 1, INTERRUPT_TIMER_CONTROLLER = 2, RTC_CONTROLLER = 3, PCI_HOT_PLUG_CONTROLLER = 4, SDHCI = 5, IOMMU = 6, }; enum class base_system_peripheral_int_controller : uint8_t { PIC_8259_COMPATIBLE = 0, PIC_ISA_COMPATIBLE = 1, PIC_EISA_COMPATIBLE = 2, IOAPIC_IRQ_CONTROLLER = 0x10, IOxAPIC_IRQ_CONTROLLER = 0x20, }; enum class base_system_peripheral_dma_controller : uint8_t { DMA_8237_COMPATIBLE = 0, DMA_ISA_COMPATIBLE = 1, DMA_EISA_COMPATIBLE = 2, }; enum class base_system_peripheral_timer_controller : uint8_t { PIT_8237_COMPATIBLE = 0, PIT_ISA_COMPATIBLE = 1, PIT_EISA_COMPATIBLE = 2, HPET = 3, }; const char *base_sys_device_str(uint8_t subclass, uint8_t prog_if); // -------------------------- SERIAL_BUS_CONTROLLER -------------------------- enum class serial_bus_controller_subclass : uint8_t { FIREWIRE_CONTROLLER = 0, ACCESS_BUS_CONTROLLER = 1, SSA_CONTROLLER = 2, USB_CONTROLLER = 3, FIBRE_CHANNEL_CONTROLLER = 4, SMBus_CONTROLLER = 5, InfiniBand_CONTROLLER = 6, IMPMI_INTERFACE_CONTROLLER = 7, }; enum class serial_firewire_controller : uint8_t { GENERIC_FIREWIRE_CONTROLLER = 0, OHCI_FIREWIRE_CONTROLLER = 0x10, }; enum class serial_usb_controller : uint8_t { uHCI_USB1_CONTROLLER = 0, oHCI_USB1_CONTROLLER = 0x10, eHCI_USB2_CONTROLLER = 0x20, xHCI_USB3_CONTROLLER = 0x30, USB_DEVICE = 0xFE, }; const char *serial_bus_device_str(uint8_t subclass, uint8_t prog_if); #endif // PCI_STR_CONVERT_H
aiuno/WingOS
libs/utils/type_traits.h
#ifndef TYPE_TRAITS_H #define TYPE_TRAITS_H #include <utils/type/integral_constant.h> namespace utils { // remove reference template <typename t> struct remove_reference { using type = t; }; template <typename t> struct remove_reference<t &> { using type = t; }; template <typename t> struct remove_reference<t &&> { using type = t; }; template <typename t> using remove_reference_t = typename remove_reference<t>::type; // remove const template <class T> struct remove_const { typedef T type; }; template <class T> struct remove_const<const T> { typedef T type; }; // remove volatile template <class T> struct remove_volatile { typedef T type; }; template <class T> struct remove_volatile<volatile T> { typedef T type; }; // remove pointer template <class T> struct remove_pointer { typedef T type; }; template <class T> struct remove_pointer<T *> { typedef T type; }; // is const template <typename T> struct is_const : public false_type { }; template <typename T> struct is_const<T const> : public true_type { }; // is enum template <typename T> struct is_enum : public integral_constant<bool, __is_enum(T)> { }; // is union template <typename T> struct is_union : public integral_constant<bool, __is_union(T)> { }; // is class template <typename T> struct is_class : public integral_constant<bool, __is_class(T)> { }; // is base of template <typename base, typename derived> struct is_base_of : public integral_constant<bool, __is_base_of(base, derived)> { }; // is_function template <typename T> struct is_function : public integral_constant<bool, !is_const<const T>::value> { }; template <typename T> struct is_function<T &> : public false_type { }; template <typename T> struct is_function<T &&> : public false_type { }; template <typename t> constexpr decltype(auto) move(t &&val) { return static_cast<remove_reference_t<t> &&>(val); } } // namespace utils #endif // TYPE_TRAITS_H
aiuno/WingOS
unit-test/src/bit_check.h
#pragma once int get_bit_check(); int set_bit_check();
aiuno/WingOS
libs/utils/json_parser.h
#ifndef JSON_PARSER_H #define JSON_PARSER_H #include <stdint.h> #include <utils/container/wvector.h> namespace utils { enum json_type { JSON_INT = 1, JSON_BOOL, JSON_FLOAT, JSON_STRING, JSON_NULL }; class json_value { bool is_loaded = false; json_type type; const char *vdata; void detect_type(); public: bool is_valid() { return is_loaded; } void init(const char *data); template <typename T> T get_as(); template <bool> bool get_as(); template <const char *> const char *get_as(); bool is_array(); json_type get_type() { return type; } }; class json_storage { json_value val; public: const char *storage_name; const char *storage_value; vector<json_storage *> sub_storage; bool is_an_array; json_storage *parent; json_value get_value(); json_storage &operator[](const char *name); }; class json_data { public: char get_next_data_close_delimitor(int index); void read(); void from_file(const char *file_path); void from_data(const char *data); // null terminated string json_storage get_storage() { return storage; } private: void create_higher_storage(); char *json_raw_data; json_storage storage; vector<char> higher_storage; }; } // namespace utils #endif // JSON_PARSER_H
aiuno/WingOS
libs/utils/error_result.h
<filename>libs/utils/error_result.h #ifndef ERROR_RESULT_H #define ERROR_RESULT_H #include <assert.h> #include <utils/wstring.h> namespace utils { class error { const char *_error = "no error"; // don't use utils::string for the moment because we need to check error as a compile time too and string is not constexpr for the moment const char *_file = "no file"; int _line = 0; bool _is_error = false; bool _is_detailed = false; public: error(const char *file, int line, const char *error_str) : _error(error_str), _file(file), _line(line), _is_error(true), _is_detailed(true){}; error(const char *error_str) : _error(error_str), _file("none"), _line(0), _is_error(true), _is_detailed(false){}; error() = default; const char *error_str() const { return _error; }; const char *file() const { return _file; }; int line() const { return _line; }; void throw_if_error(); // don't throw anything if not an error bool is_error() const { return _is_error; }; operator bool() const { return is_error(); } }; #define ERROR(str) utils::error(__FILE__, __LINE__, str) #define NO_ERROR() utils::error() template <typename T> class error_or_result { error _possible_error; T _value; // todo: add a optional<T> type public: error_or_result(T value) : _value(value) { _possible_error = error(); } error_or_result(const error err) : _value(0) { _possible_error = err; } bool is_error() const { return _possible_error.is_error(); } T get_value() { _possible_error.throw_if_error(); return _value; } error get_error() const { return _possible_error; } }; } // namespace utils #endif // ERROR_RESULT_H
aiuno/WingOS
libs/gui/raw_graphic.h
<reponame>aiuno/WingOS #pragma once #include <stdint.h> namespace sys { struct real_pos { uint32_t x; uint32_t y; } __attribute__((packed)); struct raw_pos { union { real_pos rpos; uint64_t pos; }; } __attribute__((packed)); } // namespace sys
aiuno/WingOS
libs/utils/sys/proc_info_flag.h
<reponame>aiuno/WingOS #ifndef PROC_INFO_FLAG_H #define PROC_INFO_FLAG_H #define PROC_INFO_STATUS 0 // running, sleeping... #define PROC_INFO_NAME 1 #define PROC_INFO_EXIT_STATUS 2 #endif // PROC_INFO_FLAG_H
aiuno/WingOS
libs/module/device_generic_driver.h
#ifndef DEVICE_GENERIC_DRIVER_H #define DEVICE_GENERIC_DRIVER_H #include <stddef.h> #include <stdint.h> #include <string.h> #include <utils/container/wvector.h> #include <utils/sys/device_file_info.h> enum device_type : uint32_t { TIMER_DEVICE = 0, DRIVE_DEVICE = 1, NETWORK_DEVICE = 2, MOUSE_DEVICE = 3, KEYBOARD_DEVICE = 4, CLOCK_DEVICE = 5, DEBUG_DEVICE = 6, FRAMEBUFFER_DEVICE = 7, NULL_DEVICE = 0xfffff, }; class general_device { public: virtual const char *get_name() const { return "null device"; }; virtual device_type get_type() const { return device_type::NULL_DEVICE; }; virtual ~general_device() = default; uint32_t device_id; }; class interrupt_timer : public general_device { protected: bool state; uint32_t current_clock; public: static device_type get_stype() { return device_type::TIMER_DEVICE; }; device_type get_type() const final { return get_stype(); }; virtual void set_clock(uint32_t clock) = 0; virtual void turn_off() = 0; virtual void turn_on() = 0; bool get_state() const { return state; } }; class general_mouse : public general_device { public: static device_type get_stype() { return device_type::MOUSE_DEVICE; }; device_type get_type() const final { return get_stype(); }; virtual int32_t get_mouse_x() = 0; virtual int32_t get_mouse_y() = 0; virtual uint64_t get_mouse_button(int code) = 0; virtual void set_ptr_to_update(uint32_t *x, uint32_t *y); size_t read_mouse_buffer(void *addr, size_t buffer_idx, size_t length); }; class general_keyboard : public general_device { protected: utils::vector<keyboard_buff_info> buffer; public: static device_type get_stype() { return device_type::KEYBOARD_DEVICE; }; device_type get_type() const final { return get_stype(); }; void update_key_out(char out); virtual bool get_key(uint8_t keycode) const = 0; virtual uint8_t get_last_keypress() const = 0; virtual void set_ptr_to_update(uint32_t *d) = 0; size_t read_key_buffer(void *addr, size_t buffer_idx, size_t length) { size_t rlength = length; if (buffer_idx > buffer.size() * sizeof(keyboard_buff_info)) { return 0; } else if (buffer_idx + length > buffer.size() * sizeof(keyboard_buff_info)) { rlength = sizeof(mouse_buff_info) - buffer_idx; } memcpy((uint8_t *)addr, ((uint8_t *)buffer.raw()) + buffer_idx, rlength); return rlength; } size_t get_key_buffer_size() { return buffer.size() * sizeof(keyboard_buff_info); } }; class generic_io_device : public general_device { public: static device_type get_stype() { return device_type::DRIVE_DEVICE; }; device_type get_type() const final { return get_stype(); }; enum io_rw_output { io_ERROR = 0, io_OK = 1, }; virtual io_rw_output read(uint8_t *data, uint64_t count, uint64_t cursor) = 0; io_rw_output read_unaligned(uint8_t *data, uint64_t count, uint64_t cursor); virtual io_rw_output write(uint8_t *data, uint64_t count, uint64_t cursor) = 0; io_rw_output write_unaligned(uint8_t *data, uint64_t count, uint64_t cursor); }; class debug_device : public general_device { public: static device_type get_stype() { return device_type::DEBUG_DEVICE; }; device_type get_type() const final { return get_stype(); }; virtual bool echo_out(const char *data, uint64_t data_length) = 0; virtual bool echo_out(const char *data) = 0; }; class generic_framebuffer : public general_device { public: static device_type get_stype() { return device_type::FRAMEBUFFER_DEVICE; }; device_type get_type() const final { return get_stype(); }; virtual uintptr_t get_addr() = 0; virtual size_t width() = 0; virtual size_t height() = 0; size_t read_buffer(void *addr, size_t length) { size_t rlength = length; if (length > get_buffer_size()) { rlength = sizeof(framebuffer_buff_info); } framebuffer_buff_info info{0}; info.width = width(); info.height = height(); info.addr = get_addr(); memcpy((uint8_t *)addr, ((uint8_t *)&info), rlength); return rlength; } size_t get_buffer_size() { return sizeof(framebuffer_buff_info); } }; #endif
aiuno/WingOS
kernel/arch/x86_64/rsyscall.h
<gh_stars>100-1000 #ifndef SYSCALL_H #define SYSCALL_H void init_syscall_for_current_cpu(); #endif // SYSCALL_H
aiuno/WingOS
libs/utils/bit.h
#ifndef BIT_H #define BIT_H #include <stddef.h> namespace utils { template <typename T> constexpr bool get_bit(const T value, const size_t offset) { return (value & (1 << (offset))); } template <typename T> constexpr void set_bit(T &value, const size_t offset, const bool new_value) { if (new_value) { value |= (1 << (offset)); } else { value &= ~(1 << (offset)); } } } // namespace utils #endif // BIT_H
aiuno/WingOS
libs/utils/container/alloc_array.h
#ifndef ALLOC_ARRAY_H #define ALLOC_ARRAY_H #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <utils/container/container.h> #include <utils/type_traits.h> namespace utils { // an alloc array is an alternative to vector, used/will be used for things like message list // were we want a list with the "status" of the element, if it is used or usable // we can do msg_list.alloc() to find a free message descriptor and use it, and when we do not want to use it we can free it with msg_list.free() // it may be used instead of a vector for passing element by pointer without reallocating the buffer, it is important with smp, as a cpu can realloc a buffer when the second use it // we can use lock but i don't want to lock everything every time we just want to look something template <typename vtype, size_t array_count> class alloc_array : public container<vtype> { vtype _buffer[array_count]; bool _status[array_count]; // maybe use a bitmap ? but if I use a bitmap the array_count must be a multiple of 8 size_t _element_count; size_t _last_free; inline bool is_bounded(size_t val) const { if (val > array_count) { return false; } return true; } public: alloc_array() { for (size_t i = 0; i < array_count; i++) { _status[i] = false; } _element_count = 0; } alloc_array(const vtype new_value) { for (size_t i = 0; i < array_count; i++) { _buffer[i] = new_value; _status[i] = false; } _element_count = 0; } vtype &operator[](size_t idx) { if (!is_bounded(idx)) { printf("out of bound error\n"); return _buffer[0]; } if (_status[idx]) { return _buffer[idx]; } printf("free idx error\n"); return _buffer[0]; } const vtype &operator[](size_t idx) const { if (!is_bounded(idx)) { printf("out of bound error\n"); return _buffer[0]; } if (_status[idx]) { return _buffer[idx]; } printf("free idx error\n"); return _buffer[0]; } vtype &get(size_t idx) override { if (!is_bounded(idx)) { printf("out of bound error\n"); return _buffer[0]; } if (_status[idx]) { return _buffer[idx]; } printf("free idx error\n"); return _buffer[0]; }; const vtype &get(size_t idx) const override { if (!is_bounded(idx)) { printf("out of bound error\n"); return _buffer[0]; } if (_status[idx]) { return _buffer[idx]; } printf("free idx error\n"); return _buffer[0]; }; bool status(size_t idx) { if (!is_bounded(idx)) { printf("out of bound error\n"); return false; } return _status[idx]; } vtype *raw() { // really not recommanded return _buffer; } constexpr size_t size() const override { return array_count; } size_t capacity() const { return array_count * sizeof(vtype); } size_t allocated_element_count() const { return _element_count; }; long alloc() { for (size_t i = 0; i < array_count; i++) { if (_status[i] == false) { _status[i] = true; _element_count++; return (long)i; }; } printf("can't allocate a new entry in alloc_array\n"); return 0; } bool free(size_t idx) { if (!is_bounded(idx)) { printf("out of bound error\n"); return false; } if (!_status[idx]) { printf("error: trying to free an already free array element\n"); return false; } _element_count--; _status[idx] = false; return true; } template <typename func> bool foreach_entry(func call) { for (size_t i = 0; i < array_count; i++) { if (_status[i] == true) { call(_buffer[i]); }; } return true; } }; }; // namespace utils #endif // ALLOC_ARRAY_H
aiuno/WingOS
libs/kern/mouse_keyboard.h
#pragma once #include <stddef.h> #include <stdint.h> #include <utils/sys/device_file_info.h> namespace sys { static const char asciiDefault[58] = { 0, 0, // ESC 49, // 1 50, 51, 52, 53, 54, 55, 56, 57, // 9 48, // 0 45, // - 61, // = 8, 0, 113, // q 119, 101, 114, 116, 121, 117, 105, 111, 112, // p 91, // [ 93, // ] '\n', 10, // return 97, // a 115, 100, 102, 103, 104, 106, 107, 108, // l 59, // ; 39, // ' 96, // ` 0, 92, // BACKSLASH 122, // z 120, 99, 118, 98, 110, 109, // m 44, // , 46, // . 47, // / 0, 42, // * 0, 32, // SPACE }; static const char asciiShift[] = { 0, 0, // ESC 33, // ! 64, // @ 35, // # 36, // $ 37, // % 94, // ^ 38, // & 42, // * 40, // ( 41, // ) 95, // _ 43, // + 0, 0, 81, // Q 87, 69, 82, 84, 89, 85, 73, 79, 80, // P 123, // { 125, // } 0, 10, 65, // A 83, 68, 70, 71, 72, 74, 75, 76, // L 58, // : 34, // " 126, // ~ 0, 124, // | 90, // Z 88, 67, 86, 66, 78, 77, // M 60, // < 62, // > 63, // ? 0, 0, 0, 32, // SPACE }; int32_t get_mouse_x(); int32_t get_mouse_y(); bool get_mouse_button(int button_id); char get_last_key_press(); size_t get_current_keyboard_offset(); keyboard_buff_info get_key_press(size_t id); struct raw_request_data { uint8_t raw_data[32]; } __attribute__((packed)); struct mouse_get_position { bool get_x_value; } __attribute__((packed)); struct mouse_get_button { int mouse_button_type; } __attribute__((packed)); enum device_target_type { TARGET_MOUSE = 1, TARGET_KEYBOARD = 2, }; enum keyboard_request_type { GET_KEYBOARD_KEY = 0, }; struct get_keyboard_key_down { bool unused; } __attribute__((packed)); struct ps2_device_request { uint8_t device_target; // for the moment 1 = mouse 2 = keyboard uint64_t request_type; union { raw_request_data data; mouse_get_position mouse_request_pos; mouse_get_button mouse_button_request; get_keyboard_key_down get_key_down; }; } __attribute__((packed)); enum mouse_request_type { GET_MOUSE_POSITION = 0, GET_MOUSE_BUTTON = 1 }; enum mouse_button_type { GET_MOUSE_LEFT_CLICK = 0, GET_MOUSE_RIGHT_CLICK = 1, GET_MOUSE_MIDDLE_CLICK = 2 }; } // namespace sys