write_soft_mask.py

Die Python-Datei des Beispiels „Eine Farbe, durch sechs Schablonen gesehen“. Derselbe Farbblock sechsmal, jeder durch eine eigene Schablone gesehen: eine Ausblendung für ein Foto unter einer Schlagzeile, abgedunkelte Ränder, die den Blick halten, sauber herausgeschnittene Buchstaben, eine Schablone aus einer bereits gezeichneten Form, dieselben Buchstaben umgestülpt und durch eine Kurve abgemilderte Buchstaben.

Python 497 Zeilen

Wofür dieses Beispiel da ist

Ein Foto, das zum Fuß eines Titelblatts hin ausblendet. Ein Banner, dessen Ränder dunkler werden. Ein aus einem Farbblock ausgeschnittenes Wort, so wie eine Schablone eine Form aus Karton schneidet. Diese drei Effekte werden meist in einem Zeichenprogramm gemacht und danach als Bild eingefügt — und ein Bild ist schwer, zeigt beim Drucken, wo es aufhört, und muss an dem Tag, an dem sich die Farbe ändert, ganz neu gemacht werden. Hier werden sie stattdessen im Dokument gezeichnet: derselbe Farbblock, sechsmal gezeigt, durch sechs verschiedene Schablonen gesehen.

Was dieses Beispiel zeigt

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
"""Fades, vignettes, cut-out and punched-out letters, all from soft masks.

The Python twin of the `write_soft_mask` example in Rust. A soft mask is a
drawing composited apart from the page and then read as a coverage rather than
shown: where it comes out light, what the state paints goes through whole; where
it comes out dark, nothing does. The same six panels are painted the same way —
one flat rectangle each — and differ only in the mask in force. The fifth is the
third's mask turned inside out. The sixth draws its letters dark on a white backdrop,
the colour the mask reads wherever its drawing paints nothing, and bends what it reads
through a curve, so the letters let the panel through at half strength.

The page is held in `Words`, once per language, and `HQF_PDF_LANG` picks which set is
drawn. The two words the third mask is drawn in are language as much as the captions
are: they are what the panel is seen through, and what the fifth is punched out by.

Usage: python examples/write_soft_mask.py [out.pdf] [font.ttf]
       HQF_PDF_LANG=fr python examples/write_soft_mask.py
"""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

import _language
import _licence
import _out

import hqf_pdf

# The size of one panel, in points.
PANEL = (215.0, 100.0)

# The bottom-left corner of each panel.
CORNERS = [
    (70.0, 630.0),
    (305.0, 630.0),
    (70.0, 500.0),
    (305.0, 500.0),
    (70.0, 370.0),
    (305.0, 370.0),
]

@dataclass(frozen=True)
class Words:
    """Every word the page draws, in one language.

    The two words the third mask is drawn in are here with the rest: the panel is seen
    through their shapes, so a reader reads them as much as a caption.
    """

    # The line at the head of the page.
    title: str
    # The two lines under it, saying what a mask is.
    intro: tuple[str, str]
    # What each panel shows, in the order they are laid out.
    captions: tuple[str, str, str, str, str, str]
    # The two words the third panel is cut through.
    cut: tuple[str, str]
    # The word on the tag the band's last state paints whole.
    whole: str
    # What stands under the band.
    band: str


# The page in English.
ENGLISH = Words(
    title="One flat rectangle, six masks",
    intro=(
        "Each panel below is the same rectangle in the same colour. What differs "
        "is the mask in",
        "force: a drawing composited apart from the page and read as a coverage "
        "rather than shown.",
    ),
    captions=(
        "Faded away by a black-to-white gradient",
        "Held in the middle by a radial one",
        "Cut through letters the mask drew",
        "Read from how opaque the mask came out",
        "Punched out by the same letters, turned inside out",
        "Letters on a white backdrop, eased by a curve",
    ),
    cut=("MASK", "THIS"),
    whole="WHOLE",
    band="A band running out under a mask, and a tag a second state paints whole",
)

