Exemplo n.º 1
0
void set_text(void)
{
    if (!TTF_WasInit() && TTF_Init() != 0) {
        printf("Error TTF %s \n", TTF_GetError());
        exit(EXIT_FAILURE);
    }

    if ((font = TTF_OpenFont(FONT_TTF, 64)) == NULL) {
        printf("Error %s\n", TTF_GetError());
        exit(EXIT_FAILURE);
    }

    if ((tiny_font = TTF_OpenFont(FONT_TTF, 34)) == NULL) {
        printf("Error %s\n", TTF_GetError());
        exit(EXIT_FAILURE);
    }
}
Exemplo n.º 2
0
void Font::Clean() {
  if (this->font != NULL) {
    TTF_CloseFont(this->font);
    this->font = NULL;
  }

  if (this->name != NULL) {
    delete [] this->name;
    this->name = NULL;
  }

  if (loadedFonts == 1 && TTF_WasInit() == 1) {
    TTF_Quit();
  }
  
  loadedFonts--;
}
Exemplo n.º 3
0
FontEngine::FontEngine() {
	font_pt = 10;

	// Initiate SDL_ttf
	if(!TTF_WasInit() && TTF_Init()==-1) {
		printf("TTF_Init: %s\n", TTF_GetError());
		exit(2);
	}

	// load the font
	string font_path;
	FileParser infile;
	if (infile.open(PATH_DATA + "engine/font_settings.txt")) {
		while (infile.next()) {
			if (infile.key == "font_regular"){
				font_path = infile.val;
			}
			if (infile.key == "ptsize"){
				font_pt = atoi(infile.val.c_str());
			}
		}
	}
	font_path = PATH_DATA + "fonts/" + font_path;
	font = TTF_OpenFont(font_path.c_str(), font_pt);
	if(!font) printf("TTF_OpenFont: %s\n", TTF_GetError());

	// calculate the optimal line height
	line_height = TTF_FontLineSkip(font);
	font_height = TTF_FontHeight(font); 

	// set the font colors
	SDL_Color white = {255,255,255};
	SDL_Color red = {255,0,0};
	SDL_Color green = {0,255,0};
	SDL_Color blue = {0,0,255};
	SDL_Color grey = {128,128,128};
	SDL_Color black = {0,0,0};

	colors[FONT_WHITE] = white;
	colors[FONT_RED] = red;
	colors[FONT_GREEN] = green;
	colors[FONT_BLUE] = blue;
	colors[FONT_GREY] = grey;
	colors[FONT_BLACK] = black;
}
Exemplo n.º 4
0
Font::Font(const char *fontPath, const Uint32 initialSizeCount) :
	fontPath_(fontPath),
	font_(initialSizeCount),
	renderColor_( {0, 0, 0, 255} ),  //black color
	renderStyle_(STYLE_NORMAL)
{
	if (fontPath_ == nullptr) {
		Engine::log << Priority::error << "Font path is invalid."
		            << std::endl;
		Engine::exit(1);
	}

	if(TTF_WasInit() == 0) {
		Engine::log << Priority::error
		            << "SDL_ttf was not initialized yet." << std::endl;
	}

}
Exemplo n.º 5
0
bool KFontProperties::enumerateFont(const KFile *file, int ptSize) {
  if(file->isFile()) {
    if(strToLower(file->getExtension()) == ".ttf") {
      if(!TTF_WasInit()) {
        TTF_Init();
      }
      TTF_Font *_Font = TTF_OpenFont(file->getAbsolutePath().c_str(), ptSize);
      if(_Font != nullptr) {
        KFontProperties *fp = new KFontProperties(_Font, file, ptSize);
        // free the font.
        TTF_CloseFont(_Font);
        auto lock = getLock();
        fontList[file->getAbsolutePath()][ptSize].reset(fp);
        return true;
      }
    }
  }
  return false;
}
Exemplo n.º 6
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);
	}
}
Exemplo n.º 7
0
TextParams::TextParams(std::string font, float size, int style,
	                   float red, float green, float blue,
	                   float shadowRed, float shadowGreen, float shadowBlue)
	: r(red), g(green), b(blue), sr(shadowRed), sg(shadowGreen), sb(shadowBlue)
{
	if(!TTF_WasInit() && TTF_Init() < 0) {
		fprintf(stderr, "TTF_Init failed: %s\n", TTF_GetError());
		exit(1);
	}
	if(!fontPool)
		fontPool = NEW FontPool;
	
	std::string fontName = retprintf("%s,%.1f,%i", font.c_str(), size, style);
	if(fontPool->find(fontName) == fontPool->end()) {
		TTF_Font *f = TTF_OpenFont(font.c_str(), size);
		(*fontPool)[fontName] = f;
		TTF_SetFontStyle(f, style);
	}
	this->font = (*fontPool)[fontName];
}
Exemplo n.º 8
0
void SDL::exit()
{
	// Freeing everything related to VIDEO


	// Freeing everything related to AUDIO


	Mix_AllocateChannels(0); // Frees all allocated channels

	//Mix_Quit(); segmentation fault! why?
	Mix_CloseAudio();

	// Freeing everything related to FONTS

	if (TTF_WasInit())
		TTF_Quit();

	SDL_Quit();
}
Exemplo n.º 9
0
struct s_object *f_environment_new_flags(struct s_object *self, int width, int height, int flags) {
	struct s_environment_attributes *attributes = p_environment_alloc(self);
	int surface, index, initialized_systems;
	t_boolean initialized = d_true;
	for (surface = 0; surface < e_environment_surface_NULL; ++surface)
		for (index = 0; index < d_environment_layers; ++index)
			memset(&(attributes->drawable[surface][index]), 0, sizeof(struct s_list));
	memset(&(attributes->eventable), 0, sizeof(struct s_list));
	if ((initialized_systems = SDL_WasInit(d_environment_default_systems)) != d_environment_default_systems)
		if (SDL_Init(d_environment_default_systems&(d_environment_default_systems&(~initialized_systems))) < 0) {
			d_err(e_log_level_ever, "SDL graphical system returns an error during the initialization (flags 0x%08x)",
					(d_environment_default_systems&(~initialized_systems)));
			initialized = d_false;
		}
	if (initialized) {
		/* TTF initialization */
		if (TTF_WasInit() == 0)
			if (TTF_Init() < 0) {
				initialized = d_false;
				d_err(e_log_level_ever, "SDL font system returns an error during the initialization");
			}
		if ((attributes->window = SDL_CreateWindow(d_environment_default_title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height,
						(flags|SDL_WINDOW_OPENGL))))
			attributes->renderer = SDL_CreateRenderer(attributes->window, -1, (SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC));
	}
	attributes->fps = d_environment_default_fps;
	/* geometry */
	attributes->reference_w = d_environment_default_reference_w;
	attributes->reference_h = d_environment_default_reference_h;
	attributes->current_w = width;
	attributes->current_h = height;
	attributes->camera_origin_x = 0;
	attributes->camera_origin_y = 0;
	attributes->camera_focus_x = (width / 2.0);
	attributes->camera_focus_y = (height / 2.0);
	attributes->zoom = 1;
	attributes->continue_loop = d_true;
	return self;
}
Exemplo n.º 10
0
void Text::setFont(std::string fontFileName, int fontSize, RGBColor fontColor) {
	if (mFontColor)
		delete mFontColor;
	mFontColor = fontColor.getInternalColor();

	if ((mFontFileName.compare(fontFileName) == 0) &&
		(mFontSize == fontSize)) {
		return;
	}

	mFontFileName = fontFileName;
	mFontSize = fontSize;
	if (TTF_WasInit() < 1) {
		logger->log("Weird behaviour: had to init SDL_ttf over again");
		TTF_Init();
	}
	if (mFont)
		TTF_CloseFont(mFont);
	mFont = TTF_OpenFont(mFontFileName.c_str(), mFontSize);
	if (!mFont)
		logger->log("Unable to open font " + mFontFileName + ": " + TTF_GetError());
}
Exemplo n.º 11
0
bool Font::Init( SDL_Renderer* renderer_, const std::string &fontName, int32_t fontSize )
{
	//renderer = renderer_;

	if ( TTF_WasInit() == 0 )
	{
		if ( TTF_Init() == -1 )
		{
			std::cout << "Failed to init TTF! " << TTF_GetError() << std::endl;
			return false;
		}

	}
	font = TTF_OpenFont( fontName.c_str(), fontSize );

	if ( font == nullptr )
	{
		std::cout << "Failed to load font";
		return false;
	}

	return true;
}
Exemplo n.º 12
0
SText::SText()
{
    if ( !TTF_WasInit() )
        TTF_Init();
}
Exemplo n.º 13
0
bool uniInicializar(int largura_janela, int altura_janela, bool tela_cheia, string titulo_janela, int flags_sdl_window)
{
	if (uniEstaInicializada())
	{
		gDebug.erro("uniInicializar() falhou. A biblioteja já foi inicializada anteriormente.");
		return false;
	}

	//	inicializa SDL
	SDL_Init(SDL_INIT_EVERYTHING);
	if (!SDL_WasInit(0))
		return false;

	//	inicializa SDL_ttf (biblioteca de fontes)
	TTF_Init();
	if (!TTF_WasInit())
	{
		SDL_Quit();
		return false;
	}

	//	inicializa globais
	Global::getInstancia().inicializar();

	//	cria janela principal
	bool janela_ok = gJanela.criar(largura_janela, altura_janela, tela_cheia, titulo_janela, flags_sdl_window);
	if (!janela_ok)
	{
		Global::getInstancia().finalizar();
		TTF_Quit();
		SDL_Quit();
		return false;
	}

	uniInicializada = true;		//	seta uniInicializada para true. Precisa ser feito aqui para poder carregar a fonte padrao
	gGraficos.inicializar(gJanela.getSDL_Renderer());
	if (!gGraficos.getFontePadrao())
	{
		//	se a fonte padrao nao foi carregada,
		//  limpa o painel de debug e desativa 
		//	para nao tentar desenhar sem ter uma fonte.
		gDebug.limpar();
		gDebug.desativar();
	}
	uniInicializada = false;	//	volta a ser false para continuar a inicializacao

								//	inicializa painel de debug
	gDebug.inicializar();

	//	inicializa audio
	gAudios.inicializar();
	if (!gAudios.estaInicializado())
	{
		gDebug.finalizar();
		gGraficos.finalizar();
		gJanela.destruir();
		Global::getInstancia().finalizar();
		TTF_Quit();
		SDL_Quit();
		return false;
	}

	//	inicializa handlers de eventos
	gEventos.janela = &gJanela;
	gEventos.mouse = &gMouse;
	gEventos.teclado = &gTeclado;
	gEventos.joysticks = &gJoysticks;
	gEventos.toques = &gToques;
	gEventos.atualizar();

	//	inicializa gerenciador de tempo
	gTempo.inicializar();

	//	seta uniInicializada para true
	uniInicializada = true;

	return true;
}
Exemplo n.º 14
0
void Map::draw_map (SDL_Surface * dest_surf, 
				   Role & player, SDL_Surface *assist_surf)
{
	static int flash = 1;
	int i, j;
	int TileNum;
    SDL_Rect map_src, map_dest, assist_src;

	//画地图元素
	for(i=0;i<10;i++)
	{
		for(j=0;j<15;j++)
		{
			TileNum = Tile[i][j];
            if (TileNum <40||count_in_row==15)
            {
			    map_src.x = (TileNum % count_in_row)*32;
			    map_src.y = (TileNum/count_in_row)*32;
            }
            else 
            {
			    map_src.x = (TileNum % count_in_row)*32+128;
			    map_src.y = (TileNum/count_in_row)*32-320;         
            }
			
			    map_src.w = 32;
			    map_src.h = 32;   

#ifdef PSP
            map_dest.x = j*32;
            map_dest.y = i*27;
			map_dest.w = 32;
			map_dest.h = 27;
#else
            map_dest.x = j*32;
            map_dest.y = i*32;
			map_dest.w = 32;
			map_dest.h = 32;
#endif

            SDL_BlitSurface(Surf, &map_src, dest_surf, &map_dest);
						
			//画场景切换点
			if (Trap[i][j]&& Trap[i][j]<100)
			{
				//SetRect(&Rect_map_dest, j*32, i*32, (j+1)*32, (i+1)*32);
				if (flash > 0) {
                    assist_src.x = 1;
				}
				else {
                    assist_src.x = 36;
				}
                assist_src.y = 176;
                assist_src.w = 35;
                assist_src.h = 35;

                SDL_BlitSurface(assist_surf, &assist_src, dest_surf, &map_dest);
			}

		}
	}
	
	//画Npc
	if (Npc) {
		Role *temp;
		temp = Npc;
		while(temp && (temp->Y < player.Y)) {
			temp->draw_self(dest_surf);
			temp = temp->R;
		}
		player.draw_self(dest_surf);
		while (temp) {
			temp->draw_self(dest_surf);
			temp = temp->R;
		}
	}
	else {
		player.draw_self(dest_surf);
	}
	
    if (!TTF_WasInit()){
        printf("Truetype font engine has not been initialized!\n");
        exit(1);
    }
    SDL_BlitText(Name, dest_surf, SCR_W/2-8, 8, Font, *Color);

	//更新Flash
	flash = -flash;
}
Exemplo n.º 15
0
static mrb_value
mrb_sdl2_ttf_was_init(mrb_state *mrb, mrb_value self)
{
  return (TTF_WasInit() == 0) ? mrb_false_value() : mrb_true_value();
}
Exemplo n.º 16
0
CAMLprim value
caml_SDL_TTF_WasInit(value unit)
{
    CAMLparam1(unit);
    CAMLreturn(Val_bool(TTF_WasInit()));
}
Exemplo n.º 17
0
int main(int argc, char** argv)
{
    int result = 0;

#ifndef DEBUG //in debug mode we wanna have a backtrace
    try {
        std::cout << "Starting " << PACKAGE_NAME << " (version " << PACKAGE_VERSION << ")...\n";
#else
        std::cout << "Starting " << PACKAGE_NAME << " (version " << PACKAGE_VERSION << ") in Debug Mode...\n";
#endif                                                     
        initPhysfs(argv[0]);
        dictionaryManager = new TinyGetText::DictionaryManager();
        dictionaryManager->set_charset("UTF-8");
        dictionaryManager->add_directory("locale");
#ifdef DEBUG
        std::cout << "Language is \"" << dictionaryManager->get_language() << "\".\n";
#endif
        
#ifndef DEBUG
    } catch(std::exception& e) {
        std::cerr << "Unexpected exception: " << e.what() << "\n";        
        return 1;
    } catch(...) {
        std::cerr << "Unexpected exception.\n";
        return 1;
    }                                                                     
#endif

    parseCommandLine(argc, argv);
   
// in debug mode we want a backtrace of the exceptions so we don't catch them
#ifndef DEBUG
    try {
#endif
        xmlInitParser();
        std::auto_ptr<Sound> sound; 
        sound.reset(new Sound()); 
        initSDL();
        initTTF();
        initVideo(getConfig()->videoX, getConfig()->videoY);

        mainLoop();
#ifndef DEBUG
    } catch(std::exception& e) {
        std::cerr << "Unexpected exception: " << e.what() << "\n";
        result = 1;
    } catch(...) {
        std::cerr << "Unexpected exception.\n";
        result = 1;
    }
#endif
    getConfig()->save();
    delete painter;
    delete fontManager;
    delete texture_manager;
    if(TTF_WasInit())
        TTF_Quit();
    if(SDL_WasInit(0))
        SDL_Quit();
    xmlCleanupParser();
    delete dictionaryManager;
    dictionaryManager = 0;
    PHYSFS_deinit();
    if( restart ){
#ifdef WIN32
        //Windows has a Problem with Whitespaces.
        std::string fixWhiteSpaceInPathnameProblem;
	    fixWhiteSpaceInPathnameProblem="\"";
	    fixWhiteSpaceInPathnameProblem+=argv[0];
	    fixWhiteSpaceInPathnameProblem+="\"";
        execlp( argv[0], fixWhiteSpaceInPathnameProblem.c_str(), (char *) NULL );
#else
        execlp( argv[0], argv[0], (char *) NULL );
#endif
    }
    return result;
}
bool CheckFiles()
{
    WasItInit = TTF_WasInit();
    if (Background == NULL) {
        OpenDebugWindow("Background failed to load!");
        return false;
    }
    else if (MenuBackground == NULL) {
        OpenDebugWindow("MenuBackground failed to load!");
        return false;
    }
    else if (EightBitLimit == NULL) {
        OpenDebugWindow("Bens font failed to load!");
        return false;
    }
    else if (CursorSheet == NULL) {
        OpenDebugWindow("CursorSheet failed to load!");
        return false;
    }
    else if (KarmaFuture == NULL) {
        OpenDebugWindow("KarmaFuture failed to load!");
        return false;
    }
    else if (EightBitLimitSmall == NULL) {
        OpenDebugWindow("Bens font small failed to load!");
        return false;
    }
    else if (PausedScreen == NULL) {
        OpenDebugWindow("Pause screen failed to load!");
        return false;
    }
    else if (FrontDed == NULL) {
        OpenDebugWindow("Frontded failed to load!");
        return false;
    }
    else if (HighscoresNormal == NULL) {
        OpenDebugWindow("High Scores Normal failed to load!");
        return false;
    }
    else if (HighscoresMouseover == NULL) {
        OpenDebugWindow("High Scores Mouseover failed to load!");
        return false;
    }
    else if (U1 == NULL) {
        OpenDebugWindow("U1 failed to load!");
        return false;
    }
    else if (R1 == NULL) {
        OpenDebugWindow("R1 failed to load!");
        return false;
    }
    else if (D1 == NULL) {
        OpenDebugWindow("D1 failed to load!");
        return false;
    }
    else if (L1 == NULL) {
        OpenDebugWindow("L1 failed to load!");
        return false;
    }
    else if (StartNormal == NULL) {
        OpenDebugWindow("StartNormal failed to load!");
        return false;
    }
    else if (StartMouseOver == NULL) {
        OpenDebugWindow("StartMouseOver failed to load!");
        return false;
    }
    else if (HighscoresNormal == NULL) {
        OpenDebugWindow("StartNormal failed to load!");
        return false;
    }
    else if (HighscoresMouseover == NULL) {
        OpenDebugWindow("StartMouseOver failed to load!");
        return false;
    }
    else if (KillsImg == NULL) {
        OpenDebugWindow("KillsImg failed to load!");
        return false;
    }
    else if (YouDied == NULL) {
        OpenDebugWindow("YouDied failed to load!");
        return false;
    }
    else if (LivesIcon == NULL) {
        OpenDebugWindow("LivesIcon failed to load!");
        return false;
    }
    else if (YouAreShit == NULL) {
        OpenDebugWindow("You'reShit failed to load!");
        return false;
    }
    else if (Projectile == NULL) {
        OpenDebugWindow("Projectile failed to load!");
        return false;
    }
    else if (BigGrid == NULL) {
        OpenDebugWindow("BigGrid failed to load!");
        return false;
    }
    else if (SmallGrid == NULL) {
        OpenDebugWindow("SmallGrid failed to load!");
        return false;
    }
    else if (SniperFlipped == NULL) {
        OpenDebugWindow("Flipped sniper failed to load!");
        return false;
    }
    else if (Sniper == NULL) {
        OpenDebugWindow("Sniper failed to load!");
        return false;
    }
    else if (EnemyDownClips == NULL) {
        OpenDebugWindow("EnemyDownClips failed to load!");
        return false;
    }
    else if (EnemyUpClips == NULL) {
        OpenDebugWindow("EnemyUpClips failed to load!");
        return false;
    }
    else if (EnemuIndicator == NULL) {
        OpenDebugWindow("Enemy indicator failed to load!");
        return false;
    }
    else if (HighscoresBackground == NULL) {
        OpenDebugWindow("Highscores Background indicator failed to load!");
        return false;
    }
    else if (Background2 == NULL) {
        OpenDebugWindow("Background2 failed to load!");
        return false;
    }
    OpenDebugWindow("All files loaded successfully");
    return true;

}
Exemplo n.º 19
0
static void 
mySDL_init(int w, int h)
{
if (!SDL_WasInit(SDL_INIT_VIDEO))
    {
    int status=SDL_Init(SDL_INIT_VIDEO);
    if (status<0)
        fnError2("sdl-init-video failed.", SDL_GetError());
    }


// init ttf
if (!TTF_WasInit())
    {
    int status=TTF_Init();
    if (status<0)
        fnError2("TTF_Init failed.", SDL_GetError());
    }
    
// FIXME the two following modern fonts do not work properly.
//gFont=TTF_OpenFont("fonts/DroidSansMono.ttf", 12);
//gFont=TTF_OpenFont("fonts/DejaVuSansMono.ttf", 12);
gFont=TTF_OpenFont("fonts/fixedsys.fon", 12);
adjust_cell_size_from_font(gFont);
gFont_zh=TTF_OpenFont("fonts/wqy-zenhei.ttc", 14);
// adjust wide font size according to cell size does not work well, for now.
/*
adjust_wide_font_from_cell_size("fonts/wqy-zenhei.ttc", 
        gDisplay_cell_w, gDisplay_cell_h);
        */

if (gFont==NULL || gFont_zh==NULL)
    fnError2("fail open font cour.ttf/msyh.ttf", SDL_GetError());
int i;
for (i=0; i<4; i++)
    {
    TTF_Font* gFont_tmp= TTF_OpenFont("fonts/fixedsys.fon", 10);
    if (gFont_tmp==NULL)
        fnError2("error load font ", SDL_GetError());
    gDisplayFontNormal[i]=gFont_tmp;
    TTF_SetFontStyle(gFont_tmp, i);
    gDisplayFontWide[i]=gFont_zh;
    }
gDisplayFontCur=gDisplayFontNormal[0];


myInfo_init(500,500);
send_setcellsize_to_adapter(gDisplay_cell_w, gDisplay_cell_h);
myDisplay_init(DISPLAY_W ,DISPLAY_H);
mySDLrunning=1;

/*
info_push_messagef("cell_pix_w=%d, h=%d", gDisplay_cell_w, 
        gDisplay_cell_h);
*/
SDL_Color color={0xff,0xff, 0xff,0xff};
init_font(&myInfoFont, gInfoRenderer, gFont, &color_black);
//init_font(&myDisplayFont, gDisplayRenderer, gFont, &color_black);

SDL_Color textColor={255, 255, 0, 0xff};
static char buf[300]="hello##";
int ii;
for (ii=0; ii<256; ii++)
    buf[ii]=ii+1;
buf[256]=0;
SDL_Surface *textSurface=TTF_RenderText_Blended(gFont, buf, textColor);
if (textSurface==NULL)
    fnWarn("textSurface==NULL");
text_hello=SDL_CreateTextureFromSurface(gInfoRenderer, textSurface);
if (text_hello==NULL)
    fnWarn("text_hello==NULL");
SDL_FreeSurface(textSurface);

}
Exemplo n.º 20
0
 bool FontManager::isInitialized()
 {
     return TTF_WasInit();
 }
