🔤 fonts#

Shared building blocks for the custom bitmap fonts StewBeet generates.

Imports are explicit rather than star imports: this package is re-exported all the way up to the top-level stewbeet namespace, and star importing would leak PIL.Image and friends into it.

allocator#

Unicode glyph allocation for Minecraft bitmap fonts.

Every visual element rendered inside a text component (item icon, recipe template, page background, invisible spacer) is a PNG mapped to a character inside a Minecraft bitmap font. This module owns the counter handing out those characters and the provider registry backing the generated font JSON.

get_font(i: int) → str[source]#

Return the unicode character used for a glyph index.

Minecraft only allows characters starting at 0x0020, so the index is offset by that.

>>> get_font(0)
' '
>>> get_font(0x0035) == chr(0x0055)
True
class GlyphAllocator(
project_id: str,
next_craft_font: int = 32768,
providers: list[JsonDict] = <factory>,
lock: lock = <factory>,
first_char_by_file: dict[str,
str]=<factory>,
space_chars: dict[int,
str]=<factory>,
space_provider: JsonDict | None = None,
)[source]#

Bases: object

Owns the dynamic unicode counter and the bitmap font-provider registry.

This is the single source of truth for a generated font’s providers. All mutating methods are guarded by a lock so callers can prepare their glyphs from several threads.

>>> alloc = GlyphAllocator(project_id="test")
>>> a, b = alloc.allocate(), alloc.allocate()
>>> a != b
True
>>> char = alloc.register_image("test:font/example.png", ascent=8, height=16)
>>> alloc.register_image("test:font/example.png", ascent=8, height=16) == char  # deduped by file
True
>>> alloc.to_font_json()["providers"][0]["file"]
'test:font/example.png'
project_id: str[source]#

Namespace of the project owning the font.

next_craft_font: int[source]#

Next dynamic code point to hand out (see allocate()).

providers: list[JsonDict][source]#

Bitmap providers accumulated for the generated font JSON.

lock: lock[source]#

Guards the counter and provider list for multithreaded glyph preparation.

first_char_by_file: dict[str, str][source]#

First registered glyph char per provider file (index for find_char_by_file()).

space_chars: dict[int, str][source]#

Advance in pixels -> glyph char, for the characters handed out by add_space().

space_provider: JsonDict | None[source]#

The single space provider collecting those characters, created on first use.

allocate() → str[source]#

Reserve and return the next free dynamic glyph character.

add_provider(
char: str,
file: str,
ascent: int,
height: int,
) → None[source]#

Register a bitmap provider mapping char to the texture file.

add_space(advance: int) → str[source]#

Return a glyph char drawing nothing and moving the pen by advance pixels.

Negative advances are how a spliced image gets put back together: they bring the pen back to the left edge before the next row is drawn. All of them share one space provider, and the same advance always hands back the same character.

>>> alloc = GlyphAllocator(project_id="test")
>>> back = alloc.add_space(-64)
>>> alloc.add_space(-64) == back  # deduped by advance
True
>>> alloc.to_font_json()["providers"][0]["advances"][back]
-64
find_char_by_file(file: str) → str | None[source]#

Return the glyph char already registered for file (dedupe), if any.

register_image(
file: str,
ascent: int,
height: int,
) → str[source]#

Allocate a glyph for file (deduped by file) and register its provider.

Returns the glyph character.

to_font_json() → JsonDict[source]#

Build the font definition holding every registered provider.

colors#

Color analysis and recoloring for generated font atlases.

Used to tint a packaged glyph atlas towards the colors of a project logo, so a generated font looks like it belongs to the pack instead of shipping a hardcoded palette.

MIN_SATURATION: float = 0.15[source]#

Pixels below this saturation count as gray and are ignored when looking for a dominant color.

MIN_VALUE: float = 0.15[source]#

Pixels below this brightness count as black and are ignored when looking for a dominant color.

HUE_BUCKETS: int = 24[source]#

Number of hue groups colored pixels are bucketed into.

NO_RECOLOR_VALUES: tuple[str, ...] = ('', 'no', 'none', 'false', 'off', 'keep')[source]#

