예제 #1
0
FontHelper::FontHelper(const string &font, int size, RGBAColor textColor, RGBAColor outlineColor) {
	this->textColor = textColor;
	this->outlineColor = outlineColor;

	if (!TTF_WasInit()) {
		DEBUG("Initializing font");
		if (TTF_Init() == -1) {
			ERROR("TTF_Init: %s", TTF_GetError());
			exit(2);
		}
	}
	this->font = TTF_OpenFont(font.c_str(), size);
	if (!this->font) {
		ERROR("TTF_OpenFont %s: %s", font.c_str(), TTF_GetError());
		exit(2);
	}
	fontOutline = TTF_OpenFont(font.c_str(), size);
	if (!fontOutline) {
		ERROR("TTF_OpenFont %s: %s", font.c_str(), TTF_GetError());
		exit(2);
	}
	TTF_SetFontHinting(this->font, TTF_HINTING_NORMAL);
	TTF_SetFontHinting(fontOutline, TTF_HINTING_NORMAL);
	TTF_SetFontOutline(fontOutline, 1);
	height = 0;
	// Get maximum line height with a sample text
	TTF_SizeUTF8(fontOutline, "AZ|¹0987654321", NULL, &height);
	halfHeight = height/2;
}
예제 #2
0
//Sets the Kerning value of the font (basically, disable this if there are character overlaps)
//param:fontIndex->The index of the font to modify
//param:enableKerning->True to enable, false to disable
void SpriteFont::SetFontKerning(int fontIndex, bool enableKerning)
{
	//Try block to make sure index is valid
	try
	{
		//Get the font to modify
		TTF_Font* font = fontList.at(fontIndex);

		//Make sure its not null
		if(font)
		{			
			//Convert the bool to an integer. False = 0 (disable), non zero = true
			TTF_SetFontHinting(font, (int)enableKerning);			
		}
		else
		{
			std::cout<<"SetFontKerning error: Provided index is NULL"<<std::endl;
			return;
		}
	}
	catch(std::out_of_range problem)
	{
		//display invalid index
		std::cout<<"SetFontKerning error: font index invalid"<<std::endl;
		return;
	}
}
예제 #3
0
//Set the hinting of the value
//param:fontIndex->The index of the font
//param:hintingStyle->The style of hinting to apply
//TTF_HINTING_NORMAL: Normal hinting
//TTF_HINTING_LIGHT: Light hinting
//TTF_HINTING_MONO: Monochromatic hinting
//TTF_HINTING_NONE: No hinting
void SpriteFont::SetFontHinting(int fontIndex, int hintingStyle)
{
	//Try block to make sure index is valid
	try
	{
		//Get the font to modify
		TTF_Font* font = fontList.at(fontIndex);

		//Make sure its not null
		if(font)
		{
			//Get the current style
			int currentHint = TTF_GetFontHinting(font);

			//Save processing by not changing style if they are identical
			if(currentHint != hintingStyle)
			{
				//Otherwise, set the style
				TTF_SetFontHinting(font, hintingStyle);
			}
		}
		else
		{
			std::cout<<"SetFontHinting error: Provided index is NULL"<<std::endl;
			return;
		}
	}
	catch(std::out_of_range problem)
	{
		//display invalid index
		std::cout<<"SetFontOutline error: font index invalid"<<std::endl;
		return;
	}
}
예제 #4
0
static mrb_value
mrb_sdl2_ttf_font_set_hinting(mrb_state *mrb, mrb_value self)
{
  mrb_int hinting;
  mrb_get_args(mrb, "i", &hinting);
  TTF_SetFontHinting(mrb_sdl2_font_get_ptr(mrb, self), hinting);
  return mrb_nil_value();
}
예제 #5
0
		int LOBJECT_METHOD(setFontHinting, TTF_Font * font){
			int style = TTF_HINTING_NORMAL;
			if (state.is_number(1)){
				style = state.to_integer(1);
			}
			TTF_SetFontHinting(font, style);
			return 0;
		}