# The page in French.
FRENCH = Words(
    title="Un rectangle plat, six masques",
    intro=(
        "Chaque panneau ci-dessous est le même rectangle, dans la même couleur. "
        "Seul change le",
        ("masque en vigueur : un dessin composé à part, lu comme une couverture, "
         "jamais affiché."),
    ),
    captions=(
        "Estompé par un dégradé du noir au blanc",
        "Retenu au centre par un dégradé radial",
        "Découpé par les lettres du masque",
        "Lu sur l’opacité du masque, non sur sa clarté",
        "Évidé par les mêmes lettres, masque inversé",
        "Lettres sur fond blanc, adoucies par une courbe",
    ),
    cut=("ÔTE", "ÇA"),
    whole="ENTIER",
    band=("Une bande qui s’éteint sous un masque, une étiquette qu’un second état "
          "peint entière"),
)

# The page in Dutch.
DUTCH = Words(
    title="Eén effen rechthoek, zes maskers",
    intro=(
        "Elk paneel hieronder is dezelfde rechthoek in dezelfde kleur. Wat verschilt "
        "is het masker dat",
        "geldt: een tekening die los van de pagina wordt samengesteld en als dekking "
        "gelezen in plaats van getoond.",
    ),
    captions=(
        "Weggevaagd door een verloop van zwart naar wit",
        "In het midden vastgehouden door een radiaal verloop",
        "Uitgesneden door letters die het masker tekende",
        "Gelezen uit hoe dekkend het masker uitviel",
        "Uitgestanst door dezelfde letters, binnenstebuiten",
        "Letters op een witte achtergrond, verzacht door een curve",
    ),
    cut=("MASKER", "DIT"),
    whole="HEEL",
    band="Een band die onder een masker uitloopt, en een label dat een tweede status helemaal schildert",
)

# The page in Portuguese.
PORTUGUESE = Words(
    title="Um retângulo liso, seis máscaras",
    intro=(
        "Cada painel abaixo é o mesmo retângulo na mesma cor. O que muda é a máscara",
        "em vigor: um desenho composto à parte da página e lido como cobertura em vez "
        "de ser mostrado.",
    ),
    captions=(
        "Esbatido por um degradé do preto ao branco",
        "Preso ao meio por um radial",
        "Recortado através de letras que a máscara desenhou",
        "Lido pela opacidade com que a máscara saiu",
        "Perfurado pelas mesmas letras, do avesso",
        "Letras sobre fundo branco, suavizadas por uma curva",
    ),
    cut=("MÁSCARA", "ESTE"),
    whole="INTEIRO",
    band="Uma faixa que se apaga sob uma máscara, e uma etiqueta que um segundo estado pinta inteira",
)

# The page in Italian.
ITALIAN = Words(
    title="Un rettangolo piatto, sei maschere",
    intro=(
        "Ogni pannello qui sotto è lo stesso rettangolo dello stesso colore. Ciò che "
        "cambia è la maschera",
        "in vigore: un disegno composto a parte dalla pagina e letto come copertura "
        "anziché mostrato.",
    ),
    captions=(
        "Sfumato da un gradiente dal nero al bianco",
        "Tenuto al centro da uno radiale",
        "Ritagliato attraverso lettere disegnate dalla maschera",
        "Letto da quanto opaca è uscita la maschera",
        "Traforato dalle stesse lettere, rovesciate",
        "Lettere su fondo bianco, ammorbidite da una curva",
    ),
    cut=("MASCHERA", "QUESTO"),
    whole="INTERO",
    band="Una fascia che si spegne sotto una maschera, e un’etichetta che un secondo stato dipinge intera",
)

# The page in Spanish.
SPANISH = Words(
    title="Un rectángulo plano, seis máscaras",
    intro=(
        "Cada panel de abajo es el mismo rectángulo del mismo color. Lo que cambia es "
        "la máscara",
        "vigente: un dibujo compuesto aparte de la página y leído como cobertura en "
        "vez de mostrarse.",
    ),
    captions=(
        "Desvanecido por un degradado de negro a blanco",
        "Sostenido en el centro por uno radial",
        "Recortado a través de letras que dibujó la máscara",
        "Leído según lo opaca que salió la máscara",
        "Perforado por las mismas letras, del revés",
        "Letras sobre un fondo blanco, suavizadas por una curva",
    ),
    cut=("MÁSCARA", "ESTE"),
    whole="ENTERO",
    band="Una banda que se apaga bajo una máscara, y una etiqueta que un segundo estado pinta entera",
)