Configuration strings asking for the packaged atlas colors to be kept as-is.

Pixel = Pixel[source]#

A RGBA pixel.

get_pixels(
image: Image,
) → list[Pixel][source]#

Return every pixel of an image as row-major RGBA tuples.

>>> get_pixels(Image.new("RGBA", (2, 1), (1, 2, 3, 4)))
[(1, 2, 3, 4), (1, 2, 3, 4)]
get_dominant_color(
image: Image,
) → tuple[int, int, int] | None[source]#

Dominant color of an image ignoring transparent, gray and dark pixels, None when no colored pixel is left.

The remaining pixels are grouped by hue and weighted by saturation * value, so a small vivid area beats a large washed-out one. The result is the average color of the heaviest hue group.

>>> get_dominant_color(Image.new("RGBA", (4, 4), (30, 90, 200, 255)))
(30, 90, 200)
>>> get_dominant_color(Image.new("RGBA", (4, 4), (128, 128, 128, 255))) is None  # Gray
True
>>> get_dominant_color(Image.new("RGBA", (4, 4), (200, 30, 30, 0))) is None  # Transparent
True
recolor_image(
image: Image,
target: tuple[int, int, int],
) → Image[source]#

Recolor an image so that its average opaque pixel becomes target.

Hues are rotated by a constant offset while saturation and brightness are scaled, so the gradients of the source image survive instead of being flattened to a single flat color. Alpha is untouched.

Returns:

A new RGBA image using the target color range.

>>> single = Image.new("RGBA", (2, 2), (255, 162, 20, 255))
>>> recolor_image(single, (20, 100, 255)).getpixel((0, 0))  # A single color lands on the target
(20, 100, 255, 255)
>>> recolor_image(Image.new("RGBA", (2, 2), (0, 0, 0, 0)), (20, 100, 255)).getpixel((0, 0))
(0, 0, 0, 0)
parse_color(
raw: object,
logo_path: str | None = None,
config_key: str = 'color',
) → tuple[int, int, int] | None[source]#

Resolve a user-supplied color value into the RGB an atlas should be recolored to.

Accepted values are "auto" (derive it from the logo), any color Pillow understands ("#55FFFF", "gold", [85, 255, 255]), or a falsy value / "none" to keep the packaged colors untouched.

Parameters:
  • logo_path – Path to the logo used by the "auto" mode.

  • config_key – Name shown in the warning emitted for an unparsable color.

>>> parse_color("gold")
(255, 215, 0)
>>> parse_color("auto") is None  # "auto" without a logo has nothing to derive from
True

image_utils#

PIL helpers shared by every glyph generator.

PNG_INDEX_NAME: str = '_png_index.json'[source]#

File kept next to the pngs save_png writes, recording what each of them holds.

png_indexes: dict[str, dict[str, list[str | int]]] = {}[source]#

Loaded indexes by directory: file name to [pixels digest, size, mtime in ns] of the file save_png last wrote.

dirty_png_indexes: set[str] = {}[source]#

Directories whose index changed since the last flush_png_indexes.

png_index_lock: lock = <unlocked _thread.lock object>[source]#

Guards the two variables above.

lighten_color(
color_hex: int,
factor: float = 1.42,
) → tuple[int, int, int, int][source]#

Lighten a packed RGB color by a factor and return RGBA.

>>> lighten_color(0x803721)
(182, 78, 47, 255)
careful_resize(
image: Image,
max_result_size: int,
resampling: Resampling = Resampling.NEAREST,
) → Image[source]#

Resize an image while keeping the aspect ratio.

>>> careful_resize(Image.new("RGBA", (64, 32)), 32).size
(32, 16)
>>> careful_resize(Image.new("RGBA", (16, 64)), 32).size
(8, 32)
ensure_rgba_color(
c: tuple[int, ...],
) → tuple[int, int, int, int][source]#

Ensure the color is in RGBA format.

>>> ensure_rgba_color((10, 20, 30))
(10, 20, 30, 255)
>>> ensure_rgba_color((10, 20, 30, 40))
(10, 20, 30, 40)
add_border(
image: Image,
border_color: tuple[int, int, int, int],
border_size: int,
) → Image[source]#