예제 #6
0
void CFontManager::Initialize(CRenderManager* pRenderManager)
{
	m_pRenderManager = pRenderManager;

	SDL_ERROR_CHECK(TTF_Init() == -1, "SDL_ttf could not initialize!");

	m_pTTFont = TTF_OpenFont("../Fonts/unispace.ttf", 72);
	TTF_SetFontHinting(m_pTTFont, TTF_HINTING_LIGHT);
}
예제 #7
0
void Font::printDamages(u16 damages, u16 x, u16 y, Color color) {
	TTF_SetFontKerning(m_fontLarge, 0);
	TTF_SetFontHinting(m_fontLarge, TTF_HINTING_NONE);
	
	TTF_SetFontOutline(m_fontLarge, 3);
	
	print(to_string(damages).c_str(), x - 3, y - 3, FONT_LARGE, Color::black);
	
	TTF_SetFontOutline(m_fontLarge, 2);
	
	print(to_string(damages).c_str(), x - 2, y - 2, FONT_LARGE, Color::white);
	
	TTF_SetFontOutline(m_fontLarge, 0);
	
	print(to_string(damages).c_str(), x, y, FONT_LARGE, color);
	
	TTF_SetFontHinting(m_fontLarge, TTF_HINTING_NORMAL);
	TTF_SetFontKerning(m_fontLarge, 1);
}
예제 #8
0
FontAdapter_SDL_ttf::FontAdapter_SDL_ttf(GraphicsContext* gc, const FontDescriptor& fontDescriptor)
{
	const float scaling = 1.2f;

	if (!TTF_WasInit())
		TTF_Init();

	int size = (int)(scaling * fontDescriptor.size * gc->GetCombinedScaling());
	if (size == 0)
		size = (int)(scaling * 12 * gc->GetCombinedScaling());

	_font1 = TTF_OpenFont(fontDescriptor.bold ? FONTNAME_BOLD : FONTNAME_REGULAR, size);
	_font2 = TTF_OpenFont(FONTNAME_FALLBACK, size);
	//_emoji = TTF_OpenFont(FONTNAME_EMOJI, size);

	int style = fontDescriptor.bold ? TTF_STYLE_BOLD : TTF_STYLE_NORMAL;
	int hinting = TTF_HINTING_NORMAL;

	if (_font1 != NULL)
	{
		//TTF_SetFontStyle(_font1, style);
		TTF_SetFontOutline(_font1, 0);
		TTF_SetFontKerning(_font1, 1);
		TTF_SetFontHinting(_font1, hinting);
	}

	if (_font2 != NULL)
	{
		//TTF_SetFontStyle(_font2, style);
		TTF_SetFontOutline(_font2, 0);
		TTF_SetFontKerning(_font2, 1);
		TTF_SetFontHinting(_font2, hinting);
	}

	if (_emoji != NULL)
	{
		//TTF_SetFontStyle(_emoji, style);
		TTF_SetFontOutline(_emoji, 0);
		TTF_SetFontKerning(_emoji, 1);
		TTF_SetFontHinting(_emoji, hinting);
	}
}
예제 #9
0
파일: SDLFont.cpp 프로젝트: benzap/Kampf
void SDLFont::setHinting(enumFontHintingType hinting) {
    int hintingNum = TTF_HINTING_NORMAL;
    switch(hinting) {
    case enumFontHintingType::NONE:
	hintingNum = TTF_HINTING_NONE;
	break;
    case enumFontHintingType::NORMAL:
	hintingNum = TTF_HINTING_NORMAL;
    case enumFontHintingType::LIGHT:
	hintingNum = TTF_HINTING_LIGHT;
    case enumFontHintingType::MONO:
	hintingNum = TTF_HINTING_MONO;
    }
    TTF_SetFontHinting(this->fontContext, hintingNum);
}
예제 #10
0
GuiManager::GuiManager(GraphicsManager* graphics, Encounter* encounter)
    : m_graphics(graphics),
      m_parent(encounter)
{
   m_EIManager = m_parent->getEIHandler().get();

   const char* liberation = "resource/fonts/liberation.ttf";
   
   m_headingFont = TTF_OpenFont(liberation, 18);
   m_contentFont = TTF_OpenFont(liberation, 12);

   assert(m_headingFont != NULL);
   assert(m_contentFont != NULL);

   TTF_SetFontHinting(m_headingFont, TTF_HINTING_MONO);
}
예제 #11
0
void cache_glyphs()
{
    int i;
    char title[800];
    SDL_Color fg={0,0,0,255};
#if RENDER_MODE==1
    SDL_Color bg={255,255,255,255};
#endif

    free_glyphs();
    if(!font)
        return;
    if(style!=TTF_GetFontStyle(font))
        TTF_SetFontStyle(font,style);
    if(kerning != !!TTF_GetFontKerning(font))
        TTF_SetFontKerning(font,kerning);
    if(hinting != TTF_GetFontHinting(font))
        TTF_SetFontHinting(font,hinting);
    if(outline != TTF_GetFontOutline(font))
        TTF_SetFontOutline(font,outline);
    for(i=0; i<128; i++)
    {
        /* cache rendered surface */
#if RENDER_MODE==0
        text[i]=TTF_RenderGlyph_Solid(font,i+start_glyph,fg);
#elif RENDER_MODE==1
        text[i]=TTF_RenderGlyph_Shaded(font,i+start_glyph,fg,bg);
#elif RENDER_MODE==2
        text[i]=TTF_RenderGlyph_Blended(font,i+start_glyph,fg);
#endif
        if(!text[i])
        {
            printf("TTF_RenderGlyph_Shaded: %s\n", TTF_GetError());
            exit(4);
        }
        /* cache metrics */
        TTF_GlyphMetrics(font, i+start_glyph,
            &gm[i].minx, &gm[i].maxx,
            &gm[i].miny, &gm[i].maxy,
            &gm[i].advance);
    }

    sprintf(title,"%s-%s:%d+0x%04x",TTF_FontFaceFamilyName(font),
        TTF_FontFaceStyleName(font),font_size,start_glyph);
    SDL_WM_SetCaption(title,"latin1");
}
예제 #12
0
void cache_glyphs()
{
	SDL_Color fg={0,0,0,255};

#if RENDER_MODE==1
	SDL_Color bg={255,255,255,255};
#endif

	if (!font) return;
	
	if (style!=TTF_GetFontStyle(font)) TTF_SetFontStyle(font,style);

	if (kerning != !!TTF_GetFontKerning(font)) TTF_SetFontKerning(font,kerning);

	if (hinting != TTF_GetFontHinting(font)) TTF_SetFontHinting(font,hinting);
	if (outline != TTF_GetFontOutline(font)) TTF_SetFontOutline(font,outline);
}
예제 #13
0
파일: i_ttf.c 프로젝트: PrisimaTheFox/SRB2
// Load TTF font from file.
INT32 I_TTFLoadFont(const char *file, UINT32 ptsize)
{
	TTF_Font *tmpfont = NULL;
	float fontsize;

	// If a font is currently loaded, unload it.
	if (currentfont)
	{
		TTF_CloseFont(currentfont);
	}

	// Scale the specified font point size for the current resolution.
	fontsize = (ptsize * 0.005f) * (res.width - res.height);

	tmpfont = TTF_OpenFont(file, fontsize);

	if (!tmpfont)
		return FONTHANDLE;

	// set pointer for current font
	currentfont = tmpfont;

	// set current font point size
	currentfontpoint = ptsize;

	// get font properties, and set them
	currentfontstyle = TTF_GetFontStyle(currentfont);
	TTF_SetFontStyle(currentfont, currentfontstyle);

	// these functions only exist in SDL_ttf 2.0.10 onwards
#if SDL_TTF_VERSION_ATLEAST(2,0,10)
	currentfontkerning = TTF_GetFontKerning(currentfont);
	TTF_SetFontKerning(currentfont, currentfontkerning);

	currentfonthinting = TTF_GetFontHinting(currentfont);
	TTF_SetFontHinting(currentfont, currentfonthinting);

	currentfontoutline = TTF_GetFontOutline(currentfont);
	TTF_SetFontOutline(currentfont, currentfontoutline);
#endif

	return 0;
}
예제 #14
0
int main(int argc, char *argv[])
{
	char *argv0 = argv[0];
	SDL_Surface *screen;
	TTF_Font *font;
	SDL_Surface *text, *temp;
	int ptsize;
	int i, done;
	int rdiff, gdiff, bdiff;
	SDL_Color colors[NUM_COLORS];
	SDL_Color white = { 0xFF, 0xFF, 0xFF, 0 };
	SDL_Color black = { 0x00, 0x00, 0x00, 0 };
	SDL_Color *forecol;
	SDL_Color *backcol;
	SDL_Rect dstrect;
	SDL_Event event;
	int rendersolid;
	int renderstyle;
	int outline;
	int hinting;
	int kerning;
	int dump;
	enum {
		RENDER_LATIN1,
		RENDER_UTF8,
		RENDER_UNICODE
	} rendertype;
	char *message, string[128];

	/* Look for special execution mode */
	dump = 0;
	/* Look for special rendering types */
	rendersolid = 0;
	renderstyle = TTF_STYLE_NORMAL;
	rendertype = RENDER_LATIN1;
	outline = 0;
	hinting = TTF_HINTING_NORMAL;
	kerning = 1;
	/* Default is black and white */
	forecol = &black;
	backcol = &white;
	for ( i=1; argv[i] && argv[i][0] == '-'; ++i ) {
		if ( strcmp(argv[i], "-solid") == 0 ) {
			rendersolid = 1;
		} else
		if ( strcmp(argv[i], "-utf8") == 0 ) {
			rendertype = RENDER_UTF8;
		} else
		if ( strcmp(argv[i], "-unicode") == 0 ) {
			rendertype = RENDER_UNICODE;
		} else
		if ( strcmp(argv[i], "-b") == 0 ) {
			renderstyle |= TTF_STYLE_BOLD;
		} else
		if ( strcmp(argv[i], "-i") == 0 ) {
			renderstyle |= TTF_STYLE_ITALIC;
		} else
		if ( strcmp(argv[i], "-u") == 0 ) {
			renderstyle |= TTF_STYLE_UNDERLINE;
		} else
		if ( strcmp(argv[i], "-s") == 0 ) {
			renderstyle |= TTF_STYLE_STRIKETHROUGH;
		} else
		if ( strcmp(argv[i], "-outline") == 0 ) {
			if ( sscanf (argv[++i], "%d", &outline) != 1 ) {
				fprintf(stderr, Usage, argv0);
				return(1);
			}
		} else
		if ( strcmp(argv[i], "-hintlight") == 0 ) {
			hinting = TTF_HINTING_LIGHT;
		} else
		if ( strcmp(argv[i], "-hintmono") == 0 ) {
			hinting = TTF_HINTING_MONO;
		} else
		if ( strcmp(argv[i], "-hintnone") == 0 ) {
			hinting = TTF_HINTING_NONE;
		} else
		if ( strcmp(argv[i], "-nokerning") == 0 ) {
			kerning = 0;
		} else
		if ( strcmp(argv[i], "-dump") == 0 ) {
			dump = 1;
		} else
		if ( strcmp(argv[i], "-fgcol") == 0 ) {
			int r, g, b;
			if ( sscanf (argv[++i], "%d,%d,%d", &r, &g, &b) != 3 ) {
				fprintf(stderr, Usage, argv0);
				return(1);
			}
			forecol->r = (Uint8)r;
			forecol->g = (Uint8)g;
			forecol->b = (Uint8)b;
		} else
		if ( strcmp(argv[i], "-bgcol") == 0 ) {
			int r, g, b;
			if ( sscanf (argv[++i], "%d,%d,%d", &r, &g, &b) != 3 ) {
				fprintf(stderr, Usage, argv0);
				return(1);
			}
			backcol->r = (Uint8)r;
			backcol->g = (Uint8)g;
			backcol->b = (Uint8)b;
		} else {
			fprintf(stderr, Usage, argv0);
			return(1);
		}
	}
	argv += i;
	argc -= i;

	/* Check usage */
	if ( ! argv[0] ) {
		fprintf(stderr, Usage, argv0);
		return(1);
	}

	/* Initialize SDL */
	if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) {
		fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError());
		return(2);
	}

	/* Initialize the TTF library */
	if ( TTF_Init() < 0 ) {
		fprintf(stderr, "Couldn't initialize TTF: %s\n",SDL_GetError());
		SDL_Quit();
		return(2);
	}

	/* Open the font file with the requested point size */
	ptsize = 0;
	if ( argc > 1 ) {
		ptsize = atoi(argv[1]);
	}
	if ( ptsize == 0 ) {
		i = 2;
		ptsize = DEFAULT_PTSIZE;
	} else {
		i = 3;
	}
	font = TTF_OpenFont(argv[0], ptsize);
	if ( font == NULL ) {
		fprintf(stderr, "Couldn't load %d pt font from %s: %s\n",
					ptsize, argv[0], SDL_GetError());
		cleanup(2);
	}
	TTF_SetFontStyle(font, renderstyle);
	TTF_SetFontOutline(font, outline);
	TTF_SetFontKerning(font, kerning);
	TTF_SetFontHinting(font, hinting);

	if( dump ) {
		for( i = 48; i < 123; i++ ) {
			SDL_Surface* glyph = NULL;

			glyph = TTF_RenderGlyph_Shaded( font, i, *forecol, *backcol );

			if( glyph ) {
				char outname[64];
				sprintf( outname, "glyph-%d.bmp", i );
				SDL_SaveBMP( glyph, outname );
			}

		}
		cleanup(0);
	}

	/* Set a 640x480x8 video mode */
	screen = SDL_SetVideoMode(640, 480, 8, SDL_SWSURFACE);
	if ( screen == NULL ) {
		fprintf(stderr, "Couldn't set 640x480x8 video mode: %s\n",
							SDL_GetError());
		cleanup(2);
	}

	/* Set a palette that is good for the foreground colored text */
	rdiff = backcol->r - forecol->r;
	gdiff = backcol->g - forecol->g;
	bdiff = backcol->b - forecol->b;
	for ( i=0; i<NUM_COLORS; ++i ) {
		colors[i].r = forecol->r + (i*rdiff)/4;
		colors[i].g = forecol->g + (i*gdiff)/4;
		colors[i].b = forecol->b + (i*bdiff)/4;
	}
	SDL_SetColors(screen, colors, 0, NUM_COLORS);

	/* Clear the background to background color */
	SDL_FillRect(screen, NULL,
			SDL_MapRGB(screen->format, backcol->r, backcol->g, backcol->b));
	SDL_UpdateRect(screen, 0, 0, 0, 0);

	/* Show which font file we're looking at */
	sprintf(string, "Font file: %s", argv[0]);  /* possible overflow */
	if ( rendersolid ) {
		text = TTF_RenderText_Solid(font, string, *forecol);
	} else {
		text = TTF_RenderText_Shaded(font, string, *forecol, *backcol);
	}
	if ( text != NULL ) {
		dstrect.x = 4;
		dstrect.y = 4;
		dstrect.w = text->w;
		dstrect.h = text->h;
		SDL_BlitSurface(text, NULL, screen, &dstrect);
		SDL_FreeSurface(text);
	}
	
	/* Render and center the message */
	if ( argc > 2 ) {
		message = argv[2];
	} else {
		message = DEFAULT_TEXT;
	}
	switch (rendertype) {
	    case RENDER_LATIN1:
		if ( rendersolid ) {
			text = TTF_RenderText_Solid(font,message,*forecol);
		} else {
			text = TTF_RenderText_Shaded(font,message,*forecol,*backcol);
		}
		break;

	    case RENDER_UTF8:
		if ( rendersolid ) {
			text = TTF_RenderUTF8_Solid(font,message,*forecol);
		} else {
			text = TTF_RenderUTF8_Shaded(font,message,*forecol,*backcol);
		}
		break;

	    case RENDER_UNICODE:
		{
			Uint16 unicode_text[BUFSIZ];
			int index;
#ifdef HAVE_ICONV
			/* Use iconv to convert the message into utf-16.
			 * "char" and "" are aliases for the local 8-bit encoding */
			iconv_t cd;
			/*ICONV_CONST*/ char *from_str = message;
			char *to_str = (char*)unicode_text;
			size_t from_sz = strlen(message) + 1;
			size_t to_sz = sizeof(unicode_text);
			size_t res;
			int i;

			if ((cd = iconv_open("UTF-16", "char")) == (iconv_t)-1
			    && (cd = iconv_open("UTF-16", "")) == (iconv_t)-1) {
				perror("Couldn't open iconv");
				exit(1);
			}

			res = iconv(cd, &from_str, &from_sz, &to_str, &to_sz);
			if (res == -1) {
				perror("Couldn't use iconv");
				exit(1);
			}

			iconv_close(cd);
#else
			/* Convert the message from ascii into utf-16.
			 * This is unreliable as a test because it always
			 * gives the local ordering. */
			for (index = 0; message[index]; index++) {
				unicode_text[index] = message[index];
			}
			unicode_text[index] = 0;
#endif

			if ( rendersolid ) {
				text = TTF_RenderUNICODE_Solid(font,
					unicode_text, *forecol);
			} else {
				text = TTF_RenderUNICODE_Shaded(font,
					unicode_text, *forecol, *backcol);
			}
		}
		break;
	    default:
		text = NULL; /* This shouldn't happen */
		break;
	}
	if ( text == NULL ) {
		fprintf(stderr, "Couldn't render text: %s\n", SDL_GetError());
		TTF_CloseFont(font);
		cleanup(2);
	}
	dstrect.x = (screen->w - text->w)/2;
	dstrect.y = (screen->h - text->h)/2;
	dstrect.w = text->w;
	dstrect.h = text->h;
	printf("Font is generally %d big, and string is %hd big\n",
						TTF_FontHeight(font), text->h);

	/* Blit the text surface */
	if ( SDL_BlitSurface(text, NULL, screen, &dstrect) < 0 ) {
		fprintf(stderr, "Couldn't blit text to display: %s\n", 
								SDL_GetError());
		TTF_CloseFont(font);
		cleanup(2);
	}
	SDL_UpdateRect(screen, 0, 0, 0, 0);

	/* Set the text colorkey and convert to display format */
	if ( SDL_SetColorKey(text, SDL_SRCCOLORKEY|SDL_RLEACCEL, 0) < 0 ) {
		fprintf(stderr, "Warning: Couldn't set text colorkey: %s\n",
								SDL_GetError());
	}
	temp = SDL_DisplayFormat(text);
	if ( temp != NULL ) {
		SDL_FreeSurface(text);
		text = temp;
	}

	/* Wait for a keystroke, and blit text on mouse press */
	done = 0;
	while ( ! done ) {
		if ( SDL_WaitEvent(&event) < 0 ) {
			fprintf(stderr, "SDL_PullEvent() error: %s\n",
								SDL_GetError());
			done = 1;
			continue;
		}
		switch (event.type) {
			case SDL_MOUSEBUTTONDOWN:
				dstrect.x = event.button.x - text->w/2;
				dstrect.y = event.button.y - text->h/2;
				dstrect.w = text->w;
				dstrect.h = text->h;
				if ( SDL_BlitSurface(text, NULL, screen,
							&dstrect) == 0 ) {
					SDL_UpdateRects(screen, 1, &dstrect);
				} else {
					fprintf(stderr,
					"Couldn't blit text to display: %s\n", 
								SDL_GetError());
				}
				break;
				
			case SDL_KEYDOWN:
			case SDL_QUIT:
				done = 1;
				break;
			default:
				break;
		}
	}
	SDL_FreeSurface(text);
	TTF_CloseFont(font);
	cleanup(0);

	/* Not reached, but fixes compiler warnings */
	return 0;
}
예제 #15
0
파일: font.c 프로젝트: FrMo/gravit
int loadFonts() {

    TTF_Font		*font = NULL;
    SDL_Surface		*fontSurface = NULL;
    SDL_Surface		*tmp = NULL;
    Uint32 saved_flags;
    Uint8  saved_alpha;
    static SDL_Color fontColour = {255,255,255};
    char letter[2];
    int i;
    char *p;

    letter[1] = 0;

    p = findFile(va("%s/%s", MISCDIR, video.fontFile));
    
    if (!p) {
        conAdd(LERR, "Could not open font");
        return 0;
    }

    font = TTF_OpenFont(p, video.fontSize);

    if (!font) {
        conAdd(LERR, "Could not open %s", p);
        return 0;
    }

    TTF_SetFontStyle(font, TTF_STYLE_NORMAL);
#ifdef TTF_HINTING_NORMAL
    TTF_SetFontHinting(font, TTF_HINTING_NORMAL);
#endif

    memset(fonts, 0, sizeof(fonts));
    fontHeight = 0;

    for (i = 32; i < 128; i++) {

        letter[0] = i;

        fontSurface = TTF_RenderText_Blended(font, letter, fontColour);

        if (!fontSurface) {

#ifdef WIN32
            MessageBox(NULL, TTF_GetError(), "gravit: font engine error", MB_OK);
#else
            printf("%s\n", TTF_GetError());
#endif
            TTF_CloseFont(font);
            return 0;

        }

        fonts[i].ow = fontSurface->w;
        fonts[i].oh = fontSurface->h;

        if (fonts[i].oh > fontHeight)
            fontHeight = (float)fonts[i].oh;

        fonts[i].w = gfxPowerOfTwo(fonts[i].ow);
        fonts[i].h = gfxPowerOfTwo(fonts[i].oh);

        if (fonts[i].w > fonts[i].h)
            fonts[i].h = fonts[i].w;
        if (fonts[i].h > fonts[i].w)
            fonts[i].w = fonts[i].h;

        tmp = SDL_CreateRGBSurface(SDL_SWSURFACE, fonts[i].w, fonts[i].h, 32,
#if SDL_BYTEORDER == SDL_LIL_ENDIAN /* OpenGL RGBA masks depend on byteorder */
			0x000000FF,
			0x0000FF00,
			0x00FF0000,
			0xFF000000);
#else
			0xFF000000,
			0x00FF0000,
			0x0000FF00,
			0x000000FF);
#endif

        if (!tmp) {

            TTF_CloseFont(font);
            SDL_FreeSurface(fontSurface);

            return 0;

        }


	/* Save the alpha blending attributes */
	saved_flags = fontSurface->flags & (SDL_SRCALPHA|SDL_RLEACCELOK);
#if SDL_VERSION_ATLEAST(1, 3, 0)
	SDL_GetSurfaceAlphaMod(fontSurface, &saved_alpha);
	SDL_SetSurfaceAlphaMod(fontSurface, 0xFF);
#else
	saved_alpha = fontSurface->format->alpha;
	if ( (saved_flags & SDL_SRCALPHA) == SDL_SRCALPHA ) {
		SDL_SetAlpha(fontSurface, 0, 0);
	}
#endif

	/* copy to texture surface */
        if (SDL_BlitSurface(fontSurface, NULL, tmp, NULL)) {

            TTF_CloseFont(font);
            SDL_FreeSurface(tmp);
            SDL_FreeSurface(fontSurface);

            return 0;

        }

        glGenTextures(1, &fonts[i].id);
        glCheck();

        glBindTexture(GL_TEXTURE_2D, fonts[i].id);
        glCheck();

        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, fonts[i].w, fonts[i].h, 0, GL_RGBA, GL_UNSIGNED_BYTE, tmp->pixels);
        glCheck();

        glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
        glCheck();

        glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
        glCheck();

        SDL_FreeSurface(tmp);
        SDL_FreeSurface(fontSurface);

    }

    TTF_CloseFont(font);

    return 1;


}
예제 #16
0
int PDC_scr_open(int argc, char **argv)
{
    int i;

    PDC_LOG(("PDC_scr_open() - called\n"));

    SP = calloc(1, sizeof(SCREEN));

    if (!SP)
        return ERR;

    pdc_own_screen = !pdc_screen;

    if (pdc_own_screen)
    {
        if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) < 0)
        {
            fprintf(stderr, "Could not start SDL: %s\n", SDL_GetError());
            return ERR;
        }

        atexit(_clean);
    }