Exemplo n.º 21
0
/**
 * Initializes the required resources.
 *
 * Should only be called once, right after starting.
 */
Code initialize(Window **window, Renderer **renderer) {
  char log_buffer[MAXIMUM_STRING_SIZE];
  Uint32 renderer_flags = 0;
  initialize_logger();
  initialize_profiler();
  initialize_settings();
  if (SDL_Init(SDL_INIT_FLAGS)) {
    sprintf(log_buffer, "SDL initialization error: %s.", SDL_GetError());
    log_message(log_buffer);
    return CODE_ERROR;
  }
  SDL_ShowCursor(SDL_DISABLE);
  initialize_joystick();
  if (!TTF_WasInit()) {
    if (TTF_Init()) {
      sprintf(log_buffer, "TTF initialization error: %s.", SDL_GetError());
      log_message(log_buffer);
      return CODE_ERROR;
    }
  }
  if ((IMG_Init(IMG_FLAGS) & IMG_FLAGS) != IMG_FLAGS) {
    sprintf(log_buffer, "Failed to initialize required image support.");
    log_message(log_buffer);
    return CODE_ERROR;
  }
  /**
   * The number of columns and the number of lines are fixed. However, the
   * number of pixels we need for the screen is not. We find this number by
   * experimenting before creating the window.
   */
  /* Log the size of the window we are going to create. */
  *window = create_window(&window_width, &window_height);
  sprintf(log_buffer, "Created a %dx%d window.", window_width, window_height);
  log_message(log_buffer);
  if (*window == NULL) {
    sprintf(log_buffer, "SDL initialization error: %s.", SDL_GetError());
    log_message(log_buffer);
    return CODE_ERROR;
  }
  if (initialize_fonts()) {
    sprintf(log_buffer, "Failed to initialize fonts.");
    log_message(log_buffer);
    return CODE_ERROR;
  }
  if (initialize_font_metrics()) {
    sprintf(log_buffer, "Failed to initialize font metrics.");
    log_message(log_buffer);
    return CODE_ERROR;
  }
  /* Must disable text input to prevent a name capture bug. */
  SDL_StopTextInput();
  set_window_title_and_icon(*window);
  if (get_renderer_type() == RENDERER_HARDWARE) {
    renderer_flags = SDL_RENDERER_ACCELERATED;
  } else {
    renderer_flags = SDL_RENDERER_SOFTWARE;
  }
  *renderer = SDL_CreateRenderer(*window, -1, renderer_flags);
  set_color(*renderer, COLOR_DEFAULT_BACKGROUND);
  clear(*renderer);
  return CODE_OK;
}
Exemplo n.º 22
0
SDLFontEngine::SDLFontEngine() : FontEngine(), active_font(NULL) {
	// Initiate SDL_ttf
	if(!TTF_WasInit() && TTF_Init()==-1) {
		logError("SDLFontEngine: TTF_Init: %s", TTF_GetError());
		exit(2);
	}

	// load the fonts
	// @CLASS SDLFontEngine: Font settings|Description of engine/font_settings.txt
	FileParser infile;
	if (infile.open("engine/font_settings.txt")) {
		while (infile.next()) {
			if (infile.new_section) {
				SDLFontStyle f;
				f.name = infile.section;
				font_styles.push_back(f);
			}

			if (font_styles.empty()) continue;

			SDLFontStyle *style = &(font_styles.back());
			if ((infile.key == "default" && style->path == "") || infile.key == LANGUAGE) {
				// @ATTR $STYLE.default, $STYLE.$LANGUAGE|filename (string), point size (integer), blending (boolean)|Filename, point size, and blend mode of the font to use for this language. $STYLE can be something like "font_normal" or "font_bold". $LANGUAGE can be a 2-letter region code.
				style->path = popFirstString(infile.val);
				style->ptsize = popFirstInt(infile.val);
				style->blend = toBool(popFirstString(infile.val));
				style->ttfont = TTF_OpenFont(mods->locate("fonts/" + style->path).c_str(), style->ptsize);
				if(style->ttfont == NULL) {
					logError("FontEngine: TTF_OpenFont: %s", TTF_GetError());
				}
				else {
					int lineskip = TTF_FontLineSkip(style->ttfont);
					style->line_height = lineskip;
					style->font_height = lineskip;
				}
			}
		}
		infile.close();
	}

	// set the font colors
	Color color;
	if (infile.open("engine/font_colors.txt")) {
		while (infile.next()) {
			// @ATTR menu_normal, menu_bonus, menu_penalty, widget_normal, widget_disabled|r (integer), g (integer), b (integer)|Colors for menus and widgets
			// @ATTR combat_givedmg, combat_takedmg, combat_crit, combat_buff, combat_miss|r (integer), g (integer), b (integer)|Colors for combat text
			// @ATTR requirements_not_met, item_bonus, item_penalty, item_flavor|r (integer), g (integer), b (integer)|Colors for tooltips
			// @ATTR item_$QUALITY|r (integer), g (integer), b (integer)|Colors for item quality. $QUALITY should match qualities used in items/items.txt
			color_map[infile.key] = toRGB(infile.val);
		}
		infile.close();
	}

	// Attempt to set the default active font
	setFont("font_regular");
	if (!active_font) {
		logError("FontEngine: Unable to determine default font!");
		SDL_Quit();
		exit(1);
	}
}
Exemplo n.º 23
0
SDLFontEngine::SDLFontEngine() : FontEngine(), active_font(NULL) {
	// Initiate SDL_ttf
	if(!TTF_WasInit() && TTF_Init()==-1) {
		logError("SDLFontEngine: TTF_Init: %s", TTF_GetError());
		Exit(2);
	}

	// load the fonts
	// @CLASS SDLFontEngine: Font settings|Description of engine/font_settings.txt
	FileParser infile;
	if (infile.open("engine/font_settings.txt")) {
		while (infile.next()) {
			if (infile.new_section && infile.section == "font") {
				SDLFontStyle f;
				f.name = infile.section;
				font_styles.push_back(SDLFontStyle());
			}

			if (font_styles.empty()) continue;

			SDLFontStyle *style = &(font_styles.back());

			if (infile.key == "id") {
				// @ATTR font.id|string|An identifier used to reference this font.
				style->name = infile.val;
			}
			else if (infile.key == "style") {
				// @ATTR font.style|repeatable(["default", predefined_string], filename, int, bool) : Language, Font file, Point size, Blending|Filename, point size, and blend mode of the font to use for this language. Language can be "default" or a 2-letter region code.

				std::string lang = popFirstString(infile.val);

				if ((lang == "default" && style->path == "") || lang == LANGUAGE) {
					style->path = popFirstString(infile.val);
					style->ptsize = popFirstInt(infile.val);
					style->blend = toBool(popFirstString(infile.val));

					style->ttfont = TTF_OpenFont(mods->locate("fonts/" + style->path).c_str(), style->ptsize);
					if(style->ttfont == NULL) {
						logError("FontEngine: TTF_OpenFont: %s", TTF_GetError());
					}
					else {
						int lineskip = TTF_FontLineSkip(style->ttfont);
						style->line_height = lineskip;
						style->font_height = lineskip;
					}
				}
			}
		}
		infile.close();
	}

	// set the font colors
	Color color;
	if (infile.open("engine/font_colors.txt")) {
		while (infile.next()) {
			// @ATTR menu_normal|color|Basic menu text color. Recommended: white.
			// @ATTR menu_bonus|color|Positive menu text color. Recommended: green.
			// @ATTR menu_penalty|color|Negative menu text color. Recommended: red.
			// @ATTR widget_normal|color|Basic widget text color. Recommended: white.
			// @ATTR widget_disabled|color|Disabled widget text color. Recommended: grey.
			// @ATTR combat_givedmg|color|Enemy damage text color. Recommended: white.
			// @ATTR combat_takedmg|color|Player damage text color. Recommended: red.
			// @ATTR combat_crit|color|Enemy critical damage text color. Recommended: yellow.
			// @ATTR requirements_no_met|color|Unmet requirements text color. Recommended: red.
			// @ATTR item_bonus|color|Item bonus text color. Recommended: green.
			// @ATTR item_penalty|color|Item penalty text color. Recommended: red.
			// @ATTR item_flavor|color|Item flavor text color. Recommended: grey.
			color_map[infile.key] = toRGB(infile.val);
		}
		infile.close();
	}

	// Attempt to set the default active font
	setFont("font_regular");
	if (!active_font) {
		logError("FontEngine: Unable to determine default font!");
		Exit(1);
	}
}
Exemplo n.º 24
0
bool Game::setup(unsigned int GameSizeX, unsigned int GameSizeY, unsigned int BPP)
{
    Globals::setGameData(this, GameSizeX, GameSizeY, BPP);
    State::bgColor = 0xff000000;

#if defined(SDL_VIDEO) 

#ifdef DEBUG
    fprintf(stdout, "Initializing SDL Everything\n");
#endif
    if(SDL_Init(SDL_INIT_EVERYTHING) < 0)
    {
        _failtype = -1;
        fprintf(stderr, "Cannot initialize SDL\n");
        return false;
    }

#ifdef DEBUG
    fprintf(stdout, "Setup Game (W: %d H: %d BPP: %d) \n", GameSizeX, GameSizeY, BPP);
#endif

#if defined(SW_RENDER)    
    _screen = SDL_SetVideoMode(Globals::width, Globals::height, BPP, SDL_SWSURFACE);
#elif defined(HW_RENDER)

#if defined(__APPLE__)

#else
    _screen = SDL_SetVideoMode(Globals::width, Globals::height, BPP, SDL_OPENGL);
#endif

#endif    

    if(!_screen) {
        _failtype = -1;
        fprintf(stderr, "Cannot initialize Video Mode\n");
        return false;
    }

    if(TTF_WasInit() == 0) {
#ifdef DEBUG
        fprintf(stdout, "Initializing SDL_TTF\n");
#endif
        if(TTF_Init() < 0) {
            _failtype = -1;
            fprintf(stderr, "Cannot initialize TTF system\n");
            return false;
        }
    }

    SDL_WM_SetCaption(Globals::gameTitle.c_str(), NULL);

    atexit(SDL_Quit);
    atexit(TTF_Quit);

#endif

#if defined(X11_VIDEO) && defined(HW_RENDER)
    int attrListSgl[] = {
        GLX_RGBA, 
        GLX_RED_SIZE, 4,
        GLX_GREEN_SIZE, 4,
        GLX_BLUE_SIZE, 4,
        GLX_DEPTH_SIZE, 16, 
        None};

    int attrListDbl[] = {
        GLX_RGBA, 
        GLX_DOUBLEBUFFER,
        GLX_RED_SIZE, 4,
        GLX_GREEN_SIZE, 4,
        GLX_BLUE_SIZE, 4,
        GLX_DEPTH_SIZE, 16, 
        None};

    XVisualInfo *vi;
    Colormap cmap;
    int dpyWidth, dpyHeight;
    int i;
    int vidModeMajorVersion, vidModeMinorVersion;
    XF86VidModeModeInfo **modes;
    int modeNum;
    int bestMode;
    Atom wmDelete;
    Window winDummy;
    unsigned int borderDummy;

    _GLWin.fs = false;
    bestMode = 0;

    _GLWin.dpy = XOpenDisplay(0);
    _GLWin.screen = DefaultScreen(_GLWin.dpy);
    XF86VidModeQueryVersion(_GLWin.dpy, &vidModeMajorVersion,
            &vidModeMinorVersion);

    XF86VidModeGetAllModeLines(_GLWin.dpy, _GLWin.screen, &modeNum, &modes);

    _GLWin.deskMode = *modes[0];

    for (i = 0; i < modeNum; i++)
    {
        if ((modes[i]->hdisplay == GameSizeX) && (modes[i]->vdisplay == GameSizeY))
        {
            bestMode = i;
        }
    }

    vi = glXChooseVisual(_GLWin.dpy, _GLWin.screen, attrListDbl);
    if(NULL == vi)
    {
        vi = glXChooseVisual(_GLWin.dpy, _GLWin.screen, attrListSgl);
        _GLWin.doublebuffer = false;
    }
    else
    {
        _GLWin.doublebuffer = true;
    }

    _GLWin.ctx = glXCreateContext(_GLWin.dpy, vi, 0, GL_TRUE);

    cmap = XCreateColormap(_GLWin.dpy, RootWindow(_GLWin.dpy, vi->screen),vi->visual, AllocNone);
    _GLWin.attr.colormap = cmap;
    _GLWin.attr.border_pixel = 0;

    if(_GLWin.fs)
    {
        XF86VidModeSwitchToMode(_GLWin.dpy, _GLWin.screen, modes[bestMode]);
        XF86VidModeSetViewPort(_GLWin.dpy, _GLWin.screen, 0, 0);
        dpyWidth = modes[bestMode]->hdisplay;
        dpyHeight = modes[bestMode]->vdisplay;
        XFree(modes);
        _GLWin.attr.override_redirect = True;
        _GLWin.attr.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask |
            StructureNotifyMask;
        _GLWin.win = XCreateWindow(_GLWin.dpy, RootWindow(_GLWin.dpy, vi->screen),
                0, 0, dpyWidth, dpyHeight, 0, vi->depth, InputOutput, vi->visual,
                CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect,
                &_GLWin.attr);
        XWarpPointer(_GLWin.dpy, None, _GLWin.win, 0, 0, 0, 0, 0, 0);
        XMapRaised(_GLWin.dpy, _GLWin.win);
        XGrabKeyboard(_GLWin.dpy, _GLWin.win, True, GrabModeAsync,GrabModeAsync, CurrentTime);
        XGrabPointer(_GLWin.dpy, _GLWin.win, True, ButtonPressMask,
                GrabModeAsync, GrabModeAsync, _GLWin.win, None, CurrentTime);
    }
    else
    {
        _GLWin.attr.event_mask = ExposureMask | KeyPressMask | ButtonPressMask |
            StructureNotifyMask;
        _GLWin.win = XCreateWindow(_GLWin.dpy, RootWindow(_GLWin.dpy, vi->screen),
                0, 0, GameSizeX, GameSizeY, 0, vi->depth, InputOutput, vi->visual,
                CWBorderPixel | CWColormap | CWEventMask, &_GLWin.attr);
        wmDelete = XInternAtom(_GLWin.dpy, "WM_DELETE_WINDOW", True);
        XSetWMProtocols(_GLWin.dpy, _GLWin.win, &wmDelete, 1);
        XSetStandardProperties(_GLWin.dpy, _GLWin.win, Globals::gameTitle.c_str(),
                Globals::gameTitle.c_str(), None, NULL, 0, NULL);
        XMapRaised(_GLWin.dpy, _GLWin.win);
    }

    glXMakeCurrent(_GLWin.dpy, _GLWin.win, _GLWin.ctx);
    XGetGeometry(_GLWin.dpy, _GLWin.win, &winDummy, &_GLWin.x, &_GLWin.y,
            &_GLWin.width, &_GLWin.height, &borderDummy, &_GLWin.bpp);

    XSetStandardProperties(_GLWin.dpy, _GLWin.win, Globals::gameTitle.c_str(),
                           Globals::gameTitle.c_str(), None, NULL, 0, NULL);
    glFlush();
#endif

#if defined(HW_RENDER)
#if defined(VBO)
    
#else
    glViewport(0, 0, Globals::width, Globals::height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45.0f, (GLfloat) Globals::width / (GLfloat) Globals::height, 0.1f, 100.0f);
    glMatrixMode(GL_MODELVIEW);

    glPushAttrib(GL_ENABLE_BIT);
    glDisable(GL_DEPTH_TEST);
    glDisable(GL_CULL_FACE);
    glEnable(GL_TEXTURE_2D);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
    glViewport(0, 0, Globals::width, Globals::height);

    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();

    glOrtho(0.0, (GLdouble)Globals::width,(GLdouble)Globals::height, 0.0, 0.0, 1.0);

    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
#endif
#endif

    return true;
}
Exemplo n.º 25
0
    SpriteFont::SpriteFont(const char* font, int size, char cs, char ce) {
        // Initialize SDL_ttf
        if (!TTF_WasInit()) {
            TTF_Init();
        }
        TTF_Font* f = TTF_OpenFont(font, size);
        if (f == nullptr) {
            fprintf(stderr, "Failed to open TTF font %s\n", font);
            fflush(stderr);
            throw 281;
        }
        _fontHeight = TTF_FontHeight(f);
        _regStart = cs;
        _regLength = ce - cs + 1;
        int padding = size / 8;

        // First neasure all the regions
        glm::ivec4* glyphRects = new glm::ivec4[_regLength];
        int i = 0, advance;
        for (char c = cs; c <= ce; c++) {
            TTF_GlyphMetrics(f, c, &glyphRects[i].x, &glyphRects[i].z, &glyphRects[i].y, &glyphRects[i].w, &advance);
            glyphRects[i].z -= glyphRects[i].x;
            glyphRects[i].x = 0;
            glyphRects[i].w -= glyphRects[i].y;
            glyphRects[i].y = 0;
            i++;
        }

        // Find best partitioning of glyphs
        int rows = 1, w, h, bestWidth = 0, bestHeight = 0, area = MAX_TEXTURE_RES * MAX_TEXTURE_RES, bestRows = 0;
        std::vector<int>* bestPartition = nullptr;
        while (rows <= _regLength) {
            h = rows * (padding + _fontHeight) + padding;
            auto gr = createRows(glyphRects, _regLength, rows, padding, w);

            // Desire a power of 2 texture
            w = closestPow2(w);
            h = closestPow2(h);

            // A texture must be feasible
            if (w > MAX_TEXTURE_RES || h > MAX_TEXTURE_RES) {
                rows++;
                delete[] gr;
                continue;
            }

            // Check for minimal area
            if (area >= w * h) {
                if (bestPartition) delete[] bestPartition;
                bestPartition = gr;
                bestWidth = w;
                bestHeight = h;
                bestRows = rows;
                area = bestWidth * bestHeight;
                rows++;
            } else {
                delete[] gr;
                break;
            }
        }

        // Can a bitmap font be made?
        if (!bestPartition) {
            fprintf(stderr, "Failed to Map TTF font %s to texture. Try lowering resolution.\n", font);
            fflush(stderr);
            throw 282;
        }
        // Create the texture
        glGenTextures(1, &_texID);
        glBindTexture(GL_TEXTURE_2D, _texID);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, bestWidth, bestHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);

        // Now draw all the glyphs
        SDL_Color fg = { 255, 255, 255, 255 };
        int ly = padding;
        for (int ri = 0; ri < bestRows; ri++) {
            int lx = padding;
            for (size_t ci = 0; ci < bestPartition[ri].size(); ci++) {
                int gi = bestPartition[ri][ci];

                SDL_Surface* glyphSurface = TTF_RenderGlyph_Blended(f, (char)(cs + gi), fg);

                // Pre-multiplication occurs here
                unsigned char* sp = (unsigned char*)glyphSurface->pixels;
                int cp = glyphSurface->w * glyphSurface->h * 4;
                for (int i = 0; i < cp; i += 4) {
                    float a = sp[i + 3] / 255.0f;
                    sp[i] = (unsigned char)((float)sp[i] * a);
                    sp[i + 1] = sp[i];
                    sp[i + 2] = sp[i];
                }

                // Save glyph image and update coordinates
                glTexSubImage2D(GL_TEXTURE_2D, 0, lx, bestHeight - ly - 1 - glyphSurface->h, glyphSurface->w, glyphSurface->h, GL_BGRA, GL_UNSIGNED_BYTE, glyphSurface->pixels);
                glyphRects[gi].x = lx;
                glyphRects[gi].y = ly;
                glyphRects[gi].z = glyphSurface->w;
                glyphRects[gi].w = glyphSurface->h;

                SDL_FreeSurface(glyphSurface);
                glyphSurface = nullptr;

                lx += glyphRects[gi].z + padding;
            }
            ly += _fontHeight + padding;
        }

        // Draw the unsupported glyph
        int rs = padding - 1;
        int* pureWhiteSquare = new int[rs * rs];
        memset(pureWhiteSquare, 0xffffffff, rs * rs * sizeof(int));
        glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, rs, rs, GL_RGBA, GL_UNSIGNED_BYTE, pureWhiteSquare);
        delete[] pureWhiteSquare;
        pureWhiteSquare = nullptr;

        // Set some texture parameters
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

        // Create spriteBatch glyphs
        _glyphs = new CharGlyph[_regLength + 1];
        for (i = 0; i < _regLength; i++) {
            _glyphs[i].character = (char)(cs + i);
            _glyphs[i].size = glm::vec2(glyphRects[i].z, glyphRects[i].w);
            _glyphs[i].uvRect = glm::vec4(
                (float)glyphRects[i].x / (float)bestWidth,
                (float)glyphRects[i].y / (float)bestHeight,
                (float)glyphRects[i].z / (float)bestWidth,
                (float)glyphRects[i].w / (float)bestHeight
                );
        }
        _glyphs[_regLength].character = ' ';
        _glyphs[_regLength].size = _glyphs[0].size;
        _glyphs[_regLength].uvRect = glm::vec4(0, 0, (float)rs / (float)bestWidth, (float)rs / (float)bestHeight);

        glBindTexture(GL_TEXTURE_2D, 0);
        delete[] glyphRects;
        delete[] bestPartition;
        TTF_CloseFont(f);
    }
Exemplo n.º 26
0
Typeface::~Typeface() {
	// just in case SDL_ttf is shut down before we get here
	if (TTF_WasInit()) {
		TTF_CloseFont(font);
	}
}
Exemplo n.º 27
0
bool checkInit()
{
	return (SDL_WasInit(sdlInitFlags) == sdlInitFlags) and TTF_WasInit();
}
Exemplo n.º 28
0
bool ModuleFontManager::CleanUp()
{
	if (TTF_WasInit()){ TTF_Quit(); }
	return true;
}