Add a colored border around the opaque region of an image (alpha dilation).

pixels_digest(image: Image) → str[source]#

A digest of everything Pillow writes in a png: mode, size, palette, info and pixels.

>>> pixels_digest(Image.new("RGBA", (2, 2), "red")) == pixels_digest(Image.new("RGBA", (2, 2), "red"))
True
>>> pixels_digest(Image.new("RGBA", (2, 2), "red")) == pixels_digest(Image.new("RGBA", (2, 2), "blue"))
False
save_png(image: Image, path: str) → None[source]#

Save an image as png, unless the file there already holds what save_png wrote from the same pixels.

Encoding is the costly part of generated fonts, and most of them do not change between builds. The file’s size and modification time are checked too, so a file changed by anything else is written again. Call flush_png_indexes once the build wrote its images, or the next one encodes them all again.

>>> import tempfile
>>> with tempfile.TemporaryDirectory() as tmp:
...     path = os.path.join(tmp, "red.png")
...     save_png(Image.new("RGBA", (2, 2), "red"), path)
...     before = os.stat(path).st_mtime_ns
...     save_png(Image.new("RGBA", (2, 2), "red"), path)
...     os.stat(path).st_mtime_ns == before
True
source_key(source: str, *parameters: object) → str | None[source]#

A key for an image drawn from the file at source with parameters, None when there is no such file.

The StewBeet version is part of it, since the templates drawn along come with the package.

>>> source_key("missing.png") is None
True
stewbeet_version() → str[source]#

Installed StewBeet version, or “unknown” when the package metadata is not there.

is_png_recorded(path: str, key: str | None) → bool[source]#

Whether the png at path is the one record_png recorded as drawn from key, untouched since.

A generator checks it before even opening its sources, which is what saves the decoding and resizing as well as the encoding.

>>> import tempfile
>>> with tempfile.TemporaryDirectory() as tmp:
...     path = os.path.join(tmp, "red.png")
...     save_png(Image.new("RGBA", (2, 2), "red"), path)
...     before = is_png_recorded(path, "key")
...     record_png(path, "key")
...     before, is_png_recorded(path, "key"), is_png_recorded(path, "other key")
(False, True, False)
record_png(path: str, key: str | None) → None[source]#

Record the png just written at path as drawn from key, see is_png_recorded.

file_signature(
digest: str,
path: str,
) → list[str | int] | None[source]#

The index entry describing the file at path as holding digest, None when there is no file.

load_png_index(directory: str) → dict[str, list[str | int]][source]#

The index of a directory, read from disk the first time.

flush_png_indexes() → None[source]#

Write the indexes save_png changed, and forget the loaded ones so the next build reads them again.

item_images#

Per-item PNG renders, the image source behind every item glyph.

Three kinds of item ids resolve differently: project items are rasterized from their resource pack model with model_resolver, minecraft: items are downloaded from the wiki, and items belonging to any other pack are read from disk (the project is expected to drop them there itself).

The resulting folder is shared by every consumer, so an item is only ever rendered once per build.

DEFAULT_ISO_RENDERS_PATH: str = 'manual_cache/items'[source]#

Folder used when neither ‘iso_renders_path’ nor the deprecated ‘manual.cache_path’ is configured.

iso_renders_path() → str[source]#

Folder holding the per-item PNG renders.

Reads meta.stewbeet.iso_renders_path, falling back to the deprecated meta.stewbeet.manual.cache_path suffixed with /items so existing projects keep their folder.

Returns:

Path to the renders folder, e.g. "manual_cache/items".

Return type:

str

item_image_path(item_id: str) → str[source]#

Path of the PNG backing an item id, whether it exists yet or not.

Parameters:

item_id – Fully qualified item id, e.g. "minecraft:stone".

Returns:

Path inside the renders folder, e.g. "manual_cache/items/minecraft/stone.png".

Return type:

str

get_session() → requests.Session[source]#

HTTP session of the current thread, created on first use.

