"""Night-sky drawing kit for the sky and ISS views: Inter type, letter-spaced labels, colour mixing, moon phase.""" import math from functools import lru_cache from pathlib import Path from PIL import Image, ImageChops, ImageDraw, ImageFont W, H = 480, 320 FONT_PATH = Path(__file__).parent / "assets" / "fonts" / "Inter.ttf" WEEKDAYS = ["po", "út", "st", "čt", "pá", "so", "ne"] @lru_cache(maxsize=None) def font(size: int, weight: int = 500) -> ImageFont.FreeTypeFont: f = ImageFont.truetype(str(FONT_PATH), size) f.set_variation_by_axes([14 if size < 20 else 32, weight]) # optical size, weight return f def mix(a, b, t: float): t = max(0.0, min(1.0, t)) return tuple(round(x + (y - x) * t) for x, y in zip(a, b)) def hm(t) -> str: return "--:--" if t is None else f"{t.hour}:{t.minute:02d}" def tracked(d: ImageDraw.ImageDraw, xy, text: str, f, fill, track: float = 1.2, right: bool = False) -> float: """Letter-spaced text on baseline xy[1]; returns the end x.""" width = sum(d.textlength(ch, font=f) for ch in text) + track * (len(text) - 1) x = xy[0] - width if right else xy[0] for ch in text: d.text((x, xy[1]), ch, font=f, fill=fill, anchor="ls") x += d.textlength(ch, font=f) + track return x def tag(d: ImageDraw.ImageDraw, xy, text: str, f, fill, ink) -> None: """A pill-shaped label with its text baseline at xy[1].""" x, y = xy width = d.textlength(text, font=f) d.rounded_rectangle((x, y - 13, x + width + 12, y + 4), 8, fill=fill) d.text((x + 6, y), text, font=f, fill=ink, anchor="ls") def moon_disc(img: Image.Image, cx: float, cy: float, r: int, pct: float, waxing: bool, lit, dark) -> None: """The moon as seen from the northern hemisphere: lit on the right while waxing, on the left while waning.""" p = math.acos(max(-1.0, min(1.0, 1 - 2 * pct / 100))) / (2 * math.pi) # 0 new .. 0.5 full p = p if waxing else 1 - p s = 2 * r * 4 # drawn 4x larger, then scaled down for smooth edges disc = Image.new("L", (s, s), 0) ImageDraw.Draw(disc).ellipse((0, 0, s - 1, s - 1), fill=255) half = Image.new("L", (s, s), 0) ImageDraw.Draw(half).rectangle((s // 2, 0, s, s) if p < 0.5 else (0, 0, s // 2, s), fill=255) lit_mask = ImageChops.multiply(half, disc) ew = s * abs(math.cos(2 * math.pi * p)) / 2 # half-width of the terminator ellipse terminator = Image.new("L", (s, s), 0) ImageDraw.Draw(terminator).ellipse((s / 2 - ew, 0, s / 2 + ew, s - 1), fill=255) if pct < 50: lit_mask = ImageChops.subtract(lit_mask, terminator) else: lit_mask = ImageChops.lighter(lit_mask, ImageChops.multiply(terminator, disc)) x0, y0 = round(cx - r), round(cy - r) box = (x0, y0, x0 + 2 * r, y0 + 2 * r) img.paste(dark, box, disc.resize((2 * r, 2 * r), Image.LANCZOS)) if pct > 0: img.paste(lit, box, lit_mask.resize((2 * r, 2 * r), Image.LANCZOS).point(lambda v: 255 if v > 127 else 0))