Repository navigation
Expand file tree
/
Copy pathdecode_figures.cs
More file actions
1744 lines (1644 loc) · 87.3 KB
/
Copy pathdecode_figures.cs
File metadata and controls
1744 lines (1644 loc) · 87.3 KB
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
#:sdk Microsoft.NET.Sdk
#:property TargetFramework=net10.0
#:property Nullable=enable
#:project ../src/FeatherQR/FeatherQR.csproj
using System.Globalization;
using System.Text;
using FeatherQR;
// Draws the decode figures of the design records, one folder per symbology: a strip of the main path's
// stages on a clean symbol, and one figure per input class the image decoder reads.
//
// dotnet run tools/decode_figures.cs -- .github/docs/images
// dotnet run tools/decode_figures.cs -- <directory> --preview also a page of every figure, light and dark
//
// Each input class is also rendered to pixels and decoded through the public API, and the run fails
// unless it decodes. The figures carry pictures and labels only. Their text is in the symbology's
// design record (.github/docs/specs/*-decoder.md), whose numbered notes match the numbers on the boxes.
// A box is green when, without its stage, the input would not read, or would read only after more grids
// fail than with it. A grid is one sampling, and its transposed, coverage and module-space reads are the same grid.
// The boxes follow the image-level outline in the symbology's spec-to-code map.
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
var root = args.FirstOrDefault(a => !a.StartsWith("--", StringComparison.Ordinal)) ?? ".";
var preview = args.Contains("--preview");
var qrDir = Path.Combine(root, "standardqr");
var microDir = Path.Combine(root, "microqr");
var rmqrDir = Path.Combine(root, "rmqr");
Directory.CreateDirectory(qrDir);
Directory.CreateDirectory(microDir);
Directory.CreateDirectory(rmqrDir);
const string Payload = "FeatherQR decoder";
var v2 = Matrix(QRCodeGenerator.Create(Payload, QREccLevel.M, new QRCodeGeneratorOptions { Version = QRVersionRange.Exactly(2), QuietZoneSize = 0 }));
const string MeshPayload = "FeatherQR decoder, a version 14 symbol for the mesh figure";
var v14 = Matrix(QRCodeGenerator.Create(MeshPayload, QREccLevel.M, new QRCodeGeneratorOptions { Version = QRVersionRange.Exactly(14), QuietZoneSize = 0 }));
// Its bottom-right alignment pattern painted over, so nothing anchors the four-point transform's fourth corner
for (var r = 73 - 9; r <= 73 - 5; r++)
for (var c = 73 - 9; c <= 73 - 5; c++)
v14[r, c] = false;
// Data modules read the wrong way in the damaged figure
(int R, int C)[] flips = [(10, 11), (12, 14), (14, 9), (15, 13), (11, 19), (19, 10), (21, 13), (13, 21)];
var damaged = (bool[,])v2.Clone();
foreach (var (r, c) in flips)
damaged[r, c] = !damaged[r, c];
// Every input class, rendered and decoded
var failures = new List<string>();
void Check(string name, bool[,] m, string payload, Func<double, double, double, H> shape, int size, int supersample, Func<double, double, double>? light = null, bool invert = false, bool blur = false, bool expectCorrections = false, double spread = 0)
{
var map = shape(0, 0, size);
var luminance = Render(m, map, size, size, supersample, light, invert, blur, spread);
var ok = QRCodeDecoder.TryDecodeImage(luminance, size, size, out var text, out var info);
var corrected = info.ErrorsCorrected;
var pass = ok && text == payload && (!expectCorrections || corrected > 0);
Console.WriteLine($"{(pass ? "ok " : "FAIL")} {name}: {size}x{size} px, {info.Status}, corrected {corrected}");
if (!pass)
failures.Add(name);
}
Check("clean", v2, Payload, (x, y, s) => Square(25, x, y, s), 33 * 4, 1);
Check("rotated and mirrored", Transposed(v2), Payload, (x, y, s) => Rotated(25, x, y, s, 30), 180, 4);
Check("keystone", v2, Payload, (x, y, s) => Keystone(25, x, y, s, 0.25), 150, 4);
Check("grey edges and wrong modules", damaged, Payload, (x, y, s) => Square(25, x, y, s), 109, 4, blur: true, expectCorrections: true);
// Thin rings: every dark edge moved inward by ThinSpread of a module
const double ThinTurn = 11, ThinSpread = -0.18;
const int ThinPx = 155;
Check("thin rings", v2, Payload, (x, y, s) => Rotated(25, x, y, s, ThinTurn), ThinPx, 4, spread: ThinSpread);
// The figure says the row scan finds each finder on a row that reads 1:1:3:1:1, and that the lines through its centre miss the ratio and read by like edges
{
var map = Rotated(25, 0, 0, ThinPx, ThinTurn);
var thin = Render(v2, map, ThinPx, ThinPx, 4, null, false, false, ThinSpread);
var threshold = Otsu(thin);
foreach (var f in new[] { (U: 3.5, V: 3.5), (U: 21.5, V: 3.5), (U: 3.5, V: 21.5) })
{
var (cx, cy) = map.Map(f.U, f.V);
var rowReads = Enumerable.Range(-3, 7).Any(dy => FinderRuns(thin, ThinPx, (int)cx, (int)cy + dy, 1, 0, threshold) is { } runs && IsRatio(runs));
var centreLines = new[] { (1, 0), (0, 1), (1, 1), (1, -1) }.All(d => FinderRuns(thin, ThinPx, (int)cx, (int)cy, d.Item1, d.Item2, threshold) is { } runs && !IsRatio(runs) && IsLikeEdges(runs));
Console.WriteLine($"{(rowReads && centreLines ? "ok " : "FAIL")} thin rings: finder at ({f.U}, {f.V}), a row reads the ratio {rowReads}, the centre's lines read by like edges only {centreLines}");
if (!rowReads || !centreLines)
failures.Add($"thin rings finder ({f.U}, {f.V})");
}
}
Check("uneven lighting", v2, Payload, (x, y, s) => Square(25, x, y, s), 33 * 4, 1, light: Shadow(33 * 4, 0.5, 3 * 4));
// The figure says the global threshold falls between lit and shadowed paper, so shadowed paper reads as ink
{
var lit = Render(v2, Square(25, 0, 0, 33 * 4), 33 * 4, 33 * 4, 1, Shadow(33 * 4, 0.5, 3 * 4), false, false);
var threshold = Otsu(lit);
var shadowedPaper = 220 * 0.5;
var below = shadowedPaper < threshold;
Console.WriteLine($"{(below ? "ok " : "FAIL")} uneven lighting: global threshold {threshold}, shadowed paper {shadowedPaper}");
if (!below)
failures.Add("uneven lighting threshold");
}
Check("low density", v2, Payload, (x, y, s) => Square(25, x, y, s), 43, 1);
Check("light on dark", v2, Payload, (x, y, s) => Square(25, x, y, s), 33 * 4, 1, invert: true);
Check("large version", v14, MeshPayload, (x, y, s) => Keystone(73, x, y, s, 0.12), 81 * 4, 4);
// Micro QR: an M3 for the clean figure, so the larger size is tried first, and an M4 for the others
const string MicroPayload = "FEATHERQR";
var m3 = MicroMatrix(MicroQRCodeGenerator.Create(MicroPayload, MicroQREccLevel.M, new MicroQRCodeGeneratorOptions { Version = MicroQRVersion.M3, QuietZoneSize = 0 }));
const string MicroPayload4 = "FEATHERQR MICRO";
var m4 = MicroMatrix(MicroQRCodeGenerator.Create(MicroPayload4, MicroQREccLevel.M, new MicroQRCodeGeneratorOptions { Version = MicroQRVersion.M4, QuietZoneSize = 0 }));
void CheckMicro(string name, bool[,] m, string payload, Func<double, double, double, H> shape, int size, int supersample, bool blur = false)
{
var luminance = Render(m, shape(0, 0, size), size, size, supersample, null, false, blur);
var ok = MicroQRCodeDecoder.TryDecodeImage(luminance, size, size, out var text, out var info);
var pass = ok && text == payload;
Console.WriteLine($"{(pass ? "ok " : "FAIL")} micro {name}: {size}x{size} px, {info.Status}, {info.Version}, corrected {info.ErrorsCorrected}");
if (!pass)
failures.Add("micro " + name);
}
// The inputs as rendered, shared with their figures
const double MicroTurn = 30, MicroShrink = 0.08;
const int MicroRotatedPx = 116, MicroKeystonePx = 78, MicroSnapPx = 41, MicroLowPx = 22, MicroGreyPx = 38;
const bool MicroGreyBlur = false;
CheckMicro("clean", m3, MicroPayload, (x, y, s) => Square(15, x, y, s, 2), 19 * 4, 1);
CheckMicro("rotated and mirrored", Transposed(m4), MicroPayload4, (x, y, s) => Rotated(17, x, y, s, MicroTurn, 2), MicroRotatedPx, 4);
CheckMicro("keystone", m4, MicroPayload4, (x, y, s) => Keystone(17, x, y, s, MicroShrink, 2), MicroKeystonePx, 4);
CheckMicro("grey edges", m4, MicroPayload4, (x, y, s) => Square(17, x, y, s, 2), MicroGreyPx, 4, blur: MicroGreyBlur);
CheckMicro("snapped scale", m4, MicroPayload4, (x, y, s) => Square(17, x, y, s, 2), MicroSnapPx, 1);
CheckMicro("low density", m4, MicroPayload4, (x, y, s) => Square(17, x, y, s, 2), MicroLowPx, 1);
// rMQR: an R11x77 for most figures. Each input is a map in image pixels and the image's size.
const string RmqrPayload = "FEATHERQR RMQR";
var r11 = RmqrMatrix(RmQRCodeGenerator.Create(RmqrPayload, RmQREccLevel.M, new RmQRCodeGeneratorOptions { Version = RmQRVersion.R11x77, QuietZoneSize = 0 }));
// The strip draws a shorter symbol, so its panels stay legible
var r43 = RmqrMatrix(RmQRCodeGenerator.Create("FEATHERQR", RmQREccLevel.M, new RmQRCodeGeneratorOptions { Version = RmQRVersion.R11x43, QuietZoneSize = 0 }));
void CheckRmqr(string name, bool[,] m, string payload, (H Map, int Width, int Height) input, int supersample, bool blur = false)
{
var luminance = Render(m, input.Map, input.Width, input.Height, supersample, null, false, blur);
var ok = RmQRCodeDecoder.TryDecodeImage(luminance, input.Width, input.Height, out var text, out var info);
var pass = ok && text == payload;
Console.WriteLine($"{(pass ? "ok " : "FAIL")} rmqr {name}: {input.Width}x{input.Height} px, {info.Status}, {info.Version}, corrected {info.ErrorsCorrected}");
if (!pass)
failures.Add("rmqr " + name);
}
// The inputs as rendered, shared with their figures
const double RmqrPitch = 4, RmqrTurn = 30, RmqrKeystonePitch = 8, RmqrShrink = 0.16, RmqrWide = 4, RmqrTall = 3, RmqrGreyPitch = 1.55, RmqrGreyTurn = 3, RmqrLowPitch = 1.2;
const char RmqrShrunkEdge = 'T';
const int RmqrSnapWidth = 137;
const bool RmqrGreyBlur = false;
// The 5 x 5 sub-finder in the bottom-right corner painted to paper
var r11Hidden = (bool[,])r11.Clone();
for (var r = r11.GetLength(0) - 5; r < r11.GetLength(0); r++)
for (var c = r11.GetLength(1) - 5; c < r11.GetLength(1); c++)
r11Hidden[r, c] = false;
var rmqrClean = RectUpright(r11, RmqrPitch, RmqrPitch);
var rmqrRotated = RectRotated(MirroredX(r11), RmqrPitch, RmqrTurn);
var rmqrKeystone = RectKeystone(r11, RmqrKeystonePitch, RmqrShrink, RmqrShrunkEdge);
var rmqrNonSquare = RectUpright(r11, RmqrWide, RmqrTall);
var rmqrGrey = RectRotated(r11, RmqrGreyPitch, RmqrGreyTurn);
var rmqrHidden = RectUpright(r11Hidden, RmqrPitch, RmqrPitch);
var rmqrSnapped = RectUpright(r11, RmqrSnapWidth / 81.0, RmqrSnapWidth / 81.0);
var rmqrLow = RectUpright(r11, RmqrLowPitch, RmqrLowPitch);
CheckRmqr("clean", r11, RmqrPayload, rmqrClean, 1);
CheckRmqr("rotated and mirrored", MirroredX(r11), RmqrPayload, rmqrRotated, 4);
CheckRmqr("keystone", r11, RmqrPayload, rmqrKeystone, 4);
CheckRmqr("non-square modules", r11, RmqrPayload, rmqrNonSquare, 1);
CheckRmqr("grey edges", r11, RmqrPayload, rmqrGrey, 4, RmqrGreyBlur);
CheckRmqr("hidden sub-finder", r11Hidden, RmqrPayload, rmqrHidden, 1);
CheckRmqr("snapped scale", r11, RmqrPayload, rmqrSnapped, 1);
CheckRmqr("low density", r11, RmqrPayload, rmqrLow, 1);
// ---------- Drawing ----------
const string Font = "-apple-system,'Segoe UI',Helvetica,Arial,sans-serif";
string Style() => $$"""
<style>
.card{fill:#ffffff;stroke:#d0d7de}
.box{fill:#f6f8fa;stroke:#d8dee4}
.h{font:600 12px {{Font}};fill:#1f2328}
.xs{font:11px {{Font}};fill:#59636e}
.lab{font:600 11px {{Font}};fill:#0969da;paint-order:stroke;stroke:#ffffff;stroke-width:3px;stroke-linejoin:round}
.estt{font:600 11px {{Font}};fill:#57606a;paint-order:stroke;stroke:#ffffff;stroke-width:3px;stroke-linejoin:round}
.rowt{font:600 11px {{Font}};fill:#8250df;paint-order:stroke;stroke:#ffffff;stroke-width:3px;stroke-linejoin:round}
.ink{fill:#1f2328}
.paper{fill:#ffffff}
.det{fill:#0969da}
.detl{stroke:#0969da;fill:none;stroke-width:1.6}
.detd{stroke:#0969da;fill:none;stroke-width:1.4;stroke-dasharray:5 3}
.pred{stroke:#bf8700;fill:none;stroke-width:1.6;stroke-dasharray:4 3}
.twopx{fill:#bf8700;fill-opacity:.35}
.predr{stroke:#bf8700;fill:#ffffff;stroke-width:1.6}
.est{stroke:#6e7781;fill:none;stroke-width:1.4;stroke-dasharray:3 3}
.estx{stroke:#57606a;fill:none;stroke-width:2.4}
.row{stroke:#8250df;fill:none;stroke-width:2.2;stroke-dasharray:5 3}
.tick{stroke:#0969da;fill:none;stroke-width:3;stroke-linecap:round}
.err{stroke:#cf222e;fill:none;stroke-width:1.8}
.pt{fill:#0969da;fill-opacity:.7}
.hist{fill:#d0d7de;stroke:#8c959f;stroke-width:1}
.thr{stroke:#bf8700;stroke-width:1.6;stroke-dasharray:3 2}
.sep{stroke:#d8dee4;stroke-width:1}
.fmt{fill:#0969da;fill-opacity:.55}
.lat{stroke:#0969da;stroke-opacity:.85;stroke-width:1.4;fill:none}
.blk{stroke:#8250df;stroke-opacity:.35;stroke-width:.8;fill:none}
.arrow{stroke:#8c959f;stroke-width:1.6;fill:none}
.num{font:600 10px {{Font}};fill:#ffffff}
.bk{fill:#dafbe1;stroke:#4ac26b;stroke-width:1.2}.bkt{font:600 12px {{Font}};fill:#1f2328}
.bu{fill:#f6f8fa;stroke:#d0d7de}.but{font:600 12px {{Font}};fill:#1f2328}
.bc{fill:#ffffff;stroke:#bf8700;stroke-dasharray:4 3}.bct{font:600 12px {{Font}};fill:#7d4e00}
.bs{fill:#ffffff;stroke:#d8dee4;stroke-dasharray:2 3}.bst{font:600 12px {{Font}};fill:#8c959f}
.flow{stroke:#8c959f;stroke-width:1.4;fill:none}
.flowd{stroke:#bf8700;stroke-width:1.4;fill:none;stroke-dasharray:4 3}
</style>
""";
string F(double v) => v.ToString("0.##", CultureInfo.InvariantCulture);
string Esc(string s) => s.Replace("&", "&").Replace("<", "<").Replace(">", ">");
string Poly(H map, double u0, double v0, double u1, double v1)
{
var a = map.Map(u0, v0); var b = map.Map(u1, v0); var c = map.Map(u1, v1); var d = map.Map(u0, v1);
return $"M{F(a.X)} {F(a.Y)}L{F(b.X)} {F(b.Y)}L{F(c.X)} {F(c.Y)}L{F(d.X)} {F(d.Y)}Z";
}
string Symbol(H map, bool[,] m, string ink = "#1f2328", string paper = "#ffffff")
{
var rows = m.GetLength(0); var cols = m.GetLength(1);
var path = new StringBuilder();
for (var r = 0; r < rows; r++)
for (var c = 0; c < cols; c++)
if (m[r, c])
path.Append(Poly(map, c, r, c + 1, r + 1));
return $"<path fill=\"{paper}\" stroke=\"#d0d7de\" d=\"{Poly(map, -2, -2, cols + 2, rows + 2)}\"/><path fill=\"{ink}\" stroke=\"{ink}\" stroke-width=\"0.35\" d=\"{path}\"/>";
}
// A symbol whose dark edges all moved by spread of a module, outward when positive: each dark module grown by it, or the
// light modules grown into the ink, with the round corners the render's distance rule gives. An affine map only
string SpreadSymbol(H map, bool[,] m, double spread)
{
string P(double v) => v.ToString("0.#####", CultureInfo.InvariantCulture);
var rows = m.GetLength(0); var cols = m.GetLength(1);
var reach = Math.Abs(spread);
var grown = new StringBuilder();
for (var r = 0; r < rows; r++)
for (var c = 0; c < cols; c++)
if (m[r, c] == spread > 0)
grown.Append($"<rect x=\"{F(c - reach)}\" y=\"{F(r - reach)}\" width=\"{F(1 + 2 * reach)}\" height=\"{F(1 + 2 * reach)}\" rx=\"{F(reach)}\"/>");
var paper = $"<path fill=\"#ffffff\" stroke=\"#d0d7de\" d=\"{Poly(map, -2, -2, cols + 2, rows + 2)}\"/>";
var transform = $"matrix({P(map.A)} {P(map.D)} {P(map.B)} {P(map.E)} {P(map.C)} {P(map.F)})";
return spread > 0
? $"{paper}<g transform=\"{transform}\" fill=\"#1f2328\">{grown}</g>"
: $"{paper}<g transform=\"{transform}\"><rect fill=\"#1f2328\" x=\"{F(reach)}\" y=\"{F(reach)}\" width=\"{F(cols - 2 * reach)}\" height=\"{F(rows - 2 * reach)}\"/><g fill=\"#ffffff\">{grown}</g></g>";
}
string Dot((double X, double Y) p, double r = 4, string cls = "det") => $"<circle class=\"{cls}\" cx=\"{F(p.X)}\" cy=\"{F(p.Y)}\" r=\"{F(r)}\"/>";
string Line((double X, double Y) a, (double X, double Y) b, string cls) => $"<line class=\"{cls}\" x1=\"{F(a.X)}\" y1=\"{F(a.Y)}\" x2=\"{F(b.X)}\" y2=\"{F(b.Y)}\"/>";
// A line read by like edges, styled in place: a class would enter every figure's style block
string LikeLine((double X, double Y) a, (double X, double Y) b) => $"<line stroke=\"#0969da\" stroke-width=\"2.4\" stroke-linecap=\"round\" x1=\"{F(a.X)}\" y1=\"{F(a.Y)}\" x2=\"{F(b.X)}\" y2=\"{F(b.Y)}\"/>";
string Text(double x, double y, string s, string cls, string anchor = "start") => $"<text class=\"{cls}\" x=\"{F(x)}\" y=\"{F(y)}\" text-anchor=\"{anchor}\">{Esc(s)}</text>";
string Cross((double X, double Y) p, double s, string cls) => Line((p.X - s, p.Y - s), (p.X + s, p.Y + s), cls) + Line((p.X - s, p.Y + s), (p.X + s, p.Y - s), cls);
string Window(H map, (double U, double V) centre, double half, string cls) => $"<path class=\"{cls}\" d=\"{Poly(map, centre.U - half, centre.V - half, centre.U + half, centre.V + half)}\"/>";
string Marker(double cx, double cy, int n) => $"<circle cx=\"{F(cx)}\" cy=\"{F(cy)}\" r=\"8\" fill=\"#1a7f37\"/><text class=\"num\" x=\"{F(cx)}\" y=\"{F(cy + 3.5)}\" text-anchor=\"middle\">{n}</text>";
List<string> Wrap(string s, int max)
{
var lines = new List<string>();
var line = new StringBuilder();
foreach (var word in s.Split(' '))
{
if (line.Length > 0 && line.Length + 1 + word.Length > max)
{
lines.Add(line.ToString());
line.Clear();
}
if (line.Length > 0)
line.Append(' ');
line.Append(word);
}
if (line.Length > 0)
lines.Add(line.ToString());
return lines;
}
// Finder centres and the bottom-right alignment centre of a version 2 grid
(double U, double V) tl = (3.5, 3.5), tr = (21.5, 3.5), bl = (3.5, 21.5), al = (18.5, 18.5);
(double X, double Y) ParallelogramAlignment(H map, int dim)
{
var a = map.Map(3.5, 3.5); var b = map.Map(dim - 3.5, 3.5); var c = map.Map(3.5, dim - 3.5);
var cornerX = b.X + c.X - a.X; var cornerY = b.Y + c.Y - a.Y;
var k = 1 - 3.0 / (dim - 7);
return (a.X + k * (cornerX - a.X), a.Y + k * (cornerY - a.Y));
}
string LabelAway(H map, (double U, double V) f, string label, double distance)
{
var p = map.Map(f.U, f.V);
var g = map.Map((tl.U + tr.U + bl.U) / 3, (tl.V + tr.V + bl.V) / 3);
var dx = p.X - g.X; var dy = p.Y - g.Y;
var n = Math.Sqrt(dx * dx + dy * dy);
return Text(p.X + dx / n * distance, p.Y + dy / n * distance + 4, label, "lab", "middle");
}
string Histogram(double x, double y, double w, double h)
{
var sb = new StringBuilder($"M{F(x)} {F(y + h)}");
for (var i = 0; i <= 60; i++)
{
var t = i / 60.0;
var v = Math.Exp(-Math.Pow(t - 0.18, 2) / 0.004) * 0.75 + Math.Exp(-Math.Pow(t - 0.86, 2) / 0.003) + 0.06;
sb.Append($"L{F(x + t * w)} {F(y + h - v * h)}");
}
sb.Append($"L{F(x + w)} {F(y + h)}Z");
return $"<path class=\"hist\" d=\"{sb}\"/>";
}
string Card(int width, int height, string defs = "")
=> $"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{width}\" height=\"{height}\" viewBox=\"0 0 {width} {height}\">{Style()}<defs>{defs}<marker id=\"ah\" viewBox=\"0 0 10 10\" refX=\"9\" refY=\"5\" markerWidth=\"7\" markerHeight=\"7\" orient=\"auto-start-reverse\"><path d=\"M0 0L10 5L0 10z\" fill=\"#8c959f\"/></marker></defs>"
+ $"<rect class=\"card\" x=\"0.5\" y=\"0.5\" width=\"{width - 1}\" height=\"{height - 1}\" rx=\"12\"/>";
// ---------- The stage strip ----------
{
const int W = 1080, H0 = 250;
var sb = new StringBuilder();
sb.Append(Card(W, H0,
"<filter id=\"lens\" x=\"-5%\" y=\"-5%\" width=\"110%\" height=\"110%\"><feGaussianBlur stdDeviation=\"0.8\"/></filter><linearGradient id=\"light\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\"><stop offset=\"0\" stop-color=\"#ffffff\" stop-opacity=\".35\"/><stop offset=\"1\" stop-color=\"#000000\" stop-opacity=\".22\"/></linearGradient>"));
const double P = 150, S = 36, Gap = 28, X0 = 24, Y0 = 20;
string[] labels = ["Luminance", "Global threshold", "Finder triple", "Corner from the triangle", "Alignment search", "Matrix decode"];
for (var i = 0; i < 6; i++)
{
var x = X0 + i * (P + Gap);
sb.Append($"<rect class=\"box\" x=\"{F(x)}\" y=\"{F(Y0)}\" width=\"{P}\" height=\"{P + S}\" rx=\"8\"/>");
sb.Append(Line((x, Y0 + P), (x + P, Y0 + P), "sep"));
var map = Square(25, x + 10, Y0 + 10, P - 20, 2);
var sy = Y0 + P;
switch (i)
{
case 0:
sb.Append($"<g filter=\"url(#lens)\">{Symbol(map, v2, "#4a4a48", "#e7e3db")}</g>");
sb.Append($"<path fill=\"url(#light)\" d=\"{Poly(map, -2, -2, 27, 27)}\"/>");
sb.Append(Histogram(x + 20, sy + 7, P - 40, 22));
break;
case 1:
sb.Append(Symbol(map, v2));
sb.Append(Histogram(x + 20, sy + 7, P - 40, 22));
var tx = x + 20 + 0.52 * (P - 40);
sb.Append(Line((tx, sy + 4), (tx, sy + 31), "thr"));
break;
case 2:
sb.Append($"<g opacity=\"0.3\">{Symbol(map, v2)}</g>");
sb.Append(Line(map.Map(-1.5, tl.V), map.Map(8.5, tl.V), "detl"));
foreach (var f in new[] { tl, tr, bl })
sb.Append(Dot(map.Map(f.U, f.V)));
var unit = 15.0; var bx = x + (P - 7 * unit) / 2; var by = sy + 7;
int[] runs = [1, 1, 3, 1, 1];
var rx = bx;
for (var k = 0; k < runs.Length; k++)
{
var wdt = runs[k] * unit;
sb.Append(k % 2 == 0
? $"<rect class=\"ink\" x=\"{F(rx)}\" y=\"{F(by)}\" width=\"{F(wdt)}\" height=\"9\"/>"
: $"<rect fill=\"#ffffff\" stroke=\"#8c959f\" x=\"{F(rx)}\" y=\"{F(by)}\" width=\"{F(wdt)}\" height=\"9\"/>");
sb.Append(Text(rx + wdt / 2, by + 22, runs[k].ToString(CultureInfo.InvariantCulture), "xs", "middle"));
rx += wdt;
}
break;
case 3:
sb.Append($"<g opacity=\"0.3\">{Symbol(map, v2)}</g>");
sb.Append(Line(map.Map(tl.U, tl.V), map.Map(tr.U, tr.V), "detl"));
sb.Append(Line(map.Map(tl.U, tl.V), map.Map(bl.U, bl.V), "detl"));
sb.Append(Line(map.Map(tr.U, tr.V), map.Map(bl.U, bl.V), "est"));
foreach (var f in new[] { tl, tr, bl })
sb.Append(Dot(map.Map(f.U, f.V)));
sb.Append(LabelAway(map, tl, "TL", 13));
sb.Append(LabelAway(map, tr, "TR", 13));
sb.Append(LabelAway(map, bl, "BL", 13));
sb.Append(Line((x + 26, sy + 18), (x + 46, sy + 18), "est"));
sb.Append(Text(x + 52, sy + 22, "longest side", "xs"));
break;
case 4:
sb.Append($"<g opacity=\"0.3\">{Symbol(map, v2)}</g>");
var pts = new StringBuilder();
for (var r = 0; r < 25; r++)
for (var c = 0; c < 25; c++)
{
var p = map.Map(c + 0.5, r + 0.5);
pts.Append($"M{F(p.X - 0.9)} {F(p.Y)}a0.9 0.9 0 1 0 1.8 0a0.9 0.9 0 1 0 -1.8 0");
}
sb.Append($"<path class=\"pt\" d=\"{pts}\"/>");
sb.Append(Window(map, al, 3, "pred"));
foreach (var f in new[] { tl, tr, bl })
sb.Append(Dot(map.Map(f.U, f.V)));
sb.Append($"<circle class=\"detl\" cx=\"{F(map.Map(al.U, al.V).X)}\" cy=\"{F(map.Map(al.U, al.V).Y)}\" r=\"3.5\"/>");
sb.Append(Dot(map.Map(al.U, al.V), 2));
sb.Append($"<rect class=\"pred\" x=\"{F(x + 10)}\" y=\"{F(sy + 12)}\" width=\"10\" height=\"10\"/>");
sb.Append(Text(x + 25, sy + 21, "search", "xs"));
sb.Append(Dot((x + 70, sy + 17), 2.2, "pt"));
sb.Append(Text(x + 77, sy + 21, "sample point", "xs"));
break;
case 5:
sb.Append($"<path class=\"paper\" stroke=\"#d0d7de\" d=\"{Poly(map, -2, -2, 27, 27)}\"/>");
var cells = new StringBuilder();
var fmt = new StringBuilder();
for (var r = 0; r < 25; r++)
for (var c = 0; c < 25; c++)
{
var isFormat = (r == 8 && (c <= 8 || c >= 17) && c != 6) || (c == 8 && (r <= 8 || r >= 18) && r != 6);
if (isFormat)
fmt.Append(Poly(map, c + 0.12, r + 0.12, c + 0.88, r + 0.88));
else if (v2[r, c])
cells.Append(Poly(map, c + 0.12, r + 0.12, c + 0.88, r + 0.88));
}
sb.Append($"<path class=\"ink\" d=\"{cells}\"/><path class=\"fmt\" d=\"{fmt}\"/>");
sb.Append($"<rect class=\"fmt\" x=\"{F(x + 26)}\" y=\"{F(sy + 12)}\" width=\"10\" height=\"10\"/>");
sb.Append(Text(x + 42, sy + 21, "format information", "xs"));
break;
}
sb.Append(Text(x + P / 2, Y0 + P + S + 22, labels[i], "h", "middle"));
if (i < 5)
{
var ax = x + P + 6; var ay = Y0 + P / 2;
sb.Append($"<path class=\"arrow\" d=\"M{F(ax)} {F(ay)}h{Gap - 12}m-5 -5l5 5l-5 5\"/>");
}
}
sb.Append("</svg>");
File.WriteAllText(Path.Combine(qrDir, "decode-overview.svg"), sb.ToString());
}
// ---------- The Micro QR stage strip ----------
{
const int W = 1080, H0 = 250;
var sb = new StringBuilder();
sb.Append(Card(W, H0,
"<filter id=\"lens\" x=\"-5%\" y=\"-5%\" width=\"110%\" height=\"110%\"><feGaussianBlur stdDeviation=\"0.8\"/></filter><linearGradient id=\"light\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\"><stop offset=\"0\" stop-color=\"#ffffff\" stop-opacity=\".35\"/><stop offset=\"1\" stop-color=\"#000000\" stop-opacity=\".22\"/></linearGradient>"));
const double P = 150, S = 36, Gap = 28, X0 = 24, Y0 = 20;
string[] labels = ["Luminance", "Global threshold", "Finder candidates", "Module sizes and centre", "Sizes M4 to M1", "Matrix decode"];
// The single finder's centre, in the modules of an M3
(double U, double V) centre = (3.5, 3.5);
for (var i = 0; i < 6; i++)
{
var x = X0 + i * (P + Gap);
sb.Append($"<rect class=\"box\" x=\"{F(x)}\" y=\"{F(Y0)}\" width=\"{P}\" height=\"{P + S}\" rx=\"8\"/>");
sb.Append(Line((x, Y0 + P), (x + P, Y0 + P), "sep"));
// Room for an M4 outline around the M3: the quiet zone is two modules
var map = Square(15, x + 10, Y0 + 10, P - 20, 2);
var sy = Y0 + P;
switch (i)
{
case 0:
sb.Append($"<g filter=\"url(#lens)\">{Symbol(map, m3, "#4a4a48", "#e7e3db")}</g>");
sb.Append($"<path fill=\"url(#light)\" d=\"{Poly(map, -2, -2, 17, 17)}\"/>");
sb.Append(Histogram(x + 20, sy + 7, P - 40, 22));
break;
case 1:
sb.Append(Symbol(map, m3));
sb.Append(Histogram(x + 20, sy + 7, P - 40, 22));
var tx = x + 20 + 0.52 * (P - 40);
sb.Append(Line((tx, sy + 4), (tx, sy + 31), "thr"));
break;
case 2:
sb.Append($"<g opacity=\"0.3\">{Symbol(map, m3)}</g>");
sb.Append(Line(map.Map(-1.5, centre.V), map.Map(8.5, centre.V), "detl"));
sb.Append(Dot(map.Map(centre.U, centre.V)));
var unit = 15.0; var bx = x + (P - 7 * unit) / 2; var by = sy + 7;
int[] runs = [1, 1, 3, 1, 1];
var rx = bx;
for (var k = 0; k < runs.Length; k++)
{
var wdt = runs[k] * unit;
sb.Append(k % 2 == 0
? $"<rect class=\"ink\" x=\"{F(rx)}\" y=\"{F(by)}\" width=\"{F(wdt)}\" height=\"9\"/>"
: $"<rect fill=\"#ffffff\" stroke=\"#8c959f\" x=\"{F(rx)}\" y=\"{F(by)}\" width=\"{F(wdt)}\" height=\"9\"/>");
sb.Append(Text(rx + wdt / 2, by + 22, runs[k].ToString(CultureInfo.InvariantCulture), "xs", "middle"));
rx += wdt;
}
break;
case 3:
// Each size pairs the dark ring's inner edge on one side with its outer edge on the other: six modules
sb.Append($"<g opacity=\"0.3\">{Symbol(map, m3)}</g>");
sb.Append(Line(map.Map(1, centre.V - 0.25), map.Map(7, centre.V - 0.25), "tick"));
sb.Append(Line(map.Map(centre.U + 0.25, 1), map.Map(centre.U + 0.25, 7), "tick"));
sb.Append(Dot(map.Map(centre.U, centre.V)));
sb.Append(Line((x + 26, sy + 18), (x + 46, sy + 18), "tick"));
sb.Append(Text(x + 52, sy + 22, "six modules", "xs"));
break;
case 4:
sb.Append($"<g opacity=\"0.3\">{Symbol(map, m3)}</g>");
foreach (var size in new[] { 17, 13, 11 })
sb.Append($"<path class=\"est\" d=\"{Poly(map, 0, 0, size, size)}\"/>");
sb.Append($"<path class=\"detl\" d=\"{Poly(map, 0, 0, 15, 15)}\"/>");
sb.Append(Dot(map.Map(centre.U, centre.V)));
sb.Append(Line((x + 12, sy + 18), (x + 30, sy + 18), "est"));
sb.Append(Text(x + 35, sy + 22, "other sizes", "xs"));
sb.Append(Line((x + 96, sy + 18), (x + 110, sy + 18), "detl"));
sb.Append(Text(x + 114, sy + 22, "reads", "xs"));
break;
case 5:
sb.Append($"<path class=\"paper\" stroke=\"#d0d7de\" d=\"{Poly(map, -2, -2, 17, 17)}\"/>");
var cells = new StringBuilder();
var fmt = new StringBuilder();
for (var r = 0; r < 15; r++)
for (var c = 0; c < 15; c++)
{
// Format information: row 8 columns 1-8, column 8 rows 1-7
var isFormat = (r == 8 && c >= 1 && c <= 8) || (c == 8 && r >= 1 && r <= 7);
if (isFormat)
fmt.Append(Poly(map, c + 0.12, r + 0.12, c + 0.88, r + 0.88));
else if (m3[r, c])
cells.Append(Poly(map, c + 0.12, r + 0.12, c + 0.88, r + 0.88));
}
sb.Append($"<path class=\"ink\" d=\"{cells}\"/><path class=\"fmt\" d=\"{fmt}\"/>");
sb.Append($"<rect class=\"fmt\" x=\"{F(x + 26)}\" y=\"{F(sy + 12)}\" width=\"10\" height=\"10\"/>");
sb.Append(Text(x + 42, sy + 21, "format information", "xs"));
break;
}
sb.Append(Text(x + P / 2, Y0 + P + S + 22, labels[i], "h", "middle"));
if (i < 5)
{
var ax = x + P + 6; var ay = Y0 + P / 2;
sb.Append($"<path class=\"arrow\" d=\"M{F(ax)} {F(ay)}h{Gap - 12}m-5 -5l5 5l-5 5\"/>");
}
}
sb.Append("</svg>");
File.WriteAllText(Path.Combine(microDir, "decode-overview.svg"), sb.ToString());
}
// ---------- The rMQR stage strip ----------
{
// Two rows of three: a wide symbol needs wide panels
const double P = 320, PH = 116, S = 36, Gap = 28, X0 = 24, Y0 = 20, RowGap = 48;
const int W = 1080, H0 = (int)(Y0 + 2 * (PH + S) + RowGap + 22 + 20);
var sb = new StringBuilder();
sb.Append(Card(W, H0,
"<filter id=\"lens\" x=\"-5%\" y=\"-5%\" width=\"110%\" height=\"110%\"><feGaussianBlur stdDeviation=\"0.8\"/></filter><linearGradient id=\"light\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\"><stop offset=\"0\" stop-color=\"#ffffff\" stop-opacity=\".35\"/><stop offset=\"1\" stop-color=\"#000000\" stop-opacity=\".22\"/></linearGradient>"));
string[] labels = ["Luminance", "Global threshold", "Finder candidates", "Finder-side format copy", "Sub-finder", "Isotropic grid"];
int rows = r43.GetLength(0), cols = r43.GetLength(1);
(double U, double V) finder = (3.5, 3.5), sub = (cols - 2.5, rows - 2.5);
for (var i = 0; i < 6; i++)
{
var x = X0 + i % 3 * (P + Gap); var y = Y0 + i / 3 * (PH + S + RowGap);
sb.Append($"<rect class=\"box\" x=\"{F(x)}\" y=\"{F(y)}\" width=\"{P}\" height=\"{PH + S}\" rx=\"8\"/>");
sb.Append(Line((x, y + PH), (x + P, y + PH), "sep"));
var pitch = (P - 20) / (cols + 4);
var map = H.Affine(x + 10 + 2 * pitch, y + (PH - (rows + 4) * pitch) / 2 + 2 * pitch, pitch, 0, 0, pitch);
var sy = y + PH;
switch (i)
{
case 0:
sb.Append($"<g filter=\"url(#lens)\">{Symbol(map, r43, "#4a4a48", "#e7e3db")}</g>");
sb.Append($"<path fill=\"url(#light)\" d=\"{Poly(map, -2, -2, cols + 2, rows + 2)}\"/>");
sb.Append(Histogram(x + 40, sy + 7, P - 80, 22));
break;
case 1:
sb.Append(Symbol(map, r43));
sb.Append(Histogram(x + 40, sy + 7, P - 80, 22));
var tx = x + 40 + 0.52 * (P - 80);
sb.Append(Line((tx, sy + 4), (tx, sy + 31), "thr"));
break;
case 2:
sb.Append($"<g opacity=\"0.3\">{Symbol(map, r43)}</g>");
sb.Append(Line(map.Map(-1.5, finder.V), map.Map(8.5, finder.V), "detl"));
sb.Append(Dot(map.Map(finder.U, finder.V)));
var unit = 15.0; var bx = x + (P - 7 * unit) / 2; var by = sy + 7;
int[] runs = [1, 1, 3, 1, 1];
var rx = bx;
for (var k = 0; k < runs.Length; k++)
{
var wdt = runs[k] * unit;
sb.Append(k % 2 == 0
? $"<rect class=\"ink\" x=\"{F(rx)}\" y=\"{F(by)}\" width=\"{F(wdt)}\" height=\"9\"/>"
: $"<rect fill=\"#ffffff\" stroke=\"#8c959f\" x=\"{F(rx)}\" y=\"{F(by)}\" width=\"{F(wdt)}\" height=\"9\"/>");
sb.Append(Text(rx + wdt / 2, by + 22, runs[k].ToString(CultureInfo.InvariantCulture), "xs", "middle"));
rx += wdt;
}
break;
case 3:
// Finder side: rows 1-5 of columns 8-10, then rows 1-3 of column 11
sb.Append($"<g opacity=\"0.3\">{Symbol(map, r43)}</g>");
var fmt = new StringBuilder();
for (var c = 8; c <= 11; c++)
for (var r = 1; r <= (c == 11 ? 3 : 5); r++)
fmt.Append(Poly(map, c + 0.1, r + 0.1, c + 0.9, r + 0.9));
sb.Append($"<path class=\"fmt\" d=\"{fmt}\"/>");
sb.Append($"<rect class=\"fmt\" x=\"{F(x + 90)}\" y=\"{F(sy + 12)}\" width=\"10\" height=\"10\"/>");
sb.Append(Text(x + 106, sy + 21, "format copy", "xs"));
break;
case 4:
sb.Append($"<g opacity=\"0.3\">{Symbol(map, r43)}</g>");
sb.Append(Window(map, sub, 3.5, "pred"));
sb.Append(Dot(map.Map(sub.U, sub.V)));
sb.Append($"<rect class=\"pred\" x=\"{F(x + 90)}\" y=\"{F(sy + 12)}\" width=\"10\" height=\"10\"/>");
sb.Append(Text(x + 106, sy + 21, "search", "xs"));
sb.Append(Dot((x + 170, sy + 17), 4));
sb.Append(Text(x + 180, sy + 21, "found centre", "xs"));
break;
case 5:
sb.Append($"<g opacity=\"0.3\">{Symbol(map, r43)}</g>");
var pts = new StringBuilder();
for (var r = 0; r < rows; r++)
for (var c = 0; c < cols; c++)
{
var p = map.Map(c + 0.5, r + 0.5);
pts.Append($"M{F(p.X - 0.9)} {F(p.Y)}a0.9 0.9 0 1 0 1.8 0a0.9 0.9 0 1 0 -1.8 0");
}
sb.Append($"<path class=\"pt\" d=\"{pts}\"/>");
sb.Append(Line(map.Map(finder.U, finder.V), map.Map(sub.U, sub.V), "detl"));
sb.Append(Dot(map.Map(finder.U, finder.V)));
sb.Append(Dot(map.Map(sub.U, sub.V)));
sb.Append(Line((x + 60, sy + 18), (x + 80, sy + 18), "detl"));
sb.Append(Text(x + 86, sy + 22, "finder to sub-finder", "xs"));
sb.Append(Dot((x + 210, sy + 17), 2.2, "pt"));
sb.Append(Text(x + 217, sy + 21, "sample point", "xs"));
break;
}
sb.Append(Text(x + P / 2, y + PH + S + 22, labels[i], "h", "middle"));
if (i % 3 < 2)
{
var ax = x + P + 6; var ay = y + PH / 2;
sb.Append($"<path class=\"arrow\" d=\"M{F(ax)} {F(ay)}h{Gap - 12}m-5 -5l5 5l-5 5\"/>");
}
else if (i == 2)
{
var nx = X0 + P / 2; var ny = Y0 + PH + S + RowGap;
var mid = y + PH + S + 36;
sb.Append($"<path class=\"arrow\" d=\"M{F(x + P / 2)} {F(y + PH + S + 28)}V{F(mid)}H{F(nx)}V{F(ny - 4)}m-5 -5l5 5l5 -5\"/>");
}
}
sb.Append("</svg>");
File.WriteAllText(Path.Combine(rmqrDir, "decode-overview.svg"), sb.ToString());
}
// ---------- The input figures ----------
// The image-level outline's stages, in its order. The matrix decode every grid goes through is the bar under them.
string[] qrBoxes =
[
"Binarization pass",
"Finder triple",
"Corner from the triangle",
"Low density",
"Finder centres and module sizes",
"Finders' frame and dimension candidates",
"Alignment search",
"Mesh over the alignment lattice",
"Four-point transform",
"Coverage re-read",
"Module-space re-read",
"Parallelogram or frame grid",
"Alternative triples",
];
// The matrix decode under the stages, in marks. Its state is the last in a states string.
const int Bar = -1;
// The picture on the left, the path through the outline's stages on the right. marks lists the boxes
// that carry the design record's numbered notes, in the notes' order. Bar is the matrix decode.
void InputFigure(string path, string[] boxes, Func<StringBuilder, double, double, double, string[]> picture, int[] marks, string states, int dashedFrom, string defs = "")
=> Figure(path, boxes, (sb, x, y, w, h) => picture(sb, x, y, w), 0, marks, states, dashedFrom, defs);
// A wide symbol's figure: the picture across the top, pictureHeight high, and the path under it
void InputFigureWide(string path, string[] boxes, Func<StringBuilder, double, double, double, double, string[]> picture, double pictureHeight, int[] marks, string states, int dashedFrom, string defs = "")
=> Figure(path, boxes, picture, pictureHeight, marks, states, dashedFrom, defs);
void Figure(string path, string[] boxes, Func<StringBuilder, double, double, double, double, string[]> picture, double wideHeight, int[] marks, string states, int dashedFrom, string defs)
{
const double PX = 24, PY = 20, PS = 260;
const double BW = 132, BH = 62, BG = 20, RG = 30;
const double FW = 4 * BW + 3 * BG;
var wide = wideHeight > 0;
var pw = wide ? FW : PS; var ph = wide ? wideHeight : PS;
var body = new StringBuilder();
body.Append($"<rect class=\"box\" x=\"{PX}\" y=\"{PY}\" width=\"{F(pw)}\" height=\"{F(ph)}\" rx=\"8\"/>");
var legend = picture(body, PX, PY, pw, ph);
var lx = PX; var ly = PY + ph + 24;
foreach (var item in legend)
{
var parts = item.Split('|');
var width = 20 + parts[1].Length * 6.0 + 18;
if (lx + width > PX + pw + 10)
{
lx = PX;
ly += 20;
}
body.Append(parts[0] switch
{
"det" => Dot((lx + 6, ly - 4), 4),
"detl" => Line((lx, ly - 4), (lx + 14, ly - 4), "detl"),
"detd" => Line((lx, ly - 4), (lx + 14, ly - 4), "detd"),
"pred" => $"<rect class=\"pred\" x=\"{F(lx + 1)}\" y=\"{F(ly - 10)}\" width=\"12\" height=\"12\"/>",
"twopx" => $"<rect class=\"twopx\" x=\"{F(lx + 1)}\" y=\"{F(ly - 10)}\" width=\"12\" height=\"12\"/>",
"predr" => $"<circle class=\"predr\" cx=\"{F(lx + 6)}\" cy=\"{F(ly - 4)}\" r=\"4\"/>",
"est" => Cross((lx + 6, ly - 4), 4, "estx"),
"estl" => Line((lx, ly - 4), (lx + 14, ly - 4), "est"),
"row" => Line((lx, ly - 4), (lx + 14, ly - 4), "row"),
"like" => LikeLine((lx, ly - 4), (lx + 14, ly - 4)),
"tick" => Line((lx + 2, ly - 4), (lx + 12, ly - 4), "tick"),
"err" => $"<rect class=\"err\" x=\"{F(lx + 1)}\" y=\"{F(ly - 10)}\" width=\"12\" height=\"12\"/>",
"lat" => Line((lx, ly - 4), (lx + 14, ly - 4), "lat"),
"blk" => $"<rect class=\"blk\" x=\"{F(lx + 1)}\" y=\"{F(ly - 10)}\" width=\"12\" height=\"12\"/>",
"px" => $"<rect fill=\"none\" stroke=\"#8c959f\" x=\"{F(lx + 1)}\" y=\"{F(ly - 10)}\" width=\"12\" height=\"12\"/>",
"fmt" => $"<rect class=\"fmt\" x=\"{F(lx + 1)}\" y=\"{F(ly - 10)}\" width=\"12\" height=\"12\"/>",
"shade" => $"<rect fill=\"#1f2328\" fill-opacity=\".35\" x=\"{F(lx + 1)}\" y=\"{F(ly - 10)}\" width=\"12\" height=\"12\"/>",
_ => "",
});
body.Append(Text(lx + 20, ly, parts[1], "xs"));
lx += width;
}
var numbers = new Dictionary<int, List<int>>();
for (var i = 0; i < marks.Length; i++)
{
if (!numbers.TryGetValue(marks[i], out var list))
numbers[marks[i]] = list = [];
list.Add(i + 1);
}
// Rows of four stages, then the matrix decode every grid goes through, beside the picture, or under a wide one
var FX = wide ? PX : PX + PS + 32;
var FY = wide ? ly + 28 : PY;
(double X, double Y) At(int b) => (FX + (b % 4) * (BW + BG), FY + (b / 4) * (BH + RG));
(string Box, string Text) Classes(char state) => state switch
{
'K' => ("bk", "bkt"),
'U' => ("bu", "but"),
'C' => ("bc", "bct"),
_ => ("bs", "bst"),
};
for (var b = 0; b < boxes.Length; b++)
{
var (x, y) = At(b);
var (box, t) = Classes(states[b]);
body.Append($"<rect class=\"{box}\" x=\"{F(x)}\" y=\"{F(y)}\" width=\"{BW}\" height=\"{BH}\" rx=\"8\"/>");
var lines = Wrap(boxes[b], 18);
for (var l = 0; l < lines.Count; l++)
body.Append(Text(x + 10, y + 20 + l * 15, lines[l], t));
if (numbers.TryGetValue(b, out var ns))
for (var k = 0; k < ns.Count; k++)
body.Append(Marker(x + BW - 12 - (ns.Count - 1 - k) * 19, y, ns[k]));
}
for (var b = 0; b < boxes.Length - 1; b++)
{
var (x, y) = At(b);
var cls = b >= dashedFrom ? "flowd" : "flow";
if (b % 4 == 3)
{
var (nx, ny) = At(b + 1);
body.Append($"<path class=\"{cls}\" marker-end=\"url(#ah)\" d=\"M{F(x + BW / 2)} {F(y + BH + 2)}V{F(y + BH + RG / 2)}H{F(nx + BW / 2)}V{F(ny - 4)}\"/>");
}
else
{
body.Append($"<path class=\"{cls}\" marker-end=\"url(#ah)\" d=\"M{F(x + BW + 2)} {F(y + BH / 2)}H{F(x + BW + BG - 4)}\"/>");
}
}
var rows = (boxes.Length + 3) / 4;
var barY = FY + rows * BH + (rows - 1) * RG + 14;
{
var (box, t) = Classes(states[boxes.Length]);
body.Append($"<rect class=\"{box}\" x=\"{F(FX)}\" y=\"{F(barY)}\" width=\"{F(FW)}\" height=\"30\" rx=\"8\"/>");
body.Append(Text(FX + 10, barY + 20, "Matrix decode", t));
if (numbers.TryGetValue(Bar, out var ns))
for (var k = 0; k < ns.Count; k++)
body.Append(Marker(FX + 118 + k * 19, barY + 15, ns[k]));
}
var ky = barY + 30 + 26;
(string Box, string Label)[] key = [("bk", "key"), ("bu", "runs"), ("bc", "only if needed"), ("bs", "skipped")];
var kx = FX;
foreach (var (box, label) in key)
{
body.Append($"<rect class=\"{box}\" x=\"{F(kx)}\" y=\"{F(ky - 11)}\" width=\"18\" height=\"14\" rx=\"4\"/>");
body.Append(Text(kx + 26, ky, label, "xs"));
kx += 26 + label.Length * 6.0 + 22;
}
var w = (int)Math.Ceiling(FX + FW + 24);
var h = (int)Math.Ceiling(Math.Max(ly, ky) + 20);
var sb = new StringBuilder();
sb.Append(Card(w, h, defs));
sb.Append(body);
sb.Append("</svg>");
File.WriteAllText(path, sb.ToString());
}
// Clean
InputFigure(Path.Combine(qrDir, "decode-input-clean.svg"), qrBoxes,
(sb, x, y, s) =>
{
var map = Square(25, x + 20, y + 20, s - 40);
sb.Append(Symbol(map, v2));
sb.Append(Line(map.Map(tl.U, tl.V), map.Map(tr.U, tr.V), "detl"));
sb.Append(Line(map.Map(tl.U, tl.V), map.Map(bl.U, bl.V), "detl"));
sb.Append(Line(map.Map(tr.U, tr.V), map.Map(bl.U, bl.V), "est"));
sb.Append(Window(map, al, 3, "pred"));
foreach (var f in new[] { tl, tr, bl })
sb.Append(Dot(map.Map(f.U, f.V), 5));
sb.Append(Dot(map.Map(al.U, al.V), 3.5));
return ["det|found centre", "detl|finder line", "estl|longest side", "pred|alignment search"];
},
[],
"UUUSUUUSUSSCSU", 8);
// Rotated or mirrored
InputFigure(Path.Combine(qrDir, "decode-input-rotated.svg"), qrBoxes,
(sb, x, y, s) =>
{
var map = Rotated(25, x + 20, y + 20, s - 40, 30);
sb.Append(Symbol(map, v2));
var c = map.Map(tl.U, tl.V);
var reach = (map.Map(1, 0).X - map.Map(0, 0).X) / Math.Cos(Math.PI / 6) * 5.4;
sb.Append(Line(map.Map(tl.U, tl.V), map.Map(tr.U, tr.V), "detl"));
sb.Append(Line(map.Map(tl.U, tl.V), map.Map(bl.U, bl.V), "detl"));
sb.Append(Line(map.Map(tr.U, tr.V), map.Map(bl.U, bl.V), "est"));
sb.Append(Line((c.X - reach, c.Y), (c.X + reach, c.Y), "row"));
sb.Append(Text(c.X + reach + 4, c.Y + 4, "image row", "rowt"));
foreach (var f in new[] { tl, tr, bl })
sb.Append(Dot(map.Map(f.U, f.V), 5));
sb.Append(LabelAway(map, tl, "TL", 16));
return ["det|found centre", "detl|finder line", "row|image row", "estl|longest side"];
},
[4, Bar],
"UUUSKUUSUCCCSK", 8);
// Keystone: tilted back about the horizontal axis, so the left finder line runs into the distance
InputFigure(Path.Combine(qrDir, "decode-input-keystone.svg"), qrBoxes,
(sb, x, y, s) =>
{
var map = Keystone(25, x + 20, y + 20, s - 40, 0.25);
sb.Append(Symbol(map, v2));
var a = map.Map(tl.U, tl.V); var b = map.Map(tr.U, tr.V); var c = map.Map(bl.U, bl.V);
sb.Append(Line(a, b, "detl"));
sb.Append(Line(a, c, "detl"));
sb.Append(Line(map.Map(-1.1, tl.V - 0.5), map.Map(-1.1, tl.V + 0.5), "tick"));
sb.Append(Line(map.Map(-1.1, bl.V - 0.5), map.Map(-1.1, bl.V + 0.5), "tick"));
var est = ParallelogramAlignment(map, 25);
sb.Append($"<path class=\"est\" d=\"M{F(b.X)} {F(b.Y)}L{F(b.X + c.X - a.X)} {F(b.Y + c.Y - a.Y)}L{F(c.X)} {F(c.Y)}\"/>");
sb.Append(Cross(est, 5, "estx"));
sb.Append(Window(map, al, 3, "pred"));
var pa = map.Map(al.U, al.V);
sb.Append($"<path class=\"detd\" d=\"M{F(a.X)} {F(a.Y)}L{F(b.X)} {F(b.Y)}L{F(pa.X)} {F(pa.Y)}L{F(c.X)} {F(c.Y)}Z\"/>");
foreach (var f in new[] { tl, tr, bl })
sb.Append(Dot(map.Map(f.U, f.V), 5));
sb.Append(Dot(pa, 3.5));
return ["det|found centre", "tick|one module, near and far", "pred|alignment search", "est|parallelogram estimate", "detd|four-point anchors"];
},
[4, 5, 6, 8, 10],
"UUUSKKKSKCCCSU", 8);
// Grey edges and wrong modules
InputFigure(Path.Combine(qrDir, "decode-input-degraded.svg"), qrBoxes,
(sb, x, y, s) =>
{
var map = Square(25, x + 20, y + 20, s - 40);
sb.Append($"<g filter=\"url(#soft)\">{Symbol(map, damaged)}</g>");
foreach (var (r, c) in flips)
sb.Append($"<path class=\"err\" d=\"{Poly(map, c - 0.1, r - 0.1, c + 1.1, r + 1.1)}\"/>");
foreach (var f in new[] { tl, tr, bl })
sb.Append(Dot(map.Map(f.U, f.V), 4));
return ["det|refined centre", "err|wrong module"];
},
[9, Bar],
"UUUSUUUSUCCCSK", 8,
"<filter id=\"soft\" x=\"-5%\" y=\"-5%\" width=\"110%\" height=\"110%\"><feGaussianBlur stdDeviation=\"1.2\"/></filter>");
// Thin rings: the top-left finder's row that reads 1:1:3:1:1, and the column through its centre, which reads only by like edges
InputFigure(Path.Combine(qrDir, "decode-input-thin-rings.svg"), qrBoxes,
(sb, x, y, s) =>
{
var map = Rotated(25, x + 20, y + 20, s - 40, ThinTurn);
sb.Append(SpreadSymbol(map, v2, ThinSpread));
// In the render's pixels, then scaled into the picture
var render = Rotated(25, 0, 0, ThinPx, ThinTurn);
var thin = Render(v2, render, ThinPx, ThinPx, 4, null, false, false, ThinSpread);
var threshold = Otsu(thin);
var (cx, cy) = render.Map(tl.U, tl.V);
var row = (int)cy + Enumerable.Range(-3, 7).First(dy => FinderRuns(thin, ThinPx, (int)cx, (int)cy + dy, 1, 0, threshold) is { } runs && IsRatio(runs));
var k = (s - 40) / ThinPx;
var reach = 5.5 * render.Map(1, 0).X - 5.5 * render.Map(0, 0).X;
(double X, double Y) At(double px, double py) => (x + 20 + px * k, y + 20 + py * k);
sb.Append(Line(At(cx - reach, row + 0.5), At(cx + reach, row + 0.5), "row"));
sb.Append(LikeLine(At((int)cx + 0.5, cy - reach), At((int)cx + 0.5, cy + reach)));
foreach (var f in new[] { tl, tr, bl })
sb.Append(Dot(map.Map(f.U, f.V), 4));
return ["det|found centre", "row|a row reading 1:1:3:1:1", "like|read by like edges"];
},
[1],
"UKUSUUUSUCCCSU", 8);
// Uneven lighting
InputFigure(Path.Combine(qrDir, "decode-input-lighting.svg"), qrBoxes,
(sb, x, y, s) =>
{
var map = Square(25, x + 20, y + 20, s - 40);
sb.Append(Symbol(map, v2));
// The rendered shadow: across its edge along the diagonal, the light falls by half
var scale = (s - 40) / (33.0 * 4);
var from = x + 20 + (33 * 4 / 2.0 - 6) * scale; var to = x + 20 + (33 * 4 / 2.0 + 6) * scale;
var fromY = from - x + y; var toY = to - x + y;
sb.Append($"<linearGradient id=\"shadow\" gradientUnits=\"userSpaceOnUse\" x1=\"{F(from)}\" y1=\"{F(fromY)}\" x2=\"{F(to)}\" y2=\"{F(toY)}\"><stop offset=\"0\" stop-color=\"#000000\" stop-opacity=\"0\"/><stop offset=\"0.5\" stop-color=\"#000000\" stop-opacity=\".25\"/><stop offset=\"1\" stop-color=\"#000000\" stop-opacity=\".5\"/></linearGradient>");
sb.Append($"<path fill=\"url(#shadow)\" d=\"{Poly(map, -4, -4, 29, 29)}\"/>");
// The blocks the regional threshold averages over: two modules a side at the rendered density
var blocks = new StringBuilder();
for (var k = -2; k <= 27; k += 2)
{
blocks.Append(Line(map.Map(k, -2), map.Map(k, 27), "blk"));
blocks.Append(Line(map.Map(-2, k), map.Map(27, k), "blk"));
}
sb.Append(blocks);
return ["shade|soft shadow", "blk|regional threshold block"];
},
[0, 0],
"KUUSUUUSUSCCSU", 8);
// Low density
InputFigure(Path.Combine(qrDir, "decode-input-low-density.svg"), qrBoxes,
(sb, x, y, s) =>
{
// The render itself, pixel by pixel
const int px = 43;
var raster = Render(v2, Square(25, 0, 0, px), px, px, 1, null, false, false);
var cell = (s - 40) / px;
var dark = new StringBuilder();
for (var r = 0; r < px; r++)
for (var c = 0; c < px; c++)
if (raster[r * px + c] < 128)
dark.Append($"M{F(x + 20 + c * cell)} {F(y + 20 + r * cell)}h{F(cell)}v{F(cell)}h{F(-cell)}Z");
sb.Append($"<rect fill=\"#ffffff\" stroke=\"#d0d7de\" x=\"{F(x + 20)}\" y=\"{F(y + 20)}\" width=\"{F(px * cell)}\" height=\"{F(px * cell)}\"/>");
sb.Append($"<path class=\"ink\" d=\"{dark}\"/>");
var pixelGrid = new StringBuilder();
for (var k = 0; k <= px; k++)
{
pixelGrid.Append($"M{F(x + 20 + k * cell)} {F(y + 20)}v{F(px * cell)}");
pixelGrid.Append($"M{F(x + 20)} {F(y + 20 + k * cell)}h{F(px * cell)}");
}
sb.Append($"<path stroke=\"#8c959f\" stroke-opacity=\".45\" stroke-width=\".5\" fill=\"none\" d=\"{pixelGrid}\"/>");
// Module boundaries read off the two timing patterns: module row 6 and module column 6, finder to finder
var map = Square(25, 0, 0, px);
for (var k = 7; k <= 18; k++)
{
var b = map.Map(k, 6.5); var bx = x + 20 + Math.Round(b.X) * cell;
sb.Append(Line((bx, y + 20 + map.Map(0, 6).Y * cell - 2), (bx, y + 20 + map.Map(0, 7).Y * cell + 2), "tick"));
var d = map.Map(6.5, k); var dy = y + 20 + Math.Round(d.Y) * cell;
sb.Append(Line((x + 20 + map.Map(6, 0).X * cell - 2, dy), (x + 20 + map.Map(7, 0).X * cell + 2, dy), "tick"));
}
return ["tick|module boundary", "px|pixel"];
},
[1, 3, 3],
"UKUKSSSSSSSSSU", 8);
// Light on dark
InputFigure(Path.Combine(qrDir, "decode-input-light-on-dark.svg"), qrBoxes,
(sb, x, y, s) =>
{
var map = Square(25, x + 20, y + 20, s - 40);
sb.Append(Symbol(map, v2, "#ffffff", "#1f2328"));
foreach (var f in new[] { tl, tr, bl })
sb.Append(Dot(map.Map(f.U, f.V), 5));
return ["det|found centre"];
},
[0, 0],
"KUUSUUUSUSSCSU", 8);
// Large version: the mesh, with the bottom-right alignment pattern lost
InputFigure(Path.Combine(qrDir, "decode-input-large-version.svg"), qrBoxes,
(sb, x, y, s) =>
{
var map = Keystone(73, x + 20, y + 20, s - 40, 0.12);
sb.Append(Symbol(map, v14));
// Annex E alignment coordinates of version 14
int[] coords = [6, 26, 46, 66];
var lattice = new StringBuilder();
foreach (var cc in coords)
{
lattice.Append(Line(map.Map(coords[0] + 0.5, cc + 0.5), map.Map(coords[^1] + 0.5, cc + 0.5), "lat"));
lattice.Append(Line(map.Map(cc + 0.5, coords[0] + 0.5), map.Map(cc + 0.5, coords[^1] + 0.5), "lat"));
}
sb.Append(lattice);
// The coordinate-6 row and column are extrapolated, and the painted-over node is predicted from the others
foreach (var r in coords)
foreach (var c in coords)
{
var p = map.Map(c + 0.5, r + 0.5);
sb.Append(r == 6 || c == 6 || (r == 66 && c == 66) ? $"<circle class=\"predr\" cx=\"{F(p.X)}\" cy=\"{F(p.Y)}\" r=\"3\"/>" : Dot(p, 3));
}
return ["det|found node", "predr|predicted node", "lat|mesh"];
},
[7],
"UUUSUUUKCCCCSU", 8);
// ---------- The Micro QR input figures ----------
// The Micro QR image-level outline's stages, in its order
string[] microBoxes =
[
"Binarization pass",
"Finder candidates",
"Module sizes and centre",
"Sizes M4 to M1",
"Coverage re-read",
"Timing frame",
"Low density",
"Arbitrary orientation",
"Scale search",
"Perspective search",
];
// Past the first size's grid, every stage runs only when the grids before it failed
const int MicroDashedFrom = 3;
// A render drawn pixel by pixel, filling the picture, each pixel at its own grey. Returns the size of one pixel.