requests is imported here rather than at module level, since this module is reachable from the top-level stewbeet package and the HTTP stack costs a fifth of a second on every build, even one that downloads no texture.

download_item(
path: str,
item: str,
cache_assets: bool,
destination: str = '',
) → None[source]#

Download a single vanilla item texture from the wiki.

download_vanilla_textures(
path: str,
used_vanilla_items: set[str],
cache_assets: bool,
) → None[source]#

Download vanilla item textures from the wiki using multithreading.

collect_used_vanilla_items() → set[str][source]#

Collect all vanilla items referenced in recipes across all definitions.

recipe_items(
recipe: RecipeBase,
) → list[str][source]#

The item ids a recipe names, its ingredients and its result, tags left out.

build_model_resolver_queue(
path: str,
ns: str,
cache_assets: bool,
only: Iterable[str] | None = None,
) → dict[str, str | Item][source]#

Build the queue of items that need iso renders generated.

A StewBeet definition knows which model backs its item. Without one, the conventional item/<id> model of the resource pack is used instead, so a plain beet project gets its items rendered too rather than having to supply the PNGs by hand.

Parameters:
  • path – Renders folder.

  • ns – Project namespace.

  • cache_assets – Skip items whose PNG already exists.

  • only – Restrict to these item ids, or None for every definition.

Returns:

Mapping of destination PNG path to the resource pack model to render, or to the definition

whose user-set “item_model” component is rendered through its items/ definition.

Return type:

dict[str, str | Item]

render_source(
item: str,
ns: str,
) → str | Item | None[source]#

What model_resolver renders an item from, None when there is nothing to render.

Returns:

The definition when its “item_model” component is user-set, else the resource pack model path.

run_model_resolver(
for_model_resolver: dict[str, str | Item],
) → None[source]#

Run the model resolver to generate iso renders for a queue built by build_model_resolver_queue.

copy_painting_textures(
path: str,
ns: str,
cache_assets: bool,
) → None[source]#

Download and copy painting textures for custom painting items.

generate_all_iso_renders(
renders_path: str = '',
project_id: str = '',
cache_assets: bool = True,
ignore_vanilla: bool = False,
ignore_painting: bool = False,
) → None[source]#

Generate iso renders for every item plus download referenced vanilla textures.

Parameters:
  • renders_path – Renders folder, defaults to iso_renders_path().

  • project_id – Project namespace, defaults to the context one.

  • cache_assets – Skip items whose PNG already exists.

  • ignore_vanilla – Skip downloading the vanilla textures used by recipes.

  • ignore_painting – Skip copying the painting textures.

ensure_item_images(
item_ids: Iterable[str],
cache_assets: bool = True,
) → dict[str, str][source]#

Make sure a PNG exists for every given item id, generating or downloading what is missing.

The three namespace kinds are batched: project items go through a single model_resolver run, minecraft: items through a single multithreaded download, and any other namespace is expected to already be on disk, in iso_renders_path or else in textures_folder. Only textures_folder survives stewbeet clean, so it is where hand made images belong.

Parameters:
  • item_ids – Item ids, namespaced or bare (bare means the project namespace).

  • cache_assets – Reuse the PNGs that already exist instead of regenerating them.

Returns:

Mapping of fully qualified item id to PNG path, missing ones left out.

Return type:

dict[str, str]

image_on_disk(item: str, ns: str) → str | None[source]#

Where the PNG of a qualified item id is, in the renders cache or else, for another pack’s item, among the project textures.

Warns, naming every place looked at, when it is in none of them.

resolve_item_image(
item_id: str,
cache_assets: bool = True,
) → str | None[source]#

Path of the PNG for a single item id, generating or downloading it when needed.

Parameters:
  • item_id – Item id, namespaced or bare (bare means the project namespace).

  • cache_assets – Reuse the PNG if it already exists instead of regenerating it.

Returns:

Path to the PNG, or None when it could not be resolved.

Return type:

str | None

providers#

Writing bitmap font providers into the resource pack.

Minecraft fonts are additive: several generators may contribute providers to the same font file, so every write merges into whatever is already there instead of replacing it.

FONT_MAX_LEVEL: int = 2[source]#