#ifdef PDC_WIDE
    if (!pdc_ttffont)
    {
        const char *ptsz, *fname;

        if (TTF_Init() == -1)
        {
            fprintf(stderr, "Could not start SDL_TTF: %s\n", SDL_GetError());
            return ERR;
        }

        ptsz = getenv("PDC_FONT_SIZE");
        if (ptsz != NULL)
           pdc_font_size = atoi(ptsz);
        if (pdc_font_size <= 0)
           pdc_font_size = 18;

        fname = getenv("PDC_FONT");
        pdc_ttffont = TTF_OpenFont(fname ? fname : PDC_FONT_PATH,
                                   pdc_font_size);
    }

    if (!pdc_ttffont)
    {
        fprintf(stderr, "Could not load font\n");
        return ERR;
    }

    TTF_SetFontKerning(pdc_ttffont, 0);
    TTF_SetFontHinting(pdc_ttffont, TTF_HINTING_MONO);

    SP->mono = FALSE;
#else
    if (!pdc_font)
    {
        const char *fname = getenv("PDC_FONT");
        pdc_font = SDL_LoadBMP(fname ? fname : "pdcfont.bmp");
    }

    if (!pdc_font)
        pdc_font = SDL_LoadBMP_RW(SDL_RWFromMem(deffont, sizeof(deffont)), 0);

    if (!pdc_font)
    {
        fprintf(stderr, "Could not load font\n");
        return ERR;
    }

    SP->mono = !pdc_font->format->palette;
