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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534 | """Paints axial, radial and function-based gradients, each into a clipped box.
The Python twin of the `write_gradient` example in Rust. Six panels: a
horizontal two-colour gradient, a diagonal one, a radial one whose outer colour
is extended to fill the corners, a three-stop gradient built from a stitched
function, a checkerboard whose colour is read from a calculation of both
coordinates of the point, the reader asked to filter its sudden colour steps
against aliasing, and a radial gradient extended both ways that holds itself to
its box. Each is added to the document once; the first five are painted into a
rectangle the page clips to, the last is painted with no clip at all.
The second page says the same kind of gradient in the inks a press lays down: from one
process colour to another, a radial one in the same inks, one ink of the press's own
from none to full, and two such inks at once, one fading as the other rises. Under them,
a gradient said in CIE L*a*b*, a space the document holds, runs through three colours set
at three places along it. Each label counts the numbers a point of its gradient is made
of, read from the space it is said in.
The title and the eleven labels are held in `Words`, once per language, and
`HQF_PDF_LANG` picks which set is drawn.
Usage: python examples/write_gradient.py [out.pdf] [font.ttf]
HQF_PDF_LANG=fr python examples/write_gradient.py
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
import _language
import _licence
import _out
import hqf_pdf
# The width and height of every panel, in points.
BOX = (210.0, 170.0)
# How many squares the checkerboard is cut into along each of its two axes.
SQUARES = 8.0
# How much of the colour it lands on a darkened square of the checkerboard keeps.
SHADED = 0.45
@dataclass(frozen=True)
class Words:
"""Every word the page draws, in one language."""
# The title across the top of the page.
title: str
# The label under each of the six panels.
horizontal: str
diagonal: str
radial: str
three_stops: str
checkerboard: str
bounded: str
# The second page's title.
inks_title: str
# The label under each of the second page's four panels; `{n}` stands for the count
# of numbers a point of the gradient is made of.
inks: tuple[str, str, str, str]
# The label under the gradient said in L*a*b*; `{n}` as in `inks`.
lab: str
# The page in English.
ENGLISH = Words(
title="Gradients, and a colour read from a function",
horizontal="Axial, two colours",
diagonal="Axial, on the diagonal",
radial="Radial, outer extended",
three_stops="Axial, three stops",
checkerboard=(
"Function-based: a checkerboard on x and y at once, anti-aliasing asked for"
),
bounded="Radial, held to its own box",
inks_title="The same gradients, in the inks a press lays down",
inks=(
"Axial, four inks: {n} numbers a point",
"Radial, four inks, outer extended",
"One ink of its own: {n} number a point",
"Two inks at once: {n} numbers a point",
),
lab="L*a*b*, three stops: {n} numbers a point",
)
# The page in French.
FRENCH = Words(
title="Dégradés, et une couleur lue dans une fonction",
horizontal="Linéaire, deux couleurs",
diagonal="Linéaire, en diagonale",
radial="Radial, couleur extérieure prolongée",
three_stops="Linéaire, trois couleurs",
checkerboard=(
"Par fonction : un damier en largeur et en hauteur à la fois, anticrénelage "
"demandé"
),
bounded="Radial, limité à sa propre boîte",
inks_title="Les mêmes dégradés, dans les encres d’imprimerie",
inks=(
"Linéaire, quatre encres : {n} nombres par point",
"Radial, quatre encres, extérieur prolongé",
"Un ton direct : {n} nombre par point",
"Deux encres à la fois : {n} nombres par point",
),
lab="L*a*b*, trois couleurs : {n} nombres par point",
)
# The page in Dutch.
DUTCH = Words(
title="Verlopen, en een kleur gelezen uit een functie",
horizontal="Axiaal, twee kleuren",
diagonal="Axiaal, op de diagonaal",
radial="Radiaal, buitenkant doorgetrokken",
three_stops="Axiaal, drie stops",
checkerboard=(
"Op functie gebaseerd: een dambord in x en y tegelijk, met anti-aliasing gevraagd"
),
bounded="Radiaal, binnen zijn eigen kader gehouden",
inks_title="Dezelfde verlopen, in de inkten die een pers neerlegt",
inks=(
"Axiaal, vier inkten: {n} getallen per punt",
"Radiaal, vier inkten, buitenkant doorgetrokken",
"Eén eigen inkt: {n} getal per punt",
"Twee inkten tegelijk: {n} getallen per punt",
),
lab="L*a*b*, drie stops: {n} getallen per punt",
)
# The page in Portuguese.
PORTUGUESE = Words(
title="Degradés, e uma cor lida de uma função",
horizontal="Axial, duas cores",
diagonal="Axial, na diagonal",
radial="Radial, exterior prolongado",
three_stops="Axial, três pontos de cor",
checkerboard=(
"Baseado em função: um tabuleiro de xadrez em x e y ao mesmo tempo, com suavização pedida"
),
bounded="Radial, preso à sua caixa",
inks_title="Os mesmos degradés, nas tintas que uma gráfica põe",
inks=(
"Axial, quatro tintas: {n} números por ponto",
"Radial, quatro tintas, exterior prolongado",
"Uma tinta própria: {n} número por ponto",
"Duas tintas juntas: {n} números por ponto",
),
lab="L*a*b*, três cores: {n} números por ponto",
)
# The page in Italian.
ITALIAN = Words(
title="Gradienti, e un colore letto da una funzione",
horizontal="Assiale, due colori",
diagonal="Assiale, in diagonale",
radial="Radiale, esterno esteso",
three_stops="Assiale, tre arresti",
checkerboard=(
"Basato su funzione: una scacchiera in x e y insieme, con antialias richiesto"
),
bounded="Radiale, tenuto nel suo riquadro",
inks_title="Gli stessi gradienti, negli inchiostri da stampa",
inks=(
"Assiale, quattro inchiostri: {n} numeri per punto",
"Radiale, quattro inchiostri, esterno esteso",
"Un inchiostro proprio: {n} numero per punto",
"Due inchiostri insieme: {n} numeri per punto",
),
lab="L*a*b*, tre arresti: {n} numeri per punto",
)
# The page in Spanish.
SPANISH = Words(
title="Degradados, y un color leído de una función",
horizontal="Axial, dos colores",
diagonal="Axial, en diagonal",
radial="Radial, exterior prolongado",
three_stops="Axial, tres paradas",
checkerboard=(
"Basado en función: un damero en x e y a la vez, con suavizado pedido"
),
bounded="Radial, ceñido a su propia caja",
inks_title="Los mismos degradados, en tintas de imprenta",
inks=(
"Axial, cuatro tintas: {n} números por punto",
"Radial, cuatro tintas, exterior prolongado",
"Una tinta propia: {n} número por punto",
"Dos tintas a la vez: {n} números por punto",
),
lab="L*a*b*, tres paradas: {n} números por punto",
)
# The page in German.
GERMAN = Words(
title="Verläufe und eine Farbe aus einer Funktion",
horizontal="Axial, zwei Farben",
diagonal="Axial, auf der Diagonale",
radial="Radial, außen verlängert",
three_stops="Axial, drei Stufen",
checkerboard=(
"Funktionsbasiert: Schachbrett über x und y, mit Kantenglättung"
),
bounded="Radial, auf seinen eigenen Rahmen begrenzt",
inks_title="Dieselben Verläufe in Druckfarben",
inks=(
"Axial, vier Farben: {n} Zahlen je Punkt",
"Radial, vier Farben, außen verlängert",
"Eine eigene Farbe: {n} Zahl je Punkt",
"Zwei Farben zugleich: {n} Zahlen je Punkt",
),
lab="L*a*b*, drei Stufen: {n} Zahlen je Punkt",
)
# 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 panel(content, font, shading, x, y, label):
"""Paint a gradient into the box at (x, y), sized BOX, and label it."""
content.save_state()
content.rect(x, y, BOX[0], BOX[1])
content.clip()
content.end_path()
content.draw_shading(shading)
content.restore_state()
content.draw_text(font, 10.0, x, y - 15.0, label)
def checkerboard(x, y):
"""The gradient that paints a checkerboard into the box at (x, y), sized BOX.
Its colour is read from a calculation of both coordinates of the point at once:
red grows across the box, green grows up it, and every other square of the
SQUARES by SQUARES board keeps only SHADED of the colour it lands on. The reader is
asked to filter the sudden steps between squares against aliasing.
"""
return hqf_pdf.FunctionBased(
((0.0, 1.0), (0.0, 1.0)),
(BOX[0], 0.0, 0.0, BOX[1], x, y),
hqf_pdf.DeviceSpace.Rgb,
hqf_pdf.Calculation(
[(0.0, 1.0), (0.0, 1.0)],
[(0.0, 1.0), (0.0, 1.0), (0.0, 1.0)],
[
hqf_pdf.Op.integer(2),
hqf_pdf.Op.copy(),
hqf_pdf.Op.real(SQUARES),
hqf_pdf.Op.multiply(),
hqf_pdf.Op.floor(),
hqf_pdf.Op.exchange(),
hqf_pdf.Op.real(SQUARES),
hqf_pdf.Op.multiply(),
hqf_pdf.Op.floor(),
hqf_pdf.Op.add(),
hqf_pdf.Op.to_integer(),
hqf_pdf.Op.integer(2),
hqf_pdf.Op.modulo(),
hqf_pdf.Op.integer(0),
hqf_pdf.Op.not_equal(),
hqf_pdf.Op.integer(3),
hqf_pdf.Op.integer(1),
hqf_pdf.Op.roll(),
hqf_pdf.Op.real(0.2),
hqf_pdf.Op.integer(4),
hqf_pdf.Op.integer(3),
hqf_pdf.Op.roll(),
hqf_pdf.Op.if_(
[
hqf_pdf.Op.real(SHADED),
hqf_pdf.Op.multiply(),
hqf_pdf.Op.integer(3),
hqf_pdf.Op.integer(1),
hqf_pdf.Op.roll(),
hqf_pdf.Op.real(SHADED),
hqf_pdf.Op.multiply(),
hqf_pdf.Op.integer(3),
hqf_pdf.Op.integer(1),
hqf_pdf.Op.roll(),
hqf_pdf.Op.real(SHADED),
hqf_pdf.Op.multiply(),
hqf_pdf.Op.integer(3),
hqf_pdf.Op.integer(1),
hqf_pdf.Op.roll(),
]
),
],
),
).anti_alias(True)
# What one point of Corporate Blue lays down on each process plate, at full strength.
BLUE = [0.92, 0.58, 0.0, 0.06]
GOLD = [0.0, 0.28, 0.95, 0.04]
# The white the L*a*b* gradient is measured against: daylight at 5000 K, as CIE XYZ.
D50 = (0.9642, 1.0, 0.8249)
# The three colours of the L*a*b* gradient and where along it each one is reached: a
# deep blue, a near white and a warm orange, as lightness, then green to red, then blue
# to yellow.
LAB_STOPS = [
(0.0, [30.0, 20.0, -60.0]),
(0.5, [95.0, 0.0, 0.0]),
(1.0, [65.0, 45.0, 70.0]),
]
def mix_two_inks():
"""The program that shows the two inks together where their plates are not to
hand: each process plate takes the first ink's share at the first tint plus the
second ink's at the second.
Both tints stay at the bottom of the stack while the four outputs are worked out
above them, so each one is reached again by counting down past the outputs already
there; the pair is then turned to the top and thrown away.
"""
body = []
reach = 1
for first, second in zip(BLUE, GOLD):
body += [
hqf_pdf.Op.integer(reach),
hqf_pdf.Op.index(),
hqf_pdf.Op.real(first),
hqf_pdf.Op.multiply(),
hqf_pdf.Op.integer(reach),
hqf_pdf.Op.index(),
hqf_pdf.Op.real(second),
hqf_pdf.Op.multiply(),
hqf_pdf.Op.add(),
]
reach += 1
body += [
hqf_pdf.Op.integer(6),
hqf_pdf.Op.integer(4),
hqf_pdf.Op.roll(),
hqf_pdf.Op.pop(),
hqf_pdf.Op.pop(),
]
return hqf_pdf.Calculation([(0.0, 1.0)] * 2, [(0.0, 1.0)] * 4, body)
def counted(label, space):
"""A label whose `{n}` is the count of numbers a colour in `space` is made of."""
return label.replace("{n}", str(space.components))
def inks_page(document, font, words):
"""Draw the second page: the gradients said in the inks a press lays down."""
left, right, top, bottom, lowest = 70.0, 315.0, 560.0, 330.0, 100.0
process = hqf_pdf.DeviceSpace.Cmyk
axial = document.add_shading(
hqf_pdf.Axial.cmyk(
(left, top),
(left + BOX[0], top),
hqf_pdf.Cmyk(1.0, 0.0, 0.0, 0.0),
hqf_pdf.Cmyk(0.0, 1.0, 0.0, 0.0),
)
)
radial = document.add_shading(
hqf_pdf.Radial.cmyk(
(right + BOX[0] / 2.0, top + BOX[1] / 2.0, 0.0),
(right + BOX[0] / 2.0, top + BOX[1] / 2.0, BOX[0] / 2.0),
hqf_pdf.Cmyk(0.0, 0.0, 1.0, 0.0),
hqf_pdf.Cmyk(0.0, 0.9, 0.9, 0.2),
).extend(False, True)
)
one = hqf_pdf.Separation.ink("Corporate Blue", hqf_pdf.Cmyk(*BLUE))
one_label = counted(words.inks[2], one)
tint = document.add_shading(
hqf_pdf.Axial(
(left, bottom),
(left + BOX[0], bottom),
one,
hqf_pdf.Function.exponential((0.0, 1.0), 1.0),
)
)
two = hqf_pdf.DeviceN(
["Corporate Blue", "Corporate Gold"], hqf_pdf.DeviceSpace.Cmyk, mix_two_inks()
)
two_label = counted(words.inks[3], two)
pair = document.add_shading(
hqf_pdf.Axial(
(right, bottom),
(right + BOX[0], bottom),
two,
hqf_pdf.Function.exponential(
(0.0, 1.0), 1.0, endpoints=([1.0, 0.0], [0.0, 1.0])
),
)
)
measured = hqf_pdf.Lab(D50)
lab_label = counted(words.lab, measured)
lab = document.add_shading(
hqf_pdf.Axial.through_stops(
(left, lowest),
(left + BOX[0], lowest),
document.add_color_space(measured),
LAB_STOPS,
)
)
content = hqf_pdf.Content()
content.draw_text(font, 18.0, left, 770.0, words.inks_title)
panel(content, font, axial, left, top, counted(words.inks[0], process))
panel(content, font, radial, right, top, words.inks[1])
panel(content, font, tint, left, bottom, one_label)
panel(content, font, pair, right, bottom, two_label)
panel(content, font, lab, left, lowest, lab_label)
return content
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("gradient.pdf", language)).stem)
document = hqf_pdf.Document()
document.set_license(_licence.licensed())
handle = document.add_font(hqf_pdf.Font.from_path(_out.font_path()))
# Left column x, right column x, then the foot of each of the three rows.
left, right, top, middle, bottom = 70.0, 315.0, 560.0, 320.0, 100.0
# A horizontal two-colour gradient across the top-left box.
horizontal = document.add_shading(
hqf_pdf.Axial.rgb(
(left, top),
(left + BOX[0], top),
hqf_pdf.Rgb(0.85, 0.12, 0.12),
hqf_pdf.Rgb(0.12, 0.2, 0.8),
)
)
# A diagonal two-colour gradient across the top-right box.
diagonal = document.add_shading(
hqf_pdf.Axial.rgb(
(right, middle + BOX[1]),
(right + BOX[0], top + BOX[1]),
hqf_pdf.Rgb(0.95, 0.8, 0.1),
hqf_pdf.Rgb(0.1, 0.55, 0.2),
)
)
# A radial gradient in the middle-left box, its outer colour extended so it reaches
# the corners.
radial = document.add_shading(
hqf_pdf.Radial.rgb(
(left + BOX[0] / 2.0, middle + BOX[1] / 2.0, 0.0),
(left + BOX[0] / 2.0, middle + BOX[1] / 2.0, BOX[0] / 2.0),
hqf_pdf.Rgb(1.0, 1.0, 1.0),
hqf_pdf.Rgb(0.1, 0.15, 0.45),
).extend(False, True)
)
# A three-stop gradient in the middle-right box, from a stitched function: red to
# green over the first half, green to blue over the second.
rainbow_function = hqf_pdf.Function.stitching(
(0.0, 1.0),
[
hqf_pdf.Function.exponential(
(0.0, 1.0), 1.0, ([0.85, 0.12, 0.12], [0.12, 0.6, 0.2])
),
hqf_pdf.Function.exponential(
(0.0, 1.0), 1.0, ([0.12, 0.6, 0.2], [0.12, 0.2, 0.8])
),
],
[0.5],
[(0.0, 1.0), (0.0, 1.0)],
)
rainbow = document.add_shading(
hqf_pdf.Axial(
(right, middle),
(right + BOX[0], middle),
hqf_pdf.DeviceSpace.Rgb,
rainbow_function,
)
)
# A checkerboard across the bottom-left box.
board = document.add_shading(checkerboard(left, bottom))
# A radial gradient in the bottom-right box, extended both ways so it would cover
# the whole page, and held to the box by its own bounding box.
held = document.add_shading(
hqf_pdf.Radial.rgb(
(right + BOX[0] / 2.0, bottom + BOX[1] / 2.0, 10.0),
(right + BOX[0] / 2.0, bottom + BOX[1] / 2.0, BOX[1] / 2.0),
hqf_pdf.Rgb(0.95, 0.75, 0.2),
hqf_pdf.Rgb(0.55, 0.1, 0.35),
)
.extend(True, True)
.bounding_box(hqf_pdf.Rect(right, bottom, BOX[0], BOX[1]))
)
content = hqf_pdf.Content()
content.draw_text(handle, 18.0, left, 770.0, words.title)
panel(content, handle, horizontal, left, top, words.horizontal)
panel(content, handle, diagonal, right, top, words.diagonal)
panel(content, handle, radial, left, middle, words.radial)
panel(content, handle, rainbow, right, middle, words.three_stops)
panel(content, handle, board, left, bottom, words.checkerboard)
# No clip: the gradient's bounding box is what keeps it in its panel.
content.draw_shading(held)
content.draw_text(handle, 10.0, right, bottom - 30.0, words.bounded)
page = hqf_pdf.Page.a4()
page.set_content(content)
document.add_page(page)
page = hqf_pdf.Page.a4()
page.set_content(inks_page(document, handle, words))
document.add_page(page)
written = document.write(out)
print(f"wrote {out}: {written} bytes")
if __name__ == "__main__":
main()
|