Add Customize Launcher: colour schemes, a background picture of the player's own, animations and sound effects.

The launcher's home screen has a Customize Launcher row. Color Scheme steps through six schemes (Kokiri Forest, the colours so far, Death Mountain, Zora's Domain, Gerudo Valley, Temple of Time and Shadow Temple): each is the first scheme with its woods, accents, backdrop and glow turned to other hues, so all keep the same light and dark steps and the same text. Background takes a picture file, cuts it to the window's shape and keeps a fitted copy in data/background.npy; Background Dimming darkens it and the panels turn a little see-through over it. Animations (on by default) make the cursor glide between rows, a new screen slide in, sparks drift over the backdrop and Navi bob in the title band; they move by the time that passed and stand still while the window is hidden. Sounds are short chimes made from sine tones, off until the player picks a loudness.

Redrawing in another scheme takes about a third of a second: the blurred masks and the noise, which no colour changes, are kept, and compositing onto a solid picture is a plain mix.

The selftest's screen capture passed window handles as plain ints, which failed for a handle above 2^31 and left some screens without their picture; its calls are typed now.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
epicmeme546
2026-11-09 23:27:02 -05:00
parent 9ae7764ab5
commit 44d4095094
10 changed files with 1115 additions and 83 deletions

View File

@@ -8,7 +8,8 @@ The window is one Tk canvas at 1000 x 640 logical pixels, scaled to the display.
flat cells and the orange choices are canvas items. Screens:
first_run the dump, the install folder, three choices and Begin Installation
home Play, Updates, the game folder, Saves, Rebuild the Game, Settings
home Play, Updates, the game folder, Saves, Rebuild the Game, Customize Launcher, Settings
customize the colour scheme, the player's own background picture, animations and sounds
saves Export Save (a zip for a bug report or another player), Import a Save (such a zip), a save folder
job the steps of an install, update or rebuild, with their progress, and Cancel; after a failure Try Again
and Copy Report
@@ -16,9 +17,16 @@ flat cells and the orange choices are canvas items. Screens:
uninstall what to remove, then Uninstall or Cancel
Mouse, keyboard (arrows, Enter or Space, Esc, F5) and an XInput gamepad (d-pad or stick, A, B, Y) all move the cursor.
The look is the player's (Customize Launcher): art.set_theme fills the palette every picture is drawn from, a picture
of the player's own can replace the backdrop (picture.py), and unless Animations is off the cursor glides between
rows, a new screen slides in, sparks drift over the backdrop and Navi bobs in the title band (animate). sound.py
plays a short chime for a move, a change, a choice and the end of a job.
"""
import argparse
import math
import os
import random
import shutil
import sys
import time
@@ -29,7 +37,7 @@ from tkinter import filedialog
from .. import NAME, build, feed, gameini, gamefiles, jobs, saves, versions, winsys
from ..context import Context
from . import art
from . import art, picture, sound
W, H = 1000, 640
BAND = (0, 1000, 56) # x0, x1, height: the whole top of the window, which is also its title bar
@@ -39,7 +47,12 @@ ROWS = (140, 552, 96) # x0, x1, top
LABEL_W = 222 # 54 % of the row
GAP = 12
DESC = (614, 336) # x, width
P = art.PALETTE
P = art.PALETTE # the colour scheme in use: art.set_theme changes it in place
FRAME_MS = 15 # between two steps of the animations; they move by the time that really passed
SPARKS = 22 # the dust drifting over the backdrop
DEPTH = {'first_run': 0, 'home': 0, 'job': 1, 'saves': 1, 'settings': 1, 'customize': 1, 'uninstall': 2}
DIMS = (0, 20, 40, 60, 80) # Background Dimming, in percent
SOUND_LEVELS = (('off', 'Off'), ('low', 'Low'), ('medium', 'Medium'), ('high', 'High'))
class Row:
@@ -154,6 +167,7 @@ class App:
enabled=not self.layout.dev and not args.selftest)
self.row_gap = GAP
self.message = ''
self.look_message = '' # why the last background picture was not taken, in Customize Launcher's descriptions
self.save_message = '' # the last import's result, shown in the import rows' descriptions
self.export_message = '' # the last Export Save result, shown in its description
self.dumps = None
@@ -166,6 +180,23 @@ class App:
self.tb_hover = None
self.drag = None
self.ico = None
# the look: the colour scheme, the player's background picture at the window's size (None: the scheme's own
# backdrop), the sounds (none while the selftest draws the screens)
art.set_theme(self.settings.get('theme'))
self.bg_store = self.layout.data / 'background.npy'
self.picture = None
self.sounds = sound.Sounds(self.layout.cache, 'off' if args.selftest else self.settings.get('sounds'), ctx.log)
# the animations' state (animate): the clock and the last step's time, the cursor's place on its way to the
# focused row, how far the screen still stands from its place after a change, the sparks, Navi and its halo
self.anim_t = 0.0
self.anim_last = time.perf_counter()
self.cur_xy = self.cur_target = None
self.cur_screen = None
self.slide = 0.0
self.slide_applied = 0
self.sparks = []
self.navi_xy = None
self.halo = []
root.title(NAME)
root.resizable(False, False)
@@ -175,6 +206,7 @@ class App:
self.canvas.pack()
self.set_icon()
self.load_fonts()
self.load_picture()
self.draw_static()
self.bind_input()
self.start()
@@ -300,15 +332,35 @@ class App:
self.sprites[key] = art.photo(self.root, make())
return self.sprites[key]
def animated(self):
"""Animations on (Customize Launcher); never while the selftest draws the screens, whose pictures must not
depend on the moment they are taken."""
return bool(self.settings.get('animations')) and not self.args.selftest
def load_picture(self):
"""The player's background at the window's size, when one is set and its kept copy is readable."""
self.picture = None
if self.settings.get('background'):
self.picture = picture.kept(self.bg_store, self.X(W), self.X(H))
if self.picture is None:
self.ctx.log(f'background: {self.bg_store} is missing or unreadable; the colour scheme\'s backdrop')
def see_through(self):
"""How solid the panel and the description box are: a little see-through over the player's own picture."""
return 0.8 if self.picture is not None else 1.0
def draw_static(self):
c, s = self.canvas, self.s
c.delete('static')
c.create_image(0, 0, anchor='nw', image=self.sprite('backdrop', lambda: art.backdrop(self.X(W), self.X(H), s)),
tags='static')
dim = max(0, min(100, self.settings.get('background_dim', 40))) / 100.0
c.create_image(0, 0, anchor='nw', tags='static',
image=self.sprite('backdrop', lambda: art.backdrop(self.X(W), self.X(H), s, self.picture, dim)))
self.make_sparks() # over the backdrop, under the panel and the band
bx0, bx1, bh = BAND
px0, ptop, px1 = PANEL
c.create_image(self.X(px0), self.X(ptop), anchor='nw', tags='static',
image=self.sprite('panel', lambda: art.panel(self.X(px1) - self.X(px0), self.X(H - ptop), s)))
image=self.sprite('panel', lambda: art.panel(self.X(px1) - self.X(px0), self.X(H - ptop), s,
self.see_through())))
c.create_image(self.X(bx0), 0, anchor='nw', tags='static',
image=self.sprite('band', lambda: art.band(self.X(bx1) - self.X(bx0), self.X(bh), s)))
k = max(1, int(round(2 * s))) # Navi in whole pixels: two screen pixels per artwork pixel at 100 %
@@ -317,16 +369,50 @@ class App:
title_w = self.f['band'].measure(NAME)
gap = self.X(12)
x = self.X(W / 2) - (ew + gap + title_w) // 2
c.create_image(x, self.X(bh / 2), anchor='w', image=emblem, tags='static')
# Navi's halo, behind her: a soft light that pulses while the animations run
size = self.X(bh) - 2
if ('halo', size) not in self.sprites:
self.sprites[('halo', size)] = [art.photo(self.root, f) for f in art.halo_frames(size)]
self.halo = self.sprites[('halo', size)]
c.create_image(x + ew // 2, self.X(bh / 2), image=self.halo[0], tags=('static', 'halo'))
self.navi_xy = (x, self.X(bh / 2))
c.create_image(x, self.X(bh / 2), anchor='w', image=emblem, tags=('static', 'navi'))
tx = x + ew + gap
c.create_text(tx + 1, self.X(bh / 2) + self.X(2), text=NAME, anchor='w', font=self.f['band'], fill='#1a120a',
tags='static')
c.create_text(tx + 1, self.X(bh / 2) + self.X(2), text=NAME, anchor='w', font=self.f['band'],
fill=P['band_shadow'], tags='static')
c.create_text(tx, self.X(bh / 2), text=NAME, anchor='w', font=self.f['band'], fill=P['band_text'],
tags='static')
c.create_rectangle(0, 0, self.X(W) - 1, self.X(H) - 1, outline='#140e09', tags='static')
c.create_rectangle(0, 0, self.X(W) - 1, self.X(H) - 1, outline=P['frame'], tags='static')
c.tag_lower('static')
self.draw_title_buttons()
def make_sparks(self):
"""The dust over the backdrop: SPARKS soft dots of three sizes, each with its own speed, sway and twinkle, at
places of their own from the first frame on. None while Animations is off."""
self.sparks = []
if not self.animated():
return
rnd = random.Random(7)
for i in range(SPARKS):
size = self.X((5, 8, 12)[i % 3])
pics = [self.sprite(('spark', size, a), lambda sz=size, al=a: art.spark(sz, al)) for a in (0.9, 0.55, 0.25)]
# logical pixels: its speed upwards a second, how far it sways to each side and how fast
sp = {'x': rnd.uniform(0, W), 'y': rnd.uniform(BAND[2], H), 'vy': rnd.uniform(4, 14),
'sway': rnd.uniform(4, 16), 'rate': rnd.uniform(0.4, 1.1), 'phase': rnd.uniform(0, 6.28),
'pics': pics, 'shown': 0}
sp['id'] = self.canvas.create_image(self.X(sp['x']), self.X(sp['y']), image=pics[0], tags=('static', 'spark'))
self.sparks.append(sp)
def apply_look(self):
"""Draw everything again after the colour scheme, the background or Animations changed."""
art.set_theme(self.settings.get('theme'))
self.sprites.clear()
self.root.configure(background=P['window'])
self.canvas.configure(background=P['window'])
self.load_picture()
self.draw_static()
self.render()
def draw_title_buttons(self):
"""Minimise and close at the band's right end, lit when the mouse is over them."""
c, X = self.canvas, self.X
@@ -385,7 +471,10 @@ class App:
if not idx:
return
pos = idx.index(self.focus) if self.focus in idx else 0
was = self.focus
self.focus = idx[max(0, min(len(idx) - 1, pos + d))]
if self.focus != was:
self.sounds.play('move')
self.render()
def focused(self):
@@ -403,6 +492,7 @@ class App:
r.pick = max(0, min(len(r.actions) - 1, getattr(r, 'pick', 0) + d))
else:
return
self.sounds.play('move' if r.kind == 'pair' else 'toggle')
self.render()
def activate(self):
@@ -410,24 +500,36 @@ class App:
if not r or not r.enabled:
return
if r.kind == 'toggle':
self.sounds.play('toggle')
r.on(not r.get())
elif r.kind == 'enum':
self.sounds.play('toggle')
r.right()
elif r.kind == 'pair':
self.sounds.play('select')
r.actions[getattr(r, 'pick', 0)][1]()
return
elif r.on:
self.sounds.play('back' if r.kind == 'action' and r.label == 'Back' else 'select')
r.on()
return
self.render()
def home_row(self, label):
"""The index of the home screen's row with this label, for coming back to it."""
return next((i for i, r in enumerate(self.rows_home()) if r.label == label), None)
def back(self):
if self.screen in ('settings', 'uninstall', 'saves', 'customize', 'job'):
self.sounds.play('back')
if self.screen == 'settings':
self.show('home')
self.show('home', self.home_row('Settings'))
elif self.screen == 'uninstall':
self.show('settings')
elif self.screen == 'saves':
self.show('home', next((i for i, r in enumerate(self.rows_home()) if r.label == 'Saves'), None))
self.show('home', self.home_row('Saves'))
elif self.screen == 'customize':
self.show('home', self.home_row('Customize Launcher'))
elif self.screen == 'job' and self.job and self.job.result is None:
self.cancel_job()
elif self.screen == 'job':
@@ -459,6 +561,7 @@ class App:
r = self.rows[i]
if r.kind == 'pair':
r.pick = 0 if e.x < (r.rect[0] + r.rect[2]) / 2 else 1
self.sounds.play('move')
self.render()
elif i is not None and self.rows[i].kind == 'pair':
r = self.rows[i]
@@ -494,14 +597,17 @@ class App:
return
if r.kind == 'toggle' and r.value_rect:
x0, _, x1, _ = r.value_rect
self.sounds.play('toggle')
r.on(e.x < (x0 + x1) / 2)
self.render()
elif r.kind == 'enum' and r.value_rect:
x0, _, x1, _ = r.value_rect
self.sounds.play('toggle')
(r.left if e.x < x0 + (x1 - x0) / 3 else r.right)()
self.render()
elif r.kind == 'pair':
r.pick = 0 if e.x < (r.rect[0] + r.rect[2]) / 2 else 1
self.sounds.play('select')
r.actions[r.pick][1]()
else:
self.activate()
@@ -511,6 +617,7 @@ class App:
self.job.cancel()
if self.bg.staging(): # what it downloaded is resumed, and its unfinished folder replaced, next time
self.bg.job.cancel()
self.sounds.stop()
self.root.destroy()
# ---------------------------------------------------------------- screens
@@ -550,6 +657,10 @@ class App:
f'{versions.display(self.layout.version)}.')
def show(self, screen, focus=None):
if screen != self.screen and self.screen is not None and self.animated():
# another screen slides into place: from the right when it lies deeper, from the left on the way back
deeper = DEPTH.get(screen, 1) >= DEPTH.get(self.screen, 0)
self.slide = float(self.X(44) if deeper else -self.X(44))
self.screen = screen
self.rows = getattr(self, 'rows_' + screen)()
idx = self.focusables()
@@ -764,10 +875,113 @@ class App:
Row('value', 'Rebuild the Game', rebuild_value, rebuild_style, on=self.start_rebuild,
desc=('Build the game again from the files of the last build. Only what changed is compiled. Use it '
'after changing build tools, or if the game stopped starting.',)),
Row('value', 'Customize Launcher', art.THEMES[art.theme]['label'], 'arrow',
on=lambda: self.show('customize'),
desc=('Colour scheme, background picture, animations and sounds.',)),
Row('value', 'Settings', '', 'arrow', on=lambda: self.show('settings'),
desc=('Updates, the game folder, the logs and uninstalling.',)),
]
# ---- customize
def rows_customize(self):
names = list(art.THEMES)
custom = bool(self.settings.get('background'))
def scheme(d):
self.settings['theme'] = names[(names.index(art.theme) + d) % len(names)]
self.settings.save()
self.apply_look()
def dim(d):
now = self.settings.get('background_dim', 40)
at = min(range(len(DIMS)), key=lambda i: abs(DIMS[i] - now))
self.settings['background_dim'] = DIMS[max(0, min(len(DIMS) - 1, at + d))]
self.settings.save()
self.apply_look()
def animations(v):
self.settings['animations'] = bool(v)
self.settings.save()
self.cur_xy = None
self.slide = 0.0
self.apply_look()
def sounds(d):
keys = [k for k, _ in SOUND_LEVELS]
now = self.settings.get('sounds')
at = keys.index(now) if now in keys else 0
self.settings['sounds'] = keys[max(0, min(len(keys) - 1, at + d))]
self.settings.save()
self.sounds.set_level(self.settings['sounds'])
self.sounds.play('toggle') # the new loudness, heard at once
bg_desc = ('Use a picture of your own as the background.',)
if self.look_message:
bg_desc = (self.look_message,) + bg_desc
rows = [
Row('enum', 'Color Scheme', get=lambda: art.THEMES[art.theme]['label'],
left=lambda: scheme(-1), right=lambda: scheme(1),
desc=('The launcher\'s colours.',)),
Row('value', 'Background', Path(self.settings['background']).name if custom else 'Choose a Picture',
'arrow', on=self.choose_background, desc=bg_desc),
]
if custom:
rows += [
Row('enum', 'Background Dimming', get=lambda: f'{self.settings.get("background_dim", 40)} %',
left=lambda: dim(-1), right=lambda: dim(1),
desc=('Darkens your picture so the text stays easy to read.',)),
Row('value', 'Remove Background', '', 'arrow', on=self.clear_background,
desc=('Go back to the colour scheme\'s own background.',)),
]
rows += [
Row('divider'),
Row('toggle', 'Animations', on=animations, get=lambda: bool(self.settings.get('animations')),
desc=('A gliding cursor, sliding screens and drifting sparks.',)),
Row('enum', 'Sounds', get=lambda: dict(SOUND_LEVELS).get(self.settings.get('sounds'), 'Off'),
left=lambda: sounds(-1), right=lambda: sounds(1),
desc=('Short chimes when you move and choose. Off by default.',)),
Row('divider'),
Row('action', 'Back', on=lambda: self.show('home', self.home_row('Customize Launcher')), height=40,
desc=('Back to the main menu.',)),
]
return rows
def choose_background(self):
start = self.settings.get('background')
start = str(Path(start).parent) if start and Path(start).parent.is_dir() else \
str(winsys.known_folder('pictures') or Path.home())
pattern = ' '.join('*' + t for t in picture.TYPES)
path = filedialog.askopenfilename(parent=self.root, title='Choose a background picture', initialdir=start,
filetypes=[('Pictures', pattern), ('All files', '*.*')])
if not path:
return
try:
picture.keep(path, self.bg_store, self.root)
except (picture.PictureError, OSError, MemoryError, ValueError) as e:
self.ctx.log(f'background: {path}: {e!r}')
self.look_message = str(e) if isinstance(e, picture.PictureError) else \
f'{Path(path).name} could not be used as the background: {e}'
self.sounds.play('error')
self.show('customize', self.focus)
return
self.look_message = ''
self.settings['background'] = str(Path(path))
self.settings.save()
self.apply_look()
self.show('customize', self.focus)
def clear_background(self):
self.settings['background'] = ''
self.settings.save()
try:
self.bg_store.unlink(missing_ok=True)
except OSError as e:
self.ctx.log(f'background: {e}')
self.look_message = ''
self.apply_look()
self.show('customize', 1)
def save_waiting(self, gd):
"""A save put into the game folder's saves folder (a shared zip, a save folder), waiting to be imported."""
if gd and Path(gd).is_dir():
@@ -999,6 +1213,7 @@ class App:
self.render()
return
self.ctx.log(f'play: {exe}')
self.sounds.play('start')
if self.settings.get('hide_while_playing'):
self.root.withdraw()
self.root.after(1000, self.watch_game)
@@ -1275,6 +1490,8 @@ class App:
j = self.job
winsys.keep_awake(False)
self.ctx.log(f'job {j.kind}: {j.result} {j.error}')
if j.result in ('ok', 'failed'):
self.sounds.play('done' if j.result == 'ok' else 'error')
if j.result == 'ok':
if j.after == 'restart':
if winsys.restart(self.layout, ['--continue-update', versions.display(self.layout.version)]):
@@ -1358,10 +1575,66 @@ class App:
self.root.after(60000, self.minute)
def animate(self):
if self.cursor_frames:
self.cursor_k = (self.cursor_k + 1) % len(self.cursor_frames)
self.canvas.itemconfigure('cursor', image=self.cursor_frames[self.cursor_k])
self.root.after(250, self.animate)
"""One step of everything that moves: the cursor on its way to the focused row and its breath, the screen
sliding into place, the sparks and Navi. Each moves by the time since the last step (the timer comes when
Tk gets to it, 16 to 50 ms apart), at most a tenth of a second's worth. With Animations off, and while the
window is hidden or minimised (the game is running), nothing moves and the timer runs slowly."""
moving = False
try:
now = time.perf_counter()
dt = min(0.1, max(0.0, now - self.anim_last))
self.anim_last = now
moving = self.animated() and self.root.state() == 'normal'
if moving:
self.anim_t += dt
self.step_slide(dt)
self.step_cursor(dt)
self.step_backdrop(dt)
except Exception as e: # a drawing error must not stop the timer
self.ctx.log(f'animate: {e!r}')
self.root.after(FRAME_MS if moving else 300, self.animate)
def step_slide(self, dt):
if not self.slide:
return
left = self.slide * math.exp(-dt * 16) # most of the way in a fifth of a second
if abs(left) < 1:
left = 0.0
self.canvas.move('dyn', int(left) - self.slide_applied, 0)
self.slide, self.slide_applied = left, int(left)
def step_cursor(self, dt):
c = self.canvas
if self.cursor_frames: # one breath in 1.6 s
k = int(self.anim_t / 1.6 * len(self.cursor_frames)) % len(self.cursor_frames)
if k != self.cursor_k:
self.cursor_k = k
c.itemconfigure('cursor', image=self.cursor_frames[k])
if self.cur_xy and self.cur_target and self.cur_xy != self.cur_target:
(x, y), (tx, ty) = self.cur_xy, self.cur_target
f = 1 - math.exp(-dt * 22) # there in about a tenth of a second
x, y = x + (tx - x) * f, y + (ty - y) * f
if abs(tx - x) < 0.6 and abs(ty - y) < 0.6:
x, y = tx, ty
self.cur_xy = (x, y)
c.coords('cursor', round(x) + self.slide_applied, round(y))
def step_backdrop(self, dt):
c, t = self.canvas, self.anim_t
for sp in self.sparks: # up, swaying, and back in at the bottom once under the title band
sp['y'] -= sp['vy'] * dt
if sp['y'] < BAND[2] - 8:
sp['y'] = H + 8
c.coords(sp['id'], self.X(sp['x'] + math.sin(t * sp['rate'] + sp['phase']) * sp['sway']), self.X(sp['y']))
k = int((math.sin(t * sp['rate'] * 2.3 + sp['phase'] * 3) + 1) * 1.49) # 0, 1 or 2: its twinkle
if k != sp['shown']:
sp['shown'] = k
c.itemconfigure(sp['id'], image=sp['pics'][k])
if self.navi_xy: # Navi rises and sinks two pixels every 2.4 s, her halo pulses with her
x, y = self.navi_xy
c.coords('navi', x, y + round(math.sin(t * 2.6) * self.X(2)))
if self.halo:
c.itemconfigure('halo', image=self.halo[int(t / 2.4 * len(self.halo)) % len(self.halo)])
# ---------------------------------------------------------------- drawing
@@ -1381,6 +1654,9 @@ class App:
self.draw_status()
self.draw_cursor()
self.draw_desc()
self.slide_applied = int(self.slide)
if self.slide_applied: # drawn in place, then put where the slide has got to (step_slide)
c.move('dyn', self.slide_applied, 0)
def fit_rows(self, top, bottom):
"""The height of each row and the gap between rows (logical pixels) that end the rows above bottom. A screen
@@ -1421,7 +1697,7 @@ class App:
def text(self, x, y, text, font, fill, anchor='w', shadow=True, width=0):
c = self.canvas
if shadow:
c.create_text(x + 1, y + 1, text=text, font=font, fill='#2a1e10', anchor=anchor, tags='dyn',
c.create_text(x + 1, y + 1, text=text, font=font, fill=P['text_shadow'], anchor=anchor, tags='dyn',
width=width)
return c.create_text(x, y, text=text, font=font, fill=fill, anchor=anchor, tags='dyn', width=width)
@@ -1440,7 +1716,9 @@ class App:
for k, (label, cb) in enumerate(parts):
px0 = x0 + k * (w + gap)
px1 = px0 + w if k < len(parts) - 1 else x1
img = self.sprite(('label', px1 - px0, y1 - y0), lambda a=px1 - px0, b=y1 - y0: art.label_cell(a, b, s))
lit = r is self.focused() and (r.kind == 'action' or getattr(r, 'pick', 0) == k)
img = self.sprite(('label', px1 - px0, y1 - y0, lit),
lambda a=px1 - px0, b=y1 - y0: art.label_cell(a, b, s, lit))
ring = max(1, int(round(s)))
c.create_image(px0 - ring, y0 - ring, anchor='nw', image=img, tags='dyn')
font = self.fit_font(self.f['action_big'] if r.h >= 50 else self.f['action'], label,
@@ -1451,7 +1729,8 @@ class App:
return
lw = X(LABEL_W)
lx1 = x0 + lw
img = self.sprite(('label', lw, y1 - y0), lambda: art.label_cell(lw, y1 - y0, s))
lit = r is self.focused()
img = self.sprite(('label', lw, y1 - y0, lit), lambda: art.label_cell(lw, y1 - y0, s, lit))
ring = max(1, int(round(s)))
c.create_image(x0 - ring, y0 - ring, anchor='nw', image=img, tags='dyn')
tx = x0 + X(16)
@@ -1468,8 +1747,8 @@ class App:
size = X(22)
b = self.sprite(('badge', size), lambda: art.badge(size, s))
c.create_image(bx, (y0 + y1) // 2, anchor='w', image=b, tags='dyn')
c.create_text(bx + (size + 4) // 2, (y0 + y1) // 2, text='!', font=self.f['badge'], fill='#3a2208',
tags='dyn')
c.create_text(bx + (size + 4) // 2, (y0 + y1) // 2, text='!', font=self.f['badge'],
fill=P['badge_text'], tags='dyn')
vx0 = lx1
r.value_rect = (vx0, y0, x1, y1)
c.create_rectangle(vx0, y0, x1 - 1, y1 - 1, fill=P['value'], outline=P['value_border'], width=1, tags='dyn')
@@ -1500,7 +1779,7 @@ class App:
fw = int((ix1 - ix0) * max(0.0, min(1.0, r.fraction)))
if fw > 2:
self.orange(ix0, iy0, ix0 + fw, iy1)
self.canvas.create_text(cx + 1, cy + 1, text=r.value, font=vfont, fill='#1a120a', tags='dyn')
self.canvas.create_text(cx + 1, cy + 1, text=r.value, font=vfont, fill=P['band_shadow'], tags='dyn')
self.canvas.create_text(cx, cy, text=r.value, font=vfont, fill=P['on_text'], tags='dyn')
elif r.style == 'orange_arrow':
self.orange(ix0, iy0, ix1, iy1)
@@ -1514,7 +1793,7 @@ class App:
c.create_image(sx + label_w + X(10), cy, anchor='w', image=img, tags='dyn')
elif r.style == 'arrow':
cw, ch = X(9), X(12)
img = self.sprite(('chev', cw, ch, False, 'dim'), lambda: art.chevron(cw, ch, '#d9ccae'))
img = self.sprite(('chev', cw, ch, False, 'dim'), lambda: art.chevron(cw, ch, P['chevron_dim']))
c.create_image(x1 - X(16), cy, anchor='e', image=img, tags='dyn')
if r.value: # a value, centred in the cell's room left of the arrow
right = x1 - X(16) - cw - X(10)
@@ -1546,6 +1825,7 @@ class App:
r = self.focused()
self.cursor_frames = []
if not r or not r.rect:
self.cur_xy = self.cur_target = None
return
if r.kind == 'pair' and r.parts:
box = r.parts[getattr(r, 'pick', 0)][0]
@@ -1557,7 +1837,14 @@ class App:
frames, mg = self.glow(x1 - x0, y1 - y0)
self.cursor_frames = frames
self.cursor_k %= len(frames)
self.canvas.create_image(x0 - mg, y0 - mg, anchor='nw', image=frames[self.cursor_k], tags=('dyn', 'cursor'))
# The cursor is drawn where it has got to and animate takes it on to the row (step_cursor); on a new screen,
# while one slides in and with Animations off it stands on the row at once.
target = (float(x0 - mg), float(y0 - mg))
glide = self.animated() and self.cur_xy and self.cur_screen == self.screen and not self.slide
self.cur_xy = self.cur_xy if glide else target
self.cur_target, self.cur_screen = target, self.screen
self.canvas.create_image(round(self.cur_xy[0]), round(self.cur_xy[1]), anchor='nw',
image=frames[self.cursor_k], tags=('dyn', 'cursor'))
def glow(self, w, h):
key = ('glow', w, h)
@@ -1642,7 +1929,7 @@ class App:
y += X(22)
elif kind == 'bullet':
(text,) = args
c.create_rectangle(x0 + padx + X(1), y + X(8), x0 + padx + X(6), y + X(13), fill='#c99a45',
c.create_rectangle(x0 + padx + X(1), y + X(8), x0 + padx + X(6), y + X(13), fill=P['bullet'],
outline='', tags=('dyn', 'desc'))
tid = c.create_text(x0 + padx + X(16), y, text=text, font=self.f['value'], fill=P['desc_text'],
anchor='nw', width=inner - X(16), tags=('dyn', 'desc'))
@@ -1670,7 +1957,7 @@ class App:
hb = max(X(60), height)
key = ('desc', w, hb // 4)
if key not in self.sprites:
img, pad = art.desc_box(w, hb, self.s)
img, pad = art.desc_box(w, hb, self.s, self.see_through())
self.sprites[key] = (art.photo(self.root, img), pad)
pic, pad = self.sprites[key]
bid = c.create_image(x0 - pad, top - pad, anchor='nw', image=pic, tags='dyn')

View File

@@ -6,9 +6,11 @@ the small icons. Tk's canvas draws lines and polygons without antialiasing on Wi
shape is a picture; flat rectangles and text stay canvas items.
Colours follow the game's options menu (docs/launcher.md, "Look"). Sizes are in logical pixels times the display
scale s.
scale s. PALETTE holds the colours of the colour scheme in use: set_theme fills it from THEMES, each scheme the
first one with its woods, accents, backdrop and glow turned to other hues.
"""
import base64
import colorsys
import re
import struct
import zlib
@@ -17,7 +19,8 @@ import numpy as np
# ---------------------------------------------------------------- colours
PALETTE = {
# The first colour scheme, Kokiri Forest: bronze wood on a misty dark green.
BASE = {
'window': '#06180d',
'panel': '#3a2b22',
'label_top': '#7a5c32', 'label_mid': '#775930', 'label_bottom': '#72552d', 'label_border': '#6a4f29',
@@ -30,8 +33,88 @@ PALETTE = {
'ok': '#a7d68c', 'gold': '#e6b65a', 'band_text': '#f3ecdc', 'status': '#b9a988', 'log_text': '#cfc4ab',
'line': '#54442f', 'dot': '#5d4b36', 'filigree': '#7a6443', 'glow': '#e9ebee',
'button_hover': '#8a6c3f', 'close_hover': '#b0402c',
# the backdrop: the field's four heights, its mist, the see-through tint over it (edge, side, middle), the corners
'scene_0': '#394244', 'scene_1': '#414b4c', 'scene_2': '#474234', 'scene_3': '#3e3523', 'mist': '#262a22',
'tint_edge': '#05180d', 'tint_side': '#092615', 'tint_mid': '#0c2e1b', 'vignette': '#020e07',
# the title band's wood from top to bottom and the two lines under it
'wood_0': '#4c3b26', 'wood_1': '#5a4529', 'wood_2': '#6b5232', 'wood_3': '#806239',
'band_line_dark': '#2c2217', 'band_line_light': '#a9874f',
# the cursor's glow near and far from its frame, the sparks drifting over the backdrop, Navi's halo
'glow_near': '#afc5e8', 'glow_far': '#96b4e6', 'spark': '#cfe6ff', 'halo': '#7fc4ff',
'icon_frame': '#e9dcc0', 'icon_fill': '#efe4ca', 'chevron_dim': '#d9ccae', 'bullet': '#c99a45',
'badge_top': '#fbbd45', 'badge_bottom': '#e2942a', 'badge_ring': '#3a2a14', 'badge_text': '#3a2208',
'text_shadow': '#2a1e10', 'band_shadow': '#1a120a', 'frame': '#140e09',
}
# The colours a scheme turns together, each group to one hue.
GROUPS = {
'wood': ('panel', 'label_top', 'label_mid', 'label_bottom', 'label_border', 'ring', 'desc', 'desc_border', 'line',
'dot', 'filigree', 'button_hover', 'wood_0', 'wood_1', 'wood_2', 'wood_3', 'band_line_dark',
'band_line_light', 'value', 'value_border', 'text_shadow', 'band_shadow', 'frame'),
'accent': ('orange', 'orange_light', 'orange_dark', 'gold', 'badge_top', 'badge_bottom', 'badge_ring',
'badge_text', 'bullet'),
'scene': ('window', 'scene_0', 'scene_1', 'scene_2', 'scene_3', 'mist', 'tint_edge', 'tint_side', 'tint_mid',
'vignette'),
'glow': ('glow', 'glow_near', 'glow_far', 'spark', 'halo'),
'text': ('text', 'text_bright', 'value_text', 'desc_text', 'muted', 'band_text', 'status', 'log_text', 'on_text',
'icon_frame', 'icon_fill', 'chevron_dim'),
}
# The colour schemes of Customize Launcher, in the order the row steps through them. Each group: (hue in degrees or
# None to keep each colour's own, saturation factor, lightness factor, saturation added), applied to the first
# scheme's colours (recolor), so a scheme keeps the first one's light and dark steps. 'set': colours given as they are.
THEMES = {
'kokiri': {'label': 'Kokiri Forest'},
'death_mountain': {'label': 'Death Mountain', 'wood': (14, 0.95, 0.80, 0), 'accent': (16, 1.05, 1.0, 0),
'scene': (6, 1.0, 1.0, 0.25), 'glow': (30, 1.0, 1.0, 0), 'text': (30, 1.0, 1.0, 0)},
'zora': {'label': "Zora's Domain", 'wood': (207, 0.75, 0.92, 0), 'accent': (188, 0.95, 1.0, 0),
'scene': (200, 1.0, 1.05, 0.2), 'glow': (185, 1.0, 1.0, 0), 'text': (200, 0.55, 1.02, 0)},
'gerudo': {'label': 'Gerudo Valley', 'wood': (26, 1.15, 1.0, 0), 'accent': (352, 0.9, 1.0, 0),
'scene': (318, 0.8, 0.95, 0.15), 'glow': (45, 1.0, 1.0, 0), 'text': (36, 1.0, 1.0, 0)},
'temple': {'label': 'Temple of Time', 'wood': (220, 0.22, 0.95, 0), 'accent': (46, 0.95, 1.02, 0),
'scene': (222, 0.55, 1.0, 0.05), 'glow': (48, 1.0, 1.0, 0.5), 'text': (48, 0.45, 1.02, 0)},
'shadow': {'label': 'Shadow Temple', 'wood': (268, 0.55, 0.78, 0), 'accent': (286, 0.75, 1.0, 0),
'scene': (272, 0.9, 0.8, 0.2), 'glow': (280, 1.0, 1.0, 0.2), 'text': (270, 0.5, 1.0, 0)},
}
DEFAULT_THEME = 'kokiri'
def recolor(hexcolor, hue, sat=1.0, light=1.0, add=0.0):
"""hexcolor turned to hue (degrees; None keeps its own), its saturation times sat plus add, its lightness times
light."""
h = hexcolor.lstrip('#')
r, g, b = (int(h[i:i + 2], 16) / 255.0 for i in (0, 2, 4))
hh, ll, ss = colorsys.rgb_to_hls(r, g, b)
if hue is not None:
hh = (hue % 360) / 360.0
r, g, b = colorsys.hls_to_rgb(hh, max(0.0, min(1.0, ll * light)), max(0.0, min(1.0, ss * sat + add)))
return '#%02x%02x%02x' % tuple(int(round(v * 255)) for v in (r, g, b))
def theme_palette(name):
"""The colours of scheme name (an unknown name: the first scheme's)."""
t = THEMES.get(name) or THEMES[DEFAULT_THEME]
pal = dict(BASE)
for group, keys in GROUPS.items():
if group in t:
for k in keys:
pal[k] = recolor(BASE[k], *t[group])
pal.update(t.get('set', {}))
return pal
PALETTE = dict(BASE)
theme = DEFAULT_THEME
def set_theme(name):
"""Fills PALETTE (in place: the window holds a reference) with scheme name's colours; the name in effect."""
global theme
theme = name if name in THEMES else DEFAULT_THEME
PALETTE.clear()
PALETTE.update(theme_palette(theme))
return theme
def rgb(hexcolor):
h = hexcolor.lstrip('#')
@@ -89,6 +172,20 @@ def ico_bytes(images):
# ---------------------------------------------------------------- drawing primitives
# The blurred masks and the noise depend on sizes only, not on colours: kept here, a change of the colour scheme
# paints them again in its colours without computing them again (most of the time a redraw took). The arrays kept
# are read, never written.
_KEPT = {}
def kept(key, make):
if key not in _KEPT:
if len(_KEPT) >= 160: # row and box sizes of every screen stay far below this
_KEPT.clear()
_KEPT[key] = make()
return _KEPT[key]
def new(h, w, color=None, alpha=0.0):
img = np.zeros((h, w, 4), dtype=np.float32)
if color is not None:
@@ -107,17 +204,37 @@ def over(dst, src, x=0, y=0):
s = src[y0 - y:y1 - y, x0 - x:x1 - x]
d = dst[y0:y1, x0:x1]
sa, da = s[..., 3:4], d[..., 3:4]
oa = sa + da * (1 - sa)
oc = np.where(oa > 0, (s[..., :3] * sa + d[..., :3] * da * (1 - sa)) / np.maximum(oa, 1e-6), 0)
if da.min() >= 1: # onto a solid picture (the backdrop's layers): a plain mix, the result stays solid
d[..., :3] += (s[..., :3] - d[..., :3]) * sa
return dst
under = da * (1 - sa)
oa = sa + under
oc = s[..., :3] * sa
oc += d[..., :3] * under
oc /= np.maximum(oa, 1e-6) # where both are clear the sum above is 0, and stays 0
d[..., :3], d[..., 3:4] = oc, oa
return dst
def paint(img, mask, color, alpha=1.0):
"""Paint a colour through a coverage mask (HxW, 0..1) onto img."""
layer = new(*mask.shape, color)
layer[..., 3] = np.clip(mask, 0, 1) * alpha
return over(img, layer)
if mask.shape != img.shape[:2]:
layer = new(*mask.shape, color)
layer[..., 3] = np.clip(mask, 0, 1) * alpha
return over(img, layer)
# over() with one colour for the whole layer, without making the layer
sa = (np.clip(mask, 0, 1) * alpha)[..., None].astype(np.float32)
c, da = rgb(color), img[..., 3:4]
if da.min() >= 1:
img[..., :3] += (c - img[..., :3]) * sa
return img
under = da * (1 - sa)
oa = sa + under
oc = img[..., :3] * under
oc += c * sa
oc /= np.maximum(oa, 1e-6)
img[..., :3], img[..., 3:4] = oc, oa
return img
def vgradient(h, w, stops):
@@ -174,6 +291,11 @@ def fractal(h, w, period_x, period_y=None, octaves=3, seed=0, contrast=0.4):
def _fractal01(h, w, period_x, period_y=None, octaves=3, seed=0):
return kept(('fractal', h, w, period_x, period_y, octaves, seed),
lambda: _fractal01_make(h, w, period_x, period_y, octaves, seed))
def _fractal01_make(h, w, period_x, period_y, octaves, seed):
period_y = period_y or period_x
out = np.zeros((h, w), dtype=np.float32)
amp, total = 1.0, 0.0
@@ -340,56 +462,97 @@ FILIGREE_PATHS = (
# ---------------------------------------------------------------- the window's pieces
def backdrop(W, H, s):
"""The whole window behind the panels: a dim misty field under a see-through dark green, darker at the sides."""
img = new(H, W, PALETTE['window'], 1.0)
def backdrop(W, H, s, picture=None, dim=0.4):
"""The whole window behind the panels: a dim misty field under a see-through tint of the colour scheme, darker at
the sides. picture: the player's own background instead of the field, an H x W x 3 array in 0..1 (the window's
size), darkened by dim (0 as it is .. 1 the scheme's darkest colour) so the text over it stays readable."""
P = PALETTE
img = new(H, W, P['window'], 1.0)
pad = int(45 * s)
vig = kept(('vignette', W, H, s), lambda: 1 - box_blur(np.pad(rect_mask(H, W, 0, 0, W, H), pad,
constant_values=0), 45 * s)[pad:-pad, pad:-pad])
if picture is not None:
img[..., :3] = picture[:H, :W]
paint(img, np.ones((H, W), dtype=np.float32), P['tint_edge'], max(0.0, min(1.0, dim)))
paint(img, np.clip(vig * 1.6, 0, 1), P['vignette'], 0.45)
return img
m = int(30 * s)
scene = new(H, W - 2 * m)
scene[..., :3] = vgradient(H, W - 2 * m, [(0, '#394244'), (0.36, '#414b4c'), (0.60, '#474234'), (1, '#3e3523')])
scene[..., :3] = vgradient(H, W - 2 * m, [(0, P['scene_0']), (0.36, P['scene_1']), (0.60, P['scene_2']),
(1, P['scene_3'])])
scene[..., 3] = 1
over(img, scene, m, 0)
band = np.zeros((H, W), dtype=np.float32)
y0, y1 = int(250 * s), int(330 * s)
t = (np.arange(y1 - y0) + 0.5) / max(y1 - y0, 1)
band[y0:y1, m:W - m] = (np.interp(t, [0, 0.55, 1], [0, 0.85, 0]))[:, None]
paint(img, box_blur(band, 10 * s), '#262a22')
over(img, hgradient_rgba(H, W, [(0, '#05180d', 0.96), (0.14, '#092615', 0.82), (0.5, '#0c2e1b', 0.72),
(0.86, '#092615', 0.82), (1, '#05180d', 0.96)]))
inner = rect_mask(H, W, 0, 0, W, H)
vig = 1 - box_blur(np.pad(inner, int(45 * s), constant_values=0), 45 * s)[int(45 * s):-int(45 * s),
int(45 * s):-int(45 * s)]
paint(img, np.clip(vig * 1.6, 0, 1), '#020e07', 0.6)
def mist():
band = np.zeros((H, W), dtype=np.float32)
y0, y1 = int(250 * s), int(330 * s)
t = (np.arange(y1 - y0) + 0.5) / max(y1 - y0, 1)
band[y0:y1, m:W - m] = (np.interp(t, [0, 0.55, 1], [0, 0.85, 0]))[:, None]
return box_blur(band, 10 * s)
paint(img, kept(('mist', W, H, s), mist), P['mist'])
over(img, hgradient_rgba(H, W, [(0, P['tint_edge'], 0.96), (0.14, P['tint_side'], 0.82), (0.5, P['tint_mid'], 0.72),
(0.86, P['tint_side'], 0.82), (1, P['tint_edge'], 0.96)]))
paint(img, np.clip(vig * 1.6, 0, 1), P['vignette'], 0.6)
return img
def spark(size, alpha=1.0):
"""One spark of the dust drifting over the backdrop: a soft round dot of the scheme's spark colour, size pixels
across, brightest in its middle."""
ys = (np.arange(size, dtype=np.float32) + 0.5) / size * 2 - 1
d = np.hypot(ys[:, None], ys[None, :])
img = new(size, size, PALETTE['spark'])
img[..., 3] = np.clip(1 - d, 0, 1) ** 1.6 * alpha
core = np.clip(1 - d * 2.6, 0, 1)
img[..., :3] += (1 - img[..., :3]) * core[..., None] # a white middle
return img
def halo_frames(size, n=12):
"""The light around Navi in the title band: a soft disc of the scheme's halo colour, n frames of one slow pulse."""
ys = (np.arange(size, dtype=np.float32) + 0.5) / size * 2 - 1
d = np.hypot(ys[:, None], ys[None, :])
fall = np.clip(1 - d, 0, 1) ** 2
frames = []
for k in range(n):
t = 0.5 - 0.5 * np.cos(2 * np.pi * k / n)
img = new(size, size, PALETTE['halo'])
img[..., 3] = fall * (0.30 + 0.30 * t)
frames.append(img)
return frames
def band(w, h, s):
"""The wooden title band, its two-line bottom edge and the shadow under it; (image, extra height below)."""
pad = int(14 * s)
img = new(h + pad, w)
wood = vgradient(h, w, [(0, '#4c3b26'), (0.30, '#5a4529'), (0.65, '#6b5232'), (1, '#806239')])
wood = vgradient(h, w, [(0, PALETTE['wood_0']), (0.30, PALETTE['wood_1']), (0.65, PALETTE['wood_2']),
(1, PALETTE['wood_3'])])
wood = overlay(wood, fractal(h, w, 300 * s, 11 * s, 3, seed=9), 0.32)
wood = overlay(wood, fractal(h, w, 33 * s, None, 3, seed=4), 0.2)
shade = rect_mask(h + pad, w, 0, 0, w, h + 4 * s)
over(img, shadow(h + pad, w, shade, '#000000', 0.6, 16 * s, 0, 5 * s))
over(img, kept(('band shadow', w, h, s), lambda: shadow(h + pad, w, rect_mask(h + pad, w, 0, 0, w, h + 4 * s),
'#000000', 0.6, 16 * s, 0, 5 * s)))
top = new(h, w)
top[..., :3], top[..., 3] = wood, 1
over(img, top)
paint(img, rect_mask(h + pad, w, 0, h, w, h + 2 * s), '#2c2217')
paint(img, rect_mask(h + pad, w, 0, h + 2 * s, w, h + 4 * s), '#a9874f')
paint(img, rect_mask(h + pad, w, 0, h, w, h + 2 * s), PALETTE['band_line_dark'])
paint(img, rect_mask(h + pad, w, 0, h + 2 * s, w, h + 4 * s), PALETTE['band_line_light'])
return img
def panel(w, h, s):
"""The left list panel with the shadow on its right."""
def panel(w, h, s, alpha=1.0):
"""The left list panel with the shadow on its right. alpha below 1 lets the player's own background show through
it."""
sh = int(26 * s)
img = new(h, w + sh)
body = rect_mask(h, w + sh, 0, 0, w, h)
over(img, shadow(h, w + sh, body, '#000000', 0.35, 18 * s, 6 * s, 0))
over(img, kept(('panel shadow', w, h, s), lambda: shadow(h, w + sh, rect_mask(h, w + sh, 0, 0, w, h), '#000000',
0.35, 18 * s, 6 * s, 0)))
col = np.broadcast_to(rgb(PALETTE['panel']), (h, w, 3)).copy()
col = overlay(col, fractal(h, w, 33 * s, None, 3, seed=4), 0.18)
layer = new(h, w)
layer[..., :3], layer[..., 3] = col, 1
over(img, layer)
if alpha < 1:
img[:, :w, 3] = alpha
return img
@@ -408,7 +571,7 @@ def label_cell(w, h, s, bright=False):
return img
def desc_box(w, h, s):
def desc_box(w, h, s, alpha=1.0):
pad = int(20 * s)
img = new(h + 2 * pad, w + 2 * pad)
body = rect_mask(h + 2 * pad, w + 2 * pad, pad, pad, pad + w, pad + h)
@@ -418,26 +581,28 @@ def desc_box(w, h, s):
layer = new(h, w)
layer[..., :3], layer[..., 3] = col, 1
over(img, layer, pad, pad)
if alpha < 1: # the player's own background shows through the box, not through its border
img[pad:pad + h, pad:pad + w, 3] = alpha
paint(img, ring_mask(h + 2 * pad, w + 2 * pad, pad, pad, pad + w, pad + h, max(1, round(s))),
PALETTE['desc_border'])
return img, pad
def glow_frames(w, h, s, n=8):
"""The selection cursor around a w x h box: a 3 px white frame 6 px outside it with a soft blue glow inside and
out, n frames of one breath. Returns (frames, margin) where the box sits at (margin, margin)."""
def glow_frames(w, h, s, n=12):
"""The selection cursor around a w x h box: a 3 px white frame 6 px outside it with a soft glow of the scheme's
colour inside and out, n frames of one breath. Returns (frames, margin) where the box sits at (margin, margin)."""
gap, thick, spread = 6 * s, 3 * s, 16 * s
mg = int(gap + spread)
H, W = h + 2 * mg, w + 2 * mg
ring = ring_mask(H, W, mg - gap, mg - gap, mg + w + gap, mg + h + gap, thick)
soft_out = box_blur(ring, 6 * s)
soft_far = box_blur(ring, 12 * s)
soft_out = kept(('glow near', w, h, s), lambda: np.clip(box_blur(ring, 6 * s) * 2.8, 0, 1))
soft_far = kept(('glow far', w, h, s), lambda: np.clip(box_blur(ring, 12 * s) * 2.2, 0, 1))
frames = []
for k in range(n):
t = 0.5 - 0.5 * np.cos(2 * np.pi * k / n)
img = new(H, W)
paint(img, np.clip(soft_far * 2.2, 0, 1), '#96b4e6', 0.35 + 0.25 * t)
paint(img, np.clip(soft_out * 2.8, 0, 1), '#afc5e8', 0.7 + 0.3 * t)
paint(img, soft_far, PALETTE['glow_far'], 0.35 + 0.25 * t)
paint(img, soft_out, PALETTE['glow_near'], 0.7 + 0.3 * t)
paint(img, ring, PALETTE['glow'])
frames.append(img)
return frames, mg
@@ -574,12 +739,12 @@ def framed_icon(size, s, kind):
"""The square-framed icon of a big row (play or refresh), like the icon frames of the game's menu rows."""
img = new(size, size)
t = 1.5 * s
paint(img, ring_mask(size, size, 0.5, 0.5, size - 0.5, size - 0.5, t), '#e9dcc0')
paint(img, ring_mask(size, size, 0.5, 0.5, size - 0.5, size - 0.5, t), PALETTE['icon_frame'])
c = size / 2
if kind == 'play':
k = size / 32
paint(img, polygon_mask(size, size, [(c - 5 * k, c - 7 * k), (c + 7 * k, c), (c - 5 * k, c + 7 * k)]),
'#efe4ca')
PALETTE['icon_fill'])
elif kind == 'refresh':
import math
k = size / 32
@@ -594,7 +759,7 @@ def framed_icon(size, s, kind):
[(c + r * math.cos(math.radians(160)) + 3.5 * k, c + r * math.sin(math.radians(160)) + 1 * k),
(c + r * math.cos(math.radians(160)), c + r * math.sin(math.radians(160))),
(c + r * math.cos(math.radians(160)) - 0.5 * k, c + r * math.sin(math.radians(160)) + 4 * k)]]
paint(img, stroke_mask(size, size, arcs + heads, 2.2 * k), '#efe4ca')
paint(img, stroke_mask(size, size, arcs + heads, 2.2 * k), PALETTE['icon_fill'])
return img
@@ -602,11 +767,11 @@ def badge(size, s):
"""The orange "!" disc beside Updates when a new version is ready (the "!" itself is text)."""
img = new(size + 4, size + 4)
ring = stroke_mask(size + 4, size + 4, [[((size + 4) / 2, (size + 4) / 2)]], size + 1.5 * s)
over(img, shadow(size + 4, size + 4, ring, '#fbbd45', 0.6, 6 * s))
paint(img, ring, '#3a2a14')
over(img, shadow(size + 4, size + 4, ring, PALETTE['badge_top'], 0.6, 6 * s))
paint(img, ring, PALETTE['badge_ring'])
disc = stroke_mask(size + 4, size + 4, [[((size + 4) / 2, (size + 4) / 2)]], size)
layer = new(size + 4, size + 4)
layer[..., :3] = vgradient(size + 4, size + 4, [(0, '#fbbd45'), (1, '#e2942a')])
layer[..., :3] = vgradient(size + 4, size + 4, [(0, PALETTE['badge_top']), (1, PALETTE['badge_bottom'])])
layer[..., 3] = disc
over(img, layer)
return img

218
launcher/ui/picture.py Normal file
View File

@@ -0,0 +1,218 @@
"""The player's own background picture (Customize Launcher): read a picture file into a numpy array, fit it to the
window's shape and keep that copy in data/background.npy, so the launcher shows it without the file it came from.
Pillow reads the file where the launcher's Python has it (a release's does: tools/requirements-launcher.txt), turned
the way its EXIF data says. Without Pillow (a checkout's Python may lack it), GDI+ reads it on Windows (PNG, JPEG,
BMP, GIF, TIFF) and Tk elsewhere (PNG, GIF; the pixels come over as a PPM file). The kept copy is 8-bit RGB at
KEEP_W x KEEP_H, 1.6 times the window's logical size: enough for a display scaled to 200 %, and five megabytes on
disk.
"""
import ctypes
import os
import tempfile
from pathlib import Path
import numpy as np
KEEP_W, KEEP_H = 1600, 1024 # the window's 1000 x 640 times 1.6
MAX_SIDE, MAX_PIXELS = 16384, 120_000_000
try:
from PIL import Image, ImageOps
except ImportError:
Image = None
# the file types the dialog offers: what the reader in use takes (load)
TYPES = ('.png', '.jpg', '.jpeg', '.webp', '.bmp', '.gif', '.tif', '.tiff') if Image else ('.png', '.jpg', '.jpeg', '.bmp', '.gif', '.tif', '.tiff') if os.name == 'nt' else ('.png', '.gif')
class PictureError(Exception):
"""The file is no picture this PC can read; the text is for the player."""
def _too_large(path, w, h):
return PictureError(f'{Path(path).name} is {w} x {h} pixels; the background takes up to {MAX_SIDE} pixels a side '
f'and {MAX_PIXELS // 1_000_000} megapixels.')
def _load_pillow(path):
"""The picture as an H x W x 3 uint8 array, read by Pillow and turned upright (a phone's photo says in its EXIF
data which way is up)."""
try:
with Image.open(path) as im:
w, h = im.size
if not w or not h or w > MAX_SIDE or h > MAX_SIDE or w * h > MAX_PIXELS:
raise _too_large(path, w, h)
return np.asarray(ImageOps.exif_transpose(im).convert('RGB')).copy()
except PictureError:
raise
except Exception as e: # Pillow raises its own errors, OSError and SyntaxError for files it cannot read
raise PictureError(f'{Path(path).name} is not a picture the launcher can read: {e}') from None
def _load_gdiplus(path):
"""The picture as an H x W x 3 uint8 array, read by GDI+ (part of Windows)."""
from ctypes import wintypes
class StartupInput(ctypes.Structure):
_fields_ = [('GdiplusVersion', ctypes.c_uint32), ('DebugEventCallback', ctypes.c_void_p),
('SuppressBackgroundThread', wintypes.BOOL), ('SuppressExternalCodecs', wintypes.BOOL)]
class BitmapData(ctypes.Structure):
_fields_ = [('Width', ctypes.c_uint), ('Height', ctypes.c_uint), ('Stride', ctypes.c_int),
('PixelFormat', ctypes.c_int), ('Scan0', ctypes.c_void_p), ('Reserved', ctypes.c_void_p)]
g = ctypes.WinDLL('gdiplus')
vp, pvp = ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p)
g.GdiplusStartup.argtypes = [pvp, ctypes.POINTER(StartupInput), vp]
g.GdiplusShutdown.argtypes = [vp]
g.GdipCreateBitmapFromFile.argtypes = [ctypes.c_wchar_p, pvp]
g.GdipGetImageWidth.argtypes = g.GdipGetImageHeight.argtypes = [vp, ctypes.POINTER(ctypes.c_uint)]
g.GdipBitmapLockBits.argtypes = [vp, ctypes.POINTER(ctypes.c_int * 4), ctypes.c_uint, ctypes.c_int,
ctypes.POINTER(BitmapData)]
g.GdipBitmapUnlockBits.argtypes = [vp, ctypes.POINTER(BitmapData)]
g.GdipDisposeImage.argtypes = [vp]
token = vp()
if g.GdiplusStartup(ctypes.byref(token), ctypes.byref(StartupInput(1, None, 0, 0)), None):
raise PictureError('Windows could not start its picture reader (GDI+).')
bmp = vp()
try:
if g.GdipCreateBitmapFromFile(str(path), ctypes.byref(bmp)) or not bmp:
raise PictureError(f'{Path(path).name} is not a picture Windows can read (PNG, JPEG, BMP, GIF or TIFF).')
w, h = ctypes.c_uint(), ctypes.c_uint()
g.GdipGetImageWidth(bmp, ctypes.byref(w))
g.GdipGetImageHeight(bmp, ctypes.byref(h))
w, h = w.value, h.value
if not w or not h or w > MAX_SIDE or h > MAX_SIDE or w * h > MAX_PIXELS:
raise _too_large(path, w, h)
data = BitmapData()
rect = (ctypes.c_int * 4)(0, 0, w, h)
# ImageLockModeRead, PixelFormat32bppARGB: GDI+ converts whatever the file holds
if g.GdipBitmapLockBits(bmp, ctypes.byref(rect), 1, 0x26200A, ctypes.byref(data)) or not data.Scan0:
raise PictureError(f'{Path(path).name} could not be decoded.')
try:
stride = abs(data.Stride)
raw = np.frombuffer(ctypes.string_at(data.Scan0, stride * h), dtype=np.uint8).reshape(h, stride)
bgra = raw[:, :w * 4].reshape(h, w, 4)
if data.Stride < 0: # bottom-up rows
bgra = bgra[::-1]
return bgra[..., [2, 1, 0]].copy()
finally:
g.GdipBitmapUnlockBits(bmp, ctypes.byref(data))
finally:
if bmp:
g.GdipDisposeImage(bmp)
g.GdiplusShutdown(token)
def read_ppm(data):
"""A binary PPM (P6, 8 bits a channel) as an H x W x 3 uint8 array."""
fields, pos = [], 0
while len(fields) < 4: # magic, width, height, maximum: separated by white space, comments from # to line end
while data[pos:pos + 1].isspace():
pos += 1
if data[pos:pos + 1] == b'#':
pos = data.index(b'\n', pos) + 1
continue
end = pos
while end < len(data) and not data[end:end + 1].isspace():
end += 1
fields.append(data[pos:end])
pos = end
if fields[0] != b'P6' or int(fields[3]) != 255:
raise PictureError('not an 8-bit binary PPM')
w, h = int(fields[1]), int(fields[2])
return np.frombuffer(data, dtype=np.uint8, count=w * h * 3, offset=pos + 1).reshape(h, w, 3).copy()
def _load_tk(path, master):
"""The picture read by Tk (PNG, GIF) and written out as a PPM, which is three bytes a pixel after a short header."""
import tkinter as tk
try:
photo = tk.PhotoImage(master=master, file=str(path))
except tk.TclError:
raise PictureError(f'{Path(path).name} is not a PNG or GIF picture.') from None
w, h = photo.width(), photo.height()
if not w or not h or w > MAX_SIDE or h > MAX_SIDE or w * h > MAX_PIXELS:
raise _too_large(path, w, h)
fd, tmp = tempfile.mkstemp(suffix='.ppm')
os.close(fd)
try:
photo.write(tmp, format='ppm')
return read_ppm(Path(tmp).read_bytes())
finally:
os.unlink(tmp)
def load(path, master=None):
"""The picture file as an H x W x 3 uint8 array. master: a Tk window, needed where Tk reads the file."""
if not Path(path).is_file():
raise PictureError(f'{path} is not there.')
if Image:
return _load_pillow(path)
if os.name == 'nt':
try:
return _load_gdiplus(path)
except OSError as e: # no gdiplus.dll: Tk's own reader
if master is None:
raise PictureError(f'{Path(path).name} could not be read: {e}') from None
return _load_tk(path, master)
def resize(img, w, h):
"""img (H x W x 3) at w x h: whole pixels averaged first where it shrinks to less than half, then a bilinear
interpolation. Returns float32 when it interpolates."""
H, W = img.shape[:2]
k = min(H // h, W // w)
if k >= 2: # average k x k blocks, so a much larger picture does not alias
img = img[:H // k * k, :W // k * k].reshape(H // k, k, W // k, k, 3).mean(axis=(1, 3), dtype=np.float32)
H, W = img.shape[:2]
if (H, W) == (h, w):
return img
ys = (np.arange(h, dtype=np.float32) + 0.5) * H / h - 0.5
xs = (np.arange(w, dtype=np.float32) + 0.5) * W / w - 0.5
y0 = np.clip(np.floor(ys).astype(int), 0, H - 1)
x0 = np.clip(np.floor(xs).astype(int), 0, W - 1)
y1, x1 = np.minimum(y0 + 1, H - 1), np.minimum(x0 + 1, W - 1)
fy = np.clip(ys - y0, 0, 1)[:, None, None]
fx = np.clip(xs - x0, 0, 1)[None, :, None]
a = img.astype(np.float32)
top = a[y0][:, x0] * (1 - fx) + a[y0][:, x1] * fx
bot = a[y1][:, x0] * (1 - fx) + a[y1][:, x1] * fx
return top * (1 - fy) + bot * fy
def cover(img, w, h):
"""img cut to the shape w : h around its middle and resized to w x h, so it fills the window with nothing
stretched; uint8."""
H, W = img.shape[:2]
if W * h > H * w: # wider than the window: cut the sides
cw = max(1, round(H * w / h))
x = (W - cw) // 2
img = img[:, x:x + cw]
else: # taller: cut top and bottom
ch = max(1, round(W * h / w))
y = (H - ch) // 2
img = img[y:y + ch]
out = resize(img, w, h)
return np.clip(np.rint(out), 0, 255).astype(np.uint8)
def keep(path, store, master=None):
"""Reads the picture at path, fits it to the window's shape and writes it to store (data/background.npy)."""
fitted = cover(load(path, master), KEEP_W, KEEP_H)
store = Path(store)
tmp = store.with_name(store.name + '.tmp')
with open(tmp, 'wb') as f:
np.save(f, fitted, allow_pickle=False)
os.replace(tmp, store)
return fitted
def kept(store, w, h):
"""The kept background at w x h as float32 in 0..1, or None when there is none (or it is not what keep wrote)."""
try:
a = np.load(store, allow_pickle=False)
except (OSError, ValueError):
return None
if a.dtype != np.uint8 or a.ndim != 3 or a.shape[2] != 3 or a.shape[0] < 8 or a.shape[1] < 8:
return None
return np.clip(resize(a, w, h).astype(np.float32) / 255.0, 0, 1)

View File

@@ -15,11 +15,19 @@ def grab_gdi(x, y, w, h, path):
from ctypes import wintypes
import numpy as np
from . import art
user32, gdi32 = ctypes.windll.user32, ctypes.windll.gdi32
user32.GetDC.restype = wintypes.HDC
gdi32.CreateCompatibleDC.restype = wintypes.HDC
gdi32.CreateCompatibleBitmap.restype = wintypes.HBITMAP
gdi32.SelectObject.restype = wintypes.HGDIOBJ
# private handles with every argument typed: a handle is a pointer, and one above 2^31 passed as a plain int
# failed with "int too long to convert", so some screens went without their picture
user32, gdi32 = ctypes.WinDLL('user32'), ctypes.WinDLL('gdi32')
vp = ctypes.c_void_p
user32.GetDC.restype = gdi32.CreateCompatibleDC.restype = gdi32.CreateCompatibleBitmap.restype = vp
gdi32.SelectObject.restype = vp
user32.GetDC.argtypes = gdi32.CreateCompatibleDC.argtypes = gdi32.DeleteObject.argtypes = [vp]
gdi32.DeleteDC.argtypes = [vp]
user32.ReleaseDC.argtypes = gdi32.SelectObject.argtypes = [vp, vp]
gdi32.CreateCompatibleBitmap.argtypes = [vp, ctypes.c_int, ctypes.c_int]
gdi32.BitBlt.argtypes = [vp, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, vp, ctypes.c_int,
ctypes.c_int, wintypes.DWORD]
gdi32.GetDIBits.argtypes = [vp, vp, ctypes.c_uint, ctypes.c_uint, vp, vp, ctypes.c_uint]
screen = user32.GetDC(None)
mem = gdi32.CreateCompatibleDC(screen)
bmp = gdi32.CreateCompatibleBitmap(screen, w, h)
@@ -182,10 +190,28 @@ def states(app):
app.release, app.message = rel, ''
app.show('home', 1)
def customize():
app.bg.ready = lambda release=None: None
app.release, app.message, app.look_message = None, '', ''
app.show('customize', 0)
def color_scheme(): # another colour scheme on the home screen, then the first one again
from . import art
was = s.get('theme')
s['theme'] = list(art.THEMES)[2]
app.apply_look()
app.show('home', 0)
s['theme'] = was
def restore_scheme():
app.apply_look()
app.show('home', 0)
return [('1-first-run', first_run), ('2-installing', installing), ('3-home', home),
('4-update-ready', update_ready), ('5-updating', updating), ('6-settings', settings),
('7-build-failed', failed), ('8-uninstall', uninstall), ('9-import-saves', import_saves),
('10-shaders', shaders), ('11-update-staged', update_staged), ('12-export-save', export_save)]
('10-shaders', shaders), ('11-update-staged', update_staged), ('12-export-save', export_save),
('13-customize', customize), ('14-color-scheme', color_scheme), ('15-first-scheme', restore_scheme)]
def run(app, shots):

134
launcher/ui/sound.py Normal file
View File

@@ -0,0 +1,134 @@
"""The launcher's sound effects: short chimes made here from sine tones, so no sound file ships and none comes from
the game.
They are off until the player picks a loudness in Customize Launcher (the Sounds row). Each effect is a few plucked
notes (a tone with two overtones, a quick attack and an exponential decay) written as a 16-bit mono WAV in memory.
Windows plays it with PlaySound from that memory; elsewhere the WAV goes to a file in the cache folder and the first
of pw-play, paplay and aplay found plays it. One effect sounds at a time: a new one cuts the last, which suits a
cursor moving quickly down a list.
move the cursor went to another row
toggle a switch or a choice changed
select a row was chosen (another screen, a folder dialog)
back back to the screen before
start Play
done an install, update or rebuild finished
error something could not be done
"""
import ctypes
import os
import shutil
import struct
import subprocess
import numpy as np
RATE = 44100
LEVELS = {'off': 0.0, 'low': 0.18, 'medium': 0.4, 'high': 0.75} # the Sounds choice: the loudest sample's share of full scale
# Notes as (start in seconds, frequency in Hz, length in seconds, loudness 0..1).
C5, D5, E5, G5, A5, C6, D6, E6, G6, C7 = 523.25, 587.33, 659.25, 783.99, 880.0, 1046.5, 1174.66, 1318.51, 1567.98, 2093.0
EFFECTS = {
'move': [(0, E6, 0.07, 0.55)],
'toggle': [(0, G5, 0.10, 0.8), (0.035, D6, 0.10, 0.5)],
'select': [(0, C6, 0.12, 0.8), (0.07, G6, 0.20, 0.8)],
'back': [(0, G5, 0.12, 0.8), (0.07, C5, 0.20, 0.7)],
'start': [(0, C6, 0.14, 0.7), (0.08, E6, 0.14, 0.7), (0.16, G6, 0.14, 0.7), (0.24, C7, 0.45, 0.8)],
'done': [(0, G5, 0.16, 0.8), (0.12, C6, 0.16, 0.8), (0.24, E6, 0.16, 0.8), (0.36, G6, 0.5, 0.9)],
'error': [(0, 220.0, 0.16, 0.9), (0.14, 174.61, 0.3, 0.9)],
}
def pluck(freq, length, loudness):
"""One note: the tone and two quieter overtones, in within 4 ms and dying away over its length."""
n = int(RATE * length)
t = np.arange(n, dtype=np.float32) / RATE
wave = np.sin(2 * np.pi * freq * t) + 0.35 * np.sin(2 * np.pi * 2 * freq * t) + 0.12 * np.sin(2 * np.pi * 3 * freq * t)
env = np.minimum(t / 0.004, 1) * np.exp(-t * 5.5 / length)
tail = np.minimum((length - t) / 0.01, 1) # the last 10 ms go to nothing, so the end does not click
return wave * env * tail * loudness
def synth(name):
"""The effect's samples in -1..1, its loudest at 1."""
notes = EFFECTS[name]
total = int(RATE * max(start + length for start, _f, length, _l in notes)) + 1
out = np.zeros(total, dtype=np.float32)
for start, freq, length, loudness in notes:
note = pluck(freq, length, loudness)
at = int(RATE * start)
out[at:at + len(note)] += note
peak = float(np.abs(out).max())
return out / peak if peak > 0 else out
def wav_bytes(samples, level):
"""A 16-bit mono WAV of samples (-1..1) at level (0..1 of full scale)."""
pcm = (np.clip(samples * level, -1, 1) * 32767).astype('<i2').tobytes()
return (b'RIFF' + struct.pack('<I', 36 + len(pcm)) + b'WAVEfmt ' + struct.pack('<IHHIIHH', 16, 1, 1, RATE, RATE * 2, 2, 16)
+ b'data' + struct.pack('<I', len(pcm)) + pcm)
class Sounds:
"""Plays the effects at the level of the Sounds choice. Every failure is silent: a PC without a sound device, or
without a player program, just has a quiet launcher."""
def __init__(self, cache_dir, level='off', log=None):
self.cache = cache_dir
self.log = log or (lambda line: None)
self.level = None # set_level below: 'off' unless the player chose a loudness
self.wavs = {} # name -> WAV bytes at the current level (Windows plays from this memory: it must stay)
self.files = {} # name -> the WAV file elsewhere
self.player = None # elsewhere: the program that plays a WAV file
self.winmm = None
self.failed = False
if os.name == 'nt':
try:
self.winmm = ctypes.WinDLL('winmm')
self.winmm.PlaySoundW.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint32]
self.winmm.PlaySoundW.restype = ctypes.c_int
except (OSError, AttributeError) as e:
self.log(f'sounds: {e}')
else:
self.player = next((p for p in ('pw-play', 'paplay', 'aplay') if shutil.which(p)), None)
self.set_level(level)
def set_level(self, level):
level = level if level in LEVELS else 'off'
if level == self.level:
return
self.stop()
self.level = level
self.wavs, self.files = {}, {}
def wav(self, name):
if name not in self.wavs:
self.wavs[name] = wav_bytes(synth(name), LEVELS[self.level])
return self.wavs[name]
def stop(self):
"""Ends what is sounding, before the memory it plays from goes."""
if self.winmm:
try:
self.winmm.PlaySoundW(None, None, 0)
except OSError:
pass
def play(self, name):
if LEVELS.get(self.level, 0) <= 0 or self.failed or name not in EFFECTS:
return
try:
if self.winmm:
# SND_ASYNC | SND_NODEFAULT | SND_MEMORY: PlaySound reads the bytes while it plays, and self.wavs
# keeps them until the level changes (set_level stops the sound first)
self.winmm.PlaySoundW(self.wav(name), None, 0x0001 | 0x0002 | 0x0004)
elif self.player:
if name not in self.files:
path = self.cache / f'sound-{name}-{self.level}.wav'
path.write_bytes(self.wav(name))
self.files[name] = path
subprocess.Popen([self.player, str(self.files[name])], stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL)
except (OSError, ValueError) as e: # no device, no player: stay quiet from here on
self.failed = True
self.log(f'sounds: {e}')