#endif

    if (!SP->mono && !pdc_back)
    {
        const char *bname = getenv("PDC_BACKGROUND");
        pdc_back = SDL_LoadBMP(bname ? bname : "pdcback.bmp");
    }

    if (!SP->mono && (pdc_back || !pdc_own_screen))
    {
        SP->orig_attr = TRUE;
        SP->orig_fore = COLOR_WHITE;
        SP->orig_back = -1;
    }
    else
        SP->orig_attr = FALSE;

#ifdef PDC_WIDE
    TTF_SizeText(pdc_ttffont, "W", &pdc_fwidth, &pdc_fheight);
#else
    pdc_fheight = pdc_font->h / 8;
    pdc_fwidth = pdc_font->w / 32;

    if (!SP->mono)
        pdc_flastc = pdc_font->format->palette->ncolors - 1;
#endif

    if (pdc_own_screen && !pdc_icon)
    {
        const char *iname = getenv("PDC_ICON");
        pdc_icon = SDL_LoadBMP(iname ? iname : "pdcicon.bmp");

        if (!pdc_icon)
            pdc_icon = SDL_LoadBMP_RW(SDL_RWFromMem(deficon,
                                                    sizeof(deficon)), 0);

        if (pdc_icon)
            SDL_WM_SetIcon(pdc_icon, NULL);
    }

    if (pdc_own_screen)
    {
        const char *env = getenv("PDC_LINES");
        pdc_sheight = (env ? atoi(env) : 25) * pdc_fheight;

        env = getenv("PDC_COLS");
        pdc_swidth = (env ? atoi(env) : 80) * pdc_fwidth;

        pdc_screen = SDL_SetVideoMode(pdc_swidth, pdc_sheight, 0,
            SDL_SWSURFACE|SDL_ANYFORMAT|SDL_RESIZABLE);
    }
    else
    {
        if (!pdc_sheight)
            pdc_sheight = pdc_screen->h - pdc_yoffset;

        if (!pdc_swidth)
            pdc_swidth = pdc_screen->w - pdc_xoffset;
    }

    if (!pdc_screen)
    {
        fprintf(stderr, "Couldn't create a surface: %s\n", SDL_GetError());
        return ERR;
    }

    if (SP->orig_attr)
        PDC_retile();

    for (i = 0; i < 8; i++)
    {
        pdc_color[i].r = (i & COLOR_RED) ? 0xc0 : 0;
        pdc_color[i].g = (i & COLOR_GREEN) ? 0xc0 : 0;
        pdc_color[i].b = (i & COLOR_BLUE) ? 0xc0 : 0;

        pdc_color[i + 8].r = (i & COLOR_RED) ? 0xff : 0x40;
        pdc_color[i + 8].g = (i & COLOR_GREEN) ? 0xff : 0x40;
        pdc_color[i + 8].b = (i & COLOR_BLUE) ? 0xff : 0x40;
    }

    for (i = 0; i < 16; i++)
        pdc_mapped[i] = SDL_MapRGB(pdc_screen->format, pdc_color[i].r,
                                   pdc_color[i].g, pdc_color[i].b);

    SDL_EnableUNICODE(1);

    PDC_mouse_set();

    if (pdc_own_screen)
        PDC_set_title(argc ? argv[0] : "PDCurses");

    SP->lines = PDC_get_rows();
    SP->cols = PDC_get_columns();

    SP->mouse_wait = PDC_CLICK_PERIOD;
    SP->audible = FALSE;

    PDC_reset_prog_mode();

    return OK;
}
예제 #17
0
파일: sys.c 프로젝트: imclab/freeblocks
bool sysLoadFiles() {
    // font
    font = TTF_OpenFont(PKGDATADIR "/fonts/Alegreya-Regular.ttf",20);
    if(!font) return false;
    else TTF_SetFontHinting(font, TTF_HINTING_LIGHT);

    // graphics
    surface_blocks = IMG_Load(PKGDATADIR "/graphics/blocks.png");
    if (!surface_blocks) return false;
    else {
        SDL_Surface *cleanup = surface_blocks;
        surface_blocks = SDL_DisplayFormatAlpha(surface_blocks);
        SDL_FreeSurface(cleanup);
    }

    surface_clear = IMG_Load(PKGDATADIR "/graphics/clear.png");
    if (!surface_clear) return false;
    else {
        SDL_Surface *cleanup = surface_clear;
        surface_clear = SDL_DisplayFormatAlpha(surface_clear);
        SDL_FreeSurface(cleanup);
    }

    surface_cursor = IMG_Load(PKGDATADIR "/graphics/cursor.png");
    if (!surface_cursor) return false;
    else {
        SDL_Surface *cleanup = surface_blocks;
        surface_blocks = SDL_DisplayFormatAlpha(surface_blocks);
        SDL_FreeSurface(cleanup);
    }

    surface_bar = IMG_Load(PKGDATADIR "/graphics/bar.png");
    if (!surface_bar) return false;
    else {
        SDL_Surface *cleanup = surface_bar;
        surface_bar = SDL_DisplayFormatAlpha(surface_bar);
        SDL_FreeSurface(cleanup);
    }

    surface_bar_inactive = IMG_Load(PKGDATADIR "/graphics/bar_inactive.png");
    if (!surface_bar_inactive) return false;
    else {
        SDL_Surface *cleanup = surface_bar_inactive;
        surface_bar_inactive = SDL_DisplayFormatAlpha(surface_bar_inactive);
        SDL_FreeSurface(cleanup);
    }

    surface_background = IMG_Load(PKGDATADIR "/graphics/background.png");
    if (!surface_background) return false;
    else {
        SDL_Surface *cleanup = surface_background;
        surface_background = SDL_DisplayFormat(surface_background);
        SDL_FreeSurface(cleanup);
    }

    surface_title = IMG_Load(PKGDATADIR "/graphics/title.png");
    if (!surface_title) return false;
    else {
        SDL_Surface *cleanup = surface_title;
        surface_title = SDL_DisplayFormatAlpha(surface_title);
        SDL_FreeSurface(cleanup);
    }

    surface_highscores = IMG_Load(PKGDATADIR "/graphics/highscores.png");
    if (!surface_highscores) return false;
    else {
        SDL_Surface *cleanup = surface_highscores;
        surface_highscores = SDL_DisplayFormatAlpha(surface_highscores);
        SDL_FreeSurface(cleanup);
    }

    // background music
    music = Mix_LoadMUS(PKGDATADIR "/sounds/music.ogg");
    if (!music) return false;

    // sound effects
    sound_menu = Mix_LoadWAV(PKGDATADIR "/sounds/menu.wav");
    if (!sound_menu) return false;

    sound_switch = Mix_LoadWAV(PKGDATADIR "/sounds/switch.wav");
    if (!sound_switch) return false;

    sound_match = Mix_LoadWAV(PKGDATADIR "/sounds/match.wav");
    if (!sound_match) return false;

    return true;
}
    ManifestBasedResources(std::string manifest, SDL_Renderer* renderer)
    {
        auto configuration = LoadLuaConfiguration(manifest);
        
        auto images = configuration.Get<LuaTable>("images");
        
        images.ForAllIntegerKeys([&](int key, LuaType::Value type)
                                 {
                                     if (type == LuaType::table)
                                     {
                                         auto value = images.Get<LuaTable>(key);
                                         auto id = value.Get<int>("id");
                                         auto path = value.Get<std::string>("path");
                                         auto x = value.Get<int>("x");
                                         auto y = value.Get<int>("y");
                                         auto w = value.Get<int>("w");
                                         auto h = value.Get<int>("h");
                                         
                                         SDL_Rect rect;
                                         rect.x = x;
                                         rect.y = y;
                                         rect.w = w;
                                         rect.h = h;
                                         
                                         auto texture = texturesByName.find(path);
                                         if (texture == texturesByName.end())
                                         {
                                             texturesByName[path] = std::shared_ptr<SDL_Texture>(IMG_LoadTexture(renderer, path.c_str()), SDL_DestroyTexture);
                                             
                                             
                                             texture = texturesByName.find(path);
                                             
                                             if (!texture->second)
                                             {
                                                 printlog("Image '%s' IMG:%s\n", path.c_str(), IMG_GetError());
                                             }
                                         }
                                         
                                         imageResources[id] = std::shared_ptr<ImageDesc>(new ImageDesc(texture->second, rect));
                                     }
                                 });
        
        
        auto sprites = configuration.Get<LuaTable>("sprites");
        
        sprites.ForAllIntegerKeys([&](int key, LuaType::Value type)
                                 {
                                     if (type == LuaType::table)
                                     {
                                         auto sprite = sprites.Get<LuaTable>(key);
                                         
                                         auto id = sprite.Get<int>("id");
                                         auto imageIds = sprite.Get<LuaTable>("imageIds");
                                         unsigned int delay = sprite.Get<int>("delay");
                                         
                                         std::vector< std::shared_ptr<ImageDesc> > imageList;
                                         imageIds.ForAllIntegerKeys([&](int key, LuaType::Value type)
                                                                    {
                                                                        auto imageId = imageIds.Get<int>(key);
                                                                        imageList.push_back(GetImage(imageId));
                                                                   });
                                         
                                         SDL_Rect rect = *(imageList[0]->GetRect());
                                         
                                         spriteResources[id] = std::shared_ptr<SpriteDesc>(new SpriteDesc(imageList, rect, delay));
                                         
                                     }
                                 });
        
        auto fonts = configuration.Get<LuaTable>("fonts");
        
        fonts.ForAllIntegerKeys([&](int key, LuaType::Value type)
                                  {
                                      if (type == LuaType::table)
                                      {
                                          auto font = fonts.Get<LuaTable>(key);
                                          
                                          auto id = font.Get<int>("id");
                                          auto path = font.Get<std::string>("path");
                                          auto color = font.Get<LuaTable>("color");
                                          auto ptsize = font.Get<int>("ptsize");
                                          
                                          std::stringstream ss;
                                          ss << path << "@" << ptsize;
                                          
                                          auto fontFile = fontsByName.find(ss.str());
                                          if (fontFile == fontsByName.end())
                                          {
                                              fontsByName[path] = std::shared_ptr<TTF_Font>(TTF_OpenFont(path.c_str(), ptsize), TTF_CloseFont);
                                              fontFile = fontsByName.find(path);
                                              TTF_SetFontHinting(fontFile->second.get(), 1);
                                              TTF_SetFontKerning(fontFile->second.get(), 1);
                                          }
                                          
                                          SDL_Color c;
                                          c.a = 0xff;
                                          c.r = (Uint8)color.Get<int>("r");
                                          c.g = (Uint8)color.Get<int>("g");
                                          c.b = (Uint8)color.Get<int>("b");

                                          fontResources[id] = std::shared_ptr<TTFFontDesc>(new TTFFontDesc(fontFile->second, c));

                                      }
                                  });
    }