Indentation depth of a generated font file: one line per provider, which stays readable in a diff.

iter_fonts(
component: TextComponent,
) → Iterator[str][source]#

Yield every font id a text component references, its nested lists and parts included.

Parameters:

component – Text component to inspect.

Returns:

Each "namespace:font" found, in reading order, duplicates included.

Return type:

Iterator[str]

>>> list(iter_fonts([{"text": "a"}, [{"text": "b", "font": "mypack:tooltip"}]]))
['mypack:tooltip']
>>> list(iter_fonts({"text": "a", "extra": [{"text": "b", "font": "mypack:glyphs"}]}))
['mypack:glyphs']
>>> list(iter_fonts("plain string"))
[]
uses_font(
component: TextComponent,
font: str,
) → bool[source]#

Recursively check whether a text component (or any of its parts) renders with font.

Parameters:
  • component – Text component to inspect.

  • font – Fully qualified font id, e.g. "mypack:tooltip".

Returns:

True when at least one part of the component uses that font.

Return type:

bool

>>> uses_font([{"text": "a"}, {"text": "b", "font": "mypack:tooltip"}], "mypack:tooltip")
True
>>> uses_font({"text": "a", "extra": [{"text": "b", "font": "mypack:tooltip"}]}, "mypack:tooltip")
True
>>> uses_font("plain string", "mypack:tooltip")
False
merge_font_providers(
namespace: str,
font_name: str,
providers: list[JsonDict],
) → Font[source]#

Append providers to the <namespace>:<font_name> font, creating it when missing.

Parameters:
  • namespace – Resource pack namespace holding the font.

  • font_name – Font file name, without the namespace, e.g. "tooltip".

  • providers – Providers to append to the existing ones.

Returns:

The font object stored in the resource pack.

Return type:

Font

write_font_from_allocator(
namespace: str,
font_name: str,
allocator: GlyphAllocator,
) → Font[source]#

Merge every provider an allocator collected into the <namespace>:<font_name> font.

Parameters:
  • namespace – Resource pack namespace holding the font.

  • font_name – Font file name, without the namespace, e.g. "manual".

  • allocator – Allocator whose providers should be written.

Returns:

The font object stored in the resource pack.

Return type:

Font

validate_font_providers(
namespace: str,
providers: list[JsonDict],
) → None[source]#

Error out if any provider references a missing texture or maps no character.

Parameters:
  • namespace – Resource pack namespace the textures live in.

  • providers – Providers to check.

splicing#

Cutting an oversized image into the grid of glyphs Minecraft can actually draw.

Minecraft stitches every bitmap glyph into a 256x256 font atlas, and one that fits in no sheet is drawn as the missing-character box instead, so a bigger picture has to be cut into tiles. Each tile becomes its own glyph, and the text component puts them back together: the tiles of a row sit side by side, negative spacing brings the pen back to the left edge, and the next row hangs from a lower ascent.

Two rules drive the geometry, both taken from the game’s own code (BitmapProvider, FontTexture and DynamicAtlasTree):

  • BitmapProvider.Definition.validate rejects a provider whose ascent exceeds its height, which means no row may stop above the baseline. The topmost row therefore always reaches down to it, and the part of the image standing above the baseline is what caps the resolution: it has to fit in a single glyph.

  • Spacing is whole pixels only, so tiles line up seamlessly only when each is an exact number of screen pixels wide. Hence scale: the stored texture is an integer multiple of the displayed size, so cutting on a screen pixel also cuts on a texture pixel.

MAX_GLYPH_SIZE: int = 256[source]#

Largest bitmap glyph Minecraft can stitch into its font atlas, in texture pixels.

FontTexture allocates 256x256 sheets, and its atlas tree hands out a slot of exactly that size before it starts splitting, so a 256x256 glyph fits (taking a whole sheet) and a 257px one never does. A glyph no sheet accepts is replaced by the missing-character box.

LETTER_SPACING: int = 1[source]#

Pixels Minecraft adds to the advance of every bitmap glyph, on top of its measured width.

class SpliceTile(
row: int,
column: int,
box: tuple[int, int, int, int],
width: int,
ascent: int,
height: int,
)[source]#

