Example #1
0
//
// Initialize the game state
void Renderer::Init(int width, int height)
{
    SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    TTF_Init();

    surface_ = SDL_SetVideoMode(width, height, 32, SDL_OPENGL);
    if (!surface_) {
        Die("Could not create SDL surface");
    }

    glViewport(0, 0, width, height);

    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    width_ = width;
    height_ = height;

    Pack& pack = app_->pack();
    if (pack.contains("fonts/VeraBd.ttf")) {
        PackEntry entry = pack["fonts/VeraBd.ttf"];
        SDL_RWops *rwops = SDL_RWFromMem(entry.data, entry.length);
        font_ = TTF_OpenFontRW(rwops, 1, 16);
    }
}
 /**
  * 初期化します。
  */
int initTextRenderer(SDL_RWops *src,int default_fontsize){
	Font = TTF_OpenFontRW(src,1,default_fontsize);
	//十分に大きな領域を確保
	makeEmptySprite(&RenderingSprite,default_fontsize<<3,default_fontsize<<4,TRUE,TRUE);
	if(Font != NULL) return TRUE;
	return FALSE;
}
Example #3
0
/**
 * @brief Initializes the font system.
 */
void TextSurface::initialize() {

  TTF_Init();

  // first determine the available fonts
  IniFile ini("text/fonts.dat", IniFile::READ);
  for (ini.start_group_iteration(); ini.has_more_groups(); ini.next_group()) {

    // get the font metadata
    std::string font_id = ini.get_group();
    std::string file_name = ini.get_string_value("file", "");
    Debug::check_assertion(file_name.size() > 0, StringConcat() << "Missing font file name in file 'text/fonts.dat' for group '" << font_id << "'");
    int font_size = ini.get_integer_value("size", 0);
    Debug::check_assertion(font_size > 0, StringConcat() << "Missing font size in file 'text/fonts.dat' for group '" << font_id << "'");
    fonts[font_id].file_name = file_name;
    fonts[font_id].font_size = font_size;

    if (ini.get_boolean_value("default", false)) {
      default_font_id = font_id;
    }

    // load the font
    size_t size;
    FileTools::data_file_open_buffer(file_name, &fonts[font_id].buffer, &size);
    fonts[font_id].rw = SDL_RWFromMem(fonts[font_id].buffer, int(size));
    fonts[font_id].internal_font = TTF_OpenFontRW(fonts[font_id].rw, 0, font_size);
    Debug::check_assertion(fonts[font_id].internal_font != NULL, StringConcat() << "Cannot load font from file '" << file_name << "': " << TTF_GetError());
  }

  Debug::check_assertion(default_font_id.size() > 0, "No default font set in file 'text/fonts.dat'");
}
Example #4
0
static TTF_Font *read_font(const char *path, int font_size)
{
	TTF_Font *out;
	SDL_RWops *rw;
	Uint8 *data = (Uint8*)malloc(1 * 1024*1024);
	FILE *fp = fopen(path, "r");

	if (!data) {
		write_log("Malloc failed\n");
		exit(1);
	}
	if (!fp) {
		write_log("Could not open font\n");
		exit(1);
	}
	fread(data, 1, 1 * 1024 * 1024, fp);
	rw = SDL_RWFromMem(data, 1 * 1024 * 1024);
	if (!rw) 
	{
		write_log("Could not create RW: %s\n", SDL_GetError());
		exit(1);
	}
	out = TTF_OpenFontRW(rw, 1, font_size);
	if (!out)
	{
		write_log("Unable to open font %s\n", path);
		exit(1);
	}
	fclose(fp);

	return out;
}
Example #5
0
/**
 * \brief Returns an outline font with the specified size.
 * \param font_id Id of the outline font to get. It must exist.
 * \param size Size to use.
 * \return The font.
 */
