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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229 | //! The four kinds of PDF function, and what each is good for.
//!
//! A gradient, a spot ink, a transfer curve: each is a number going in and a
//! tuple of numbers coming out, and the file says how. Four panels: a spectrum
//! read off a table of samples, a stepped ramp worked out by a stack program,
//! an ink whose tint transform is a program of its own, and the table and a
//! pair of endpoints stitched end to end. Each program is printed under what it
//! draws.
//!
//! The second page runs every other operator of the calculator language, each
//! in a program of its own that draws a grey ramp, printed under it as the file
//! carries it. The third samples one ramp at every depth a table can hold,
//! fills it in by a cubic rather than a line, reads a table back to front with
//! its outputs narrowed, and joins the three other kinds of function under one
//! range.
//!
//! The words are held in `Words`, once per language, and `HQF_PDF_LANG` picks
//! which set the page is captioned in. The two programs are not language: what
//! is printed under the second and third panels is the very working the file
//! carries, and it is spelled the same way whoever reads the page.
//!
//! Usage: `cargo run --example write_functions -- tmp/functions.pdf [font.ttf]`
//! `HQF_PDF_LANG=fr cargo run --example write_functions --
//! tmp/fonctions.pdf`
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use hqf_pdf::content::Content;
use hqf_pdf::{
Axial, Calculation, ColorSpaceHandle, DeviceSpace, Document, Exponential, Font, FontHandle,
Function, Op, Page, Rgb, SampleDepth, SampleOrder, Sampled, Separation, Shading, ShadingHandle,
Stitching,
};
#[path = "shared/out.rs"]
mod out;
#[path = "shared/licence.rs"]
mod licence;
#[path = "shared/language.rs"]
mod language;
#[path = "shared/failure.rs"]
mod failure;
use language::Language;
/// The font the example draws with when none is given on the command line.
fn default_font() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fonts")
.join("DejaVuSans.ttf")
}
/// The left edge of everything, and how wide a panel runs.
const LEFT: f64 = 70.0;
/// See [`LEFT`].
const WIDTH: f64 = 455.0;
/// How tall a painted bar is.
const BAR: f64 = 74.0;
/// The foot of each of the four panels, down the page.
const SPECTRUM_FOOT: f64 = 632.0;
/// See [`SPECTRUM_FOOT`].
const STEPPED_FOOT: f64 = 476.0;
/// See [`SPECTRUM_FOOT`].
const INK_FOOT: f64 = 310.0;
/// See [`SPECTRUM_FOOT`].
const JOINED_FOOT: f64 = 150.0;
/// The seven colours the spectrum is read off, red round to violet.
const SPECTRUM: &[[f64; 3]] = &[
[0.85, 0.12, 0.12],
[0.95, 0.55, 0.10],
[0.95, 0.85, 0.15],
[0.15, 0.65, 0.25],
[0.10, 0.60, 0.75],
[0.15, 0.20, 0.75],
[0.45, 0.15, 0.60],
];
/// The left edge of each tint swatch, and how wide one runs.
const TINT_X: &[f64] = &[70.0, 135.0, 200.0, 265.0, 330.0, 395.0, 460.0];
/// See [`TINT_X`].
const SWATCH: f64 = 59.0;
/// The tints the ink is shown at, and what each of them is called.
const TINTS: &[(f64, &str)] = &[
(0.1, "10%"),
(0.25, "25%"),
(0.4, "40%"),
(0.55, "55%"),
(0.7, "70%"),
(0.85, "85%"),
(1.0, "100%"),
];
/// The working printed under the stepped ramp, which is the program the file
/// carries rather than anything a language writes.
const STEPPED_PROGRAM: &str = "{ 7 mul cvi dup 6 gt { pop 6 } if 6 div dup 1 exch sub 0.25 }";
/// The working printed under the ink, likewise.
const INK_PROGRAM: &str = "{ dup 0.9 mul exch dup 0.6 mul exch 3 exp 0.4 mul 0 exch }";
/// The top of the first strip of the second page, and how far each strip stands
/// under the one before.
const OPERATOR_TOP: f64 = 720.0;
/// See [`OPERATOR_TOP`].
const OPERATOR_STEP: f64 = 52.0;
/// The five samples the third page's ramp is read off, black to white.
const RAMP: [f64; 5] = [0.0, 0.3, 0.45, 0.8, 1.0];
/// How far each strip of the third page stands under the one before.
const SAMPLE_STEP: f64 = 52.0;
/// The words the page is captioned in, one set per language.
#[derive(Debug)]
struct Words {
/// The title over the page.
title: &'static str,
/// The two lines under the title.
intro: [&'static str; 2],
/// The caption over each of the four panels, and the note under it. The two
/// notes that stand under a program hold only what follows it.
captions: [[&'static str; 2]; 4],
/// The two lines of the closing note.
closing: [&'static str; 2],
/// The second page's title, and the line under it.
operators: [&'static str; 2],
/// The third page's title, and the line under it.
samples: [&'static str; 2],
/// What the three last strips of the third page show.
sample_notes: [&'static str; 3],
}
impl Words {
/// The words the page is captioned in, in `language`.
fn of(language: Language) -> &'static Self {
language::pick(&WORDS, language)
}
/// The note under the stepped ramp: the program the file carries, then what
/// the caption says about it.
fn stepped_note(&self) -> String {
format!("{STEPPED_PROGRAM}{}", self.captions[1][1])
}
/// The note under the ink, likewise.
fn ink_note(&self) -> String {
format!("{INK_PROGRAM}{}", self.captions[2][1])
}
}
/// The page in English.
const ENGLISH: Words = Words {
title: "What a function says a colour does",
intro: [
"A gradient, an ink, a curve: one number goes in and a colour comes out, and the file says \
how.",
"It can say it by naming two ends, by tabulating the answer, or by writing out the working.",
],
captions: [
[
"Read off a table: seven colours, sixteen bits apiece",
"The table holds what the colour is at seven points; between them \
reading software draws the line.",
],
[
"Worked out: a program that cuts the input into bands",
" — reading software runs this.",
],
[
"One ink, shown through a program where the press is not to hand",
" — the black lags, then catches up.",
],
[
"Stitched: the table over the first half, two endpoints over the second",
"A piece written as a stream stands as an object of its own, and the joint points at \
it.",
],
],
closing: [
"A table and a program are both written as streams, which is what lets them hold as much \
as they do.",
"The program is built here as steps, not as text, so what reaches the file is what can be \
written.",
],
operators: [
"The rest of the calculator, one operator a strip",
"Each strip is a grey ramp worked out by the program printed under it.",
],
samples: [
"One ramp of five samples, at every depth a table holds",
"The fewer bits a sample takes, the fewer greys it can say: one bit says black or white.",
],
sample_notes: [
"Filled in by a cubic rather than a straight line",
"Read back to front, its outputs narrowed to 0.2 to 0.8",
"Three kinds of function joined end to end, under a range of 0.2 to 0.8",
],
};
/// The page in French.
const FRENCH: Words = Words {
title: "Comment une fonction décrit une couleur",
intro: [
"Un dégradé, une encre, une courbe : un nombre entre, une couleur sort, et le \
fichier dit comment.",
"Il peut le dire en nommant deux extrémités, en tabulant la réponse, ou en écrivant le \
calcul.",
],
captions: [
[
"Lu dans une table : sept couleurs, seize bits chacune",
"La table dit la couleur en sept points ; entre eux, le logiciel de lecture \
trace la droite.",
],
[
"Calculé : un programme qui découpe l’entrée en bandes",
" — le logiciel de lecture exécute ceci.",
],
[
"Une encre, rendue par un programme en l’absence de presse",
" — le noir tarde, puis se rattrape.",
],
[
"Assemblé : la table sur la première moitié, deux extrémités sur la seconde",
"Un morceau écrit en flux devient un objet distinct, auquel l’assemblage renvoie.",
],
],
closing: [
"Une table et un programme s’écrivent tous deux comme des flux, ce qui leur \
permet d’en contenir autant.",
"Le programme est construit ici par étapes, non en texte : n’arrive au fichier \
que ce qui peut s’y écrire.",
],
operators: [
"Le reste de la calculatrice, un opérateur par bande",
"Chaque bande est un dégradé de gris que calcule le programme imprimé dessous.",
],
samples: [
"Un dégradé de cinq échantillons, à chaque profondeur de table",
"Moins un échantillon a de bits, moins il offre de gris : un seul bit donne noir \
ou blanc.",
],
sample_notes: [
"Interpolé par une cubique plutôt que par une droite",
"Lu à rebours, ses sorties ramenées entre 0,2 et 0,8",
"Trois sortes de fonctions mises bout à bout, bornées entre 0,2 et 0,8",
],
};
/// The page in Dutch.
const DUTCH: Words = Words {
title: "Wat een functie zegt dat een kleur doet",
intro: [
"Een verloop, een inkt, een curve: er gaat een getal in en er komt een kleur uit, en het bestand zegt hoe.",
"Dat kan met twee uiteinden, met het antwoord in een tabel of met de uitgeschreven berekening.",
],
captions: [
[
"Uit een tabel gelezen: zeven kleuren, zestien bits per stuk",
"De tabel bevat de kleur op zeven punten; daartussen trekt de leessoftware de lijn.",
],
[
"Berekend: een programma dat de invoer in banden verdeelt",
" — dit voert de leessoftware uit.",
],
[
"Eén inkt, getoond via een programma wanneer er geen pers is",
" — het zwart blijft achter en haalt dan in.",
],
[
"Aan elkaar gestikt: de tabel over de eerste helft, twee eindpunten over de tweede",
"Een als stroom geschreven stuk is een eigen object, en de naad wijst ernaar.",
],
],
closing: [
"Een tabel en een programma worden allebei als stroom geschreven, en daardoor kunnen ze zoveel bevatten.",
"Het programma bestaat hier uit stappen, niet uit tekst: in het bestand komt wat geschreven kan worden.",
],
operators: [
"De rest van de rekenmachine, één operator per strook",
"Elke strook is een grijsverloop berekend door het programma dat eronder staat.",
],
samples: [
"Vijf monsters, op elke diepte die een tabel toelaat",
"Hoe minder bits per monster, hoe minder grijstinten: één bit geeft alleen zwart of wit.",
],
sample_notes: [
"Ingevuld met een kubische curve in plaats van een rechte lijn",
"Achterstevoren gelezen, met de uitvoer beperkt tot tussen 0,2 en 0,8",
"Drie soorten functie achter elkaar gezet, binnen een bereik van 0,2 tot 0,8",
],
};
/// The page in Portuguese.
const PORTUGUESE: Words = Words {
title: "O que uma função diz que uma cor faz",
intro: [
"Um degradé, uma tinta, uma curva: entra um número e sai uma cor, e o ficheiro diz como.",
"Pode dizê-lo nomeando dois extremos, tabelando a resposta ou escrevendo o cálculo.",
],
captions: [
[
"Lido de uma tabela: sete cores, dezasseis bits cada uma",
"A tabela guarda a cor em sete pontos; entre eles, o programa de leitura traça a linha.",
],
[
"Calculado: um programa que corta a entrada em faixas",
" — é o programa de leitura que o executa.",
],
[
"Uma tinta, mostrada através de um programa quando a gráfica não está à mão",
" — o preto atrasa-se e depois recupera.",
],
[
"Cosido: a tabela na primeira metade, dois extremos na segunda",
"Uma peça escrita como fluxo é um objeto próprio, e a junção aponta para ele.",
],
],
closing: [
"Uma tabela e um programa escrevem-se ambos como fluxos, e é isso que lhes permite guardar tanto.",
"O programa constrói-se aqui como passos, não como texto: o que chega ao ficheiro é o que pode ser escrito.",
],
operators: [
"O resto da calculadora, um operador por faixa",
"Cada faixa é uma rampa de cinzentos calculada pelo programa impresso por baixo.",
],
samples: [
"Cinco amostras, em cada profundidade que uma tabela admite",
"Quanto menos bits uma amostra ocupa, menos cinzentos pode dizer: um bit diz preto ou branco.",
],
sample_notes: [
"Preenchido por uma cúbica em vez de uma reta",
"Lido de trás para a frente, com as saídas reduzidas de 0,2 a 0,8",
"Três tipos de função unidos em sequência, num intervalo de 0,2 a 0,8",
],
};
/// The page in Italian.
const ITALIAN: Words = Words {
title: "Ciò che una funzione dice che fa un colore",
intro: [
"Un gradiente, un inchiostro, una curva: entra un numero ed esce un colore, e il file dice come.",
"Può dirlo nominando due estremi, tabulando la risposta o scrivendo il calcolo.",
],
captions: [
[
"Letto da una tabella: sette colori, sedici bit ciascuno",
"La tabella tiene il colore in sette punti; tra questi il programma di lettura traccia la linea.",
],
[
"Calcolato: un programma che taglia l’ingresso in fasce",
" — questo lo esegue il programma di lettura.",
],
[
"Un inchiostro, mostrato con un programma quando la macchina da stampa non è a portata",
" — il nero resta indietro, poi recupera.",
],
[
"Cucito: la tabella sulla prima metà, due estremi sulla seconda",
"Un pezzo scritto come flusso è un oggetto a sé, e la giunzione rimanda a esso.",
],
],
closing: [
"Una tabella e un programma si scrivono entrambi come flussi, ed è questo che permette loro di contenere tanto.",
"Il programma qui si costruisce a passi, non come testo, così ciò che arriva al file è ciò che si può scrivere.",
],
operators: [
"Il resto della calcolatrice, un operatore per striscia",
"Ogni striscia è una scala di grigi calcolata dal programma stampato sotto.",
],
samples: [
"Cinque campioni, a ogni profondità che una tabella ammette",
"Meno bit occupa un campione, meno grigi può dire: un bit dice nero o bianco.",
],
sample_notes: [
"Riempito con una cubica anziché con una retta",
"Letto al contrario, con le uscite ristrette da 0,2 a 0,8",
"Tre tipi di funzione uniti in fila, su un intervallo da 0,2 a 0,8",
],
};
/// The page in Spanish.
const SPANISH: Words = Words {
title: "Lo que una función dice que hace un color",
intro: [
"Un degradado, una tinta, una curva: entra un número y sale un color, y el archivo dice cómo.",
"Puede decirlo nombrando dos extremos, tabulando la respuesta o escribiendo el cálculo.",
],
captions: [
[
"Leído de una tabla: siete colores, dieciséis bits cada uno",
"La tabla guarda el color en siete puntos; entre ellos, el programa de lectura traza la línea.",
],
[
"Calculado: un programa que corta la entrada en bandas",
" — esto lo ejecuta el programa de lectura.",
],
[
"Una tinta, mostrada con un programa cuando la imprenta no está a mano",
" — el negro se retrasa y luego se pone al día.",
],
[
"Cosido: la tabla en la primera mitad, dos extremos en la segunda",
"Una pieza escrita como flujo es un objeto propio, y la unión apunta a él.",
],
],
closing: [
"Una tabla y un programa se escriben ambos como flujos, y por eso pueden guardar tanto.",
"El programa se construye aquí con pasos, no con texto: lo que llega al archivo es lo que puede escribirse.",
],
operators: [
"El resto de la calculadora, un operador por franja",
"Cada franja es una rampa de grises calculada por el programa impreso debajo.",
],
samples: [
"Cinco muestras, en cada profundidad que admite una tabla",
"Cuantos menos bits ocupa una muestra, menos grises puede decir: un bit dice negro o blanco.",
],
sample_notes: [
"Rellenado con una cúbica en vez de una recta",
"Leído del revés, con sus salidas reducidas al intervalo de 0,2 a 0,8",
"Tres tipos de función unidos uno tras otro, en un rango de 0,2 a 0,8",
],
};
/// The page in German.
const GERMAN: Words = Words {
title: "Was eine Funktion über eine Farbe sagt",
intro: [
"Verlauf, Farbe, Kurve: Eine Zahl geht hinein, eine Farbe heraus, und die Datei sagt, wie.",
"Sie sagt es mit zwei Enden, mit einer Tabelle der Antworten oder mit dem Rechenweg.",
],
captions: [
[
"Aus einer Tabelle gelesen: sieben Farben, je sechzehn Bit",
"Die Tabelle enthält die Farbe an sieben Punkten; dazwischen zieht die Lesesoftware die Linie.",
],
[
"Ausgerechnet: ein Programm, das die Eingabe in Bänder teilt",
" — die Lesesoftware führt dies aus.",
],
[
"Eine Farbe, durch ein Programm gezeigt, wo die Druckmaschine nicht zur Hand ist",
" — das Schwarz hinkt nach und holt dann auf.",
],
[
"Zusammengesetzt: die Tabelle über die erste Hälfte, zwei Endpunkte über die zweite",
"Ein als Datenstrom geschriebenes Stück ist ein eigenes Objekt, und die Naht verweist darauf.",
],
],
closing: [
"Tabelle und Programm sind beide Datenströme, darum fassen sie so viel.",
"Das Programm wird aus Schritten gebaut, nicht aus Text: In die Datei kommt nur Schreibbares.",
],
operators: [
"Die übrigen Operatoren des Rechners, einer je Streifen",
"Jeder Streifen ist ein Graukeil, berechnet vom Programm, das darunter gedruckt ist.",
],
samples: [
"Ein Keil aus fünf Werten, in jeder Tiefe, die eine Tabelle fasst",
"Je weniger Bit ein Wert hat, desto weniger Grautöne: Ein Bit sagt schwarz oder weiß.",
],
sample_notes: [
"Mit einer kubischen Kurve statt einer Geraden gefüllt",
"Rückwärts gelesen, die Ausgaben auf 0,2 bis 0,8 verengt",
"Drei Arten von Funktion aneinandergefügt, in einem Bereich von 0,2 bis 0,8",
],
};
/// Every language the example is written in. A language is added by writing its
/// own set of words and naming it here.
static WORDS: [(Language, &Words); 7] = [
(Language::English, &ENGLISH),
(Language::French, &FRENCH),
(Language::German, &GERMAN),
(Language::Spanish, &SPANISH),
(Language::Italian, &ITALIAN),
(Language::Portuguese, &PORTUGUESE),
(Language::Dutch, &DUTCH),
];
/// Draws one line of text with its baseline at `(x, y)`.
fn text(
content: &mut Content,
font: &FontHandle,
size: f64,
x: f64,
y: f64,
line: &str,
) -> Result<(), hqf_pdf::Error> {
content.begin_text();
content.set_font(font, size)?;
content.text_origin(x, y)?;
content.show_glyphs(&font.glyphs(line));
content.end_text();
Ok(())
}
/// Draws a caption over a panel whose foot is at `base`, and the note that goes
/// under it.
fn caption(
content: &mut Content,
font: &FontHandle,
base: f64,
heading: &str,
note: &str,
) -> Result<(), hqf_pdf::Error> {
content.save_state();
content.set_fill(Rgb::gray(0.2))?;
text(content, font, 11.0, LEFT, base + BAR + 10.0, heading)?;
content.set_fill(Rgb::gray(0.4))?;
text(content, font, 8.5, LEFT, base - 26.0, note)?;
content.restore_state();
Ok(())
}
/// Paints a gradient across the width of the page, its foot at `y`.
fn bar(content: &mut Content, shading: &ShadingHandle, y: f64) -> Result<(), hqf_pdf::Error> {
content.save_state();
content.rect(LEFT, y, WIDTH, BAR)?.clip().end_path();
content.draw_shading(shading);
content.restore_state();
Ok(())
}
/// Draws the ink at every tint, each swatch labelled with how much goes down.
fn tint_ramp(
content: &mut Content,
font: &FontHandle,
ink: &ColorSpaceHandle,
y: f64,
) -> Result<(), hqf_pdf::Error> {
for (x, (tint, name)) in TINT_X.iter().zip(TINTS) {
content.save_state();
content.set_fill_space(ink);
content.set_fill_components(&[*tint])?;
content.rect(*x, y, SWATCH, BAR)?.fill();
content.restore_state();
content.save_state();
content.set_fill(Rgb::gray(0.35))?;
text(content, font, 7.5, *x, y - 11.0, name)?;
content.restore_state();
}
Ok(())
}
/// The table the spectrum is read off: every colour of [`SPECTRUM`], red first.
fn spectrum_table() -> Vec<f64> {
SPECTRUM.iter().flatten().copied().collect()
}
/// The program that steps a ramp: the input is cut into seven bands, the last
/// of which takes the input's own top end, and the band runs one output up
/// while it runs another down.
fn stepped() -> Vec<Op> {
vec![
Op::Integer(7),
Op::Multiply,
Op::ToInteger,
Op::Duplicate,
Op::Integer(6),
Op::Greater,
Op::If(vec![Op::Pop, Op::Integer(6)]),
Op::Integer(6),
Op::Divide,
Op::Duplicate,
Op::Integer(1),
Op::Exchange,
Op::Subtract,
Op::Real(0.25),
]
}
/// The program an ink is shown through: the tint runs the cyan and the magenta
/// plates straight up, leaves the yellow one empty, and lets the black one lag
/// behind until the ink is nearly solid.
fn ink_transform() -> Vec<Op> {
vec![
Op::Duplicate,
Op::Real(0.9),
Op::Multiply,
Op::Exchange,
Op::Duplicate,
Op::Real(0.6),
Op::Multiply,
Op::Exchange,
Op::Integer(3),
Op::Power,
Op::Real(0.4),
Op::Multiply,
Op::Integer(0),
Op::Exchange,
]
}
/// Draws the page: the title, the four panels and what is said under them.
fn draw(
content: &mut Content,
font: &FontHandle,
words: &Words,
gradients: (&ShadingHandle, &ShadingHandle, &ShadingHandle),
ink: &ColorSpaceHandle,
) -> Result<(), hqf_pdf::Error> {
let (spectrum, steps, joined) = gradients;
text(content, font, 16.0, LEFT, 786.0, words.title)?;
content.save_state();
content.set_fill(Rgb::gray(0.35))?;
text(content, font, 10.0, LEFT, 767.0, words.intro[0])?;
text(content, font, 10.0, LEFT, 753.0, words.intro[1])?;
content.restore_state();
bar(content, spectrum, SPECTRUM_FOOT)?;
caption(
content,
font,
SPECTRUM_FOOT,
words.captions[0][0],
words.captions[0][1],
)?;
bar(content, steps, STEPPED_FOOT)?;
caption(
content,
font,
STEPPED_FOOT,
words.captions[1][0],
&words.stepped_note(),
)?;
tint_ramp(content, font, ink, INK_FOOT)?;
caption(
content,
font,
INK_FOOT,
words.captions[2][0],
&words.ink_note(),
)?;
bar(content, joined, JOINED_FOOT)?;
caption(
content,
font,
JOINED_FOOT,
words.captions[3][0],
words.captions[3][1],
)?;
content.save_state();
content.set_fill(Rgb::gray(0.45))?;
text(content, font, 9.0, LEFT, 96.0, words.closing[0])?;
text(content, font, 9.0, LEFT, 82.0, words.closing[1])?;
content.restore_state();
Ok(())
}
/// The programs of the second page: every operator of the calculator language
/// the first page leaves out, each turning the position along a strip into a
/// grey from black to white.
#[allow(
clippy::too_many_lines,
reason = "the list holds one program per operator, each as the file writes it"
)]
fn operator_programs() -> Vec<Vec<Op>> {
vec![
vec![
Op::Real(0.5),
Op::Subtract,
Op::Abs,
Op::Integer(2),
Op::Multiply,
],
vec![
Op::Integer(10),
Op::Multiply,
Op::ToInteger,
Op::Integer(3),
Op::IntegerDivide,
Op::Integer(3),
Op::Divide,
],
vec![Op::Negate, Op::Integer(1), Op::Add],
vec![
Op::Integer(4),
Op::Multiply,
Op::Round,
Op::Integer(4),
Op::Divide,
],
vec![
Op::Integer(4),
Op::Multiply,
Op::Ceiling,
Op::Integer(4),
Op::Divide,
],
vec![
Op::Integer(4),
Op::Multiply,
Op::Truncate,
Op::Integer(4),
Op::Divide,
],
vec![Op::Sqrt],
vec![
Op::Integer(360),
Op::Multiply,
Op::Sin,
Op::Integer(1),
Op::Add,
Op::Integer(2),
Op::Divide,
],
vec![
Op::Integer(360),
Op::Multiply,
Op::Cos,
Op::Integer(1),
Op::Add,
Op::Integer(2),
Op::Divide,
],
vec![Op::Integer(1), Op::Atan, Op::Integer(45), Op::Divide],
vec![
Op::Real(1.718_282),
Op::Multiply,
Op::Integer(1),
Op::Add,
Op::NaturalLog,
],
vec![
Op::Integer(9),
Op::Multiply,
Op::Integer(1),
Op::Add,
Op::Log10,
],
vec![
Op::Integer(4),
Op::Multiply,
Op::ToInteger,
Op::ToReal,
Op::Integer(4),
Op::Divide,
],
vec![
Op::Integer(15),
Op::Multiply,
Op::ToInteger,
Op::Integer(12),
Op::And,
Op::Integer(15),
Op::Divide,
],
vec![
Op::Integer(15),
Op::Multiply,
Op::ToInteger,
Op::Integer(3),
Op::Or,
Op::Integer(15),
Op::Divide,
],
vec![
Op::Integer(15),
Op::Multiply,
Op::ToInteger,
Op::Integer(9),
Op::Xor,
Op::Integer(15),
Op::Divide,
],
vec![
Op::Integer(15),
Op::Multiply,
Op::ToInteger,
Op::Not,
Op::Integer(15),
Op::And,
Op::Integer(15),
Op::Divide,
],
vec![
Op::Integer(4),
Op::Multiply,
Op::ToInteger,
Op::Integer(1),
Op::Exchange,
Op::Shift,
Op::Integer(16),
Op::Divide,
],
vec![
Op::Integer(4),
Op::Multiply,
Op::ToInteger,
Op::Integer(2),
Op::Equal,
Op::IfElse(vec![Op::Integer(1)], vec![Op::Integer(0)]),
],
vec![
Op::Real(0.5),
Op::Less,
Op::IfElse(vec![Op::Integer(0)], vec![Op::Integer(1)]),
],
vec![
Op::Real(0.25),
Op::LessOrEqual,
Op::IfElse(vec![Op::Real(0.2)], vec![Op::Real(0.8)]),
],
vec![
Op::Real(0.75),
Op::GreaterOrEqual,
Op::IfElse(vec![Op::Integer(1)], vec![Op::Real(0.4)]),
],
vec![
Op::True,
Op::IfElse(
vec![Op::Integer(1), Op::Exchange, Op::Subtract],
vec![Op::Real(0.5), Op::Multiply],
),
],
vec![
Op::False,
Op::IfElse(
vec![Op::Integer(1), Op::Exchange, Op::Subtract],
vec![Op::Real(0.5), Op::Multiply],
),
],
]
}
/// A grey strip `width` wide and `height` tall, its foot at `(x, y)`, painted
/// by `function` from its left edge to its right.
fn strip(
doc: &mut Document,
content: &mut Content,
at: (f64, f64),
size: (f64, f64),
function: impl Into<Function>,
) -> Result<(), hqf_pdf::Error> {
let (x, y) = at;
let (width, height) = size;
let shading = doc.add_shading(&Shading::from(Axial::new(
(x, y),
(x + width, y),
DeviceSpace::Gray,
function,
)?))?;
content.save_state();
content.rect(x, y, width, height)?.clip().end_path();
content.draw_shading(&shading);
content.restore_state();
content.save_state();
content.set_stroke(Rgb::gray(0.75))?;
content.set_line_width(0.5)?;
content.rect(x, y, width, height)?.stroke();
content.restore_state();
Ok(())
}
/// Draws the second page: every other operator, each in a program of its own,
/// two columns of strips with the program printed under each.
fn operators_page(
doc: &mut Document,
font: &FontHandle,
words: &Words,
) -> Result<Content, hqf_pdf::Error> {
let mut content = Content::new();
text(&mut content, font, 16.0, LEFT, 786.0, words.operators[0])?;
content.save_state();
content.set_fill(Rgb::gray(0.35))?;
text(&mut content, font, 10.0, LEFT, 767.0, words.operators[1])?;
content.restore_state();
let programs = operator_programs();
let per_column = programs.len().div_ceil(2);
for (place, body) in programs.into_iter().enumerate() {
let x = if place < per_column {
LEFT
} else {
LEFT + 235.0
};
let row =
u32::try_from(place % per_column).map_err(|_| hqf_pdf::Error::ImpossibleGeometry {
what: "a row number beyond counting",
})?;
let y = f64::from(row).mul_add(-OPERATOR_STEP, OPERATOR_TOP);
let calculation = Calculation::new([[0.0, 1.0]], [[0.0, 1.0]], body);
let program = calculation.program()?;
strip(
doc,
&mut content,
(x, y),
(220.0, 16.0),
Function::Calculation(calculation),
)?;
content.save_state();
content.set_fill(Rgb::gray(0.3))?;
text(&mut content, font, 6.5, x, y - 10.0, &program)?;
content.restore_state();
}
Ok(content)
}
/// Draws the third page: one ramp sampled at every depth a table holds, then
/// filled in by a cubic, read back to front, and a joint clipped to a range.
fn samples_page(
doc: &mut Document,
font: &FontHandle,
words: &Words,
) -> Result<Content, hqf_pdf::Error> {
let mut content = Content::new();
text(&mut content, font, 16.0, LEFT, 786.0, words.samples[0])?;
content.save_state();
content.set_fill(Rgb::gray(0.35))?;
text(&mut content, font, 10.0, LEFT, 767.0, words.samples[1])?;
content.restore_state();
let ramp = || Sampled::new([[0.0, 1.0]], [[0.0, 1.0]], [5], RAMP.to_vec());
let depths = [
("BitsPerSample 1", SampleDepth::Bits1),
("BitsPerSample 2", SampleDepth::Bits2),
("BitsPerSample 4", SampleDepth::Bits4),
("BitsPerSample 8", SampleDepth::Bits8),
("BitsPerSample 12", SampleDepth::Bits12),
("BitsPerSample 16", SampleDepth::Bits16),
("BitsPerSample 24", SampleDepth::Bits24),
("BitsPerSample 32", SampleDepth::Bits32),
];
let mut y = 720.0;
for (label, depth) in depths {
strip(
doc,
&mut content,
(LEFT, y),
(WIDTH, 22.0),
Function::Sampled(ramp()?.depth(depth)),
)?;
content.save_state();
content.set_fill(Rgb::gray(0.3))?;
text(&mut content, font, 7.5, LEFT, y - 11.0, label)?;
content.restore_state();
y -= SAMPLE_STEP;
}
// The same five samples filled in by a cubic, then read back to front: the
// input runs over the table from its last point to its first, and the
// outputs are narrowed to the middle of the grey.
let cubic = ramp()?.order(SampleOrder::Cubic);
let reversed = ramp()?
.order(SampleOrder::Linear)
.encode(vec![[4.0, 0.0]])
.decode(vec![[0.2, 0.8]]);
// A joint of the three other kinds, under a range that keeps its outputs to
// the middle of the grey.
let joint = Stitching::new(
[0.0, 1.0],
vec![
Function::Exponential(Exponential::new([0.0, 1.0], 2.0)),
Function::Calculation(Calculation::new(
[[0.0, 1.0]],
[[0.0, 1.0]],
vec![Op::Real(0.5), Op::Multiply, Op::Real(0.5), Op::Add],
)),
Function::Sampled(ramp()?),
],
vec![1.0 / 3.0, 2.0 / 3.0],
vec![[0.0, 1.0], [0.0, 1.0], [0.0, 1.0]],
)
.range(vec![[0.2, 0.8]]);
let shown = [
Function::Sampled(cubic),
Function::Sampled(reversed),
Function::Stitching(joint),
];
for (function, note) in shown.into_iter().zip(words.sample_notes) {
strip(doc, &mut content, (LEFT, y), (WIDTH, 22.0), function)?;
content.save_state();
content.set_fill(Rgb::gray(0.3))?;
text(&mut content, font, 7.5, LEFT, y - 11.0, note)?;
content.restore_state();
y -= SAMPLE_STEP;
}
Ok(content)
}
fn main() -> std::process::ExitCode {
failure::reported(run())
}
fn run() -> Result<(), Box<dyn std::error::Error>> {
let language = Language::from_environment()?;
let words = Words::of(language);
let mut args = env::args().skip(1);
// A named file is written as named; the default one carries the language,
// so the two languages do not overwrite each other in `tmp/`.
let out = args
.next()
.unwrap_or_else(|| language.file_name(&out::default_path("functions")));
let font_path = args.next().map_or_else(default_font, PathBuf::from);
let mut doc = Document::new();
doc.set_license(licence::licensed());
let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);
// A spectrum no pair of endpoints could describe: seven colours on a grid,
// and reading software draws the line between one point and the next.
let points = u32::try_from(SPECTRUM.len())?;
let table = || {
Sampled::new(
[[0.0, 1.0]],
[[0.0, 1.0], [0.0, 1.0], [0.0, 1.0]],
[points],
spectrum_table(),
)
.map(|table| table.depth(SampleDepth::Bits16))
};
let spectrum = doc.add_shading(&Shading::from(Axial::new(
(LEFT, SPECTRUM_FOOT),
(LEFT + WIDTH, SPECTRUM_FOOT),
DeviceSpace::Rgb,
table()?,
)?))?;
// A ramp with corners in it: the program cuts the input into bands, which
// no interpolation between endpoints can do.
let bands = Calculation::new([[0.0, 1.0]], [[0.0, 1.0]; 3], stepped());
let steps = doc.add_shading(&Shading::from(Axial::new(
(LEFT, STEPPED_FOOT),
(LEFT + WIDTH, STEPPED_FOOT),
DeviceSpace::Rgb,
bands,
)?))?;
let ink = doc.add_color_space(Separation::new(
"Corporate Blue",
DeviceSpace::Cmyk,
Calculation::new([[0.0, 1.0]], [[0.0, 1.0]; 4], ink_transform()),
));
// The table over the first half of the run, and a fade into the dark over
// the second: a joint holds pieces of whatever kind, and the one that is a
// stream stands as an object of its own.
let joined = doc.add_shading(&Shading::from(Axial::new(
(LEFT, JOINED_FOOT),
(LEFT + WIDTH, JOINED_FOOT),
DeviceSpace::Rgb,
Stitching::new(
[0.0, 1.0],
vec![
Function::from(table()?),
Function::from(
Exponential::new([0.0, 1.0], 1.0)
.endpoints(vec![0.45, 0.15, 0.60], vec![0.06, 0.05, 0.12]),
),
],
vec![0.5],
vec![[0.0, 1.0], [0.0, 1.0]],
),
)?))?;
let mut content = Content::new();
draw(
&mut content,
&font,
words,
(&spectrum, &steps, &joined),
&ink,
)?;
let mut page = Page::a4();
page.content = content.into_bytes();
doc.add_page(page)?;
let mut page = Page::a4();
page.content = operators_page(&mut doc, &font, words)?.into_bytes();
doc.add_page(page)?;
let mut page = Page::a4();
page.content = samples_page(&mut doc, &font, words)?.into_bytes();
doc.add_page(page)?;
let bytes = doc.to_bytes()?;
if let Some(parent) = Path::new(&out).parent() {
fs::create_dir_all(parent)?;
}
fs::write(&out, &bytes)?;
println!(
"wrote {out}: {} bytes, a table of {} colours, two programs and a joint",
bytes.len(),
SPECTRUM.len()
);
Ok(())
}
#[cfg(test)]
mod tests {
use hqf_pdf::{Document, Font};
use super::{LEFT, SPECTRUM, TINTS, WORDS, default_font, language, operator_programs};
use hqf_pdf::Calculation;
/// The lines two languages are allowed to write the same way. Every line
/// here is a title, a caption or a note, and no two languages write one
/// alike; the two programs are not in `Words` at all.
const SPARED: [&str; 0] = [];
/// A4's width, and the room a line of the page has: nothing on it is broken
/// to a measure, so a line only has to stay on the paper.
const PAGE_WIDTH: f64 = 595.276;
/// See [`PAGE_WIDTH`].
const PAPER: f64 = PAGE_WIDTH - LEFT;
/// How many colours the table is read off, and how many tints the ink is
/// shown at: the first caption spells the one out in words, and no language
/// works either of them out from the page.
const POINTS: usize = 7;
#[test]
fn every_language_draws_the_page_in_its_own_words() {
let untranslated = language::untranslated_lines(&WORDS, &SPARED);
assert!(
untranslated.is_empty(),
"the page says these in more than one language: {untranslated:?}"
);
}
/// Nothing on the page is broken to a width: a caption or a note longer
/// than the paper runs off the sheet, and the two notes that carry a
/// program are the longest lines the page draws.
#[test]
fn every_language_writes_lines_no_wider_than_the_paper() {
let mut doc = Document::new();
let font = Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
.expect("the committed font parses");
let text = doc.add_font(font);
for (named, words) in WORDS {
let code = named.code();
let lines = std::iter::once((16.0, words.title.to_owned()))
.chain(words.intro.map(|line| (10.0, line.to_owned())))
.chain(words.captions.map(|caption| (11.0, caption[0].to_owned())))
.chain([
(8.5, words.captions[0][1].to_owned()),
(8.5, words.stepped_note()),
(8.5, words.ink_note()),
(8.5, words.captions[3][1].to_owned()),
])
.chain(words.closing.map(|line| (9.0, line.to_owned())));
for (size, line) in lines {
let measured = text.measure(&line, size);
assert!(
measured <= PAPER,
"the {code} page draws {line:?} over {measured:.1} points, \
and the paper leaves {PAPER:.1}"
);
}
}
}
/// A program printed under a strip of the second page's first column must
/// stop short of the second column, 235 points to the right.
#[test]
fn every_program_fits_under_its_strip() {
let mut doc = Document::new();
let font = Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
.expect("the committed font parses");
let text = doc.add_font(font);
for body in operator_programs() {
let program = Calculation::new([[0.0, 1.0]], [[0.0, 1.0]], body)
.program()
.expect("the program writes");
let measured = text.measure(&program, 6.5);
assert!(
measured <= 230.0,
"{program} runs over {measured:.1} points"
);
}
}
/// The titles and notes of the second and third pages stay on the paper.
#[test]
fn the_other_pages_write_lines_no_wider_than_the_paper() {
let mut doc = Document::new();
let font = Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
.expect("the committed font parses");
let text = doc.add_font(font);
for (_, words) in WORDS {
let lines = [
(16.0, words.operators[0]),
(10.0, words.operators[1]),
(16.0, words.samples[0]),
(10.0, words.samples[1]),
]
.into_iter()
.chain(words.sample_notes.map(|note| (7.5, note)));
for (size, line) in lines {
let measured = text.measure(line, size);
assert!(measured <= PAPER, "{line:?} runs over {measured:.1} points");
}
}
}
/// The first caption counts the colours of the table in words, which no
/// language reads off the page, and the ink is shown at one tint per
/// colour: a point added or dropped leaves every language saying a number
/// the page no longer holds.
#[test]
fn the_table_holds_the_colours_the_first_caption_counts() {
assert_eq!(SPECTRUM.len(), POINTS);
assert_eq!(TINTS.len(), POINTS);
}
}
|