diff --git a/README.md b/README.md index 50211e8..3f40479 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ | --- | --- | | `blueprints/` | креслення Create (`.nbt`) державних будівель | | `images/` | зображення проекту | +| `tools/` | скрипти, якими зроблено зображення | ## Креслення @@ -33,3 +34,40 @@ креслення, вид станції й блок. З них реєструються точки на сервері (`/createrp factory point at …`). Де яка будівля стоїть у місті — у вікі клієнта, сторінка «Державний квартал». + +## Таблички з назвами будівель + +`images/signs/*.png` — назви державних будівель для мода **Immersive Paintings**: піксельний шрифт +Minecraft, літери залито текстурою андезиту, темна обвідка, прозоре тло. 256×128 px, тобто +**2 блоки завширшки × 1 заввишки** при 128 px на блок. + +| Файл | Напис | +| --- | --- | +| `ratusha.png` | Ратуша | +| `ministerstvo.png` | Міністерство промисловості | +| `bank.png` | Державний банк | +| `centr_zainiatosti.png` | Центр зайнятості | +| `poshta.png` | Пошта | +| `kontora_importu.png` | Контора імпорту | +| `sklad_derzhavy.png` | Склад держави | +| `inspekcia.png` | Інспекція надр і землі | +| `efirna_palata.png` | Ефірна палата | +| `shahta.png` | Державна шахта | +| `zavod.png` | Державний завод | +| `pidstancia.png` | Підстанція | +| `bakalia.png` | Бакалія | +| `hospodarchyi_lariok.png` | Господарчий ларьок | +| `prylady_i_tekhnika.png` | Прилади й техніка | + +Як повісити: предмет **«Графіті»** (не «Картина» — у зображень є прозорість) → «Нова картина» → +вибрати файл → увімкнути «Pixelart» → ширина 2, висота 1, роздільність 128 → зберегти. Картина +завантажується на сервер і лишається у «Ваших картинах». Вікно «Нова картина» показує `.png` з теки +`screenshots/` клієнта — файл можна покласти туди або перетягнути у вікно. + +Як зроблено: `tools/signs/render.py` малює написи шрифтом і текстурою з клієнтського jar-а Minecraft +(самі файли Mojang у репозиторії не лежать). Один піксель шрифта — квадрат 3–5 px: що коротша +назва, то більші літери. Новий напис — рядок у словнику `SIGNS` і запуск: + +``` +python tools/signs/render.py <шлях до 1.21.1.jar> images/signs [--texture polished_andesite] +``` diff --git a/images/signs/bakalia.png b/images/signs/bakalia.png new file mode 100644 index 0000000..ea7332b Binary files /dev/null and b/images/signs/bakalia.png differ diff --git a/images/signs/bank.png b/images/signs/bank.png new file mode 100644 index 0000000..7f049df Binary files /dev/null and b/images/signs/bank.png differ diff --git a/images/signs/centr_zainiatosti.png b/images/signs/centr_zainiatosti.png new file mode 100644 index 0000000..8669642 Binary files /dev/null and b/images/signs/centr_zainiatosti.png differ diff --git a/images/signs/efirna_palata.png b/images/signs/efirna_palata.png new file mode 100644 index 0000000..b206aa1 Binary files /dev/null and b/images/signs/efirna_palata.png differ diff --git a/images/signs/hospodarchyi_lariok.png b/images/signs/hospodarchyi_lariok.png new file mode 100644 index 0000000..a92eadd Binary files /dev/null and b/images/signs/hospodarchyi_lariok.png differ diff --git a/images/signs/inspekcia.png b/images/signs/inspekcia.png new file mode 100644 index 0000000..3a26288 Binary files /dev/null and b/images/signs/inspekcia.png differ diff --git a/images/signs/kontora_importu.png b/images/signs/kontora_importu.png new file mode 100644 index 0000000..3a01a0f Binary files /dev/null and b/images/signs/kontora_importu.png differ diff --git a/images/signs/ministerstvo.png b/images/signs/ministerstvo.png new file mode 100644 index 0000000..1116711 Binary files /dev/null and b/images/signs/ministerstvo.png differ diff --git a/images/signs/pidstancia.png b/images/signs/pidstancia.png new file mode 100644 index 0000000..4d9bda9 Binary files /dev/null and b/images/signs/pidstancia.png differ diff --git a/images/signs/poshta.png b/images/signs/poshta.png new file mode 100644 index 0000000..8391d06 Binary files /dev/null and b/images/signs/poshta.png differ diff --git a/images/signs/prylady_i_tekhnika.png b/images/signs/prylady_i_tekhnika.png new file mode 100644 index 0000000..694097d Binary files /dev/null and b/images/signs/prylady_i_tekhnika.png differ diff --git a/images/signs/ratusha.png b/images/signs/ratusha.png new file mode 100644 index 0000000..7300604 Binary files /dev/null and b/images/signs/ratusha.png differ diff --git a/images/signs/shahta.png b/images/signs/shahta.png new file mode 100644 index 0000000..68ef522 Binary files /dev/null and b/images/signs/shahta.png differ diff --git a/images/signs/sklad_derzhavy.png b/images/signs/sklad_derzhavy.png new file mode 100644 index 0000000..744d6c8 Binary files /dev/null and b/images/signs/sklad_derzhavy.png differ diff --git a/images/signs/zavod.png b/images/signs/zavod.png new file mode 100644 index 0000000..4b7fe30 Binary files /dev/null and b/images/signs/zavod.png differ diff --git a/tools/signs/render.py b/tools/signs/render.py new file mode 100644 index 0000000..cb0b0ef --- /dev/null +++ b/tools/signs/render.py @@ -0,0 +1,144 @@ +"""Building name signs for Immersive Paintings: Minecraft's own pixel font, letters filled with a block +texture, dark outline, transparent background. 256x128 px = 2x1 blocks at 128 px per block. + + python render.py [preview.png] [--texture andesite] + +The font sheets and the block texture are read from the client jar and are not stored in this repo. +One font pixel becomes an s x s square (s chosen per sign so the text fills the plate) and takes the +colour of one texel of the block texture, so every letter is made of whole "stone pixels". +""" +import io +import json +import sys +import zipfile +from pathlib import Path + +import numpy as np +from PIL import Image + +W, H = 256, 128 +MARGIN = 6 # canvas px kept free on every side +MAX_SCALE = 5 +LINE_PITCH = 10 # font px from one baseline to the next (7 px capitals + 3 px gap) +OUTLINE = 0.30 # outline colour = block texture's mean colour * this + +SIGNS = { + 'ratusha': ['РАТУША'], + 'ministerstvo': ['МІНІСТЕРСТВО', 'ПРОМИСЛОВОСТІ'], + 'bank': ['ДЕРЖАВНИЙ', 'БАНК'], + 'centr_zainiatosti': ['ЦЕНТР', 'ЗАЙНЯТОСТІ'], + 'poshta': ['ПОШТА'], + 'kontora_importu': ['КОНТОРА', 'ІМПОРТУ'], + 'sklad_derzhavy': ['СКЛАД', 'ДЕРЖАВИ'], + 'inspekcia': ['ІНСПЕКЦІЯ', 'НАДР І ЗЕМЛІ'], + 'efirna_palata': ['ЕФІРНА', 'ПАЛАТА'], + 'shahta': ['ДЕРЖАВНА', 'ШАХТА'], + 'zavod': ['ДЕРЖАВНИЙ', 'ЗАВОД'], + 'pidstancia': ['ПІДСТАНЦІЯ'], + 'bakalia': ['БАКАЛІЯ'], + 'hospodarchyi_lariok': ['ГОСПОДАРЧИЙ', 'ЛАРЬОК'], + 'prylady_i_tekhnika': ['ПРИЛАДИ', 'Й ТЕХНІКА'], +} + + +LINE_H, BASELINE = 12, 10 # every glyph sits in a 12 px high row: 3 px for accents, 7 px capitals, 2 px below + + +class Font: + """Minecraft's default bitmap font. Plain glyphs are 8 px high (ascent 7), accented ones such as Й + come from a sheet with 12 px cells (ascent 10); both are placed on a common baseline.""" + + def __init__(self, jar: zipfile.ZipFile): + self.glyphs = {} + providers = json.loads(jar.read('assets/minecraft/font/include/default.json'))['providers'] + for p in providers: + if p.get('type') != 'bitmap': + continue + sheet = np.asarray(Image.open(io.BytesIO( + jar.read('assets/minecraft/textures/' + p['file'].split(':')[1]))).convert('RGBA'))[..., 3] > 0 + rows = [list(r) for r in p['chars']] + ch, cw = sheet.shape[0] // len(rows), sheet.shape[1] // len(rows[0]) + top = BASELINE - p['ascent'] + for y, row in enumerate(rows): + for x, c in enumerate(row): + if c in ('\u0000', ' ') or c in self.glyphs: + continue + cell = sheet[y * ch:(y + 1) * ch, x * cw:(x + 1) * cw] + cols = np.nonzero(cell.any(axis=0))[0] + if len(cols): + g = np.zeros((LINE_H, cols.max() + 1), bool) + g[top:top + ch] = cell[:LINE_H - top, :cols.max() + 1] + self.glyphs[c] = g + + def line(self, text: str) -> np.ndarray: + parts = [] + for c in text: + g = np.zeros((LINE_H, 3), bool) if c == ' ' else self.glyphs[c] + parts += [g, np.zeros((LINE_H, 1), bool)] + return np.hstack(parts[:-1]) + + +def render(font: Font, lines: list[str], tile: np.ndarray) -> Image.Image: + rows = [font.line(t) for t in lines] + width = max(r.shape[1] for r in rows) + # a line with accents above the capitals (Й, Ї) needs more room, or the accent touches the line above + tops = [0] + for r in rows[1:]: + tops.append(tops[-1] + (LINE_PITCH + 2 if r[:BASELINE - 7].any() else LINE_PITCH)) + mask = np.zeros((tops[-1] + LINE_H, width), bool) + for top, r in zip(tops, rows): + x = (width - r.shape[1]) // 2 + mask[top:top + LINE_H, x:x + r.shape[1]] |= r + ys = np.nonzero(mask.any(axis=1))[0] + mask = np.pad(mask[ys.min():ys.max() + 1], 1) # trim empty rows, leave room for the outline + + near = np.zeros_like(mask) + for dy in (-1, 0, 1): + for dx in (-1, 0, 1): + near |= np.roll(np.roll(mask, dy, 0), dx, 1) + outline = near & ~mask + + h, w = mask.shape + scale = max(1, min(MAX_SCALE, (W - 2 * MARGIN) // w, (H - 2 * MARGIN) // h)) + yy, xx = np.mgrid[0:h, 0:w] + dark = (tile.reshape(-1, 3).mean(axis=0) * OUTLINE).astype(np.uint8) + small = np.zeros((h, w, 4), np.uint8) + small[..., :3] = dark + small[mask, :3] = tile[yy % tile.shape[0], xx % tile.shape[1]][mask] + small[mask | outline, 3] = 255 + + big = np.repeat(np.repeat(small, scale, 0), scale, 1) + out = np.zeros((H, W, 4), np.uint8) + out[..., :3] = dark # no foreign colour under the transparency + oy, ox = (H - big.shape[0]) // 2, (W - big.shape[1]) // 2 + out[oy:oy + big.shape[0], ox:ox + big.shape[1]] = big + return Image.fromarray(out, 'RGBA'), scale + + +def main() -> None: + args = [a for a in sys.argv[1:] if not a.startswith('--')] + texture = sys.argv[sys.argv.index('--texture') + 1] if '--texture' in sys.argv else 'andesite' + out_dir = Path(args[1]) + out_dir.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(args[0]) as jar: + font = Font(jar) + tile = np.asarray(Image.open(io.BytesIO( + jar.read(f'assets/minecraft/textures/block/{texture}.png'))).convert('RGB')) + done = [] + for name, lines in SIGNS.items(): + im, scale = render(font, lines, tile) + im.save(out_dir / f'{name}.png', optimize=True) + done.append(im) + print(f'{name}: {" / ".join(lines)} — font pixel {scale} px') + if len(args) > 2: + cols, z = 3, 2 + rows = (len(done) + cols - 1) // cols + sheet = Image.new('RGB', (cols * (W * z + 8) + 8, rows * (H * z + 8) + 8), (110, 52, 40)) # brick red + for i, im in enumerate(done): + im = im.resize((W * z, H * z), Image.NEAREST) + sheet.paste(im, (8 + (i % cols) * (W * z + 8), 8 + (i // cols) * (H * z + 8)), im) + sheet.save(args[2]) + + +if __name__ == '__main__': + main()