TTF_Font& FontResource::get_outline_font(const std::string& font_id, int size) {

  if (!fonts_loaded) {
    load_fonts();
  }

  const auto& kvp = fonts.find(font_id);
  Debug::check_assertion(kvp != fonts.end(), std::string("No such font: '") + font_id + "'");
  FontFile& font = kvp->second;
  Debug::check_assertion(font.bitmap_font == nullptr, std::string("This is not an outline font: '") + font_id + "'");

  std::map<int, OutlineFontReader>& outline_fonts = kvp->second.outline_fonts;

  const auto& kvp2 = outline_fonts.find(size);
  if (kvp2 != outline_fonts.end()) {
    return *kvp2->second.outline_font;
  }

  // First time we want this font with this particular size.
  SDL_RWops_UniquePtr rw = SDL_RWops_UniquePtr(SDL_RWFromMem(
      const_cast<char*>(font.buffer.data()),
      (int) font.buffer.size()
  ));
  TTF_Font_UniquePtr outline_font(TTF_OpenFontRW(rw.get(), 0, size));
  Debug::check_assertion(outline_font != nullptr,
      std::string("Cannot load font from file '") + font.file_name
      + "': " + TTF_GetError()
  );
  OutlineFontReader reader = { std::move(rw), std::move(outline_font) };
  outline_fonts.emplace(size, std::move(reader));
  return *outline_fonts.at(size).outline_font;
}
int load_font(char *fname, int size) {
	char *p;

	free_font();
	font = TTF_OpenFont(fname, size);

	if (!font) {
		//Try to open the in memory font
		SDL_RWops *s;
		s = SDL_RWFromMem(dejavu_sans_ttf, dejavu_sans_ttf_len);
		font = TTF_OpenFontRW(s, 0, size);
		if (font) {
			__android_log_print(ANDROID_LOG_INFO, "BroovPlayer",
					"Open font from memory successful");
		} else {
			__android_log_print(ANDROID_LOG_INFO, "BroovPlayer",
					"Open font from memory failed:%s",
					TTF_GetError());
			return 3;
		}

	}

	/* print some metrics and attributes */
	//printf("size                    : %d\n",size);
	//printf("TTF_FontHeight          : %d\n",TTF_FontHeight(font));
	//printf("TTF_FontAscent          : %d\n",TTF_FontAscent(font));
	//printf("TTF_FontDescent         : %d\n",TTF_FontDescent(font));
	//printf("TTF_FontLineSkip        : %d\n",TTF_FontLineSkip(font));
	//printf("TTF_FontFaceIsFixedWidth: %d\n",TTF_FontFaceIsFixedWidth(font));
	/* cache new glyphs */
	cache_glyphs();

	return 0;
}
Example #7
0
d_define_method(fonts, add_font)(struct s_object *self, unsigned int id, struct s_object *stream, int size) {
	d_using(fonts);
	struct s_stream_attributes *stream_attributes = d_cast(stream, stream);
	char buffer[d_string_buffer_size];
	SDL_RWops *font_block;
	if (fonts_attributes->fonts[id].font) {
		TTF_CloseFont(fonts_attributes->fonts[id].font);
		munmap(fonts_attributes->fonts[id].font_block, fonts_attributes->fonts[id].file_stats.st_size);
	}
	fstat(stream_attributes->descriptor, &(fonts_attributes->fonts[id].file_stats));
	if ((fonts_attributes->fonts[id].font_block = mmap(NULL, fonts_attributes->fonts[id].file_stats.st_size, PROT_READ, MAP_SHARED,
					stream_attributes->descriptor, 0)) != MAP_FAILED) {
		font_block = SDL_RWFromMem(fonts_attributes->fonts[id].font_block, fonts_attributes->fonts[id].file_stats.st_size);
		if (!(fonts_attributes->fonts[id].font = TTF_OpenFontRW(font_block, d_true, size))) {
			munmap(fonts_attributes->fonts[id].font_block, fonts_attributes->fonts[id].file_stats.st_size);
			snprintf(buffer, d_string_buffer_size, "ungenerable TTF for font %s exception",
					d_string_cstring(stream_attributes->string_name));
			d_throw(v_exception_ttf, buffer);
		}
	} else {
		snprintf(buffer, d_string_buffer_size, "wrong type for file %s exception", d_string_cstring(stream_attributes->string_name));
		d_throw(v_exception_wrong_type, buffer);
	}
	return self;
}
Example #8
0
static TTF_Font * Load_Font(int ptsize)
{
  SDL_RWops *sdlrwmem = NULL;

  sdlrwmem = SDL_RWFromConstMem(&FontDump, FontSize);

  return TTF_OpenFontRW(sdlrwmem, 1, ptsize);
}
Example #9
0
File: Fonts.cpp Project: qdii/vcmi
TTF_Font * CTrueTypeFont::loadFont(const JsonNode &config)
{
    int pointSize = config["size"].Float();

    if(!TTF_WasInit() && TTF_Init()==-1)
        throw std::runtime_error(std::string("Failed to initialize true type support: ") + TTF_GetError() + "\n");

    return TTF_OpenFontRW(SDL_RWFromConstMem(data.first.get(), data.second), 1, pointSize);
}
Example #10
0
void CFont::Load(const char *filepath) {
	TiXmlDocument doc(filepath);

	if(!doc.LoadFile()) {
		common->Error("Failed to load font '%s'\n", filepath);
	}

	TiXmlElement *root = doc.FirstChildElement("Font");

	/*  do a "do { ... } while(0)" loop here
		we break the loop if we are sure of
		an syntax error in the font file
    */
	do {
		if(!root) {
			break;
		}

		const char *location = NULL;

		TiXmlElement *elem;
		FOR_EACH_ELEM(root, elem) {
			if(strcmp(elem->Value(), "Size") == 0) {
				TiXmlText *text = elem->FirstChild()->ToText();
				if(!text) {
					continue;
				}
				size = atoi(text->Value());
			} else if(strcmp(elem->Value(), "Location") == 0) {
				TiXmlText *text = elem->FirstChild()->ToText();
				if(!text) {
					continue;
				}
				location = text->Value();
			}
		}

		/* Break if any of these are missing */
		if(!location || !size) {
			break;
		}
	
		/* Load the font. TTF will free the memory for us */
		unsigned int dsize = 0;
		void *data = fileSystem_local.ReadFile(StrUtl::FormatString("data/res/font/%s", location).c_str(), dsize);
	
		font = TTF_OpenFontRW(SDL_RWFromMem(data, (int)dsize), 1, size);
		if(!font) {
			common->Error("Failed to load font data %s: %s\n", filepath, TTF_GetError());
		}

		return;
	} while(0);

	common->Error("The font config file has invalid syntax %s\n", filepath);
}
Example #11
0
_TTF_Font *SharedFontState::getFont(std::string family,
                                    int size)
{
	/* Check for substitutions */
	if (p->subs.contains(family))
		family = p->subs[family];

	/* Find out if the font asset exists */
	const FontSet &req = p->sets[family];

	if (req.regular.empty() && req.other.empty())
	{
		/* Doesn't exist; use built-in font */
		family = "";
	}

	FontKey key(family, size);

	TTF_Font *font = p->pool.value(key);

	if (font)
		return font;

	/* Not in pool; open new handle */
	SDL_RWops *ops;

	if (family.empty())
	{
		/* Built-in font */
		ops = openBundledFont();
	}
	else
	{
		/* Use 'other' path as alternative in case
		 * we have no 'regular' styled font asset */
		const char *path = !req.regular.empty()
		                 ? req.regular.c_str() : req.other.c_str();

		ops = SDL_AllocRW();
		shState->fileSystem().openReadRaw(*ops, path, true);
	}

	// FIXME 0.9 is guesswork at this point
//	float gamma = (96.0/45.0)*(5.0/14.0)*(size-5);
//	font = TTF_OpenFontRW(ops, 1, gamma /** .90*/);
	font = TTF_OpenFontRW(ops, 1, size* .90);

	if (!font)
		throw Exception(Exception::SDLError, "%s", SDL_GetError());

	p->pool.insert(key, font);

	return font;
}
Example #12
0
static mrb_value
mrb_sdl2_ttf_font_initialize(mrb_state *mrb, mrb_value self)
{
  TTF_Font *font = NULL;
  mrb_sdl2_ttf_font_data_t *data =
    (mrb_sdl2_ttf_font_data_t*)DATA_PTR(self);

  if (NULL == data) {
    data = (mrb_sdl2_ttf_font_data_t*)mrb_malloc(mrb, sizeof(mrb_sdl2_ttf_font_data_t));
    if (NULL == data) {
      mrb_raise(mrb, E_RUNTIME_ERROR, "insufficient memory.");
    }
    data->font = NULL;
  }

  if (2 == mrb->c->ci->argc) {
    SDL_RWops *rwops;
    mrb_value object;
    mrb_int size;
    mrb_get_args(mrb, "oi", &object, &size);

    if (mrb_obj_is_kind_of(mrb, object, mrb_class_get_under(mrb, mrb->object_class, "String"))) {
      font = TTF_OpenFont(RSTRING_PTR(object), size);
    } else if (mrb_obj_is_kind_of(mrb, object, mrb_class_get_under(mrb, mod_SDL2, "RWops"))) {
      rwops = mrb_sdl2_rwops_get_ptr(mrb, object);
      font = TTF_OpenFontRW(rwops, 0, size);
    }
  } else if (3 == mrb->c->ci->argc) {
    SDL_RWops *rwops;
    mrb_value object;
    mrb_int size, index;
    mrb_get_args(mrb, "oii", &object, &size, &index);
    if (mrb_obj_is_kind_of(mrb, object, mrb_class_get_under(mrb, mrb->object_class, "String"))) {
      font = TTF_OpenFontIndex(RSTRING_PTR(object), size, index);
    } else if (mrb_obj_is_kind_of(mrb, object, mrb_class_get_under(mrb, mod_SDL2, "RWops"))) {
      rwops = mrb_sdl2_rwops_get_ptr(mrb, object);
      font = TTF_OpenFontIndexRW(rwops, 0, size, index);
    }
  } else {
    mrb_free(mrb, data);
    mrb_raise(mrb, E_ARGUMENT_ERROR, "wrong number of arguments.");
  }
  if (NULL == font) {
    mrb_free(mrb, data);
    mruby_sdl2_raise_error(mrb);
  }

  data->font = font;

  DATA_PTR(self) = data;
  DATA_TYPE(self) = &mrb_sdl2_ttf_font_data_type;
  return self;
}
Example #13
0
void *archive_load_font( const char *filename, int size )
{
	void *asset;
	TTF_Font *font;
	char buf[264];

	if ( asset_acquire((void*)filename) != NULL ) return (void*)filename;
	font = TTF_OpenFontRW( archive_open_file(filename), 1, size );
	if ( font == NULL ) {
		fatal( "Failed to load font %s:\n%s\n", filename, TTF_GetError() );
	}
	SDL_snprintf( buf, 256, "%s:%d", filename, size );
	return asset_create( buf, font, ASSET_FONT );
}
Example #14
0
TTF_Font* LoadFont(const String &file, int fontSize)
{
	TTF_Font *font = nullptr;

	#if defined(__ANDROID__)
		SDL_RWops *f = SDL_RWFromFile(file.c_str(), "rb");
		font = TTF_OpenFontRW(f, 1, fontSize);
	#elif defined(_WIN32)
		font = TTF_OpenFont(file.c_str(), fontSize);
	#endif

	if (font == nullptr)
		logSDLError(std::cout, "OpenFont");

	return font;
}
Example #15
0
// Load new texture from file path
TTF_Font* const Fonts::load(const char* path, int size)
{
	TTF_Font* font = TTF_OpenFontRW(app->fs->load(path), 1, size);

	if (font == NULL)
	{
		LOG("Could not load TTF font with path: %s. TTF_OpenFont: %s", path, TTF_GetError());
	}
	else
	{
		LOG("Successfully loaded font %s size %d", path, size);
		fonts.push_back(font);
	}

	return font;
}
Example #16
0
TTF_Font *loadFontFromPak(char *name, int fontSize)
{
	unsigned long size;
	unsigned char *buffer;
	SDL_RWops *rw;
	TTF_Font *font;

	buffer = uncompressFileRW(name, &size);

	rw = SDL_RWFromMem(buffer, size);

	font = TTF_OpenFontRW(rw, TRUE, fontSize);

	/*free(buffer);*/

	return font;
}
Example #17
0
CachedFont* CText::GetOrOpenFont(FontType font, float size)
{
    Math::IntPoint windowSize = m_engine->GetWindowSize();
    int pointSize = static_cast<int>(size * (windowSize.Length() / REFERENCE_SIZE.Length()));

    if (m_lastCachedFont != nullptr)
    {
        if (m_lastFontType == font && m_lastFontSize == pointSize)
            return m_lastCachedFont;
    }

    auto it = m_fonts.find(font);
    if (it == m_fonts.end())
    {
        m_error = std::string("Invalid font type ") + StrUtils::ToString<int>(static_cast<int>(font));
        return nullptr;
    }

    MultisizeFont* mf = (*it).second;

    auto jt = mf->fonts.find(pointSize);
    if (jt != mf->fonts.end())
    {
        m_lastCachedFont = (*jt).second;
        m_lastFontType = font;
        m_lastFontSize = pointSize;
        return m_lastCachedFont;
    }

    m_lastCachedFont = new CachedFont();
    SDL_RWops* file = CResourceManager::GetSDLFileHandler(mf->fileName);
    if(file == nullptr)
    {
        m_error = std::string("Unable to open file");
        return nullptr;
    }
    m_lastCachedFont->font = TTF_OpenFontRW(file, 1, pointSize);
    if (m_lastCachedFont->font == nullptr)
        m_error = std::string("TTF_OpenFont error ") + std::string(TTF_GetError());

    mf->fonts[pointSize] = m_lastCachedFont;

    return m_lastCachedFont;
}
Example #18
0
   Font::Font(const void* data, int data_size, int font_size)
   {
      // Try to load a font from memory, throw exception on failure.

      // Create a SDL_RWops object from memory (SDL_TTF can load fonts from RWops, but not firectly from memory)
      SDL_RWops* font_rw = SDL_RWFromConstMem(data, data_size);

      if(NULL == font_rw) // Check if the creation of rwops succeeded
      {
         throw std::runtime_error(SDL_GetError());
      }

      // Attempt to load the font from rwops
      m_font = TTF_OpenFontRW(font_rw, 1, font_size);
      if(NULL == m_font)
      {
         throw std::runtime_error(TTF_GetError());
      }
   }