예제 #19
0
파일: styleswitcher.c 프로젝트: ckeen/KiWi
int main(int argc, char ** argv) {
  SDL_Window * window;
  SDL_Renderer * renderer;
  KW_GUI * gui;
  TTF_Font * dejavu;
  SDL_Rect framegeom, editgeom, labelgeom, buttongeom;
  KW_Widget * editbx, * label, * button, * kthxbai, * frame, * buttonsframe;
  int hinting;
  
  /* initialize window and renderer */
  SDL_Init(SDL_INIT_EVERYTHING);
  SDL_CreateWindowAndRenderer(320, 240, 0, &window, &renderer);
  SDL_SetRenderDrawColor(renderer, 118, 152, 162, 1);
  TTF_Init();
  
  /* load tilesets */
  setalloy = IMG_Load_RW(SDL_RWFromFile("tileset-alloy.png", "r"), SDL_TRUE);
  setfutter = IMG_Load_RW(SDL_RWFromFile("tileset-futterpedia.png", "r"), SDL_TRUE);
  setflat = IMG_Load_RW(SDL_RWFromFile("tileset-flat.png", "r"), SDL_TRUE);
  set = IMG_Load_RW(SDL_RWFromFile("tileset.png", "r"), SDL_TRUE);

  
  /* initialize gui */
  gui = KW_Init(renderer, setfutter);
  fontin = TTF_OpenFontRW(SDL_RWFromFile("Fontin-Regular.ttf", "r"), SDL_TRUE, 12);
  sourcepro = TTF_OpenFontRW(SDL_RWFromFile("SourceSansPro-Semibold.ttf", "r"), SDL_TRUE, 12);
  dejavu = TTF_OpenFontRW(SDL_RWFromFile("DejaVuSans.ttf", "r"), SDL_TRUE, 11);
  
  hinting = TTF_HINTING_NONE;
  TTF_SetFontHinting(fontin, hinting);
  TTF_SetFontHinting(sourcepro, hinting);
  TTF_SetFontHinting(dejavu, hinting);
  KW_SetFont(gui, fontin);

  /* top frame */  
  framegeom.x = 10, framegeom.y = 10, framegeom.w = 300, framegeom.h = 220;
  frame = KW_CreateFrame(gui, NULL, &framegeom);
  
  /* buttons frame */
  framegeom.x = 10, framegeom.y = 160, framegeom.w = 280, framegeom.h = 48;
  buttonsframe = KW_CreateFrame(gui, frame, &framegeom);
  
  /* buttons */
  button = NULL;
  buttongeom.x = 10, buttongeom.y = 8, buttongeom.w = 32, buttongeom.h = 32;
  button = KW_CreateButton(gui, buttonsframe, "", &buttongeom);
  KW_SetWidgetTilesetSurface(button, set);
  KW_AddWidgetMouseDownHandler(button, SwitchNormalClicked);
  
  buttongeom.x += 290/4;
  button = KW_CreateButton(gui, buttonsframe, "", &buttongeom);
  KW_SetWidgetTilesetSurface(button, setalloy);
  KW_AddWidgetMouseDownHandler(button, SwitchAlloyClicked);
  
  buttongeom.x += 290/4;
  button = KW_CreateButton(gui, buttonsframe, "", &buttongeom);
  KW_SetWidgetTilesetSurface(button, setfutter);
  KW_AddWidgetMouseDownHandler(button, SwitchFutterClicked);
  
  buttongeom.x += 290/4;
  button = KW_CreateButton(gui, buttonsframe, "", &buttongeom);
  KW_SetWidgetTilesetSurface(button, setflat);
  KW_AddWidgetMouseDownHandler(button, SwitchFlatClicked);
  
  /* reset framegeom */
  framegeom.x = 10, framegeom.y = 10, framegeom.w = 300, framegeom.h = 220;
  framegeom.w -= 20; framegeom.h = 100;
  
  /* create the editbox frames */
  editgeom.x = 120, editgeom.y = 20, editgeom.w = 150, editgeom.h = 35;
  labelgeom.x = 10, labelgeom.y = 20, labelgeom.w = 110, labelgeom.h = 35;
  frame = KW_CreateFrame(gui, frame, &framegeom);
  editbx = KW_CreateEditbox(gui, frame, "βέβαιος (sure)", &editgeom);
  KW_SetEditboxFont(editbx, dejavu);
  label = KW_CreateLabel(gui, frame, "Can you do UTF-8?", &labelgeom);
  KW_SetLabelAlignment(label, KW_LABEL_ALIGN_RIGHT, 0, KW_LABEL_ALIGN_MIDDLE, 0);
  
  buttongeom = editgeom;
  buttongeom.y = 60; buttongeom.h -= 10;
  kthxbai = KW_CreateButton(gui, frame, "kthxbai", &buttongeom);
  KW_AddWidgetMouseDownHandler(kthxbai, kthxbaiClicked);
  
  while (!SDL_QuitRequested() && !quit) {
    SDL_RenderClear(renderer);
    KW_Paint(gui);
    SDL_RenderPresent(renderer);
    SDL_Delay(1);
  }
  
  /* free stuff */
  KW_Quit(gui);
  TTF_CloseFont(fontin);
  TTF_CloseFont(dejavu);
  SDL_FreeSurface(set);
  SDL_FreeSurface(setalloy);
  SDL_FreeSurface(setflat);
  SDL_FreeSurface(setfutter);
  TTF_Quit();
  SDL_Quit();
  
  return 0;
}
예제 #20
0
파일: scrollbox.c 프로젝트: ckeen/KiWi
int main(int argc, char ** argv) {
  SDL_Window * window;
  SDL_Renderer * renderer;
  SDL_Surface * set;
  KW_GUI * gui;
  TTF_Font * font;
  SDL_Rect geometry = {0, 0, 320, 240};
  KW_Widget * frame, * button;
  int i;
  SDL_Event ev;
  
  /* initialize SDL */
  SDL_Init(SDL_INIT_EVERYTHING);

  
#if defined(ANDROID)
  /* enjoy all the screen size on android */
  i = SDL_GetNumVideoDisplays();
  if (i < 1) exit(1);
  SDL_GetDisplayBounds(0, &geometry);
#endif
  SDL_CreateWindowAndRenderer(geometry.w, geometry.h, SDL_WINDOW_RESIZABLE, &window, &renderer);
  SDL_SetRenderDrawColor(renderer, 100, 200, 100, 1);
  TTF_Init();
  
  /* load tileset */
  set = IMG_Load("tileset.png");
  
  /* initialize gui */
  gui = KW_Init(renderer, set);
  font = TTF_OpenFont("SourceSansPro-Semibold.ttf", 12);
  TTF_SetFontHinting(font, TTF_HINTING_NONE);
  KW_SetFont(gui, font);

  geometry.x = geometry.w * 0.0625; geometry.y = geometry.h * .0625; geometry.w *= .875f; geometry.h *= .875;
  frame = KW_CreateScrollbox(gui, NULL, &geometry);
  KW_AddWidgetDragStartHandler(frame, DragStart);
  KW_AddWidgetDragHandler(frame, Drag);
  KW_AddWidgetDragStopHandler(frame, DragStop);
  SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);

  geometry.x = 10; geometry.y = 0; geometry.h = 40; geometry.w = 230;
  
  for (i = 0; i < 5; i++) {
    button = KW_CreateButton(gui, frame, "Drag me, resize me.", &geometry);
    KW_AddWidgetDragStartHandler(button, DragStart);
    KW_AddWidgetDragHandler(button, Drag);
    KW_AddWidgetDragStopHandler(button, DragStop);
    geometry.y += geometry.h;
  }
    
  /* create another parent frame */
  while (!SDL_QuitRequested()) {
    while (SDL_PollEvent(&ev)) {
      if (ev.type == SDL_WINDOWEVENT && ev.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) {
        geometry.w = ev.window.data1;
        geometry.h = ev.window.data2;
        geometry.x = geometry.w * 0.0625; geometry.y = geometry.h * .0625; geometry.w *= .875f; geometry.h *= .875;
        KW_SetWidgetGeometry(frame, &geometry);
      }
    }
    SDL_RenderClear(renderer);
    KW_Paint(gui);
    SDL_RenderPresent(renderer);
    SDL_Delay(1);
  }
  TTF_CloseFont(font);
  TTF_Quit();
  KW_Quit(gui);
  SDL_FreeSurface(set);
  SDL_Quit();
  
  return 0;
}
예제 #21
0
파일: pdcscrn.c 프로젝트: wmcbrine/PDCurses
int PDC_scr_open(int argc, char **argv)
{
    PDC_LOG(("PDC_scr_open() - called\n"));

    SP = calloc(1, sizeof(SCREEN));

    if (!SP)
        return ERR;

    pdc_own_screen = !pdc_screen;

    if (pdc_own_screen)
    {
        if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) < 0)
        {
            fprintf(stderr, "Could not start SDL: %s\n", SDL_GetError());
            return ERR;
        }

        atexit(_clean);
    }

