00001 #ifndef GAME_SYOKUNIN_COM_TINYFONT_FONT_H 00002 00003 #define GAME_SYOKUNIN_COM_TINYFONT_FONT_H 00004 00005 #include <boost/cstdint.hpp> 00006 #include <boost/assert.hpp> 00007 00008 namespace TinyFont { 00010 00014 template < boost::uint8_t Width, boost::uint8_t Height > 00015 class Font { 00016 public: 00017 typedef boost::uint8_t uint8_t; 00018 typedef boost::uint32_t uint32_t; 00019 00020 static const uint8_t width = Width; 00021 static const uint8_t height = Height; 00022 static const uint8_t numChars = '~' - '!' + 1; 00023 static const uint32_t bitSize = width * height * numChars; 00024 static const uint32_t byteSize = ( bitSize + 7 ) / 8; 00025 00026 private: 00027 const uint8_t* bytes_; 00028 public: 00029 Font() {} 00030 explicit Font( const uint8_t* ioBytes ) : bytes_( ioBytes ) {} 00031 00033 static uint8_t charToIndex( uint8_t ch ) { 00034 return ch > '!' ? ch - '!' : numChars; 00035 } 00036 00038 const uint8_t* data() const { 00039 return bytes_; 00040 } 00041 00043 bool operator [] ( uint32_t i ) const { 00044 return ( bytes_[ i / 8 ] >> ( i % 8 ) ) & 0x1; 00045 } 00046 00048 00053 struct Image { 00054 uint8_t bytes[ ( width * height + 7 ) / 8 ]; 00055 00056 Image() {} 00057 Image( const Image& other ) { 00058 memcpy( this, &other, sizeof ( Image ) ); 00059 } 00060 Image& operator = ( const Image& other ) { 00061 memcpy( this, &other, sizeof ( Image ) ); 00062 } 00063 bool operator () ( uint32_t x, uint32_t y ) const { 00064 return ( *this )[ y * width + x ]; 00065 } 00066 00067 void set( boost::uint32_t i, boost::uint8_t bit ) { 00068 BOOST_ASSERT( 0 == bit || 1 == bit ); 00069 bytes[ i / 8 ] &= ( ~( 1 << ( i % 8 ) ) ); 00070 bytes[ i / 8 ] |= ( bit << ( i % 8 ) ); 00071 } 00072 00074 bool operator [] ( uint32_t i ) const { 00075 return ( bytes[ i / 8 ] >> ( i % 8 ) ) & 0x1; 00076 } 00077 }; 00078 00080 void getImage( uint32_t nth, Image& outImage ) const { 00081 for ( uint32_t i = 0; i < width * height; ++i ) { 00082 outImage.set( i, ( *this )[ nth * width * height + i ] ); 00083 } 00084 } 00085 }; 00086 00088 template < boost::uint8_t Width, boost::uint8_t Height > 00089 class WritableFont : Font< Width, Height > { 00090 public: 00092 const uint8_t* data() const { 00093 return Font< Width, Height >::data(); 00094 } 00095 00097 uint8_t* data() { 00098 return const_cast< uint8_t* >( Font< Width, Height >::data() ); 00099 } 00100 00102 bool operator [] ( uint32_t i ) const { 00103 return ( bytes[ i / 8 ] >> ( i % 8 ) ) & 0x1; 00104 } 00105 00106 void set( boost::uint32_t i, boost::uint8_t bit ) { 00107 BOOST_ASSERT( 0 == bit || 1 == bit ); 00108 00109 uint8_t* dat = data(); 00110 00111 dat[ i / 8 ] &= ( ~( 1 << ( i % 8 ) ) ); 00112 dat[ i / 8 ] |= ( bit << ( i % 8 ) ); 00113 } 00114 }; 00115 } 00116 00117 #endif