Example #19
0
File: font.c Project: cbhuber/Games
static int open_font(lua_State * L) {
	const char * filename;
	lua_Integer fontsize;
	TTF_Font * font;
	TTF_Font ** ud;
	char adjusted_filename[MAX_ADJUSTED_FILENAME_LEN];
	SDL_RWops * file;
	
	filename = luaL_checkstring(L, 1);
	prepend_data_path(adjusted_filename, filename, MAX_ADJUSTED_FILENAME_LEN);
	file = SDL_RWFromFile(adjusted_filename, "rt");
	fontsize = luaL_checkinteger(L, 2);
	font = TTF_OpenFontRW(file, 1, fontsize);
	if (!font) fatal(TTF_GetError());
	ud = (TTF_Font **) lua_newuserdata(L, sizeof(TTF_Font *));
	if (ud == NULL) fatal("ud NULL in open_font");
	*ud = font;
	return 1;
}
Example #20
0
void SharedFontState::initFontSetCB(SDL_RWops &ops,
                                    const std::string &filename)
{
	TTF_Font *font = TTF_OpenFontRW(&ops, 0, 0);

	if (!font)
		return;

	std::string family = TTF_FontFaceFamilyName(font);
	std::string style = TTF_FontFaceStyleName(font);

	TTF_CloseFont(font);

	FontSet &set = p->sets[family];

	if (style == "Regular")
		set.regular = filename;
	else
		set.other = filename;
}
Example #21
0
TextButton::TextButton() : GuiButton() {
    Name = ClassName;

    TextTransparency = 0;
#ifndef OPENBLOX_NO_GRAPHICS
    needsRecalc = false;
    Font = TTF_OpenFontRW(OpenBlox::AssetLocator::getInstance()->openSDLRW("res://fonts/OpenSans-Regular.ttf"), 0, 20);
    tex = 0;
#endif
    TextBounds = new ob_type::Vector2(0, 0);
    TextColor3 = new ob_type::Color3();

    TextXAlignment = ob_enum::TextXAlignment::Left;
    TextYAlignment = ob_enum::TextYAlignment::Top;

    tw = 0;
    th = 0;

    Text = "";
}
Example #22
0
void *FontInfo::openFont( char *font_file, int ratio1, int ratio2 )
{
    int font_size;
    if ( font_size_xy[0] < font_size_xy[1] )
        font_size = font_size_xy[0];
    else
        font_size = font_size_xy[1];

    FontContainer *fc = &root_font_container;
    while( fc->next ){
        if ( fc->next->size == font_size ) break;
        fc = fc->next;
    }
    if ( !fc->next ){
        fc->next = new FontContainer();
        fc->next->size = font_size;
        FILE *fp = fopen( font_file, "r" );
        if ( fp == NULL ) return NULL;
        fclose( fp );
#if defined(PSP)
        fc->next->rw_ops = SDL_RWFromFile(font_file, "r");
        fc->next->font = TTF_OpenFontRW( fc->next->rw_ops, SDL_TRUE, font_size * ratio1 / ratio2 );
        fc->next->power_resume_number = psp_power_resume_number;
        strcpy(fc->next->name, font_file);
#else
        fc->next->font = TTF_OpenFont( font_file, font_size * ratio1 / ratio2 );
#endif
    }
#if defined(PSP)
    else if (fc->next->power_resume_number != psp_power_resume_number){
        FILE *fp = fopen(fc->next->name, "r");
        fc->next->rw_ops->hidden.stdio.fp = fp;
        fc->next->power_resume_number = psp_power_resume_number;
    }
#endif

    ttf_font = (void*)fc->next->font;
    
    return fc->next->font;
}
Example #23
0
/**
 * \brief Function called by the Lua data file to add a font.
 *
 * - Argument 1 (table): properties of the font.
 *
 * \param l the Lua context that is calling this function
 * \return number of values to return to Lua
 */