# The page in German.
GERMAN = Words(
    title="Ein flaches Rechteck, sechs Masken",
    intro=(
        "Jedes Feld unten ist dasselbe Rechteck in derselben Farbe. Was sich "
        "unterscheidet, ist die",
        "wirksame Maske: eine getrennt von der Seite zusammengesetzte Zeichnung, als "
        "Deckung gelesen.",
    ),
    captions=(
        "Durch einen Verlauf von Schwarz nach Weiß ausgeblendet",
        "Durch einen radialen Verlauf in der Mitte gehalten",
        "Durch Buchstaben geschnitten, die die Maske zeichnete",
        "Aus der Deckkraft gelesen, mit der die Maske herauskam",
        "Von denselben Buchstaben ausgestanzt, umgekehrt",
        "Buchstaben auf weißem Hintergrund, durch eine Kurve gemildert",
    ),
    cut=("MASKE", "DIESE"),
    whole="GANZ",
    band="Ein Band, das unter einer Maske ausläuft, und ein Etikett, das ein zweiter Zustand ganz malt",
)


# Every language the example is written in. A language is added by writing its own set
# of words and naming it here.
WORDS = {_language.ENGLISH: ENGLISH, _language.FRENCH: FRENCH, _language.GERMAN: GERMAN, _language.SPANISH: SPANISH, _language.ITALIAN: ITALIAN, _language.PORTUGUESE: PORTUGUESE, _language.DUTCH: DUTCH}


def box_of(corner: tuple[float, float]) -> tuple[float, float, float, float]:
    """The rectangle of the panel at `corner`, as a quadruple."""
    width, height = PANEL
    return (corner[0], corner[1], width, height)


def painted_group(
    content: hqf_pdf.Content,
    corner: tuple[float, float],
    shading: hqf_pdf.ShadingHandle,
) -> None:
    """Paints `shading` across the panel at `corner` and nothing outside it."""
    x, y, width, height = box_of(corner)
    content.save_state()
    content.rect(x, y, width, height)
    content.clip()
    content.end_path()
    content.draw_shading(shading)
    content.restore_state()


