summaryrefslogtreecommitdiff
path: root/graphics/pgf/contrib/tikz-nfold/tikzlibrarynfold.code.tex
blob: da48d7b62b4730357e80ddead4ed8f461dbe3a92 (plain)
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
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
%% tikz-nfold.sty
%% Copyright 2023 Jonathan Schulz
%
% This work may be distributed and/or modified under the
% conditions of the LaTeX Project Public License, either version 1.3c
% of this license or (at your option) any later version.
% The latest version of this license is in
% http://www.latex-project.org/lppl.txt
% and version 1.3c or later is part of all distributions of LaTeX
% version 2008-05-04 or later.
%
% This work has the LPPL maintenance status 'maintained'.
%
% The Current Maintainer of this work is Jonathan Schulz.
%
% This work consists of the files pgflibrarybezieroffset.code.tex,
% tikzlibrarynfold.code.tex, tikz-nfold-doc.tex, and tikz-nfold-doc.pdf.

\usetikzlibrary{arrows.meta}
\usepgflibrary{bezieroffset}


%
% General idea
% ============
%
% In order to offset a path, we must first analyse and slightly modify it. For example,
% the start and end points of segments need to be relocated slightly in order to make room
% for the joins, and most curves must be subdivided for the offsetting algorithm. To avoid
% redundant computations in n-fold paths, we pre-compute as much data as possible and store
% all this information in a "parsed path" macro. The structure of the parsed path resembles
% the structure of a pgf softpath, but it consists of different tokens.
%



%
% Intercepting join settings
% --------------------------
%
% The current settings of the line joins are not stored in any TeX registers; instead, direct system
% calls are made to apply the settings. Therefore, we need to modify the pgf macros in order
% to cache the current settings.
%

% According to the pgf documentation, miter limit=10 is the default value,
% but I couldn't find and verify this setting in the pgf code
\gdef\pgf@nfold@cached@miterlimit{10}
\let\pgf@nfold@old@miterlimit\pgfsetmiterlimit
\def\pgfsetmiterlimit#1{%
  \pgf@nfold@old@miterlimit{#1}%
  \edef\pgf@nfold@cached@miterlimit{#1}%
}

% default line join is "miter"
\global\let\pgf@cached@linejoin=m% % b = bevel, m=miter, r=round
\let\pgf@nfold@old@setbeveljoin\pgfsetbeveljoin
\let\pgf@nfold@old@setmiterjoin\pgfsetmiterjoin
\let\pgf@nfold@old@setroundjoin\pgfsetroundjoin
\def\pgfsetbeveljoin{%
  \pgf@nfold@old@setbeveljoin%
  % do NOT change this globally! Needs to be changed back at the end of groups for scoping reasons
  \let\pgf@cached@linejoin=b%
}
\def\pgfsetmiterjoin{%
  \pgf@nfold@old@setmiterjoin%
  \let\pgf@cached@linejoin=m%
}
\def\pgfsetroundjoin{%
  \pgf@nfold@old@setroundjoin%
  \let\pgf@cached@linejoin=r%
}


%
% Joining offset lines
% --------------------
%
% One of the more difficult aspects is joining the segments of an offset path. Without this step,
% the path would be interrupted or self-intersect whenever there is a non-zero angle between
% two segments. This code reproduces the existing line joins "bevel", "miter" and "round".
%

\def\pgf@nfold@miterjoin{
  % The tip of the miter join is computed starting from the original (unshifted) centre of the join;
  % we then move orthorgonal to the average of the old and new angle
  \pgfpathlineto{
    \pgfpointadd{\pgf@nfold@join@centre}{%
      \pgfpointpolar{\pgf@nfold@firstang+.5*\pgf@nfold@deltaphi+90}% do not change
        {\pgf@nfold@shiftamount/cos(.5*\pgf@nfold@deltaphi)}%
    }%
  }%
}

\def\pgf@nfold@beveljoin{
  % The bevel join for one component line consists of three parts:
  % 1) an extension of the ingoing line,
  % 2) a middle line, angled at the average of the incoming and outgoing line,
  % 3) an extension of the outgoing line.
  % Different components of the ingoing and outgoing lines have a constant distance from each other.
  % For a good-looking output, the mittle parts of the component lines thus should also have a constant distance,
  % which is a non-trivial condition. To generate such an output the outer lines get a bevel-like join
  % and the inner lines get a miter-like join; the threshold depends on deltaphi.
  % We first compute by how much the outermost line must be continued from the beginning of the join.
  % The protrusion amount must be lowered by a little bit for a rather complicated reason: The offset would be
  % dead on if the outermost offset line were centered on the _edge_ of the wide line, but we want to draw 
  % the outside line _fully inside_ the wide line. The factor of tan(deltaphi/4) can be derived, but is not obvious.
  \pgfmathsetlengthmacro{\bevelouterprotrusion}%
    {\pgf@nfold@shortenstartjoin pt - .5*\pgflinewidth*abs(tan(.25*\pgf@nfold@deltaphi))}
  % The following applies to middle lines only: We compute by how much they need to be shortened so the distance
  % between the lines in the join is correct.
  \pgfmathsetmacro{\bevelshorten}{2*\insidepercentage*abs(tan(.25*\pgf@nfold@deltaphi))}
  % This threshold decides if the inside line has a bevel or a miter join
  \pgfmathparse{\bevelshorten < abs(sin(.5*\pgf@nfold@deltaphi))}
  \ifnum\pgfmathresult=1\relax
    \pgfmathsetlengthmacro{\bevelextension}{\bevelouterprotrusion-\bevelshorten*\pgf@nfold@hwidth}
    \pgfpointadd{\pgf@nfold@join@start}{\pgfpointpolar{\pgf@nfold@firstang}{\bevelextension}}
    \pgfpathlineto{}
    \pgfpointadd{\pgf@nfold@join@end}{\pgfpointpolar{\pgf@nfold@secondang}{-\bevelextension}}
    \pgfpathlineto{}
  \else
    \pgf@nfold@miterjoin
  \fi
}

\def\pgf@nfold@roundjoin{
  % The outer half of the lines get arcs, the others get miters
  \ifdim\insidepercentage pt<.5pt\relax
    \pgfpointadd{\pgf@nfold@join@start}{\pgfpointpolar{\pgf@nfold@firstang}{\pgf@nfold@shortenstartjoin}}
    \pgfpathlineto{}
    % TODO needs unit tests for all cases left, right, across the 360 gap etc.
    \pgfmathsetmacro\pgf@tmp@firstang{\pgf@nfold@firstang+90*\turnindicator}
    \pgfpatharc%
      {\pgf@tmp@firstang}%
      {\pgf@tmp@firstang+\pgf@nfold@deltaphi}%
      {abs(\pgf@nfold@shift@fraction)*\pgf@nfold@hwidth}%
  \else
    \pgf@nfold@miterjoin
  \fi
}