Bases: object

One cell of a spliced render: a crop of the stored texture, and where it lands on screen.

row: int[source]#

Index of the tile row, 0 being the topmost.

column: int[source]#

Index of the tile column, 0 being the leftmost.

box: tuple[int, int, int, int][source]#

Crop box inside the stored texture: left, top, right, bottom.

width: int[source]#

On-screen width of the tile in pixels.

ascent: int[source]#

Baseline offset of the row this tile belongs to.

height: int[source]#

On-screen height of the row this tile belongs to.

class SpliceLayout(
tiles: tuple[SpliceTile, ...],
content: tuple[int, int],
stored: tuple[int, int],
width: int,
height: int,
ascent: int,
scale: int,
columns: int,
rows: int,
)[source]#

Bases: object

How an oversized image is cut into glyph-sized tiles, and how big they are on screen.

tiles: tuple[SpliceTile, ...][source]#

Every tile, in reading order: left to right, top row first.

content: tuple[int, int][source]#

Size the source image must be resized to.

stored: tuple[int, int][source]#

Size of the texture the tiles are cut out of, the content padded down to the baseline.

width: int[source]#

Total on-screen width of the reassembled image, in pixels.

height: int[source]#

Total on-screen height of the image, in pixels.

ascent: int[source]#

Pixels between the top of the image and the text baseline, clamped to what is representable.

scale: int[source]#

Texture pixels per on-screen pixel.

columns: int[source]#

Number of tiles per row.

rows: int[source]#

Number of tile rows.

split_evenly(total: int, parts: int) → tuple[int, ...][source]#

Cut total pixels into parts slices differing by at most one pixel.

Parameters:
  • total – Number of pixels to share out.

  • parts – Number of slices to cut.

Returns:

Width of each slice, summing back to total.

Return type:

tuple[int, …]

>>> split_evenly(100, 4)
(25, 25, 25, 25)
>>> split_evenly(10, 3)
(3, 4, 3)
>>> split_evenly(7, 1)
(7,)
glyph_advance(opaque: int, scale: int) → int[source]#

On-screen pixels Minecraft moves the pen by after drawing a bitmap glyph.

It measures the glyph up to its last non-transparent column, scales that down rounding halves up, then adds one pixel of spacing. Transparent columns on the right therefore shorten the advance, so spacing corrections come from the tile images, not their widths.

Parameters:
  • opaque – Width of the tile up to its last non-transparent column, in texture pixels.

  • scale – Texture pixels per on-screen pixel.

>>> glyph_advance(256, 16)  # a tile whose content reaches its right edge
17
>>> glyph_advance(24, 16)   # 1.5 rounds up, never to even
3
opaque_width(image: Image) → int[source]#

Index just past the rightmost column of image holding a non-transparent pixel.

Only the alpha channel is looked at, mirroring what Minecraft measures: a column of invisible pixels counts as empty whatever color it carries.

Parameters:

image – Tile image, in RGBA.

>>> from PIL import Image
>>> opaque_width(Image.new("RGBA", (16, 16), (255, 0, 0, 255)))
16
>>> opaque_width(Image.new("RGBA", (16, 16), (255, 0, 0, 0)))
0
plan_splice(
native: tuple[int, int],
height: int,
ascent: int,
resolution: int = 0,
limit: int = 256,
) → SpliceLayout[source]#

Work out the grid an image has to be cut into to be displayed at height pixels tall.

The stored texture is an integer multiple of the displayed size, so every cut lands on a whole texture pixel. That multiple follows resolution or the source image, shrinking until the part above the baseline fits one glyph.

Parameters:
  • height – On-screen height of the whole image, in pixels.

  • ascent – Pixels between the top of the image and the text baseline.

  • resolution – Wanted texture height, or 0 to follow the source image.

  • limit – Largest glyph Minecraft can display, in texture pixels.

>>> layout = plan_splice((1000, 370), height=37, ascent=21)
>>> layout.stored, layout.width, layout.scale   # a 10:1 image kept at its native pixels
((1000, 370), 100, 10)