def main() -> None:
    language = _language.from_environment()
    words = _language.words_of(WORDS, language)

    # A named file is written as named; the default one carries the language, so the two
    # languages do not overwrite each other in `tmp/`.
    out = _out.output_path(Path(_language.file_name("soft_mask.pdf", language)).stem)

    document = hqf_pdf.Document()
    document.set_license(_licence.licensed())
    font = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))

    black = hqf_pdf.Rgb.gray(0.0)
    white = hqf_pdf.Rgb.gray(1.0)

    # The mask of the first panel: a gradient running the panel's width, dark at the
    # left and light at the right.
    x0, y0, width0, _ = box_of(CORNERS[0])
    sweep = document.add_shading(
        hqf_pdf.Axial.rgb((x0, y0), (x0 + width0, y0), black, white)
    )
    faded = hqf_pdf.Content()
    painted_group(faded, CORNERS[0], sweep)
    fade = document.add_ext_gstate(
        hqf_pdf.ExtGState(
            soft_mask=hqf_pdf.SoftMask.luminosity(
                hqf_pdf.Drawing(faded, hqf_pdf.Rect(x0, y0, width0, PANEL[1])),
                hqf_pdf.DeviceSpace.Rgb,
            )
        )
    )

    # The second: light in the middle of the panel and dark at its edge, so what it
    # masks is held in the middle and let go at the sides.
    x1, y1, width1, height1 = box_of(CORNERS[1])
    middle = (x1 + width1 / 2.0, y1 + height1 / 2.0)
    halo = document.add_shading(
        hqf_pdf.Radial.rgb(
            (middle[0], middle[1], 0.0),
            (middle[0], middle[1], height1 / 2.0),
            white,
            black,
        ).extend(False, True)
    )
    vignette = hqf_pdf.Content()
    painted_group(vignette, CORNERS[1], halo)
    hold = document.add_ext_gstate(
        hqf_pdf.ExtGState(
            soft_mask=hqf_pdf.SoftMask.luminosity(
                hqf_pdf.Drawing(
                    vignette, hqf_pdf.Rect(x1, y1, width1, height1)
                ),
                hqf_pdf.DeviceSpace.Rgb,
            )
        )
    )

    # The third: letters in white on nothing at all. Everything the mask left alone
    # stays black, which lets nothing through, so the panel is seen only through the
    # shapes of the letters.
    x2, y2, width2, height2 = box_of(CORNERS[2])
    letters = hqf_pdf.Content()
    letters.set_fill(white)
    letters.draw_text(font, 38.0, x2 + 12.0, y2 + 56.0, words.cut[0])
    letters.draw_text(font, 38.0, x2 + 12.0, y2 + 14.0, words.cut[1])
    cut = document.add_ext_gstate(
        hqf_pdf.ExtGState(
            soft_mask=hqf_pdf.SoftMask.luminosity(
                hqf_pdf.Drawing(letters, hqf_pdf.Rect(x2, y2, width2, height2)),
                hqf_pdf.DeviceSpace.Rgb,
            )
        )
    )

    # The fifth: the same letters, and the mask turned inside out, so the letters stop
    # the panel and everything round them lets it through.
    x4, y4, width4, height4 = box_of(CORNERS[4])
    punched = hqf_pdf.Content()
    punched.set_fill(white)
    punched.draw_text(font, 38.0, x4 + 12.0, y4 + 56.0, words.cut[0])
    punched.draw_text(font, 38.0, x4 + 12.0, y4 + 14.0, words.cut[1])
    punch = document.add_ext_gstate(
        hqf_pdf.ExtGState(
            soft_mask=hqf_pdf.SoftMask.luminosity(
                hqf_pdf.Drawing(punched, hqf_pdf.Rect(x4, y4, width4, height4)),
                hqf_pdf.DeviceSpace.Rgb,
            ).inverted()
        )
    )

    # The fourth reads how opaque the mask came out rather than how light, so the shapes
    # it paints let the panel through by exactly the opacity they were painted at,
    # whatever colour they were.
    dimmed = document.add_ext_gstate(hqf_pdf.ExtGState(fill_alpha=0.4, stroke_alpha=0.4))
    x3, y3, width3, height3 = box_of(CORNERS[3])
    shapes = hqf_pdf.Content()
    shapes.set_fill(hqf_pdf.Rgb(0.2, 0.6, 0.9))
    shapes.rect(x3 + 14.0, y3 + 14.0, 90.0, 72.0)
    shapes.fill()
    shapes.save_state()
    shapes.set_ext_gstate(dimmed)
    shapes.set_fill(hqf_pdf.Rgb(0.9, 0.4, 0.1))
    shapes.rect(x3 + 112.0, y3 + 14.0, 90.0, 72.0)
    shapes.fill()
    shapes.restore_state()
    through = document.add_ext_gstate(
        hqf_pdf.ExtGState(
            soft_mask=hqf_pdf.SoftMask.alpha(
                hqf_pdf.Drawing(shapes, hqf_pdf.Rect(x3, y3, width3, height3))
            )
        )
    )

    # The sixth: the letters drawn dark, on a backdrop of white. Where the drawing
    # paints nothing the mask reads the backdrop and lets the panel through; the curve
    # lifts the dark of the letters halfway, so they let half of it through.
    x5, y5, width5, height5 = box_of(CORNERS[5])
    dark = hqf_pdf.Content()
    dark.set_fill(black)
    dark.draw_text(font, 38.0, x5 + 12.0, y5 + 56.0, words.cut[0])
    dark.draw_text(font, 38.0, x5 + 12.0, y5 + 14.0, words.cut[1])
    eased = document.add_ext_gstate(
        hqf_pdf.ExtGState(
            soft_mask=hqf_pdf.SoftMask.luminosity(
                hqf_pdf.Drawing(dark, hqf_pdf.Rect(x5, y5, width5, height5)),
                hqf_pdf.DeviceSpace.Rgb,
            )
            .backdrop([1.0, 1.0, 1.0])
            .transfer(
                hqf_pdf.Function.exponential((0.0, 1.0), 1.0, endpoints=([0.5], [1.0]))
            )
        )
    )

    # The last: a band running out towards its right edge, and the state that drops the
    # mask again for what is painted inside it.
    run_out = document.add_shading(
        hqf_pdf.Axial.rgb((70.0, 200.0), (520.0, 200.0), white, black)
    )
    band = hqf_pdf.Content()
    band.save_state()
    band.rect(70.0, 200.0, 450.0, 130.0)
    band.clip()
    band.end_path()
    band.draw_shading(run_out)
    band.restore_state()
    run_out = document.add_ext_gstate(
        hqf_pdf.ExtGState(
            soft_mask=hqf_pdf.SoftMask.luminosity(
                hqf_pdf.Drawing(band, hqf_pdf.Rect(70.0, 200.0, 450.0, 130.0)),
                hqf_pdf.DeviceSpace.Rgb,
            )
        )
    )
    whole = document.add_ext_gstate(hqf_pdf.ExtGState(without_soft_mask=True))

    content = hqf_pdf.Content()
    content.draw_text(font, 15.0, 70.0, 780.0, words.title)
    content.save_state()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    content.draw_text(
        font,
        10.0,
        70.0,
        762.0,
        words.intro[0],
    )
    content.draw_text(
        font,
        10.0,
        70.0,
        748.0,
        words.intro[1],
    )
    content.restore_state()

    ink = hqf_pdf.Rgb(0.12, 0.28, 0.52)
    states = [fade, hold, cut, through, punch, eased]
    for corner, caption, state in zip(CORNERS, words.captions, states):
        x, y, width, height = box_of(corner)

        content.save_state()
        content.set_fill(hqf_pdf.Rgb(0.96, 0.96, 0.94))
        content.rect(x, y, width, height)
        content.fill()
        content.set_ext_gstate(state)
        content.set_fill(ink)
        content.rect(x, y, width, height)
        content.fill()
        content.restore_state()

        content.save_state()
        content.set_stroke(hqf_pdf.Rgb.gray(0.55))
        content.set_line_width(0.6)
        content.rect(x, y, width, height)
        content.stroke()
        content.set_fill(hqf_pdf.Rgb.gray(0.35))
        content.draw_text(font, 9.0, x, y - 14.0, caption)
        content.restore_state()

    # A mask holds until the state that set it is restored, or until a state drops it:
    # the band fades out, and the tag inside it is painted whole.
    x4, y4 = 70.0, 200.0
    width4, height4 = 450.0, 130.0
    content.save_state()
    content.set_fill(hqf_pdf.Rgb(0.96, 0.96, 0.94))
    content.rect(x4, y4, width4, height4)
    content.fill()
    content.set_ext_gstate(run_out)
    content.set_fill(ink)
    content.rect(x4, y4, width4, height4)
    content.fill()

    content.save_state()
    content.set_ext_gstate(whole)
    content.set_fill(hqf_pdf.Rgb(0.85, 0.42, 0.15))
    content.rect(x4 + 300.0, y4 + 45.0, 120.0, 60.0)
    content.fill()
    content.set_fill(hqf_pdf.Rgb.gray(1.0))
    content.draw_text(font, 13.0, x4 + 318.0, y4 + 68.0, words.whole)
    content.restore_state()
    content.restore_state()

    content.save_state()
    content.set_stroke(hqf_pdf.Rgb.gray(0.55))
    content.set_line_width(0.6)
    content.rect(x4, y4, width4, height4)
    content.stroke()
    content.set_fill(hqf_pdf.Rgb.gray(0.35))
    content.draw_text(
        font,
        9.0,
        x4,
        y4 - 14.0,
        words.band,
    )
    content.restore_state()

    page = hqf_pdf.Page.a4()
    page.set_content(content)
    document.add_page(page)

    written = document.write(out)
    print(
        f"wrote {out}: {written} bytes, {len(CORNERS)} masked panels "
        "and a band that runs out"
    )


if __name__ == "__main__":
    main()