% The handler that will be added to the parsed path
% #1: The centre of the join
% #2: The end point of the first segment
% #3: The starting point of the second segment
% #4: The angle of the first segment
% #5: The angle of the second segment
% #6: deltaphi in the range [-180, 180]
% #7: the distance between #1 and #2
% #8: the join + finish macro
\def\pgf@nfold@token@join#1#2#3#4#5#6#7#8{%
  \def\pgf@nfold@join@centre{#1}%
  \def\pgf@nfold@join@prevend{#2}%
  \def\pgf@nfold@join@nextstart{#3}%
  \def\pgf@nfold@firstang{#4}%
  \def\pgf@nfold@secondang{#5}%
  % Offset the start and end of this join
  \pgfextract@process\pgf@nfold@join@start{%
    \pgfpointadd{#2}{\pgfpointpolar{\pgf@nfold@firstang+90}{\pgf@nfold@shiftamount}}}%
  \pgfextract@process\pgf@nfold@join@end{%
    \pgfpointadd{#3}{\pgfpointpolar{\pgf@nfold@secondang+90}{\pgf@nfold@shiftamount}}}%
  \pgf@process{\pgfpointdiff{\pgf@nfold@join@start}{\pgf@nfold@join@end}}
  % Check if the start of this segment is very close to the end of the previous segment.
  % In that case we don't need a join at all
  \pgfpointtaxicabnorm\pgfutil@tempdima
  \ifdim\pgfutil@tempdima>0.1pt\relax
    \def\pgf@nfold@deltaphi{#6}%
    \def\pgf@nfold@shortenstartjoin{#7}%
    % First step: Check if left or right turn (-1=left, 1=right)
    \ifdim\pgf@nfold@deltaphi pt<0pt
      \def\turnindicator{1}
    \else
      \def\turnindicator{-1}
    \fi
    % \insidepercentage: between 0.0 and 1.0;
    % 0=no distance to cover in the join, 1=maximum distance to cover
    \pgfutil@tempdima=\pgf@nfold@shift@fraction pt\relax
    \pgfutil@tempdima=\turnindicator\pgfutil@tempdima
    \advance\pgfutil@tempdima by-1pt\relax
    \pgfutil@tempdima=-.5\pgfutil@tempdima
    % \insidepercentage  = .5 * (1 - \turnindicator*\pgf@nfold@shift@fraction)
    \edef\insidepercentage{\pgf@sys@tonumber\pgfutil@tempdima}%
    #8%
  \fi
}


%
% Parser: Join handler
%
\def\pgf@nfold@parser@handlejoin{%
  % \pgf@xa := abs(deltaphi@start)
  \pgf@xa=\pgf@nfold@deltaphi@start pt\relax
  \ifdim\pgf@xa<0pt\relax
    \pgf@xa=-\pgf@xa
  \fi
  % Skip the entire join if abs(deltaphi) is too small
  \ifdim\pgf@xa>1pt\relax
    \edef\pgf@nfold@jointype{\pgf@cached@linejoin}
    \if\pgf@cached@linejoin m% \ifx is not needed because both are only one character
      % miter join
      % First we implement the miter limit: If the angle is too sharp, the miter join is replaced
      % by a bevel join. This is controlled by /tikz/miter limit=..., initially 10.
      \pgf@xa=.5\pgf@xa
      \pgfmathcos@{\pgf@sys@tonumber\pgf@xa}
      \pgf@xa=\pgfmathresult pt\relax
      \pgf@xa=\pgf@nfold@cached@miterlimit\pgf@xa
      % Switch to bevel if miterlimit*cos(.5*abs(deltaphi)) <= 1
      \ifdim\pgf@xa>1pt\relax
        \def\pgf@nfold@tmp@joinmacro{\pgf@nfold@miterjoin}
      \else
        \def\pgf@nfold@tmp@joinmacro{\pgf@nfold@beveljoin}
      \fi
    \else
      \if b\pgf@cached@linejoin\relax
        \def\pgf@nfold@tmp@joinmacro{\pgf@nfold@beveljoin}
      \else
        \def\pgf@nfold@tmp@joinmacro{\pgf@nfold@roundjoin}
      \fi
    \fi
    % The last parameter is a macro to be called when this segment of the join is non-trivial.
    % It consists of
    %   - the macro to actually draw the join,
    %   - either finish@normal or finish@edgecase.
    \edef\pgf@nfold@macrotoadd{%
      \noexpand\pgf@nfold@token@join{\pgf@nfold@cur@first}{\pgf@nfold@prev@segment@end}
        {\pgf@nfold@cur@movedfirst}{\pgf@nfold@prev@angle@ii}{\pgf@nfold@cur@angle@i}%
        {\pgf@nfold@deltaphi@start}{\pgf@nfold@shortenstartjoin}{%
          \expandafter\noexpand\pgf@nfold@tmp@joinmacro%
          \expandafter\noexpand\ifpgf@nfold@closejoinsedgecase%
            \pgf@nfold@token@finish@edgecase{\pgf@nfold@cur@movedlast}%
          \else%
            \pgf@nfold@token@finish@normal%
          \fi%
        }%
    }%
    \pgf@nfold@addmacro\pgf@parsed@cur@conn@seg%
  \fi% end if abs(deltaphi) > 1
}


% All non-trivial joins connect to the end of the join, which is the starting point of the next segment.
% Note that this entire macro is skipped by if the start and end of the join coincide, so we never create a zero length segment here.
%
% There is one edge case here: If two subsequent joins are so close that \pgf@nfold@cur@movedlast
% and \pgf@nfold@cur@movedfirst exchange places *and* we are on the outside of the first join 
% (implying that we are on the inside of the second join), the first join must not connect all the way to
% to \pgf@nfold@cur@movedfirst, because that would overshoot the second join. Instead we connect to
% \pgf@nfold@cur@movedlast (which is *closer* to the first join than \pgf@nfold@cur@movedfirst in this edge case).
% To accomodate for the vertical offset we connect to \pgf@nfold@join@end which is the vertical
% offset of \pgf@nfold@cur@movedlast by definition.
\def\pgf@nfold@token@finish@normal{%
  \pgfpathlineto{\pgf@nfold@join@end}%
}

% parameter #1: @movedlast of the next segment
\def\pgf@nfold@token@finish@edgecase#1{%
  \pgf@nfold@join@end%
  \ifdim\insidepercentage pt<.5pt\relax%
    \pgf@process{\pgfpointadd{#1}{\pgfpointpolar{\pgf@nfold@secondang+90}{\pgf@nfold@shiftamount}}}
  \fi%
  \pgfpathlineto{}%
}


%
% Main rendering pipeline
% -----------------------
%

% This stores whether the current segment should begin with a moveto to its offset
\newif\ifpgf@nfold@continuesegment
% This stores whether we are in some edge case of very close joins, see below for details
\newif\ifpgf@nfold@closejoinsedgecase
% This stores whether we are in an error case where we need to avoid dividing by zero
\newif\ifpgf@nfold@angletoosharp
% This stores whether we need the intersections library for an arrow tip but it is not loaded
\newif\ifpgf@nfold@intersectionsnotloaded


\def\pgf@nfold@parser@handlesegment{%
  \if\pgf@nfold@cur@visible 0
    % first, last and moveto are invisible
    \if\pgf@nfold@cur@type m
      % We don't need to do anything for a moveto: If a visible segment follows, it will move to
      % its starting location by itself. However, we might need to draw the arrow tip extension 
      % at the start (if present).
      \if\pgf@nfold@start@arrowcode1
        \if\pgf@nfold@prev@type f
          \if\pgf@nfold@next@visible1
            \edef\pgf@nfold@macrotoadd{%
              \noexpand\pgf@nfold@extendtotip{s}{\pgf@nfold@cur@last}{\pgf@nfold@next@angle@i}
            }%
            \pgf@nfold@addmacro\pgf@parsed@cur@conn@seg%
            % hack: We make the next segment believe that this segment was a lineto
            % so the path does not get interrupted
            \let\pgf@nfold@cur@type l
            \let\pgf@nfold@cur@visible 1
            \let\pgf@nfold@cur@angle@ii\pgf@nfold@next@angle@i
            \let\pgf@nfold@cur@tang@ii\pgf@nfold@next@tang@i
          \fi
        \fi%
      \fi
    \fi%
  \else%
    \let\pgf@nfold@cur@movedfirst\pgf@nfold@cur@first
    \let\pgf@nfold@cur@movedlast\pgf@nfold@cur@last
    %%% Step 1: Make room for joins if necessary
    % In order to make room for the join, it may be necessary to shorten the current segment
    % at the start and/or the end. In here we store by how much the segment needs to be shortened.
    \def\pgf@nfold@shortenstartjoin{0}
    \def\pgf@nfold@shortenendjoin{0}
    \pgf@nfold@closejoinsedgecasefalse
    \pgf@nfold@angletoosharpfalse
    % Step 1.1: Make room for the join at the start if needed
    \if\pgf@nfold@prev@visible1
      \pgf@nfold@continuesegmenttrue
      % TODO can we just use deltaphi@end from the previous round?
      % Compute the angle difference at the start (between -180 and +180 degrees)
      % using \pgfmathsubtract@ is more readable and no less efficient than computing this manually
      \pgfmathsubtract@{\pgf@nfold@cur@angle@i}{\pgf@nfold@prev@angle@ii}
      \pgf@nfold@clampangle
      \edef\pgf@nfold@deltaphi@start{\pgfmathresult}
      \pgf@xb=\pgf@nfold@deltaphi@start pt\relax
      \ifdim\pgf@xb<0pt\relax
        \pgf@xb=-\pgf@xb
      \fi
      \ifdim\pgf@xb>178pt\relax
        % we go full backwards, don't relocate the start and disable the join to avoid division by zero
        % don't need an error message here, it has already been displayed in the previous segment
        \pgf@nfold@angletoosharptrue
      \else
        \ifdim\pgf@xb>0.5pt\relax
          % make room for the start join if the angle is nonzero;
          % shortenstartjoin := hwidth*tan(.5*abs(deltaphi@start))
          \pgf@yb=.5\pgf@xb
          \pgfmathtan@{\pgf@sys@tonumber\pgf@yb}
          \pgf@yb=\pgf@nfold@hwidth\relax
          \pgf@yb=\pgfmathresult\pgf@yb
          \edef\pgf@nfold@shortenstartjoin{\pgf@sys@tonumber\pgf@yb}
          \pgfextract@process\pgf@nfold@cur@movedfirst{%
            \pgfpointadd{\pgf@nfold@cur@first}%
                        {\pgfqpointscale{\pgf@nfold@shortenstartjoin}{\pgf@nfold@cur@tang@i}}}%
          % If the current segment is a curve, we need to relocate @supporta point as well,
          % as otherwise the @first point could overtake it
          \if\pgf@nfold@cur@type c
            \pgf@process{\pgfpointdiff{\pgf@nfold@cur@first}{\pgf@nfold@cur@supporta}}
            \pgfmathveclen@{\pgf@sys@tonumber\pgf@x}{\pgf@sys@tonumber\pgf@y}
            \ifdim\pgfmathresult pt>0.1pt\relax
              % regular curves (supporta != first):
              % Increase dist(first, supporta) to sqrt(a^2 + b^2) where a=dist(first, supporta) and b=shortenstart. This way, the order of first and supporta is guaranteed to be preserved, and the change to supporta is as small as reasonably possible.
              \pgfmathveclen@{\pgfmathresult}{\pgf@sys@tonumber\pgf@yb}
              \pgfextract@process\pgf@nfold@cur@supporta{\pgfpointadd%
                {\pgf@nfold@cur@first}%
                % TODO migrate to tangent
                {\pgfqpointpolar{\pgf@nfold@cur@angle@i}{\pgfmathresult pt}}}%
            \else
              % special treatment for singular curves (supporta = first) to avoid rounding error glitches.
              % In this special case, a slight corner at the end of the join is unavoidable unless we
              % also relocate @supportb, which may have unintended side effects
              \let\pgf@nfold@cur@supporta\pgf@nfold@cur@movedfirst
            \fi
          \fi
        \fi
      \fi
    \else
      \pgf@nfold@continuesegmentfalse
    \fi
    % Step 1.2: Make room for the join at the end if needed
    \if\pgf@nfold@next@visible1
      % Compute the angle difference at the start (between -180 and +180 degrees)
      % using \pgfmathsubtract@ is more readable and no less efficient than computing this manually
      \pgfmathsubtract@{\pgf@nfold@next@angle@i}{\pgf@nfold@cur@angle@ii}
      \pgf@nfold@clampangle
      \edef\pgf@nfold@deltaphi@end{\pgfmathresult}
      \pgf@xb=\pgf@nfold@deltaphi@end pt\relax
      \ifdim\pgf@xb<0pt\relax
        \pgf@xb=-\pgf@xb
      \fi
      \ifdim\pgf@xb>178pt\relax
        \pgfutil@packagewarning{tikz-nfold}{Angle too sharp, expect visual errors}
        \pgf@nfold@angletoosharptrue
      \else
        \ifdim\pgf@xb>0.5pt\relax
           % make room for the start join if the angle is nonzero
          % shortenendjoin := hwidth*tan(.5*abs(deltaphi@end))
          \pgf@yb=.5\pgf@xb
          \pgfmathtan@{\pgf@sys@tonumber\pgf@yb}
          \pgf@yb=\pgf@nfold@hwidth\relax
          \pgf@yb=\pgfmathresult\pgf@yb
          \edef\pgf@nfold@shortenendjoin{\pgf@sys@tonumber\pgf@yb}
          \pgf@yb=-\pgf@yb
          \pgfextract@process\pgf@nfold@cur@movedlast{%
            % the use of the minus sign is fine here because \pgf@nfold@shortenendjoin >= 0.0
            \pgfpointadd{\pgf@nfold@cur@last}%
              {\pgfqpointscale{-\pgf@nfold@shortenendjoin}{\pgf@nfold@cur@tang@ii}}}%
          \pgfextract@process\pgf@nfold@cur@movedlast{%
            \pgfpointadd{\pgf@nfold@cur@last}%
              {\pgfqpointpolar{\pgf@nfold@cur@angle@ii}{\pgf@yb}}}%
          \if\pgf@nfold@cur@type c
            % Same procedure as above: relocate supportb if we have a curve
            \pgf@process{\pgfpointdiff{\pgf@nfold@cur@supportb}{\pgf@nfold@cur@last}}
            \pgfmathveclen@{\pgf@sys@tonumber\pgf@x}{\pgf@sys@tonumber\pgf@y}
            \ifdim\pgfmathresult pt>0.1pt\relax
              \pgfmathveclen@{\pgfmathresult}{\pgf@sys@tonumber\pgf@yb}
              % can use qpoint and minus because \pgfmathresult is guaranteed to be positive
              \pgfextract@process\pgf@nfold@cur@supportb{\pgfpointadd%
                {\pgf@nfold@cur@last}%
                % TODO migrate to tangent
                {\pgfqpointpolar{\pgf@nfold@cur@angle@ii}{-\pgfmathresult pt}}}%
            \else
              \let\pgf@nfold@cur@supportb\pgf@nfold@cur@movedlast
            \fi
          \fi
        \fi
      \fi
      % Step 1.3: Detect an edge case
      % This edge case appears whenever the current segment is such a short line that we would
      % have to reduce its length to less than zero to make space for the joins. In such cases,
      % the line is not drawn at all, and slight modifications must be made to the joins to ensure
      % a correct output (i.e. one join is immediately followed by the next without a segment in between).
      %
      % This edge case can appear for curves as well, but they are much harder to deal with.
      \if\pgf@nfold@cur@type l
        % No need to check for \pgf@nfold@inputsegmentclosepath as it should not be followed by any further segments
        % Now: Check if the total amount of shortening is larger than the length of the segment
        \pgf@process{\pgfpointdiff{\pgf@nfold@cur@first}{\pgf@nfold@cur@last}}
        \pgfmathveclen@{\pgf@sys@tonumber\pgf@x}{\pgf@sys@tonumber\pgf@y}
        \pgf@xa=\pgf@nfold@shortenstartjoin pt\relax
        \advance\pgf@xa by\pgf@nfold@shortenendjoin pt\relax
        \ifdim\pgf@xa>\pgfmathresult pt\relax
          \pgf@nfold@closejoinsedgecasetrue
        \fi
      \fi
    \fi% end if next segment visible
    %
    % Step 2.1: Draw the join at the start if applicable
    %
    \if\pgf@nfold@prev@visible0%
      \ifpgf@nfold@closejoinsedgecase
        % If the previous segment is a moveto and the current segment is a "close joins" edge case,
        % nothing needs to be drawn here (the relevant draw call will be made at the join of the subsequent
        % segment). We must therefore make sure that we move to the correct end point of this segment.
        % Counterintuitively, this is given by the offset of \pgf@nfold@cur@movedfirst since the start and end
        % are reversed in the edge case.
        \edef\pgf@nfold@macrotoadd{%
          \noexpand\pgf@nfold@token@edgecase@movetostart{\pgf@nfold@cur@movedfirst}{\pgf@nfold@cur@angle@i}%
        }%
        \pgf@nfold@addmacro\pgf@parsed@cur@conn@seg%
      \fi
    \else
      % If we draw the join when the start angle is close to 180 degrees, we get a division by zero
      \ifpgf@nfold@angletoosharp\else
        \pgf@nfold@parser@handlejoin
      \fi
    \fi
    % Step 2.2: Store where the current (non-offset) end point was relocated
    % in order to make space for the end join. This may be used if the next
    % segment begins with a join
    \let\pgf@nfold@prev@segment@end\pgf@nfold@cur@movedlast
    %
    % Step 3: Draw the new segment.
    %
    % The value of \ifpgf@nfold@continuesegment decides whether we start with a moveto.
    % curveto
    \if\pgf@nfold@cur@type l
      % In the edge case, one join is followed immediately by the next. The line segment
      % thus has a negative length and will be skipped.
      \ifpgf@nfold@closejoinsedgecase\else
        \edef\pgf@nfold@macrotoadd{%
          \expandafter\noexpand\ifpgf@nfold@continuesegment%
            \pgf@nfold@token@lineto@continue%
          \else%
            \pgf@nfold@token@lineto%
          \fi{\pgf@nfold@cur@movedfirst}{\pgf@nfold@cur@movedlast}{\pgf@nfold@cur@tang@i}%
        }%
        \pgf@nfold@addmacro\pgf@parsed@cur@conn@seg%
      \fi
    \fi
    \if\pgf@nfold@cur@type o
      \def\pgf@nfold@macrotoadd{\pgf@nfold@token@closepath}%
      \pgf@nfold@addmacro\pgf@parsed@cur@conn@seg%
    \fi
    \if\pgf@nfold@cur@type c
      \ifpgf@nfold@continuesegment
        \pgf@subdividecurve{\pgf@nfold@cur@movedfirst}{\pgf@nfold@cur@supporta}{\pgf@nfold@cur@supportb}{\pgf@nfold@cur@movedlast}{\pgf@offset@max@recursion}{0}{\pgf@nfold@addcurvesegment@callback@continue}
      \else
        \pgf@subdividecurve{\pgf@nfold@cur@movedfirst}{\pgf@nfold@cur@supporta}{\pgf@nfold@cur@supportb}{\pgf@nfold@cur@movedlast}{\pgf@offset@max@recursion}{0}{\pgf@nfold@addcurvesegment@callback}%
      \fi
    \fi
    \if\pgf@nfold@cur@type i
      \edef\pgf@nfold@macrotoadd{%
        \noexpand\pgf@nfold@token@invisibleline{\pgf@nfold@cur@movedfirst}{\pgf@nfold@cur@movedlast}{\pgf@nfold@cur@tang@i}%
      }%
      \pgf@nfold@addmacro\pgf@parsed@cur@conn@seg%
    \fi
    % Step 4: Extend into the arrow tip at the end (if present)
    \if\pgf@nfold@next@type t%
      \ifnum\pgf@nfold@end@arrowcode=1
        \edef\pgf@nfold@macrotoadd{%
          \noexpand\pgf@nfold@extendtotip{e}{\pgf@nfold@cur@last}{\pgf@nfold@cur@angle@ii}}%
        \pgf@nfold@addmacro\pgf@parsed@cur@conn@seg%
      \fi%
    \fi%
  \fi% end if current visible
}


\def\pgf@nfold@addcurvesegment@callback#1#2#3#4#5{%
  \if#50%
    \edef\pgf@nfold@macrotoadd{%
      % The subdivision algorithm has already computed the tangents
      \noexpand\pgf@nfold@token@curveto{#1}{#2}{#3}{#4}{\pgf@tmp@tang@i}{\pgf@tmp@tang@ii}%
    }%
    \pgf@nfold@addmacro\pgf@parsed@cur@conn@seg%
  \else%
    \pgf@nfold@addcurvesegment@callback@continue{#1}{#2}{#3}{#4}{#5}%
  \fi%
}

\def\pgf@nfold@addcurvesegment@callback@continue#1#2#3#4#5{%
  % The subdivision algorithm has already computed the tangents
  \edef\pgf@nfold@macrotoadd{%
    \noexpand\pgf@nfold@token@curveto@continue{#1}{#2}{#3}{#4}{\pgf@tmp@tang@i}{\pgf@tmp@tang@ii}%
  }%
  \pgf@nfold@addmacro\pgf@parsed@cur@conn@seg%
}


% Rendering arrow tips
% --------------------

% Precomputed intersections
%
% For arrows of order n > 2 with an Implies tip, the constituent parts of the n-fold arrow
% end somewhere in the middle of the tip. The exact end point must be computed using
% the intersections library. To speed up compilation times, the intersection points are precomputed
% up to n = 5. If your document contains arrows of order 6 or larger, consider adding those
% as well; the values are output in the log file.
\expandafter\def\csname pgf@nfold@intersec@cache@2@3\endcsname{\pgfqpoint{2pt}{0pt}}
\expandafter\def\csname pgf@nfold@intersec@cache@2@4\endcsname{\pgfqpoint{0.94063pt}{-0.33333pt}}
\expandafter\def\csname pgf@nfold@intersec@cache@3@4\endcsname{\pgfqpoint{0.94063pt}{0.33333pt}}
\expandafter\def\csname pgf@nfold@intersec@cache@2@5\endcsname{\pgfqpoint{0.64167pt}{-0.5pt}}
\expandafter\def\csname pgf@nfold@intersec@cache@3@5\endcsname{\pgfqpoint{2pt}{0pt}}
\expandafter\def\csname pgf@nfold@intersec@cache@4@5\endcsname{\pgfqpoint{0.64167pt}{0.5pt}}
% intersections are precomputed up to this order
\def\pgf@nfold@intersec@numcached{5}

% This macro extends the arrow body to the tips
% #1: s=start, e=end
% #2: start/end point of the path
% #3: angle
\newif\ifpgf@nfold@ontheedge
\def\pgf@nfold@extendtotip#1#2#3{
  \ifpgf@nfold@intersectionsnotloaded
    \pgfutil@packageerror{tikz-nfold}{%
        If `nfold' is larger than \pgf@nfold@intersec@numcached\space and you use
        an `Implies' arrow tip you need to say \string\usetikzlibrary{intersections}}{}
  \else
  \pgf@nfold@ontheedgetrue
  % Do not extend the arrow for index=1 and index=order, it already ends in the right place
  \ifnum\pgf@nfold@index>1\relax\ifnum\pgf@nfold@index<\pgf@nfold@order\relax%
    \pgf@nfold@ontheedgefalse
  \fi\fi
  \ifpgf@nfold@ontheedge%
    % the extension at the start needs a moveto to the correct starting point
    \if#1s
      \pgfpathmoveto{\pgfpointadd{#2}{\pgfpointpolar{#3+90}{\pgf@nfold@shiftamount}}}%
    \fi
  \else
    % Step 1: Find the intersection of the arrow's path with the head
    \ifcsname pgf@nfold@intersec@cache@\the\pgf@nfold@index @\the\pgf@nfold@order\endcsname
      \pgfextract@process\pgf@nfold@arrowintersect
        {\csname pgf@nfold@intersec@cache@\the\pgf@nfold@index @\the\pgf@nfold@order\endcsname}%
    \else
      % the intersection has not been precomputed, thus compute on the fly here
      \pgfintersectionofpaths{
        % specify the tip
        \pgfpathmoveto{\pgfqpoint{-1.4pt}{2.65pt}}
        \pgfpathcurveto{\pgfqpoint{-0.75pt}{1.25pt}}{\pgfqpoint{1pt}{0.05pt}}{\pgfqpoint{2pt}{0pt}}
        \pgfpathcurveto{\pgfqpoint{1pt}{-0.05pt}}{\pgfqpoint{-0.75pt}{-1.25pt}}{\pgfqpoint{-1.4pt}{-2.65pt}}
      }{
        % extend the body to intersect the tip
        \pgfpathmoveto{\pgfqpoint{-3pt}{\pgf@nfold@shift@fraction pt}}
        \pgfpathlineto{\pgfqpoint{3pt}{\pgf@nfold@shift@fraction pt}}
      }
      \ifnum\pgfintersectionsolutions>0
        \pgfextract@process\pgf@nfold@arrowintersect{\pgfpointintersectionsolution{1}}%
        \immediate\write17{tikz-nfold: computed intersection cache@\the\pgf@nfold@index @\the\pgf@nfold@order: \string\pgfqpoint{\the\pgf@x}{\the\pgf@y}^^J}
        % add the new intersection to the cache
        \expandafter\xdef\csname pgf@nfold@intersec@cache@\the\pgf@nfold@index @\the\pgf@nfold@order\endcsname{\noexpand\pgfqpoint{\the\pgf@x}{\the\pgf@y}}
      \else
        % this is a failsafe and should never be reached
        \pgfutil@packagewarning{tikz-nfold}{did not find intersection}
        \pgfextract@process\pgf@nfold@arrowintersect{\pgfqpoint{0pt}{\pgf@nfold@shift@fraction pt}}%
      \fi
    \fi% if precomputed
    % Step 2: Extend the arrow body to the intersection point.
    % If the tip is at the beginning of the path, we have to move to the intersection
    % and then draw a line to the "regular" starting point. The subsequent segment then
    % should omit its moveto.
    % If the tip is at the end, we are already in the right position and only need to extend
    % the current path to the intersection point.
    \begingroup
      \pgftransformreset
      \pgftransformshift{#2}
      \pgftransformrotate{#3}
      \if#1s
        \pgftransformxscale{-1}
      \fi
      % we don't want to undo the shift by .42\pgflinewidth after the scaling
      \pgfutil@tempdima=\pgf@nfold@hwidth
      \pgfutil@tempdima=\pgf@nfold@shift@fraction\pgfutil@tempdima
      \pgfextract@process\pgf@nfold@startofextension
        {\pgfpointtransformed{\pgfqpoint{0pt}{\pgfutil@tempdima}}}
      % 0.5 - 0.06 = 0.42
      \pgftransformshift{\pgfqpoint{.42\pgflinewidth}{0pt}}
      \pgftransformscale{\pgf@nfold@hwidth}
      \pgfextract@process\pgf@nfold@arrowintersect{\pgfpointtransformed{\pgf@nfold@arrowintersect}}
      \global\let\pgf@nfold@startofextension\pgf@nfold@startofextension
      \global\let\pgf@nfold@arrowintersect\pgf@nfold@arrowintersect
    \endgroup
    \if#1s
      \pgfpathmoveto{\pgf@nfold@arrowintersect}
      % This is precisely the start of the body, shifted vertically
      \pgfpathlineto{\pgf@nfold@startofextension}
    \else\if#1e
      \pgfpathlineto{\pgf@nfold@arrowintersect}
    \else
      \pgfutil@packageerror{tikz-nfold}{Invalid argument to \string\pgf@nfold@extendtotip: \meaning#1}{}
    \fi\fi
    \pgftransformreset
    \fi% if 1 < i < nArrows
  \fi% if intersections is needed and not loaded
}

% Parsing the arrow tips
% ----------------------
%
% We need to detect if the user has set Implies[] arrows at the start and/or end tip.
% To do so, we parse \pgf@start@tip@sequence. If the user specifies Implies[] manually,
% we find that
%   pgf@start@tip@sequence=\pgf@arrow@handle{Implies}{...}
% However, in other cases (like tikz-cd) we may find 
%   \pgf@arrow@handle@shorthand@empty {\csname pgf@ar@means@tikzcd implies cap\endcsname }
% In such cases we must expand the first parameter once and then match as above.

% Set global defaults
\def\pgf@nfold@start@arrowcode{0}
\def\pgf@nfold@end@arrowcode{0}

\def\pgf@nfold@parsearrows{
  \ifpgfutil@tempswa% this is set in \pgfusepath and stores whether we draw arrow tips at all
    \expandafter\pgf@nfold@parsearrowmacro\pgf@start@tip@sequence\relax
    \let\pgf@nfold@start@arrowcode\pgf@nfold@detectedarrow
    \expandafter\pgf@nfold@parsearrowmacro\pgf@end@tip@sequence\relax
    \let\pgf@nfold@end@arrowcode\pgf@nfold@detectedarrow
  \else
    \def\pgf@nfold@start@arrowcode{0}
    \def\pgf@nfold@end@arrowcode{0}
  \fi
}

\def\pgf@nfold@parsearrowmacro#1{%
  \def\pgf@nfold@detectedarrow{0}
  \ifx#1\relax
    \let\pgf@next\relax
  \else
    \ifx#1\pgf@arrow@handle
      % found \pgf@arrow@handle{...}, now parse the first parameter
      \let\pgf@next\pgf@nfold@parse@arrow@handle
    \else
      \ifx#1\pgf@arrow@handle@shorthand@empty
        \let\pgf@next\pgf@nfold@parse@shorthandempty
      \else
        % found nothing
        \let\pgf@next\pgfutil@gobble@until@relax
      \fi
    \fi
  \fi
  \pgf@next
}

\def\pgf@nfold@param@Implies{Implies}

\def\pgf@nfold@parse@arrow@handle#1{%
  \def\pgf@tmp{#1}
  \ifx\pgf@tmp\pgf@nfold@param@Implies
    \def\pgf@nfold@detectedarrow{1}
  \fi
  \pgfutil@gobble@until@relax
}

\def\pgf@nfold@parse@shorthandempty#1{
  % Expand #1 once (\pgf@arrow@handle@shorthand@empty is just an identity operator)
  \expandafter\def\expandafter\pgf@tmp\expandafter{#1}
  \expandafter\pgf@nfold@parsearrowmacro\pgf@tmp\relax
  % still need to gobble the rest of the orginal arrow definition
  \pgfutil@gobble@until@relax
}


%
% Hooking into pgf's rendering pipeline
% -------------------------------------
%
% The new code has to be injected into \pgfusepath (pgfcorepathusage.code.tex). For rendering the new paths,
% \pgf@stroke@inner@line is a natural choice as this is where /tikz/double is rendered. However, we also
% need to disable rendering the ordinary path, which is not as easy. In the future I will make a pull request
% to TikZ to simplify such injections.
%
% The call to draw the path comes right before \pgf@stroke@inner@line. The macro before \pgf@stroke@inner@line
% is either \pgf@path@check@proper or \pgf@prepare@start@of@path (depending on the result of the proper check).
% We therefore must inject code into both of them to see if nfold is enabled. If it is, we call the old macro,
% cache and delete the current softpath (so the call to \pgfsyssoftpath@invokecurrentpath has no effect), then we
% restore and offset the cached softpath in \pgf@stroke@inner@line.
%
% The macros \pgf@path@check@proper and \pgf@prepare@start@of@path are also used in \pgf@up@draw@arrows@only,
% so we must make sure that the latter is unaffected by the modifications. Luckily, this turns out not to be
% a problem - the only macros that are called after the modified ones are \pgf@add@arrow@at@start and
% \pgf@add@arrow@at@end, which do not change their behaviour even if we modify the paths.
%

\newcount\pgf@nfold@order
\pgf@nfold@order=1

\def\pgf@nfold@preparenfoldpath{%
  \ifnum\pgf@nfold@order>1\relax
    \ifdim\pgfinnerlinewidth>0pt\relax
      % Hack the rendering pipeline: There is a \pgfsyssoftpath@invokecurrentpath call following
      % which we do not want if nfold is active. We therefore clear the current path here
      % and then perform the nfold drawing in our modification of \pgf@stroke@inner@line
      \pgfsyssoftpath@getcurrentpath\pgf@nfold@cachedpath%
      \pgfsyssoftpath@setcurrentpath\pgfutil@empty%
    \else
      \pgfutil@packageerror{tikz-nfold}{Must set \string\pgfinnerlinewidth\space to use nfold, e.g. by setting /tikz/double distance}{}
    \fi
  \fi
}

\let\pgf@nfold@old@path@check@proper\pgf@path@check@proper
\def\pgf@path@check@proper{%
  \pgf@nfold@old@path@check@proper%
  \ifpgfutil@tempswa\else%
    % if \pgfutil@tempswa is false, this is the last macro we can overwrite before the draw call.
    % Otherwise, we inject into \pgf@prepare@start@of@path%
    \pgf@nfold@preparenfoldpath%
  \fi%
}

\let\pgf@nfold@old@prepare@start@of@path\pgf@prepare@start@of@path
\def\pgf@prepare@start@of@path{%
  \pgf@nfold@old@prepare@start@of@path%
  \pgf@nfold@preparenfoldpath%
}

\let\pgf@nfold@old@stroke@inner@line\pgf@stroke@inner@line
\def\pgf@stroke@inner@line{%
  \ifnum\pgf@nfold@order>1\relax%
    \pgf@nfold@render@cached@softpath%
  \else%
    % Old behaviour
    \pgf@nfold@old@stroke@inner@line%
  \fi%
}


%
% Parsing the soft path
% ---------------------
%
% A significant part of the code below is based on pgfmoduledecorations.code.tex (c) 2019 Mark Wibrow and Till Tantau.
% Quite similar to decorations we parse the current soft path and put it into a form that makes it easier
% to iterate over.
%
%


%
% In order to correctly implement \pgfpathclose we already need to know about
% the \pgfpathclose (and the penultimate point) at the beginning of this
% connected segment as these data affect the first/last join.
% We therefore parse one connected segment of the softpath and store it in a modified
% form in \pgf@cur@conn@segment. When reaching the end of the connected segment we call
% the proper parser to turn \pgf@cur@conn@segment into a parsed path. We do this for
% all connected segments and concatenate all the parsed paths.
%


\def\pgf@nfold@parsesoftpath#1#2{%
  \let\pgf@cur@conn@segment\pgfutil@empty%
  \let\pgf@all@parsed@segments\pgfutil@empty%
  \edef\pgf@nfold@parser@last@moveto{{\the\pgf@path@lastx}{\the\pgf@path@lasty}}%
  \let\pgf@nfold@last@closepath@from\pgfutil@empty%
  \pgf@nfold@parse@setupfirst%
  \expandafter\pgf@nfold@@parsesoftpath#1\pgf@stop{}{}%
  \let#2\pgf@all@parsed@segments%
}%

\def\pgf@nfold@@parsesoftpath#1#2#3{%
  \let\pgf@next\pgf@nfold@@parsesoftpath%
  \ifx#1\pgf@stop%
    \def\pgf@nfold@macrotoadd{\pgf@nfold@parselast}%
    \pgf@nfold@addmacro\pgf@cur@conn@segment%
    \pgf@nfold@process@conn@segment%
    \let\pgf@next\relax%
  \else%
    \ifx#1\pgfsyssoftpath@movetotoken%
      \ifx\pgf@cur@conn@segment\pgfutil@empty%
        % This case happens for the very first segment or for double movetos.
        % We need special treatment here, as otherwise the arrow tip extension
        % does not work correctly. The \pgf@nfold@parsemoveto will be called
				% in \pgf@nfold@process@conn@segment.
        \def\pgf@nfold@parser@last@moveto{{#2}{#3}}%
        % Make sure \pgf@cur@conn@segment is no longer empty so double movetos are not
        % treated the same as single movetos. This is also relevant to arrow tip extensions
        \def\pgf@cur@conn@segment{\relax}%
      \else%
        \def\pgf@nfold@macrotoadd{\pgf@nfold@parsemoveto{#2}{#3}}%
        \pgf@nfold@addmacro\pgf@cur@conn@segment%
        % A moveto marks the beginning/end of one connected segment
        \pgf@nfold@process@conn@segment%
        \let\pgf@nfold@last@closepath@from\pgfutil@empty%
        \let\pgf@cur@conn@segment\pgfutil@empty%
        \def\pgf@nfold@parser@last@moveto{{#2}{#3}}%
      \fi
    \else%
      \ifx#1\pgfsyssoftpath@linetotoken%
        \def\pgf@nfold@macrotoadd{\pgf@nfold@parselineto{#2}{#3}}%
        \pgf@nfold@addmacro\pgf@cur@conn@segment%
      \else%
        \ifx#1\pgfsyssoftpath@curvetosupportatoken%
          \def\pgf@nfold@parse@supporta{{#2}{#3}}%
        \else%
          \ifx#1\pgfsyssoftpath@curvetosupportbtoken%
            \def\pgf@nfold@parse@supportb{{#2}{#3}}%
          \else%
            \ifx#1\pgfsyssoftpath@curvetotoken%
              \edef\pgf@nfold@macrotoadd{\noexpand\pgf@nfold@parsecurveto\pgf@nfold@parse@supporta\pgf@nfold@parse@supportb{#2}{#3}}%
              \pgf@nfold@addmacro\pgf@cur@conn@segment%
            \else%
              \ifx#1\pgfsyssoftpath@closepathtoken%
                \let\pgf@nfold@last@closepath@from\pgf@nfold@parser@previous@pt%
                \def\pgf@nfold@macrotoadd{\pgf@nfold@parseclosepath{#2}{#3}}%
                \pgf@nfold@addmacro\pgf@cur@conn@segment%
              \else%
                \ifx#1\pgfsyssoftpath@rectcornertoken%
                  \def\pgf@nfold@parse@rectcorner{{#2}{#3}}%
                \else%
                  \ifx#1\pgfsyssoftpath@rectsizetoken%
                    \edef\pgf@nfold@macrotoadd{\noexpand\pgf@nfold@parserect\pgf@nfold@parse@rectcorner{#2}{#3}}%
                    \pgf@nfold@addmacro\pgf@cur@conn@segment%
                  \else%
                    \pgfutil@packageerror{tikz-nfold}{Unrecognised soft path token `#1'}{}%
                  \fi%
                \fi%
              \fi%
            \fi%
          \fi%
        \fi%
      \fi%
    \fi%
  \fi%
  \def\pgf@nfold@parser@previous@pt{{#2}{#3}}%
  \pgf@next}%

\def\pgf@nfold@process@conn@segment{%
  \let\pgf@parsed@cur@conn@seg\pgfutil@empty%
  \ifx\pgf@nfold@last@closepath@from\pgfutil@empty%
    \expandafter\pgf@nfold@parsemoveto\pgf@nfold@parser@last@moveto%
  \else%
    % This connected segment ends on a closepath. In order to get
    % the join right, we prepend the current segment with an invisible line
    % identical to the line of the \pgfpathclose. This way, 
    \expandafter\pgf@nfold@parsemoveto\pgf@nfold@last@closepath@from%
    \expandafter\pgf@nfold@parseinvisibleline\pgf@nfold@parser@last@moveto%
  \fi%
  \pgf@cur@conn@segment%
  \let\pgf@nfold@macrotoadd\pgf@parsed@cur@conn@seg%
  \pgf@nfold@addmacro\pgf@all@parsed@segments%
}

%
% Values for \pgf@nfold@next@type:
% f=first, m=moveto, c=curveto, l=lineto, r=rect, o=closepath, t=last, i=invisibleline
%

\def\pgf@nfold@parsemoveto#1#2{%
  \pgf@nfold@parser@moveup%
  \let\pgf@nfold@next@type=m%
  \let\pgf@nfold@next@visible=0%
  \edef\pgf@nfold@next@last{\pgf@x#1\pgf@y#2}%
  \pgf@nfold@parser@handlesegment%
}%


% Common code for parselineto and parseclosepath
\def\pgf@nfold@parse@line@common#1#2#3{%
  \pgf@nfold@parser@moveup%
  \pgfextract@process\pgf@tmp@tang@i{\pgfpointnormalised{}\global\let\pgf@nfold@tmp\pgf@tmp}
  \let\pgf@nfold@next@type=#3%
  \let\pgf@nfold@next@visible=1%
  \let\pgf@nfold@next@tang@i\pgf@tmp@tang@i
  \let\pgf@nfold@next@tang@ii\pgf@tmp@tang@i
  \let\pgf@nfold@next@angle@i\pgf@nfold@tmp
  \let\pgf@nfold@next@angle@ii\pgf@nfold@tmp
  \let\pgf@nfold@next@first\pgf@nfold@cur@last
  \def\pgf@nfold@next@last{\pgf@x#1\pgf@y#2}%
  \pgf@nfold@parser@handlesegment%
}

\def\pgf@nfold@parselineto#1#2{%
  % the current end is still stored in next@last because parser@moveup has not been called yet
  \pgf@process{\pgfpointdiff{\pgf@nfold@next@last}{\pgf@x#1\pgf@y#2}}%
  \pgfpointtaxicabnorm\pgf@xa%
  % remove degenerate line segments (reduces glitches)
  \ifdim\pgf@xa>.1pt\relax%
    \pgf@nfold@parse@line@common{#1}{#2}{l}%
  \fi%
}%

\def\pgf@nfold@parsecurveto#1#2#3#4#5#6{%
  \pgf@nfold@parser@moveup%
  \pgf@offset@compute@tangents{\pgf@nfold@cur@last}{\pgf@x#1\pgf@y#2}{\pgf@x#3\pgf@y#4}{\pgf@x#5\pgf@y#6}%
  \let\pgf@nfold@next@type=c%
  \let\pgf@nfold@next@visible=1%
  % the following only need to be set if visible=1
  \let\pgf@nfold@next@tang@i=\pgf@tmp@tang@i
  \let\pgf@nfold@next@tang@ii=\pgf@tmp@tang@ii
  \let\pgf@nfold@next@angle@i\pgf@tmp@angle@i
  \let\pgf@nfold@next@angle@ii\pgf@tmp@angle@ii
  \let\pgf@nfold@next@first\pgf@nfold@cur@last
  \def\pgf@nfold@next@supporta{\pgf@x#1\pgf@y#2}
  \def\pgf@nfold@next@supportb{\pgf@x#3\pgf@y#4}
  \def\pgf@nfold@next@last{\pgf@x#5\pgf@y#6}
  \pgf@nfold@parser@handlesegment%
}%

\def\pgf@nfold@parseclosepath#1#2{%
  \pgf@process{\pgfpointdiff{\pgf@nfold@next@last}{\pgf@x#1\pgf@y#2}}%
  % closepath segments should always be processed even if they have zero length
  \pgf@nfold@parse@line@common{#1}{#2}{o}%
}%

\def\pgf@nfold@parseinvisibleline#1#2{%
  \pgf@process{\pgfpointdiff{\pgf@nfold@next@last}{\pgf@x#1\pgf@y#2}}%
  % invisibleline segments should always be processed even if they have zero length.
  % Counterintuitively, an "invisibleline" segment has next@visible=1 because
  % we want its end join to be rendered.
  \pgf@nfold@parse@line@common{#1}{#2}{i}%
}%

\def\pgf@nfold@parselast{%
  \pgf@nfold@parser@moveup%
  \let\pgf@nfold@next@type=t%
  \let\pgf@nfold@next@visible=0%
  \pgf@nfold@parser@handlesegment%
}

% Mostly for the sake of completeness; using TikZ' "\path (0,0) rectangle (1,1);" does not call this code
\def\pgf@nfold@parserect#1#2#3#4{%
  \pgf@nfold@parsemoveto{#1}{#2}%
  \pgf@xc=#1\relax
  \pgf@yc=#2\relax
  \pgf@xd=#3\relax
  \pgf@yd=#4\relax
  \advance\pgf@yc\pgf@yd%
  \edef\pgf@temp{{\the\pgf@xc}{\the\pgf@yc}}%
  \expandafter\pgf@nfold@parselineto\pgf@temp%
  \advance\pgf@xc\pgf@xd%
  \edef\pgf@temp{{\the\pgf@xc}{\the\pgf@yc}}%
  \expandafter\pgf@nfold@parselineto\pgf@temp%
  \advance\pgf@yc-\pgf@yd%
  \edef\pgf@temp{{\the\pgf@xc}{\the\pgf@yc}}%
  \expandafter\pgf@nfold@parselineto\pgf@temp%
  \advance\pgf@xc-\pgf@xd%
  \edef\pgf@temp{{\the\pgf@xc}{\the\pgf@yc}}%
  \expandafter\pgf@nfold@parselineto\pgf@temp%
  \edef\pgf@marshal{\noexpand\pgf@nfold@parsemoveto{\the\pgf@xc}{\the\pgf@yc}}%
  \pgf@marshal%
}

% adds the contents of \pgf@nfold@macrotoadd to #1
\def\pgf@nfold@addmacro#1{%
  % need a \gdef because we have nested groups in the subdivision
  \expandafter\expandafter\expandafter\gdef%
  \expandafter\expandafter\expandafter#1%
  \expandafter\expandafter\expandafter{%
  \expandafter#1\pgf@nfold@macrotoadd}%
}


%
% Tokens for the parsed path
%

%#3: cached normalised tangent (for efficiency)
\def\pgf@nfold@token@lineto#1#2#3{%
  \pgfoffsetline@{#1}{#2}{\pgf@nfold@shiftamount}{#3}%
}

\def\pgf@nfold@token@lineto@continue#1#2#3{%
  \pgfoffsetlinenomove@{#1}{#2}{\pgf@nfold@shiftamount}{#3}%
}

\def\pgf@nfold@token@invisibleline#1#2#3{%
  % An invisible line should execute a moveto to the end point of the line
  \pgfqpointscale{\pgf@nfold@shiftamount}{#3}%
  \pgf@xc=-\pgf@y%
  \pgf@y=\pgf@x%
  \pgf@x=\pgf@xc%
  \pgfpathmoveto{\pgfpointadd{}{#2}}%
}

% #5, #6: cached normalised tangents at start and end (for efficiency)
\def\pgf@nfold@token@curveto#1#2#3#4#5#6{%
  \def\pgf@tmp@tang@i{#5}%
  \def\pgf@tmp@tang@ii{#6}%
  \pgf@offset@bezier@segment@{#1}{#2}{#3}{#4}{\pgf@nfold@shiftamount}%
  \pgfpathmoveto{\pgf@bezier@offset@i}%
  \pgfpathcurveto{\pgf@bezier@offset@ii}{\pgf@bezier@offset@iii}{\pgf@bezier@offset@iv}%
}

\def\pgf@nfold@token@curveto@continue#1#2#3#4#5#6{%
  \def\pgf@tmp@tang@i{#5}%
  \def\pgf@tmp@tang@ii{#6}%
  \pgf@offset@bezier@segment@{#1}{#2}{#3}{#4}{\pgf@nfold@shiftamount}%
  \pgfpathcurveto{\pgf@bezier@offset@ii}{\pgf@bezier@offset@iii}{\pgf@bezier@offset@iv}%
}

\def\pgf@nfold@token@closepath{%
  \pgfpathclose%
}

% This is needed for some edge case explained above.
% #1: segment@start, which is actually the end point of the current segment in the edge case
% #2: the angle of the current segment (start or end does not matter for straight lines)
\def\pgf@nfold@token@edgecase@movetostart#1#2{%
  \pgfpathmoveto{\pgfpointadd%
    {#1}{\pgfpointpolar{#2+90}{\pgf@nfold@shiftamount}}}%
}


\def\pgf@nfold@parse@setupfirst{%
  \let\pgf@nfold@next@type=f%
  % technically, @visible can be derived from @type, but I think this is more efficient
  \let\pgf@nfold@next@visible=0%
  \edef\pgf@nfold@next@last{\pgf@x\the\pgf@path@lastx\pgf@y\the\pgf@path@lasty}%
  % the following only need to be set if visible=1
  \let\pgf@nfold@next@tang@i=\pgfpointorigin%
  \let\pgf@nfold@next@tang@ii=\pgfpointorigin%
  \def\pgf@nfold@next@angle@i{0}%
  \def\pgf@nfold@next@angle@ii{0}%
  \let\pgf@nfold@next@first\pgfpointorigin%
  % the following only need to be set if type=c
  \let\pgf@nfold@next@supporta\pgfpointorigin%
  \let\pgf@nfold@next@supportb\pgfpointorigin%
}

\def\pgf@nfold@clampangle{
  % The computed angles are values between 0 and 360, so their difference is between 360 and -360;
  % we want the difference to be between -180 and 180
  \ifdim\pgfmathresult pt<-180pt\relax
    \pgfutil@tempdima=\pgfmathresult pt
    \advance\pgfutil@tempdima by 360pt
    \edef\pgfmathresult{\pgf@sys@tonumber\pgfutil@tempdima}
  \else\ifdim\pgfmathresult pt>180pt\relax
    \pgfutil@tempdima=\pgfmathresult pt
    \advance\pgfutil@tempdima by -360pt
    \edef\pgfmathresult{\pgf@sys@tonumber\pgfutil@tempdima}
  \fi\fi
}



\def\pgf@nfold@parser@moveup{%
  \let\pgf@nfold@prev@type\pgf@nfold@cur@type%
  \let\pgf@nfold@prev@visible\pgf@nfold@cur@visible%
  \let\pgf@nfold@prev@tang@i\pgf@nfold@cur@tang@i%
  \let\pgf@nfold@prev@tang@ii\pgf@nfold@cur@tang@ii%
  \let\pgf@nfold@prev@angle@i\pgf@nfold@cur@angle@i%
  \let\pgf@nfold@prev@angle@ii\pgf@nfold@cur@angle@ii%
  \let\pgf@nfold@prev@first\pgf@nfold@cur@first%
  \let\pgf@nfold@prev@supporta\pgf@nfold@cur@supporta%
  \let\pgf@nfold@prev@supportb\pgf@nfold@cur@supportb%
  \let\pgf@nfold@prev@last\pgf@nfold@cur@last%
  \let\pgf@nfold@cur@type\pgf@nfold@next@type%
  \let\pgf@nfold@cur@visible\pgf@nfold@next@visible%
  \let\pgf@nfold@cur@tang@i\pgf@nfold@next@tang@i%
  \let\pgf@nfold@cur@tang@ii\pgf@nfold@next@tang@ii%
  \let\pgf@nfold@cur@angle@i\pgf@nfold@next@angle@i%
  \let\pgf@nfold@cur@angle@ii\pgf@nfold@next@angle@ii
  \let\pgf@nfold@cur@first\pgf@nfold@next@first%
  \let\pgf@nfold@cur@supporta\pgf@nfold@next@supporta%
  \let\pgf@nfold@cur@supportb\pgf@nfold@next@supportb%
  \let\pgf@nfold@cur@last\pgf@nfold@next@last%
}

%
% Iterating over the parsed soft path
% -----------------------------------
%

\newcount\pgf@nfold@index
\def\pgf@nfold@run@loop{%
  \pgf@nfold@index=\pgf@nfold@order%
  \pgf@nfold@run@loop@%
}

\def\pgf@nfold@run@loop@{%
  \pgf@nfold@loop@inner%
  \advance\pgf@nfold@index by -1\relax
  \ifnum\pgf@nfold@index>0\relax%
    \pgf@nfold@run@loop@%
  \fi%
}

\def\pgf@nfold@loop@inner{%
  \pgfmathsetmacro{\pgf@nfold@shift@fraction}%
    {-1+2*(\pgf@nfold@index-1)/(\pgf@nfold@order-1)}%
  % Do not store shiftamount as a length (i.e. with pt) because we want to use it in \pgfqpointscale{}{}
  \pgfmathsetmacro{\pgf@nfold@shiftamount}{\pgf@nfold@hwidth*\pgf@nfold@shift@fraction}
  % Transformations are already baked into the path; without this call, they would be applied twice
  \pgftransformreset%
  \parsedpath%
  \pgfsyssoftpath@flushcurrentpath%
  \pgf@up@action%
}

% Computes both the width of the component lines into \pgf@x and the distance
% from the center to the outermost line centers into \pgf@y
% from the current values of \pgflinewidth and \pgfinnerlinewidth.
\def\pgf@nfold@compute@widths@from@double{
    \pgf@x=\pgflinewidth\relax%
    \pgf@y=\pgf@x\relax%
    \advance\pgf@x-\pgfinnerlinewidth\relax%
    \advance\pgf@y+\pgfinnerlinewidth\relax%
    \pgf@x=.5\pgf@x\relax%
    \pgf@y=.25\pgf@y\relax%
}

\def\pgf@nfold@render@cached@softpath{%
  \pgfscope% must use a scope, otherwise we break the arrow tips
    % Compute the full and constituent part line widths
    \pgf@nfold@compute@widths@from@double%
    \pgfsetlinewidth\pgf@x%
    \edef\pgf@nfold@hwidth{\the\pgf@y}%
    \pgfprocessround{\pgf@nfold@cachedpath}{\pgf@nfold@cachedpath}% remove tokens from the soft path
    \pgf@nfold@parsearrows%
    \pgf@nfold@parsesoftpath{\pgf@nfold@cachedpath}{\parsedpath}%
    \pgf@nfold@run@loop%
  \endpgfscope%
}


%
% user interface and pgf/TikZ keys
% --------------------------------
%

% Outputs a provided soft path in #1 offset by a distance provided in #2.
\def\pgfoffsetpath#1#2{%
  \begingroup
    \pgfmathsetlengthmacro\pgf@nfold@parsed@hwidth{#2}
    % \pgf@nfold@hwidth must always be positive
    \pgf@x=\pgf@nfold@parsed@hwidth\relax
    \ifdim\pgf@x<0pt\relax
      \pgf@x=-\pgf@x
      \def\pgf@nfold@shift@fraction{-1}
    \else
      \def\pgf@nfold@shift@fraction{1}
    \fi
    \edef\pgf@nfold@parsed@hwidth{\the\pgf@x}
    \pgfoffsetpathqfraction{#1}{\pgf@nfold@parsed@hwidth}{\pgf@nfold@shift@fraction}
  \endgroup
}

% Outputs a provided soft path in #1 offset by #3*#2 where #2 is a length (>= 0 pt)
% and #3 is a number between -1.0 and 1.0. This differs from \pgfoffsetpath{#1}{#2*#3} 
% in how the joins between segments are rendered.  In particular, \pgfoffsetpathfraction{#1}{10pt}{0}
% does *not* yield the original path, but a new path in the centre of #1 drawn at line width 20pt.
%
\def\pgfoffsetpathfraction#1#2#3{%
  \begingroup
    \pgfmathsetlengthmacro\pgf@nfold@parsed@hwidth{#2}
    \pgfmathsetmacro\pgf@nfold@shift@fraction{#3}
    \pgfoffsetpathqfraction{#1}{\pgf@nfold@parsed@hwidth}{\pgf@nfold@shift@fraction}
  \endgroup
}

% This has the same output as the #3-th segment of nfold=#4.
\def\pgfoffsetpathindex#1#2#3#4{%
  \begingroup
    \pgfmathsetmacro\pgf@nfold@shift@fraction{-1+2*(#3-1)/(#4-1)}
    \pgfoffsetpathqfraction{#1}{#2}{\pgf@nfold@shift@fraction}
  \endgroup
}

% A quick version that skips processing the input values
\def\pgfoffsetpathqfraction#1#2#3{%
  \begingroup
    \pgf@x=#2\relax
    \edef\pgf@nfold@hwidth{\the\pgf@x}
    \edef\pgf@nfold@shift@fraction{#3}
    \pgf@x=\pgf@nfold@shift@fraction\pgf@x\relax
    \edef\pgf@nfold@shiftamount{\pgf@sys@tonumber\pgf@x}
    \pgfprocessround{#1}{\pgf@nfold@cachedpath}% remove tokens from the soft path
    \pgf@nfold@parsesoftpath{\pgf@nfold@cachedpath}{\parsedpath}%
  % Transformations are already baked into the path; without this call, they would be applied twice
    \pgftransformreset%
    \parsedpath%
  \endgroup
}


\pgfkeys{
  /pgf/nfold/.code={%
    \pgf@nfold@order=#1\relax%
    \ifnum\pgf@nfold@order<1\relax%
      \pgfutil@packageerror{tikz-nfold}{The key /pgf/nfold must take a value of at least 1, got \the\pgf@nfold@order}{}%
    \fi%
    % If nfold > numcached AND intersections is not loaded AND we draw an Implies tip, we get an error.
    % We check the first two conditions now and set the respective flag
    \ifnum\pgf@nfold@order>\pgf@nfold@intersec@numcached\relax
      \ifdefined\pgfintersectionofpaths\else
        \pgf@nfold@intersectionsnotloadedtrue
      \fi
    \fi
  },
  /pgf/nfold/.default=2
}


% use \tikzset for scoping reasons, does not appear to be equivalent to \pgfset{/tikz/...=...}
\tikzset{
  nfold/.code={
    \edef\pgf@tmp{\noexpand\pgfkeys{/pgf/nfold=#1}}
    % patch \tikz@double@setup to set /pgf/nfold=#1 as well
    \expandafter\expandafter\expandafter\def%
      \expandafter\expandafter\expandafter\tikz@double@setup%
      \expandafter\expandafter\expandafter{\expandafter\tikz@double@setup\pgf@tmp}
  },
  nfold/.default=2,
  scaling nfold/.code={%
    \pgfscope% scope to contain \tikz@double@setup
      \tikz@double@setup
      % extract double distance between line centers into \pgf@x
      \pgf@nfold@compute@widths@from@double
      \pgf@y=2\pgf@y
      % store (order-1)*\pgf@x in \pgf@xa
      \c@pgf@counta=#1
      \advance\c@pgf@counta by -1\relax
      \global\pgf@y=\c@pgf@counta\pgf@y
    \endpgfscope
    \tikzset{
      double distance between line centers=\pgf@y,
      nfold=#1
    }
  },
  scaling nfold/.default=2,
  % This simply defines the key if tikzcd is not loaded, so we don't run into any errors
  commutative diagrams/scaling nfold/.code={
    \pgfscope% scope to contain \tikz@double@setup
      \tikz@double@setup
      % extract double distance between line centers into \pgf@x
      \pgf@nfold@compute@widths@from@double
      % store (order-1)*\pgf@y in \pgf@ya
      \c@pgf@counta=#1
      \advance\c@pgf@counta by -1\relax
      \pgf@ya=\c@pgf@counta\pgf@y
      % compute the label offset, which is (order-2)*\pgf@y + .5*\pgf@x
      \advance\c@pgf@counta by -1\relax
      \pgf@xa=\c@pgf@counta\pgf@y
      \advance\pgf@xa by .5\pgf@x
      % save the results in \pgf@x and \pgf@y
      \global\pgf@x=\pgf@xa
      \global\pgf@y=2\pgf@ya
    \endpgfscope
    \tikzset{
      commutative diagrams/every label/.append style/.expanded={outer sep=\the\pgf@x},
      double distance between line centers=\pgf@y,
      nfold=#1
    }
  },
  commutative diagrams/scaling nfold/.default=2
}

\endinput