#ifdef PDC_WIDE
    if (!pdc_ttffont)
    {
        const char *ptsz, *fname;

        if (TTF_Init() == -1)
        {
            fprintf(stderr, "Could not start SDL_TTF: %s\n", SDL_GetError());
            return ERR;
        }

        ptsz = getenv("PDC_FONT_SIZE");
        if (ptsz != NULL)
           pdc_font_size = atoi(ptsz);
        if (pdc_font_size <= 0)
           pdc_font_size = 18;

        fname = getenv("PDC_FONT");
        pdc_ttffont = TTF_OpenFont(fname ? fname : PDC_FONT_PATH,
                                   pdc_font_size);
    }

    if (!pdc_ttffont)
    {
        fprintf(stderr, "Could not load font\n");
        return ERR;
    }

    TTF_SetFontKerning(pdc_ttffont, 0);
    TTF_SetFontHinting(pdc_ttffont, TTF_HINTING_MONO);

    SP->mono = FALSE;
#else
    if (!pdc_font)
    {
        const char *fname = getenv("PDC_FONT");
        pdc_font = SDL_LoadBMP(fname ? fname : "pdcfont.bmp");
    }

    if (!pdc_font)
        pdc_font = SDL_LoadBMP_RW(SDL_RWFromMem(font437, sizeof(font437)), 0);

    if (!pdc_font)
    {
        fprintf(stderr, "Could not load font\n");
        return ERR;
    }

    SP->mono = !pdc_font->format->palette;
