Source

rwkc / src / textsurface.d

Full commit
/**
 * Class for creating and drawing text surfaces.
 */

module textsurface;

import derelict.sdl.sdl;
import derelict.sdl.ttf;
import std.stdio;
import std.string;

import screen;


class TextSurface {

	SDL_Surface* mSurface;
	char[] mText;

	static TTF_Font* mFont;


	this( char[] text = "" ) {
		if( !mFont ) {
			DerelictSDLttf.load();
			if( TTF_Init() ) {
				writefln( "Can't init SDL_ttf." );
				assert(0);
			}
			mFont = TTF_OpenFont( toStringz("data/Comfortaa Bold.ttf"), 24 );
			if( !mFont ) {
				writefln( "openfont error: %s", std.string.toString(TTF_GetError()) );
				assert(0);
			}
		}

		setText( text );
	}


	~this() {
		if( mSurface ) {
			SDL_FreeSurface( mSurface );
		}
	}


	SDL_Surface* getSurface() {
		return mSurface;
	}

	uint w() { if( mSurface) return mSurface.w;  else return(0); }
	uint h() { if( mSurface) return mSurface.h; else return(0); }

	void setText( char[] text ) {
		if( text == "" ) {
			// TTF_Render...() fails for ""
			text = " ";
		}
		if( /*mSurface &&*/ text == mText ) {
			return;
		}
		mText = text;

		if( mSurface ) {
			SDL_FreeSurface( mSurface );
		}

		SDL_Color fg = {255, 255, 255};
		mSurface = TTF_RenderUTF8_Blended( mFont, toStringz(text), fg );
		assert( mSurface != null );
	}

	string getText() { return( mText ); }

	void draw( int x, int y ) {
		SDL_Rect rect = {
			cast(short) x,
			cast(short) y,
			cast(ushort) mSurface.w,
			cast(ushort) mSurface.h
		};
		SDL_BlitSurface( mSurface, null, gScreen.mSurface, &rect );
	}

}