Changeset - r24900:959a621b6aa9
[Not reviewed]
master
0 6 0
Michael Lutz - 3 years ago 2021-01-16 15:43:31
michi@icosahedron.de
Codechange: Make the simple Malloc sprite allocator globally usable.
6 files changed with 13 insertions and 11 deletions:
0 comments (0 inline, 0 general)
src/fontcache.cpp
Show inline comments
 
@@ -232,175 +232,170 @@ TrueTypeFontCache::~TrueTypeFontCache()
 
 */
 
void TrueTypeFontCache::ClearFontCache()
 
{
 
	if (this->glyph_to_sprite == nullptr) return;
 

	
 
	for (int i = 0; i < 256; i++) {
 
		if (this->glyph_to_sprite[i] == nullptr) continue;
 

	
 
		for (int j = 0; j < 256; j++) {
 
			if (this->glyph_to_sprite[i][j].duplicate) continue;
 
			free(this->glyph_to_sprite[i][j].sprite);
 
		}
 

	
 
		free(this->glyph_to_sprite[i]);
 
	}
 

	
 
	free(this->glyph_to_sprite);
 
	this->glyph_to_sprite = nullptr;
 

	
 
	Layouter::ResetFontCache(this->fs);
 
}
 

	
 

	
 
TrueTypeFontCache::GlyphEntry *TrueTypeFontCache::GetGlyphPtr(GlyphID key)
 
{
 
	if (this->glyph_to_sprite == nullptr) return nullptr;
 
	if (this->glyph_to_sprite[GB(key, 8, 8)] == nullptr) return nullptr;
 
	return &this->glyph_to_sprite[GB(key, 8, 8)][GB(key, 0, 8)];
 
}
 

	
 
void TrueTypeFontCache::SetGlyphPtr(GlyphID key, const GlyphEntry *glyph, bool duplicate)
 
{
 
	if (this->glyph_to_sprite == nullptr) {
 
		DEBUG(freetype, 3, "Allocating root glyph cache for size %u", this->fs);
 
		this->glyph_to_sprite = CallocT<GlyphEntry*>(256);
 
	}
 

	
 
	if (this->glyph_to_sprite[GB(key, 8, 8)] == nullptr) {
 
		DEBUG(freetype, 3, "Allocating glyph cache for range 0x%02X00, size %u", GB(key, 8, 8), this->fs);
 
		this->glyph_to_sprite[GB(key, 8, 8)] = CallocT<GlyphEntry>(256);
 
	}
 

	
 
	DEBUG(freetype, 4, "Set glyph for unicode character 0x%04X, size %u", key, this->fs);
 
	this->glyph_to_sprite[GB(key, 8, 8)][GB(key, 0, 8)].sprite = glyph->sprite;
 
	this->glyph_to_sprite[GB(key, 8, 8)][GB(key, 0, 8)].width = glyph->width;
 
	this->glyph_to_sprite[GB(key, 8, 8)][GB(key, 0, 8)].duplicate = duplicate;
 
}
 

	
 
void *AllocateFont(size_t size)
 
{
 
	return MallocT<byte>(size);
 
}
 

	
 

	
 
/* Check if a glyph should be rendered with anti-aliasing. */
 
static bool GetFontAAState(FontSize size)
 
{
 
	/* AA is only supported for 32 bpp */
 
	if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() != 32) return false;
 

	
 
	switch (size) {
 
		default: NOT_REACHED();
 
		case FS_NORMAL: return _freetype.medium.aa;
 
		case FS_SMALL:  return _freetype.small.aa;
 
		case FS_LARGE:  return _freetype.large.aa;
 
		case FS_MONO:   return _freetype.mono.aa;
 
	}
 
}
 

	
 
bool TrueTypeFontCache::GetDrawGlyphShadow()
 
{
 
	return this->fs == FS_NORMAL && GetFontAAState(FS_NORMAL);
 
}
 

	
 
uint TrueTypeFontCache::GetGlyphWidth(GlyphID key)
 
{
 
	if ((key & SPRITE_GLYPH) != 0) return this->parent->GetGlyphWidth(key);
 

	
 
	GlyphEntry *glyph = this->GetGlyphPtr(key);
 
	if (glyph == nullptr || glyph->sprite == nullptr) {
 
		this->GetGlyph(key);
 
		glyph = this->GetGlyphPtr(key);
 
	}
 

	
 
	return glyph->width;
 
}
 

	
 