int TextSurface::l_font(lua_State* l) {

    luaL_checktype(l, 1, LUA_TTABLE);

    const std::string& font_id = LuaContext::check_string_field(l, 1, "id");
    const std::string& file_name = LuaContext::check_string_field(l, 1, "file");
    int font_size = LuaContext::opt_int_field(l, 1, "size", 11);
    bool is_default = LuaContext::opt_boolean_field(l, 1, "default", false);

    fonts[font_id].file_name = file_name;
    fonts[font_id].font_size = font_size;

    if (is_default || default_font_id.empty()) {
        default_font_id = font_id;
    }

    // Load the font.
    size_t index = file_name.rfind('.');
    std::string extension;
    if (index != std::string::npos) {
        extension = file_name.substr(index);
    }

    if (extension == ".png" || extension == ".PNG") {
        // It's a bitmap font.
        fonts[font_id].bitmap = new Surface(file_name, Surface::DIR_DATA);
    }
    else {
        // It's a normal font.
        size_t size;
        FileTools::data_file_open_buffer(file_name, &fonts[font_id].buffer, &size);
        fonts[font_id].bitmap = NULL;
        fonts[font_id].rw = SDL_RWFromMem(fonts[font_id].buffer, int(size));
        fonts[font_id].internal_font = TTF_OpenFontRW(fonts[font_id].rw, 0, font_size);
        Debug::check_assertion(fonts[font_id].internal_font != NULL,
                               StringConcat() << "Cannot load font from file '" << file_name << "': " << TTF_GetError());
    }

    return 0;
}
Example #24
0
TTF_Font* FontManager::getTTF_Font(std::string filename, int pointsize)
{
	TTFId id;
	id.filename = filename;
	id.pointsize = pointsize;

	std::map<TTFId, TTF_Font*>::iterator iter;
	iter = ttf_fonts.find(id);

	if (iter != ttf_fonts.end())
		return iter->second;

	IDataSource* fontids;
	fontids = FileSystem::get_instance()->ReadFile("@data/" + filename);
	if (!fontids) {
		perr << "Failed to open TTF: @data/" << filename << std::endl;
		return 0;
	}

	// open font using SDL_RWops.
	// Note: The RWops and IDataSource will be deleted by the TTF_Font
	TTF_Font* font = TTF_OpenFontRW(fontids->getRWops(), 1, pointsize);

	if (!font) {
		perr << "Failed to open TTF: @data/" << filename
			 << ": " << TTF_GetError() << std::endl;
		return 0;
	}

	ttf_fonts[id] = font;

#ifdef DEBUG
	pout << "Opened TTF: @data/" << filename << "." << std::endl;
#endif

	return font;
}
Example #25
0
TTF_Font *read_and_alloc_font(const char *path, int pt_size)
{
	TTF_Font *out;
	SDL_RWops *rw;
	Uint8 *data;
	FILE *fp = fopen(path, "r");
	size_t r;

	if (!fp) {
		fprintf(stderr, "Could not open font %s\n", path);
		return NULL;
	}
	data = (Uint8*)xmalloc(1 * 1024*1024);
	r = fread(data, 1, 1 * 1024 * 1024, fp);
	if (r == 0 || ferror(fp))
	{
		free(data);
		return NULL;
	}
	rw = SDL_RWFromMem(data, 1 * 1024 * 1024);
	if (!rw)
	{
		fprintf(stderr, "Could not create RW: %s\n", SDL_GetError());
		free(data);
		return NULL;
	}
	out = TTF_OpenFontRW(rw, 1, pt_size);
	if (!out)
	{
		fprintf(stderr, "TTF: Unable to create font %s (%s)\n",
				path, TTF_GetError());
	}
	fclose(fp);

	return out;
}
Example #26
0
static TTF_Font* open_font(const std::string& fname, int size)
{
	std::string name;
	if(!game_config::path.empty()) {
		name = game_config::path + "/fonts/" + fname;
		if(!filesystem::file_exists(name)) {
			name = "fonts/" + fname;
			if(!filesystem::file_exists(name)) {
				name = fname;
				if(!filesystem::file_exists(name)) {
					ERR_FT << "Failed opening font: '" << name << "': No such file or directory" << std::endl;
					return NULL;
				}
			}
		}

	} else {
		name = "fonts/" + fname;
		if(!filesystem::file_exists(name)) {
			if(!filesystem::file_exists(fname)) {
				ERR_FT << "Failed opening font: '" << name << "': No such file or directory" << std::endl;
				return NULL;
			}
			name = fname;
		}
	}

	SDL_RWops *rwops = filesystem::load_RWops(name);
	TTF_Font* font = TTF_OpenFontRW(rwops, true, size); // SDL takes ownership of rwops
	if(font == NULL) {
		ERR_FT << "Failed opening font: TTF_OpenFont: " << TTF_GetError() << std::endl;
		return NULL;
	}

	return font;
}
Example #27
0
Typeface::Typeface(const std::string& path, int pt) : Asset(path) {
	font = TTF_OpenFontRW(file, 0, pt);
	if (font == NULL) {
		throw std::runtime_error(TTF_GetError());
	}
}
Example #28
0
void setup (void) {
	SDL_Surface * image;
	TTF_Font *temp1, *temp2;
	SDL_Color color;
	SDL_Rect rect, rect2;
	int g;
	char buffer_file[8192];
	char *systemdata_path = get_systemdata_path ();
	
	/* Inicializar el Video SDL */
	if (SDL_Init(SDL_INIT_VIDEO) < 0) {
		fprintf (stderr,
			_("Error: Can't initialize the video subsystem\n"
			"The error returned by SDL is:\n"
			"%s\n"), SDL_GetError());
		exit (1);
	}
	sprintf (buffer_file, "%simages/icon.png", systemdata_path);
	image = IMG_Load (buffer_file);
	if (image) {
		SDL_WM_SetIcon (image, NULL);
		SDL_FreeSurface (image);
	}
	SDL_WM_SetCaption (_("Paddle Puffle"), _("Paddle Puffle"));
	
	/* Crear la pantalla de dibujado */
	screen = set_video_mode (0);
	
	if (screen == NULL) {
		fprintf (stderr,
			_("Error: Can't setup 760x480 video mode.\n"
			"The error returned by SDL is:\n"
			"%s\n"), SDL_GetError());
		exit (1);
	}
	
	use_sound = 1;
	if (SDL_InitSubSystem (SDL_INIT_AUDIO) < 0) {
		fprintf (stdout,
			_("Warning: Can't initialize the audio subsystem\n"
			"Continuing...\n"));
		use_sound = 0;
	}
	
	if (use_sound) {
		/* Inicializar el sonido */
		if (Mix_OpenAudio (22050, AUDIO_S16, 2, 4096) < 0) {
			fprintf (stdout,
				_("Warning: Can't initialize the SDL Mixer library\n"));
			use_sound = 0;
		}
	}
	
	for (g = 0; g < NUM_IMAGES; g++) {
		sprintf (buffer_file, "%s%s", systemdata_path, images_names[g]);
		image = IMG_Load (buffer_file);
		
		if (image == NULL) {
			fprintf (stderr,
				_("Failed to load data file:\n"
				"%s\n"
				"The error returned by SDL is:\n"
				"%s\n"), buffer_file, SDL_GetError());
			SDL_Quit ();
			exit (1);
		}
		
		images[g] = image;
		/* TODO: Mostrar la carga de porcentaje */
	}
	
	/* Pre-Dibujar la pantalla gris */
	grey_screen = SDL_CreateRGBSurface (SDL_SWSURFACE | SDL_SRCALPHA, 760, 480, 32, 0, 0, 0, 0);
	SDL_FillRect (grey_screen, NULL,
	              SDL_MapRGB (grey_screen->format, 0, 0, 0)); /* Negro */
	SDL_SetAlpha (grey_screen, SDL_SRCALPHA, 128); /* Alpha al 50 % */
	
	if (use_sound) {
		for (g = 0; g < NUM_SOUNDS; g++) {
			sprintf (buffer_file, "%s%s", systemdata_path, sound_names[g]);
			sounds[g] = Mix_LoadWAV (buffer_file);
			
			if (sounds[g] == NULL) {
				fprintf (stderr,
					_("Failed to load data file:\n"
					"%s\n"
					"The error returned by SDL is:\n"
					"%s\n"), buffer_file, SDL_GetError ());
				SDL_Quit ();
				exit (1);
			}
			Mix_VolumeChunk (sounds[g], MIX_MAX_VOLUME / 2);
		}
		
		/* Cargar la música */
		sprintf (buffer_file, "%s%s", systemdata_path, MUS_CARNIE);
		mus_carnie = Mix_LoadMUS (buffer_file);
		
		if (mus_carnie == NULL) {
			fprintf (stderr,
				_("Failed to load data file:\n"
				"%s\n"
				"The error returned by SDL is:\n"
				"%s\n"), buffer_file, SDL_GetError ());
			SDL_Quit ();
			exit (1);
		}
		
	}
	
	if (TTF_Init () < 0) {
		fprintf (stderr,
			_("Error: Can't initialize the SDL TTF library\n"
			"%s\n"), TTF_GetError ());
		SDL_Quit ();
		exit (1);
	}
	
	/* Tipografias 10, 14, 16, 26 */
	sprintf (buffer_file, "%s%s", systemdata_path, "ccfacefront.ttf");
	ttf_facefront = SDL_RWFromFile (buffer_file, "rb");
	
	if (ttf_facefront == NULL) {
		fprintf (stderr,
			_("Failed to load font file 'CCFaceFront'\n"
			"The error returned by SDL is:\n"
			"%s\n"), TTF_GetError ());
		SDL_Quit ();
		exit (1);
	}
	
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	temp1 = TTF_OpenFontRW (ttf_facefront, 0, 10);
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	ttf14_normal = TTF_OpenFontRW (ttf_facefront, 0, 14);
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	ttf16_normal = TTF_OpenFontRW (ttf_facefront, 0, 16);
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	ttf26_normal = TTF_OpenFontRW (ttf_facefront, 0, 26);
	
	if (!temp1 || !ttf14_normal || !ttf16_normal || !ttf26_normal) {
		SDL_Quit ();
		exit (1);
	}
	
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	ttf20_normal = TTF_OpenFontRW (ttf_facefront, 0, 20);
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	ttf20_outline = TTF_OpenFontRW (ttf_facefront, 0, 20);
	SDL_RWseek (ttf_facefront, 0, RW_SEEK_SET);
	ttf16_outline = TTF_OpenFontRW (ttf_facefront, 1, 16);
	
	if (!ttf20_normal || !ttf20_outline || !ttf16_outline) {
		SDL_Quit ();
		exit (1);
	}
	
	TTF_SetFontStyle (temp1, TTF_STYLE_ITALIC);
	TTF_SetFontStyle (ttf14_normal, TTF_STYLE_ITALIC);
	TTF_SetFontStyle (ttf16_normal, TTF_STYLE_ITALIC);
	TTF_SetFontStyle (ttf26_normal, TTF_STYLE_ITALIC);
	TTF_SetFontStyle (ttf16_outline, TTF_STYLE_ITALIC);
	TTF_SetFontStyle (ttf20_outline, TTF_STYLE_ITALIC);
	TTF_SetFontStyle (ttf20_normal, TTF_STYLE_ITALIC);
	
	TTF_SetFontOutline (ttf16_outline, OUTLINE_TEXT);
	TTF_SetFontOutline (ttf20_outline, OUTLINE_TEXT);
	
	/* Generar textos */
	bind_textdomain_codeset (PACKAGE, "UTF-8");
	color.r = color.g = color.b = 0; /* Negro */
	
	for (g = 0; g < NUM_TEXTS; g++) {
		switch (text_info [g]) {
			case 10: temp2 = temp1; break;
			case 14: temp2 = ttf14_normal; break;
			case 16: temp2 = ttf16_normal; break;
			case 26: temp2 = ttf26_normal; break;
			default: temp2 = ttf16_normal;
		}
		
		texts[g] = draw_text (temp2, _(text_strings[g]), &color);
	}
	
	/* Copiar la palabra "Tickets" en el background */
	/* También copiar el nombre del juego al titulo y al fondo */
	rect.x = 607 + ((135 - texts[TEXT_TICKETS]->w) / 2); rect.y = 38;
	rect.w = texts[TEXT_TICKETS]->w; rect.h = texts[TEXT_TICKETS]->h;
	rect2.x = 191; rect2.y = 96;
	rect2.w = images[IMG_TITLE]->w; rect2.h = images[IMG_TITLE]->h;
	for (g = IMG_BACKGROUND_NORMAL; g <= IMG_BACKGROUND_FAIL_1; g++) {
		SDL_BlitSurface (texts[TEXT_TICKETS], NULL, images[g], &rect);
		SDL_BlitSurface (images[IMG_TITLE], NULL, images[g], &rect2);
	}
	
	/* X = 84.35, Y = 50.85 */
	rect2.x = 84; rect2.y = 51;
	SDL_BlitSurface (images[IMG_TITLE], NULL, images[IMG_TITLE_OPENING], &rect2);
	
	TTF_CloseFont (temp1);
	/* Generador de números aleatorios */
	srand ((unsigned int) getpid ());
}
Example #29
0
bool font_init(void)
{
bool error = false;

	// we'll be bypassing the NXSurface automatic scaling features
	// and drawing at the real resolution so we can get better-looking fonts.
//	sdl_screen = screen->GetSDLSurface();
	
	// at 320x240 switch to bitmap fonts for better appearance
	#ifdef CONFIG_ENABLE_TTF
	if (SCALE == 1)
	#endif
	{
		stat("fonts: using bitmapped from %s", bmpfontfile);
		
		SDL_RWops* rwops = fileopen_SDL_RWops_RO(bmpfontfile);
		if (!rwops) { staterr("Couldn't open bitmap font file %s: SDL_RWFromFP: %s", bmpfontfile, SDL_GetError()); return 1; }
		SDL_Surface *sheet = SDL_LoadBMP_RW(rwops, 1);
		if (!sheet) { staterr("Couldn't open bitmap font file: SDL_LoadBMP_RW: %s", SDL_GetError()); return 1; }
		
		uint32_t fgindex = SDL_MapRGB(sheet->format, 255, 255, 255);
		
		error = error || whitefont.InitBitmapChars(sheet, fgindex, 0xffffff);
		error = error || greenfont.InitBitmapChars(sheet, fgindex, 0x00ff80);
		error = error || bluefont.InitBitmapChars(sheet, fgindex, 0xa0b5de);
		error = error || shadowfont.InitBitmapCharsShadowed(sheet, fgindex, 0xffffff, 0x000000);
	}
	#ifdef CONFIG_ENABLE_TTF
	else
	{
		// It will get size 8, 17, 26, 35, ...
		// Hope ot will look nice on higher resolutions
		int pointsize = 8 + 9 * (SCALE - 1);
        
		stat("fonts: using truetype at %dpt", pointsize);

		// initilize normal TTF fonts
		if (TTF_Init() < 0)
		{
			staterr("Couldn't initialize SDL_ttf: %s", TTF_GetError());
			return 1;
		}
		
		TTF_Font *font = TTF_OpenFontRW(SDL_RWFromFP(fileopenRO(ttffontfile), SDL_TRUE), 1, pointsize);
		if (!font)
		{
			staterr("Couldn't open font: '%s'", ttffontfile);
			return 1;
		}
		
		error = error || whitefont.InitChars(font, 0xffffff);
		error = error || greenfont.InitChars(font, 0x00ff80);
		error = error || bluefont.InitChars(font, 0xa0b5de);
		error = error || shadowfont.InitCharsShadowed(font, 0xffffff, 0x000000);
		
		TTF_CloseFont(font);
	}
	#endif

	error = error || whitefont.InitTextures();
	error = error || greenfont.InitTextures();
	error = error || bluefont.InitTextures();
	error = error || shadowfont.InitTextures();
	
	error = error || create_shade_sfc();
	if (error) return 1;
	
	fontheight = (whitefont.letters['M']->h / SCALE);
	initilized = true;
	return 0;
}
Example #30
0
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;
}