#endif

    if (!SP->mono && !pdc_back)
    {
        const char *bname = getenv("PDC_BACKGROUND");
        pdc_back = SDL_LoadBMP(bname ? bname : "pdcback.bmp");
    }

    if (!SP->mono && (pdc_back || !pdc_own_screen))
    {
        SP->orig_attr = TRUE;
        SP->orig_fore = COLOR_WHITE;
        SP->orig_back = -1;
    }
    else
        SP->orig_attr = FALSE;

#ifdef PDC_WIDE
    TTF_SizeText(pdc_ttffont, "W", &pdc_fwidth, &pdc_fheight);
    pdc_fthick = pdc_font_size / 20 + 1;
#else
    pdc_fheight = pdc_font->h / 8;
    pdc_fwidth = pdc_font->w / 32;
    pdc_fthick = 1;

    if (!SP->mono)
        pdc_flastc = pdc_font->format->palette->ncolors - 1;
#endif

    if (pdc_own_screen && !pdc_icon)
    {
        const char *iname = getenv("PDC_ICON");
        pdc_icon = SDL_LoadBMP(iname ? iname : "pdcicon.bmp");

        if (!pdc_icon)
            pdc_icon = SDL_LoadBMP_RW(SDL_RWFromMem(iconbmp,
                                                    sizeof(iconbmp)), 0);

        if (pdc_icon)
            SDL_WM_SetIcon(pdc_icon, NULL);
    }

    if (pdc_own_screen)
    {
        const SDL_VideoInfo *info = SDL_GetVideoInfo();
        max_height = info->current_h;
        max_width = info->current_w;

        const char *env = getenv("PDC_LINES");
        pdc_sheight = (env ? atoi(env) : 25) * pdc_fheight;

        env = getenv("PDC_COLS");
        pdc_swidth = (env ? atoi(env) : 80) * pdc_fwidth;

        pdc_screen = SDL_SetVideoMode(pdc_swidth, pdc_sheight, 0,
            SDL_SWSURFACE|SDL_ANYFORMAT|SDL_RESIZABLE);
    }
    else
    {
        if (!pdc_sheight)
            pdc_sheight = pdc_screen->h - pdc_yoffset;

        if (!pdc_swidth)
            pdc_swidth = pdc_screen->w - pdc_xoffset;
    }

    if (!pdc_screen)
    {
        fprintf(stderr, "Couldn't create a surface: %s\n", SDL_GetError());
        return ERR;
    }

    if (SP->orig_attr)
        PDC_retile();

    _initialize_colors();

    SDL_EnableUNICODE(1);

    PDC_mouse_set();

    if (pdc_own_screen)
        PDC_set_title(argc ? argv[0] : "PDCurses");

    SP->lines = PDC_get_rows();
    SP->cols = PDC_get_columns();

    SP->mouse_wait = PDC_CLICK_PERIOD;
    SP->audible = FALSE;

    SP->termattrs = A_COLOR | A_UNDERLINE | A_LEFT | A_RIGHT | A_REVERSE;
#ifdef PDC_WIDE
    SP->termattrs |= A_ITALIC;