const Sprite *TrueTypeFontCache::GetGlyph(GlyphID key)
 
{
 
	if ((key & SPRITE_GLYPH) != 0) return this->parent->GetGlyph(key);
 

	
 
	/* Check for the glyph in our cache */
 
	GlyphEntry *glyph = this->GetGlyphPtr(key);
 
	if (glyph != nullptr && glyph->sprite != nullptr) return glyph->sprite;
 

	
 
	if (key == 0) {
 
		GlyphID question_glyph = this->MapCharToGlyph('?');
 
		if (question_glyph == 0) {
 
			/* The font misses the '?' character. Use built-in sprite.
 
			 * Note: We cannot use the baseset as this also has to work in the bootstrap GUI. */
 
#define CPSET { 0, 0, 0, 0, 1 }
 
#define CP___ { 0, 0, 0, 0, 0 }
 
			static SpriteLoader::CommonPixel builtin_questionmark_data[10 * 8] = {
 
				CP___, CP___, CPSET, CPSET, CPSET, CPSET, CP___, CP___,
 
				CP___, CPSET, CPSET, CP___, CP___, CPSET, CPSET, CP___,
 
				CP___, CP___, CP___, CP___, CP___, CPSET, CPSET, CP___,
 
				CP___, CP___, CP___, CP___, CPSET, CPSET, CP___, CP___,
 
				CP___, CP___, CP___, CPSET, CPSET, CP___, CP___, CP___,
 
				CP___, CP___, CP___, CPSET, CPSET, CP___, CP___, CP___,
 
				CP___, CP___, CP___, CPSET, CPSET, CP___, CP___, CP___,
 
				CP___, CP___, CP___, CP___, CP___, CP___, CP___, CP___,
 
				CP___, CP___, CP___, CPSET, CPSET, CP___, CP___, CP___,
 
				CP___, CP___, CP___, CPSET, CPSET, CP___, CP___, CP___,
 
			};
 
#undef CPSET
 
#undef CP___
 
			static const SpriteLoader::Sprite builtin_questionmark = {
 
				10, // height
 
				8,  // width
 
				0,  // x_offs
 
				0,  // y_offs
 
				ST_FONT,
 
				SCC_PAL,
 
				builtin_questionmark_data
 
			};
 

	
 
			Sprite *spr = BlitterFactory::GetCurrentBlitter()->Encode(&builtin_questionmark, AllocateFont);
 
			Sprite *spr = BlitterFactory::GetCurrentBlitter()->Encode(&builtin_questionmark, SimpleSpriteAlloc);
 
			assert(spr != nullptr);
 
			GlyphEntry new_glyph;
 
			new_glyph.sprite = spr;
 
			new_glyph.width  = spr->width + (this->fs != FS_NORMAL);
 
			this->SetGlyphPtr(key, &new_glyph, false);
 
			return new_glyph.sprite;
 
		} else {
 
			/* Use '?' for missing characters. */
 
			this->GetGlyph(question_glyph);
 
			glyph = this->GetGlyphPtr(question_glyph);
 
			this->SetGlyphPtr(key, glyph, true);
 
			return glyph->sprite;
 
		}
 
	}
 

	
 
	return this->InternalGetGlyph(key, GetFontAAState(this->fs));
 
}
 

	
 
const void *TrueTypeFontCache::GetFontTable(uint32 tag, size_t &length)
 
{
 
	const FontTable::iterator iter = this->font_tables.Find(tag);
 
	if (iter != this->font_tables.data() + this->font_tables.size()) {
 
		length = iter->second.first;
 
		return iter->second.second;
 
	}
 

	
 
	const void *result = this->InternalGetFontTable(tag, length);
 

	
 
	this->font_tables.Insert(tag, std::pair<size_t, const void *>(length, result));
 
	return result;
 
}
 

	
 

	
 
#ifdef WITH_FREETYPE
 
#include <ft2build.h>
 
#include FT_FREETYPE_H
 
#include FT_GLYPH_H
 
#include FT_TRUETYPE_TABLES_H
 

	
 
/** Font cache for fonts that are based on a freetype font. */
 
class FreeTypeFontCache : public TrueTypeFontCache {
 
private:
 
	FT_Face face;  ///< The font face associated with this font.
 

	
 
	void SetFontSize(FontSize fs, FT_Face face, int pixels);
 
	virtual const void *InternalGetFontTable(uint32 tag, size_t &length);
 