#endif

    PDC_reset_prog_mode();

    return OK;
}
예제 #22
0
int main(int argc, char *argv[])
{
    char *argv0 = argv[0];
    SDL_Window *window;
    SDL_Renderer *renderer;
    TTF_Font *font;
    SDL_Surface *text;
    Scene scene;
    int ptsize;
    int i, done;
    SDL_Color white = { 0xFF, 0xFF, 0xFF, 0 };
    SDL_Color black = { 0x00, 0x00, 0x00, 0 };
    SDL_Color *forecol;
    SDL_Color *backcol;
    SDL_Event event;
    int rendersolid;
    int renderstyle;
    int outline;
    int hinting;
    int kerning;
    int dump;
    enum {
        RENDER_LATIN1,
        RENDER_UTF8,
        RENDER_UNICODE
    } rendertype;
    char *message, string[128];

    /* Look for special execution mode */
    dump = 0;
    /* Look for special rendering types */
    rendersolid = 0;
    renderstyle = TTF_STYLE_NORMAL;
    rendertype = RENDER_LATIN1;
    outline = 0;
    hinting = TTF_HINTING_NORMAL;
    kerning = 1;
    /* Default is black and white */
    forecol = &black;
    backcol = &white;
    for ( i=1; argv[i] && argv[i][0] == '-'; ++i ) {
        if ( strcmp(argv[i], "-solid") == 0 ) {
            rendersolid = 1;
        } else
        if ( strcmp(argv[i], "-utf8") == 0 ) {
            rendertype = RENDER_UTF8;
        } else
        if ( strcmp(argv[i], "-unicode") == 0 ) {
            rendertype = RENDER_UNICODE;
        } else
        if ( strcmp(argv[i], "-b") == 0 ) {
            renderstyle |= TTF_STYLE_BOLD;
        } else
        if ( strcmp(argv[i], "-i") == 0 ) {
            renderstyle |= TTF_STYLE_ITALIC;
        } else
        if ( strcmp(argv[i], "-u") == 0 ) {
            renderstyle |= TTF_STYLE_UNDERLINE;
        } else
        if ( strcmp(argv[i], "-s") == 0 ) {
            renderstyle |= TTF_STYLE_STRIKETHROUGH;
        } else
        if ( strcmp(argv[i], "-outline") == 0 ) {
            if ( sscanf (argv[++i], "%d", &outline) != 1 ) {
                fprintf(stderr, Usage, argv0);
                return(1);
            }
        } else
        if ( strcmp(argv[i], "-hintlight") == 0 ) {
            hinting = TTF_HINTING_LIGHT;
        } else
        if ( strcmp(argv[i], "-hintmono") == 0 ) {
            hinting = TTF_HINTING_MONO;
        } else
        if ( strcmp(argv[i], "-hintnone") == 0 ) {
            hinting = TTF_HINTING_NONE;
        } else
        if ( strcmp(argv[i], "-nokerning") == 0 ) {
            kerning = 0;
        } else
        if ( strcmp(argv[i], "-dump") == 0 ) {
            dump = 1;
        } else
        if ( strcmp(argv[i], "-fgcol") == 0 ) {
            int r, g, b;
            if ( sscanf (argv[++i], "%d,%d,%d", &r, &g, &b) != 3 ) {
                fprintf(stderr, Usage, argv0);
                return(1);
            }
            forecol->r = (Uint8)r;
            forecol->g = (Uint8)g;
            forecol->b = (Uint8)b;
        } else
        if ( strcmp(argv[i], "-bgcol") == 0 ) {
            int r, g, b;
            if ( sscanf (argv[++i], "%d,%d,%d", &r, &g, &b) != 3 ) {
                fprintf(stderr, Usage, argv0);
                return(1);
            }
            backcol->r = (Uint8)r;
            backcol->g = (Uint8)g;
            backcol->b = (Uint8)b;
        } else {
            fprintf(stderr, Usage, argv0);
            return(1);
        }
    }
    argv += i;
    argc -= i;

    /* Check usage */
    if ( ! argv[0] ) {
        fprintf(stderr, Usage, argv0);
        return(1);
    }

    /* Initialize the TTF library */
    if ( TTF_Init() < 0 ) {
        fprintf(stderr, "Couldn't initialize TTF: %s\n",SDL_GetError());
        SDL_Quit();
        return(2);
    }

    /* Open the font file with the requested point size */
    ptsize = 0;
    if ( argc > 1 ) {
        ptsize = atoi(argv[1]);
    }
    if ( ptsize == 0 ) {
        i = 2;
        ptsize = DEFAULT_PTSIZE;
    } else {
        i = 3;
    }
    font = TTF_OpenFont(argv[0], ptsize);
    if ( font == NULL ) {
        fprintf(stderr, "Couldn't load %d pt font from %s: %s\n",
                ptsize, argv[0], SDL_GetError());
        cleanup(2);
    }
    TTF_SetFontStyle(font, renderstyle);
    TTF_SetFontOutline(font, outline);
    TTF_SetFontKerning(font, kerning);
    TTF_SetFontHinting(font, hinting);

    if( dump ) {
        for( i = 48; i < 123; i++ ) {
            SDL_Surface* glyph = NULL;

            glyph = TTF_RenderGlyph_Shaded( font, i, *forecol, *backcol );

            if( glyph ) {
                char outname[64];
                sprintf( outname, "glyph-%d.bmp", i );
                SDL_SaveBMP( glyph, outname );
            }

        }
        cleanup(0);
    }

    /* Create a window */
    if (SDL_CreateWindowAndRenderer(WIDTH, HEIGHT, 0, &window, &renderer) < 0) {
        fprintf(stderr, "SDL_CreateWindowAndRenderer() failed: %s\n", SDL_GetError());
        cleanup(2);
    }

    /* Show which font file we're looking at */
    sprintf(string, "Font file: %s", argv[0]);  /* possible overflow */
    if ( rendersolid ) {
        text = TTF_RenderText_Solid(font, string, *forecol);
    } else {
        text = TTF_RenderText_Shaded(font, string, *forecol, *backcol);
    }
    if ( text != NULL ) {
        scene.captionRect.x = 4;
        scene.captionRect.y = 4;
        scene.captionRect.w = text->w;
        scene.captionRect.h = text->h;
        scene.caption = SDL_CreateTextureFromSurface(renderer, text);
        SDL_FreeSurface(text);
    }

    /* Render and center the message */
    if ( argc > 2 ) {
        message = argv[2];
    } else {
        message = DEFAULT_TEXT;
    }
    switch (rendertype) {
        case RENDER_LATIN1:
            if ( rendersolid ) {
                text = TTF_RenderText_Solid(font,message,*forecol);
            } else {
                text = TTF_RenderText_Shaded(font,message,*forecol,*backcol);
            }
            break;

        case RENDER_UTF8:
            if ( rendersolid ) {
                text = TTF_RenderUTF8_Solid(font,message,*forecol);
            } else {
                text = TTF_RenderUTF8_Shaded(font,message,*forecol,*backcol);
            }
            break;

        case RENDER_UNICODE:
        {
            Uint16 *unicode_text = SDL_iconv_utf8_ucs2(message);
            if ( rendersolid ) {
                text = TTF_RenderUNICODE_Solid(font,
                                               unicode_text, *forecol);
            } else {
                text = TTF_RenderUNICODE_Shaded(font,
                                                unicode_text, *forecol, *backcol);
            }
            SDL_free(unicode_text);
        }
            break;
        default:
            text = NULL; /* This shouldn't happen */
            break;
    }
    if ( text == NULL ) {
        fprintf(stderr, "Couldn't render text: %s\n", SDL_GetError());
        TTF_CloseFont(font);
        cleanup(2);
    }
    scene.messageRect.x = (WIDTH - text->w)/2;
    scene.messageRect.y = (HEIGHT - text->h)/2;
    scene.messageRect.w = text->w;
    scene.messageRect.h = text->h;
    scene.message = SDL_CreateTextureFromSurface(renderer, text);
    printf("Font is generally %d big, and string is %d big\n",
           TTF_FontHeight(font), text->h);

    draw_scene(renderer, &scene);

    /* Wait for a keystroke, and blit text on mouse press */
    done = 0;
    while ( ! done ) {
        if ( SDL_WaitEvent(&event) < 0 ) {
            fprintf(stderr, "SDL_PullEvent() error: %s\n",
                    SDL_GetError());
            done = 1;
            continue;
        }
        switch (event.type) {
            case SDL_MOUSEBUTTONDOWN:
                scene.messageRect.x = event.button.x - text->w/2;
                scene.messageRect.y = event.button.y - text->h/2;
                scene.messageRect.w = text->w;
                scene.messageRect.h = text->h;
                draw_scene(renderer, &scene);
                break;

            case SDL_KEYDOWN:
            case SDL_QUIT:
                done = 1;
                break;
            default:
                break;
        }
    }
    SDL_FreeSurface(text);
    TTF_CloseFont(font);
    SDL_DestroyTexture(scene.caption);
    SDL_DestroyTexture(scene.message);
    cleanup(0);

    /* Not reached, but fixes compiler warnings */
    return 0;
}