	virtual const Sprite *InternalGetGlyph(GlyphID key, bool aa);
 

	
 
@@ -598,97 +593,97 @@ const Sprite *FreeTypeFontCache::Interna
 
{
 
	FT_GlyphSlot slot = this->face->glyph;
 

	
 
	FT_Load_Glyph(this->face, key, aa ? FT_LOAD_TARGET_NORMAL : FT_LOAD_TARGET_MONO);
 
	FT_Render_Glyph(this->face->glyph, aa ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO);
 

	
 
	/* Despite requesting a normal glyph, FreeType may have returned a bitmap */
 
	aa = (slot->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY);
 

	
 
	/* Add 1 pixel for the shadow on the medium font. Our sprite must be at least 1x1 pixel */
 
	uint width  = std::max(1U, (uint)slot->bitmap.width + (this->fs == FS_NORMAL));
 
	uint height = std::max(1U, (uint)slot->bitmap.rows  + (this->fs == FS_NORMAL));
 

	
 
	/* Limit glyph size to prevent overflows later on. */
 
	if (width > MAX_GLYPH_DIM || height > MAX_GLYPH_DIM) usererror("Font glyph is too large");
 

	
 
	/* FreeType has rendered the glyph, now we allocate a sprite and copy the image into it */
 
	SpriteLoader::Sprite sprite;
 
	sprite.AllocateData(ZOOM_LVL_NORMAL, width * height);
 
	sprite.type = ST_FONT;
 
	sprite.colours = (aa ? SCC_PAL | SCC_ALPHA : SCC_PAL);
 
	sprite.width = width;
 
	sprite.height = height;
 
	sprite.x_offs = slot->bitmap_left;
 
	sprite.y_offs = this->ascender - slot->bitmap_top;
 

	
 
	/* Draw shadow for medium size */
 
	if (this->fs == FS_NORMAL && !aa) {
 
		for (uint y = 0; y < (uint)slot->bitmap.rows; y++) {
 
			for (uint x = 0; x < (uint)slot->bitmap.width; x++) {
 
				if (aa ? (slot->bitmap.buffer[x + y * slot->bitmap.pitch] > 0) : HasBit(slot->bitmap.buffer[(x / 8) + y * slot->bitmap.pitch], 7 - (x % 8))) {
 
					sprite.data[1 + x + (1 + y) * sprite.width].m = SHADOW_COLOUR;
 
					sprite.data[1 + x + (1 + y) * sprite.width].a = aa ? slot->bitmap.buffer[x + y * slot->bitmap.pitch] : 0xFF;
 
				}
 
			}
 
		}
 
	}
 

	
 
	for (uint y = 0; y < (uint)slot->bitmap.rows; y++) {
 
		for (uint x = 0; x < (uint)slot->bitmap.width; x++) {
 
			if (aa ? (slot->bitmap.buffer[x + y * slot->bitmap.pitch] > 0) : HasBit(slot->bitmap.buffer[(x / 8) + y * slot->bitmap.pitch], 7 - (x % 8))) {
 
				sprite.data[x + y * sprite.width].m = FACE_COLOUR;
 
				sprite.data[x + y * sprite.width].a = aa ? slot->bitmap.buffer[x + y * slot->bitmap.pitch] : 0xFF;
 
			}
 
		}
 
	}
 

	
 
	GlyphEntry new_glyph;
 
	new_glyph.sprite = BlitterFactory::GetCurrentBlitter()->Encode(&sprite, AllocateFont);
 
	new_glyph.sprite = BlitterFactory::GetCurrentBlitter()->Encode(&sprite, SimpleSpriteAlloc);
 
	new_glyph.width  = slot->advance.x >> 6;
 

	
 
	this->SetGlyphPtr(key, &new_glyph);
 

	
 
	return new_glyph.sprite;
 
}
 

	
 

	
 
GlyphID FreeTypeFontCache::MapCharToGlyph(WChar key)
 
{
 
	assert(IsPrintable(key));
 

	
 
	if (key >= SCC_SPRITE_START && key <= SCC_SPRITE_END) {
 
		return this->parent->MapCharToGlyph(key);
 
	}
 

	
 
	return FT_Get_Char_Index(this->face, key);
 
}
 

	
 
const void *FreeTypeFontCache::InternalGetFontTable(uint32 tag, size_t &length)
 
{
 
	FT_ULong len = 0;
 
	FT_Byte *result = nullptr;
 

	
 
	FT_Load_Sfnt_Table(this->face, tag, 0, nullptr, &len);
 

	
 
	if (len > 0) {
 
		result = MallocT<FT_Byte>(len);
 
		FT_Load_Sfnt_Table(this->face, tag, 0, result, &len);
 
	}
 

	
 
	length = len;
 
	return result;
 
}
 
#endif /* WITH_FREETYPE */
 

	
 

	
 
/**
 
 * (Re)initialize the freetype related things, i.e. load the non-sprite fonts.
 
 * @param monospace Whether to initialise the monospace or regular fonts.
 
 */
 
void InitFreeType(bool monospace)
 
{
 
	for (FontSize fs = FS_BEGIN; fs < FS_END; fs++) {
 
		if (monospace != (fs == FS_MONO)) continue;
 

	
 
		FontCache *fc = FontCache::Get(fs);
 
		if (fc->HasParent()) delete fc;
src/fontcache_internal.h
Show inline comments
 
@@ -29,51 +29,49 @@ protected:
 
	int used_size; ///< Used font size.
 

	
 
	typedef SmallMap<uint32, std::pair<size_t, const void *> > FontTable; ///< Table with font table cache
 
	FontTable font_tables; ///< Cached font tables.
 

	
 
	/** Container for information about a glyph. */
 
	struct GlyphEntry {
 
		Sprite *sprite; ///< The loaded sprite.
 
		byte width;     ///< The width of the glyph.
 
		bool duplicate; ///< Whether this glyph entry is a duplicate, i.e. may this be freed?
 
	};
 

	
 
	/**
 
	 * The glyph cache. This is structured to reduce memory consumption.
 
	 * 1) There is a 'segment' table for each font size.
 
	 * 2) Each segment table is a discrete block of characters.
 
	 * 3) Each block contains 256 (aligned) characters sequential characters.
 
	 *
 
	 * The cache is accessed in the following way:
 
	 * For character 0x0041  ('A'): glyph_to_sprite[0x00][0x41]
 
	 * For character 0x20AC (Euro): glyph_to_sprite[0x20][0xAC]
 
	 *
 
	 * Currently only 256 segments are allocated, "limiting" us to 65536 characters.
 
	 * This can be simply changed in the two functions Get & SetGlyphPtr.
 
	 */
 
	GlyphEntry **glyph_to_sprite;
 

	
 
	GlyphEntry *GetGlyphPtr(GlyphID key);
 
	void SetGlyphPtr(GlyphID key, const GlyphEntry *glyph, bool duplicate = false);
 

	
 
	virtual const void *InternalGetFontTable(uint32 tag, size_t &length) = 0;
 
	virtual const Sprite *InternalGetGlyph(GlyphID key, bool aa) = 0;
 

	
 
public:
 
	TrueTypeFontCache(FontSize fs, int pixels);
 
	virtual ~TrueTypeFontCache();
 
	int GetFontSize() const override { return this->used_size; }
 
	SpriteID GetUnicodeGlyph(WChar key) override { return this->parent->GetUnicodeGlyph(key); }
 
	void SetUnicodeGlyph(WChar key, SpriteID sprite) override { this->parent->SetUnicodeGlyph(key, sprite); }
 
	void InitializeUnicodeGlyphMap() override { this->parent->InitializeUnicodeGlyphMap(); }
 
	const Sprite *GetGlyph(GlyphID key) override;
 
	const void *GetFontTable(uint32 tag, size_t &length) override;
 
	void ClearFontCache() override;
 
	uint GetGlyphWidth(GlyphID key) override;
 
	bool GetDrawGlyphShadow() override;
 
	bool IsBuiltInFont() override { return false; }
 
};
 

	
 
void *AllocateFont(size_t size);
 

	
 
#endif /* FONTCACHE_INTERNAL_H */
src/os/macosx/font_osx.cpp
Show inline comments
 
@@ -288,97 +288,97 @@ const Sprite *CoreTextFontCache::Interna
 
	sprite.type = ST_FONT;
 
	sprite.colours = (use_aa ? SCC_PAL | SCC_ALPHA : SCC_PAL);
 
	sprite.width = width;
 
	sprite.height = height;
 
	sprite.x_offs = (int16)std::round(CGRectGetMinX(bounds));
 
	sprite.y_offs = this->ascender - (int16)std::ceil(CGRectGetMaxY(bounds));
 

	
 
	if (bounds.size.width > 0) {
 
		/* Glyph is not a white-space glyph. Render it to a bitmap context. */
 

	
 
		/* We only need the alpha channel, as we apply our own colour constants to the sprite. */
 
		int pitch = Align(bb_width, 16);
 
		byte *bmp = CallocT<byte>(bb_height * pitch);
 
		CFAutoRelease<CGContextRef> context(CGBitmapContextCreate(bmp, bb_width, bb_height, 8, pitch, nullptr, kCGImageAlphaOnly));
 
		/* Set antialias according to requirements. */
 
		CGContextSetAllowsAntialiasing(context.get(), use_aa);
 
		CGContextSetAllowsFontSubpixelPositioning(context.get(), use_aa);
 
		CGContextSetAllowsFontSubpixelQuantization(context.get(), !use_aa);
 
		CGContextSetShouldSmoothFonts(context.get(), false);
 

	
 
		float offset = 0.5f; // CoreText uses 0.5 as pixel centers. We want pixel alignment.
 
		CGPoint pos{offset - bounds.origin.x, offset - bounds.origin.y};
 
		CTFontDrawGlyphs(this->font.get(), &glyph, &pos, 1, context.get());
 

	
 
		/* Draw shadow for medium size. */
 
		if (this->fs == FS_NORMAL && !use_aa) {
 
			for (uint y = 0; y < bb_height; y++) {
 
				for (uint x = 0; x < bb_width; x++) {
 
					if (bmp[y * pitch + x] > 0) {
 
						sprite.data[1 + x + (1 + y) * sprite.width].m = SHADOW_COLOUR;
 
						sprite.data[1 + x + (1 + y) * sprite.width].a = use_aa ? bmp[x + y * pitch] : 0xFF;
 
					}
 
				}
 
			}
 
		}
 

	
 
		/* Extract pixel data. */
 
		for (uint y = 0; y < bb_height; y++) {
 
			for (uint x = 0; x < bb_width; x++) {
 
				if (bmp[y * pitch + x] > 0) {
 
					sprite.data[x + y * sprite.width].m = FACE_COLOUR;
 
					sprite.data[x + y * sprite.width].a = use_aa ? bmp[x + y * pitch] : 0xFF;
 
				}
 
			}
 
		}
 
	}
 

	
 
	GlyphEntry new_glyph;
 
	new_glyph.sprite = BlitterFactory::GetCurrentBlitter()->Encode(&sprite, AllocateFont);
 
	new_glyph.sprite = BlitterFactory::GetCurrentBlitter()->Encode(&sprite, SimpleSpriteAlloc);
 
	new_glyph.width = (byte)std::round(CTFontGetAdvancesForGlyphs(this->font.get(), kCTFontOrientationDefault, &glyph, nullptr, 1));
 
	this->SetGlyphPtr(key, &new_glyph);
 

	
 
	return new_glyph.sprite;
 
}
 

	
 
/**
 
 * Loads the TrueType font.
 
 * If a CoreText font description is present, e.g. from the automatic font
 
 * fallback search, use it. Otherwise, try to resolve it by font name.
 
 * @param fs The font size to load.
 
 */
 
void LoadCoreTextFont(FontSize fs)
 
{
 
	static const char *SIZE_TO_NAME[] = { "medium", "small", "large", "mono" };
 

	
 
	FreeTypeSubSetting *settings = nullptr;
 
	switch (fs) {
 
		default: NOT_REACHED();
 
		case FS_SMALL:  settings = &_freetype.small;  break;
 
		case FS_NORMAL: settings = &_freetype.medium; break;
 
		case FS_LARGE:  settings = &_freetype.large;  break;
 
		case FS_MONO:   settings = &_freetype.mono;   break;
 
	}
 

	
 
	if (StrEmpty(settings->font)) return;
 

	
 
	CFAutoRelease<CTFontDescriptorRef> font_ref;
 

	
 
	if (settings->os_handle != nullptr) {
 
		font_ref.reset(static_cast<CTFontDescriptorRef>(const_cast<void *>(settings->os_handle)));
 
		CFRetain(font_ref.get()); // Increase ref count to match a later release.
 
	}
 

	
 
	if (!font_ref && MacOSVersionIsAtLeast(10, 6, 0)) {
 
		/* Might be a font file name, try load it. Direct font loading is
 
		 * only supported starting on OSX 10.6. */
 
		CFAutoRelease<CFStringRef> path;
 

	
 
		/* See if this is an absolute path. */
 
		if (FileExists(settings->font)) {
 
			path.reset(CFStringCreateWithCString(kCFAllocatorDefault, settings->font, kCFStringEncodingUTF8));
 
		} else {
 
			/* Scan the search-paths to see if it can be found. */
 
			std::string full_font = FioFindFullPath(BASE_DIR, settings->font);
 
			if (!full_font.empty()) {
 
				path.reset(CFStringCreateWithCString(kCFAllocatorDefault, full_font.c_str(), kCFStringEncodingUTF8));
 
			}
src/os/windows/font_win32.cpp
Show inline comments
 
@@ -487,97 +487,97 @@ void Win32FontCache::ClearFontCache()
 
	/* Add 1 pixel for the shadow on the medium font. Our sprite must be at least 1x1 pixel. */
 
	uint width = std::max(1U, (uint)gm.gmBlackBoxX + (this->fs == FS_NORMAL));
 
	uint height = std::max(1U, (uint)gm.gmBlackBoxY + (this->fs == FS_NORMAL));
 

	
 
	/* Limit glyph size to prevent overflows later on. */
 
	if (width > MAX_GLYPH_DIM || height > MAX_GLYPH_DIM) usererror("Font glyph is too large");
 

	
 
	/* GDI has rendered the glyph, now we allocate a sprite and copy the image into it. */
 
	SpriteLoader::Sprite sprite;
 
	sprite.AllocateData(ZOOM_LVL_NORMAL, width * height);
 
	sprite.type = ST_FONT;
 
	sprite.colours = (aa ? SCC_PAL | SCC_ALPHA : SCC_PAL);
 
	sprite.width = width;
 
	sprite.height = height;
 
	sprite.x_offs = gm.gmptGlyphOrigin.x;
 
	sprite.y_offs = this->ascender - gm.gmptGlyphOrigin.y;
 

	
 
	if (size > 0) {
 
		/* All pixel data returned by GDI is in the form of DWORD-aligned rows.
 
		 * For a non anti-aliased glyph, the returned bitmap has one bit per pixel.
 
		 * For anti-aliased rendering, GDI uses the strange value range of 0 to 64,
 
		 * inclusively. To map this to 0 to 255, we shift left by two and then
 
		 * subtract one. */
 
		uint pitch = Align(aa ? gm.gmBlackBoxX : std::max(gm.gmBlackBoxX / 8u, 1u), 4);
 

	
 
		/* Draw shadow for medium size. */
 
		if (this->fs == FS_NORMAL && !aa) {
 
			for (uint y = 0; y < gm.gmBlackBoxY; y++) {
 
				for (uint x = 0; x < gm.gmBlackBoxX; x++) {
 
					if (aa ? (bmp[x + y * pitch] > 0) : HasBit(bmp[(x / 8) + y * pitch], 7 - (x % 8))) {
 
						sprite.data[1 + x + (1 + y) * sprite.width].m = SHADOW_COLOUR;
 
						sprite.data[1 + x + (1 + y) * sprite.width].a = aa ? (bmp[x + y * pitch] << 2) - 1 : 0xFF;
 
					}
 
				}
 
			}
 
		}
 

	
 
		for (uint y = 0; y < gm.gmBlackBoxY; y++) {
 
			for (uint x = 0; x < gm.gmBlackBoxX; x++) {
 
				if (aa ? (bmp[x + y * pitch] > 0) : HasBit(bmp[(x / 8) + y * pitch], 7 - (x % 8))) {
 
					sprite.data[x + y * sprite.width].m = FACE_COLOUR;
 
					sprite.data[x + y * sprite.width].a = aa ? (bmp[x + y * pitch] << 2) - 1 : 0xFF;
 
				}
 
			}
 
		}
 
	}
 

	
 
	GlyphEntry new_glyph;
 
	new_glyph.sprite = BlitterFactory::GetCurrentBlitter()->Encode(&sprite, AllocateFont);
 
	new_glyph.sprite = BlitterFactory::GetCurrentBlitter()->Encode(&sprite, SimpleSpriteAlloc);
 
	new_glyph.width = gm.gmCellIncX;
 

	
 
	this->SetGlyphPtr(key, &new_glyph);
 

	
 
	return new_glyph.sprite;
 
}
 

	
 
/* virtual */ GlyphID Win32FontCache::MapCharToGlyph(WChar key)
 
{
 
	assert(IsPrintable(key));
 

	
 
	if (key >= SCC_SPRITE_START && key <= SCC_SPRITE_END) {
 
		return this->parent->MapCharToGlyph(key);
 
	}
 

	
 
	/* Convert characters outside of the BMP into surrogate pairs. */
 
	WCHAR chars[2];
 
	if (key >= 0x010000U) {
 
		chars[0] = (WCHAR)(((key - 0x010000U) >> 10) + 0xD800);
 
		chars[1] = (WCHAR)(((key - 0x010000U) & 0x3FF) + 0xDC00);
 
	} else {
 
		chars[0] = (WCHAR)(key & 0xFFFF);
 
	}
 

	
 
	WORD glyphs[2] = { 0, 0 };
 
	GetGlyphIndicesW(this->dc, chars, key >= 0x010000U ? 2 : 1, glyphs, GGI_MARK_NONEXISTING_GLYPHS);
 

	
 
	return glyphs[0] != 0xFFFF ? glyphs[0] : 0;
 
}
 

	
 
/* virtual */ const void *Win32FontCache::InternalGetFontTable(uint32 tag, size_t &length)
 
{
 
	DWORD len = GetFontData(this->dc, tag, 0, nullptr, 0);
 

	
 
	void *result = nullptr;
 
	if (len != GDI_ERROR && len > 0) {
 
		result = MallocT<BYTE>(len);
 
		GetFontData(this->dc, tag, 0, result, len);
 
	}
 

	
 
	length = len;
 
	return result;
 
}
 

	
 

	
 
/**
 
 * Loads the GDI font.
 
 * If a GDI font description is present, e.g. from the automatic font
src/spritecache.cpp
Show inline comments
 
@@ -764,96 +764,104 @@ static void DeleteEntryFromSpriteCache()
 
		}
 
	}
 

	
 
	/* Display an error message and die, in case we found no sprite at all.
 
	 * This shouldn't really happen, unless all sprites are locked. */
 
	if (best == UINT_MAX) error("Out of sprite memory");
 

	
 
	DeleteEntryFromSpriteCache(best);
 
}
 

	
 
static void *AllocSprite(size_t mem_req)
 
{
 
	mem_req += sizeof(MemBlock);
 

	
 
	/* Align this to correct boundary. This also makes sure at least one
 
	 * bit is not used, so we can use it for other things. */
 
	mem_req = Align(mem_req, S_FREE_MASK + 1);
 

	
 
	for (;;) {
 
		MemBlock *s;
 

	
 
		for (s = _spritecache_ptr; s->size != 0; s = NextBlock(s)) {
 
			if (s->size & S_FREE_MASK) {
 
				size_t cur_size = s->size & ~S_FREE_MASK;
 

	
 
				/* Is the block exactly the size we need or
 
				 * big enough for an additional free block? */
 
				if (cur_size == mem_req ||
 
						cur_size >= mem_req + sizeof(MemBlock)) {
 
					/* Set size and in use */
 
					s->size = mem_req;
 

	
 
					/* Do we need to inject a free block too? */
 
					if (cur_size != mem_req) {
 
						NextBlock(s)->size = (cur_size - mem_req) | S_FREE_MASK;
 
					}
 

	
 
					return s->data;
 
				}
 
			}
 
		}
 

	
 
		/* Reached sentinel, but no block found yet. Delete some old entry. */
 
		DeleteEntryFromSpriteCache();
 
	}
 
}
 

	
 
/**
 
 * Sprite allocator simply using malloc.
 
 */
 
void *SimpleSpriteAlloc(size_t size)
 
{
 
	return MallocT<byte>(size);
 
}
 

	
 
/**
 
 * Handles the case when a sprite of different type is requested than is present in the SpriteCache.
 
 * For ST_FONT sprites, it is normal. In other cases, default sprite is loaded instead.
 
 * @param sprite ID of loaded sprite
 
 * @param requested requested sprite type
 
 * @param sc the currently known sprite cache for the requested sprite
 
 * @return fallback sprite
 
 * @note this function will do usererror() in the case the fallback sprite isn't available
 
 */
 
static void *HandleInvalidSpriteRequest(SpriteID sprite, SpriteType requested, SpriteCache *sc, AllocatorProc *allocator)
 
{
 
	static const char * const sprite_types[] = {
 
		"normal",        // ST_NORMAL
 
		"map generator", // ST_MAPGEN
 
		"character",     // ST_FONT
 
		"recolour",      // ST_RECOLOUR
 
	};
 

	
 
	SpriteType available = sc->type;
 
	if (requested == ST_FONT && available == ST_NORMAL) {
 
		if (sc->ptr == nullptr) sc->type = ST_FONT;
 
		return GetRawSprite(sprite, sc->type, allocator);
 
	}
 

	
 
	byte warning_level = sc->warned ? 6 : 0;
 
	sc->warned = true;
 
	DEBUG(sprite, warning_level, "Tried to load %s sprite #%d as a %s sprite. Probable cause: NewGRF interference", sprite_types[available], sprite, sprite_types[requested]);
 

	
 
	switch (requested) {
 
		case ST_NORMAL:
 
			if (sprite == SPR_IMG_QUERY) usererror("Uhm, would you be so kind not to load a NewGRF that makes the 'query' sprite a non-normal sprite?");
 
			FALLTHROUGH;
 
		case ST_FONT:
 
			return GetRawSprite(SPR_IMG_QUERY, ST_NORMAL, allocator);
 
		case ST_RECOLOUR:
 
			if (sprite == PALETTE_TO_DARK_BLUE) usererror("Uhm, would you be so kind not to load a NewGRF that makes the 'PALETTE_TO_DARK_BLUE' sprite a non-remap sprite?");
 
			return GetRawSprite(PALETTE_TO_DARK_BLUE, ST_RECOLOUR, allocator);
 
		case ST_MAPGEN:
 
			/* this shouldn't happen, overriding of ST_MAPGEN sprites is checked in LoadNextSprite()
 
			 * (the only case the check fails is when these sprites weren't even loaded...) */
 
		default:
 
			NOT_REACHED();
 
	}
 
}
 

	
 
/**
 
 * Reads a sprite (from disk or sprite cache).
 
 * If the sprite is not available or of wrong type, a fallback sprite is returned.
 
 * @param sprite Sprite to read.
src/spritecache.h
Show inline comments
 
/*
 
 * This file is part of OpenTTD.
 
 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
 
 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 
 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
 
 */
 

	
 
/** @file spritecache.h Functions to cache sprites in memory. */
 

	
 
#ifndef SPRITECACHE_H
 
#define SPRITECACHE_H
 

	
 
#include "gfx_type.h"
 
#include "spriteloader/spriteloader.hpp"
 

	
 
/** Data structure describing a sprite. */
 
struct Sprite {
 
	uint16 height; ///< Height of the sprite.
 
	uint16 width;  ///< Width of the sprite.
 
	int16 x_offs;  ///< Number of pixels to shift the sprite to the right.
 
	int16 y_offs;  ///< Number of pixels to shift the sprite downwards.
 
	byte data[];   ///< Sprite data.
 
};
 

	
 
extern uint _sprite_cache_size;
 

	
 
typedef void *AllocatorProc(size_t size);
 

	
 
void *SimpleSpriteAlloc(size_t size);
 
void *GetRawSprite(SpriteID sprite, SpriteType type, AllocatorProc *allocator = nullptr, SpriteEncoder *encoder = nullptr);
 
bool SpriteExists(SpriteID sprite);
 

	
 
SpriteType GetSpriteType(SpriteID sprite);
 
uint GetOriginFileSlot(SpriteID sprite);
 
uint32 GetSpriteLocalID(SpriteID sprite);
 
uint GetSpriteCountForSlot(uint file_slot, SpriteID begin, SpriteID end);
 
uint GetMaxSpriteID();
 

	
 

	
 
static inline const Sprite *GetSprite(SpriteID sprite, SpriteType type)
 
{
 
	assert(type != ST_RECOLOUR);
 
	return (Sprite*)GetRawSprite(sprite, type);
 
}
 

	
 
static inline const byte *GetNonSprite(SpriteID sprite, SpriteType type)
 
{
 
	assert(type == ST_RECOLOUR);
 
	return (byte*)GetRawSprite(sprite, type);
 
}
 

	
 
void GfxInitSpriteMem();
 
void GfxClearSpriteCache();
 
void IncreaseSpriteLRU();
 

	
 
void ReadGRFSpriteOffsets(byte container_version);
 
size_t GetGRFSpriteOffset(uint32 id);
 
bool LoadNextSprite(int load_index, byte file_index, uint file_sprite_id, byte container_version);
 
bool SkipSpriteData(byte type, uint16 num);
 
void DupSprite(SpriteID old_spr, SpriteID new_spr);
 

	
 
#endif /* SPRITECACHE_H */
0 comments (0 inline, 0 general)