Debian Codegraph @

texmf-dist/source/generic/mfpic/grafbase.dtx

raw
1 % \iffalse
2 % File: grafbase.dtx
3 % A part of mfpic 1.10 2012/12/03
4 %
5 % -------------------------------------------------------------------
6 %
7 % Copyright 2002--2012, Daniel H. Luecking
8 %
9 % Mfpic may be distributed and/or modified under the conditions of the
10 % LaTeX Project Public License, either version 1.3b of this license or (at
11 % your option) any later version. The latest version of this license is in
12 % <http://www.latex-project.org/lppl.txt>
13 % and version 1.3c or later is part of all distributions of LaTeX version
14 % 2008/12/01 or later.
15 %
16 % Mfpic has maintenance status "author-maintained". The Current Maintainer
17 % is Daniel H. Luecking. There are several Base Interpreters: plain TeX, LaTeX,
18 % plain Metafont and plain MetaPost.
19 %
20 %<*driver>
21 \ProvidesFile{grafbase.dtx}
22 [2012/12/03 v1.10. Metafont/post macros to interface with mfpic.]%
23 \documentclass{ltxdoc}
24 \usepackage{docmfp}
25
26 \addtolength{\textwidth}{.5878pt}
27
28 \def\mytt{\upshape\mdseries\ttfamily}
29 \renewcommand\marg[1]{{\mytt \{#1\}}}
30 \renewcommand\oarg[1]{{\mytt [#1]}}
31 \renewcommand\parg[1]{{\mytt (#1)}}
32 \renewcommand{\meta}[1]{{$\langle$\rmfamily\itshape#1$\rangle$}}
33 \DeclareRobustCommand\cs[1]{{\mytt\char`\\#1}}
34 \def\prog#1{{\mdseries\scshape #1}}
35 \def\grafbase{\prog{grafbase}}
36 \def\Grafbase{\prog{Grafbase}}
37 \def\mfpic{\prog{mfpic}}
38 \def\Mfpic{\prog{Mfpic}}
39 \def\MF{\prog{meta\-font}}
40 \def\MP{\prog{meta\-post}}
41 \def\PS{\prog{Post\-Script}}
42 \def\CMF{\prog{Meta\-font}}
43 \def\CMP{\prog{Meta\-post}}
44 \def\opt#1{{\sffamily\upshape#1}}
45 \def\mfc#1{{\mytt#1}}
46 \let\env\mfc
47 \let\file\mfc
48 \let\gbc\mfc
49 \renewcommand\{{{\mytt\char`\{}}
50 \renewcommand\}{{\mytt\char`\}}}
51 \renewcommand\|{${}\mathrel{|}{}$}
52
53 \makeatletter
54 \let\HD@SetMacroIndent\@gobble
55 \newcommand\bsl{{\mytt\@backslashchar}}
56 % Stupid lists!
57 \def\@listi{\leftmargin\leftmargini
58 \parsep \z@ \@plus\p@ \@minus\z@
59 \topsep 4\p@ \@plus\p@ \@minus2\p@
60 \itemsep\parsep}
61 \let\@listI\@listi \@listi
62 \renewcommand\labelitemi{\normalfont\bfseries \textendash}
63 \renewcommand\labelitemii{\textasteriskcentered}
64 \renewcommand\labelitemiii{\textperiodcentered}
65 \leftmargini\parindent
66 % Stupid index!
67 \def\usage#1{\textrm{#1}}
68 \def\index@prologue{\section*{Index}\markboth{Index}{Index}}
69 \def\IndexParms{%
70 \parindent \z@ \columnsep 15pt
71 \parskip 0pt plus 1pt
72 \rightskip 5pt plus2em \mathsurround \z@
73 \parfillskip=-5pt \small
74 % less hanging:
75 \def\@idxitem{\par\hangindent 20pt}%
76 \def\subitem{\@idxitem\hspace*{15pt}}%
77 \def\subsubitem{\@idxitem\hspace*{25pt}}%
78 \def\indexspace{\par\vspace{10pt plus 2pt minus 3pt}}}
79 \renewcommand\routinestring{}
80 \renewcommand\variablestring{\space(var.)}
81 % Why does every command have to be indexed twice?
82 \renewcommand\SpecialMfpIndex[3]{\@bsphack
83 \index{%
84 \string#1\actualchar
85 \string\verb\quotechar*\verbatimchar\string#1\verbatimchar
86 #2 \encapchar usage}%
87 \@esphack}
88 \def\close@crossref{\SpecialEscapechar{:}}
89 \makeatother
90 \def\VariableIndex#1{\SpecialMfpIndex{#1}{\variablestring}{}}
91 \def\RoutineIndex #1{\SpecialMfpIndex{#1}{}{}}
92
93 \def\pdfTeX{\textrm{pdf\kern.04em\TeX}}
94 \def\pdfLaTeX{\textrm{pdf\kern.06em\LaTeX}}
95 \def\ConTeXt{\textrm{Con\kern-.16em\TeX\kern-0.06em t}}
96 \def\PiCTeX{\textrm{P\kern-.13em\lower.3ex\hbox{I}C\TeX}}
97
98 \title{The \grafbase{} macros\thanks{This file has version number
99 \fileversion, last revised \filedate. The code described here
100 was developed by several people, notably Thomas Leathrum,
101 Geoffrey Tobin and Dan Luecking. Dan wrote this documentation.}}
102 \author{Dan Luecking}
103 \date{\filedate}
104 \SpecialEscapechar{:}
105 \def\bslash{:}
106 \DisableCrossrefs
107 \CodelineIndex
108 \AlsoImplementation
109
110 \begin{document}
111 \DeleteShortVerb{\|}
112 \DocInput{grafbase.dtx}
113 \end{document}
114 %</driver>
115 %\fi
116 %
117 % \CheckSum{1631}
118 % \CharacterTable
119 % {Upper-case \A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z
120 % Lower-case \a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z
121 % Digits \0\1\2\3\4\5\6\7\8\9
122 % Exclamation \! Double quote \" Hash (number) \#
123 % Dollar \$ Percent \% Ampersand \&
124 % Acute accent \' Left paren \( Right paren \)
125 % Asterisk \* Plus \+ Comma \,
126 % Minus \- Point \. Solidus \/
127 % Colon \: Semicolon \; Less than \<
128 % Equals \= Greater than \> Question mark \?
129 % Commercial at \@ Left bracket \[ Backslash \\
130 % Right bracket \] Circumflex \^ Underscore \_
131 % Grave accent \` Left brace \{ Vertical bar \|
132 % Right brace \} Tilde \~}
133 %
134 % \catcode`\_=12
135 % \GetFileInfo{grafbase.dtx}
136 % \maketitle
137 %
138 % \begin{abstract}
139 % Macros are defined for use with \mfpic{}. The latter is a set of \TeX{}
140 % macros which allows a \file{.tex} file to write a \file{.mf} or
141 % \file{.mp} file that, with the help of these macros and \MF{} (or \MP),
142 % can be used to create pictures in the document, especially mathematical
143 % pictures. There are two versions of \grafbase, one for \MF{} and one for
144 % \MP{}. As they are more alike than different (95\% of the code is
145 % identical), we document both here.
146 %
147 % This file documents the \grafbase{} source code. The user manual for
148 % \mfpic{} is distributed as \file{mfpic-doc.pdf}, produced from
149 % \file{mfpic-doc.tex}. An introductory guide to \mfpic{} is available
150 % in \file{mfpguide.pdf}, produced from \file{mfpguide.tex}
151 % \end{abstract}
152 %
153 % \StopEventually{\PrintIndex}
154 % \tableofcontents
155 %
156 %
157 %
158 % \section{Introduction}\label{intro}
159 %
160 %
161 % \subsection{Identification and checks}\label{checks}
162 %
163 % \DescribeVariable{grafbaseversion} We use \mfc{grafbaseversion} to
164 % check if \prog{grafbase} has been previously loaded, later we use it
165 % to check a mismatch with the version of \mfpic{} (if used).
166 % \gbc{grafbase} was used in previous versions. If either is known, we
167 % bail out. The \gbc{grafbase} boolean is really never needed, but it
168 % has been around since I took over. It is possible to write files that
169 % change behavior when \grafbase{} is loaded, however if they say
170 % ``\gbc{if grafbase:}, they can only be called with \gbc{grafbase} a
171 % known boolean.
172 %
173 % \VariableIndex{fileversion} \gbc{fileversion} and
174 % \VariableIndex{filedate} \gbc{filedate} provide identifying information.
175 %
176 % \DescribeRoutine{GBmsg}
177 % These are used fairly consistently and identify the source of the
178 % message delivered as being `\gbc{Grafbase}'.
179 % \DescribeRoutine{GBwarn}
180 % Warnings are delivered by \gbc{GBwarn}. The macro \gbc{GBerrmsg} takes
181 % care of both the
182 % \DescribeRoutine{GBerrmsg}
183 % error message and the \mfc{errhelp} string.
184 % \begin{macrocode}
185 %<*MF|MP>
186 if (known grafbaseversion) or (known grafbase):
187 message "Grafbase (" & jobname & "): You have loaded grafbase more "
188 & "than once! Please make sure that it is loaded only once.";
189 endinput;
190 fi
191 boolean grafbase; grafbase := true;
192
193 string fileversion, filedate;
194 fileversion := "1.10"; filedate := "2012/12/03";
195
196 message " Loading grafbase macros, version " & fileversion & ", " &
197 filedate & ".";
198 message " ";
199
200 def GBmsg expr s = message "Grafbase (" & jobname & "): " & s;
201 enddef;
202 def GBwarn expr s = GBmsg "Warning, " & s; enddef;
203 def GBerrmsg (expr s) expr t = errhelp t;
204 errmessage "Grafbase (" & jobname & "): " & s; errhelp "";
205 enddef;
206
207 % \end{macrocode}
208 %
209 % \DescribeVariable{MFPIC}
210 % The \gbc{MFPIC} variable is not yet used at all.
211 % It might be possible (at some point) to optimize things for \mfpic{} use
212 % whenever \gbc{mfpicversion} is defined, but so far we don't do anything
213 % except test the version and set this boolean.
214 %
215 % \DescribeVariable{mfpicversion}
216 % The output file written by the \mfpic{} macros includes a test that
217 % \gbc{mfpicversion} and \mfc{grafbaseversion} are the same,
218 % but that would fail to catch a new \grafbase{} with an old \mfpic. So
219 % we also put a test here with
220 % \DescribeRoutine{checkversions}
221 % \gbc{checkversions}, though it alone would fail to catch the use
222 % of older versions of \grafbase{} with current versions of \mfpic. Newer
223 % versions of \mfpic{} signal their version before inputting
224 % \file{grafbase}. Unfortunately (for error checking), \grafbase{} can
225 % also be used without \mfpic, so if \gbc{mfpicversion} is unknown, we
226 % merely write a message.
227 % \begin{macrocode}
228 boolean MFPIC; MFPIC := false;
229
230 def checkversions (expr g)=
231 numeric grafbaseversion; grafbaseversion := g;
232 if unknown mfpicversion: % no mfpic, or < 0.63
233 GBmsg "Recent mfpic not detected.";
234 elseif g = mfpicversion:
235 MFPIC := true;
236 else:
237 message "";
238 GBwarn "Version mismatch: "
239 & "mfpic and grafbase versions do not match.";
240 message "";
241 fi
242 enddef;
243
244 checkversions (110);
245
246 % \end{macrocode}
247 %
248 % We try to make sure that the macros of \file{plain.mf} or
249 % \file{plain.mp} (where \mfc{base_name} is defined to be \mfc{"plain"})
250 % are available.
251 % \begin{macrocode}
252 if unknown base_name : input plain;
253 elseif not string base_name: input plain;
254 elseif base_name <> "plain": input plain;
255 fi
256
257 % \end{macrocode}
258 %
259 % \DescribeRoutine{GBdebug}
260 % The \gbc{debug} flag is for developers, who should set it before
261 % inputing \file{grafbase}.
262 % \DescribeRoutine{GBenddebug}
263 % These two routines start and end debug messages.
264 %
265 % \DescribeRoutine{mftitle}
266 % The \gbc{mftitle} macro is useful when debugging.
267 % It will put its argument, which should be a string, as a TFM comment,
268 % and also print it to the terminal and log file.
269 % \begin{macrocode}
270 if not boolean debug: boolean debug; debug := false; fi
271
272 def GBdebug =
273 begingroup
274 save >>; def >> = message " " & enddef;
275 message "Grafbase DEBUG";
276 enddef;
277 def GBenddebug =
278 message "End DEBUG";
279 >> "";
280 endgroup
281 enddef;
282
283 vardef mftitle expr t =
284 if string t: t; message t; fi
285 enddef;
286
287 % \end{macrocode}
288 %
289 % \DescribeVariable{METAPOST}
290 % We try to determine which of \MF{} or \MP{} is using these macros.
291 % Perhaps one day we'll merge both versions of \grafbase{} in one file and
292 % use the following boolean. For now, we only use it to catch cases where
293 % the \grafbase{} file is being used by the wrong compiler.
294 %
295 % Of course, \MP{} natively knows about colors but \MF{} doesn't, so we
296 % use that to set a boolean \gbc{METAPOST}. We don't simply check if
297 % `\mfc{blue}' is \mfc{known} because `\mfc{blue}' is certainly a legal
298 % variable name in \MF. Instead we check `\mfc{known color X}' for
299 % some unlikely \gbc{X}. In \MP, `\gbc{color X}' is either true or
300 % false (\gbc{X} is a color or it isn't) and therefore always known, so
301 % `\gbc{known color X}' is always true.
302 %
303 % In \MF{} `\mfc{color X}' is an identifier (presumably unknown) with the
304 % base name \mfc{color} and suffix \mfc{X}.
305 % \begin{macrocode}
306 boolean METAFONT, METAPOST;
307 METAPOST := known color Carl Philipp Emanuel Bach;
308 if METAPOST: METAFONT := false; else: METAFONT := true; fi
309
310 %<*MF>
311 if METAPOST:
312 GBerrmsg ("wrong compiler.")
313 "This file is for Metafont. For Metapost, use grafbase.mp.";
314 fi
315 %</MF>
316
317 %<*MP>
318 if METAFONT:
319 GBerrmsg ("wrong compiler.")
320 "This file is for Metapost. For Metafont, use grafbase.mf.";
321 fi
322
323 % \end{macrocode}
324 %
325 % \MP{} now exists in a couple of slightly incompatible versions.
326 % Versions 1.000 and later (beta versions 0.9xx also) have native support for
327 % \texttt{CMYK} colors with a \mfc{cmykcolor} data type. They also
328 % support grayscale colors (i.e., \mfc{withcolor} will accept a numeric
329 % expression), and have the alias \mfc{rgbcolor} for \mfc{color}.
330 % It also has a means to set the name of the output file: the
331 % \mfc{filenametemplate} command. In versions 1.2 and later, this is
332 % deprecated in favor of setting the internal string variable
333 % \mfc{outputtemplate}.
334 % \begin{macrocode}
335 numeric metapostversion;
336 boolean has_cmyk;
337 boolean has_filenametemplate; % e.g., filenametemplate "%j.%n;
338 boolean has_outputtemplate; % e.g., outputtemplate := "%j.%n;
339 if unknown mpversion:
340 % prior to introduction of cmykcolor and output filename templates.
341 % Latest such version was 0.641.
342 metapostversion := 0.641;
343 has_cmyk := false;
344 has_filenametemplate := false;
345 has_outputtemplate := false;
346 else:
347 metapostversion := scantokens (mpversion);
348 has_cmyk := true;
349 has_filenametemplate := true;
350 if metapostversion < 1.200:
351 has_outputtemplate := false;
352 else:
353 has_outputtemplate := true;
354 fi
355 fi
356
357 %</MP>
358 % \end{macrocode}
359 %
360 %
361 % \subsection{Setting up the font, \MF{} only}\label{font}
362 %
363 % Font-related housekeeping is only for \MF{}. \MF{} only produces
364 % fonts, so we have to define the variables it thinks are needed for
365 % fonts.
366 %
367 % \DescribeVariable{GBgeneric}
368 % We intercept the \mfc{mode} variable before \mfc{mode_setup} can set
369 % \mfc{proof} mode. We used to set \mfc{mode := cx} (and later
370 % \mfc{ljfour}) if \mfc{mode} was unknown. For a while we just issued an
371 % error message. In this version we define a 600dpi mode called
372 % \mfc{GBgeneric} as a fallback (neither \gbc{mode} nor \gbc{localfont}
373 % known).
374 %
375 % The font identifier and coding scheme are just for information and end
376 % up as comments in the \file{.tfm} file (in all capitals). The design
377 % size just needs to be rather large for graphics, and \mfc{128pt\#} is
378 % anyway the default if we didn't set it ourselves.
379 % \begin{macrocode}
380 %<*MF>
381 if unknown mode:
382 GBerrmsg ("Metafont mode is unknown.")
383 "Set mode to a known mode, perhaps ljfour. "
384 & "If you proceed, localfont will be tried. "
385 & "If that is unknown, a generic mode will be tried.";
386 if known localfont: mode := localfont;
387 else:
388 if unknown GBresolution: GBresolution := 600 fi;
389 mode_def GBgeneric =
390 mode_param (pixels_per_inch, GBresolution);
391 mode_param (blacker, 0);
392 mode_param (fillin, 0);
393 mode_param (o_correction, 1);
394 mode_common_setup_;
395 enddef;
396 mode := GBgeneric;
397 fi
398 fi
399 mode_setup;
400 if debug:
401 GBdebug;
402 >> "pixels_per_inch = " & decimal pixels_per_inch;
403 GBenddebug;
404 fi
405
406 font_identifier := "MFpic graphics";
407 font_coding_scheme := "Arbitrary";
408 interim designsize := 128pt#;
409
410 %</MF>
411 % \end{macrocode}
412 %
413 % \Mfpic-generated files make reference to \mfc{aspect_ratio} and
414 % \mfc{pt\#}, while \MP{} has no need for them. Rather than make
415 % \mfpic{} write different things, and to make the files intended for
416 % \MF{} also work with \MP, we define them in the obvious way. We also
417 % add a definition of \mfc{hppp} and \gbc{t_} to simplify maintenance of
418 % two versions of the \file{grafbase} files. Then we define
419 % \gbc{currenttransform} for \MP{} sake.
420 % \begin{macrocode}
421 %<MP>pt# := pt; bp# := bp;
422 %<MP>def t_ = transformed currenttransform enddef;
423 if unknown aspect_ratio: aspect_ratio := 1; fi
424 if unknown hppp: hppp := 1 fi;
425 if unknown currenttransform:
426 transform currenttransform;
427 currenttransform := identity yscaled aspect_ratio;
428 fi
429
430 % \end{macrocode}
431 %
432 % Don't complain when variables get too large. For \MF{} this \emph{must}
433 % be after \mfc{mode_setup}. Also don't complain if a clockwise path is
434 % filled (only \MF{} worries about this).
435 % \begin{macrocode}
436 interim warningcheck := 0;
437 %<MF>interim turningcheck := 0;
438
439 % \end{macrocode}
440 %
441 %
442 % \subsection{Initializations}\label{init}
443 %
444 % \VariableIndex{unitlen}
445 % \VariableIndex{xscale}
446 % \VariableIndex{yscale}
447 % \VariableIndex{xneg}
448 % \VariableIndex{xpos}
449 % \VariableIndex{yneg}
450 % \VariableIndex{ypos}
451 % The following are the various variables determining the extent of a
452 % picture. These variables would normally be set by a user for each
453 % picture, or by \mfpic, but we give them default values anyway. They
454 % give a nominal picture size of one inch with a graph unit corresponding
455 % to $1/10$ inch.
456 % \begin{macrocode}
457 numeric unitlen, xscale, yscale, xneg, xpos, yneg, ypos;
458
459 unitlen := 1 bp#;
460 xscale := 7.2;
461 yscale := 7.2;
462 xneg := 0; xpos := 10;
463 yneg := 0; ypos := 10;
464
465 % \end{macrocode}
466 %
467 % \DescribeVariable{deg}
468 % \VariableIndex{degree}
469 % We support both degrees and radians for angles. In \MF, one degree is
470 % the unit of angle.
471 % \DescribeVariable{radian}
472 % One radian is $180/\pi$ degrees. We also define \gbc{pi} so a user can
473 % say \gbc{pi/2*radian} for almost the same effect as \gbc{90deg}.
474 % \DescribeVariable{pi}
475 % But not quite: because of \MF{}'s precision limits, the former is about
476 % 90.00025 degrees. \MF{}'s precision is 16 binary places, or slightly
477 % under 5 decimals. The accuracy of \gbc{pi} and \gbc{radian} below is the
478 % maximum possible. If we \emph{define} \gbc{radian} by its mathematical
479 % definition \gbc{radian:=180/pi}, then \gbc{radian} and formulas
480 % containing it are even less accurate. (Coincidentally, defining
481 % \gbc{radian} as below, and then \gbc{pi := 180/radian} produces exactly
482 % the same value for \gbc{pi} as below.)
483 % \begin{macrocode}
484 newinternal deg, pi, radian;
485 deg := 1; pi := 3.14159;
486 radian := 57.29578;
487 numeric degree; degree := deg;
488
489 % \end{macrocode}
490 %
491 % \VariableIndex{drawpen}
492 % \VariableIndex{penwd}
493 % \DescribeRoutine{resizedrawpen}
494 % Since we need to do this frequently, we define a macro that changes the
495 % pen width for subsequent drawing. This enables the file written by
496 % \mfpic{} to be less cluttered. At least that was the original reason.
497 % Now it gives us the opportunity to localize changes to \mfc{currentpen}
498 % and \gbc{drawpen}. (We already had this for different
499 % \gbc{beginmfpic}, since that reinitializes drawpen, but now it is local
500 % to other groups as well.)
501 %
502 % \VariableIndex{hatchpen}
503 % We could do this for the hatching pen, but it doesn't seem to change as
504 % often. The \mfc{pickup} command performs \mfc{yscaled aspect_ratio}, but
505 % so does the \gbc{shpath}, the only other place pens are required. In
506 % fact, we wouldn't need to \mfc{pickup} the pen at all, except power
507 % users may want to rely on \gbc{drawpen} always being the current pen. We
508 % make its diameter \mfc{.5pt} for backward compatibility. But many
509 % journal publisher (e.g., AMS) recommend no smaller than \mfc{.5bp} for
510 % author-supplied drawings.
511 %
512 % \VariableIndex{hatchwd}
513 % The default \gbc{hatchwd} used to be larger, but it seemed ugly to me.
514 % (Backward compatibility---what's that?).
515 % \begin{macrocode}
516 newinternal penwd; penwd := 0.5pt;
517 pen drawpen;
518
519 def resizedrawpen (expr s) =
520 interim penwd := s;
521 setvariable (pen) (drawpen) pencircle scaled penwd;
522 save currentpen; pen currentpen; pickup drawpen;
523 enddef;
524
525 numeric hatchwd; hatchwd := 0.5bp;
526 pen hatchpen; hatchpen := pencircle scaled hatchwd;
527
528 % \end{macrocode}
529 %
530 % \DescribeVariable{clipall}
531 % We have two booleans related to clipping. One, \gbc{clipall} is meant to
532 % be turned on just once (per picture), and it causes the \gbc{endmfpic}
533 % code to clip the current picture to the boundaries defined by the
534 % picture size variables. The other,
535 % \DescribeVariable{ClipOn}
536 % \gbc{ClipOn}, is meant to be turned on and off. While on, most drawing
537 % macros (all?) will clip their result to the current \emph{clipping path
538 % array}.
539 % \DescribeVariable{ClipPath}
540 % The clipping path array is an array of paths: \gbc{ClipPath[\,]} together
541 % with a numeric \gbc{ClipPath}. The numeric variable contains the number
542 % of clipping paths; the paths are \gbc{ClipPath[1]} through
543 % \gbc{ClipPath[ClipPath]}. A macro later on is defined to loop through
544 % the array, clipping the current picture to the union of their interiors.
545 %
546 % \DescribeVariable{truebbox}
547 % The \gbc{truebbox} boolean sets the bounding box of the picture to its
548 % natural size in \MP. The default behavior of \MP{} is to output a
549 % bounding box that is the natural size of the graphic. The \grafbase{}
550 % default is to override this default, setting \gbc{truebbox} to
551 % \mfc{false}. \CMF's default behavior is to force the user to specify the
552 % bounding box, and provides no natural way to obtain any information
553 % about the actual extent of the ink. So, for now, this boolean is only
554 % for \MP.
555 %
556 % \DescribeRoutine{DoClip}
557 % This is for the frequent conditional code to implement \gbc{ClipOn}.
558 % The command \gbc{clipsto} is defined later.
559 %
560 % \DescribeRoutine{noclip}
561 % For debugging we sometimes want to make sure something is drawn
562 % without clipping being applied. For this we have \gbc{noclip}.
563 % \begin{macrocode}
564 boolean clipall; clipall := false;
565 boolean ClipOn; ClipOn := false;
566 path ClipPath[]; numeric ClipPath; ClipPath = 0;
567 boolean truebbox; truebbox := false;
568
569 def DoClip (suffix v) =
570 if ClipOn and (ClipPath > 0): clipsto (v, ClipPath); fi
571 enddef;
572
573 def noclip (text t) =
574 hide ( setboolean (ClipOn) false; t)
575 enddef;
576
577 % \end{macrocode}
578 %
579 % \DescribeVariable{showbbox}
580 % The boolean \gbc{showbbox} is for debugging the \gbc{*bbox} macros.
581 % \begin{macrocode}
582 boolean showbbox; showbbox := false;
583
584 % \end{macrocode}
585 %
586 %
587 % \subsubsection{Colors}\label{colors}
588 %
589 % Of course colors are only recognized by \MP. The colors \mfc{black},
590 % \mfc{white}, \mfc{red}, \mfc{green} and \mfc{blue} are part of
591 % \file{plain.mp}. We define other standard colors to get all eight
592 % colors where the coordinates are 0 or 1.
593 %
594 % \DescribeRoutine{color}
595 % We define \MF{} replacements for some of the \MP{} color variables and
596 % macros. Our point of view will be: make each color variable a numeric in
597 % \MF{}. Each will lie between $0$ and $1$ representing shades of gray.
598 % For \emph{drawing} commands we will only distinguish between nonwhite
599 % (black, ${}<1$) and white (${}\ge1$). For filling commands we will allow
600 % levels in between, and fill with an approximation using a version of
601 % the \gbc{shade} macro.
602 % \begin{macrocode}
603 %<*MF>
604 let color = numeric; color black, white;
605 let rgbcolor = numeric;
606 let cmykcolor = numeric;
607 black := 0; white := 1;
608 def withcolor text t = enddef;
609 %</MF>
610 %<MP>if not has_cmyk: let rgbcolor = color; let cmykcolor = color; fi
611 def _wc_ = withcolor enddef;
612
613 % \end{macrocode}
614 %
615 % \VariableIndex{currentcolor}
616 % \VariableIndex{drawcolor}
617 % \VariableIndex{fillcolor}
618 % \VariableIndex{hatchcolor}
619 % \VariableIndex{headcolor}
620 % \VariableIndex{pointcolor}
621 % \VariableIndex{tlabelcolor}
622 % We also define some color variables whose names reflect their use.
623 % Thus, \gbc{fillcolor} is used for filling, etc. The color
624 % \gbc{currentcolor} isn't used anywhere yet. The color
625 % \mfc{background} is used in \MP{} for unfilling a region.
626 % \begin{macrocode}
627 color currentcolor, drawcolor, fillcolor, hatchcolor,
628 headcolor, pointcolor, tlabelcolor, background;
629 currentcolor := fillcolor := drawcolor := hatchcolor :=
630 headcolor := pointcolor := tlabelcolor := black;
631 background := white;
632
633 % \end{macrocode}
634 %
635 % \DescribeRoutine{snapto}
636 % The \gbc{snapto} macro truncates numerics to the $[0,1]$ range, but also
637 % returns a value ($0$) for unknown input. It used to do the same for
638 % nonnumeric input, but that should be an error. It would have made at
639 % least one of our bugs easier to find if it had produced an error message
640 % back then.
641 % \begin{macrocode}
642 vardef snapto expr t =
643 if numeric t:
644 if unknown t: 0
645 elseif t < 0: 0
646 elseif t > 1: 1
647 else: t
648 fi
649 else:
650 GBerrmsg ("Improper expression type.")
651 "The argument to `snapto' must be a numeric.";
652 fi
653
654 enddef;
655
656 % \end{macrocode}
657 %
658 % \DescribeRoutine{cmykgray}
659 % \DescribeRoutine{rgbgray}
660 % Now we deal with all the color functions and utilities that enable
661 % \mfpic{} users to use colors without knowing what they are doing.
662 % Since colors now come in three flavors, we start with gray levels in
663 % the three models. In early \MP{}, the \gbc{cmyk} function will return
664 % an \opt{rgb} color, so there is will be no difference between these
665 % two. In \MF{} \gbc{white} is a numeric and \gbc{cmyk} returns a
666 % numeric, so these can be used with \MF{}, and both produce the same
667 % result.
668 % \begin{macrocode}
669 vardef rgbgray (expr g) = (snapto g) * white enddef;
670 vardef cmykgray (expr g) = cmyk(0,0,0,1 - snapto g) enddef;
671
672 % \end{macrocode}
673 %
674 %
675 % \DescribeRoutine{colorchoice}
676 % The \gbc{colorchoice} function (like \cs{mathchoice} in \TeX{}, after
677 % which it was named) returns one of four bits of code: \gbc{D} (default)
678 % if the first argument is unknown or not one of the recognized color
679 % models, \gbc{N} if it is numeric, \gbc{R} if it is \mfc{rgbcolor}, and
680 % \gbc{C} if it is \mfc{cmykcolor}. These arguments have to be \mfc{text}:
681 % if they were `\mfc{expr}' \MP{} would try to evaluate them, with
682 % possible errors since some of them apply functions that are not relevant
683 % to the other types.
684 %
685 % Since this is mostly used to return values inside vardef's, it is
686 % important this not be followed by a semicolon. If it is used in
687 % another context, semicolons would normally be part of the arguments.
688 % \begin{macrocode}
689 %<*MP>
690 def colorchoice (expr clr) (text D)(text N)(text R)(text C) =
691 if unknown clr: D
692 elseif numeric clr: N
693 elseif rgbcolor clr: R
694 elseif cmykcolor clr: C
695 else: D
696 fi
697 enddef;
698
699 % \end{macrocode}
700 % In recent \MP{}, all the color functions are essentially no-ops. In
701 % early \MP{}, they all return an \opt{rgb} color expression. In \MF{}
702 % they all return a numeric. It is easiest if we simply separate the three
703 % cases (MF, old MP and recent MP) and write the code for each, rather
704 % than load all the functions with three-way booleans (often containing
705 % nested booleans).
706 %
707 % \DescribeRoutine{gray}
708 % \DescribeRoutine{cmyk}
709 % For all three engines we require a definition of the color functions
710 % \gbc{gray(g)}, \gbc{rgb(r,g,b)}, and \gbc{cmyk(c,m,y,k)}, as well as
711 % conversion functions (see below), and the boolean function
712 % \gbc{iscolor}. The first three have to return numerics for \MF{},
713 % colors for early \MP{}, and the associated color type for recent \MP{}.
714 % We delay the definition of \gbc{rgb} because it only requires
715 % distinguishing \MF{} from \MP.
716 %
717 % \DescribeRoutine{grayscalegray}
718 % The grayscale version should return a numeric in recent \MP{}, so
719 % it needs a different definition for early \MP{}. Thus, it occurs
720 % in the conditional code. Oddly, its definition is the same for \MF{}
721 % and recent \MP{}.
722 % \begin{macrocode}
723 if has_cmyk :
724 vardef grayscalegray (expr g) = snapto g enddef;
725 vardef gray (expr g) = grayscalegray (g) enddef;
726 vardef cmyk (expr c, m, y, k) =
727 (snapto c, snapto m, snapto y, snapto k)
728 enddef;
729
730 % \end{macrocode}
731 %
732 % \DescribeRoutine{makecmyk}
733 % \DescribeRoutine{makergb}
734 % \DescribeRoutine{makegray}
735 % In \gbc{makecmyk} and all the other `\gbc{make}' conversions, the
736 % default is to return black in the appropriate model, numerics produce
737 % gray in the appropriate model, and cmyk or rgb is either retained
738 % unchanged or converted to the appropriate model.
739 %
740 % \DescribeRoutine{iscolor}
741 % A variable is taken to be a color if it can validly follow
742 % \mfc{withcolor}. This includes boolean, though we hope no one tries to
743 % use that.
744 % \begin{macrocode}
745 vardef makecmyk primary clr =
746 colorchoice (clr)(cmykblack)(cmykgray(clr))
747 (rgbtocmyk(redpart clr,greenpart clr,bluepart clr))
748 (clr)
749 enddef;
750 vardef makergb primary clr =
751 colorchoice (clr)(rgbblack)(rgbgray(clr))(clr)
752 (cmyktorgb(cyanpart clr, magentapart clr,
753 yellowpart clr, blackpart clr))
754 enddef;
755 vardef makegray primary clr =
756 colorchoice (clr)(grayscaleblack)(grayscalegray(clr))
757 (rgbtogray (redpart clr, greenpart clr, bluepart clr))
758 (cmyktogray(cyanpart clr, magentapart clr,
759 yellowpart clr, blackpart clr))
760 enddef;
761 vardef iscolor expr clr =
762 (rgbcolor clr) or (cmykcolor clr) or (numeric clr) or (boolean clr)
763 enddef;
764 else:
765 % \end{macrocode}
766 %
767 % In early \MP{} \gbc{colorchoice} is only a three-way choice, since
768 % \mfc{cmykcolor} is not a data type, but numeric can still be
769 % interpreted as a gray. For a numeric or an actual rgbcolor, the first or
770 % second branch would be taken. If \gbc{clr} is neither of those then
771 % \mfc{cmykcolor}, being equal to \mfc{rgbcolor}, would also be false.
772 % Therefore, in the context of early \MP{}, it is irrelevant what goes in
773 % the last argument, so we leave it empty.
774 %
775 % \DescribeRoutine{makecmyk}
776 % \DescribeRoutine{makergb}
777 % \DescribeRoutine{makegray}
778 % The \gbc{make*} functions are simpler in early \MP{}, though not as
779 % simple as in \MF{}. Ditto
780 % \DescribeRoutine{iscolor}
781 % \gbc{iscolor}. The parentheses in \gbc{iscolor} are necessary to force
782 % \MP{} to see this \mfc{color} as the start of a boolean expression and
783 % not a type declaration.
784 % \begin{macrocode}
785 vardef gray (expr g) = rgbgray(g) enddef;
786 vardef grayscalegray (expr g) = rgbgray(g) enddef;
787 vardef cmyk (expr c, m, y, k) = rgb (1-c-k, 1-m-k, 1-y-k) enddef;
788 vardef makergb primary clr =
789 colorchoice (clr)(rgbblack)(rgbgray(clr))(clr)()
790 enddef;
791 vardef makegray primary clr =
792 colorchoice (clr)(rgbblack)(rgbgray(clr))
793 (rgbtogray (redpart clr, greenpart clr, bluepart clr))()
794 enddef;
795 def makecmyk = makergb enddef;
796 vardef iscolor expr clr = (color clr) enddef;
797 fi
798
799 %</MP>
800 % \end{macrocode}
801 %
802 % \DescribeRoutine{knowncolor}
803 % Once we have \gbc{iscolor} all we need to do is add a test for
804 % \mfc{known} to get this boolean test.
805 % \begin{macrocode}
806 vardef knowncolor expr clr = (known clr) and (iscolor clr) enddef;
807
808 % \end{macrocode}
809 %
810 % These are the \MF{} versions. Everything pretty much returns its
811 % numeric argument or $0$ (black).
812 % \begin{macrocode}
813 %<*MF>
814 vardef grayscalegray (expr g) = snapto g enddef;
815 vardef gray (expr g) = grayscalegray (g) enddef;
816 vardef cmyk (expr c, m, y, k) = rgb (1-c-k, 1-m-k, 1-y-k) enddef;
817 vardef makegray primary clr =
818 if knowncolor clr: clr else: black fi
819 enddef;
820 def makergb = makegray enddef;
821 def makecmyk = makegray enddef;
822 vardef iscolor expr clr = (color clr) enddef;
823
824 %</MF>
825 % \end{macrocode}
826 %
827 % \DescribeRoutine{forceclr}
828 % \DescribeRoutine{named}
829 % This is only used in the \gbc{named} function to force a color. In
830 % \MF{} the tests are all `\mfc{if numeric}'. In early \MP{} `\mfc{if
831 % cmykcolor}' is the same as `\mfc{if rgbcolor}'.
832 % \begin{macrocode}
833 vardef forceclr (expr c) =
834 if unknown c :
835 if numeric c: grayscaleblack
836 elseif rgbcolor c: rgbblack
837 elseif cmykcolor c: cmykblack
838 else: black
839 fi
840 elseif numeric c: gray (c)
841 elseif iscolor c: c
842 else: black
843 fi
844 enddef;
845 vardef named (suffix c) = forceclr (c) enddef;
846
847 % \end{macrocode}
848 %
849 % \DescribeRoutine{togray}
850 % \DescribeRoutine{rgbtogray}
851 % \DescribeRoutine{cmyktogray}
852 % \DescribeRoutine{cmyktorgb}
853 % \DescribeRoutine{rgbtocmyk}
854 % These are used for the conversions. Strictly speaking they do not
855 % `convert' as they all take multiple numeric arguments rather than any
856 % sort of color. As \mfc{rgbcolor} exists in both early and recent
857 % \MP{} as the same data type, we need only distinguish \MF{} from \MP{}
858 % \DescribeRoutine{rgb}
859 % in the function \gbc{rgb},
860 % \begin{macrocode}
861 vardef togray (expr r, g, b) =
862 gray (sqrt((2r*r + 4g*g + b*b)/7))
863 enddef;
864
865 vardef rgbtogray (expr r, g, b) =
866 togray(snapto r, snapto g, snapto b)
867 enddef;
868 vardef cmyktogray (expr c, m, y, k) =
869 rgbtogray (1-c-k,1-m-k,1-y-k)
870 enddef;
871
872 vardef cmyktorgb (expr c,m,y,k) =
873 rgb(1-c-k,1-m-k,1-y-k)
874 enddef;
875 vardef rgbtocmyk (expr r,g,b) =
876 cmyk(1-r,1-g,1-b,0)
877 enddef;
878
879 vardef rgb (expr r, g, b) =
880 %<MF> togray (snapto r, snapto g, snapto b)
881 %<MP> (snapto r, snapto g, snapto b)
882 enddef;
883 vardef RGB (expr R, G, B) =
884 rgb (R/255, G/255, B/255)
885 enddef;
886
887 % \end{macrocode}
888 %
889 %
890 % \subsection{Arrays}\label{arrays}
891 %
892 % \gbc{ClipPath} is a typical example of an array. Arrays are based on the
893 % fact that a variable can be of a different type from (and can be almost
894 % completely unrelated to) the variables formed by putting numeric
895 % suffixes on it.
896 %
897 % \DescribeRoutine{list}
898 % The \gbc{list} macro is essentially due to Frank Michielsen, and assigns
899 % a \emph{list} (i.e., a comma separated sequence of expressions) to an
900 % array. Note that the items in the list have to be the same type, and the
901 % same type as \mfc{v[\,]}. But \mfc{v} itself must be numeric.
902 %
903 % \DescribeRoutine{map}
904 % The \gbc{map} macro takes two text parameters. The first is any
905 % procedure, the second is a list of expressions. The procedure is applied
906 % to each expression and the resulting new expressions are separated by
907 % commas, that is, a new list is generated (for use in \mfc{for} loops).
908 % This is full of possibilities for errors. One reared its head because
909 % the original version started with a comma indicating an empty starting
910 % expression (normally it would be ignored and that turn through the loop
911 % skipped). However, it managed to produce an error in a reasonable
912 % but unforeseen usage (which I've since forgotten) and so I added the
913 % \gbc{_map} variable that skips the comma on the first time through the
914 % loop. This routine is currently only used in the code that \mfpic's \
915 % \cs{plr} writes.
916 % \begin{macrocode}
917 def list (suffix v) (text lst) =
918 v := 0; for _itm = lst: v[incr v] := _itm; endfor
919 if v = 0:
920 GBerrmsg ("No list to process!")
921 "An attempt was made to produce an array from a "
922 & "list of expressions having no valid entries.";
923 fi
924 enddef;
925
926 def map (text proc) (text lst) =
927 hide (_map := 0;)
928 for _a = lst:
929 if _map = 0: hide (_map := 1;) else: , fi
930 proc (_a)
931 endfor
932 enddef;
933
934 % \end{macrocode}
935 %
936 % \DescribeRoutine{knownnumericarray}
937 % Checks if a suffix is the name of an array. Requires \gbc{arr} to be a
938 % known positive integer, and all the variables \gbc{arr[n]} to be known
939 % for \gbc{n} from 1 to \gbc{arr}. Since we so far only need it for
940 % numeric arrays, we also check if each entry is numeric.
941 % \begin{macrocode}
942 vardef knownnumericarray suffix arr =
943 setboolean (_kna) (known arr) and (numeric arr);
944 if _kna :
945 _kna := (arr = floor arr) and (arr >= 1);
946 for _idx = 1 upto arr :
947 exitif not _kna;
948 _kna := (known arr[_idx]) and (numeric arr[_idx]);
949 endfor
950 fi
951 _kna
952 enddef;
953
954 % \end{macrocode}
955 %
956 % \DescribeRoutine{copyarray}
957 % This makes some code much more readable. It simply steps through an
958 % array and copies the values into another array. It is only used for
959 % numeric arrays so far, but could be used for any kind.
960 % \begin{macrocode}
961 def copyarray (suffix src, dest) =
962 for _idx = 1 upto src: dest[_idx] := src[_idx]; endfor
963 dest := src;
964 enddef;
965
966 % \end{macrocode}
967 %
968 % \DescribeRoutine{maparr}
969 % The \gbc{maparr} macro applies a procedure \gbc{proc} to each member of
970 % array \gbc{p[\,]} with \gbc{p} members. It returns nothing. It is currently
971 % unused, although it was once used for things like \gbc{maxpair}.
972 % \begin{macrocode}
973 def maparr (text proc) (suffix p) =
974 for _idx = 1 upto p: proc (p[_idx]); endfor
975 enddef;
976
977 % \end{macrocode}
978 %
979 % \DescribeRoutine{textpairs}
980 % This macro takes a suffix (name of an array to be constructed) and a
981 % list of pairs, and assigns them to the array. It is normally called from
982 % another macro, which does any necessary \mfc{save}-ing of the variable
983 % used for the array name. We used to include \mfc{save} in this macro,
984 % but ran into a problem once when the argument had a suffix. You can't
985 % apply \mfc{save} to a variable with a suffix. Moreover, `\mfc{save p}'
986 % also renders \mfc{p.x} unknown, so I judged it best to let whoever calls
987 % this macro decide what to save. Actually, now it expands to the more
988 % general command \gbc{gsetarray} with type \gbc{pair}. That command
989 % then reads the suffix argument that should follow.
990 %
991 % Since the above change was made, macros evolved so that \emph{all} uses
992 % of \gbc{textpairs} are now preceeded by \gbc{save}. Thus, I have now
993 % replaced them all with calls to \gbc{setpairs} (it calls \gbc{setarray},
994 % which \emph{does} \gbc{save} the variable). In all those cases, the
995 % `\gbc{saved}' variable is a temporary local array.
996 %
997 % \DescribeRoutine{setuniquepairs}
998 % This does the same but omits any pair if it is identical to the previous
999 % one. It \mfc{save}\,s the variable, since all its uses are internal
1000 % and require that.
1001 % \begin{macrocode}
1002 def textpairs = gsetarray (pair) enddef;
1003
1004 def setuniquepairs (suffix p) (text t) =
1005 save p; pair p[];
1006 setpairs (_up) (t);
1007 if _up > 0:
1008 p := 1; p1 := _up1;
1009 for _i = 2 upto _up:
1010 if _up[_i] <> p[p]: p[incr p] := _up[_i]; fi
1011 endfor
1012 else:
1013 p := 0;
1014 fi
1015 enddef;
1016
1017 % \end{macrocode}
1018 %
1019 %
1020 % \subsection{Utilities}\label{utilities}
1021 %
1022 % \DescribeRoutine{chpair}
1023 % This applies a procedure \gbc{proc} (which maps numeric to numeric) to
1024 % each part of pair \gbc{p}, and returns the resultant pair. I've decided
1025 % not to use it (for efficiency), but to leave it defined for backward
1026 % compatibility.\\
1027 % \DescribeRoutine{floorpair}
1028 % \gbc{floorpair} applies \mfc{floor} to both parts of a pair.\\
1029 % \DescribeRoutine{ceilingpair}
1030 % \gbc{ceilingpair} does the same with \gbc{ceiling}.\\
1031 % \DescribeRoutine{hroundpair}
1032 % \gbc{hroundpair} does the same with \gbc{hround}.
1033 %
1034 % All three could use \gbc{chpair} with \gbc{proc} equal to \mfc{floor},
1035 % \mfc{ceiling} and \mfc{hround}, but I now code them directly.
1036 %
1037 % \DescribeRoutine{goodpair}
1038 % This last one is used (only in \MF{}) to adjust pairs to the pixel grid.
1039 % It is the only place \gbc{hroundpair} is used. None of these is used in
1040 % the \MP{} version.
1041 % \begin{macrocode}
1042 vardef chpair (text proc) (expr p) =
1043 (proc (xpart p), proc (ypart p))
1044 enddef;
1045
1046 vardef floorpair (expr p) = (floor (xpart p), floor (ypart p))
1047 enddef;
1048 vardef ceilingpair (expr p) = (ceiling (xpart p), ceiling (ypart p))
1049 enddef;
1050
1051 %<*MF>
1052 def hroundpair (expr p) = (hround (xpart p), hround (ypart p))
1053 enddef;
1054 vardef goodpair (expr p) = hroundpair(p.t_) enddef;
1055
1056 %</MF>
1057 % \end{macrocode}
1058 %
1059 % \DescribeRoutine{emin}
1060 % The macro \gbc{emin} differs from \prog{plain}'s \mfc{min} in that it
1061 % allows only two values. It can therefore be coded simply, without the
1062 % overhead of a \mfc{for}-loop.
1063 % \DescribeRoutine{emax}
1064 % \gbc{emax} is analogous. Both are needed so often that it is possible a
1065 % significant amount of time is saved with these versions.
1066 %
1067 % \DescribeRoutine{pairmin}
1068 % The macro \gbc{pairmin} operates on two pairs, returning a pair having
1069 % the smaller of the two xparts and the smaller of the two yparts. Of
1070 % course
1071 % \DescribeRoutine{pairmax}
1072 % \gbc{pairmax} is analogous, producing the maximum.
1073 %
1074 % \DescribeRoutine{minpair}
1075 % The \gbc{minpair} macro returns the pair comprising the minimum $x$ and
1076 % minimum $y$ coordinates of all pairs in the array \gbc{p[\,]}.
1077 % \DescribeRoutine{maxpair}
1078 % \gbc{maxpair} is analogous. Somehow, both of them have disappeared from
1079 % \grafbase. They were formerly used only in the \gbc{*bbox} macros.
1080 % That code used a loop to build an array of control points and these
1081 % routines would \emph{each} loop through that. The current code uses one
1082 % loop (instead of three) through the control points, updating both the
1083 % maximum and minimum at each one.
1084 % \begin{macrocode}
1085 vardef emin (expr a, b) = if a < b: a else: b fi enddef;
1086 vardef emax (expr a, b) = if a > b: a else: b fi enddef;
1087
1088 vardef pairmin (expr z, w) =
1089 ( emin (xpart z, xpart w), emin (ypart z, ypart w ) )
1090 enddef;
1091 vardef pairmax (expr z, w) =
1092 ( emax (xpart z, xpart w), emax (ypart z, ypart w ) )
1093 enddef;
1094
1095 vardef minpair (suffix p) = setpair (_mp) p1;
1096 for _idx = 2 upto p - 1: _mp := pairmin (_mp, p[_idx]); endfor
1097 pairmin (_mp, p[p])
1098 enddef;
1099 vardef maxpair (suffix p) = setpair (_mp) p1;
1100 for _idx = 2 upto p - 1: _mp := pairmax (_mp, p[_idx]); endfor
1101 pairmax (_mp, p[p])
1102 enddef;
1103
1104 % \end{macrocode}
1105 %
1106 % \DescribeRoutine{xprod}
1107 % A binary operation between pairs $z\sb1$ and $z\sb2$ that returns the
1108 % cross product $x\sb1 y\sb2 - x\sb2 y\sb1$. This gives, among other
1109 % things, twice the area of the triangle with two sides $z\sb1$ and
1110 % $z\sb2$. It is used only in \gbc{mkconvex}.
1111 % \begin{macrocode}
1112 primarydef Z xprod W = (xpart Z * ypart W - xpart W * ypart Z)
1113 enddef;
1114
1115 % \end{macrocode}
1116 %
1117 % \DescribeRoutine{force_initial}
1118 % The command \gbc{force_initial} modifies a path so that it has all the
1119 % same points and controls as before, except its first point is replaced
1120 % with \mfc{p}.
1121 % \DescribeRoutine{force_terminal}
1122 % The command \gbc{force_terminal} replaces the last point. This is for
1123 % cases where, theoretically, paths \gbc{f} and \gbc{g} should meet at an
1124 % endpoint, but do not due to finite precision. Instead of doing
1125 % \mfc{f..g}, which adds a random tiny segment, we adjust the endpoints to
1126 % exactly match the other and do \mfc{f\&g}, producing a join without an
1127 % additional segment.
1128 %
1129 % \DescribeRoutine{force_equal_ends}
1130 % The command \gbc{force_equal_ends} forces the last point of the first
1131 % path and the first point of the second to equal the average of their
1132 % original values. It is the only one of these four actually used anywhere
1133 % else in \grafbase.
1134 % \DescribeRoutine{replace_ends_of_cycle}
1135 % The command \gbc{replace_ends_of_cycle} applies something similar to a
1136 % cycle.
1137 % \begin{macrocode}
1138 def force_initial (expr p) (suffix f) =
1139 hide( setnumeric (_n) length f;
1140 f := p
1141 if _n = 0:
1142 {0,0}
1143 else:
1144 ..controls post0 (f) and pre 1 (f).. subpath (1,_n) of f
1145 fi;)
1146 enddef;
1147
1148 def force_terminal (expr p) (suffix f) =
1149 hide(setpath (_f) reverse f;
1150 force_initial (p) (_f);
1151 f := reverse _f;)
1152 enddef;
1153
1154 def force_equal_ends (suffix f, g) =
1155 hide(save _p; pair _p;
1156 _p := .5[pnt[length f] (f), pnt0(g)];
1157 force_terminal (_p) (f); force_initial (_p) (g);)
1158 enddef;
1159
1160 def replace_ends_of_cycle (expr p) (suffix f) =
1161 hide(
1162 if cycle f:
1163 save _n; _n := length f;
1164 f := p
1165 if _n = 0: &cycle
1166 else: .. controls post0 (f) and pre 1 (f) ..
1167 if _n = 1: cycle
1168 else: subpath (1, _n - 1) of f ..
1169 controls post[_n - 1](f) and pre[_n](f) .. cycle
1170 fi
1171 fi;
1172 fi)
1173 enddef;
1174
1175 % \end{macrocode}
1176 %
1177 % \DescribeRoutine{intersects}
1178 % A binary relation, with the precedence level (almost) that of other
1179 % relations, produces \mfc{true} if \MF{} determines that the paths
1180 % intersect, false otherwise. It also
1181 % \DescribeVariable{thetimes}
1182 % sets the pair variable \gbc{thetimes} and its parts \gbc{_Xtime} and
1183 % \gbc{_Ytime}. Then
1184 % \DescribeRoutine{misses}
1185 % \gbc{misses} is the opposite relation, used when the intersection point
1186 % is not needed. It only occurs in the (unused) code of \gbc{tightbbox}.
1187 % \begin{macrocode}
1188 pair thetimes;
1189 numeric _Xtime, _Ytime;
1190 tertiarydef a intersects b =
1191 begingroup
1192 thetimes := a intersectiontimes b;
1193 _Xtime := xpart thetimes;
1194 _Ytime := ypart thetimes;
1195 (_Xtime > -1)
1196 endgroup
1197 enddef;
1198
1199 tertiarydef a misses b = ((a intersectiontimes b) < origin) enddef;
1200
1201 % \end{macrocode}
1202 %
1203 % \DescribeRoutine{makepicture}
1204 % The \gbc{makepicture} command takes any expression and does what it can
1205 % to make a picture from it.
1206 %
1207 % \DescribeRoutine{onepointpath}
1208 % The \gbc{onepointpath} command takes a point and forces it to be a path.
1209 % If a vardef takes a list of points and it \emph{must} return a path that
1210 % perhaps \emph{must} be cyclic, it can use this as a fallback. If an
1211 % \mfpic{} command such as \cs{arc} receives an invalid optional
1212 % parameter, it won't know what command to write to the output file. It
1213 % can use
1214 % \DescribeRoutine{fallbackpath}
1215 % \gbc{fallbackpath} as long as the first parameter is a point.
1216 %
1217 % \DescribeRoutine{even}
1218 % \DescribeRoutine{divides}
1219 % Of course \gbc{even} means \gbc{not odd}. The relation \gbc{divides}
1220 % is true if the right side is an integer multiple of the left.
1221 % \begin{macrocode}
1222 vardef makepicture (expr s) =
1223 if picture s: s
1224 %<MP> elseif string s: s infont defaultfont scaled defaultscale
1225 elseif path s: picpath (s)
1226 else: nullpicture
1227 fi
1228 enddef;
1229
1230 vardef onepointpath (expr cyclic, q) =
1231 q if cyclic: &cycle else: {0,0} fi
1232 enddef;
1233
1234 vardef fallbackpath (expr cyclic, p) (text t) =
1235 onepointpath (cyclic, p)
1236 enddef;
1237
1238 def even = not odd enddef;
1239
1240 primarydef a divides b =
1241 ((b mod a) = 0)
1242 enddef;
1243
1244 % \end{macrocode}
1245 %
1246 % \DescribeRoutine{image}
1247 % The \mfc{image} macro exists in \file{plain.mp} but not \file{plain.mf}.
1248 % The purpose is to just use the \file{plain} \MF{} and \grafbase{} macros
1249 % as you normally would, but wrap the whole thing in parentheses preceded
1250 % by \gbc{X := image} to get all those things drawn on the picture
1251 % variable \gbc{X}.
1252 %
1253 % \DescribeRoutine{beginimage}
1254 % Instead of making lengthy drawing code a parameter, one might prefer an
1255 % environment-like syntax, writing \gbc{X := beginimage } at the start
1256 % and
1257 % \DescribeRoutine{endimage}
1258 % \gbc{endimage} at the end.
1259 %
1260 % \DescribeRoutine{makeimage}
1261 % This is for the \mfpic{} command \cs{mfpimage}. It takes a suffix
1262 % parameter (the name of the picture variable) and a coordinate pair (in
1263 % graph coordinates). The drawing commands, up to the following
1264 % \gbc{endimage}, draw on this picture variable with the given pair as the
1265 % reference point.
1266 % \begin{macrocode}
1267 %<*MF>
1268 vardef image (text t) =
1269 newpicture (currentpicture);
1270 t;
1271 currentpicture
1272 enddef;
1273
1274 %</MF>
1275 def beginimage =
1276 begingroup
1277 newpicture (currentpicture);
1278 enddef;
1279 def endimage =
1280 ; currentpicture
1281 endgroup
1282 enddef;
1283
1284 def makeimage (suffix name) (expr refpt) =
1285 setpair (_image_reference_point) zconv (refpt);
1286 setpicture (name) beginimage
1287 enddef;
1288 def concludeimage =
1289 endimage shifted
1290 %<MF> -goodpair (_image_reference_point)
1291 %<MP> -_image_reference_point
1292 enddef;
1293
1294 % \end{macrocode}
1295 %
1296 % \DescribeRoutine{setvariable}
1297 % This is are mainly to save space in \mfpic-generated files. In \grafbase{}
1298 % itself the \mfc{save} is often inconvenient, but it turns out there are
1299 % many cases where it \emph{is} used; enough so that we have abbreviations
1300 % \RoutineIndex{setnumeric}\gbc{setnumeric},
1301 % \RoutineIndex{setboolean}\gbc{setboolean},
1302 % \RoutineIndex{setpair}\gbc{setpair},
1303 % \RoutineIndex{setpath}\gbc{setpath},
1304 % \RoutineIndex{setpicture}\gbc{setpicture},
1305 % and \RoutineIndex{setstring}\gbc{setstring}, together with the
1306 % common uses \RoutineIndex{newpicture}\gbc{newpicture} and
1307 % \RoutineIndex{convertpath}\gbc{convertpath}. There is also a
1308 % \gbc{setcolor}, but that has such a different definition that we reserve
1309 % it for later.
1310 %
1311 % For completeness, we also include the remaining two abbreviations,
1312 % \RoutineIndex{setpen}\gbc{setpen} and
1313 % \RoutineIndex{settransform}\gbc{settransform}, even though they are not
1314 % used anywhere in \grafbase{}.
1315 %
1316 % \DescribeRoutine{gsetvariable}
1317 % The macro \gbc{gsetvariable} is the global version. It has no
1318 % abbreviations, but it is occasionally needed for \mfpic{}. The only
1319 % difference between it and the local version is the lack of a
1320 % \gbc{save}. None of these commands take the value as a parameter. That
1321 % should follow, and is picked up by the ending \mfc{:=}.
1322 %
1323 % \DescribeRoutine{setarray}
1324 % Then \gbc{setarray} is the array version. It takes the same parameters
1325 % as \gbc{setvariable}, but what should follow is a list of expressions in
1326 % parentheses. It calls \gbc{list} to read each item into
1327 % \gbc{name1}, \gbc{name2}, etc. There is also has a global version
1328 % \DescribeRoutine{gsetarray}
1329 % \gbc{gsetarray}.
1330 % \DescribeRoutine{setpairs}
1331 % \gbc{setpairs} is an abbreviation for arrays
1332 % of pairs. Historically, it came first.
1333 % \begin{macrocode}
1334 def setvariable (text kind) (suffix name) =
1335 save name; kind name; name :=
1336 enddef;
1337 def gsetvariable (text kind) (suffix name) = kind name; name :=
1338 enddef;
1339
1340 def setnumeric (suffix name) = save name; name := enddef;
1341 def setboolean = setvariable (boolean) enddef;
1342 def setpair = setvariable (pair) enddef;
1343 def setpath = setvariable (path) enddef;
1344 def setpicture = setvariable (picture) enddef;
1345 def setstring = setvariable (string) enddef;
1346 def settransform = setvariable (transform) enddef;
1347 def setpen = setvariable (pen) enddef;
1348 def settension (suffix tn) expr tens =
1349 setnumeric (tn) if tens > 0: tens else: default_tension fi;
1350 enddef;
1351 def fixtension (suffix tn) = if tn < .75: tn := .75; fi enddef;
1352
1353 def newpicture (suffix pic) = setpicture (pic) nullpicture; enddef;
1354 def convertpath (suffix g) expr f = setpath (g) zconv (f); enddef;
1355
1356 def setarray (text kind) (suffix name) =
1357 save name; kind name[]; list (name)
1358 enddef;
1359 def setpairs = setarray (pair) enddef;
1360 def gsetarray (text kind) (suffix name) =
1361 numeric name; kind name[]; list (name)
1362 enddef;
1363
1364 % \end{macrocode}
1365 % The next are slightly different, but seem to belong here.
1366
1367 % \DescribeRoutine{setbbox}
1368 % In \gbc{setbbox} we save and initialize \emph{two} pair variables and
1369 % set them to the bounding box of a path that should follow.
1370 %
1371 % \DescribeRoutine{setsplit}
1372 % There are a couple of routines that modify a variable to make sure it is
1373 % positive and integral. In a couple of places two routine \emph{must} use
1374 % the same value. Here we isolate the code that does the modification, and
1375 % then both routines call \gbc{setsplit}.
1376 % \begin{macrocode}
1377 def setbbox (suffix ll, ur) =
1378 save ll, ur; pair ll, ur; getbbox (ll, ur)
1379 enddef;
1380
1381 def setsplit (suffix s) expr ss =
1382 setnumeric (s) emax (1, ceiling ss);
1383 enddef;
1384
1385 %<*MP>
1386 if has_cmyk:
1387 def setrgbcolor = setvariable (rgbcolor) enddef;
1388 def setcmykcolor = setvariable (cmykcolor) enddef;
1389 def setcolor (suffix name) expr val =
1390 if boolean val : setboolean
1391 elseif numeric val : setnumeric
1392 elseif rgbcolor val : setrgbcolor
1393 elseif cmykcolor val : setcmykcolor
1394 % this should give a suitable error message:
1395 else: setvariable (color)
1396 fi (name) val;
1397 enddef;
1398 def gsetcolor (suffix name) expr val =
1399 if boolean val : boolean name;
1400 elseif numeric val : numeric name;
1401 elseif rgbcolor val : rgbcolor name;
1402 elseif cmykcolor val : cmykcolor name;
1403 else: color name;
1404 fi name := val;
1405 enddef;
1406 else:
1407 def setrgbcolor = setcolor enddef;
1408 def setcmykcolor = setcolor enddef;
1409 def setcolor = setvariable (color) enddef;
1410 def gsetcolor = gsetvariable (color) enddef;
1411 fi
1412 %</MP>
1413 %<*MF>
1414 def setrgbcolor = setcolor enddef;
1415 def setcmykcolor = setcolor enddef;
1416 def setcolor = setvariable (color) enddef;
1417 def gsetcolor = gsetvariable (color) enddef;
1418 %</MF>
1419
1420 % \end{macrocode}
1421 %
1422 % And then the standard colors. Using the color functions ensures that
1423 % they are defined in \MF{} as well as all versions of \MP{}. In early
1424 % \MP{} they are all \mfc{rgbcolor}, in \MF{} they are all numeric. In
1425 % recent \MP{}, they have the type correspondimg to the name of the
1426 % color function, with \gbc{gray()} being numeric.
1427 % \begin{macrocode}
1428 setcolor(rgbblack) rgb(0,0,0);
1429 setcolor(red) rgb(1,0,0);
1430 setcolor(green) rgb(0,1,0);
1431 setcolor(blue) rgb(0,0,1);
1432 setcolor(rgbwhite) rgb(1,1,1);
1433 setcolor(cmykwhite) cmyk(0,0,0,0);
1434 setcolor(cyan) cmyk(1,0,0,0); % Maybe these should
1435 setcolor(magenta) cmyk(0,1,0,0); % be rbg for backward
1436 setcolor(yellow) cmyk(0,0,1,0); % compatibility?
1437 setcolor(cmykblack) cmyk(0,0,0,1);
1438 setcolor(grayscaleblack) gray(0);
1439 setcolor(grayscalewhite) gray(1);
1440
1441 %<*MP>
1442 if has_outputtemplate:
1443 def setoutputtemplate = outputtemplate := enddef;
1444 elseif has_filenametemplate:
1445 def setoutputtemplate = filenametemplate enddef;
1446 else:
1447 def setoutputtemplate text garbage = enddef;
1448 fi
1449 %</MP>
1450 %<MF>def setoutputtemplate text garbage = enddef;
1451
1452 % \end{macrocode}
1453 %
1454 % \DescribeRoutine{GBromannumeral}
1455 % We will append roman numerals to the ends of a variable name to
1456 % emulate an array. This will be needed when our `array' consists of
1457 % colors with different types. \MP{} doesn't permit true arrays to
1458 % contain different types. We use `\gbc{GB}' in the name because a
1459 % package exists that defines \mfc{romannumeral} differently
1460 %
1461 % \DescribeRoutine{GBromandigit}
1462 % Roman numerals can conveniently be computed one digit at a time. The
1463 % algorithm is the same for each digit, differing only in the letters
1464 % used. Thus we define \gbc{GBromandigit} and call it three times with
1465 % different sets of letters.
1466 %
1467 % \DescribeRoutine{strrepeat}
1468 % The helper macro \gbc{strrepeat} creates a new string by concatenating
1469 % \mfc{rep} copies of the string \mfc{str}.
1470 % \begin{macrocode}
1471 vardef GBromannumeral (expr X) =
1472 save Y, _tmp, U; string U;
1473
1474 Y.m := X div 1000; % thousands digit
1475 _tmp := X - 1000Y.m; % hundreds digits and lower
1476 Y.c := _tmp div 100; % hundreds
1477 _tmp := _tmp - 100Y.c; % tens and units
1478 Y.x := _tmp div 10; % tens
1479 Y.i := _tmp - 10Y.x; % units
1480
1481 strrepeat("m", Y.m) &
1482 GBromandigit("c", "d", "m", Y.c) &
1483 GBromandigit("x", "l", "c", Y.x) &
1484 GBromandigit("i", "v", "x", Y.i)
1485 enddef;
1486
1487 vardef GBromandigit (expr bot, mid, top, n) =
1488 if n > 9 : top & strrepeat(bot, n-10) % shouldn't happen
1489 elseif n > 8 :
1490 bot & top % "ix"
1491 elseif n > 4 : mid & strrepeat (bot, n-5) % "v"--"viii"
1492 elseif n > 3 :
1493 bot & mid % "iv"
1494 else: strrepeat (bot, n) % ""--"iii" for 0--3
1495 fi
1496 enddef;
1497
1498 vardef strrepeat (expr st, rep) =
1499 "" for i = 1 upto rep: & st endfor
1500 enddef;
1501
1502 % \end{macrocode}
1503 %
1504 %
1505 %
1506 % \section{The \grafbase{} Coordinate System}\label{coordinate}
1507 %
1508 % We need to make a distinction between graph units, sharped units, and
1509 % device units. In \MF, a device unit is 1 pixel. On a LaserJet IV, one
1510 % inch is 600 pixels. When constructing a character, \MF{} uses the pixel
1511 % as its unit. Since this differs from one printing device to another,
1512 % \file{plain.mf} arranges for \emph{sharped} units (the name comes from the
1513 % convention that they are written using a name that ends in \mfc{\#}). The
1514 % dimension \mfc{1pt\#} in \MF{} is arbitrarily set to 1, and other
1515 % units defined by conversion factors (\mfc{in\#=72.27}; neither \MF{}
1516 % nor \MP{} makes a distinction between distances and numbers: \mfc{2pt}
1517 % just means \mfc{2} times the value of \mfc{pt}). When one needs to
1518 % draw something actually \emph{one point long}, then \mfc{1pt} is used.
1519 % It is defined to equal \mfc{pt\#*hppp}, where \mfc{hppp} stands for
1520 % ``horizontal pixels per point'' and its value is usually set by
1521 % \mfc{mode_setup}. So \mfc{1pt} is $600/72.27$ (pixels) if
1522 % \mfc{mode} is \mfc{ljfour}.
1523 %
1524 % Often, when we want numbers not to become too large, we do calculations,
1525 % define paths, etc., in sharped units, then draw by scaling to device
1526 % units. In \grafbase{} we take this one step further: a horizontal graph
1527 % unit (i.e., the difference between the graph points $(0,0)$ and $(1,0)$)
1528 % represents \gbc{unitlen*xscale} sharped units, and
1529 % \gbc{unitlen*xscale*hppp} actual pixels. The \grafbase{} macros do much
1530 % of the calculations in graph units.
1531 %
1532 % In \MP, there is no difference between device and sharped units.
1533 % The \emph{postscript point} or \emph{big point} (1/72 inches) is the
1534 % unit in \MP: \mfc{bp = 1}.
1535 %
1536 % Some things need to be in graph units (for example, positions within a
1537 % graph defined by the user) or independent of units (standard shapes)
1538 % that scale appropriately when scales change. Other things (thickness of
1539 % lines) are a design decision that either should be independent of scale
1540 % or should scale in a nonobvious way. The diameter of the drawing pen is
1541 % one of the latter things, so the default pen width is in device units.
1542 % Also for the hatching pen.
1543 %
1544 % When drawing a path we want to use device coordinates. When defining
1545 % paths, we typically want to use graph coordinates. The macros that do
1546 % the drawing, therefore, need to convert from one to the other. In
1547 % addition, for inclusion of the picture in a \TeX{} document, we normally
1548 % want the lower left corner of the graph space to have device coordinates
1549 % $(0,0)$.
1550 %
1551 %
1552 % \subsection{The main transforms}\label{ztr}
1553 %
1554 % \DescribeVariable{vtr}
1555 % We therefore have two transforms: \gbc{vtr} is the \emph{vector} or
1556 % linear transform for pair quantities that remain invariant under shifts,
1557 % and
1558 % \DescribeVariable{ztr}
1559 % \gbc{ztr} is a \emph{point} or affine transformation for pair quantities
1560 % that change appropriately under shifts.
1561 %
1562 % The quantities \gbc{xneg}, \gbc{xpos}, \gbc{yneg}, and \gbc{ypos} are
1563 % in \emph{graph} coordinates. Shifting by \gbc{(-xneg, -yneg)} transforms
1564 % the lower left corner to $(0,0)$. Multiplication by \gbc{xscale} and
1565 % \gbc{yscale} converts to multiples of \gbc{unitlen} and multiplication
1566 % by \gbc{unitlen} gets us sharped coordinates. For \MF{},
1567 % multiplication by \mfc{hppp} converts to device coordinates, while for
1568 % \MP{} sharped and device are the same (the printer's PostScript
1569 % rasterizing engine---\prog{GhostScript} perhaps---does the final
1570 % conversion to actual pixels).
1571 %
1572 % In \MF{}, \mfc{currenttransform} (via the macro \mfc{.t_}, defined by
1573 % \mfc{mode_setup}) takes care of the aspect ratio. In \MP{} the final
1574 % rasterizer should do this.
1575 %
1576 % \gbc{charwd} and \gbc{charht} are sharped coordinates defined by the
1577 % startup code \gbc{beginmfpic}, while \gbc{w_} and \gbc{h_} are the
1578 % corresponding device (pixel) coordinates
1579 %
1580 % \DescribeRoutine{setztr}
1581 % This macro does the defining of \gbc{ztr} and \gbc{vtr}. It is called
1582 % by \gbc{beginmfpic}, at which time all the necessary quantities should be
1583 % known.
1584 % \begin{macrocode}
1585 transform ztr, vtr;
1586 def setztr =
1587 if debug:
1588 GBdebug;
1589 %<*MF>
1590 >> "charwd = " & decimal charwd & "pt#";
1591 >> "charht = " & decimal charht & "pt#";
1592 >> "w_ = " & decimal w_ & " pixels";
1593 >> "h_ = " & decimal h_ & " pixels";
1594 >> "unitlen = " & decimal unitlen & "pt#";
1595 >> "hppp = " & decimal hppp;
1596 %</MF>
1597 %<*MP>
1598 >> "w_ = " & decimal w_ & "bp";
1599 >> "h_ = " & decimal h_ & "bp";
1600 >> "unitlen = " & decimal unitlen & "bp";
1601 %</MP>
1602 >> "xneg = " & decimal xneg;
1603 >> "xpos = " & decimal xpos;
1604 >> "yneg = " & decimal yneg;
1605 >> "ypos = " & decimal ypos;
1606 >> "xscale = " & decimal xscale;
1607 >> "yscale = " & decimal yscale;
1608 GBenddebug;
1609 fi
1610 save ztr, vtr;
1611 transform ztr, vtr;
1612 vtr := identity xscaled xscale yscaled yscale scaled (unitlen*hppp);
1613 ztr := identity shifted (-xneg, -yneg) transformed vtr;
1614 if debug:
1615 GBdebug;
1616 >> "ztr is";
1617 show ztr;
1618 >> "vtr is";
1619 show vtr;
1620 GBenddebug;
1621 fi
1622 enddef;
1623
1624 % \end{macrocode}
1625 %
1626 % \DescribeRoutine{zconv}
1627 % The macro \gbc{zconv} converts a variety of expressions from graph to
1628 % device coordinates. The expressions include pairs, paths, and transforms.
1629 % This is an affine transform. The inverse,
1630 % \DescribeRoutine{invzconv}
1631 % \gbc{invzconv}, converts a variety of expressions from device to graph
1632 % coordinates.
1633 %
1634 % \DescribeRoutine{vconv}
1635 % The vector version, \gbc{vconv}, converts a vector \gbc{v} from graph to
1636 % device coordinates. This is a linear (ie, vector) transform. Also,
1637 % \DescribeRoutine{invvconv}
1638 % \gbc{invvconv} converts a vector from device to graph coordinates.
1639 % \begin{macrocode}
1640 vardef zconv (expr a) = a transformed ztr enddef;
1641 vardef invzconv (expr a) = a transformed (inverse ztr) enddef;
1642 vardef vconv (expr v) = v transformed vtr enddef;
1643 vardef invvconv (expr v) = v transformed (inverse vtr) enddef;
1644
1645 % \end{macrocode}
1646 %
1647 %
1648 % \subsection{The \gbc{mfpic} environment}\label{mfpic}
1649 %
1650 % \DescribeRoutine{active_plane}
1651 % \gbc{active_plane} is the active drawing plane. \mfc{currentpicture} is
1652 % unknown at this stage (because it's set in \gbc{beginmfpic}). We use a
1653 % \mfc{def}, and not a picture assignment, partly for this reason but also
1654 % because we can achieve special effects by redefining it (see the
1655 % \gbc{tile} macro).
1656 % \begin{macrocode}
1657 def active_plane = currentpicture enddef;
1658
1659 % \end{macrocode}
1660 %
1661 % \DescribeRoutine{initpic}
1662 % \gbc{initpic} is called by \gbc{beginmfpic} after \gbc{w_} and
1663 % \gbc{h_} are defined. At this point \gbc{xneg}, \gbc{xscale}, etc.,
1664 % have known values and \gbc{setztr} can define the transforms that are
1665 % based on them. Also, the default \gbc{drawpen} is initialized and the
1666 % boundary of the graph space is assigned to the clipping array.
1667 %
1668 % If \gbc{underlaylabels} is true, we try to make them part of the
1669 % background, adding them to the picture variable \gbc{background_labels}.
1670 % Just before shipout, the picture is placed on top of these labels.
1671 %
1672 % If \gbc{overlaylabels} is \gbc{true}, we try to make labels in \MP{}
1673 % behave the same as labels in \TeX{} (for \mfpic) by adding the labels
1674 % on last. We do this by adding them to the picture variable
1675 % \gbc{foreground_labels} as they occur, then add that picture onto
1676 % \gbc{active_plane} just before shipout. For backward compatibility,
1677 % the default for \gbc{overlaylabels} is \gbc{false}.
1678 %
1679 % We initialize \gbc{foreground_labels} and \gbc{background_labels} here. The
1680 % pair variables \gbc{labelbb.ll} and \gbc{labelbb.ur} keep track of the
1681 % bounding box of added labels in case \gbc{overlaylabels},
1682 % \gbc{truebbox}, and \gbc{clipall} are all \gbc{false}.
1683 % \begin{macrocode}
1684 %<*MP>
1685 boolean overlaylabels, underlaylabels, havebackground;
1686 overlaylabels := false;
1687 underlaylabels := false;
1688 havebackground := false;
1689
1690 %</MP>
1691 def initpic =
1692 setztr;
1693 resizedrawpen (penwd);
1694 if ClipOn: ClipPath := 1;
1695 ClipPath1 := rect (origin, (w_, h_));
1696 fi
1697 if debug:
1698 GBdebug;
1699 >> "Drawing nominal bounding box around picture";
1700 GBenddebug;
1701 noclip ( safedraw rect (origin, (w_, h_)) );
1702 fi
1703 %<*MP>
1704 newpicture (foreground_labels);
1705 newpicture (background_labels);
1706 havebackground := false;
1707 save labelbb; pair labelbb.ll, labelbb.ur;
1708 labelbb.ll := labelbb.ur := origin;
1709 %</MP>
1710 enddef;
1711
1712 % \end{macrocode}
1713 %
1714 % \DescribeRoutine{mfpicenv}
1715 % We define a \gbc{mfpicenv} environment for compatibility with older
1716 % \file{graphbase.mf} (mainly for \prog{fig2dev}'s \file{genmf.c}).
1717 % \DescribeRoutine{endmfpicenv}
1718 % Actually, I have no idea if \prog{fig2dev} even works with the current
1719 % \mfpic.
1720 %
1721 % \DescribeRoutine{bounds}
1722 % This also used to be unused, for compatibility only, but I decided it was a
1723 % convenient abbreviation and \mfpic{} uses it again.
1724 % \begin{macrocode}
1725 def mfpicenv = enddef;
1726 def endmfpicenv = enddef;
1727 def bounds (expr a, b, c, d) =
1728 xneg := a; xpos := b;
1729 yneg := c; ypos := d;
1730 enddef;
1731
1732 % \end{macrocode}
1733 %
1734 % \DescribeRoutine{beginmfpic}
1735 % This is the figure wrapper. \mfpic{} used to begin with figure 1 and
1736 % progressively increment the number. The current value of \gbc{gcode} was
1737 % always equal to the current figure number. Now, \mfpic{} explicitly
1738 % writes the figure number, so we assign \gbc{gcode} to that number in
1739 % case any old files made use of the current number through the
1740 % \gbc{gcode} variable.
1741 %
1742 % Originally, \gbc{beginmfpic} defined \mfc{w}, \mfc{h} and \mfc{d}, but
1743 % that caused problems if an \mfpic{} user tried to store a path in a
1744 % variable named \gbc{h}, etc. So now we use the less obvious names ending
1745 % in underscore. Apart from this, the code below is a clone of
1746 % \file{plain.mf}'s \mfc{beginchar} (for \MF). In fact, it used to invoke
1747 % \mfc{beginchar}. For \MP, we invoke \mfc{beginfig} explicitly. This does
1748 % the \mfc{clear...} actions and \mfc{charcode} assignment.
1749 %
1750 % The `\mfc{extra_...mfpic}' strings provide a compiler-independent way
1751 % to add to the extra beginning and ending tokens.
1752 % \begin{macrocode}
1753 string extra_beginmfpic; extra_beginmfpic := "";
1754 string extra_endmfpic; extra_endmfpic := "";
1755
1756 def beginmfpic (expr ch) =
1757 %<MP> beginfig (ch);
1758 %<MF> begingroup
1759 gcode := ch;
1760 save w_, h_, d_;
1761 charwd := (xpos-xneg)*xscale*unitlen;
1762 charht := (ypos-yneg)*yscale*unitlen;
1763 chardp := 0;
1764 %<*MF>
1765 charcode := if known ch: byte ch else: 0 fi;
1766 w_ := hround (charwd*hppp);
1767 h_ := vround (charht*hppp);
1768 d_ := vround (chardp*hppp);
1769 charic := 0; clearxy; clearit; clearpen;
1770 scantokens extra_beginchar;
1771 %</MF>
1772 %<*MP>
1773 w_ := charwd;
1774 h_ := charht;
1775 d_ := chardp;
1776 %</MP>
1777 initpic;
1778 scantokens extra_beginmfpic;
1779 enddef;
1780
1781 % \end{macrocode}
1782 %
1783 % \DescribeRoutine{endmfpic}
1784 % For \MF, we again clone \file{plain.mf}'s \mfc{endchar}, adding support
1785 % for the \gbc{clipall} (clip to the graph rectangle), and \gbc{ClipOn}
1786 % (clip to some user specified array of paths), and \gbc{showbbox} (draw
1787 % the boundary of the graph for debugging purposes).
1788 % \begin{macrocode}
1789 def endmfpic =
1790 scantokens extra_endmfpic;
1791 if debug:
1792 GBdebug;
1793 %<MF> >> "TFM charwd = " & decimal charwd & "pt#";
1794 %<MF> >> "TFM charht = " & decimal charht & "pt#";
1795 %<MP> >> "width = " & decimal w_ & "bp";
1796 %<MP> >> "height = " & decimal h_ & "bp";
1797 GBenddebug;
1798 fi
1799 DoClip (active_plane);
1800 if clipall: clipto (active_plane) rect (origin, (w_, h_)); fi
1801 if showbbox: noclip ( safedraw rect (origin, (w_, h_)) ); fi
1802 %<*MF>
1803 scantokens extra_endchar;
1804 if proofing > 0: makebox (proofrule); fi
1805 chardx := w_; % desired width of character in pixels
1806 shipit;
1807 if displaying > 0: makebox (screenrule); showit; fi
1808 endgroup
1809 %</MF>
1810 % \end{macrocode}
1811 %
1812 % \MP's code is more involved due to the possibility to put typeset text
1813 % in a picture. In addition to the \gbc{clipall}, \gbc{ClipOn} and
1814 % \gbc{showbbox} support, we have support for labels and \gbc{truebbox}.
1815 % \begin{macrocode}
1816 %<*MP>
1817 save _ll, _ur;
1818 pair _ll, _ur;
1819 if truebbox:
1820 _ll := llcorner active_plane;
1821 _ur := urcorner active_plane;
1822 % \end{macrocode}
1823 % We try to let the bbox include labels, even when they extend beyond the
1824 % nominal picture boundaries. However, they will have been clipped off if
1825 % \gbc{clipall} is set. In that case, we just set the bounding box to the
1826 % coordinates determined by \gbc{w_} and \gbc{h_}, otherwise we expand
1827 % them to the \gbc{labelbb} values.
1828 % \begin{macrocode}
1829 elseif clipall:
1830 _ll := origin;
1831 _ur := (w_,h_);
1832 else: % expand to accomodate labels
1833 _ll := pairmin ((0, 0 ), labelbb.ll);
1834 _ur := pairmax ((w_, h_), labelbb.ur);
1835 fi
1836 % \end{macrocode}
1837 % A bounding box in the output PostScript code can have a side with
1838 % length 0 (e.g., a picture drawn with \mfpic{} that contains only
1839 % text placed by \TeX). This can cause division by 0 errors in some
1840 % cases. That's why we don't just let \MP{} determine the bounding box,
1841 % but force the upper and lower coordinates to differ.
1842 % \begin{macrocode}
1843 _ur := pairmax (_ur, _ll + eps*(1, 1));
1844 setbounds active_plane to rect (_ll, _ur);
1845 % \end{macrocode}
1846 % Finally, if \gbc{overlaylabels} or \gbc{underlaylabels} was true during
1847 % a \gbc{newgblabel} command, then the label was not added to
1848 % \mfc{currentpicture} but rather to \gbc{foreground_labels} or
1849 % \gbc{background_labels}. We add those pictures now, the former on top of
1850 % \mfc{currentpicture}, the latter underneath. This might extend the bbox
1851 % calculated above, but that is one of the effects we \emph{want} to
1852 % achieve. Picture variables can consume a lot of memory, so we clear
1853 % each one after we have added it. Unfortunately, we will temporarily
1854 % have two copies of the current picture in memory for background text, so
1855 % we perform this operation only if \gbc{havebackground} is true.
1856 % \begin{macrocode}
1857 if havebackground:
1858 addto background_labels also active_plane;
1859 active_plane := background_labels;
1860 background_labels := nullpicture;
1861 fi
1862 addto active_plane also foreground_labels;
1863 foreground_labels := nullpicture;
1864 endfig;
1865 %</MP>
1866 enddef;
1867
1868 % \end{macrocode}
1869 %
1870 %
1871 %
1872 % \section{Text}\label{text}
1873 %
1874 % In the \MP{} version, \gbc{label_adjust}, \gbc{label_sep} and
1875 % \gbc{labelpath_sep} are the equivalent of \mfpic's \cs{tlabeloffset},
1876 % \cs{tlpointsep} and \cs{tlpathsep}. In the \MF{} version they are still
1877 % needed (in \gbc{textrect}, etc.) to place the paths that are to surround
1878 % the text that \TeX{} places.
1879 %
1880 % \gbc{label_adjust} is a vector displacement applied to all labels,
1881 % while \gbc{label_sep} is the distance from the label to
1882 % the point of placement, when that point is on the edges of the label's
1883 % bounding box. Both are in device coordinates (e.g., \mfc{3bp}).
1884 % Finally, \gbc{labelpath_sep} is the separation of a surrounding path
1885 % from the text.
1886 % \begin{macrocode}
1887 pair label_adjust;
1888 label_adjust := origin;
1889 numeric label_sep, labelpath_sep ;
1890 label_sep := 0; labelpath_sep := 0;
1891 % \end{macrocode}
1892 %
1893 % Another aspect of trying to make \mfpic's \file{.mp} and \file{.mf}
1894 % the same, we here define a version of \mfc{verbatimtex} for \MF. This
1895 % works only if \mfc{etex} is followed by a semicolon, and no semicolons
1896 % appear in the \TeX{} material. (There may be other forbidden things, and
1897 % certainly any parentheses have to be in matching pairs. Not so obvious
1898 % is that \cs{begingroup} and \cs{endgroup} have to be balanced: \MF{}
1899 % sees \cs{begingroup} as `\verb$\$' plus \mfc{begingroup}.) We would
1900 % like the output of \mfpic{} under the \opt{metapost} option to be usable
1901 % in \MF{} with minimal changes.
1902 % \begin{macrocode}
1903 %<MF>def verbatimtex text t = enddef;
1904
1905 % \end{macrocode}
1906 %
1907 %
1908 % \subsection{Placement of text, \MP{} only}\label{placement}
1909 %
1910 % \DescribeRoutine{newgblabel}
1911 % This is how \mfpic{} places labels when \opt{mplabels} is in effect.
1912 % Since labels will typically be \mfc{btex...etex}, which are picture
1913 % expressions, it will actually place any picture, \gbc{s}. If you feed it
1914 % a string or path, it will convert it to a picture (with the \mfc{infont}
1915 % operator or the \gbc{picpath} macro).
1916 %
1917 % The macro \gbc{newgblabel} takes 6 parameters. The first three
1918 % parameters could easily be condensed into two if \mfpic{} support were
1919 % all that was required, however I thought it best to make it general.
1920 % The parameters \gbc{hf} and \gbc{vf} are numeric, with \gbc{hf}
1921 % representing the fraction of the text that lies left of the point where
1922 % the text is placed and \gbc{vf} represents the fraction of
1923 % text that lies below that point. However, if the third parameter is
1924 % \mfc{true}, then \gbc{vf} is relative to the baseline (i.e., the depth
1925 % is ignored). In \mfpic{} this is only used with \gbc{vf = 0} to get
1926 % placement on the baseline.
1927 %
1928 % These three parameters correspond to the optional parameter of
1929 % \cs{tlabel} in \mfpic{} as follows:
1930 % \begin{itemize}
1931 % \item \gbc{hf} determines horizontal position: $0=\mathtt{l}$,
1932 % $.5=\mathtt{c}$, and $1 = \mathtt{r}$.
1933 % \item \gbc{vf} and \gbc{BL} determine vertical position. For placement
1934 % option \texttt{B}, $\mathtt{vf} = 0$ and \gbc{BL} is \mfc{true}. For the
1935 % rest, \gbc{BL} is \mfc{false} and \gbc{vf} corresponds as follows:
1936 % $0 = \mathtt{b}$, $.5 = \mathtt{c}$ and $1 = \mathtt{t}$.
1937 % \end{itemize}
1938 % The remaining parameters have the following meanings:
1939 % \begin{itemize}
1940 % \item \gbc{r} is degrees of rotation about the specified point.
1941 % \item \gbc{s} is a string or picture expression (typically
1942 % \mfc{btex ... etex} code)
1943 % \item \gbc{pts} is a list of pairs in graph coordinates.
1944 % \end{itemize}
1945 % First the bounding box of the picture is determined using
1946 % \gbc{pathdims}. (Why \texttt{\textit{path}dims}? Because it was written
1947 % for the paths that surround text, and was then incorporated into text
1948 % placement when \gbc{newgblabel} replace \gbc{gblabel}.) Then
1949 % \gbc{readjustdims} extends that box by \gbc{label_sep}, a new
1950 % reference point for the picture is calculated using
1951 % \DescribeRoutine{ref_shift}
1952 % \gbc{ref_shift}, and then \gbc{thegblabel} rotates it around the
1953 % reference point and adds the \gbc{label_adjust}. Finally, for each
1954 % \gbc{_itm} in \gbc{pts}, the result is shifted by \gbc{_itm}. If
1955 % \gbc{overlaylabels} is true, the label is placed on the picture
1956 % \gbc{foreground_labels} and added to \gbc{active_plane} at
1957 % \gbc{endmfpic}. If \gbc{underlaylabels} is true, it is placed in picture
1958 % \gbc{background_labels} and \gbc{active_plane} is placed on top of it.
1959 % Otherwise, it is added directly to \gbc{active_plane} and the
1960 % \gbc{labelbb} variables are adjusted.
1961 %
1962 % We also use \gbc{ref_shift} in \MF{} since the curves that surround text
1963 % require it.
1964 %
1965 % \DescribeRoutine{gblabel}
1966 % We keep \gbc{gblabel} for backward compatibility with old \mfpic{}
1967 % files, but it merely calls \gbc{newgblabel}. While the old \gbc{gblabel}
1968 % had the same flexibility as \gbc{newgblabel}, this one assumes that the
1969 % parameters are only those that \mfpic{} would write.
1970 %
1971 % We provide a null definition of newgblabel for \MF{} to allow \mfpic's
1972 % \file{.mp} files to be somewhat usable with minimal changes. It
1973 % requires a text parameter, since \MF{} would be unable to evaluate
1974 % \mfc{btex} expressions.
1975 % \begin{macrocode}
1976 %<*MP>
1977 vardef newgblabel (expr hf, vf, BL, r) (expr s) (text pts) =
1978 save _lab, _ll, _ur; picture _lab; pair _ll, _ur;
1979 _lab := makepicture (s);
1980 pathdims (origin, _lab) (_ll, _ur);
1981 readjustdims (_ll, _ur) (label_sep);
1982 _lab := thegblabel (ref_shift (hf, vf, BL, _ll, _ur), r, _lab);
1983 save _b; pair _b;
1984 for _itm = pts:
1985 _b := zconv (_itm);
1986 if overlaylabels:
1987 addto foreground_labels also _lab shifted _b _wc_ tlabelcolor;
1988 elseif underlaylabels:
1989 addto background_labels also _lab shifted _b _wc_ tlabelcolor;
1990 havebackground := true;
1991 else:
1992 addto active_plane also _lab shifted _b _wc_ tlabelcolor;
1993 labelbb.ll := pairmin (_b + llcorner _lab, labelbb.ll);
1994 labelbb.ur := pairmax (_b + urcorner _lab, labelbb.ur);
1995 fi
1996 endfor
1997 %</MP>
1998 %<MF>vardef newgblabel (expr hf, vf, BL, r) (text s) (text pts) =
1999 enddef;
2000
2001 % Assumes a+b=1 and either c+d=1 or c=d=0:
2002 %<MP>vardef gblabel (expr a, b, c, d, r) (expr s) (text t) =
2003 %<MF>vardef gblabel (expr a, b, c, d, r) (text s) (text t) =
2004 newgblabel (b, d, (c = 0) and (d = 0), r) (s) (t);
2005 enddef;
2006
2007 vardef ref_shift (expr hf, vf, BL, ll, ur) =
2008 - ( (hf)[xpart ll, xpart ur],
2009 (vf)[if BL: 0 else: (ypart ll) fi, ypart ur] )
2010 enddef;
2011
2012 % \end{macrocode}
2013 %
2014 % \DescribeRoutine{thegblabel}
2015 % When \gbc{thegblabel} is called by the above, \gbc{p} is a text picture,
2016 % but it is also called by the \gbc{textrect}, etc., in which case \gbc{p}
2017 % is a path. This is why it is needed in the \MF{} version.
2018 % \begin{macrocode}
2019 vardef thegblabel (expr z, r, p) =
2020 ((p shifted z) rotated r) shifted label_adjust
2021 enddef;
2022
2023 % \end{macrocode}
2024 %
2025 %
2026 % \subsection{Decorating the text, \MF{} or \MP{}}\label{decorating}
2027 %
2028 % The three macros \gbc{textrect}, \gbc{textoval} and \gbc{textellipse}
2029 % are designed to surround a bit of text with some curve. These macros
2030 % return the path in graph coordinates. In
2031 % \DescribeRoutine{textrect}
2032 % \gbc{textrect}, the path is a rectangle with optionally rounded corners.
2033 % The second parameter, \gbc{rad}, is the radius of quarter circles at the
2034 % corners (in device units). In the other two cases, the path is an
2035 % ellipse. They differ in the meaning of the second parameter.
2036 %
2037 % \DescribeRoutine{textoval}
2038 % In \gbc{textoval}, the second parameter \emph{multiplies} the ratio of
2039 % width to height of the text to produce the ratio for the ellipse. Thus,
2040 % with \gbc{mult}=1, the ratio will be the same as that of the text. In
2041 % \DescribeRoutine{textellipse}
2042 % \gbc{textellipse}, the second parameter \gbc{rat} is the actual value of
2043 % the ratio of width to height of the ellipse and a value of 1 produces a
2044 % circle. In either macro, if that parameter is 0, we draw a rectangle.
2045 %
2046 % The size of each path is determined so that, when the text is placed and
2047 % the path drawn, it passes through the four corners of the following
2048 % rectangle: the rectangle which just encloses the text plus the amount of
2049 % space on all sides determined by \gbc{labelpath_sep}. Note that this means
2050 % a rectangle with rounded corners will have larger height and width than
2051 % one without. These versions always center the surrounding path on the
2052 % the point \gbc{loc}. The extended versions (below) have the same
2053 % flexibility of placement as the commands that place the label being
2054 % surrounded.
2055 %
2056 % The first parameter \gbc{lbl} is either a pair representing the
2057 % height and width of the text (only possibility in \MF) or the actual
2058 % text. These macros are being kept for backward compatibity, but now they
2059 % call the extended versions that allow the path to follow arbitrary
2060 % text placement. The parameters \gbc{(.5,.5,false,0)} were those
2061 % assumed in the past version: centered at the point, with no rotation.
2062 %
2063 % The extended versions of \gbc{textoval} and \gbc{textellipse} are both
2064 % now implemented in a single command \gbc{xellipse}, with a boolean to
2065 % specify whether the aspect ratio of the text is used to calculate the
2066 % aspect of the ellipse.
2067 % \begin{macrocode}
2068 vardef textrect (expr lbl, rad, loc) =
2069 textrectx (.5, .5, false, 0) (origin, lbl, rad, loc)
2070 enddef;
2071 vardef textoval (expr lbl, mult, loc) =
2072 xellipse (true, .5, .5, false, 0) (origin, lbl, mult, loc)
2073 enddef;
2074 vardef textellipse (expr lbl, rat, loc) =
2075 xellipse (false, .5, .5, false, 0) (origin, lbl, rat, loc)
2076 enddef;
2077
2078 % \end{macrocode}
2079 %
2080 % \DescribeRoutine{textrectx}
2081 % Macro \gbc{textrectx} is the extended version of \gbc{textrect} which
2082 % allows the same adjustments to the rectangle that we can apply to the
2083 % text it surrounds (via \gbc{newgblabel}). In fact, it calculates the
2084 % position in exactly the same manner as that macro, and the first 4
2085 % parameters encode that position in the same way.
2086 %
2087 % The placement of each path is: shifted and rotated by the same amount
2088 % as the text (by \gbc{ref_shift}) according to the first four parameters,
2089 % then shifted to the point given in the third parameter \gbc{loc}, and
2090 % finally shifted by the vector specified in \gbc{label_adjust}.
2091 %
2092 % \gbc{lbl} is either the upper right corner of the text or the label
2093 % itself. In the first case \gbc{xy} is the lower left corner, in the
2094 % second case it is a dummy parameter, the bounding box being obtained (in
2095 % \gbc{pathdims}) by measuring the label. For these extended macros, the
2096 % parameters \gbc{lbl}, \gbc{mult}, \gbc{rad}, and \gbc{loc} are as in
2097 % the unextended versions.
2098 %
2099 % \DescribeVariable{roundends}
2100 % The variable \gbc{roundends} is a boolean. We really only need it to be
2101 % a type distinguishable from any numeric value. \Mfpic{} users can
2102 % specify it rather than an explicit radius, and when the code of
2103 % \gbc{textrectx} detects this, it uses the maximum radius for the corners
2104 % (making the short side of the `rectangle' a semicircle). That is, if
2105 % \gbc{rad} is a boolean (and \mfc{true}) then the radius at the corners
2106 % is so chosen. If \gbc{rad} is \mfc{false} the corners are not rounded at
2107 % all.
2108 % \begin{macrocode}
2109 boolean roundends; roundends := true;
2110 vardef textrectx (expr a, b, c, rot, xy, lbl, rad, loc) =
2111 save ll, ur, _r, f, zz;
2112 pair ll, ur, zz; path f;
2113 pathdims (xy, lbl) (ll, ur);
2114 readjustdims (ll, ur) (labelpath_sep)
2115 _r := if numeric rad: rad
2116 elseif not boolean rad: 0
2117 elseif rad: emin (xpart(ur-ll), ypart (ur-ll))/sqrt(2)
2118 else: 0
2119 fi;
2120 if _r = 0:
2121 f := rect (ll, ur);
2122 else:
2123 save p, q;
2124 pair p[]; path q;
2125 p1 := ur - _r*dir(45);
2126 p3 := ll + _r*dir(45);
2127 p2 := (xpart p3, ypart p1);
2128 p4 := (xpart p1, ypart p3);
2129 % \end{macrocode}
2130 % We allow the rounding radius to be negative and make the corners
2131 % indented in that case. We no longer reverse the path in this case.
2132 % \begin{macrocode}
2133 q := if _r < 0: reverse fi quartercircle scaled 2_r;
2134 f :=
2135 (q shifted p1)--(q rotated 90 shifted p2)
2136 --(q rotated 180 shifted p3)
2137 --(q rotated -90 shifted p4)--cycle;
2138
2139 fi
2140 readjustdims (ll, ur) (label_sep - labelpath_sep);
2141 invvconv (thegblabel (ref_shift(a, b, c, ll, ur), rot, f))
2142 shifted loc
2143 enddef;
2144
2145 % \end{macrocode}
2146 %
2147 % \DescribeRoutine{textellipsex}
2148 % The macro \gbc{textellipsex} is a simlar extension for
2149 % \gbc{textellipse}. It and the related macro
2150 % \DescribeRoutine{textovalx}
2151 % \gbc{textovalx} now call a common macro with different values of a
2152 % boolean parameter.
2153 % \begin{macrocode}
2154 def textovalx = xellipse (true) enddef;
2155 def textellipsex = xellipse (false) enddef;
2156
2157 % \end{macrocode}
2158 %
2159 % \DescribeRoutine{xellipse}
2160 % In \gbc{xellipse}, \gbc{aa} and \gbc{bb} are the horizontal and
2161 % vertical radii of the resulting ellipse, while \gbc{ww} and \gbc{hh}
2162 % are half the width and height size of the text. If the boolean
2163 % \gbc{aspect} is true, the aspect ratio of the ellipse (i.e., \gbc{aa/bb})
2164 % equals \gbc{mult*ww/hh}, otherwise it equals \gbc{mult}.
2165 % \begin{macrocode}
2166 vardef xellipse (expr aspect, a, b, c, r, xy, lbl, mult, loc) =
2167 if mult = 0:
2168 textrectx (a, b, c, r) (xy, lbl, 0, loc)
2169 else:
2170 save ll, ur, cc, ww, hh, f;
2171 pair ll, ur, cc; path f;
2172 pathdims (xy, lbl) (ll, ur);
2173 readjustdims (ll, ur) (labelpath_sep)
2174 cc := .5[ll, ur];
2175 (ww, hh) = ur - cc;
2176 if (ww = 0) or (hh = 0):
2177 f = (ll--ur);
2178 else:
2179 save aa, bb;
2180 % \end{macrocode}
2181 %
2182 % The \gbc{aa} and \gbc{bb} are now calculated in a way that decreases the
2183 % chance of overflow. As a side effect, negative \gbc{mult} no longer
2184 % reverses the path.
2185 % \begin{macrocode}
2186 aa := ww ++ if aspect: ww else: hh fi *mult;
2187 bb := hh ++ if aspect: hh else: ww fi /mult;
2188 f := ellipse (cc, aa, bb, 0);
2189 fi
2190 readjustdims (ll, ur) (label_sep - labelpath_sep);
2191 invvconv (thegblabel (ref_shift(a, b, c, ll, ur), r, f))
2192 shifted loc
2193 fi
2194 enddef;
2195
2196 % \end{macrocode}
2197 %
2198 % \DescribeRoutine{pathdims}
2199 % This has been changed to make the code of \mfpic{} a bit simpler and
2200 % to aid in backward compatibility. It takes a couple of pairs (the actual
2201 % or nominal label bounding box corners) or something visible (picture,
2202 % string or path) and assigns suitable values to \gbc{ll} and \gbc{ur}.
2203 %
2204 % \DescribeRoutine{readjustdims}
2205 % This is used to add the separations needed to implement the effects of
2206 % \gbc{label_sep} and \gbc{labelpath_sep}.
2207 % \begin{macrocode}
2208 def pathdims (expr xy, lbl) (suffix ll, ur) =
2209 if pair lbl:
2210 ll := xy; ur := lbl;
2211 else:
2212 %<MF> ll := ur := origin;
2213 %<*MP>
2214 setpicture (_lbl) makepicture (lbl);
2215 ll := llcorner _lbl;
2216 ur := urcorner _lbl;
2217 %</MP>
2218 fi
2219 enddef;
2220
2221 def readjustdims (suffix ll, ur) (expr s) =
2222 ll := ll - s*(1,1);
2223 ur := ur + s*(1,1);
2224 enddef;
2225
2226 % \end{macrocode}
2227 %
2228 %
2229 %
2230 % \section{Additional Functions}\label{functions}
2231 %
2232 % Complex variable functions are provided, which interpret a pair $(x, y)$
2233 % as the complex number $z = x + iy$. We also provide for the use of
2234 % radians, add the standard exponential and logarithms, and add the
2235 % hyperbolic functions and their inverses.
2236 %
2237 % Normally \mfc{infinity = 2**12 - epsilon} is the largest number allowed
2238 % (as a value involved in actual drawing in \MF). Since we set
2239 % \mfc{warningcheck=0}, values not assigned to a variable and not
2240 % written to the \file{.tfm} file (and any value in \MP) can be as high as
2241 % \mfc{2**15 - epsilon}, which is a speck smaller than \mfc{1/(2epsilon)}.
2242 % So \gbc{reallysmall} is the smallest number whose reciprocal is a
2243 % usable number. (\mfc{epsilon} is the smallest possible positive number
2244 % in \MF.)
2245 %
2246 % The value \gbc{eps/2 + epsilon} is the smallest value with
2247 % reciprocal less than \mfc{infinity}. I set \gbc{nottoosmall} to
2248 % \gbc{eps/2 + 2epsilon} to ensure that the same is true of
2249 % \gbc{2*(nottoosmall/2)}. This is probably not necessary as
2250 % \mfc{epsilon/2} should round up to \mfc{epsilon} and not be lost. But
2251 % it also ensures that \gbc{nottoosmall} equals \gbc{2*(nottoosmall/2)},
2252 % which could be useful.
2253 %
2254 % We set \gbc{secd x = 1/(cosd x)} unless \gbc{cosd x} is less than
2255 % \gbc{reallysmall}, then we set it equal to \gbc{1/reallysmall}. We do a
2256 % similar thing with \gbc{cscd}. (When such a substitution happens
2257 % \DescribeRoutine{TruncateWarn}
2258 % \gbc{TruncateWarn} prints a message that a truncation has taken place.)
2259 %
2260 % Why not just determine what number will produce arithmetic overflow and
2261 % test for that? Because I'm lazy: it would require a different number
2262 % for each of the functions. Instead, since \MF{} has no `arithmetic
2263 % underflow', I compute something that is guaranteed to work and occurs
2264 % in the formula for the function as a reciprocal (e.g., $t = e^{-|x|}$
2265 % for \gbc{cosh x}) and make sure the number is not too small to take its
2266 % reciprocal.
2267 %
2268 % \DescribeRoutine{signof}
2269 % This expands to a minus sign if its argument is negative, otherwise
2270 % nothing.
2271 % \begin{macrocode}
2272 newinternal reallysmall; reallysmall := 3epsilon;
2273 newinternal nottoosmall; nottoosmall := eps/2 + 2epsilon;
2274 def signof (expr X) = if X < 0: - fi enddef;
2275 def TruncateWarn expr s =
2276 GBwarn s & " is too large or undefined, so it will be truncated.";
2277 enddef;
2278
2279 % \end{macrocode}
2280 %
2281 % In addition to \mfc{sind} and \mfc{cosd} which take angles in degrees,
2282 % we define the remaining trig functions \gbc{tand}, \gbc{cotd},
2283 % \gbc{secd}, and \gbc{cscd}.
2284 %
2285 % We define \RoutineIndex{secd}\gbc{secd}, one of the simplest, to include
2286 % an out of range test (which also prevents division by 0). Then
2287 % \RoutineIndex{tand}\gbc{tand} can make use of it without any division.
2288 % We do the same with \RoutineIndex{cscd}\gbc{cscd} and
2289 % \RoutineIndex{cotd}\gbc{cotd}.
2290 % \begin{macrocode}
2291 vardef secd primary X =
2292 setnumeric (temp) cosd(X);
2293 if abs(temp) < reallysmall:
2294 TruncateWarn "Secant or Tangent";
2295 temp := signof (temp) reallysmall;
2296 fi
2297 1/temp
2298 enddef;
2299 vardef tand primary X = sind(X)*secd(X) enddef;
2300
2301 vardef cscd primary X =
2302 setnumeric (temp) sind(X);
2303 if abs(temp) < reallysmall:
2304 TruncateWarn "Cosecant or Cotangent";
2305 temp := signof(temp) reallysmall;
2306 fi
2307 1/temp
2308 enddef;
2309 vardef cotd primary X = cosd(X)*cscd(X) enddef;
2310
2311 % \end{macrocode}
2312 %
2313 % These are the inverse functions, which return an angle in degrees:
2314 % \RoutineIndex{acos}\gbc{acos}, \RoutineIndex{asin}\gbc{asin} and
2315 % \RoutineIndex{atan}\gbc{atan}.
2316 % \begin{macrocode}
2317 vardef acos primary X =
2318 if abs X > 1:
2319 TruncateWarn "Argument of arccosine";
2320 angle (signof(X) 1, 0)
2321 else:
2322 angle (X, 1 +-+ X)
2323 fi
2324 enddef;
2325 vardef asin primary X =
2326 if abs X > 1:
2327 TruncateWarn "Argument of arcsine";
2328 angle (0, signof(X) 1)
2329 else:
2330 angle (1 +-+ X, X)
2331 fi
2332 enddef;
2333 vardef atan primary X = angle (1, X) enddef;
2334
2335 % \end{macrocode}
2336 %
2337 % Now the trig functions that take angles in radians:
2338 % \RoutineIndex{sin}\gbc{sin}, \RoutineIndex{cos}\gbc{cos},
2339 % \RoutineIndex{tan}\gbc{tan}, \RoutineIndex{cot}\gbc{cot},
2340 % \RoutineIndex{sec}\gbc{sec} and \RoutineIndex{csc}\gbc{csc}.
2341 % \begin{macrocode}
2342 vardef sin primary X = sind (X*radian) enddef;
2343 vardef cos primary X = cosd (X*radian) enddef;
2344 vardef tan primary X = tand (X*radian) enddef;
2345 vardef cot primary X = cotd (X*radian) enddef;
2346 vardef sec primary X = secd (X*radian) enddef;
2347 vardef csc primary X = cscd (X*radian) enddef;
2348
2349 % \end{macrocode}
2350 %
2351 % \DescribeRoutine{degrees}
2352 % It is useful to have a command to convert from radians to degrees and
2353 % one to
2354 % \DescribeRoutine{radians}
2355 % convert from degrees to radians. For example, \gbc{degrees(pi)} produces
2356 % (approximately) $180$ and \gbc{radians(180)} is approximately $\pi$.
2357 % \begin{macrocode}
2358 vardef degrees (expr t) = t*radian enddef;
2359 vardef radians (expr t) = t/radian enddef;
2360
2361 % \end{macrocode}
2362 %
2363 % And the inverses (\RoutineIndex{invsin}\gbc{invsin},
2364 % \RoutineIndex{invcos}\gbc{invcos} and \RoutineIndex{invtan}\gbc{invtan})
2365 % that return angles in radians.
2366 % \begin{macrocode}
2367 vardef invcos primary X = radians (acos X) enddef;
2368 vardef invsin primary X = radians (asin X) enddef;
2369 vardef invtan primary X = radians (atan X) enddef;
2370
2371 % \end{macrocode}
2372 %
2373 % Here we define the standard exponential function
2374 % \RoutineIndex{exp}\gbc{exp}. (The \MF{} function \mfc{mexp} has the
2375 % unusual base $e^{1/256}$ to avoid overflow.) The inverse of \gbc{exp} is
2376 % the natural logarithm (\RoutineIndex{ln}\gbc{ln} or
2377 % \RoutineIndex{log}\gbc{log}). We also have the general base logarithm
2378 % \RoutineIndex{logbase}\gbc{logbase} and its two special instances
2379 % \RoutineIndex{logtwo} \gbc{logtwo} and \RoutineIndex{logten}\gbc{logten}.
2380 % \begin{macrocode}
2381 vardef exp primary X = mexp (256 * X) enddef;
2382 vardef ln primary X = (mlog X) / 256 enddef;
2383 vardef log primary X = ln (X) enddef;
2384 vardef logbase (expr B) primary X = (mlog X)/(mlog B) enddef;
2385 vardef logtwo primary X = logbase( 2) (X) enddef;
2386 vardef logten primary X = logbase(10) (X) enddef;
2387
2388 % \end{macrocode}
2389 %
2390 % The hyperbolic functions: \RoutineIndex{cosh}\gbc{cosh}
2391 % \RoutineIndex{sinh}\gbc{sinh}, \RoutineIndex{tanh}\gbc{tanh},
2392 % \RoutineIndex{sech}\gbc{sech}, \RoutineIndex{csch}\gbc{csch} and
2393 % \RoutineIndex{coth}\gbc{coth}.
2394 % \begin{macrocode}
2395 vardef cosh primary X =
2396 setnumeric (temp) 2 exp (-abs(X));
2397 if temp < reallysmall:
2398 TruncateWarn "Cosh";
2399 temp := reallysmall;
2400 fi
2401 1/temp + temp/4
2402 enddef;
2403
2404 vardef sinh primary X =
2405 setnumeric (temp) 2 exp (-abs(X));
2406 if temp < reallysmall:
2407 TruncateWarn "Sinh";
2408 temp := reallysmall;
2409 fi
2410 signof (X) (1/temp - temp/4)
2411 enddef;
2412
2413 vardef sech primary X =
2414 setnumeric (temp) exp(-(abs (X)));
2415 2temp/(1 + temp*temp)
2416 enddef;
2417
2418 vardef tanh primary X =
2419 setnumeric (temp) exp(-2(abs (X)));
2420 signof (X) (1 - temp)/(1 + temp)
2421 enddef;
2422
2423 vardef csch primary X =
2424 save temp, tempa; temp := exp(-(abs (X)));
2425 tempa := (1 - temp*temp)/2;
2426 if tempa < reallysmall:
2427 TruncateWarn "Csch";
2428 tempa := reallysmall;
2429 fi
2430 signof (X) temp / tempa
2431 enddef;
2432
2433 vardef coth primary X =
2434 setnumeric (temp) tanh(X);
2435 if abs(temp) < reallysmall:
2436 TruncateWarn "Coth";
2437 temp := signof (X) reallysmall;
2438 fi
2439 1/temp
2440 enddef;
2441
2442 % \end{macrocode}
2443 %
2444 % The inverses of some of the hyperbolic functions:
2445 % \RoutineIndex{acosh}\gbc{acosh}, \RoutineIndex{asinh}\gbc{asinh} and
2446 % \RoutineIndex{atanh}\gbc{atanh}.
2447 % \begin{macrocode}
2448 vardef acosh primary y =
2449 if y < 1:
2450 TruncateWarn "acosh";
2451 0
2452 else:
2453 ln (y + (y +-+ 1))
2454 fi
2455 enddef;
2456
2457 vardef asinh primary y = ln (y + (y ++ 1)) enddef;
2458
2459 vardef atanh primary y =
2460 if abs (y) < 1:
2461 (ln (1 + y) - ln (1 - y))/2
2462 else:
2463 TruncateWarn "atanh";
2464 signof (y) infinity
2465 fi
2466 enddef;
2467
2468 % \end{macrocode}
2469 %
2470 % \CMF's pair variables are a decent replacement for complex variables.
2471 % These give some of the more basic functions of standard complex
2472 % analysis: \RoutineIndex{Arg}\gbc{Arg}, \RoutineIndex{Log}\gbc{Log},
2473 % \RoutineIndex{cis}\gbc{cis}, \RoutineIndex{zexp}\gbc{zexp},
2474 % \RoutineIndex{sgn}\gbc{sgn}, \RoutineIndex{zsqrt}\gbc{zsqrt} and
2475 % \RoutineIndex{conj}\gbc{conj}.
2476 % \begin{macrocode}
2477 vardef Arg primary Z = (angle Z)/radian enddef;
2478 vardef Log primary Z = (ln (abs Z), Arg Z) enddef;
2479 vardef cis primary T = dir (T*radian) enddef;
2480 vardef zexp primary Z = (exp (xpart Z)) * cis (ypart Z) enddef;
2481 vardef sgn primary Z = if not (Z = origin): unitvector fi Z
2482 enddef;
2483 vardef zsqrt primary Z =
2484 if Z = origin: origin else: sqrt(abs(Z)) * dir ((angle Z)/2) fi
2485 enddef;
2486 vardef conj primary Z = (xpart Z, -ypart Z) enddef;
2487
2488 % \end{macrocode}
2489 %
2490 % DescribeRoutine{zmul}
2491 % Unfortunately, while \MF{} will happily add and subtract pairs, it
2492 % will not multiply or divide them without help. We provide alternatives
2493 % \DescribeRoutine{zdiv} here.
2494 % \begin{macrocode}
2495 primarydef Z zmul W = Z zscaled W enddef;
2496 primarydef Z zdiv W =
2497 Z zmul ( unitvector (conj W) / (abs W) )
2498 enddef;
2499
2500 % \end{macrocode}
2501 %
2502 % \DescribeRoutine{Moebius}
2503 % A less basic operation: the Moebius shift which takes the disk $|z| <
2504 % 1$ onto itself. It is a hyperbolic geometry analog of shifting points
2505 % in Euclidean geometry. Its mathematical definition (all variables are
2506 % complex numbers):
2507 % \[
2508 % M_a(z) = \frac{z + a}{1 + \bar az}
2509 % \]
2510 % Its inverse is $M_{-a}$.
2511 %
2512 % \DescribeRoutine{pshdist}
2513 % Related to \gbc{Moebius} is the pseudohyperbolic metric. The distance
2514 % between $z$ and $w$ in this metric is $|z-w|/|1 - \bar wz|$. There is
2515 % \DescribeRoutine{pshdist_hp}
2516 % also a version of this for the upper half-plane: $|z-w|/|z-\bar w|$.
2517 %
2518 % Closely related to all this is Kelvin transform. In complex notation
2519 % it is simply $1/\bar z = z/|z|^2$. The term ``Kelvin transform'' is
2520 % normally only used in real variables (of any dimension greater than 1).
2521 % \begin{macrocode}
2522 vardef Moebius (expr A) primary Z =
2523 save _D; pair _D;
2524 _D := (1, 0) + (Z zscaled (conj A));
2525 (Z + A)/(abs _D) rotated (- angle _D)
2526 enddef;
2527 vardef pshdist (expr Z,W) = abs(Moebius(-W)(Z)) enddef;
2528 vardef pshdist_hp (expr Z,W) = abs(Z-W)/abs(Z-conj(W)) enddef;
2529 vardef kelvin (expr Z) =
2530 save tmp_; tmp_ = abs(Z);
2531 if tmp_ = 0:
2532 (infinity, infinity)
2533 elseif tmp_ < reallysmall:
2534 infinity*unitvector Z
2535 else:
2536 (1/tmp_)*unitvector Z
2537 fi
2538 enddef;
2539
2540 % \end{macrocode}
2541 %
2542 % \DescribeRoutine{polar}
2543 % \gbc{polar} converts a polar coordinate pair $(r, \theta)$ to the
2544 % corresponding rectangular coordinate pair.
2545 % \DescribeRoutine{id}
2546 % \gbc{id} returns its argument, which can be any expression of any type.
2547 % \begin{macrocode}
2548 vardef polar primary p = (xpart p) * dir (ypart p) enddef;
2549 def id (expr x) = x enddef;
2550
2551 % \end{macrocode}
2552 %
2553 % The definition of powers (\gbc{x**y}) in \prog{plain} \MF{} and \MP{}
2554 % could be more accurate. In particular \gbc{x=2**10} ought to be an
2555 % integer (that is, satisfy \mfc{x=floor x}). Here we redefine
2556 % \prog{plain}'s \mfc{**}, intercepting the case of a positive integer
2557 % power of an integer.
2558 %
2559 % There are some negative powers, and some integer powers of nonintegers
2560 % that can also be calculated exactly within \MF{}'s limited precision,
2561 % but it is difficult to determine those cases programmatically. Computing
2562 % every integer power by repeated multiplication or division might
2563 % actually reduce accuracy in the nonexact cases, so we limit ourselves to
2564 % this one special case.
2565 % \begin{macrocode}
2566 primarydef x**y =
2567 if y=2: x*x
2568 elseif (x = floor x) and (abs y = floor y):
2569 1 for n=1 upto y: *x endfor
2570 else: takepower y of x
2571 fi
2572 enddef;
2573 let ^ = **;
2574
2575 % \end{macrocode}
2576 %
2577 %
2578 % \section{Coordinate Systems and Transformations}\label{systems}
2579 %
2580 % \DescribeVariable{T_stack}
2581 % We want to define a localization of the current transform. To do
2582 % this we define a LIFO stack of transforms \gbc{T_stack[\,]}, and a pair of
2583 % macros.
2584 % \DescribeRoutine{T_push}
2585 % \gbc{T_push} puts its argument (a transform) on the stack, and
2586 % \DescribeRoutine{T_pop}
2587 % \gbc{T_pop} pops it off into its argument (a transform variable name).
2588 % We also define two localizing macros
2589 % \DescribeRoutine{bcoords}
2590 % \gbc{bcoords} that pushes our \gbc{ztr}
2591 % on the stack, and
2592 % \DescribeRoutine{ecoords}
2593 % \gbc{ecoords} that pops it off. We no longer put \gbc{vtr} on the stack,
2594 % since we can recalculate it whenever \gbc{ztr} is changed. \gbc{apply_t}
2595 % always did this, now \gbc{ecoords} does so as well.
2596 % \begin{macrocode}
2597 transform T_stack[];
2598 numeric T_stack; T_stack := 0;
2599
2600 def T_push (expr T) = T_stack[incr T_stack] := T; enddef;
2601 def T_pop (suffix $) =
2602 if T_stack > 0:
2603 $ := T_stack[T_stack];
2604 T_stack := T_stack - 1;
2605 fi
2606 enddef;
2607
2608 def bcoords = hide ( T_push (ztr) ) enddef;
2609 def ecoords = hide ( T_pop (ztr); vtr := vectorpart ztr ) enddef;
2610
2611 % \end{macrocode}
2612 %
2613 %
2614 % \subsection{Coordinate changes}\label{changes}
2615 %
2616 % \DescribeRoutine{apply_t}
2617 % Here we define a mechanism for changing \gbc{ztr} and \gbc{vtr} by
2618 % composing them with a new transform. Since a transform can be any affine
2619 % transform, we get \gbc{ztr} by composing with the transform, but we
2620 % calculate \gbc{vtr} from \gbc{ztr} by arranging that \mfc{origin
2621 % transformed vtr} is \mfc{origin}. The syntax is \gbc{apply_t(rotated
2622 % theta)} or \gbc{apply_t(transformed T)} if \mfc{T} is a variable or
2623 % expression of type transform. Thus the argument of \gbc{apply_t} is a
2624 % phrase which, were it to follow a path, would produce a transformed
2625 % path. Knuth calls such a phrase a \emph{transformer}.
2626 % \begin{macrocode}
2627 vardef vectorpart primary T = T shifted -(origin transformed T)
2628 enddef;
2629
2630 def apply_t (text Transformer) =
2631 ztr := identity Transformer transformed ztr;
2632 vtr := vectorpart ztr;
2633 enddef;
2634
2635 % \end{macrocode}
2636 %
2637 % And now we define some available transformers.
2638 % \RoutineIndex{xslant}\gbc{xslant}, \RoutineIndex{yslant}\gbc{yslant},
2639 % \RoutineIndex{zslant}\gbc{zslant}, \RoutineIndex{xyswap}\gbc{xyswap} and
2640 % \RoutineIndex{boost}\gbc{boost}. The only two that need comment are
2641 % \gbc{zslant} and \gbc{boost}. I know that boost comes from special
2642 % relativity, but I have no idea why zslant is a `slant'.
2643 % \begin{macrocode}
2644 def xslant = slanted enddef; % (x+sy, y).
2645 def yslant primary s = % (x, y+sx).
2646 transformed
2647 begingroup
2648 save T; transform T;
2649 origin transformed T = origin;
2650 (1, 0) transformed T = (1, s);
2651 (0, 1) transformed T = (0, 1);
2652 T
2653 endgroup
2654 enddef;
2655
2656 def zslant primary p = % (xu+yv, xv+yu), where p = (u, v).
2657 transformed
2658 begingroup
2659 save T; transform T;
2660 xpart T = ypart T = 0;
2661 xxpart T = yypart T = xpart p;
2662 xypart T = yxpart T = ypart p;
2663 T
2664 endgroup
2665 enddef;
2666
2667 def xyswap = zslant (0, 1) enddef;
2668 def boost primary X = zslant (cosh X, sinh X) enddef;
2669
2670 % \end{macrocode}
2671 %
2672 %
2673 % \subsection{Path transformation}\label{transformation}
2674 %
2675 % These are functions that accept and return a path in graph coordinates.
2676 % For the most part they are named and defined to apply a similarly named
2677 % transform to the path and return the result. There are two exceptions.
2678 % When we draw things, we expect that rotated and reflected objects appear
2679 % congruent to the originals. If we define a path in graph coordinates,
2680 % and the $x$ and $y$ directions are scaled differently, then simply
2681 % rotating the graph coordinates will distort angles. The same is true of
2682 % reflection. Therefore, we apply \gbc{vtr} (so we are in drawing
2683 % coordinates) then rotate or reflect, then apply \gbc{inverse vtr}. This
2684 % may be a mistake, or perhaps we should do it for all of these. For now,
2685 % I'm sticking with the scheme I inherited. One can always use
2686 % \gbc{coords} and \gbc{apply_t} if one wants the difference in scales
2687 % ignored.
2688 %
2689 % \DescribeRoutine{transformedpath}
2690 % This is a vardef that reads an undelimited path expression and returns
2691 % the path transformed by the text argument. All the others run this,
2692 % allowing it to grab the path expression.
2693 %
2694 % \DescribeRoutine{rotatedpath}
2695 % This returns the path rotated around point \gbc{p} by angle
2696 % \gbc{th} in degrees.
2697 %
2698 % \DescribeRoutine{reflectedpath}
2699 % This reflects the path through the line containing points \gbc{p} and
2700 % \gbc{q}.
2701 %
2702 % \DescribeRoutine{scaledpath}
2703 % This returns the path scaled so that distances from the point
2704 % \gbc{p} are multiplied by \gbc{s}.
2705 % \DescribeRoutine{xscaledpath}
2706 % \gbc{xscaledpath} is similar, but only the horizontal distances from
2707 % the line $x={}$\gbc{a} are multiplied by \gbc{s}. And with
2708 % \DescribeRoutine{yscaledpath}
2709 % \gbc{yscaledpath} the vertical distances from the line $y={}$\gbc{b} are
2710 % multiplied by \gbc{s}.
2711 %
2712 % \DescribeRoutine{xslantedpath}
2713 % The macro \gbc{xslantedpath} returns the path xslanted with line
2714 % $y = {}$\gbc{b} being the pivot rather than the $x$-axis.
2715 % \DescribeRoutine{slantedpath}
2716 % The command \gbc{slantedpath} is just an alias for \gbc{xslantedpath},
2717 % while
2718 % \DescribeRoutine{yslantedpath}
2719 % \gbc{yslantedpath} is the vertical version, yslanted with line $x =
2720 % {}$\gbc{a} being the pivot rather than the $y$-axis.
2721 %
2722 % \DescribeRoutine{shiftedpath}
2723 % This returns the path shifted by the vector (pair) \gbc{v}.
2724 %
2725 % \DescribeRoutine{xyswappedpath}
2726 % The command \gbc{xyswappedpath} returns the path in which all points
2727 % have had the coordinates exchanged $(a, b) \to (b, a)$. Note that this
2728 % is not the same as \gbc{reflectedpath ((0,0), (1,1))}, as it performs
2729 % the reflection in graph coordinates, as its name implies. If \gbc{vtr}
2730 % has not been changed (by \gbc{apply_t}) then \gbc{xyswappedpath} will
2731 % convert vertical lines to horizontal and vice versa. The
2732 % \gbc{reflectedpath} version will not when $x$ and $y$ are scaled
2733 % differently, for then the line \gbc{(0,0)--(1,1)} is not at a 45 degree
2734 % angle in device coordinates where drawing takes place.
2735 %
2736 % \begin{macrocode}
2737 vardef transformedpath (text Transformer) expr f = f Transformer
2738 enddef;
2739
2740 def rotatedpath (expr p, th) =
2741 transformedpath (
2742 transformed vtr
2743 rotatedaround (p transformed vtr, th)
2744 transformed (inverse vtr)
2745 )
2746 enddef;
2747 def reflectedpath (expr p, q) =
2748 transformedpath (
2749 transformed vtr
2750 reflectedabout (p transformed vtr, q transformed vtr)
2751 transformed (inverse vtr)
2752 )
2753 enddef;
2754
2755 def scaledpath (expr p, s) =
2756 transformedpath (shifted -p scaled s shifted p)
2757 enddef;
2758 def xscaledpath (expr a, s) =
2759 transformedpath (shifted (-a, 0) xscaled s shifted (a, 0))
2760 enddef;
2761 def yscaledpath (expr b, s) =
2762 transformedpath (shifted (0, -b) yscaled s shifted (0, b))
2763 enddef;
2764
2765 def slantedpath = xslantedpath enddef;
2766 def xslantedpath (expr b, s) =
2767 transformedpath (shifted (0, -b) slanted s shifted (0, b))
2768 enddef;
2769 def yslantedpath (expr a, s) =
2770 transformedpath (shifted (-a, 0) yslant s shifted (0, a))
2771 enddef;
2772
2773 def shiftedpath (expr v) = transformedpath (shifted v) enddef;
2774
2775 def xyswappedpath = transformedpath (xyswap) enddef;
2776
2777 % \end{macrocode}
2778 %
2779 % It seems odd, in retrospect, that we got by with a user interface that
2780 % didn't include any subpath operations. But recently a user asked for the
2781 % ability to add an arrowhead to the \emph{middle} of a path, and it
2782 % seemed best to provide a subpath and use existing commands to add an
2783 % arrowhead on its end.
2784 %
2785 % \DescribeRoutine{partialpath}
2786 % The \gbc{partialpath} macro takes two fractions $\alpha$ and $\beta$
2787 % between 0 and 1, and a path \gbc{f}, and returns the subpath from
2788 % $\alpha * {} $\meta{length of \gbc{f}} to $\beta * {}$\meta{length of
2789 % \gbc{f}} of \gbc{f}. Since the \gbc{gettime} routine was written to
2790 % find the times for an increasing sequence of lengths, it was optimized
2791 % to save the index of the previous length and begin from there. Thus it
2792 % is more efficient to find the smaller of \gbc{a} and \gbc{b} first.
2793 %
2794 % Since running \gbc{gettime} would be a very inefficient way to get the
2795 % first or last point of a path we skip that if either fraction is $0$ or
2796 % $1$ (a common use is to get the first or last half of a path). We also
2797 % skip finding the second time if \gbc{a = b} (an unlikely choice, but
2798 % legal).
2799 %
2800 % \DescribeRoutine{gsubpath}
2801 % \gbc{gsubpath} is the same as \MF's subpath primitive, but follows the
2802 % prefix macro syntax of accepting a path expression (rather than a
2803 % primary) and wrapping the result in a \mfc{vardef}.
2804 % \begin{macrocode}
2805 vardef partialpath (expr a, b) expr f =
2806 save flag, flo, fhi, lo, hi, n;
2807 boolean flag; flag = true;
2808 convertpath (g) f;
2809 n := length f;
2810
2811 flo := snapto emin(a,b);
2812 if flo = 0:
2813 lo := 0;
2814 elseif flo < 1:
2815 setuplengtharray (cum, tot, idx) g;
2816 flag := false;
2817 lo := gettime (cum, idx) (flo*tot);
2818 else:
2819 lo := n;
2820 fi
2821
2822 fhi := snapto emax (a,b);
2823 if flo = fhi:
2824 hi := lo;
2825 elseif fhi < 1:
2826 if flag: setuplengtharray (cum, tot, idx) g; fi
2827 hi := gettime (cum, idx) (fhi*tot);
2828 else:
2829 hi := n;
2830 fi
2831
2832 if a > b: reverse fi subpath (lo, hi) of f
2833 enddef;
2834
2835 vardef gsubpath (expr a, b) expr f = subpath (a, b) of f enddef;
2836
2837 % \end{macrocode}
2838 %
2839 % \DescribeRoutine{setuplengtharray}
2840 % This does the frequently repeated saving, rescaling and initializing
2841 % for those commands that need to convert distance along a path to the
2842 % corresponding time or point. A path variable should follow, but that
2843 % is picked up by the \gbc{makelengtharry} at the end.
2844 % \begin{macrocode}
2845 def setuplengtharray (suffix cum, tot, idx) =
2846 save cum, tot, idx; idx := 0; tot := makelengtharray (cum)
2847 enddef;
2848
2849 % \end{macrocode}
2850 %
2851 % \DescribeRoutine{pathtime}
2852 % \gbc{pathtime} returns the time \mfc{t} such that \mfc{point t of p} is
2853 % \gbc{frac} of the distance along \gbc{p} from the start, and
2854 % \DescribeRoutine{pathpoint}
2855 % \gbc{pathpoint} returns the point itself. Because the \gbc{gettime}
2856 % routine requires it anyway, we truncate \gbc{frac} to the interval
2857 % $[0,1]$ and avoid calling that rather lengthy function at $0$ and $1$.
2858 %
2859 % The path in pathtime should be in device coordinates, whereas the
2860 % user-level command \gbc{pathpoint} expects it in graph coordinates.
2861 % In fact, since \gbc{pathpoint} would most likely be used in the
2862 % argument of some figure macro in \mfpic{}, it would require a
2863 % previously stored path, so we make the path a suffix parameter.
2864 % \begin{macrocode}
2865 vardef pathtime@# (suffix p) =
2866 if @# <= 0: 0
2867 elseif @# >= 1: length p
2868 else:
2869 setuplengtharray (cum, tot, idx) p;
2870 gettime (cum, idx) (@#*tot)
2871 fi
2872 enddef;
2873
2874 vardef pathpoint (expr frac) (suffix p) =
2875 convertpath (_pp) p; pnt[pathtime[frac] (_pp)] (p)
2876 enddef;
2877
2878 % \end{macrocode}
2879 %
2880 %
2881 %
2882 % \section{Picture-level Operations}\label{picture}
2883 %
2884 %
2885 % \subsection{Bitwise logical operations}\label{logical}
2886 %
2887 % None of these operations are available in \MP. Mostly these are used by
2888 % higher level operations. Those higher level operations are available in
2889 % \MP, but need to be defined differently.
2890 %
2891 % We have two types of operations. One type is a binary operator that
2892 % takes two picture expressions and returns a picture, the other type
2893 % returns nothing, but merely modifies a given picture variable. These
2894 % take the name of a picture and a picture expression and modify the named
2895 % one. The binary operators are not used elsewhere in graphbase except
2896 % for \gbc{picsub}, which occurs only in \gbc{shadepic}. They are all
2897 % rather wasteful of memory.
2898 %
2899 % \DescribeRoutine{mono}
2900 % Here we define the bitwise logical operations: and, or, xor, and
2901 % difference. These mostly only work if all pixels have values 0 or 1.
2902 % Since \MF{} allows other integer values, we define a \gbc{mono} operator
2903 % that converts all pixels with weight ${}\ge 1$ to 1 and all pixels
2904 % with weight ${}\le 0$ to 0. It is important to note that we can apply
2905 % \gbc{mono} only to the suffix parameter in such things as \gbc{orto}.
2906 % The expression parameter needs to be prepared by the routine that calls
2907 % these. The return result is culled, so it consists only of 0s and 1s.
2908 % \begin{macrocode}
2909 %<*MF>
2910 def mono (suffix u) = cull u keeping (1, infinity); enddef;
2911
2912 % \end{macrocode}
2913 %
2914 % \DescribeRoutine{andto, picand}
2915 % The bitwise and: in the resulting picture, a pixel is \emph{on} if and
2916 % only if it is \emph{on} in both \gbc{u} and \gbc{v}. \gbc{andto} is
2917 % only used in \gbc{interior} and \gbc{interiors}, \gbc{picand} is not
2918 % used at all.
2919 % \begin{macrocode}
2920 def andto (suffix u) (expr v) =
2921 mono (u); addto u also v; cull u keeping (2, 2);
2922 enddef;
2923 primarydef u picand v =
2924 begingroup setpicture (t) u; andto (t, v); t endgroup
2925 enddef;
2926
2927 % \end{macrocode}
2928 %
2929 % \DescribeRoutine{orto, picor}
2930 % The inclusive or: in the result, a pixel is \emph{on} if and only if it
2931 % is \emph{on} in \gbc{u} or \gbc{v} or both. I've written these so that
2932 % it doesn't matter if the expression parameter is not mono. It
2933 % \emph{is} required that it have only positive pixels. The command
2934 % \gbc{orto} is only used three places: in \gbc{coloraddto}, which
2935 % is itself never used, and in \gbc{patcharcs} and \gbc{patchrays}. This
2936 % lack of use is because a less memory intensive version, \gbc{_orto}, is
2937 % defined later, and that is what we use. Usually we build a picture
2938 % in a variable \gbc{src} and add that onto another variable \gbc{dest}.
2939 % If one used \gbc{orto (dest, src)}, then \MF{} would evaluate \gbc{src}
2940 % and pass a \emph{copy} of it as the parameter of \gbc{orto}. This
2941 % doubles the memory used, so mostly we use \gbc{_orto}, which passes both
2942 % parameters as suffixes. \gbc{picor} is never used.
2943 % \begin{macrocode}
2944 def orto (suffix u) (expr v) =
2945 mono (u); addto u also v; cull u keeping (1, infinity);
2946 enddef;
2947 primarydef u picor v =
2948 begingroup setpicture (t) u; orto (t, v); t endgroup
2949 enddef;
2950
2951 % \end{macrocode}
2952 %
2953 % \DescribeRoutine{xorto, picxor}
2954 % The exclusive or, also called the symmetric difference:
2955 % in the result, a pixel is \emph{on} if and only if it is \emph{on} in
2956 % \gbc{u} or \gbc{v}, but not both. These are not used elsewhere in
2957 % \grafbase.
2958 % \begin{macrocode}
2959 def xorto (suffix u) (expr v) =
2960 mono (u); addto u also v; cull u keeping (1, 1);
2961 enddef;
2962 primarydef u picxor v =
2963 begingroup setpicture (t) u; xorto (t, v); t endgroup
2964 enddef;
2965
2966 % \end{macrocode}
2967 %
2968 % \DescribeRoutine{subto}
2969 % The nonsymmetric difference: in the result, a pixel is \emph{on} if
2970 % and only if it is \emph{on} in \gbc{u} and off in \gbc{v}. It is
2971 % unclear whether a \gbc{v} with negative weights will ever occur, but
2972 % if so, subtracting negative pixels ought to be like adding positive
2973 % ones, so I've changed \mfc{keeping (1,1)} to \gbc{keeping (1,infinity)}.
2974 % With this understanding, it doesn't matter here whether \gbc{v} is
2975 % not mono. As with \gbc{orto}, we have a more memory efficient
2976 % \gbc{_subto} and now use that everywhere. \gbc{subto} is only used in
2977 % \gbc{coloraddto}, which is not used anymore. The binop version
2978 % \DescribeRoutine{picsub}\gbc{picsub}
2979 % is used only in \gbc{shadepic}.
2980 % \begin{macrocode}
2981 def subto (suffix u) (expr v) =
2982 mono (u); addto u also -v; cull u keeping (1, infinity);
2983 enddef;
2984 primarydef u picsub v =
2985 begingroup setpicture (t) u; mono (t); subto (t, v); t endgroup
2986 enddef;
2987
2988 %</MF>
2989 % \end{macrocode}
2990 %
2991 %
2992 % \subsection{Producing and modifying pictures}\label{pictures}
2993 %
2994 % Here we define some slightly higher level commands that make use (in \MF)
2995 % of the previous bitmap operations. In \MP, they mostly need different
2996 % definitions, but we have merged most of them by providing a \MP{}
2997 % alternative for the most frequently used bitmap operation in the
2998 % previous section, \gbc{orto}. These operations either return a picture
2999 % or modify a picture variable. They do not draw anything unless
3000 % \gbc{active_plane} is the modified picture. All curves, points,
3001 % dimension, etc., are in device coordinates.
3002 %
3003 % \DescribeRoutine{coloraddto}
3004 % This was once a useful abbreviation. In \MF{} it adds when the color
3005 % is not white, subtracts when it is. Grays are handles in \MF{} by
3006 % appropriate preparation of \gbc{u} and \gbc{v}. See, for example, the
3007 % code of \gbc{colorsafefill}. In \MP{} it is an abbreviation for the
3008 % basic \mfc{addto} operation. It was defined only so that \MP{} and \MF{}
3009 % can share the same higher level code.
3010 %
3011 % When the last parameter \gbc{v} is the name of picture we can save
3012 % memory if we pass the name rather than the value. Problems with picture
3013 % memory turned up in the shading macros for \MF{} and the dashing macros
3014 % for \MP{}.
3015 % \DescribeRoutine{coloraddon}
3016 % The macro \gbc{coloraddon} applies this memory-saving trick and has
3017 % completely replaced \gbc{coloraddto} in \grafbase{} code. Since
3018 % \gbc{coloraddto} turned out to be used only with \gbc{u} equal to
3019 % \gbc{active_plane}, we have eliminated that parameter from
3020 % \gbc{coloraddon}.
3021 %
3022 % The command \gbc{_orto} is like \gbc{orto}, but saves memory by passing
3023 % \emph{both} parameters by name. This also allows the application of
3024 % \gbc{mono} to both parameters. In addition to \gbc{coloraddon}, it is
3025 % used in \gbc{shade} and \gbc{tess}.
3026 % We also have \gbc{_subto}, an analogous version of \gbc{subto}.
3027 % \begin{macrocode}
3028 def coloraddto (expr clr) (suffix u) (expr v) =
3029 %<*MF>
3030 if clr < white:
3031 orto (u, v);
3032 else:
3033 subto (u, v);
3034 fi;
3035 %</MF>
3036 %<MP> addto u also v _wc_ clr;
3037 enddef;
3038
3039 %<MP>def orto (suffix u) (expr v) = addto u also v; enddef;
3040 %<MP>
3041 def coloraddon (expr clr) (suffix v) =
3042 %<*MF>
3043 if clr < white:
3044 _orto (active_plane, v);
3045 else:
3046 _subto (active_plane, v);
3047 fi;
3048 %</MF>
3049 %<MP> addto active_plane also v _wc_ clr;
3050 enddef;
3051
3052 def _orto (suffix u, v) =
3053 %<MF> mono (u); mono (v);
3054 addto u also v;
3055 %<MF>cull u keeping (1, 2);
3056 enddef;
3057
3058 %<*MF>
3059 def _subto (suffix u, v) =
3060 mono (u); mono (v); addto u also -v; cull u keeping (1, 1);
3061 enddef;
3062
3063 %</MF>
3064 % \end{macrocode}
3065 %
3066 % \DescribeRoutine{interior}
3067 % This takes the following expresion, \gbc{c}, which must be a
3068 % closed path, and returns the picture expression which is that path
3069 % filled. The cull command (\MF{} only) retains negative pixels
3070 % (converting them to positive). This way, clockwise contours are filled
3071 % also. \gbc{interior} is one of the most used commands throughout the
3072 % rest of \grafbase.
3073 %
3074 % We ignore color (new behavior with \mfpic{} version 0.7), since the
3075 % higher level commands now implement the coloring operations.
3076 % \begin{macrocode}
3077 vardef interior expr c =
3078 newpicture (v);
3079 addto v contour (c.t_);
3080 %<MF> cull v dropping (0,0);
3081 v
3082 enddef;
3083
3084 % \end{macrocode}
3085 %
3086 % \DescribeRoutine{interiors}
3087 % This is followed by the name of an array of closed paths and
3088 % returns the picture of the interiors of those closed paths. It builds
3089 % the returned picture from \mfc{nullpicture} by successively adding
3090 % the result of \gbc{interior} applied to each path in the array. This is
3091 % only used once by \grafbase, in \gbc{clipsto}, which might be a better
3092 % place to put the \mfc{for}-loop and not use this at all.
3093 % \begin{macrocode}
3094 vardef interiors suffix cc =
3095 newpicture (_ints);
3096 for _idx = 1 upto cc:
3097 addto _ints also interior cc[_idx]);
3098 endfor
3099 %<MF> mono (_ints);
3100 _ints
3101 enddef;
3102
3103 % \end{macrocode}
3104 %
3105 %
3106 % \subsection{Clipping}\label{basicclipping}
3107 %
3108 % \DescribeRoutine{clipto}
3109 % \gbc{clipto} takes the name of a picture \gbc{vt} and a closed path
3110 % \gbc{c} and modifies the picture leaving only the part inside the path.
3111 % In \MP{} we just invoke the \mfc{clip} primitive.
3112 %
3113 % \DescribeRoutine{clipsto}
3114 % This is similar, except it takes an array of paths \gbc{cc} and
3115 % leaves what is interior to any of the paths. This is one case where
3116 % \MP{} requires a substantially different point of view. In \MF, we
3117 % create the interiors and `and' the result to the named picture. In \MP,
3118 % we have to create the picture which is \gbc{vt} clipped to each separate
3119 % path, and combine the results. \Grafbase{} only uses this in the
3120 % \gbc{DoClip} command.
3121 % \begin{macrocode}
3122 def clipto (suffix vt) expr c =
3123 if path c:
3124 %<MF> andto (vt, interior c);
3125 %<MP> clip vt to c;
3126 fi
3127 enddef;
3128 def clipsto (suffix vt, cc) =
3129 %<MF> andto (vt, interiors cc);
3130 %<*MP>
3131 begingroup
3132 save _cl, _cl_; picture _cl, _cl_; _cl_ := nullpicture;
3133 for _idx = 1 upto cc:
3134 _cl := vt; clip _cl to cc[_idx]; addto _cl_ also _cl;
3135 endfor
3136 vt := _cl_;
3137 endgroup
3138 %</MP>
3139 enddef;
3140
3141 % \end{macrocode}
3142 %
3143 % \DescribeRoutine{Clipped}
3144 % Here, rather than modify a given picture, \gbc{Clipped} is a vardef
3145 % returning the picture which is the result of clipping the given picture
3146 % to the path. This is not used elsewhere in \grafbase{} nor \mfpic.
3147 %
3148 % Having found out that \mfc{clipped} is a \MP{} primitive, I've
3149 % changed the name to the uppercase version.
3150 % \begin{macrocode}
3151 vardef Clipped (suffix vt) expr c =
3152 setpicture (_Cl) vt; clipto (_Cl) c; _Cl
3153 enddef;
3154 %<MF>def clip = Clipped enddef;
3155
3156 % \end{macrocode}
3157 %
3158 % \DescribeRoutine{picneg}
3159 % The reverse video is easy in \MF, where \gbc{picneg} takes a picture
3160 % name and a closed path, and returns the part of the picture inside the
3161 % path, but with pixels reversed. In \MP{} we can only approximate this:
3162 % we clip the given picture and add that (using color \gbc{background})
3163 % on top of the \gbc{interior} of the curve colored \gbc{fillcolor}. This
3164 % is not used elsewhere in \file{grafbase.mp} so it may not be really
3165 % important whether \gbc{fillcolor} and \mfc{background} are the right
3166 % choices.
3167 % \begin{macrocode}
3168 vardef picneg (suffix vt) expr c =
3169 %<*MF>
3170 setpicture (_pn) interior c;
3171 _subto (_pn, vt);
3172 %</MF>
3173 %<*MP>
3174 setpicture (_cl) vt; clip _cl to c;
3175 newpicture (_pn);
3176 addto _pn also (interior c ) _wc_ fillcolor;
3177 addto _pn also _cl _wc_ background;
3178 %</MP>
3179 _pn
3180 enddef;
3181
3182 % \end{macrocode}
3183 %
3184 % \DescribeRoutine{shpath}
3185 % \gbc{shpath} does most of the work of drawing curves in \grafbase. It is
3186 % called by \gbc{safedraw} which is used by almost all the commands that
3187 % somehow draw a curve. It takes the name of a picture, a pen expression
3188 % and a path expression. It draws the path on the picture with the pen.
3189 % Since we use this (ultimately) for almost all drawing of paths, we
3190 % automatically have the aspect ratio taken care of by the \mfc{.t_}
3191 % macro.
3192 %
3193 % \DescribeRoutine{picpath}
3194 % \gbc{picpath} accepts a path expression and returns a picture, which is
3195 % either \gbc{nullpicture} (\gbc{penwd} too small) or the path drawn with
3196 % \gbc{drawpen}. This is mostly how \gbc{shpath} gets used: curve drawing
3197 % commands produce a picture with \gbc{picpath} and that gets used.
3198 %
3199 % \begin{macrocode}
3200 def shpath (suffix v) (expr q, f) =
3201 addto v doublepath (f.t_) withpen (q.t_);
3202 enddef;
3203
3204 numeric minpenwd;
3205 %<MF>minpenwd := 1; % 1 pixel
3206 %<MP>minpenwd := .05bp; % 1 pixel at 1440dpi
3207 vardef picpath expr d =
3208 newpicture (v);
3209 if penwd >= minpenwd:
3210 shpath (v, drawpen) (d);
3211 %<MF> mono (v);
3212 fi
3213 v
3214 enddef;
3215
3216 % \end{macrocode}
3217 %
3218 % \DescribeRoutine{picdot}
3219 % This places a specified picture expression (\gbc{w}) at a specified
3220 % location (\gbc{p}) in a specified picture variable (\gbc{v}). It is used
3221 % a number of places. It's \MF{} version takes care of the aspect ratio
3222 % via \mfc{.t_}. This is how we draw points and symbols and dots along a
3223 % curve: make the symbol into a picture \gbc{w} and add that picture with
3224 % \gbc{picdot}.
3225 % \begin{macrocode}
3226 def picdot (suffix v) (expr w, p) =
3227 addto v also
3228 %<MP> (w shifted p);
3229 %<MF> (w shifted goodpair (p));
3230 enddef;
3231
3232 % \end{macrocode}
3233 %
3234 % \DescribeRoutine{setdot}
3235 % \gbc{setdot} is named for its use rather than what it does. It takes a
3236 % path and a scale (numeric expression) and returns a picture which is a
3237 % drawing of the filled interior of the path (if it is a cycle) or the
3238 % path itself (not a cycle). In \MF, we ensure that the scale is at least
3239 % one pixel (assumes that the \gbc{apath} has dimension about 1 and
3240 % \gbc{minpenwd} is 1). This usually assures that something is drawn. In
3241 % \MP, \gbc{minpenwd} has the same purpose (though it is probably not
3242 % necessary). This routine is used a number of times where dots are
3243 % needed. Not in \gbc{shaded} (just below) but later in \gbc{shade} (an
3244 % older command taking paths in graph coordinates), \gbc{polkadot} and
3245 % some grid-making commands.
3246 % \begin{macrocode}
3247 vardef setdot (expr apath, sc) =
3248 if cycle apath: interior
3249 else: picpath
3250 fi
3251 %<MF> (apath scaled emax (ceiling (sc), minpenwd))
3252 %<MP> (apath scaled emax (sc, minpenwd))
3253 enddef;
3254
3255 % \end{macrocode}
3256 %
3257 % \DescribeRoutine{shadepic}
3258 % We want to shade regions with a very regular pattern of black and white
3259 % pixels for best appearance. Experiments show that symmetric dots
3260 % (e.g., circles, squares) work better than non-symmetric (e.g.,
3261 % rectangular). Circular dots are not significantly better than square at
3262 % the size needed. I believe that the default result of \gbc{shade} looks
3263 % reasonably good on my system. (That happens to produce two 3-pixel by
3264 % 3-pixel square dots in a 8-pixel square on a 360dpi printer.) So we try
3265 % to produce something similar. That is, the shading picture is 1.6bp
3266 % (8 pixels at 360dpi) square.
3267 %
3268 % As a compromise (symmetric dots look better, but rectangular dots give
3269 % more gray levels) we allow dots to be rectangles $k\times (k+1)$-pixels
3270 % (assuming the aspect ratio is 1). This produces twice the number of
3271 % gray levels. In my 360dpi example we get 15 gray levels. The two
3272 % farthest apart (4 by 4 dots versus 3 by 4 dots) differ by 1/8 in
3273 % fraction of area of coverage (which we equate to grayness).
3274 %
3275 % Why can't we have 64 grey levels in a $8\times 8$ square? Clearly we
3276 % can in principle turn on any number of the 64 pixels. Unfortunately,
3277 % spread out patterns (which look best) tend to consume memory, while
3278 % clumpy patterns are hard to make good-looking. Compensating for aspect
3279 % ratios unequal to 1 is also pretty hard to do automatically.
3280 %
3281 % The parameter \gbc{dims} needs to be a pair variable, and it will be
3282 % assigned the actual dimensions of the picture returned. These routines
3283 % are complicated by the fact that we may have an aspect ratio unequal to
3284 % $1$. When \mfc{aspect_ratio = 1} the basic concept is simple: make an
3285 % $n\times n$ square with two dots, each nearly $k \times k$ and nearly
3286 % square, where $2k^2/n^2$ is the gray level needed.
3287 %
3288 % The calculations assume a gray level greater than $1/2$, so the final
3289 % picture will be mostly white (for darker grays, we use the
3290 % complementary gray level to construct the `reverse video', and then
3291 % reverse back). Under this assumption, we concentrate all the black
3292 % pixels into the lower left and upper right quadrant of the picture we
3293 % are creating, so most of the calculation determines one of these
3294 % quadrants. The scratch variables \gbc{_hp} and \gbc{_vp} give the number
3295 % of horizontal and vertical pixels in the lower left quadrant,
3296 % \gbc{_dotwd} and \gbc{_dotht} do the same for the actual dot. Then
3297 % \gbc{_shp} is first set equal to one dot; then a copy of itself is added
3298 % in the upper right quadrant. Finally, the suffix parameter \gbc{dims} is
3299 % equated to the nominal width and height of the picture, and either
3300 % \gbc{_shp} or its reverse is returned.
3301 % \begin{macrocode}
3302 %<*MF>
3303 numeric shadepicsize; shadepicsize := 0.8bp;
3304 vardef shadepic (suffix dims) (expr grparam) =
3305 pair dims;
3306 setnumeric (_frac) 2*emin (grparam, 1 - grparam);
3307 save _hp, _vp, _dotwd, _dotht;
3308 if aspect_ratio < 1:
3309 _vp := emax (2, hround (shadepicsize.o_));
3310 _hp := hround (_vp._o_);
3311 _dotwd := hround (_hp*sqrt _frac);
3312 _dotht := if _dotwd = 0: 0
3313 else: hround (_hp*_vp*_frac/_dotwd)
3314 fi;
3315 else:
3316 _hp := emax (2, hround (shadepicsize));
3317 _vp := hround (_hp.o_);
3318 _dotht := hround (_vp*sqrt _frac);
3319 _dotwd := if _dotht = 0: 0
3320 else: hround (_hp*_vp*_frac/_dotht)
3321 fi;
3322 fi
3323 dims := ( _hp, _vp._o_ );
3324 newpicture (_shp);
3325 addto _shp contour rect (origin, (_dotwd, _dotht));
3326 picdot (_shp, _shp, dims);
3327 dims := 2dims; mono (_shp);
3328 if grparam >= .5: _shp
3329 else: (interior (rect (origin, dims))) picsub _shp
3330 fi
3331 enddef;
3332
3333 %</MF>
3334 % \end{macrocode}
3335 %
3336 % \DescribeRoutine{shaded}
3337 % This fills the interior of a contour (device coordinates) with copies of
3338 % \gbc{shadepic}. The routine \gbc{fillwith} is defined later, but its
3339 % name reflects its effect: a bounding rectangle (corners at \gbc{ll} and
3340 % \gbc{ur}) is filled with copies of a picture (in this case, the result
3341 % of \gbc{shadepic}), the picture having nominal dimensions \gbc{shdims}
3342 % in this case.
3343 %
3344 % It may seem odd that black and white return the same thing. That is
3345 % because white is handled in the calling routine by subtracting the
3346 % black result.
3347 %
3348 % The \gbc{setbbox} command was defined earlier, in
3349 % section~\ref{utilities}. The bounding rectangle it obtains is only
3350 % approximate in \MF{}, but that is sufficient, since we only use it to
3351 % produce things that are eventually clipped.
3352 %
3353 % We return \gbc{picpath} for non-cycles because I once thought to make
3354 % \gbc{shaded} a replacement for \gbc{setdot} to get gray dots (in the
3355 % \gbc{polkadot} routine). That turns out not to work, but this sort of
3356 % thing is also done in most of the rendering commands that require a
3357 % closed path.
3358 % \begin{macrocode}
3359 vardef shaded (expr clr) expr c =
3360 if cycle c:
3361 %<*MP>
3362 newpicture (v);
3363 addto v contour c _wc_ clr;
3364 v
3365 %</MP>
3366 %<*MF>
3367 if (clr <= black) or (clr >= white):
3368 interior c
3369 else:
3370 save shdims, shpic;
3371 picture shpic; pair shdims;
3372 shpic := shadepic (shdims) (clr);
3373 setbbox (ll, ur) c;
3374 newpicture (vsh);
3375 fillwith (vsh) (shpic, shdims, ll, ur);
3376 clipto (vsh) c; vsh
3377 fi
3378 %</MF>
3379 else: picpath c % should we? or just make it null?
3380 fi
3381 enddef;
3382
3383 % \end{macrocode}
3384 %
3385 % \DescribeRoutine{fillwith}
3386 % This is one of the ways we obtain something other than a solid fill. The
3387 % routines \gbc{polkadot}, \gbc{tess} and (in \MF) \gbc{shade} and
3388 % \gbc{shaded} all use it.
3389 %
3390 % It takes a picture expression \gbc{pic}, along with its dimensions (the
3391 % pair \gbc{dims}) in device coordinates, plus the opposite corners,
3392 % \gbc{ll} and \gbc{ur}, of a boundingbox rectangle, and draws that
3393 % rectangle filled with copies of \gbc{pic}. Starting with \mfpic{}
3394 % version 0.8, it adds to a predefined picture passed by name. Thus the
3395 % calling routine must make sure that picture is initialized (it need
3396 % not be \mfc{nullpicture}).
3397 %
3398 % One might do this with one loop nested in another, but it turns out to
3399 % be much faster (surprisingly much!) to do two separate loops: the second
3400 % one stacking copies of the row built by the first loop.
3401 %
3402 % We try to do any rounding that might have been forgotten. This code
3403 % takes a mode's aspect ratio into account so that (most) calling routines
3404 % don't have to. (That is, \gbc{dims} should be measured in horizontal
3405 % pixels, while \gbc{fwdims} is in actual pixels. This could have been
3406 % written in terms of \gbc{picdot}, which already handles aspect, but it
3407 % has got to be more efficient to do the aspect ratio calculations once
3408 % rather than every time through the loop.)
3409 % \begin{macrocode}
3410 vardef fillwith (suffix v) (expr pic, dims, ll, ur) =
3411 newpicture (b);
3412 %<*MF>
3413 save fwdims, _ll, _ur; pair fwdims, _ll, _ur;
3414 fwdims := goodpair (dims);
3415 _ll := floorpair (ll.t_);
3416 _ur := ur.t_;
3417 for s = xpart _ll step xpart fwdims until xpart _ur:
3418 addto b also pic shifted (s, 0);
3419 endfor
3420 for s = ypart _ll step ypart fwdims until ypart _ur:
3421 addto v also b shifted (0, s);
3422 endfor
3423 mono (v);
3424 %</MF>
3425 %<*MP>
3426 for s = xpart ll step xpart dims until xpart ur:
3427 addto b also pic shifted (s, 0);
3428 endfor
3429 for s = ypart ll step ypart dims until ypart ur:
3430 addto v also b shifted (0, s);
3431 endfor
3432 %</MP>
3433 enddef;
3434
3435 % \end{macrocode}
3436 %
3437 %
3438 % \subsection{Hatching}\label{basichatching}
3439 %
3440 % \DescribeRoutine{thatchf}
3441 % This is the all-purpose macro called by the other macros that
3442 % fill a region with hatching. It takes the name of a picture \gbc{v},
3443 % a transform expression \gbc{CT}, a numeric expresion \gbc{sp} giving the
3444 % space between hatch lines, and two pairs, \gbc{a} and \gbc{b},
3445 % that represent the lower left and upper right limits of a rectangle.
3446 % The expression \gbc{sp} must be nonzero. The calling macros should take
3447 % care of that.
3448 %
3449 % It modifies the picture by adding to it the rectangle full of
3450 % hatching lines spaced \gbc{sp} apart. The rectangle is initially upright
3451 % and the lines horizontal, but they are drawn transformed by the
3452 % transform \gbc{CT}. This is how diagonal hatching is accomplished: the
3453 % transform is a rotation.
3454 %
3455 % We guard against \gbc{ypart a} being greater than \gbc{ypart b} or
3456 % \gbc{sp} being negative: \gbc{_sp} is \gbc{sp} modified to have the same
3457 % sign as \gbc{ypart (b - a)}. Thus, repeatedly adding it to \gbc{ypart a}
3458 % gets one to \gbc{ypart b}. We make the starting value an integer
3459 % multiple of \gbc{_sp} to make sure adjacent regions don't have jarringly
3460 % misaligned hatch lines. (I guess that's the reason; this algorithm
3461 % predates my involvement with \mfpic{}.)
3462 % \begin{macrocode}
3463 def thatchf (suffix v) (expr CT, sp, a, b) =
3464 begingroup
3465 setnumeric (_sp) signof (ypart b - ypart a) abs(sp);
3466 for _y = _sp*( ceiling ((ypart a)/_sp) ) step _sp until ypart b:
3467 shpath (v, hatchpen)
3468 ( ( (xpart a, _y)--(xpart b, _y) ) transformed CT );
3469 endfor
3470 %<MF> mono (v);
3471 endgroup
3472 enddef;
3473
3474 % \end{macrocode}
3475 %
3476 %
3477 % \subsection{Gradient fills}\label{basicgradient}
3478 %
3479 % \CMP{} cannot do true gradients without some external help. Level-3
3480 % PostScript permits it, so recent \MP{} could do it by inserting
3481 % appropriate PS prologues and/or \MP{} specials. Doing that runs the
3482 % risk of introducing code not recognized by post-processors that expect
3483 % only what \MP\ natively offers. Therefore, we implement gradients by
3484 % filling a lot of thin regions with a range of different
3485 % colors.
3486 %
3487 % We have to drop down to pretty low-level operations since, before now,
3488 % we didn't need a command that added a colored region to a named
3489 % picture.
3490 %
3491 % For maximum flexibility, all our gradients pass variation in colors as a
3492 % function \mfc{clr} which must be previously \gbc{vardef}-ed and must
3493 % produce a color for each parameter value between $0$ and $1$.
3494 %
3495 % \DescribeRoutine{axialgradientf}
3496 % A linear gradient has colored rectangular strips that vary along a
3497 % single axis. The function parameter of \gbc{axialgradientf} takes one
3498 % variable and produces the color of each strip. \gbc{v} is a known
3499 % picture variable to which the resulting picture will be assigned,
3500 % \gbc{theta} is an angle, \gbc{a} and \gbc{b} are the opposite corners of
3501 % a rectangle. What is returned in \gbc{v} is a rectangular picture
3502 % rotated by \gbc{theta}.
3503 %
3504 % Normally, this is called by the \gbc{axialgradient} command which
3505 % declares the picture variable \gbc{v}, passes its angle parameter
3506 % \gbc{theta}, and computes the bounding box of a cyclic path for \gbc{a}
3507 % and \gbc{b}. The calling command will clip the result to the appropriate
3508 % path.
3509 %
3510 % The calculations with \gbc{signof} is for the same reason as in
3511 % \gbc{thatchf}. The other messy calculations try to cover the rectangle
3512 % exactly with an integer number of strips, with the first and last having
3513 % exactly the colors \gbc{clr(0)} and \gbc{clr(1)}.
3514 %
3515 % If the thickness of the strip is too small, memory problems might
3516 % result and appearence might suffer. Nevertheless we make no attempt to
3517 % enforce a minimum value.
3518 % \begin{macrocode}
3519 def axialgradientf (suffix clr, v) (expr theta, sp, a, b) =
3520 begingroup
3521 save _hh, _sp, _nn, _y;
3522 _hh := ypart b - ypart a;
3523 _sp := signof (_hh) abs(sp);
3524 _nn := emax (1, round (_hh/_sp));
3525 _sp := _hh/_nn + signof (_hh) epsilon;
3526 _nn := _nn-1;
3527 setpath (_p) rect ((xpart a, 0),(xpart b, _sp));
3528 _y := ypart a;
3529 for _i = 0 upto _nn:
3530 %<*MF>
3531 if (clr(_i/_nn)) < white :
3532 addto v also shaded (clr(_i/_nn)) ( _p shifted (0,_y))
3533 rotated theta;
3534 fi
3535 %</MF>
3536 %<*MP>
3537 addto v contour (_p shifted (0,_y)) rotated theta
3538 withcolor clr(_i/_nn);
3539 %</MP>
3540 _y := _y + _sp;
3541 endfor
3542 %<MF> mono (v);
3543 endgroup
3544 enddef;
3545
3546 % \end{macrocode}
3547 %
3548 % \DescribeRoutine{areagradientf}
3549 % The command \gbc{areagradientf} fills the rectangle determined by
3550 % corners \gbc{a} and \gbc{b} with pixels of dimension \gbc{sp} by
3551 % \gbc{tp}. Each pixel is filled with the color determined by \gbc{clr}.
3552 % This suffix parameter must be the name of a function taking two
3553 % parameters.
3554 %
3555 % The resulting rectangle is built on the picture variable whose name is
3556 % passed as the second parameter \gbc{v}. The calling routine is
3557 % \gbc{areagradient}, which determine the rectangle and initializes
3558 % the picture variable. It passes its other parameters unchanged.
3559 % \begin{macrocode}
3560 def areagradientf (suffix clr, v) (expr sp, tp, a, b) =
3561 begingroup
3562 save _ww, _hh, _sp, _tp, _nn, _mm, _x, _y;
3563 _ww := xpart b - xpart a;
3564 _hh := ypart b - ypart a;
3565 _sp := signof (_ww) abs(sp);
3566 _tp := signof (_hh) abs(tp);
3567 _nn := emax (1, round (_ww/_sp));
3568 _mm := emax (1, round (_hh/_tp));
3569 _sp := _ww/_nn + signof (_ww) epsilon;
3570 _tp := _hh/_mm + signof (_hh) epsilon;
3571 _mm := _mm-1; _nn := _nn-1;
3572 setpath (_p) rect (origin,(_sp,_tp));
3573 _x := xpart a; y_a := ypart a;
3574 for _i = 0 upto _nn:
3575 _y := y_a;
3576 for _j = 0 upto _mm:
3577 %<*MF>
3578 if (clr(_i/_nn,_j/_mm)) < white:
3579 addto v also shaded (clr(_i/_nn,_j/_mm)) (_p shifted (_x,_y));
3580 fi
3581 %</MF>
3582 %<*MP>
3583 addto v contour (_p shifted (_x,_y)) withcolor
3584 clr(_i/_nn,_j/_mm);
3585 %</MP>
3586 _y := _y + _tp;
3587 endfor
3588 _x := _x + _sp;
3589 endfor
3590 %<MF> mono (v);
3591 endgroup
3592 enddef;
3593
3594 % \end{macrocode}
3595 %
3596 % \DescribeRoutine{radialgradientf}
3597 % The command \gbc{radialgradientf} fills the a circle determined by
3598 % center \gbc{ctr} and radius \gbc{rad} with concentric circular strips of
3599 % thickness \gbc{sp}. Each strip is filled with the color determined by
3600 % \gbc{clr}. This suffix parameter must be the name of a function of one
3601 % parameter.
3602 %
3603 % This command is called by \gbc{radialgradient}, which determines the
3604 % radius of a circle needed to cover a region and clips the picture
3605 % returned in \gbc{v} to that region.
3606 % \begin{macrocode}
3607 path unitcircle;
3608 unitcircle := fullcircle scaled 2;
3609 def radialgradientf (suffix clr, v) (expr sp, ctr, rad) =
3610 begingroup
3611 save _sp, _r, _nn;
3612 _nn := emax (1, round (rad/sp));
3613 _sp := rad/_nn + epsilon;
3614 _nn := _nn - 1;
3615 _r := _sp;
3616 % fill the small center circle first
3617 %<*MF>
3618 if (clr(0)) < white :
3619 addto v also shaded (clr(0)) (unitcircle scaled _r shifted ctr);
3620 fi
3621 %</MF>
3622 %<*MP>
3623 addto v contour (unitcircle scaled _r shifted ctr)
3624 withcolor clr(0);
3625 %</MP>
3626 for _i = 1 upto _nn:
3627 %<*MF>
3628 if (clr(_i/_nn)) < white :
3629 addto v also shaded (clr(_i/_nn))
3630 (unitcircle scaled (_r + _sp) -- reverse unitcircle scaled _r
3631 --cycle) shifted ctr;
3632 fi
3633 %</MF>
3634 %<*MP>
3635 addto v contour
3636 (unitcircle scaled (_r + _sp) -- reverse unitcircle scaled _r
3637 --cycle) shifted ctr withcolor clr(_i/_nn);
3638 %</MP>
3639 _r := _r + _sp;
3640 endfor
3641 %<MF> mono (v);
3642 endgroup
3643 enddef;
3644
3645 % \end{macrocode}
3646 %
3647 %
3648 % \subsection{Tiles}\label{tiles}
3649 %
3650 % Tesselations are a type of fill in which a rectangular pattern is
3651 % repeated throughout a region. The repeated rectangle is called a tile.
3652 % We provide here an environment in which the drawing commands add to a
3653 % picture variable other than \mfc{currentpicture}. We do this very simply
3654 % by redefining \gbc{active_plane}, localizing the redefinition between
3655 % \gbc{tile} and \gbc{endtile}
3656 %
3657 % \DescribeRoutine{tile}
3658 % The macro \gbc{tile} accepts one suffix parameter, the name of the tile,
3659 % followed by three numeric expressions and a boolean. \gbc{unit} should
3660 % be a dimension in device units and is the unit of length for all high
3661 % level drawing commands within the environment. \gbc{width} and
3662 % \gbc{height} specify the size of the tile in multiples of \gbc{unit}, and
3663 % \gbc{clipit} is a boolean that determines if the resulting picture is
3664 % clipped to the rectangle these parameters determine. For example,\\
3665 % \indent \gbc{tile (fred)(1in, 1, 2, true)} \\
3666 % starts a tile named \gbc{fred} which will be 1 inch wide and 2 inches
3667 % tall, and any marks that extend beyond this rectangle are clipped off.
3668 % The tile is enclosed in a group to delimit these changes to the basic
3669 % drawing parameters.
3670 % \DescribeRoutine{endtile}
3671 % The macro \gbc{endtile} merely implements the clipping and then closes
3672 % the group.
3673 %
3674 % In \MF, the picture should be a whole number of pixels in size, so that
3675 % the tiles fit perfectly together. The fact that shifts must be integer
3676 % values is only mildly relevant, because the placement code does the
3677 % rounding.
3678 %
3679 % For tesselation (filling with tiles) we need to know various properties
3680 % of the tile, so a tile is a composite object consisting of a picture,
3681 % \gbc{fred.pic} in our example (the actual tile) and a pair
3682 % \gbc{fred.dims} of the dimensions (in device units). We used to
3683 % save the \gbc{clipit} parameter in \gbc{atile.clipon}, but it was never
3684 % used. We also used to have separate numerics \gbc{atile.wd} and
3685 % \gbc{atile.ht} but they only got used together as a pair.
3686 % \begin{macrocode}
3687 def tile (suffix atile) (expr unit, width, height, clipit) =
3688 picture atile.pic; atile.pic := nullpicture;
3689 pair atile.dims;
3690 %<MF> atile.dims := round ((width, height)*unit);
3691 %<MP> atile.dims := (width, height)*unit;
3692 begingroup
3693 % \end{macrocode}
3694 % We do a subset of what we do in \gbc{beginmfpic}, redefining
3695 % \gbc{active_plane} so that all drawing commands that add to it will
3696 % contribute to the tile, and adapting \gbc{ztr} to the tile dimensions.
3697 % Re also redefine \gbc{xneg}, et al., for the benefit of \gbc{levelset}.
3698 % \begin{macrocode}
3699 save active_plane;
3700 def active_plane = atile.pic enddef;
3701 save ztr, vtr; transform ztr, vtr;
3702 ztr := identity scaled unit; vtr := ztr;
3703 save xneg, xpos, yneg, ypos;
3704 xneg := 0; xpos := width; yneg := 0; ypos := height;
3705 % \end{macrocode}
3706 % To implement \gbc{clipit}, we set the current clipping path array
3707 % \gbc{ClipPath[\,]} to the boundary of the tile. Note that this turns off
3708 % user-defined clipping paths, which are unlikely to be correct for the
3709 % local tile coordinates.
3710 % \begin{macrocode}
3711 save ClipOn; boolean ClipOn;
3712 if clipit:
3713 ClipOn := true;
3714 setarray (path) (ClipPath) (rect(origin, atile.dims));
3715 else:
3716 ClipOn := false;
3717 fi
3718 enddef;
3719 def endtile =
3720 DoClip (active_plane);
3721 endgroup
3722 enddef;
3723
3724 % \end{macrocode}
3725 %
3726 % \DescribeRoutine{is_tile}
3727 % To test whether \gbc{atile} is really a tile, just see if the needed
3728 % components are defined and of the correct type.
3729 % \begin{macrocode}
3730 vardef is_tile (suffix atile) =
3731 (known atile.pic ) and (picture atile.pic) and
3732 (known atile.dims) and (pair atile.dims )
3733 enddef;
3734
3735 % \end{macrocode}
3736 %
3737 %
3738 %
3739 % \section{Bounding Boxes of Paths}\label{bboxes}
3740 %
3741 % To fill a region with other than a solid fill, we normally fill a
3742 % rectangle with copies of a picture (or a path) and then clip to the
3743 % boundary curve. In order not to place too many copies, we try to find a
3744 % rectangle that is not too much larger than that region. For this we have
3745 % the macro \gbc{getbbox} which takes two pair variable and a path
3746 % expression, and sets the pairs to the lower left corner and upper right
3747 % corner, respectively, of a rectangle enclosing the path. The bounding
3748 % box macros are used on paths in device coordinates, but there is no
3749 % intrinsic reason that has to be so: they will return the bounding box in
3750 % whatever coordinates the supplied path is in.
3751 %
3752 % \DescribeRoutine{getbbox}
3753 % One can get a rather loose bounding rectangle by using the fact that
3754 % each segment of a path (from \mfc{point j of g} to \mfc{point j+1 of g})
3755 % is contained in the convex set determined by all 4 control points for
3756 % that segment. So we get a containing rectangle by getting the smallest
3757 % and largest values of the $x$- and $y$-coordinates of all those points.
3758 % We can get a considerably tighter fit if we cut each segment in half
3759 % (or more) before doing that. A calling routine is expected to save and
3760 % declare the suffixes \gbc{ll} and \gbc{ur}. Within \grafbase{} commands,
3761 % \gbc{getbbox} is always called by \gbc{setbbox}, which does this.
3762 %
3763 % \DescribeRoutine{ctrlsbbox}
3764 % There is a difference between ``\mfc{postcontrol 0 of (subpath (j,j+1/2)
3765 % of p)}'' and ``\mfc{postcontrol j of p}''. To gain the tighter box we have
3766 % to look at the former. \gbc{ctrlsbbox} just updates the previously found
3767 % corners \gbc{ll} and \gbc{ur} of the bounding box based on the controls
3768 % of the path segment \gbc{p}, and the calling routine \gbc{getbbox} passes
3769 % it half a segment at a time. We don't examine the endpoints of
3770 % the half-segment: one has already been examined by \gbc{getbbox} and
3771 % the other (a subdivision point of an original segment) lies on the line
3772 % segment connecting two control points, and so can't increase the bbox.
3773 %
3774 % We've given this potentially unlimited accuracy by allowing the number
3775 % of subdivisions (\gbc{bbox_split}) to be arbitrary. We choose 2 for the
3776 % default. The \gbc{setsplit} command (subsection~\ref{utilities}) ensures
3777 % that \gbc{_s} is integral and positive, just in case \gbc{bbox_split}
3778 % somehow isn't.
3779 %
3780 % This description applies only to \MF, because \MP{} has built-in
3781 % facilities for determining the bounding box.
3782 %
3783 % I have changed \gbc{ctrlsbbox} to have the same syntax as \gbc{getbbox}.
3784 % I don't know why I defined it differently.
3785 %
3786 % \RoutineIndex{pnt}
3787 % \RoutineIndex{pre}
3788 % \RoutineIndex{post}
3789 % I got tired of typing long expressions like ``\gbc{(precontrol length
3790 % p of p)}'', and now use the following abbreviations.
3791 % \begin{macrocode}
3792 vardef pnt@# (expr p) = point @# of p enddef;
3793 vardef pre@# (expr p) = precontrol @# of p enddef;
3794 vardef post@# (expr p) = postcontrol @# of p enddef;
3795
3796 numeric bbox_split; bbox_split := 4;
3797 def getbbox (suffix ll, ur) expr g =
3798 %<MP> ll := llcorner g; ur := urcorner g;
3799 %<*MF>
3800 setsplit (_s) bbox_split;
3801 ur := ll := pnt 0 (g);
3802 for _j = 1 upto length g:
3803 ll := pairmin (ll, pnt[_j] (g)); ur := pairmax (ur, pnt[_j] (g));
3804 endfor
3805 for _j = 1 upto _s*(length g):
3806 ctrlsbbox (ll, ur) subpath ((_j-1)/_s, _j/_s) of g;
3807 endfor
3808 %</MF>
3809 if showbbox: noclip ( safedraw rect (ll, ur) ); fi
3810 enddef;
3811
3812 %<*MF>
3813 def ctrlsbbox (suffix ll, ur) expr p =
3814 ll := pairmin ( pairmin (ll, post0 (p)), pre 1 (p) );
3815 ur := pairmax ( pairmax (ur, post0 (p)), pre 1 (p) );
3816 enddef;
3817
3818 %</MF>
3819 % \end{macrocode}
3820 %
3821 % \DescribeRoutine{getradius}
3822 % This is very similar to \gbc{getbbox}, but gets a ``bounding circle''
3823 % instead of a box. It is used to get nearly the smallest circle with a
3824 % given center that contains a path. The path is shifted to place the
3825 % center at the origin and then this function is called. Similarly,
3826 % \DescribeRoutine{ctrlsradius}
3827 % \gbc{ctrlsradius} is used like \gbc{ctrlsbbox}.
3828 % \begin{macrocode}
3829 def getradius (suffix rad) expr g =
3830 setsplit (_s) bbox_split;
3831 rad := abs (pnt0 (g));
3832 for _j = 1 upto length g:
3833 rad := emax(rad, abs(pnt[_j] (g)));
3834 endfor
3835 for _j = 1 upto _s*(length g):
3836 ctrlsradius (rad) subpath ((_j-1)/_s, _j/_s) of g;
3837 endfor
3838 enddef;
3839
3840 def ctrlsradius (suffix rad) expr p =
3841 rad := emax( emax (rad, abs(post0 (p))), abs(pre1 (p) ))
3842 enddef;
3843
3844 % \end{macrocode}
3845 %
3846 % We also have \gbc{tightbbox} and \gbc{tbbox} in \MF{} but these are no
3847 % longer used so we'll omit them from \grafbase, but keep them in the
3848 % documentation for now.
3849 %
3850 % \DescribeRoutine{tightbbox}
3851 % Calculate tight bounding box points \gbc{ll} and \gbc{ur} for path
3852 % \gbc{g}. The tight bounding box is accurate to the limits of the
3853 % \mfc{solve} macro, which is the numeric \mfc{tolerance}, which we set to
3854 % \mfc{.5} (accurate enough, assuming pixel units). This is only called by
3855 % \gbc{tbbox}, which is never used.
3856 %
3857 % \gbc{xlimit(x)} returns a value of true if the path \gbc{g} doesn't
3858 % cross the vertical line at \gbc{x}. \gbc{ylimit(y)} is the same for the
3859 % horizontal line at \gbc{y}.
3860 % \begin{macrocode}
3861 %<*unused>
3862 def tightbbox (expr g) (suffix ll, ur) =
3863 begingroup
3864 interim tolerance := .5;
3865 ll := ( (solve _xlimit (-infinity, xpart pnt 0 (g))),
3866 (solve _ylimit (-infinity, ypart pnt 0 (g))) );
3867 ur := ( (solve _xlimit ( infinity, xpart pnt 0 (g))),
3868 (solve _ylimit ( infinity, ypart pnt 0 (g))) );
3869 endgroup
3870 if showbbox:
3871 noclip ( safedraw rect (ll, ur) );
3872 fi
3873 enddef;
3874
3875 vardef _xlimit (expr x) =
3876 ((x, -infinity)--(x, infinity)) misses g
3877 enddef;
3878
3879 vardef _ylimit (expr y) =
3880 ((-infinity, y)--(infinity, y)) misses g
3881 enddef;
3882
3883 % \end{macrocode}
3884 %
3885 % \DescribeRoutine{tbbox}
3886 % \gbc{tbbox} simply calls \gbc{tightbbox} on each of an array of paths
3887 % and takes the maximum of all the upper right corners and the minimum of
3888 % all the lower left. Same syntax as \gbc{tightbbox} except that, instead
3889 % of a path parameter, \gbc{g} must be the name of an array of paths.
3890 % This macro is never used elsewhere in \grafbase.
3891 % \begin{macrocode}
3892 vardef tbbox (suffix g) (suffix ll, ur) =
3893 save _gll, _gur; pair _gll, _gur;
3894 tightbbox (g1, ll, ur);
3895 for _idx = 2 upto g:
3896 tightbbox (g[_idx], _gll, _gur);
3897 ll := pairmin (ll, _gll); ur := pairmax (ll, _gur);
3898 endfor
3899 if showbbox: noclip ( safedraw rect (ll, ur) ); fi
3900 enddef;
3901
3902 %</unused>
3903 % \end{macrocode}
3904 %
3905 %
3906 %
3907 % \section{Device Coordinate Rendering Commands}\label{basicrendering}
3908 %
3909 % We use the word `rendering' to refer to commands that accept a path
3910 % expression as one parameter and use it to modify the \gbc{active_plane}.
3911 % All the commands in this section expect paths, pairs and dimensions in
3912 % device coordinates.
3913 %
3914 %
3915 % \subsection{Drawing}\label{basicdrawing}
3916 %
3917 % \DescribeRoutine{safedraw}
3918 % \gbc{safedraw} accepts a path expression, and adds the result to
3919 % \gbc{active_plane}. It is the first drawing command to draw
3920 % exclusively on \gbc{active_plane}. This is the first of many uses of
3921 % \gbc{coloraddon}. In \MP{} it is basically the primitives \mfc{addto}
3922 % and \mfc{withcolor} applied to \gbc{active_plane}, but in \MF{} it adds
3923 % when the color is less than 1 (gray or black), otherwise it subtracts
3924 % (white).
3925 %
3926 % \RoutineIndex{colorsafedraw}
3927 % The command \gbc{safedraw} merely calls \gbc{colorsafedraw}, which then
3928 % calls \gbc{picpath}, which calls \gbc{shpath}. One reason for this
3929 % roundabout sequence is to support older files (where \gbc{colorsafedraw}
3930 % was not defined). Another is that color handling in \MF{} requires a
3931 % picture with pixels of weight 1 or 0 only (\gbc{picpath}). Moreover,
3932 % \gbc{shpath} guarantees that the mode's aspect ratio is respected.
3933 % \begin{macrocode}
3934 def safedraw = colorsafedraw (drawcolor) enddef;
3935 def colorsafedraw (expr clr) expr d =
3936 begingroup
3937 setpicture (v) picpath d;
3938 DoClip (v); coloraddon (clr, v);
3939 endgroup
3940 enddef;
3941
3942 % \end{macrocode}
3943 %
3944 %
3945 % \subsection{Filling}\label{basicfilling}
3946 %
3947 % \DescribeRoutine{NoCycle}
3948 % This is a common warning for all those commands that require a cycle
3949 % (closed path) but an open path is supplied. In addition to the warning
3950 % in those commands, we also call \gbc{safedraw} for debugging purposes.
3951 %
3952 % \DescribeRoutine{safefill}
3953 % \RoutineIndex{colorsafefill}
3954 % The basic \gbc{safefill} simply calls the colored version with the
3955 % default parameter \gbc{fillcolor}. \gbc{colorsafefill} takes a color as
3956 % its first parameter and a path expression as second. These commands fill
3957 % the path in the \gbc{active_plane}. In \MF, when the color is strictly
3958 % between $0$ and 1, a gray fill is simulated with the \gbc{shaded} macro.
3959 %
3960 % To simulate the effect of painting over in gray, the \MF{} version
3961 % clears the region before adding the shaded fill.
3962 %
3963 % \DescribeRoutine{safeunfill}
3964 % \gbc{safeunfill} is just \gbc{safefill} with the color \mfc{background}.
3965 % In \MF{}, when \gbc{background = white = 1}, this is detected by
3966 % \gbc{coloraddon} which then subtracts the picture. We do this inside
3967 % \gbc{noclip}, just because it seems a user would expect clipping only
3968 % when things are \emph{added}. In \MP{} the white is indeed added, but
3969 % conceptually, material is cleared away.
3970 % \begin{macrocode}
3971 def NoCycle (expr s) expr p =
3972 GBwarn s & " cannot be applied to an open path."
3973 & " The path will be drawn instead.";
3974 safedraw p;
3975 enddef;
3976
3977 %<MF>vardef isgray (expr X) = (X > black) and (X < white) enddef;
3978 %<MF>
3979 def safefill = colorsafefill (fillcolor) enddef;
3980 vardef colorsafefill (expr clr) expr c =
3981 if cycle c:
3982 setpicture (v) interior c;
3983 DoClip (v);
3984 %<*MF>
3985 if isgray (clr):
3986 _subto (active_plane) (v);
3987 v := nullpicture;
3988 v := shaded (clr) c;
3989 fi
3990 %</MF>
3991 coloraddon (clr, v);
3992 else: NoCycle("fill") c;
3993 fi
3994 enddef;
3995 def safeunfill expr c =
3996 if cycle c: noclip (colorsafefill (background) c);
3997 else: NoCycle("unfill") c;
3998 fi
3999 enddef;
4000
4001 % \end{macrocode}
4002 %
4003 %
4004 % \subsection{Clipping}\label{clipping}
4005 %
4006 % \DescribeRoutine{safeclip}
4007 % This applies \gbc{clipto} to the active drawing plane. It follows the
4008 % pattern started with \gbc{safefill} where commands that require a cycle
4009 % will \gbc{safedraw} non-cyclic paths.
4010 % \begin{macrocode}
4011 def safeclip expr c =
4012 if cycle c: clipto (active_plane) c;
4013 else: NoCycle("clip") c;
4014 fi
4015 enddef;
4016
4017 % \end{macrocode}
4018 %
4019 %
4020 %
4021 % \section{Graph Coordinate Rendering}\label{rendering}
4022 %
4023 % \DescribeRoutine{store}
4024 % Now we come to the highest level rendering operations. These are the
4025 % commands written to the output file by \mfpic. They accept a path in
4026 % \emph{graph} coordinates, convert it to device coordinates, rendering
4027 % the result, and return the original path. This way one can render a
4028 % path and pass it on to the preceding command for further processing.
4029 % This is how \mfpic{} implements multiple prefix macros. However, this
4030 % cannot be kept up because \MF{} abhors an isolated expression. Therefore
4031 % we provide a command that accepts a path and doesn't pass it on. In
4032 % theory, it could do nothing, but in \mfpic{} we store the path in
4033 % \gbc{curpath}, making every \mfpic{} figure a path assigment command
4034 % and the rendering is `merely' a side-effect.
4035 %
4036 % \DescribeRoutine{stored}
4037 % The macro \gbc{stored} performs \gbc{store}, but passes the same path as
4038 % its return value. This is used by \mfpic{} to implement the \cs{store}
4039 % command, allowing it to also be a prefix macro
4040 %
4041 % I don't know if \gbc{store} needs to employ \mfc{hide()}, but it seems
4042 % not to hurt.
4043 % \begin{macrocode}
4044 def store (suffix fs) expr f =
4045 hide (
4046 if (not path f) and (not pair f):
4047 GBerrmsg ("Improper expression type.")
4048 "The second argument to `store' must be a path or pair.";
4049 fi
4050 if not path fs: path fs; fi
4051 fs := f
4052 )
4053 enddef;
4054 vardef stored (suffix fs) expr f = store (fs) f; f enddef;
4055
4056 % \end{macrocode}
4057 %
4058 %
4059 % \subsection{Drawing}\label{drawing}
4060 %
4061 % \DescribeRoutine{drawn}
4062 % \RoutineIndex{colordrawn}
4063 % The command \gbc{drawn} merely calls \gbc{colordrawn} with the default
4064 % color \gbc{drawcolor}. Then \gbc{colordrawn} takes a color \gbc{clr}
4065 % and a path expression \gbc{f} and returns the same path. In between,
4066 % \gbc{zconv (f)} is subjected to \gbc{colorsafedraw}.
4067 % \begin{macrocode}
4068 def drawn = colordrawn (drawcolor) enddef;
4069 vardef colordrawn (expr clr) expr f =
4070 colorsafedraw (clr) (zconv (f)); f
4071 enddef;
4072
4073 % \end{macrocode}
4074 %
4075 % \DescribeRoutine{colorwiggle}
4076 % This is a multi-tasking command that can draw either zigzag or
4077 % sinewave shapes depending on the boolean first parameter. For \mfc{true}
4078 % we get smooth wiggles, for \mfc{false} we get jagged ones. In the
4079 % smooth case, a tension parameter allows an adjustment to the smoothness.
4080 % The command
4081 % \DescribeRoutine{zigzag}
4082 % \RoutineIndex{colorzigzag}
4083 % \gbc{zigzag} calls it with the value \mfc{false} and an arbitrary
4084 % value of the tension;
4085 % \DescribeRoutine{sinewave}
4086 % \RoutineIndex{colorsinewave}
4087 % \gbc{sinewave} calls it with \mfc{true}, allowing it to pick up the
4088 % tension parameter. All expect a quadruple of dimensions to follow
4089 %
4090 % The reason for using a loop (at the end) that draws the \gbc{sinewave}
4091 % path in pieces, is that all the turning can quickly exceed \MF{}'s limit
4092 % on the ``rounding table size''. I'd never heard of this until I ran
4093 % this without a loop and received the ``capacity exceeded'' message. This
4094 % turns out to be a problem mostly when the ratio of \gbc{len} to
4095 % \gbc{wid} is too small and the `humps' of the sine are more like
4096 % `bulbs'. However it is always a problem with \gbc{corkscrew} (below).
4097 %
4098 % There is no need for the loop in \MP{}, nor in \MF{} if
4099 % \mfc{autorounding} is set to $0$, but \mfpic's curved paths definitely
4100 % look better with the default \mfc{autorounding=2}.
4101 % \begin{macrocode}
4102 def zigzag = colorzigzag (drawcolor) enddef;
4103 def colorzigzag (expr clr) = colorwiggle (false, clr, 0) enddef;
4104 def sinewave = colorsinewave (drawcolor) enddef;
4105 def colorsinewave = colorwiggle (true) enddef;
4106
4107 vardef colorwiggle (expr smth, clr, tens, blen, elen, len, wid) expr f
4108 =
4109 convertpath (g) f;
4110 setuplengtharray (cumlen, totlen, ct) g;
4111 save B;
4112 if cycle f:
4113 B := 0;
4114 else:
4115 B := abs(blen)/_rescale_factor;
4116 totlen := totlen - B - abs(elen)/_rescale_factor;
4117 fi
4118 setnumeric (n) 2*round (totlen/len*_rescale_factor);
4119 if n < 2:
4120 colorsafedraw (clr) g;
4121 else:
4122 save T, U, X, Y, Z, p;
4123 pair U, X, Y, Z; path p;
4124 T := if cycle f: 0 else: gettime (cumlen, ct) (B) fi;
4125 Z := pnt[T] (g);
4126 p :=if not cycle f: (subpath (0,T) of g)
4127 if smth: {curl 0} ..tension tens.. else: -- fi
4128 fi
4129 for i = 1 upto n:
4130 hide(
4131 T := gettime (cumlen, ct) (B+(i/n)*totlen);
4132 X := Z; Z := pnt[T] (g);
4133 Y := .5[X,Z]; U := sgn (Z-X);
4134 )
4135 (Y + (U zscaled (0, if even i: - fi wid)))
4136 if smth: {U}..tension tens.. else: -- fi
4137 endfor
4138 if cycle f: cycle
4139 else: if smth: {curl 0} fi (subpath (T, length g) of g)
4140 fi;
4141 newpicture (v);
4142 %<MP> shpath (v, drawpen) (p);
4143 %<*MF>
4144 if smth:
4145 save n, k;
4146 n := length p; k = n div 50;
4147 for i = 0 step 50 until 50*(k-1):
4148 shpath (v, drawpen) (subpath (i,i+50) of p);
4149 endfor
4150 shpath (v, drawpen) (subpath (50k,n) of p);
4151 else: shpath (v, drawpen) (p);
4152 fi
4153 %</MF>
4154 DoClip(v); coloraddon (clr, v);
4155 fi
4156 f
4157 enddef;
4158
4159 % \end{macrocode}
4160 %
4161 % \DescribeRoutine{corkscrew}
4162 % \RoutineIndex{colorcorkscrew}
4163 % The definition of \gbc{corkscrew} shares a lot of code with \gbc{zigzag}
4164 % and \gbc{sinewave}, but the middle is considerably different, so it is
4165 % not really possible to make a multipurpose command that can do all
4166 % three.
4167 % \begin{macrocode}
4168 def corkscrew = colorcorkscrew (drawcolor) enddef;
4169 vardef colorcorkscrew (expr clr, tens, blen, elen, len, wid) expr f =
4170 convertpath (g) f;
4171 setuplengtharray (cumlen, totlen, ct) g;
4172 save B;
4173 if cycle f:
4174 B := 0;
4175 else:
4176 B := abs(blen)/_rescale_factor;
4177 totlen := totlen - B - abs(elen)/_rescale_factor;
4178 fi
4179 setnumeric (n) round (totlen/len*_rescale_factor);
4180 if n < 2:
4181 colorsafedraw (clr) g;
4182 else:
4183 save T, U, X, Y, Z, p;
4184 pair U, X, Y, Z; path p;
4185 T := if cycle f: 0 else: gettime (cumlen, ct) (B) fi;
4186 Z := pnt[T] (g);
4187 p :=if (not cycle f) and (B > 0): (subpath (0,T) of g)-- fi
4188 for i = 1 upto n:
4189 hide(
4190 T := gettime (cumlen, ct) (B+(i/n)*totlen);
4191 X := Z; Z := pnt[T] (g);
4192 Y := .5[X,Z]; U := sgn (Z-X);
4193 )
4194 (X + (U zscaled (0,-wid))){ U}..tension tens..
4195 (Y + (U zscaled (0, wid))){-U}..tension tens..
4196 endfor
4197 if cycle f: cycle
4198 else:
4199 {U}(Z + (U zscaled (0,-wid)))
4200 if elen <> 0: --(subpath(T, length g) of g) fi
4201 fi;
4202 newpicture (v);
4203 %<MP> shpath (v, drawpen) (p);
4204 %<*MF>
4205 save n, k;
4206 n := length p; k = n div 50;
4207 for i = 0 step 50 until 50*(k-1):
4208 shpath (v, drawpen) (subpath (i,i+50) of p);
4209 endfor
4210 shpath (v, drawpen) (subpath (50k,n) of p);
4211 %</MF>
4212 DoClip(v); coloraddon (clr, v);
4213 fi
4214 f
4215 enddef;
4216
4217 % \end{macrocode}
4218 %
4219 %
4220 % \subsection{Filling, unfilling and clipping}\label{filling}
4221 %
4222 % \DescribeRoutine{filled}
4223 % \RoutineIndex{colorfilled}
4224 % The command \gbc{filled} calls \gbc{colorfilled} with the default color
4225 % \gbc{fillcolor}. Then \gbc{colorfilled} takes a color \gbc{clr} and a
4226 % path expression \gbc{c}, returning the same path after subjecting
4227 % \gbc{zconv (c)} to \gbc{colorsafefill}.
4228 % \DescribeRoutine{unfilled}
4229 % The macro \gbc{unfilled} returns the path after running \gbc{safeunfill}.
4230 %
4231 % \DescribeRoutine{Clip}
4232 % Finally, \gbc{Clip} is similar, running \gbc{safeclip}. The name
4233 % \gbc{clip} (lowercase) is taken: it is a \MP{} primitive.
4234 % \begin{macrocode}
4235 def filled = colorfilled (fillcolor) enddef;
4236 vardef colorfilled (expr clr) expr c =
4237 colorsafefill (clr) zconv (c); c
4238 enddef;
4239 vardef unfilled expr c = safeunfill zconv (c); c enddef;
4240 vardef Clip expr c = safeclip zconv (c); c enddef;
4241
4242 % \end{macrocode}
4243 %
4244 %
4245 % \subsection{Shading}\label{shading}
4246 %
4247 % \DescribeRoutine{shade}
4248 % Shading is accomplished differently in \MP{} from \MF; however, many of
4249 % the same parameters are used for compatibility (so that \MP{} can be run
4250 % on a \file{.mf} created for \grafbase{} by \mfpic). In \MP, shading is
4251 % just filling with some level of gray. In \MF, we place a pattern of
4252 % small dots with the size and spacing adjustable. For compatibility,
4253 % \MP{} accepts these size and spacing parameters, but simply uses them to
4254 % calculate the darkness of gray.
4255 %
4256 % Ideally (i.e., for best appearance) one would shade with single pixels
4257 % placed in a regular pattern. Unfortunately, this is the most memory
4258 % intensive for \MF, which stores bitmaps by scanning each row of pixels,
4259 % and records where changes from black to white occur. We do use simple
4260 % dots, but make them quite a bit larger than one pixel. By default,
4261 % \gbc{0.5bp} in diameter, spaced (in \mfpic) a default \gbc{1pt} between
4262 % centers.
4263 %
4264 % The shape and size of the dots can be selected by defining
4265 % \gbc{shadedotpath} and \gbc{shadewd}. A closed path representing the
4266 % boundary of one dot of unit size, \gbc{shadedotpath} is initialized to a
4267 % circle.
4268 %
4269 % The parameter \gbc{sp} is the distance between the centers of the dots in
4270 % device coordinates, and \gbc{f} is the path to be filled in \emph{graph
4271 % coordinates}.
4272 %
4273 % As usual, if the path is not closed, we draw the curve instead. If the
4274 % spacing is too small relative to \gbc{shadewd}, we fill the curve.
4275 % Otherwise the \gbc{fillwith} macro is used to fill with copies of
4276 % a dot picture.
4277 % \begin{macrocode}
4278 numeric shadewd; shadewd := 0.5bp;
4279 path shadedotpath;
4280 shadedotpath := fullcircle;
4281
4282 vardef shade (expr sp) expr f =
4283 convertpath (g) f;
4284 % \end{macrocode}
4285 % It seems clear that the gray level (\gbc{gr}) should depend
4286 % quadratically on \gbc{shadewd/sp}. Also, there is a point where the
4287 % result is essentially black and a fill would be more efficient.
4288 % The value .88 is arrived at empirically and is a compromise so that
4289 % \MF{} and \MP{} produce similar levels of gray on both printers
4290 % available to me.
4291 % \begin{macrocode}
4292 setnumeric (gr) 1 - (.88*abs(shadewd)/sp)**2;
4293 if not cycle g: NoCycle("shade") g;
4294 elseif gr <= 0: safefill g;
4295 else:
4296 %<*MF>
4297 setbbox (ll, ur) g;
4298 ll := floorpair (ll);
4299 % \end{macrocode}
4300 %
4301 % What we do is draw a row of dots and stack the rows to fill a rectangle.
4302 % We call \gbc{fillwith} to draw these copies. We have to produce this
4303 % on a picture separate from \gbc{active_plane} so we can apply
4304 % \gbc{DoClip}. Adding one complex picture onto another means there is a
4305 % time at which the added picture and the result are in memory at the same
4306 % time. To save a little memory (at the cost of a little speed), we
4307 % divide the picture into two, each with half the complexity. We add the
4308 % one, then (I hope) recover the memory by equating it to \mfc{nullpicture}
4309 % before adding the second.
4310 %
4311 % Shifts of pictures need to be by integer number of pixels, but this is
4312 % ensured by \gbc{fillwith}, using \mfc{ceiling} to define \gbc{dv} is
4313 % more to ensure it is not rounded down to 0.
4314 % \begin{macrocode}
4315 % setpair (dv) ceiling (sp/(sqrt 2))*(1,1);
4316 % test hex spacing:
4317 setpair (dv) ( ceiling(.5sp), ceiling(.5sp*sqrt 3) );
4318 setpicture (sh) setdot (shadedotpath, abs(shadewd));
4319 newpicture (v);
4320 fillwith (v) (sh, 2dv, ll, ur);
4321 newpicture (w);
4322 addto w also v shifted goodpair (dv);
4323 DoClip (v); DoClip (w);
4324 clipto (v) (g); clipto (w) (g);
4325 _orto (active_plane, v);
4326 v := nullpicture;
4327 _orto (active_plane, w);
4328 %</MF>
4329 % \end{macrocode}
4330 % In \MP{} we just fill with gray. The gray level having been calculated
4331 % at the beginning.
4332 % \begin{macrocode}
4333 %<*MP>
4334 colorsafefill (gr*white) g;
4335 %</MP>
4336 fi
4337 f
4338 enddef;
4339
4340 % \end{macrocode}
4341 %
4342 % \DescribeRoutine{polkadot}
4343 % The macro \gbc{polkadot} is intended to fill a region with \emph{large}
4344 % dots. The diameter, \gbc{polkadotwd}, is initialized to \mfc{5bp}. The
4345 % code is similar to that of \gbc{shade}, but here we attempt a hexagonal
4346 % array: each dot surrounded by 6 equally spaced dots. Because of their
4347 % larger size and presumably larger spacing, we can be a little less
4348 % efficient and so we aim for improved visual appearance. We do what we
4349 % can to avoid unsightly slivers of partial dots, and only draw a dot if
4350 % its center lies in the bounding box.
4351 %
4352 % We also permit the circles to overlap, and only replace the code with a
4353 % fill if the dots overlap so much that no background can show (this assumes
4354 % that \gbc{polkadotpath} is a circle).
4355 %
4356 % If the space \gbc{sp} and \gbc{polkadotwd} are too small, there will
4357 % be a great many tiny dots. It is quite easy to overflow \MP{} capacity
4358 % and tiny paths don't rasterize at all well in \PS. In \MF, we already
4359 % have \gbc{shade} to place tiny dots. Therefore, we merely fill if
4360 % \gbc{sp} is less that a certain minimum, even if that minimum is greater
4361 % than \gbc{polkadotwd}.
4362 % \begin{macrocode}
4363 polkadotwd := 5bp;
4364 mindotspace := 1bp;
4365 path polkadotpath; polkadotpath := fullcircle;
4366
4367 vardef polkadot (expr sp) expr f =
4368 convertpath (g) f;
4369 if not cycle g: NoCycle("polkadot") g;
4370 elseif sp <= emax (2*polkadotwd/3, mindotspace):
4371 safefill g;
4372 else:
4373 setbbox (ll, ur) g;
4374 % \end{macrocode}
4375 % As with \gbc{shade}, we shift alternate rows by half the spacing between
4376 % dot centers. The vertical shift is slightly larger (relatively speaking)
4377 % and the horizontal smaller. We apply a further horizontal and vertical
4378 % shift to avoid small pieces of dots. What it does is take only those dots
4379 % whose centers lie in the bounding box, and center the whole array
4380 % relative to that box.
4381 % \begin{macrocode}
4382 save dx, dy, dshift; pair dshift;
4383 dx := sp/2; dy := dx*sqrt 3;
4384 dshift := (xpart(ur - ll) mod dx, ypart (ur - ll) mod dy)/2;
4385 % \end{macrocode}
4386 % Here, \gbc{p} is the center of the first dot in the lower left corner.
4387 % \begin{macrocode}
4388 save p, dims; pair p, dims;
4389 p := ll + dshift;
4390 dims := 2(dx, dy);
4391 % \end{macrocode}
4392 % The extra \MF{} code is to clear what's under the dots in case they
4393 % are gray dots. And then to `gray' the dots when \gbc{fillcolor} demands
4394 % it.
4395 % \begin{macrocode}
4396 setpicture (thepolkadot) setdot (polkadotpath, polkadotwd);
4397 newpicture (v);
4398 fillwith (v) (thepolkadot, dims, p, ur);
4399 fillwith (v) (thepolkadot, dims, p + (dx, dy), ur);
4400 DoClip (v); clipto (v) g;
4401 %<*MF>
4402 if isgray (fillcolor):
4403 _subto (active_plane) (v);
4404 v := nullpicture;
4405 thepolkadot :=
4406 shaded (fillcolor) polkadotpath scaled ceiling (polkadotwd);
4407 fillwith (v) (thepolkadot, dims, p, ur);
4408 fillwith (v) (thepolkadot, dims, p + (dx, dy), ur);
4409 DoClip (v); clipto (v) g;
4410 fi
4411 %</MF>
4412 coloraddon (fillcolor, v);
4413 fi
4414 f
4415 enddef;
4416
4417 % \end{macrocode}
4418 %
4419 %
4420 % \subsection{Hatching}\label{hatching}
4421 %
4422 % \DescribeRoutine{thatch}
4423 % \RoutineIndex{colorthatch}
4424 % This command hatches the interior of path \gbc{f} (graph coordinates)
4425 % with lines at angle \gbc{theta}, spaced \gbc{sp} apart (device
4426 % coordinates). As usual an unclosed path is simply drawn. The thickness
4427 % of the lines is determined by \gbc{hatchwd}. If \gbc{sp} is not greater
4428 % than \gbc{abs(hatchwd)}, we simply fill. This will ensure \gbc{thatchf}
4429 % is called only for positive \gbc{sp}.
4430 %
4431 % We find the bounding box of the backward rotated path, so when that box
4432 % is filled with lines and rotated, it will cover the path. After calling
4433 % \gbc{thatchf} we add the picture, clipped to the path.
4434 % \begin{macrocode}
4435 def thatch = colorthatch (hatchcolor) enddef;
4436 vardef colorthatch (expr clr) (expr sp, theta) expr f =
4437 convertpath (g) f;
4438 if not cycle g: NoCycle("hatch") g;
4439 elseif sp <= abs(hatchwd): colorsafefill (clr) g;
4440 else:
4441 newpicture (v);
4442 setbbox (ll, ur) g rotated -theta;
4443 thatchf (v, identity rotated theta, sp, ll, ur);
4444 DoClip (v); clipto (v) (g);
4445 coloraddon (clr, v);
4446 fi
4447 f
4448 enddef;
4449
4450 % \end{macrocode}
4451 %
4452 % We offer some special cases, calling \gbc{thatch} with different angles.
4453 % These take only the spacing (in device coordinates) and a path
4454 % expression (in graph coordinates) as parameters.\\
4455 % \DescribeRoutine{hhatch}
4456 % \gbc{hhatch} has angle 0 and so produces horizontal lines;\\
4457 % \DescribeRoutine{vhatch}
4458 % \gbc{vhatch} produces vertical lines;\\
4459 % \DescribeRoutine{lhatch}
4460 % \gbc{lhatch} produces lines tilted to the left (running from upper left
4461 % to lower right);\\
4462 % \DescribeRoutine{rhatch}
4463 % \gbc{rhatch} produces lines running from lower left to upper right;
4464 % and\\
4465 % \DescribeRoutine{xhatch}
4466 % \gbc{xhatch} produces cross-hatching, and essentially runs \gbc{lhatch}
4467 % and \gbc{rhatch}.
4468 %
4469 % Color is a parameter only for \gbc{colorxhatch}. The reason for that
4470 % is to make code written by \mfpic{} simpler. The \mfpic{} commands for
4471 % the others actual write calls to \gbc{thatch} or \gbc{colorthatch}.
4472 %
4473 % \begin{macrocode}
4474 def hhatch (expr sp) = thatch (sp, 0) enddef;
4475 def vhatch (expr sp) = thatch (sp, 90) enddef;
4476 def lhatch (expr sp) = thatch (sp, -45) enddef;
4477 def rhatch (expr sp) = thatch (sp, 45) enddef;
4478
4479 def xhatch = colorxhatch (hatchcolor) enddef;
4480 def colorxhatch (expr clr, sp) =
4481 colorthatch (clr) (sp, 45) colorthatch (clr) (sp, -45)
4482 enddef;
4483
4484 % \end{macrocode}
4485 %
4486 %
4487 % \subsection{Gradients}
4488 %
4489 % \DescribeRoutine{axialgradient}
4490 % We pass a \mfc{vardef}-ed function that is to provide the range of
4491 % colors. It can output colors of different types if desired. Two
4492 % natural methods are: (1)~interpolate between colors of the same type:\\
4493 % \indent\mfc{vardef clrgrad (expr t) = (t)[red,blue] enddef}\\
4494 % and (2)~extract colors from a previously built array of colors:\\
4495 % \indent\mfc{vardef clrgrad (expr t)= A[round(t*N)]}\\
4496 % where, \mfc{A0}, \mfc{A1},\dots \mfc{A[N]} are colors (necessarily of
4497 % the same type).
4498 %
4499 % Since we simply fill strips with a single color, \gbc{sp} is the
4500 % thickness of the strip (in device units) and \gbc{theta} is the angle
4501 % by which these strips differ from being horizontal.
4502 % \begin{macrocode}
4503 vardef axialgradient (suffix clr) (expr sp, theta) expr f =
4504 convertpath (g) f;
4505 if not cycle g: NoCycle("axialgradient") g;
4506 else:
4507 newpicture (_grd);
4508 setbbox (ll, ur) g rotated -theta;
4509 axialgradientf (clr, _grd) (theta, sp, ll, ur);
4510 DoClip (_grd); clipto (_grd) (g);
4511 %<MF> safeunfill g;
4512 _orto (active_plane, _grd);
4513 fi
4514 f
4515 enddef;
4516
4517 % \end{macrocode}
4518 %
4519 % \DescribeRoutine{areagradient}
4520 % This fills a cyclic path with colored pixels, with the color
4521 % determined by the \mfc{vardef}-ed function \gbc{clr} which takes two
4522 % parameters. The size of the pixels is given in the last two parameters
4523 % \gbc{sp} and \gbc{tp} which are specified in device units.
4524 % \begin{macrocode}
4525 vardef areagradient (suffix clr) (expr sp, tp) expr f =
4526 convertpath (g) f;
4527 if not cycle g: NoCycle("areagradient") g;
4528 else:
4529 newpicture (_agr);
4530 setbbox (ll, ur) g;
4531 areagradientf (clr, _agr) (sp, tp, ll, ur);
4532 DoClip (_agr); clipto (_agr) (g);
4533 %<MF> safeunfill g;
4534 _orto (active_plane, _agr);
4535 fi
4536 f
4537 enddef;
4538
4539 % \end{macrocode}
4540 %
4541 % \DescribeRoutine{radialgradient}\label{getrad}
4542 % This fills a cyclic path with colored circular strips, with the color
4543 % determined by the \mfc{vardef}-ed function \gbc{clr} which takes one
4544 % parameters. The thickness of the strips is given in the last parameter
4545 % \gbc{sp} which are specified in device units. The command
4546 % \gbc{getradius} finds the distance from the center to the farthest point
4547 % of \gbc{f}. It was added (see section~\ref{bboxes}) solely for this use.
4548 % \begin{macrocode}
4549 vardef radialgradient (suffix clr) (expr sp, ctr) expr f =
4550 convertpath (g) f;
4551 if not cycle g: NoCycle("radialgradient") g;
4552 else:
4553 setpair (_ctr) zconv (ctr);
4554 newpicture (_agr);
4555 save _rad;
4556 getradius (_rad) g shifted - _ctr;
4557 radialgradientf (clr, _agr) (sp, _ctr, _rad);
4558 DoClip (_agr); clipto (_agr) (g);
4559 %<MF> safeunfill g;
4560 _orto (active_plane, _agr);
4561 fi
4562 f
4563 enddef;
4564
4565 % \end{macrocode}
4566 %
4567 %
4568 % \subsection{Tesselations}\label{tess}
4569 %
4570 % \DescribeRoutine{tess}
4571 % Tesselation of the interior of a closed path means filling with copies
4572 % of a \emph{tile} (see subsection~\ref{tiles}). The path is in graph
4573 % units, the tile is a suffix parameter and is the name of a previously
4574 % defined tile. In fact, one can create the picture any way one likes (it
4575 % doesn't have to be with the \gbc{tile} environment). Thus \gbc{tess
4576 % (fred) f;} will work as long as \gbc{fred.pic} is a picture and
4577 % \gbc{fred.dims} is a pair giving its dimensions.
4578 % \begin{macrocode}
4579 vardef NoTile (suffix atile) expr g =
4580 GBwarn str atile & " is not a valid tile for tess()."
4581 & " The path will be drawn instead.";
4582 safedraw g;
4583 enddef;
4584 vardef tess (suffix atile) expr c =
4585 convertpath (_g) c;
4586 if not cycle _g: NoCycle("tess") _g;
4587 elseif not is_tile (atile): NoTile (atile) _g;
4588 else:
4589 setbbox (_ll, _ur) _g;
4590 newpicture (_ts);
4591 fillwith (_ts) (atile.pic, atile.dims, _ll, _ur);
4592 DoClip (_ts); clipto (_ts) _g;
4593 _orto (active_plane, _ts);
4594 fi
4595 c
4596 enddef;
4597
4598 % \end{macrocode}
4599 %
4600 %
4601 % \subsection{Dots and dashes}\label{dashes}
4602 %
4603 % \MP{} already has commands for drawing a dashed or dotted curve,
4604 % but \MF{} does not. Considerable effort went into making this possible
4605 % (before \MP{} even existed). The code is now reasonably fast and the
4606 % result is actually better quality than \MP{}'s native commands so we use
4607 % the same code in both versions. It does, however, use pretty much
4608 % memory in \MP{}.
4609 %
4610 % The \grafbase{} dashing code is designed to produce a whole number of
4611 % dashes on any curve to which it is applied, and (usually) to begin and
4612 % end with half a dash (so that when dashed curves abut, the result looks
4613 % decent). \MP{}'s own facilities do neither of these. In addition, the
4614 % dotting code is flexible enough that copies of any picture (not just a
4615 % circular dot) can be used to trace a path.
4616 %
4617 % The general command is \gbc{gendashed}, which takes a suffix parameter
4618 % (the name of a \emph{dashing pattern}, see below) and a path expression
4619 % in graph coordinates.
4620 %
4621 % A dashing pattern \gbc{pat} consists of three arrays, \gbc{pat.start},
4622 % which is used to draw the beginning of the path (half a dash in the
4623 % default \gbc{dashed} command), \gbc{pat.finish}, which is used to draw
4624 % the other end, and \gbc{pat.rep}, which is the repeating pattern for
4625 % drawing the rest of the curve. Each of these is an \emph{array} of
4626 % numerics. These should be lengths, in device units, and represent the
4627 % lengths of dashes and spaces.
4628 %
4629 % We start with some variables and their defaults, some of which are no
4630 % longer used. \gbc{segment_split} is used in the code for finding the
4631 % approximate length of a curve. This is needed to make adjustments in the
4632 % length of dashes and spaces so that a whole number of repeated patterns
4633 % are used. \gbc{dashsize} and \gbc{dashgap} are no longer used.
4634 % Originally they gave the lengths of default dashes and the spaces in
4635 % between. \gbc{dash_start} and \gbc{dash_finish} are the fractions of a
4636 % dash length that are used at the start and finish if the command
4637 % \gbc{dashpat} is used to create the dashing pattern.
4638 %
4639 % And \gbc{_rescale_factor} is used to adjust numbers downward and avoid
4640 % arithmetic overflow. For a 1200dpi \MF{} mode, a curve 4 inches long
4641 % will be over \mfc{infinity} pixels in length, but only 40 deci-inches.
4642 % Our default for this variable is just that: 1/10 inch.
4643 % \begin{macrocode}
4644 if unknown segment_split: segment_split := 8; fi
4645 if unknown dashsize: dashsize := 3bp; fi
4646 if unknown dashgap: dashgap := dashsize + 2penwd; fi
4647 if unknown dash_finish: dash_finish := .5; fi
4648 if unknown dash_start: dash_start := .5; fi
4649 if unknown _rescale_factor: _rescale_factor := 0.1in; fi
4650
4651 % \end{macrocode}
4652 %
4653 % \DescribeRoutine{gendashed}
4654 % The main idea is to have a list of lengths represent the repeating
4655 % pattern of dashes and dots. These lengths represent a dash length,
4656 % followed by a gap length, etc., so there are an even number. To start
4657 % dashing a path, we normally take a fraction (\gbc{dash_start}) of the
4658 % first dash, then the rest of the pattern. We continue by repeating the
4659 % pattern as many times as will fit, then we finish off with a fraction
4660 % (\gbc{dash_finish}) of the first dash. A dash of length 0 is a dot. A
4661 % gap of length 0 is OK, but useless unless it's between a dot and a dash,
4662 % and you arrange for the dot's size to be different from \gbc{penwd}.
4663 %
4664 % We generalize this so that \gbc{pat.start} and \gbc{pat.finish} can be
4665 % any patterns, not necessarily related to \gbc{pat.rep}. Also `dots' can be
4666 % symbols like \gbc{Triangle}.
4667 %
4668 % When we tried to deal with arrays of dashing patterns, it became
4669 % rather a pain to deal with three arrays of arrays. So now we allow the
4670 % suffix \gbc{pat} to be a single array and call \gbc{mkdasharrays} to
4671 % produce \gbc{pat.start} and \gbc{pat.finish}. It returns \gbc{true} if
4672 % all three arrays are successfully produced.
4673 %
4674 % The variable \VariableIndex{last_dot_size} \gbc{last_dot_size} is
4675 % intended to allow the clearing path of arrowhead commands to encompass
4676 % a final dot larger than \gbc{penwd}.
4677 % \begin{macrocode}
4678 numeric last_dot_size; last_dot_size := 0;
4679 vardef gendashed (suffix pat) expr f =
4680 convertpath (_g) f;
4681 save _dpat;
4682 if not mkdasharrays (pat) (_dpat):
4683 GBwarn "Dash pattern " & str pat
4684 & " undefined. Path will be drawn instead.";
4685 safedraw _g;
4686 elseif _dpat.rep < 2:
4687 safedraw _g;
4688 else:
4689 % \end{macrocode}
4690 %
4691 % After the following loop, \gbc{_dl.s} is the total length of the
4692 % corresponding \gbc{pat.s} in multiples of \gbc{_rescale_factor}, and
4693 % \gbc{_dpat.s[i]} has been converted to these units.
4694 % \begin{macrocode}
4695 save _dl;
4696 forsuffixes _s = start, rep, finish:
4697 _dl._s := 0;
4698 for i = 1 upto _dpat._s:
4699 _dpat._s[i] := _dpat._s[i]/_rescale_factor;
4700 _dl._s := _dl._s + _dpat._s[i];
4701 endfor
4702 endfor
4703
4704 if _dl.rep = 0:
4705 GBwarn "Dash pattern " & str pat & " has length 0. "
4706 & "Path will be drawn instead.";
4707 safedraw _g;
4708 else:
4709 % \end{macrocode}
4710 % Here \gbc{_g} is our path in device units, but \gbc{setuplengtharray}
4711 % computes lengths in multiples of \gbc{_rescale_factor} to avoid having
4712 % paths of length \gbc{infinity}.
4713 %
4714 % This is how we process a path mathematically: let $f(t)$, $0 \le t \le
4715 % k$ be the formula for the path \gbc{f}, $k$ being the number of segments
4716 % of \gbc{f}, we consider the polygon connecting the points $f(0), f(1/s),
4717 % f(2/s),\ldots,f(k)$ (where $s$ is \gbc{segment_split}) and compute the
4718 % length of \emph{that} path. Actually, we compute and save the cumulative
4719 % lengths at each vertex of this polygon, since we use that later to
4720 % determine `when' (i.e., at what values of $t$) to place a dot or draw
4721 % a dash. The command \gbc{setuplengtharray} does this, storing the
4722 % cumulative lengths in the array \gbc{_cumlen} and the total in
4723 % \gbc{_totlen}. It also initializes \gbc{_ct} the index into that array.
4724 % \begin{macrocode}
4725 setuplengtharray (_cumlen, _totlen, _ct) _g;
4726 % \end{macrocode}
4727 % Now we adjust the dashes so that a whole number of patterns make up
4728 % the lengths of the approximating polygon. \gbc{scale_adjust} returns
4729 % the scaling factor, equates \gbc{_n} to the total number of
4730 % \gbc{pat.rep} to use. If the path length is too small compared to the
4731 % length of the start and finish patterns, this is equated to $-1$ as a
4732 % flag to draw the path instead. (recall \gbc{_dl.s} holds the length of
4733 % part \gbc{s}).
4734 %
4735 % After this we rescale the dashes and spaces stored in \gbc{_dpat}, and
4736 % the length of the patterns in \gbc{_dl}.
4737 % \begin{macrocode}
4738 save _n, _sf, _no_dots;
4739 boolean _no_dots; _no_dots := true;
4740 _sf := scale_adjust (_n, _dl) (_totlen);
4741 if _n < 0: safedraw _g;
4742 else:
4743 forsuffixes _s = start, rep, finish:
4744 for _i = 1 upto _dpat._s:
4745 if (_dpat._s[_i] = 0) and _no_dots: _no_dots := false;
4746 else: _dpat._s[_i] := _dpat._s[_i]*_sf;
4747 fi
4748 endfor
4749 _dl._s := _dl._s*_sf;
4750 endfor
4751 % \end{macrocode}
4752 % The user has the capability to use something other than a small disk for
4753 % a dot by defining \gbc{plot_pic} (and preferably also storing its
4754 % diameter in \gbc{plot_pic.size}). The utility \gbc{makesymbol} is
4755 % defined later. It examines \gbc{plot_pic} and makes a picture depending
4756 % on what type of variable it is. The default \gbc{dotpath} is
4757 % \mfc{fullcircle}, but user may also change that to get different dots.
4758 % \gbc{makesymbol} scales by \gbc{penwd} \emph{only if the first
4759 % parameter is a path}. This is how to increase the dot size (the code in
4760 % \gbc{plot} uses this.)
4761 % \begin{macrocode}
4762 if _no_dots:
4763 else:
4764 if unknown plot_pic:
4765 save plot_pic; path plot_pic;
4766 plot_pic := dotpath;
4767 fi;
4768 last_dot_size :=
4769 if known plot_pic.size: plot_pic.size else: penwd fi;
4770 setpicture (dashingdot) makesymbol (plot_pic, last_dot_size);
4771 fi
4772 % \end{macrocode}
4773 % The macro \gbc{dashit} draws the dashes, computing where they go and
4774 % drawing the appropriate subpaths of \gbc{_g} or placing a dot at the
4775 % appropriate point. \gbc{dashit} returns nothing and assumes all the
4776 % information accumulated so far, so it can only be called by
4777 % \gbc{gendashed}.
4778 %
4779 % \gbc{_t} and \gbc{_d} are temporary variables used by
4780 % \gbc{dashit}, but we declare them here since we initialize them
4781 % differently for each call. \gbc{_d0} and \gbc{_d1} hold the
4782 % position along the curve of the ends of a dash in distance from the
4783 % start; \gbc{_t0} and \gbc{_t1} are the same, but in terms of time.
4784 % A macro \gbc{gettime} converts the first to the second. It uses the
4785 % cumulative length array \gbc{_cumlen} for this, and maintains
4786 % \gbc{_ct} as the current index into that array.
4787 % \begin{macrocode}
4788 save _t, _d, _v;
4789 picture _v; _v := nullpicture;
4790 _d0 := 0; _t0 := 0;
4791 dashit (_dpat.start) (_v);
4792 % \end{macrocode}
4793 % The parameters to \gbc{dashit} are the name of the part of the dashing
4794 % pattern that is being drawn, and a temporary picture variable. The
4795 % latter holds the picture until \gbc{DoClip} can process it.
4796 % The code of \gbc{dashit} leaves \gbc{_d0} pointing to the current
4797 % position on the curve, but for safety and to reduce accumulated
4798 % round-off error, we initialize it to what it should be before each call.
4799 %
4800 % The repeating pattern has the tendency to use lots of memory. Previously
4801 % I added all the dashes to \gbc{_v} and then added it all at once to
4802 % \gbc{active_plane}. The purpose was to be able to \gbc{DoClip} it once,
4803 % and add it once with \gbc{coloraddon} to get it drawn in color under \MF.
4804 % This was simplest, but a memory hog requiring $O(n)$ in memory, where
4805 % $n$ is the number of repeated patterns. Then we tried clipping and adding
4806 % within \gbc{dashit}. This was terribly slow, requiring $O(n)$ in time.
4807 % Now we use a standard programming trick: accumulate $m < n$ repetitions
4808 % before adding them, the memory should be $O(m)$ and the time $O(n/m)$.
4809 % Making $m$ about $\sqrt n$ seems to work well.
4810 % \begin{macrocode}
4811 if _n > 0:
4812 save _m; _m := ceiling sqrt(_n);
4813 for _j = 0 step _m until _n - 1:
4814 for _i = 0 upto _m - 1:
4815 exitif (_i + _j) > _n - 1;
4816 _d0 := _dl.start + (_j + _i)*_dl.rep;
4817 _t0 := gettime (_cumlen, _ct) (_d0);
4818 dashit (_dpat.rep) (_v);
4819 endfor
4820 DoClip (_v);
4821 coloraddon (drawcolor, _v);
4822 _v := nullpicture;
4823 endfor
4824 fi
4825
4826 _d0 := _totlen - _dl.finish;
4827 _t0 := gettime (_cumlen, _ct) (_d0);
4828 dashit (_dpat.finish) (_v);
4829 DoClip (_v);
4830 coloraddon (drawcolor, _v);
4831 fi
4832 fi
4833 fi
4834 f
4835 enddef;
4836
4837 % \end{macrocode}
4838 %
4839 % \DescribeRoutine{makelengtharray}
4840 % This takes an array name and a path expression (which is assumed to be
4841 % in device coordinates), computes the array of partial lengths (of the
4842 % polygon approximation), and returns the total length. To avoid numeric
4843 % overflow we rescale the lengths and so the array elements are in units
4844 % of \gbc{_rescale_factor}. At one point we used to rescale the path,
4845 % but that turned out to be unnecessary and made it harder to accomplish
4846 % several of the things we now do with this. We also save a little
4847 % memory by making the path a suffix parameter, which avoids the memory
4848 % used for the `capsule' of an expression parameter. So far all uses apply
4849 % it to a path variable and we have to remember to keep it that way.
4850 % \begin{macrocode}
4851 vardef makelengtharray (suffix clen) suffix p =
4852 setsplit (_s) segment_split;
4853 numeric clen[];
4854 clen := _s * length p; clen0 := 0;
4855 for _i = 1 upto clen:
4856 clen[_i] := clen[_i-1] + abs (pnt[_i/_s] (p) - pnt[(_i-1)/_s] (p))
4857 / _rescale_factor;
4858 endfor
4859 clen[clen]
4860 enddef;
4861
4862 % \end{macrocode}
4863 %
4864 % \DescribeRoutine{scale_adjust}
4865 % Here \gbc{n} is a suffix defined by the calling routine,
4866 % \gbc{pl.\{start\|rep\|finish\}} are the lengths of corresponding parts
4867 % of a dashing pattern, \gbc{lngth} is the length of some path (determined
4868 % by the calling routine). It determines how many times \gbc{pl.rep} goes
4869 % into \gbc{lngth - pl.start - pl.finish}. If this is negative it remains
4870 % negative, otherwise it is rounded. \gbc{scale_adjust} then determines
4871 % and returns the scaling factor \gbc{sf} required to make
4872 % \gbc{sf*(pl.start + n*pl.rep + pl.finish)} equal to \gbc{lngth}.
4873 % \begin{macrocode}
4874 vardef scale_adjust (suffix n, pl) (expr lngth) =
4875 n := (lngth - pl.start - pl.finish)/pl.rep;
4876 n := if n < 0: -1 else: round(n) fi;
4877 lngth/(pl.start + emax (n, 0)*pl.rep + pl.finish)
4878 enddef;
4879
4880 % \end{macrocode}
4881 %
4882 % \DescribeRoutine{gettime}
4883 % \gbc{arr} is an increasing array of lengths, defined by the calling
4884 % routine. \gbc{ct} is current index into that array; it will vary with
4885 % subsequent calls. Calling routine initializes it before the first call,
4886 % \gbc{gettime} updates it. \gbc{lngth} is a length interpreted as the
4887 % length along the path associated to the array.
4888 %
4889 % Since this array is generated by splitting the segments of the path at
4890 % times \gbc{i/segment_split} we first determine in which of these splits
4891 % the given distance is (i.e., find \gbc{ct} so that \gbc{lngth} lies
4892 % between \gbc{arr[ct-1]} and \gbc{arr[ct]}). To avoid problems with
4893 % round-off error, bad length parameter, etc., we force \gbc{lngth} to
4894 % satisfy this for some index between the current value of \gbc{ct} and
4895 % \gbc{arr} inclusive.
4896 %
4897 % Once we know what segment we are in, we determine the time by linear
4898 % interpolation between the times corresponding to \gbc{ct} and
4899 % \gbc{ct+1}. Note: in the \mfc{forever} loop, the exit must come before
4900 % the increment. The function \gbc{inrange} is defined in
4901 % section~\ref{axes}. It checks if the third argument is between the
4902 % first two, or equal to one of them.
4903 % \begin{macrocode}
4904 vardef gettime (suffix arr, ct) (expr lngth) =
4905 setnumeric (_gtl) emax (arr[ct], emin (arr[arr], lngth));
4906 setsplit (_s) segment_split;
4907 forever: exitif inrange (arr[ct], arr[ct+1]) (_gtl);
4908 next ct;
4909 endfor
4910 if arr[ct] = arr[ct+1]: ct
4911 else: ( ct + (_gtl - arr[ct]) / (arr[ct+1] - arr[ct]) )
4912 fi /_s
4913 enddef;
4914
4915 def next suffix X = X := X + 1; enddef;
4916
4917 % \end{macrocode}
4918 %
4919 % \DescribeRoutine{dashit}
4920 % No variables are saved or initialized; \gbc{gendashed} defines array
4921 % \gbc{_cumlen}, path \gbc{_g}, and initializes \gbc{_d0},
4922 % \gbc{_t0} and \gbc{_ct}.
4923 %
4924 % \gbc{pos} is one of the dashpattern arrays, so it consists of numerics
4925 % interpreted as lengths of dashes (odd index) and spaces (even index). In
4926 % the first case \gbc{_d0} and \gbc{_t0} will already be pointing to
4927 % the beginning of the dash and we get to the end of the dash by adding
4928 % the length of a dash (\gbc{pos[_j]}) to \gbc{_d0} (getting
4929 % \gbc{_d1}) and calling \gbc{gettime} (getting \gbc{_t1}). We draw
4930 % the subpath between those points. Unless \gbc{pos[_j] = 0}, in which case
4931 % a dot is placed.
4932 %
4933 % For even \gbc{j} (a space) we are at \gbc{_d1} and \gbc{_t1} and
4934 % we increment them to get \gbc{_d0} and \gbc{_t0} for the next
4935 % iteration.
4936 % \begin{macrocode}
4937 def dashit (suffix pos) (suffix pic) =
4938 for _k = 1 upto pos:
4939 if odd _k:
4940 if pos[_k] = 0:
4941 _d1 := _d0; _t1 := _t0;
4942 picdot (pic, dashingdot, pnt [_t0] (_g));
4943 else:
4944 _d1 := _d0 + pos[_k];
4945 _t1 := gettime (_cumlen, _ct) (_d1);
4946 shpath (pic, drawpen) (subpath (_t0, _t1) of _g);
4947 fi
4948 else:
4949 _d0 := _d1 + pos[_k];
4950 _t0 := gettime (_cumlen, _ct) (_d0);
4951 fi
4952 endfor
4953 enddef;
4954
4955 % \end{macrocode}
4956 %
4957 % \DescribeRoutine{dashpat}
4958 % This is a utility to convert a list of lengths to an array. It is almost
4959 % the same as \gbc{list}, but it does make sure the array functions as
4960 % a dashing pattern. It needs to consist of either $1$ item (the signal to
4961 % draw a solid line) or an even number of items. So we add a zero length
4962 % term if the size is $0$ or odd and bigger than $1$.
4963 %
4964 % \DescribeRoutine{mkdasharrays}
4965 % The dashing code in \gbc{gendashed} is written so the the beginning and
4966 % ending patterns can be different from the repeating patterns. If so,
4967 % they must be named \gbc{pat.start}, \gbc{pat.rep} and \gbc{pat.finish}.
4968 % If one of these three is not a known array but \gbc{pat} is, this macro
4969 % creates the array in a generic way. When created this way, \gbc{pat.rep}
4970 % is a copy of \gbc{pat}. So is \gbc{pat.start}, except only a fraction of
4971 % the first dash is used, while \gbc{pat.finish} is just the first dash of
4972 % \gbc{pat} reduced by the factor \gbc{dash_finish}.
4973 % \begin{macrocode}
4974 def dashpat (suffix pat) (text t) =
4975 list (pat) (t);
4976 if (pat = 0) or (odd (pat) and (pat > 1)):
4977 pat[incr pat] := 0;
4978 fi
4979 enddef;
4980
4981 vardef mkdasharrays (suffix src, dest) =
4982 save _bad; boolean _bad; _bad := false;
4983 forsuffixes _s = start, rep, finish:
4984 numeric dest._s, dest._s[];
4985 boolean _bad._s;
4986 if knownnumericarray src._s:
4987 copyarray (src._s) (dest._s);
4988 _bad._s := false;
4989 else:
4990 _bad := _bad._s := true;
4991 fi
4992 endfor
4993 % _bad = one of the three arrays not copied.
4994 if _bad:
4995 if knownnumericarray src: _bad := false;
4996 if _bad.rep: % make dest.rep = src
4997 copyarray (src) (dest.rep);
4998 fi
4999 if _bad.start: % shrink first dash to get dest.start
5000 copyarray (src) (dest.start);
5001 dest.start1 := dash_start*src1;
5002 fi
5003 if _bad.finish: % use partial first dash for dest.finish
5004 dest.finish := 1;
5005 dest.finish1 := dash_finish*src1;
5006 fi
5007 fi
5008 fi
5009 not _bad
5010 enddef;
5011
5012 % \end{macrocode}
5013 %
5014 % The \mfpic{} command \cs{dashed} is now implemented by making a
5015 % dashpattern from the two arguments and calling gendashed. That is the
5016 % definition of \gbc{DASHED}.
5017 %
5018 % \gbc{dashed} takes parameters which are the length and the space (device
5019 % coordinates) and a path (graph coordinates). It returns the path.
5020 % \begin{macrocode}
5021 vardef Dashed (expr dlen, dgap) expr f =
5022 save dashes; dashpat (dashes) (dlen, dgap);
5023 gendashed (dashes) f
5024 enddef;
5025
5026 def DASHED = Dashed enddef;
5027 %<MF> def dashed = Dashed enddef;
5028
5029 % \end{macrocode}
5030 %
5031 % \DescribeRoutine{doplot}
5032 % \gbc{doplot} places symbols at positions along a path determined by
5033 % \gbc{dgap} (space between symbols), they are scaled by \gbc{sc} and the
5034 % actual symbol is \gbc{spath}. Currently this may be one of three things:
5035 % \begin{enumerate}
5036 % \item A path, giving the shape of the dot, which should be defined in
5037 % units so that the desired size is obtained under scaling by
5038 % \gbc{sc}. Normally this means one unit across.
5039 % \item A picture. This is used unscaled, it being presumed that it has
5040 % been prepared by a user to the correct size.
5041 % \item (\MP{} only) a string.
5042 % \end{enumerate}
5043 % All these are converted to a picture by the \gbc{makesymbol} command and
5044 % it is assigned to \gbc{plot_pic}, which \gbc{gendashed} has been
5045 % trained to use when dots are needed.
5046 %
5047 % After this \gbc{gendashed} is called with a pattern where the dashes are
5048 % 0 length, the signal that dots are to be used.
5049 % \DescribeRoutine{dotted}
5050 % The macro \gbc{dotted} is implemented by calling \gbc{doplot} with
5051 % \gbc{dotpath} as the the symbol.
5052 % \begin{macrocode}
5053 vardef doplot (expr spath, sc, dgap) expr f =
5054 save dots; dashpat (dots) (0, dgap);
5055 setpicture (plot_pic) makesymbol (spath, sc);
5056 plot_pic.size := sc;
5057 gendashed (dots) f
5058 enddef;
5059
5060 path dotpath; dotpath := fullcircle;
5061 def dotted = doplot (dotpath) enddef;
5062
5063 % \end{macrocode}
5064 %
5065 % \DescribeRoutine{plotnodes}
5066 % These are useful little utilities to draw the points on top of the
5067 % curve through them. \gbc{plotnodes} differs from \gbc{plotsymbol}
5068 % (defined later) in that it takes a path parameter (rather than a list of
5069 % points) and returns that path (so it works with \mfpic{} as a prefix
5070 % macro). It also uses \gbc{drawcolor}. Otherwise it calls the same code.
5071 %
5072 % \DescribeRoutine{showcontrols}
5073 % \gbc{showcontrols} was mainly for debugging; it draws a line segment
5074 % connecting the control points of each node. It optionally draws a symbol
5075 % at each control point. We use \mfc{0} for a `symbol' to indicate we
5076 % don't wish to draw a symbol there. The default color for both the
5077 % symbols and the segment is \gbc{pointcolor}.
5078 % \begin{macrocode}
5079 vardef plotnodes (expr symbol, size) expr f =
5080 if size > 0:
5081 save pln; pair pln[];
5082 pln := 0;
5083 for _a = 0 upto (length f) if cycle f: - 1 fi:
5084 pln[incr pln] := pnt[_a] (f);
5085 endfor
5086 dosymbols (drawcolor, symbol, size) (pln);
5087 fi
5088 f
5089 enddef;
5090
5091 def showcontrols = colorshowcontrols (pointcolor) enddef;
5092 vardef colorshowcontrols (expr clr, syma, symb, size) expr f =
5093 save shpre, shpost;
5094 pair shpre[], shpost[];
5095 shpre := 0; shpost := 0;
5096 for a = 0 upto (length f) if cycle f: - 1 fi:
5097 shpre [incr shpre] := pre [a] (f);
5098 shpost[incr shpost] := post[a] (f);
5099 colorsafedraw (clr)
5100 (zconv (shpre[shpre]--pnt[a](f)--shpost[shpost]));
5101 endfor
5102 if size > 0:
5103 if not numeric syma: dosymbols (clr, syma, size) (shpre) ; fi
5104 if not numeric symb: dosymbols (clr, symb, size) (shpost); fi
5105 fi
5106 f
5107 enddef;
5108
5109 % \end{macrocode}
5110 %
5111 %
5112 % \subsection{Double-line drawing}\label{doubleline}
5113 %
5114 % \DescribeRoutine{doubledraw}
5115 % This invokes \gbc{parapath}, which has issues with smooth but wiggly
5116 % paths. An easier approach would be to draw a wide line and erase a
5117 % narrow one in the middle. However, that would not be transparent in
5118 % \MP{}.
5119 % \begin{macrocode}
5120 def doubledraw = colordoubledraw (drawcolor) enddef;
5121 vardef colordoubledraw (expr clr, sep) expr f =
5122 convertpath (g) f;
5123 colorsafedraw (clr) (parapath ( sep/2) g);
5124 colorsafedraw (clr) (parapath (-sep/2) g);
5125 f
5126 enddef;
5127
5128 % \end{macrocode}
5129 %
5130 %
5131 %
5132 % \section{Points Symbols and Other Pictures}\label{symbols}
5133 %
5134 % \DescribeRoutine{centerit}
5135 % This accepts a picture and returns the same picture centered. This
5136 % is close to impossible in \MF, so we only do it in \MP. Actually, we
5137 % no longer use it, because in the one case where we did
5138 % (\gbc{makesymbol}), it seemed to restrict the user's choices too much.
5139 % \begin{macrocode}
5140 %<*MP>
5141 vardef centerit (expr pic) =
5142 pic shifted -(0.5[urcorner pic, llcorner pic])
5143 enddef;
5144
5145 %</MP>
5146 % \end{macrocode}
5147 %
5148 % \DescribeRoutine{makesymbol}
5149 % This utility takes \emph{any} expression and scale and returns a picture.
5150 % If the expression \gbc{spath} is a cycle it returns the interior, for
5151 % other paths, a drawing of the path, in either case scaled by \gbc{sc}.
5152 % If already a picture, it returns it. In \MP, if it is a string, it
5153 % returns a picture containing that string drawn in the \mfc{defaultfont}.
5154 % In any other case, the default dot is returned.
5155 % \begin{macrocode}
5156 vardef makesymbol (expr spath, sc) =
5157 if picture spath :
5158 %<MF> setpicture (v) spath; mono (v); v
5159 %<MP> spath
5160 elseif path spath: setdot (spath, sc)
5161 %<MP> elseif string spath:
5162 %<MP> spath infont defaultfont scaled defaultscale
5163 else:
5164 GBwarn "Undefined symbol for plotting, "
5165 & "dotpath will be used instead.";
5166 setdot (dotpath, sc)
5167 fi
5168 enddef;
5169
5170 % \end{macrocode}
5171 %
5172 % Points are filled or unfilled circles. They are implemented with
5173 % \gbc{plotsymbol}, but the code differs in that filled or unfilled
5174 % circles are determined by a parameter rather than the type of curve.
5175 % In addition, for unfilled circles, it clears the pixels inside the circle.
5176 %
5177 % \DescribeRoutine{bpoint}
5178 % \gbc{bpoint} is basicly a shorthand for a scaled circle shifted to a
5179 % point. The scale and the point are in device coordinates. We don't use
5180 % it anywhere in \grafbase{} anymore.
5181 % \begin{macrocode}
5182 vardef bpoint (expr ptwd, b) =
5183 fullcircle scaled ptwd shifted b
5184 enddef;
5185
5186 % \end{macrocode}
5187 %
5188 % \DescribeRoutine{pointd}
5189 % This draws disks with diameter \gbc{ptwd}, filled or unfilled based on
5190 % the boolean \gbc{filled}, at the graph coordinate coordinates in the
5191 % list \gbc{t}. In case \gbc{filled} is true, \gbc{pointd} calls
5192 % \gbc{plotsymbol (SolidCircle)} otherwise we make \gbc{clearsymbols} true
5193 % (so that the area where each point is drawn will be cleared before
5194 % drawing it) and call \gbc{plotsymbol (Circle)}.
5195 % \begin{macrocode}
5196 def pointd (expr ptwd, filled) (text t) =
5197 if filled:
5198 plotsymbol (SolidCircle, ptwd) (t);
5199 else:
5200 begingroup;
5201 setboolean (clearsymbols) true;
5202 plotsymbol (Circle, ptwd) (t);
5203 endgroup
5204 fi
5205 enddef;
5206
5207 % \end{macrocode}
5208 %
5209 % \DescribeRoutine{plotsymbol}
5210 % \RoutineIndex{colorplotsymbol}
5211 % The \gbc{plotsymbol} command places a symbol centered at each of the
5212 % graph coordinate points in the list. The symbol placed is the first
5213 % parameter, which would normally be a path, but can be a picture or, in
5214 % \MP, a string. Like the \gbc{doplot} command, it calls \gbc{makesymbol}.
5215 % If \gbc{spath} is of type path, and is cyclic, it is drawn filled. This
5216 % is because we call \gbc{makesymbol} on it, and that subjects it to
5217 % \gbc{setdot}, which has that behavior. For other types of symbols, we
5218 % simply convert them to pictures with \gbc{makesymbol} and then place
5219 % them. Unlike \gbc{pointd} above, the interior of the path is not erased
5220 % by default. However, in the special case where the symbol is an open
5221 % path, if its first point is equal to its last point, and
5222 % \gbc{clearsymbols} is true, then the interior of the path obtained by
5223 % \gbc{\& cycle} is cleared before the path itself is drawn. We copy the
5224 % text list to an array and call \gbc{dosymbols} so that \gbc{plotnodes},
5225 % \gbc{plotsymbol} and \gbc{showcontrols} can share the code.
5226 %
5227 % \DescribeRoutine{dosymbols}
5228 % Since \gbc{dosymbols} uses identical code twice (once to clear, once to
5229 % draw), we put that code in \gbc{addsymbols}.
5230 % \DescribeRoutine{addsymbols}
5231 % And finally, \gbc{addsymbols} draws copies of a symbol at a given array
5232 % of points with a given color.
5233 % \begin{macrocode}
5234 boolean clearsymbols; clearsymbols := false;
5235 vardef clearable (expr pth) =
5236 if path pth:
5237 ( pnt0 (pth) = pnt[length pth] (pth) ) and (not cycle pth)
5238 and (length pth > 0)
5239 else: false
5240 fi
5241 enddef;
5242
5243 def clearopenpath expr f =
5244 if clearable (f): safeunfill f & cycle; fi
5245 enddef;
5246
5247 def plotsymbol = colorplotsymbol (pointcolor) enddef;
5248 def colorplotsymbol (expr clr, spath, sc) (text t) =
5249 if sc > 0:
5250 begingroup
5251 setpairs (_cpls) (t);
5252 if _cpls > 0: dosymbols (clr, spath, sc) (_cpls); fi
5253 endgroup
5254 fi
5255 enddef;
5256
5257 def dosymbols (expr clr, spath, sc) (suffix arr) =
5258 if clearsymbols and clearable (spath):
5259 addsymbols (background, makesymbol (spath&cycle, sc)) (arr);
5260 fi
5261 addsymbols (clr, makesymbol (spath, sc)) (arr);
5262 enddef;
5263
5264 def addsymbols (expr clr, symb) (suffix arr) =
5265 newpicture (_pls);
5266 for _idx = 1 upto arr:
5267 picdot (_pls, symb, zconv (arr[_idx]));
5268 endfor
5269 DoClip (_pls); coloraddon (clr, _pls);
5270 enddef;
5271
5272 % \end{macrocode}
5273 %
5274 % \DescribeRoutine{putimage}
5275 % This is designed to allow \mfpic{} users to make a picture (created with
5276 % \cs{mfpimage} or \cs{tile} perhaps), and put a copy at several
5277 % locations. This allows more complex things than \cs{plotsymbol} and
5278 % more flexibility than \cs{tess}. As the picture is should be completely
5279 % prepared in advance, there is no color or size parameter. Moreover,
5280 % \gbc{pic} might be quite complex, so we don't use \gbc{picdot} which
5281 % takes the added picture as an expression, but rather repeat its code.
5282 % The indirection of adding to \gbc{_pti} is normal when we want to
5283 % respect clipping without clipping what is already drawn. Saving memory
5284 % at some sacrifice of speed, we clip and reset with each addition. (It is
5285 % uncertain whether adding multiple clipped pictures includes the clipping
5286 % path for each addition. I'll have to test the memory use of this code
5287 % versus adding all the copies to \gbc{_pti} and clipping once.)
5288 % \begin{macrocode}
5289 def putimage (suffix pic) (text t) =
5290 newpicture (_pti);
5291 for _itm = t:
5292 addto _pti also
5293 %<MF> (pic shifted goodpair (zconv (_itm)));
5294 %<MP> (pic shifted zconv (_itm));
5295 DoClip (_pti); addto active_plane also _pti;
5296 _pti := nullpicture;
5297 endfor
5298 %<MF> mono active_plane
5299 enddef;
5300
5301 % \end{macrocode}
5302 %
5303 %
5304 %
5305 % \section{Axes, Tic Marks, and Grids}\label{axes}
5306 %
5307 % \DescribeRoutine{arrowdraw}
5308 % This is used in \gbc{vectorfield} and to draw axes. It returns nothing.
5309 % This doesn't follow the usual pattern of drawing a path and returning
5310 % it. This approach makes the old \cs{axes}, \cs{xaxis} and \cs{yaxis}
5311 % commands in \mfpic{} impossible to dash or dot. The newer axis drawing
5312 % commands permit this and so use other code.
5313 %
5314 % We simply call \gbc{headpath} with default values, but add \gbc{drawn}
5315 % to make sure the path is drawn, and precede it with \gbc{store} so
5316 % \MF{} won't complain of an isolated expression. The new \mfpic{}
5317 % method of drawing an axis is to apply \cs{arrow} to the path
5318 % \gbc{axisline}. Thus it can also be \gbc{dashed}, \gbc{dotted},
5319 % etc.
5320 %
5321 % The order is significant if axis and head are different colors. This
5322 % order puts the head on top of the shaft.
5323 % \begin{macrocode}
5324 def arrowdraw (expr hlen) (expr f) =
5325 store (curpath) headpath (hlen, 0, 0) drawn f;
5326 enddef;
5327
5328 % \end{macrocode}
5329 %
5330 % \DescribeRoutine{xaxis}
5331 % The macro \gbc{xaxis} draws the $x$-axis through the point $(0,0)$ in
5332 % graph coordinates. The only parameter is the length of the arrowhead in
5333 % device coordinates.
5334 % \DescribeRoutine{yaxis}
5335 % The Macro \gbc{yaxis} draws the $y$-axis.
5336 %
5337 % \DescribeRoutine{axes}
5338 % \gbc{axes} draws both axes with the same length of head.
5339 % \begin{macrocode}
5340 def xaxis (expr hlen) = arrowdraw (hlen) ((xneg, 0)--(xpos, 0));
5341 enddef;
5342 def yaxis (expr hlen) = arrowdraw (hlen) ((0, yneg)--(0, ypos));
5343 enddef;
5344 def axes (expr hlen) = xaxis (hlen); yaxis (hlen); enddef;
5345
5346 % \end{macrocode}
5347 %
5348 % For axes at the borders of the graph coordinates, we allow for them to
5349 % be shifted inwards. The amount of the shift is given by \gbc{laxis} for
5350 % the left side axis, \gbc{baxis} for the bottom axis, etc. They are in
5351 % graph coordinates.
5352 %
5353 % \DescribeRoutine{axisline}
5354 % The commands \gbc{axisline.x}, etc., return the appropriate straight
5355 % line at the appropriate location. These are vardefs rather than
5356 % variables so they can be affected by changing shift values.
5357 %
5358 % \DescribeRoutine{axis}
5359 % Finally, the commands \gbc{axis.x}, etc. examine their suffix and
5360 % apply \gbc{headpath} to the corresponding axis line. With a recent
5361 % change in \mfpic{} code, it is no longer used there. Instead, code
5362 % is written that allows the head to be drawn after the line is.
5363 % Note it is a vardef, and so returns the line as a path..
5364 % \begin{macrocode}
5365 laxis := baxis := raxis := taxis := 0;
5366
5367 vardef xlow = xneg + laxis enddef;
5368 vardef xhigh = xpos - raxis enddef;
5369 vardef ylow = yneg + baxis enddef;
5370 vardef yhigh = ypos - taxis enddef;
5371
5372 vardef axisline.x = (xlow, 0)--(xhigh, 0) enddef;
5373 vardef axisline.y = (0, ylow)--(0, yhigh) enddef;
5374 vardef axisline.l = axisline.y shifted (xlow, 0) enddef;
5375 vardef axisline.b = axisline.x shifted (0, ylow) enddef;
5376 vardef axisline.r = axisline.y shifted (xhigh, 0) enddef;
5377 vardef axisline.t = axisline.x shifted (0, yhigh) enddef;
5378
5379 vardef axis@# (expr len) = headpath (len, 0, 0) axisline@# enddef;
5380
5381 % \end{macrocode}
5382 %
5383 % \DescribeRoutine{borderrect}
5384 % These are mostly for the simplification of \mfpic{} and readability of
5385 % code. The command \gbc{borderrect} produces the border of the picture
5386 % in graph coordinates, taking into account the four margins.
5387 %
5388 % \DescribeRoutine{between}
5389 % The boolean \gbc{between} checks if the last argument is strictly
5390 % between the first two (which must be in order).
5391 %
5392 % \DescribeRoutine{inrange}
5393 % The boolean \gbc{inrange} checks if the last argument is in the closed
5394 % interval determined by the first two (which must be in order).
5395 %
5396 % \DescribeRoutine{inbounds}
5397 % The boolean \gbc{inbounds} checks if the argument (a pair) is in
5398 % the closed border rectangle (\gbc{borderrect}). It is not yet used in
5399 % \grafbase{}, though it would seem it ought to be useful.
5400 % \begin{macrocode}
5401 vardef borderrect =
5402 rect((xlow,ylow),(xhigh,yhigh))
5403 enddef;
5404
5405 vardef between (expr A, B, X) = (A < X) and (X < B) enddef;
5406 vardef inrange (expr A, B, X) = (A <= X) and (X <= B) enddef;
5407
5408 vardef inbounds (expr Z) =
5409 inrange (xlow, xhigh) (xpart Z) and inrange (ylow, yhigh) (ypart Z)
5410 enddef;
5411
5412 % \end{macrocode}
5413 %
5414 % Possible binary relation versions. The last is just a reversal of the
5415 % order of the first. These are not yet used in \grafbase{}.
5416 % \begin{macrocode}
5417 tertiarydef X isbetween P = between (xpart P, ypart P, X) enddef;
5418 tertiarydef X isinrange P = inrange (xpart P, ypart P, X) enddef;
5419 tertiarydef P contains X = between (xpart P, ypart P, X) enddef;
5420
5421 % \end{macrocode}
5422 %
5423 % Tick marks can be on the inside or outside of a border axis,
5424 % above or below any horizontal axes, left or right of any vertical axis
5425 % or centered on any axis. The following numerics are merely used to
5426 % convert the names to numeric code that the drawing routine will examine.
5427 %
5428 % However, it is no accident that \gbc{onbottom = onright} and that
5429 % \gbc{centered} is halfway between \gbc{onright} and \gbc{onleft}. The
5430 % code uses the numeric values to compute a shift, and one can supply an
5431 % expression like \gbc{.33ontop+.67onbottom]} and then 1/3 of each mark
5432 % will be above (and 2/3 will be below) the axis.
5433 %
5434 % The negative value of \gbc{inside} and \gbc{outside} is a flag that they
5435 % are to be treated differently. The others have the property that the
5436 % direction is the direction of the axis rotated a certain way (e.g.,
5437 % $90$ degrees from \mfc{up} points \mfc{left}, $-90$ points \mfc{right}).
5438 % But \gbc{inside} is right of the left axis and left of the right axis.
5439 % \begin{macrocode}
5440 numeric inside, outside, centered, onleft, onright, ontop, onbottom;
5441 inside := -2;
5442 outside := -1;
5443 onright := 1;
5444 onleft := 2;
5445 centered := .5[onright, onleft];
5446 onbottom := onright;
5447 ontop := onleft;
5448 % \end{macrocode}
5449 %
5450 % We interact with \mfpic{} by allowing the user to change the value of
5451 % \gbc{ltick}, for example, with a command like
5452 % \cs{setaxismarks l}\marg{outside}. Here we set the defaults.
5453 % \begin{macrocode}
5454 ltick := rtick := ttick := btick := inside;
5455 xtick := ytick := centered;
5456
5457 % \end{macrocode}
5458 %
5459 % \DescribeRoutine{axismarks}
5460 % This utility macro draws the tick marks on an arbitrary axis. The
5461 % different commands \gbc{xmarks}, etc., call this command with particular
5462 % values of these parameters.
5463 % \begin{itemize}
5464 % \item \gbc{inang} is the direction one must rotate the axis to point
5465 % inside. This is always $\pm90$ degrees. The $x$-axis and $y$-axis
5466 % are treated just like bottom and left axis in this respect.
5467 % \item \gbc{tp} is the tick position (e.g., \gbc{inside} or
5468 % \gbc{ontop}).
5469 % \item \gbc{loc} is the location of the 0-point of the axis (graph
5470 % coordinates).
5471 % \item \gbc{pdir} is \mfc{right} or \mfc{up}, indicating the positive
5472 % direction on the axis.
5473 % \item \gbc{len} is the length of a tick mark, supplied as an argument
5474 % to the individual axis mark commands.
5475 % \item \gbc{t} is the list of positions, also supplied.
5476 % \end{itemize}
5477 % \begin{macrocode}
5478 vardef axismarks (expr inang, tp, loc, pdir) (expr len) (text t) =
5479 save _tp, _U, _P, _tic, _ticang;
5480 pair _U, _P; path _tic;
5481 % \end{macrocode}
5482 % For \gbc{onleft}, \gbc{onright}, \gbc{ontop} or \gbc{onbottom}, which
5483 % are positive, don't examine \gbc{inang} but for \gbc{inside/outside}
5484 % use it to determine what inside means. \gbc{_ticang} will be the angle
5485 % to rotate \gbc{pdir} to set the direction of the tic mark.
5486 %
5487 % Then we shift the numeric value of \gbc{tp} by one, so \gbc{centered}
5488 % corresponds to $.5$ and the rest to either $0$ or $1$.
5489 % \begin{macrocode}
5490 _ticang := if tp < 0: inang else: 90 fi;
5491 _tp := abs(tp) - 1;
5492 % \end{macrocode}
5493 % Except, we go through the following shenanigans so that the marks are
5494 % always perpendicular to the axis, even if a coordinate transform will
5495 % slant the axis. After this \gbc{_U} should point in direction of inside,
5496 % onleft or ontop.
5497 % \begin{macrocode}
5498 _U := unitvector (vconv (pdir)) rotated _ticang;
5499 % \end{macrocode}
5500 % Next, we use \gbc{_tp} to calculate the mark. For example, if
5501 % \gbc{tp = inside}, then \gbc{_tp = 1}. Since \gbc{_U} points toward
5502 % inside, \gbc{_tic} will go from \mfc{(0,0)} to a point a distance
5503 % \gbc{len} in the direction of \gbc{_U}.
5504 % \begin{macrocode}
5505 _tic := (-_U--(0,0)) shifted (_tp*_U) scaled len;
5506 % \end{macrocode}
5507 % Finally, for each numeric value in the list \gbc{t}, draw the tic
5508 % shifted to the corresponding point on the axis.
5509 % \begin{macrocode}
5510 for _a = t:
5511 safedraw (_tic shifted zconv (loc + _a*pdir));
5512 endfor
5513 enddef;
5514
5515 % \end{macrocode}
5516 %
5517 % \DescribeRoutine{xmarks}
5518 % And now the specialized command for each axis. Inside and outside
5519 % really make no sense for the $x$- and
5520 % \DescribeRoutine{ymarks}
5521 % \RoutineIndex{lmarks}
5522 % \RoutineIndex{bmarks}
5523 % \RoutineIndex{rmarks}
5524 % \RoutineIndex{tmarks}
5525 % $y$-axis, but since a bottom axis is usually used for $x$ and a left
5526 % axis for $y$, we give \gbc{xmarks} the same first parameter as
5527 % \gbc{bmarks} and \gbc{ymarks} the same as \gbc{lmarks}.
5528 % \begin{macrocode}
5529 def xmarks = axismarks ( 90, xtick, origin, right) enddef;
5530 def ymarks = axismarks (-90, ytick, origin, up) enddef;
5531 def lmarks = axismarks (-90, ltick, (xlow, 0), up) enddef;
5532 def bmarks = axismarks ( 90, btick, (0, ylow), right) enddef;
5533 def rmarks = axismarks ( 90, rtick, (xhigh, 0), up) enddef;
5534 def tmarks = axismarks (-90, ttick, (0, yhigh), right) enddef;
5535
5536 % \end{macrocode}
5537 %
5538 % \DescribeRoutine{vargrid}
5539 % \RoutineIndex{vgrid}
5540 % Mainly for the purpose of visualising coordinates, \gbc{vargrid}
5541 % draws a dot of size \gbc{dsize} at every point whose coordinates
5542 % are are \gbc{(n*xsp, m*ysp)}, \gbc{n} and \gbc{m} being integers.
5543 % \gbc{dsize} is in device coordinates, the spacings are in graph
5544 % coordinates.
5545 % \DescribeRoutine{grid}
5546 % The macro \gbc{grid} is for backward compatibility, calling
5547 % \gbc{vargrid} with a default \gbc{dsize} of \mfc{.5bp}. The old name
5548 % \gbc{vgrid} incorrectly suggests a connection to \gbc{vgridlines}.
5549 % \begin{macrocode}
5550 path griddotpath; griddotpath := fullcircle;
5551 def grid = vargrid (0.5bp) enddef;
5552 vardef vargrid (expr dsize, xsp, ysp) =
5553 save gdot, gridpic; picture gdot, gridpic;
5554 gdot := setdot (griddotpath, dsize);
5555 gridpic := nullpicture;
5556 for n = ceiling ((xlow)/xsp) upto floor ((xhigh)/xsp):
5557 for m = ceiling ((ylow)/ysp) upto floor ((yhigh)/ysp):
5558 picdot (gridpic, gdot, zconv ((n*xsp, m*ysp)));
5559 endfor
5560 endfor
5561 coloraddon (pointcolor, gridpic);
5562 enddef;
5563 def vgrid = vargrid enddef;
5564
5565 % \end{macrocode}
5566 %
5567 % \DescribeRoutine{gridlines}
5568 % This is more what I think of when I hear `grid', but the name was
5569 % already taken. The macro \gbc{gridlines} draws horizontal and vertical
5570 % lines through all the points that \gbc{grid} would draw.
5571 % \DescribeRoutine{hgridlines}
5572 % The macro \gbc{hgridlines} draws only the horizontal lines through the
5573 % same points, while
5574 % \DescribeRoutine{vgridlines}
5575 % \gbc{vgridlines} draws only vertical lines.
5576 % \begin{macrocode}
5577 def hgridlines (expr ysp) =
5578 for n = ceiling ((ylow)/ysp) upto floor ((yhigh)/ysp):
5579 safedraw zconv ((xlow, n*ysp)--(xhigh, n*ysp));
5580 endfor
5581 enddef;
5582 def vgridlines (expr xsp) =
5583 for n = ceiling ((xlow)/xsp) upto floor ((xhigh)/xsp):
5584 safedraw zconv ((n*xsp, ylow)--(n*xsp, yhigh));
5585 endfor
5586 enddef;
5587 def gridlines (expr xsp, ysp) =
5588 vgridlines (xsp); hgridlines (ysp);
5589 enddef;
5590
5591 % \end{macrocode}
5592 %
5593 % \DescribeRoutine{vectorfield}
5594 % This command produces a field of arrows from a pair-valued formula (text
5595 % parameter \gbc{fcn}) in a region described by a boolean-valued
5596 % expression (text parameter \gbc{cond}). This routine simply makes
5597 % functions (\mfc{vardef}\,s) out of the expressions and calls
5598 % \DescribeRoutine{mkvectorfield}
5599 % \gbc{mkvectorfield}, which steps through the points described by
5600 % \gbc{xsp} and \gbc{ysp} and places an arrow (actually, any path) at
5601 % each. The arrow path is given by the function \gbc{vf}. The arrow is
5602 % placed at the point only if the function \gbc{isOK} returns true. It
5603 % also omits points that lie in the axis margins.
5604 %
5605 % \DescribeRoutine{plrvectorfield}
5606 % The polar version differs only in the distribution of the arrows. They
5607 % are placed at regular intervals of $r$ an $\theta$. The text parameters
5608 % should be expressions in \gbc{r} and \gbc{t}, but are otherwise the
5609 % same. In particular, \gbc{fcn} should return \MF{} pairs, not polar
5610 % coordinate pairs. The function \gbc{polar} can be used to convert if
5611 % necessary. Its code is very similar, except for the boolean code needed
5612 % to keep the vectors within the bounds of the graph.
5613 % \DescribeRoutine{mkplrvectorfield}
5614 % It calls \gbc{mkplrvectorfield}, which is a lot like the non-polar
5615 % version, except it first calculates the extremes of the polar variables
5616 % with \gbc{getpolarbounds} and relies on the boolean to keep it out of
5617 % the axis margins.
5618 % \begin{macrocode}
5619 def vectorfield (expr len, xsp, ysp) (text fcn) (text cond) =
5620 save _vf, _is_OK;
5621 vardef _vf (expr x,y) = ((0,0)--(fcn)) shifted (x,y) enddef;
5622 vardef _is_OK (expr x,y) = cond enddef;
5623 mkvectorfield (len, xsp, ysp) (_vf, _is_OK);
5624 enddef;
5625
5626 vardef mkvectorfield (expr len, xsp, ysp) (suffix vf, isOK) =
5627 for n = ceiling ((xlow)/xsp) upto floor ((xhigh)/xsp):
5628 for m = ceiling ((ylow)/ysp) upto floor ((yhigh)/ysp):
5629 if isOK (n*xsp,m*ysp): arrowdraw (len) (vf(n*xsp,m*ysp)); fi
5630 endfor
5631 endfor
5632 enddef;
5633
5634 def plrvectorfield (expr len, rsp, tsp) (text fcn) (text cond) =
5635 save _vf, _is_OK, _A, _B, _C, _D;
5636 _A := xlow; _B := xhigh;
5637 _C := ylow; _D := yhigh;
5638 vardef _vf (expr r,t) = ((0,0)--(fcn)) shifted (r*dir t) enddef;
5639 vardef _is_OK (expr r,t) =
5640 save _X, _Y; _X := r*cosd t; _Y := r*sind t;
5641 (cond) and between (_A, _B) (_X) and between (_C, _D) (_Y)
5642 enddef;
5643 mkplrvectorfield (len, rsp, tsp) (_vf, _is_OK);
5644 enddef;
5645
5646 vardef mkplrvectorfield (expr len, rsp, tsp) (suffix vf, isOK) =
5647 save rmin, rmax, tmin, tmax;
5648 getpolarbounds;
5649 if rmin = 0:
5650 if isOK (0,tmin): arrowdraw (len) (vf (0,tmin)); fi
5651 rmin := rsp;
5652 fi
5653 for n = ceiling (rmin/rsp) upto floor (rmax/rsp):
5654 for m = ceiling (tmin/tsp) upto floor (tmax/tsp):
5655 if isOK (n*rsp,m*tsp): arrowdraw (len) (vf (n*rsp,m*tsp)); fi
5656 endfor
5657 endfor
5658 enddef;
5659
5660 % \end{macrocode}
5661 %
5662 % \DescribeRoutine{patcharcs}
5663 % The macro \gbc{patcharcs} draws on a picture \gbc{X} the arcs
5664 % \gbc{tstart}${}\le \theta \le{}$\gbc{tstop} with radii starting at
5665 % \gbc{rstart}, stepping by \gbc{rstep} until \gbc{rstop}.
5666 % \DescribeRoutine{patchrays}
5667 % The macro \gbc{patchrays} draws the radial lines with $r$ coordinate
5668 % varying between \gbc{rstart} and \gbc{rstop} at angles from \gbc{tstart}
5669 % to \gbc{tstop} stepping by \gbc{tstep}.
5670 % \DescribeRoutine{plrpatch}
5671 % And \gbc{plrpatch} simply calls them both, and adds the resulting
5672 % pictures to \gbc{active_plane}.
5673 % \begin{macrocode}
5674 def patcharcs (suffix X) (expr rstart, rstop, rstep, tstart, tstop) =
5675 for rad = (if rstart = 0: rstep else: rstart fi)
5676 step rstep until rstop:
5677 orto (X, picpath zconv (arcplr (origin, tstart, tstop, rad)) );
5678 endfor
5679 enddef;
5680 def patchrays (suffix X) (expr tstart, tstop, tstep, rstart, rstop) =
5681 for _ang = tstart step tstep until tstop:
5682 orto (X) (picpath zconv ((rstart*dir _ang)--(rstop*dir _ang)));
5683 endfor
5684 enddef;
5685
5686 def plrpatch (expr rstart, rstop, rstep, tstart, tstop, tstep) =
5687 begingroup
5688 newpicture (v);
5689 patcharcs (v) (rstart, rstop, rstep, tstart, tstop);
5690 coloraddon (drawcolor, v);
5691 v := nullpicture;
5692 patchrays (v) (tstart, tstop, tstep, rstart, rstop);
5693 coloraddon (drawcolor, v);
5694 endgroup
5695 enddef;
5696
5697 % \end{macrocode}
5698 %
5699 % Polar coordinate grids are analogous to \gbc{gridlines} and \gbc{grid}.
5700 % They first draw a grid large enough to cover the whole graph, then clip
5701 % it to the graph boundaries. Since three of the four require
5702 % calculating the dimensions of a polar coordinate patch that completely
5703 % covers the graph rectangle, we isolate that code in
5704 % \gbc{beginpolargrid}, defined later.
5705 %
5706 %
5707 % \DescribeRoutine{gridarcs}
5708 % \gbc{gridarcs} creates arcs having radii that are integer multiples of
5709 % \gbc{rstep} and
5710 % \DescribeRoutine{gridrays}
5711 % \gbc{gridrays} draws radial lines at angles that are multiples of
5712 % \gbc{tstep}.
5713 % \DescribeRoutine{polargrid}
5714 % The command \gbc{polargrid}simply calls the first two.
5715 %
5716 % \DescribeRoutine{polargridpoints}
5717 % On the other hand, \gbc{polargridpoints} draws dots at the points where
5718 % the lines and arcs in \gbc{poloargrid} would intersect. The `step'
5719 % parameters are in graph coordinates. \gbc{beginpolargrid} also
5720 % declares the picture variable \gbc{gridpic}, while \gbc{endpolargrid}
5721 % clips the resulting picture and adds it to \gbc{active_plane}.
5722 %
5723 % The \gbc{rmin}, etc., returned by \gbc{beginpolargrid} are modified to
5724 % fit the grid established by the step sizes. A ray could happen to be one
5725 % of the graph's sides, so we use \mfc{ceiling} and \mfc{floor} which
5726 % doesn't change integer values. However, the arc with radius \gbc{rmin}
5727 % or \gbc{rmax} could touch the graph rectangle in at most 4 points, so we
5728 % use \mfc{floor (x + 1)} and \mfc{ceiling (x - 1)} to start and stop
5729 % before the edge of the graph.
5730 % \begin{macrocode}
5731 def gridarcs (expr rstep) =
5732 beginpolargrid;
5733 if rmin = 0:
5734 picdot (gridpic, setdot (griddotpath, penwd), zconv (origin));
5735 fi
5736 rmin := rstep * floor (rmin/rstep + 1);
5737 rmax := rstep * ceiling (rmax/rstep - 1);
5738 patcharcs (gridpic) (rmin, rmax, rstep, tmin, tmax);
5739 endpolargrid (drawcolor, .5penwd);
5740 enddef;
5741
5742 def gridrays (expr tstep) =
5743 beginpolargrid;
5744 tmin := tstep * ceiling (tmin/tstep);
5745 tmax := tstep * floor (tmax/tstep);
5746 patchrays (gridpic) (tmin, tmax, tstep, rmin, rmax);
5747 endpolargrid (drawcolor, .5penwd);
5748 enddef;
5749
5750 def polargrid (expr rstep, tstep) =
5751 gridarcs (rstep); gridrays (tstep);
5752 enddef;
5753
5754 def polargridpoints (expr dsize, rstep, tstep) =
5755 beginpolargrid;
5756 setpicture (gdot) setdot (griddotpath, dsize);
5757 if rmin = 0:
5758 picdot (gridpic, gdot, zconv (origin));
5759 rmin := rstep;
5760 fi
5761 for n = ceiling (rmin/rstep) upto floor (rmax/rstep):
5762 for m = ceiling (tmin/tstep) upto floor (tmax/tstep):
5763 picdot ( gridpic, gdot, zconv ( polar ((n*rstep, m*tstep)) ) );
5764 endfor
5765 endfor
5766 endpolargrid (pointcolor, .5dsize);
5767 enddef;
5768
5769 % \end{macrocode}
5770 %
5771 % \DescribeRoutine{beginpolargrid}
5772 % The macro \gbc{beginpolargrid} calls \gbc{getpolarbounds} to compute the
5773 % bounds (on $r$ and $\theta$) of the smallest polar coordinate patch that
5774 % covers the graph rectangle.
5775 % \DescribeRoutine{getpolarbounds}
5776 % That command leaves the values in \gbc{rmin}, \gbc{rmax}, \gbc{tmin} and
5777 % \gbc{tmax}. Then \gbc{beginpolargrid} initializes \gbc{gridpic} whereon
5778 % the grids are drawn.
5779 % \begin{macrocode}
5780 def beginpolargrid =
5781 begingroup;
5782 save rmax, rmin, tmax, tmin;
5783 getpolarbounds;
5784 newpicture (gridpic);
5785 enddef;
5786
5787 def getpolarbounds =
5788 save p, r, t;
5789 pair p[];
5790 p0 := (xneg, yneg); p1 := (xneg, ypos);
5791 p2 := (xpos, ypos); p3 := (xpos, yneg);
5792 % \end{macrocode}
5793 % This loop finds the radial coordinate of each corner of the graph and
5794 % finds the maximum while doing so.
5795 % \begin{macrocode}
5796 r0 := abs(p0); rmax := r0;
5797 for j = 1 upto 3:
5798 r[j] := abs(p[j]);
5799 if rmax < r[j]: rmax := r[j]; fi
5800 endfor
5801 % \end{macrocode}
5802 % When the origin is inside the graph rectangle we need the full range
5803 % of $r$ and $\theta$. When the origin is one of the corners, the angles
5804 % can just be read off. Otherwise, to find the range of $\theta$ we
5805 % essentially rotate one corner to have angle zero, get the angles to all
5806 % corners and rotate back. This guarantees that the wedge with
5807 % \gbc{tmin}${} < \theta < {}$\gbc{tmax} includes the graph.
5808 % \begin{macrocode}
5809 rmin := 0;
5810 if between (xneg, xpos) (0) and between (yneg, ypos) (0):
5811 tmin := 0; tmax := 360;
5812 elseif (p0 = origin): tmin := 0; tmax := 90;
5813 elseif (p1 = origin): tmin := -90; tmax := 0;
5814 elseif (p2 = origin): tmin := -180; tmax := -90;
5815 elseif (p3 = origin): tmin := 90; tmax := 180;
5816 else:
5817 tmax := tmin := t0 := angle p0;
5818 for j = 1 upto 3:
5819 t := t0 + anglefromto (p0, p[j]);
5820 if tmax < t: tmax := t; fi
5821 if tmin > t: tmin := t; fi
5822 endfor
5823 % \end{macrocode}
5824 % The minimum value of $r$ can be one of 9 possibilities: if the four
5825 % sides of the graph are extended infinitely far in both directions, the
5826 % origin can be in any one of the 9 regions formed. We've already disposed
5827 % of the inside of the graph. This code considers the remaining regions in
5828 % the following order: (1)~above or below, (2)~left or right, and (3)~one
5829 % of the four corner regions.
5830 % \begin{macrocode}
5831 if between (xneg, xpos) (0):
5832 rmin := emin (abs(yneg), abs(ypos));
5833 elseif between (yneg, ypos) (0):
5834 rmin := emin (abs(xneg), abs(xpos));
5835 else:
5836 rmin := min (r0, r1, r2, r3);
5837 fi
5838 fi
5839 enddef;
5840
5841 % \end{macrocode}
5842 %
5843 % \DescribeRoutine{endpolargrid}
5844 % The \gbc{clr} is \gbc{drawcolor} for line grids, \gbc{pointcolor} for
5845 % dot grids. The \gbc{size} is half the width of the grid's lines or half
5846 % the width of the grid's dots. The purpose is to make sure dots and lines
5847 % on the graph's edge aren't cut off. For dots I should probably put this
5848 % decision in the code that draws them on \gbc{gridpic}.
5849 % \begin{macrocode}
5850
5851 def endpolargrid (expr clr, size)=
5852 clipto (gridpic) rect ( zconv ((xneg, yneg)) - size*(1,1),
5853 zconv ((xpos, ypos)) + size*(1,1) );
5854 coloraddon (clr, gridpic);
5855 endgroup
5856 enddef;
5857
5858 % \end{macrocode}
5859 %
5860 % \DescribeRoutine{polarpatch}
5861 % Finally, this just does \gbc{plrpatch}, but also draws the ending
5862 % boundaries, in case they are not an integer number of steps from the
5863 % start.
5864 % \begin{macrocode}
5865 vardef polarpatch (expr rstart, rstop, rstep, tstart, tstop, tstep) =
5866 plrpatch (rstart, rstop, rstep, tstart, tstop, tstep);
5867 safedraw zconv ( arcplr (origin, tstart, tstop, rstop) );
5868 safedraw zconv ( ((rstart, 0)--(rstop, 0)) rotated tstop );
5869 enddef;
5870
5871 % \end{macrocode}
5872 %
5873 %
5874 %
5875 % \section{Path Construction}\label{pathconstruction}
5876 %
5877 % This section is devoted to commands that accept a list or array of
5878 % points and produce a path, usually (but not necessarily) through those
5879 % points. In addition there are a few commands that find some of the key
5880 % points, lines and circles associated with a triangle. No \mfpic{}
5881 % interface is yet available for the triangle commands.
5882 %
5883 %
5884 % \subsection{Piecewise linear paths}\label{linear}
5885 %
5886 % \DescribeRoutine{rect}
5887 % Most of the macros that only define paths are coordinate independent.
5888 % The simplest is \gbc{rect}. It accepts two pair expressions and produces
5889 % the upright rectangle with those points at opposite corners. It might be
5890 % noted that if the corners really are lower left and upper right, then
5891 % the path is anticlockwise, If they are on the other diagonal, the
5892 % path is clockwise. The path is a cycle (closed). The starting/ending
5893 % point (needed for arrows and the like) is the first point of the two.
5894 %
5895 % \DescribeRoutine{triangle}
5896 % Produces a closed path joining three points with straight lines; first
5897 % named point \gbc{A} is \mfc{point 0 of triangle (A, B, C)}, etc.
5898 % \begin{macrocode}
5899 vardef rect (expr ll, ur) =
5900 ll--(xpart ur, ypart ll)--ur--(xpart ll, ypart ur)--cycle
5901 enddef;
5902 vardef triangle (expr A, B, C) = A--B--C--cycle enddef;
5903
5904 % \end{macrocode}
5905 %
5906 % \DescribeRoutine{regularpolygon}
5907 % The first argument is the number of sides, the second is an array name
5908 % to hold the list of vertices. The third argument contains two
5909 % equations separated by a semicolon, preferably the location of two of
5910 % the vertices, or the location of the center and one vertex. That plus
5911 % the equations in the \mfc{for}-loop give \gbc{n+1} equations to
5912 % determine the \gbc{n} vertices and the center. Note that the vertices
5913 % are numbered anticlockwise.
5914 %
5915 % The equations must \emph{not} be equations that are satisfied by all
5916 % $n$-gons regardless of size and position. For example:\\
5917 % \indent \gbc{regulapolygon(4)(Ted)(Ted0 := (0,0);Ted1 + Ted3 = (0,0))}\\
5918 % The second of these says the middle lies halfway between the extremes,
5919 % and is already a consequence of the code. It goes without saying that
5920 % equations that cannot be satisfied by any regular polygon are also out.
5921 % \begin{macrocode}
5922 vardef regularpolygon (expr n) (suffix Bob) (text eqns) =
5923 pair Bob[]; Bob := emax (round (abs (n)), 2);
5924 eqns;
5925 for _uncle = 1 upto Bob - 1:
5926 (Bob1 - Bob0) rotated (360/Bob*_uncle) = Bob[_uncle+1] - Bob0;
5927 endfor
5928 mkpoly (true) (Bob)
5929 enddef;
5930
5931 % \end{macrocode}
5932 %
5933 % The following set of commands take a path as argument, but it is
5934 % intended that it be a triangle. Even then, they work correctly only if
5935 % it is a cycle.
5936 %
5937 % These produce the perpendicular from \,\gbc{point n of t}\, to the
5938 % (extension of) the opposite side (i.e., the altitude).
5939 % \DescribeRoutine{altitudept}
5940 % The first one determines where the altitude meets the opposite side, and
5941 % the
5942 % \DescribeRoutine{altitude}
5943 % second just connects the two points. Since \gbc{altitudept} is always
5944 % \gbc{point 1 of altitude}, it is actually redundant. However, the
5945 % command \gbc{medianpt} (defined below) is used outside of the
5946 % construction of \gbc{median}, so it seemed possible the \gbc{altitudept}
5947 % might be useful also.
5948 %
5949 % We need a cycle so that points $n+1$ and $n+2$ will wrap around to the
5950 % start of the path when necessary.
5951 % \begin{macrocode}
5952 vardef altitudept expr n of t =
5953 save A, B, C, zz; pair A, B, C, zz;
5954 B := pnt[n + 1] (t);
5955 C := pnt[n + 2] (t);
5956 zz = whatever[B,C];
5957 zz = pnt[n](t) + whatever*((C-B) rotated 90);
5958 zz
5959 enddef;
5960
5961 vardef altitude expr n of t =
5962 (pnt[n](t))--(altitudept n of t)
5963 enddef;
5964
5965 % \end{macrocode}
5966 %
5967 % \DescribeRoutine{medianpt}
5968 % These next two produce the midpoint of the side opposite
5969 % \,\gbc{point n of t}\, and the
5970 % \DescribeRoutine{median}
5971 % line connecting those two points.
5972 % \begin{macrocode}
5973 vardef medianpt expr n of t =
5974 0.5[pnt[n + 1] (t), pnt[n + 2] (t)]
5975 enddef;
5976
5977 vardef median expr n of t =
5978 (pnt[n](t))--(medianpt n of t)
5979 enddef;
5980
5981 % \end{macrocode}
5982 %
5983 % \DescribeRoutine{anglebisectorpt}
5984 % The first produces the point on the side opposite \,\gbc{point n of t}\,
5985 % where the angle bisector at that corner crosses it and the second
5986 % produces
5987 % \DescribeRoutine{anglebisector}
5988 % the line that bisects that angle.
5989 % \begin{macrocode}
5990 vardef anglebisectorpt expr n of t =
5991 save A, B, C; pair A, B, C;
5992 A := pnt[n ] (t);
5993 B := pnt[n + 1] (t);
5994 C := pnt[n + 2] (t);
5995 save zz; pair zz;
5996 zz = whatever[B,C];
5997 zz = A + whatever*((B-A) rotated (.5*cornerangle (A,B,C)));
5998 zz
5999 enddef;
6000
6001 vardef anglebisector expr n of t =
6002 (pnt[n](t))--(anglebisectorpt n of t)
6003 enddef;
6004
6005 % \end{macrocode}
6006 %
6007 % \DescribeRoutine{cornerangle}
6008 % This calculates the angle at the corner of a triangle. Specifically,
6009 % the angle (between $-180$ and $180$) required to rotate the vector
6010 % \gbc{B-A} into \gbc{C-A}. For degenerate triangles the seemingly
6011 % arbitrary values 60 and 90 are designed to match the assumptions used
6012 % in the arc commands. But also to guarantee that the three
6013 % \gbc{cornerangle}\,s add up to $\pm180$. \gbc{cornerangle (A,B,C)} gives
6014 % the angle at \gbc{A}, positive if \gbc{A--B--C--cycle} is
6015 % anticlockwise.
6016 % \begin{macrocode}
6017 vardef anglefromto (expr u, v) =
6018 if (u = origin) or (v = origin): 0
6019 else: angle (v rotated (-angle u))
6020 fi
6021 enddef;
6022
6023 vardef cornerangle (expr A, B, C) =
6024 if (A = B) or (A = C) :
6025 if (B = C) : 60
6026 else: 90
6027 fi
6028 else: anglefromto (B - A, C - A)
6029 fi
6030 enddef;
6031
6032 % \end{macrocode}
6033 %
6034 % \DescribeRoutine{mkpath}
6035 % This accepts the name of an array of pairs and produces a path
6036 % that connects them. The first and third parameters are booleans. If
6037 % \gbc{smooth} is \mfc{true} a smooth path is produced, otherwise a
6038 % polyline. If \gbc{cyclic} is \mfc{true} the path is closed. The work is
6039 % actually done by \gbc{mksmooth} or \gbc{mkpoly}.
6040 % \begin{macrocode}
6041 vardef mkpath (expr smooth, tens, cyclic) (suffix pts) =
6042 if smooth: mksmooth (tens)
6043 else: mkpoly
6044 fi (cyclic, pts)
6045 enddef;
6046
6047 % \end{macrocode}
6048 %
6049 % \DescribeRoutine{mkpoly}
6050 % This produces the path of line segments connecting \gbc{pts1},
6051 % \gbc{pts2}, etc., closing it up if the boolean \gbc{cyclic} is true.
6052 % It can also be used with an array of paths instead of points, connecting
6053 % the end of each with the beginning of the next. We do this in \mfpic{}'s
6054 % \cs{connect} \dots\ \cs{endconnect} construct.
6055 % \begin{macrocode}
6056 vardef mkpoly (expr cyclic) (suffix pts) =
6057 for _i = 1 upto pts-1: pts[_i]-- endfor
6058 pts[pts] if cyclic: -- cycle else: {0,0} fi
6059 enddef;
6060
6061 % \end{macrocode}
6062 %
6063 % \DescribeRoutine{polyline}
6064 % This is the \mfpic{} interface. Instead of an array name, it accepts a
6065 % list of pair expressions, forms an array from them and calls
6066 % \gbc{mkpoly}.
6067 % \DescribeRoutine{NoPoints}
6068 % \mfc{NoPoints} is called when an array of points is defined (using
6069 % setpairs) that returns $0$ for the number of pairs. It prints a warning
6070 % and sets the array to a single point, the origin.
6071 % \begin{macrocode}
6072 vardef polyline (expr cyclic) (text t) =
6073 setpairs (_pl) (t);
6074 if _pl=0: NoPoints ("polyline", _pl); fi
6075 mkpoly (cyclic, _pl)
6076 enddef;
6077
6078 def NoPoints (expr s) (suffix pts) =
6079 GBwarn s & " attempted with empty list."; pts[incr pts] := origin;
6080 enddef;
6081
6082 % \end{macrocode}
6083 %
6084 % \DescribeRoutine{turtle}
6085 % \emph{Turtle graphics} was a teaching tool to get youngsters used to the
6086 % concept of programming while also teaching geometry. The students fed an
6087 % Apple II computer a sequence of angles and distances, and a small
6088 % triangle on the screen (the `turtle') would turn the indicated angle
6089 % and travel the indicated distance, tracing a polyline on the screen.
6090 %
6091 % The argument of \gbc{turtle} is a list of pairs. The first is the
6092 % starting point, the rest are vector displacements (moves). The
6093 % distance and incremental angles of the original turtle graphics would
6094 % require keeping track of the current angle and using the \gbc{polar}
6095 % command.
6096 % \begin{macrocode}
6097 vardef turtle (text t) =
6098 setnumeric (_tu) 0;
6099 setpair (_tmp) origin;
6100 pair _tu[];
6101 for _a = t:
6102 _tmp := _tmp + _a;
6103 _tu[incr _tu] := _tmp;
6104 endfor
6105 if _tu = 0: NoPoints("turtle", _tu); fi
6106 mkpoly (false, _tu)
6107 enddef;
6108
6109 % \end{macrocode}
6110 %
6111 % \DescribeRoutine{brownianpath}
6112 % I needed the following to illustrate Brownian motion. It takes a given
6113 % starting point, a given number of steps and a scaling factor. It
6114 % generates a sequence of random points, each one being chosen randomly
6115 % using a Gaussian distribution centered at the previous point. The
6116 % standard deviation of the random distance is the scale factor. Strictly
6117 % speaking this is a Gaussian random walk, not Brownian motion. A true
6118 % Brownian motion would be a limit of these, with \gbc{num} tending to
6119 % $\infty$ and \gbc{sc} tending to 0.
6120 %
6121 % \DescribeRoutine{randomwalk}
6122 % This is like \gbc{brownianpath}, but the distance from one point to
6123 % the next is always the same, only the direction is random. It takes
6124 % the same arguments as \gbc{brownianpath}
6125 %
6126 % \DescribeRoutine{browniangraph}
6127 % This command takes a given number of steps \gbc{num} and a scaling
6128 % factor/step size \gbc{scst}. It generates a sequence of points, each one
6129 % being chosen right of the previous one by the step size \gbc{scst} and
6130 % randomly up or down using a Gaussian distribution centered at the
6131 % previous $y-value$. The Gaussian distribution has standard deviation
6132 % equal to \gbc{scst}. The path starts at $(0,0)$. One needs to transform
6133 % the path to get a different start or a scale factor different from the
6134 % step size.
6135 %
6136 % In \MF{} we run into capacity problems when \gbc{num} is greater than
6137 % 500 or so. This is the \mfc{autorounding} problem again (see the
6138 % discussion at \gbc{sinewave}. We can't use the same technique we used
6139 % there since it is the drawing that invokes \mfc{autorounding} and these
6140 % macros only construct paths; they don't draw them.
6141 % \begin{macrocode}
6142 vardef brownianpath (expr start, num, sc) =
6143 setnumeric (_brp) 1;
6144 setpair (_tmp) start;
6145 pair _brp[]; _brp1 := _tmp;
6146 for _idx := 1 upto num:
6147 _tmp := _tmp + sc/(sqrt 2)*(normaldeviate,normaldeviate);
6148 _brp[incr _brp] := _tmp;
6149 endfor
6150 mkpoly (false, _brp)
6151 enddef;
6152 vardef randomwalk (expr start, num, dst) =
6153 setnumeric (_rdw) 1;
6154 setpair (_tmp) start;
6155 pair _rdw[]; _rdw1 := _tmp;
6156 for _idx := 1 upto num:
6157 _tmp := _tmp + dst*dir(uniformdeviate(360));
6158 _rdw[incr _rdw] := _tmp;
6159 endfor
6160 mkpoly (false, _rdw)
6161 enddef;
6162 vardef browniangraph (expr num, scst) =
6163 setnumeric (_brg) 1;
6164 pair _tmp, _brg[]; _tmp := _brg1 := (0,0);
6165 for _idx := 1 upto num:
6166 _tmp := _tmp + scst*(1,normaldeviate);
6167 _brg[incr _brg] := _tmp;
6168 endfor
6169 mkpoly (false, _brg)
6170 enddef;
6171
6172 % \end{macrocode}
6173 %
6174 %
6175 % \subsection{Smooth paths}\label{smooth}
6176 %
6177 % We added an optional parameter for the tension of smooth curves to
6178 % \mfpic. It used to be implemented this way: functions that implement a
6179 % tension parameter set \gbc{cur_tension} and called \gbc{mksmooth}, which
6180 % used that tension in its formation of a path. Since \gbc{mksmooth} was
6181 % only ever used in this way, I decided to change its syntax to include a
6182 % tension parameter. Only the functions \gbc{tcurve} and \gbc{mkpath}
6183 % actually call \gbc{mksmooth} directly, most other path building commands
6184 % with tension parameters call \gbc{mkpath} or \gbc{mkfcn} (which calls
6185 % \gbc{mkpath}).
6186 %
6187 % \DescribeRoutine{mksmooth}
6188 % This takes a tension value, a boolean, and the name of an array of
6189 % points, draws the curve connecting them and closes it up if the boolean
6190 % is true. It draws the curve forcing it to have the same direction at a
6191 % point as the line segment connecting the preceding and following points.
6192 % This is normally best if the curve direction changes relatively modestly
6193 % from point to point. For example, if the polyline would be convex, then
6194 % this smooth version would be pretty close to being convex. If the convex
6195 % polygon has several consecutive sides that are in the same direction,
6196 % all but the first and last of these segments in the smooth version would
6197 % be straight.
6198 % \begin{macrocode}
6199 vardef mksmooth (expr tens, cyclic) (suffix pts) =
6200 if pts = 1: onepointpath (cyclic, pts1)
6201 else:
6202 settension (_tn) tens; fixtension (_tn);
6203 pts1 if cyclic: {pts[2]-pts[pts]} fi
6204 for _i = 2 upto pts-1:
6205 ..tension _tn..pts[_i]{pts[_i+1]-pts[_i-1]}
6206 endfor
6207 ..tension _tn..pts[pts]
6208 if cyclic: {pts[1]-pts[pts-1]}..tension _tn..cycle fi
6209 fi
6210 enddef;
6211
6212 % \end{macrocode}
6213 %
6214 % \DescribeRoutine{mktenser}
6215 % This is just like \gbc{mksmooth}, except the tension value is preceded
6216 % by \mfc{atleast}. At this writing only \gbc{mkconvex} uses it (as a
6217 % fallback when there are three or fewer points to connect).
6218 % \begin{macrocode}
6219 vardef mktenser (expr tens, cyclic) (suffix pts) =
6220 if pts = 1: onepointpath (cyclic, pts1)
6221 else:
6222 settension (_tn) tens; fixtension (_tn);
6223 pts1 if cyclic: {pts[2]-pts[pts]} fi
6224 for _i = 2 upto pts-1:
6225 ..tension atleast _tn..pts[_i]{pts[_i+1]-pts[_i-1]}
6226 endfor
6227 ..tension atleast _tn..pts[pts]
6228 if cyclic: {pts[1]-pts[pts-1]}..tension atleast _tn..cycle fi
6229 fi
6230 enddef;
6231
6232 % \end{macrocode}
6233 %
6234 % \DescribeRoutine{mkconvex}
6235 % This could have been very much like \gbc{mksmooth}, using
6236 % \mfc{tension atleast} instead of \mfc{tension} (i.e., exactly
6237 % \gbc{mktenser} above). Unfortunately This destroys smoothness at the
6238 % beginning and end of any sequence of three or more points that lie on a
6239 % straight line. Some geometric situations absolutely prevent smoothness,
6240 % but this certainly isn't one of them. Two consecutive points
6241 % identical isn't either, but it does. We let the user or calling command
6242 % arrange for it not to happen (for example, using \gbc{setuniquepairs}
6243 % instead of \gbc{setpairs}.
6244 %
6245 % What we do is weight the direction to be used at each point by how flat
6246 % the polygon is on the two sides of each point, the flatter side
6247 % getting the most weight. If a point is collinear with the next two,
6248 % the flatness is infinite and the curve is forced in that direction. We
6249 % measure the flatness using the square root of the area of the triangle
6250 % made by the given point and the the next two points. Those three points
6251 % lie on a line just when the area is $0$. Using this measure of flatness
6252 % can be disputed (two triangles can be equally flat in terms of angles
6253 % but different in terms of areas), but it has the advantage that if the
6254 % points are subjected to an affine transformation, the weighting is
6255 % unchanged and the constructed direction vectors transform the same way.
6256 % Of course, this is also true of other measures. I've tested only
6257 % the square root of area and it works well for simple cases.
6258 %
6259 % The only way to ensure that the whole path transforms the same as the
6260 % points is to explicitly calculate the controls (in a manner that
6261 % transforms the same way as the points). I will do this if I can figure
6262 % out how it \emph{should} be done. It appears to be a convex programing
6263 % problem.
6264 %
6265 % The end segments of a noncycle are problematic. One could argue that
6266 % this command doesn't apply to noncycles and just truncate the cyclic
6267 % path. I decided to treat them specially and hope the result is useful.
6268 % \begin{macrocode}
6269 vardef mkconvex (expr tens, cyclic) (suffix pts) =
6270 save _B, _d, _tmp; pair _d[];
6271 settension (_tn) tens; fixtension (_tn);
6272 if pts < 4: mktenser (_tn, cyclic) (pts)
6273 else:
6274 for _j = 2 upto pts - 1:
6275 _B[_j] := sqrt(abs((pts[_j]-pts[_j-1])xprod(pts[_j+1]-pts[_j])));
6276 endfor
6277 if cyclic:
6278 _B1 := sqrt(abs((pts1 - pts[pts])xprod(pts2 - pts1)));
6279 _B[pts] := sqrt(abs((pts[pts]-pts[pts-1])xprod(pts1 - pts[pts])));
6280 else:
6281 _B1 := _B2;
6282 _B[pts] := _B[pts-1];
6283 fi
6284 for _j = 2 upto pts - 1:
6285 _tmp := _B[_j-1] + _B[_j+1];
6286 _d[_j] :=
6287 if _tmp = 0: origin % signal to use curl1
6288 else:
6289 ( _B[_j+1]*(pts[_j] - pts[_j-1]) +
6290 _B[_j-1]*(pts[_j+1] - pts[_j]) )/_tmp
6291 fi;
6292 endfor
6293 if cyclic:
6294 _tmp := _B[pts] + _B2;
6295 _d1 :=
6296 if _tmp = 0: origin
6297 else:
6298 (_B2*(pts1 - pts[pts]) + _B[pts]*(pts2 - pts1))/_tmp
6299 fi;
6300 _tmp := _B[pts-1] + _B1;
6301 _d[pts] :=
6302 if _tmp = 0: origin
6303 else:
6304 ( _B1*(pts[pts] - pts[pts-1]) +
6305 _B[pts-1]*(pts1 - pts[pts]) )/_tmp
6306 fi;
6307 else:
6308 _d1 := origin; _d[pts] := origin;
6309 fi
6310 pts1
6311 for _j = 1 upto pts-1:
6312 {if _d[_j] = origin: curl1 else: _d[_j] fi}
6313 ..tension atleast _tn..pts[_j+1]
6314 endfor
6315 {if _d[pts] = origin: curl1 else: _d[pts] fi}
6316 if cyclic: ..tension atleast _tn..cycle fi
6317 fi
6318 enddef;
6319
6320 % \end{macrocode}
6321 %
6322 % The old \cs{curve} command in \mfpic{} permitted no tension parameter
6323 % and wrote a \grafbase{} \gbc{curve} command.
6324 % \DescribeRoutine{curve}
6325 % For backward compatibility we keep that name, but simply call the
6326 % \gbc{tcurve} command with the default value for tension.
6327 % \DescribeRoutine{tcurve}
6328 % \gbc{tcurve} converts a list of pairs to an array, then calls
6329 % \gbc{mksmooth} on the array.
6330 %
6331 % The next pair call \gbc{mkconvex}, which tries to produce a convex curve
6332 % when the points form a convex polygon.
6333 % \DescribeRoutine{ccurve}
6334 % The first, \gbc{ccurve}, merely calls the second with a default texnsion,
6335 % while
6336 % \DescribeRoutine{tccurve}
6337 % creates an array from the list of pairs and calls \gbc{mkconvex} on it.
6338 % \begin{macrocode}
6339 numeric default_tension; default_tension := 1;
6340 def curve = tcurve (default_tension) enddef;
6341 vardef tcurve (expr tens, cyclic) (text t) =
6342 setpairs (_tc) (t);
6343 if _tc=0: NoPoints("curve", _tc); fi
6344 mksmooth (tens, cyclic, _tc)
6345 enddef;
6346
6347 def ccurve = tccurve (default_tension) enddef;
6348 vardef tccurve (expr tens, cyclic) (text t) =
6349 setuniquepairs (_tcc) (t);
6350 if _tcc=0: NoPoints("ccurve", _tcc); fi
6351 mkconvex (tens, cyclic, _tcc)
6352 enddef;
6353
6354 % \end{macrocode}
6355 %
6356 % It seemed odd that we had no way for an \MF-savvy user to easily get
6357 % the standard \mfc{p..q..r} kind of path. For such a simple one,
6358 % \cs{mfobj} with the explicit path expression would work, but when one
6359 % has to add a tension to it, it is nice to have an abbreviation. That's
6360 % what these are for.
6361 %
6362 % \DescribeRoutine{mkbezier}
6363 % The command \gbc{mkbezier} takes an array argument and produces either
6364 % an open or cyclic path with a given tension.
6365 % \DescribeRoutine{bezier}
6366 % The macro \gbc{bezier} does nothing more than call \gbc{tbezier} with
6367 % the default tension,
6368 % \DescribeRoutine{tbezier}
6369 % which takes a list of points and creates an array for \gbc{mkbezier} to
6370 % act on.
6371 % \begin{macrocode}
6372 vardef mkbezier (expr tens, cyclic) (suffix pts) =
6373 settension (_tn) tens; fixtension (_tn);
6374 pts1
6375 for _i = 2 upto pts: ..tension _tn..pts[_i] endfor
6376 if cyclic: ..tension _tn..cycle else: {0,0} fi
6377 enddef;
6378
6379 def bezier = tbezier (default_tension) enddef;
6380 vardef tbezier (expr tens, cyclic) (text t) =
6381 setpairs (_tbs) (t);
6382 if _tbs=0: NoPoints ("bezier", _tbs); fi
6383 mkbezier (tens, cyclic) (_tbs)
6384 enddef;
6385
6386 % \end{macrocode}
6387 %
6388 % It also seemed we ought to allow \mfpic{} users to easily reproduce the
6389 % effect of a sequence of \LaTeX's \cs{qbezier} commands. That's what
6390 % these next are for.
6391 %
6392 % These commands and the various splines below don't use tension as they
6393 % have their control points explicitly given, not computed from the
6394 % tension value by \MF. The \gbc{qbezier} command does not produce a
6395 % smooth path unless the controls are explicitely chosen for that. The
6396 % spline commands will almost always produce a smooth path.
6397 %
6398 % \DescribeRoutine{mkqbezier}
6399 % \gbc{mkqbezier} requires an even number of points for a cyclic path,
6400 % an odd number for a noncyclic path. It does not check for this, but
6401 % the calling macro \gbc{qbezier} does. If the parity is incorrect, it
6402 % repeats the last point in the list. This has the effect of making
6403 % the last link a straight line.
6404 %
6405 % \DescribeRoutine{qbezier}
6406 % The \gbc{qbezier} command takes a list of points and creates an array
6407 % from then before calling \gbc{mkqbezier}.
6408 %
6409 % \DescribeRoutine{mkcbezier}
6410 % This is like \gbc{mkqbezier}, but needs a multiple of 3 for a closed
6411 % cubic bezier, one more (the endpoint) for an open cubic bezier.
6412 %
6413 % \DescribeRoutine{cbezier}
6414 % Like \gbc{qbezier}, but calls \gbc{mkcbezier}.
6415 % \begin{macrocode}
6416 vardef mkqbezier (expr cyclic) (suffix pts) =
6417 pts1
6418 if pts=1: {0,0}
6419 else:
6420 for _i = 2 step 2 until pts - 1:
6421 ..controls 1/3[pts[_i], pts[_i-1]]
6422 and 1/3[pts[_i], pts[_i+1]].. pts[_i+1]
6423 endfor
6424 if cyclic:
6425 ..controls 1/3[ pts[pts], pts[pts - 1] ]
6426 and 1/3[ pts[pts], pts1 ]..cycle
6427 fi
6428 fi
6429 enddef;
6430
6431 vardef qbezier (expr cyclic) (text t) =
6432 setpairs (_qbz) (t);
6433 if _qbz=0: NoPoints ("qbezier", _qbz);
6434 else:
6435 if (cyclic and odd _qbz) or (not cyclic and even _qbz):
6436 _qbz[incr _qbz] := _qbz[_qbz-1];
6437 fi
6438 mkqbezier (cyclic) (_qbz)
6439 fi
6440 enddef;
6441
6442 vardef mkcbezier (expr cyclic) (suffix pts) =
6443 pts1
6444 if pts=1: {0,0}
6445 else:
6446 for _i = 1 step 3 until pts - 3:
6447 ..controls pts[_i+1] and pts[_i+2] .. pts[_i+3]
6448 endfor
6449 if cyclic:
6450 ..controls pts[pts - 1] and pts[pts]..cycle
6451 fi
6452 fi
6453 enddef;
6454
6455 vardef cbezier (expr cyclic) (text t) =
6456 setpairs (_cbz) (t);
6457 if _cbz=0: NoPoints ("qbezier", _cbz);
6458 else:
6459 % Need 0 mod 3 for cyclic, otherwise 1 mod 3
6460 setnumeric (_mdt) _cbz mod 3;
6461 if cyclic:
6462 if _mdt <> 0: _cbz[incr _cbz] := _cbz[_cbz-1]; fi
6463 if _mdt = 1 : _cbz[incr _cbz] := _cbz1; fi
6464 else: % need 1 more, duplicate next to last
6465 if _mdt = 0:
6466 _cbz := _cbz + 1;
6467 _cbz[_cbz] := _cbz[_cbz-1];
6468 _cbz[_cbz-1] := _cbz[_cbz-2];
6469 fi
6470 if _mdt = 2: % need 2 more, duplicate last 2.
6471 _cbz := _cbz + 2; % add 2 slots
6472 _cbz[_cbz] := _cbz[_cbz-2]; % fill them
6473 _cbz[_cbz-1] := _cbz[_cbz-2]; % with last node
6474 _cbz[_cbz-2] := _cbz[_cbz-3]; % orig last slot = orig previous.
6475 fi
6476 fi
6477 mkcbezier (cyclic) (_cbz)
6478 fi
6479 enddef;
6480
6481 % \end{macrocode}
6482 %
6483 % When calling \gbc{curve} or \gbc{tcurve} there can be a problem
6484 % with the resulting path: even with high tension one is not guaranteed
6485 % that a sequence of points with increasing $x$-coordinate will produce a
6486 % path with increasing $x$-coordinate. The \gbc{fcnspline} command will do
6487 % what we want, but we have no control over the path, apart from the
6488 % equations at the ends.
6489 %
6490 % The requirement to guarantee that a path have increasing $x$-coordinates
6491 % is that the control points of the segment connecting
6492 % $(x\sb{j}, y\sb{j})$ to the next $(x\sb{j+1}, y\sb{j+1})$ have their
6493 % $x$-part in the interval $x\sb{j} < x < x\sb{j+1}$.
6494 %
6495 % Therefore, if we wish to plot a curve connecting points with increasing
6496 % $x$-coordinates and believe that the resulting path should be the graph
6497 % of a function, we pretty much have to select the control points
6498 % ourselves. By default we choose the two controls so the \mfc{xpart}s
6499 % divide the $x$-interval into three equal parts. This makes the B\'ezier
6500 % $f(t)$ linear in the $x$-part and so has the added `advantage' that in
6501 % each segment, $y$ is a cubic function of $x$. It is not a spline, as
6502 % the computation of the controls uses only the two nearest points, plus
6503 % we allow them to be modified by an additional parameter.
6504 %
6505 % Another concern is what direction to place the controls. In
6506 % \gbc{mksmooth} we ask the direction at a given point to be the average
6507 % of the straight line directions to adjacent points. We do the same
6508 % here, though it is not clear if this is best.
6509 %
6510 % Finally, we permit a tension of sorts by dividing the distance to the
6511 % controls by a parameter normally equal to \gbc{default_tension}.
6512 %
6513 % \DescribeRoutine{fcncontrol}
6514 % This computes the control point for the points on the path, following
6515 % the above description. If by chance some $x$ interval is zero, we
6516 % make the controls equal to the nodes, which gives a straight vertical
6517 % (the $y$ values differ because we use \gbc{setuniquepairs}. This also
6518 % abandons smoothness there.
6519 %
6520 % The method selecting the controls is new with \mfpic{} version 0.8.
6521 % Following discussions with Stephan Hennig in \texttt{comp.text.tex} I
6522 % came to the conclusion that the method used ought to satisfy the
6523 % following: if the data are xscaled or yscaled, the control vectors ought
6524 % to scale the same way. The current version does that, the previous one
6525 % did not.
6526 %
6527 % \DescribeRoutine{mkfcnpath}
6528 % This produces the path, calling \gbc{fcncontrol} to produce the controls.
6529 %
6530 % \DescribeRoutine{fcncurve}
6531 % This is the \mfpic{} interface; \gbc{fcncurve} calls \gbc{functioncurve}
6532 % with the default tension, and
6533 % \DescribeRoutine{functioncurve}
6534 % then takes a list of points, converts it to an array, and calls
6535 % \gbc{mkfcnpath} to build the path.
6536 % \begin{macrocode}
6537 vardef fcncontrol (expr ftens, X, Y, Z) =
6538 Y if (xpart(Z-Y) <> 0) and (xpart(Y-X) <> 0):
6539 + xpart(Z-Y)/3/xpart(Z-X)*(Z - X)/ftens fi
6540 enddef;
6541
6542 vardef mkfcnpath (expr ftens) (suffix q) =
6543 settension (_tn) ftens;
6544 if _tn <= 0: _tn := 1; fi
6545 for _i = 1 upto q - 1:
6546 q[_i]..controls fcncontrol (_tn) (q[_i-1], q[_i], q[_i+1])
6547 and fcncontrol (_tn) (q[_i+2], q[_i+1], q[_i])..
6548 endfor
6549 q[q]{0,0}
6550 enddef;
6551
6552 def fcncurve = functioncurve (default_tension) enddef;
6553 def tfcncurve = functioncurve enddef;
6554 vardef functioncurve (expr ftens) (text t) =
6555 settension (_ftens) ftens; if _ftens < 1/3: _ftens := 1/3; fi
6556 setuniquepairs (_fc) (t);
6557 if _fc=0: NoPoints ("functioncurve", _fc); fi
6558 if _fc > 1: _fc0 := _fc1; _fc[_fc+1] := _fc[_fc]; fi
6559 mkfcnpath (_ftens) (_fc)
6560 enddef;
6561
6562 % \end{macrocode}
6563 %
6564 %
6565 % \subsection{Splines with explicit controls}\label{splines}
6566 %
6567 % For these quadratic B-splines, a list of pairs representing the control
6568 % points must be given. The nodes of the path and the cubic Bezi\'er
6569 % controls required to produce a quadratic B-spline are computed. The
6570 % nodes are just half way between the one control point and the next.
6571 %
6572 % \DescribeRoutine{openqbs}
6573 % For simplicity, the list is converted to an array \gbc{_oq} first. In
6574 % the closed version
6575 % \DescribeRoutine{closedqbs}
6576 % additional array elements are created at the end, repeating two of the
6577 % beginning elements. Finally,
6578 % \DescribeRoutine{mkqbs}
6579 % \gbc{mkqbs} is called. This draws an open spline based on the points in
6580 % an array \gbc{b}. The additional array elements defined by
6581 % \gbc{closedqbs} cause the resulting path to end where it began and a
6582 % simple \mfc{\&cycle} closes it.
6583 %
6584 % \DescribeRoutine{qspline}
6585 % The \mfpic{} commands \cs{qspline} and \cs{closedqspline} now call
6586 % \gbc{qspline} with appropriate boolean, for consistency with other
6587 % commands that have the same argument structure. The commands
6588 % \gbc{openqbs}, and \gbc{closedqbs} are no longer needed, but are kept
6589 % for backward compatability. The most efficient setup would be to give
6590 % \gbc{mkqbs} a boolean argument, but that could break old files.
6591 % \begin{macrocode}
6592 def openqbs = qspline (false) enddef;
6593 def closedqbs = qspline (true) enddef;
6594
6595 vardef mkqbs (suffix b) =
6596 0.5[ b1, b2]
6597 if b<3: {0,0}
6598 else:
6599 for _i = 2 upto b-1:
6600 ..controls 1/6[ b[_i], b[_i-1] ] and 1/6[ b[_i], b[_i+1] ]..
6601 0.5[ b[_i], b[_i+1] ]
6602 endfor
6603 fi
6604 enddef;
6605
6606 vardef qspline (expr cyclic) (text t) =
6607 setpairs (_qs) (t);
6608 if _qs=0: NoPoints ("qspline", _qs); fi
6609 if _qs=1: _qs[incr _qs] := _qs1; fi
6610 if cyclic:
6611 _qs[incr _qs] := _qs1; _qs[incr _qs] := _qs2;
6612 fi
6613 mkqbs (_qs) if cyclic: & cycle fi
6614 enddef;
6615
6616 % \end{macrocode}
6617 %
6618 % These cubic B-splines also require a list of `control' points. Each of
6619 % the points $Q$, combined with the next one $Q'$, determine two more
6620 % points that divide the segment from $Q$ to $Q'$ into thirds. These new
6621 % points become the two control points of a \MF{} B\'ezier segment. The
6622 % nodes of these segments are half way between the second control of one
6623 % segment and the first control of the next.
6624 %
6625 % \DescribeRoutine{mkcbs}
6626 % The main code is in \gbc{mkcbs}, which results in an open curve. For
6627 % backward compatibility, the alias
6628 % \DescribeRoutine{mkopencbs}
6629 % \gbc{mkopencbs} is supplied.
6630 %
6631 % \DescribeRoutine{mkclosedcbs}
6632 % Earlier versions of \gbc{mkclosedcbs} would partly redefine its suffix
6633 % parameter (for example, using \gbc{b[incr b]:=b1}. I decided this
6634 % shouldn't change the array variable (imagine using two such functions on
6635 % the same array). Now the code has been rearranged so the cubic case is
6636 % handled just like the quadratic. We retain \gbc{mkclosedcbs} only for
6637 % backward compatibility.
6638 %
6639 % \DescribeRoutine{opencbs}
6640 % These are the versions taking a list of points instead of an array name.
6641 % They create a temporary array and call \gbc{mkcbs}, with
6642 % \DescribeRoutine{closedcbs}
6643 % \gbc{closedcbs} extending the array, just like the quadratic versions.
6644 %
6645 % \DescribeRoutine{cspline}
6646 % The \mfpic{} commands \cs{cspline} and \cs{closedcspline} now call
6647 % \gbc{cspline} with appropriate boolean, for consistency with other
6648 % commands that have the same argument structure. The commands
6649 % \gbc{mkopencbs}, \gbc{opencbs}, and \gbc{closedcbs} are no longer
6650 % needed, but are kept for backward compatability. The most efficient
6651 % setup would be to give \gbc{mkcbs} a boolean argument, but that could
6652 % break old files.
6653 % \begin{macrocode}
6654 vardef mkcbs (suffix b) =
6655 (b[1]+4b[2]+b[3])/6
6656 if b < 4: {0,0}
6657 else:
6658 for _i = 3 upto b-1:
6659 ..controls 1/3[ b[_i-1], b[_i] ] and 1/3[ b[_i], b[_i-1] ]
6660 .. (b[_i-1] + 4b[_i] + b[_i+1])/6
6661 endfor
6662 fi
6663 enddef;
6664
6665 def mkopencbs = mkcbs enddef;
6666 vardef mkclosedcbs (suffix b) =
6667 mkcbs (b) & opencbs (b[b-2],b[b-1],b[b], b1, b2, b3) & cycle
6668 enddef;
6669
6670 def opencbs = cspline (false) enddef;
6671 def closedcbs = cspline (true) enddef;
6672
6673 vardef cspline (expr cyclic) (text t) =
6674 setpairs (_cs) (t);
6675 if _cs=0: NoPoints ("cspline", _cs); fi
6676 for _idx = _cs upto 2: _cs[incr _cs] := _cs[_idx]; endfor
6677 if cyclic:
6678 for _idx = 1 upto 3: _cs[incr _cs] := _cs[_idx]; endfor
6679 fi
6680 mkcbs (_cs) if cyclic: & cycle fi
6681 enddef;
6682
6683 % \end{macrocode}
6684 %
6685 %
6686 % \subsection{Splines with computed controls}\label{computedsplines}
6687 %
6688 % A cubic spline through a set of points is a curve obtained by joining
6689 % each point to the next with a cubic parametrized curve, where adjoining
6690 % cubics must have matching first and second derivative at their common
6691 % point. In the previous section's \gbc{mkcbs}, the control points must be
6692 % supplied, it being up to the user to arrange (if necessary) that the
6693 % spline produced passes through given points. If, instead, these points
6694 % are given, it is possible to compute the necessary controls.
6695 % Unfortunately, the controls are not uniquely determined unless the curve
6696 % is required to be closed. For open curves, there is need for two
6697 % additional conditions at the end points. A `relaxed spline' is produced
6698 % if we require that the second derivative is $0$ at those points.
6699 %
6700 % For a closed curve, the equality of the first and second derivatives at
6701 % the common beginning/ending point gives the needed additional equations.
6702 %
6703 % Note that this equates \emph{time} derivatives, so this works best when
6704 % points are relatively evenly spaced and so the speed is relatively
6705 % uniform. If points are differently spaced then the relatively slower
6706 % speed between closely spaced points allows sharper turns without large
6707 % second derivatives. Curves produced tend to have a more natural look,
6708 % and relaxed splines are most suitable for smoothing data that is
6709 % obtained by taking observations at evenly space times. Still, the
6710 % technique is somewhat unstable when points are closely spaced, for
6711 % example when a small change in the position of one point can produce a
6712 % large change in its direction when viewed from another point.
6713 %
6714 % \DescribeRoutine{init_spline_eqns}
6715 % In this command we generate the equations common to all cubic
6716 % splines: the equality of derivatives at all interior points.
6717 % This command accepts a suffix \gbc{pts}, which is the array of points
6718 % to be connected. It initializes the variables \gbc{_spl_pre[\,]} and
6719 % \gbc{_spl_post[\,]} to unknown arrays of pairs. These will hold the
6720 % control points.
6721 %
6722 % \DescribeRoutine{closed_spline_eqns}
6723 % The next two macros contain the additional equations: for a closed
6724 % spline these are the same as the interior equation, but at the first and
6725 % last point in the array.
6726 % \DescribeRoutine{relaxed_spline_eqns}
6727 % For relaxed splines they force the second derivative to be 0 at the
6728 % first and last point.
6729 %
6730 % The macro \gbc{mksplinepath} simply assembles the previously computed
6731 % points and controls into a path.
6732 %
6733 % \DescribeRoutine{mkspline}
6734 % The macro \gbc{mkspline} issues the common equations and then either the
6735 % closed equations (\gbc{closed = true}) or the relaxed equations
6736 % (\gbc{closed = false}), before calling \gbc{mksplinepath}.
6737 %
6738 % The knowledgeable user can call \gbc{init_spline_eqns}, append any
6739 % choice of equations for the end segments, and then call
6740 % \gbc{mksplinepath~(false)} to produce any sort of open spline.
6741 %
6742 % \DescribeRoutine{dospline}
6743 % This version accepts a list of pairs and produces a spline through
6744 % them. It simply stores the list in an array and calls the appropriate
6745 % version that operates on an array. This is the command passed by \mfpic{}.
6746 % \begin{macrocode}
6747 def init_spline_eqns (suffix pts) =
6748 save _spl_pre, _spl_post;
6749 pair _spl_pre[], _spl_post[];
6750 for j= 2 upto pts - 1:
6751 _spl_post[j] + _spl_pre[j] = 2pts[j];
6752 _spl_pre[j+1]+2_spl_pre[j] = 2_spl_post[j]+_spl_post[j-1];
6753 endfor
6754 enddef;
6755
6756 def closed_spline_eqns (suffix pts) =
6757 _spl_post1 + _spl_pre1 = 2pts1;
6758 _spl_post[pts] + _spl_pre[pts] = 2pts[pts];
6759 _spl_pre2 + 2_spl_pre1 = 2_spl_post1 + _spl_post[pts];
6760 _spl_pre1+2_spl_pre[pts] = 2_spl_post[pts]+_spl_post[pts-1];
6761 enddef;
6762
6763 def relaxed_spline_eqns (suffix pts) =
6764 _spl_pre2 + pts1 = 2_spl_post1;
6765 pts[pts] + _spl_post[pts-1] = 2_spl_pre[pts];
6766 enddef;
6767
6768 vardef mksplinepath (expr closed) (suffix pts) =
6769 pts1..controls _spl_post1 and
6770 for j = 2 upto pts if not closed: -1 fi:
6771 _spl_pre[j]..pts[j]..controls _spl_post[j] and
6772 endfor
6773 if closed: _spl_pre1..cycle else: _spl_pre[pts]..pts[pts] fi
6774 enddef;
6775
6776 def mkspline (expr closed) (suffix pts) =
6777 init_spline_eqns (pts);
6778 if closed: closed_spline_eqns (pts);
6779 else: relaxed_spline_eqns (pts);
6780 fi
6781 mksplinepath (closed) (pts)
6782 enddef;
6783
6784 vardef dospline (expr closed) (text the_list) =
6785 setpairs (_sp) (the_list);
6786 if _sp=0: NoPoints ("dospline", _sp); fi
6787 if _sp=1: _sp[incr _sp] := _sp1; fi
6788 mkspline (closed) (_sp)
6789 enddef;
6790
6791 % \end{macrocode}
6792 %
6793 % The above computations produce a $2$-dimensional spline. A $1$-dimensional
6794 % cubic spline would be a function $f(t)$ with numeric values rather
6795 % than pair values. Such are often used to interpolate functions. That is,
6796 % given pairs $(x\sb j,y\sb{j})$, and assuming they lie on the graph of
6797 % some function (generally unknown), fill in the graph with $y = f(x)$
6798 % where $f$ is a cubic function of $x$ in each interval $x\sb j \le x
6799 % \le x\sb {j+1}$, making sure that the resulting graph is as smooth as
6800 % possible at the points $(x\sb j, y\sb j)$.
6801 %
6802 % The requirements on our $2$-dimensional path are the following:
6803 % \begin{enumerate}
6804 % \item The $j$th link should connect $(x\sb{j},y\sb{j})$ to $(x\sb{j+1},
6805 % y\sb{j+1})$.
6806 % \item The $x$-part of that link should increase linearly from $x\sb{j}$ to
6807 % $x\sb{j+1}$ as $t$ goes from $0$ to $1$.
6808 % \item The $y$-part should be a cubic $y = f(x)$.
6809 % \item The $x$-derivatives $df/dx$ and $d^2f/dx^2$ should match at the
6810 % connecting points.
6811 % \end{enumerate}
6812 %
6813 % Two necessary equations for converting between $x$ and $t$ coordinates
6814 % are:
6815 % \begin{equation}\label{first}
6816 % x = x\sb{j} + t \Delta x\sb{j}
6817 % \end{equation}
6818 % (where $\Delta x\sb{j} = x\sb{j+1} - x\sb{j}$) and
6819 % \begin{equation}\label{second}
6820 % \frac{df}{dt} = \frac{dx}{dt}\frac{df}{dx} =
6821 % \Delta x\sb{j} \frac{df}{dx}.
6822 % \end{equation}
6823 % Thus we want to choose controls so that (\ref{first}) is maintained and
6824 % so that $x$-derivatives match. It turns out that this requires controls
6825 % at
6826 % \begin{equation}
6827 % \begin{array}{c}
6828 % (x\sb{j}, y\sb{j}) - (\Delta x\sb{j-1}, s\sb{j} \Delta x\sb{j-1})/3\\
6829 % (x\sb{j}, y\sb{j}) + (\Delta x\sb{j} , s\sb{j} \Delta x\sb{j} )/3
6830 % \end{array}
6831 % \end{equation}
6832 % where $s\sb{j}$ is the slope (derivative) at $x\sb{j}$. This provides
6833 % matching first derivatives automatically (equation (\ref{second})) and
6834 % also (\ref{first}). To get matching second derivatives we need the same
6835 % conditions as in parametric splines. We use these equations simplified to
6836 % the form:
6837 % \begin{displaymath}
6838 % s\sb{j+1} \Delta x\sb{j} - 2s\sb{j} (\Delta x\sb{j} +
6839 % \Delta x\sb{j-1}) + s\sb{j-1}\Delta x\sb{j-1}
6840 % = 3y\sb{j+1} - 3y\sb{j-1}.
6841 % \end{displaymath}
6842 % There can be almost any equations at the end points. For a relaxed
6843 % spline we equate the second derivatives to 0. To get a periodic
6844 % function, we equate the slope and second derivative at beginning to
6845 % those at the end. This makes it possible to put a shifted copy of the
6846 % graph with starting point at the end of the original and have the same
6847 % smoothness at that connection as at the other points.
6848 %
6849 % \DescribeRoutine{init_fcnspl_eqns}
6850 % This declares the temporary arrays \gbc{_dx[\,]} (the set of $dx\sb j$)
6851 % and \gbc{_sl[\,]} (the desired slopes) and issues the common equations.
6852 % The parameter \gbc{pts} is the array of $(x,y)$ values.
6853 %
6854 % \DescribeRoutine{periodic_fcnspl_eqns}
6855 % For the periodic case we use \gbc{periodic_fcnspl_eqns} to generate the
6856 % additional equations and for the
6857 % \DescribeRoutine{relaxed_fcnspl_eqns}
6858 % relaxed case we use \gbc{relaxed_fcnspl_eqns}. As before, one can
6859 % produce custom splines by issuing the common equations and then ones own
6860 % equations.
6861 %
6862 % \DescribeRoutine{mkfcnsplpath}
6863 % Then we assemble the path from the computed information by calling the
6864 % command \gbc{mkfcnsplpath}.
6865 %
6866 % \DescribeRoutine{mkfcnspline}
6867 % These commands emits the appropriate equations then assemble the path.
6868 % The if the first parameter is true it uses the periodic equations,
6869 % otherwise the relaxed equations.
6870 %
6871 % \DescribeRoutine{fcnspline}
6872 % Finally, this command is the one written by \mfpic{}. It copies a list
6873 % of pairs into an array and calls the appropriate command to process
6874 % them.
6875 % \begin{macrocode}
6876 def init_fcnspl_eqns (suffix pts) =
6877 save _dx, _sl; numeric _dx[], _sl[];
6878 _dx1 := xpart (pts2 - pts1);
6879 for j = 2 upto pts - 1:
6880 _dx[j] := xpart (pts[j+1] - pts[j]);
6881 _sl[j + 1]*_dx[j] + _sl[j-1]*_dx[j-1] + 2_sl[j]*(_dx[j] + _dx[j-1])
6882 = 3*ypart(pts[j+1] - pts[j-1]);
6883 endfor
6884 enddef;
6885
6886 def periodic_fcnspl_eqns (suffix pts) =
6887 _sl1 = _sl[pts];
6888 _sl2*_dx1 + 2_sl1*_dx1 + 2_sl[pts]*_dx[pts-1] + _sl[pts-1]*_dx[pts-1]
6889 = 3 * ypart (pts[2] - pts[pts-1]);
6890 enddef;
6891
6892 def relaxed_fcnspl_eqns (suffix pts) =
6893 _sl2*_dx1 + 2_sl1*_dx1 = 3 * ypart(pts2 - pts1);
6894 _sl[pts-1]*_dx[pts-1] + 2_sl[pts]*_dx[pts-1]
6895 = 3 * ypart(pts[pts] - pts[pts-1]);
6896 enddef;
6897
6898 vardef mkfcnsplpath (suffix pts) =
6899 pts1..controls (pts1 + (1, _sl1)/3*_dx1) and
6900 for j = 2 upto pts - 1:
6901 (pts[j] - (1, _sl[j])/3*_dx[j-1]) ..pts[j]..
6902 controls (pts[j] + (1,_sl[j])/3*_dx[j]) and
6903 endfor
6904 (pts[pts] - (1,_sl[pts])*_dx[pts-1]/3)..pts[pts]
6905 enddef;
6906
6907 vardef mkfcnspline (expr periodic) (suffix pts) =
6908 init_fcnspl_eqns (pts);
6909 if periodic: periodic_fcnspl_eqns (pts);
6910 else: relaxed_fcnspl_eqns (pts);
6911 fi
6912 mkfcnsplpath (pts)
6913 enddef;
6914
6915 vardef fcnspline (expr periodic) (text the_list) =
6916 setpairs (_fs) (the_list);
6917 if _fs<2:
6918 if _fs=0: NoPoints ("fcnspline", _fs); fi
6919 onepointpath (false, _fs1)
6920 else:
6921 mkfcnspline (periodic) (_fs)
6922 fi
6923 enddef;
6924
6925 % \end{macrocode}
6926 %
6927 %
6928 % \subsection{Arcs, circles and ellipses}\label{arcs}
6929 %
6930 % We have multiple commands that generate circular arcs, differing in
6931 % how the arc is specified. All are (in part) based on the following
6932 % \gbc{mkarc}. However, perfectly reasonable arcs can have centers so far
6933 % away that requiring the center among the parameters can cause numeric
6934 % overflow.
6935 %
6936 % I'd like to use some scheme that avoids this. It is possible, given
6937 % three reasonably spaced points on an arc with angle less than 90
6938 % degrees between each, to draw the arc without finding the center.
6939 % However, I am not sure how to reduce any given format to this
6940 % information
6941 %
6942 % Another problem is that of accuracy. If the angle is small, accuracy is
6943 % not usually a problem, but if an angle is close to 360, and the
6944 % endpoints are known, then finding the center (or finding other points on
6945 % the arc without knowing the center) is unstable.
6946 %
6947 % There is really no problem with \gbc{mkarc} itself: if you can express
6948 % both \gbc{center} and \gbc{begpt} in \MF, then the other values on the
6949 % arc should normally be no problem. (Of course, if the radius is near
6950 % \mfc{infinity}, there could be points on the arc with coordinates near
6951 % \mfc{2infinity}, causing overflow in \MF{}. One hopes this is rare.)
6952 %
6953 % Care has been taken that changing the sign of various parameters
6954 % produces reasonable results. And there should be no more problem for
6955 % arcs with sweep larger than 360 degrees than with less.
6956 %
6957 % \DescribeRoutine{mkarc}
6958 % This takes the center, starting and ending point (pair expressions) and
6959 % the angle, and returns the arc defined pretty much the way \file{plain.mf}
6960 % defines \mfc{quartercircle}.
6961 %
6962 % It would be easier to do something like we frequently do with
6963 % \mfc{fullcircle}: make an arc of unit radius, and then rotate, scale
6964 % and shift it into place. However, I would like to accomplish at least
6965 % the following: if an endpoint of the arc is among the parameters, or is
6966 % straightforwardly implied by them, then the corresponding endpoint of
6967 % the path created should test equal to that point. Shifting works OK, but
6968 % scaling and rotating cause roundoff differences.
6969 %
6970 % Note that \gbc{mkarc} has parameters that may over-determine the arc.
6971 % It is only called by arc-making commands that have calculated these
6972 % parameters and, I hope, ensured they are compatible. \gbc{mkarc}'s job
6973 % is mainly to ensure that the arc begins at \gbc{begpt} and ends at
6974 % \gbc{endpt} (exactly). A \gbc{sweep} of $0$ is actually incompatible
6975 % with any case where \gbc{begpt<>endpt} unless \gbc{center} is
6976 % literally at $\infty$, but we allow it even though I am pretty sure
6977 % the other arc commands all filter out that case.
6978 % \begin{macrocode}
6979 vardef mkarc (expr center, begpt, endpt, sweep) =
6980 if (sweep = 0): begpt--endpt
6981 else:
6982 setnumeric (n) ceiling (abs(sweep)/45);
6983 setpair (d) (begpt - center) rotated (signof (sweep) 90);
6984 begpt{d}
6985 for j = 1 upto n-1:
6986 ..(begpt rotatedabout (center, j/n*sweep)){d rotated (j/n*sweep)}
6987 endfor ..endpt{d rotated sweep}
6988 fi
6989 enddef;
6990
6991 % \end{macrocode}
6992 %
6993 % \DescribeRoutine{arc}
6994 % The most basic: center of circle, starting point of arc, and angle
6995 % subtended. Another name for \gbc{arc} is \gbc{arccps}, (``\gbc{cps}'' is
6996 % for ``center, point, sweep'').
6997 % \begin{macrocode}
6998 vardef arc (expr center, begpt, sweep) =
6999 if (center = begpt) or (sweep = 0): begpt--begpt
7000 else:
7001 mkarc (center, begpt, begpt rotatedabout (center, sweep), sweep)
7002 fi
7003 enddef;
7004 def arccps = arc enddef;
7005
7006 % \end{macrocode}
7007 %
7008 % \DescribeRoutine{arcpps}
7009 % In this form we are given two points and the angle of the arc between
7010 % them. If the points are equal or the sweep makes the arc undefined, we
7011 % return a line segment. If the sweep is less than 90 degrees we use the
7012 % idea from the code of \mfc{quartercircle}, except, when the sweep is
7013 % greater than 45 degrees we let \MF{} find the midpoint \gbc{m} of the
7014 % arc. Otherwise, we get the center \gbc{c} of the circle and call
7015 % \gbc{mkarc}.
7016 %
7017 % The code for finding \gbc{c} and \gbc{m} used to be separate commands,
7018 % \gbc{arccenter} and \gbc{midarc}. However, this is the only place we
7019 % used them and the several cases that they had to consider are reduced
7020 % because the \mfc{if} in this command takes care of some of them.
7021 %
7022 % The code for finding \gbc{m} uses the fact that the chord and the line
7023 % from one of its endpoints to the midpoint subtend a circular arc of
7024 % \gbc{sweep/2} and so the angle between them is half that, \gbc{sweep/4}.
7025 % The code gets the intersection between the line in that direction and
7026 % the perpendicular bisector of the chord.
7027 %
7028 % We find the center by intersecting two lines. One is the radius from
7029 % one end of the chord. Then we branch on two cases: if the chord is close
7030 % to a diameter, use its perpendicular bisector as the other line,
7031 % otherwise use the radius from the opposite end of the chord. Here
7032 % \gbc{cd} is a vector in the direction of the chord from \gbc{begpt} to
7033 % \gbc{endpt}. The angle \gbc{ang} is the amount we have to rotate
7034 % \gbc{cd} about \gbc{begpt} to make it point toward the center of the
7035 % circle. This gives the radius mentioned above.
7036 % \begin{macrocode}
7037 vardef arcpps (expr begpt, endpt, sweep) =
7038 if (begpt = endpt) or (sweep = 0): begpt--endpt
7039 else:
7040 setpair (cd) unitvector (endpt-begpt);
7041 if abs(sweep) <= 45:
7042 begpt{cd rotated (-sweep/2)}..endpt{cd rotated (sweep/2)}
7043 elseif abs(sweep) <= 90:
7044 save m; pair m;
7045 m = begpt + whatever*( cd rotated (-sweep/4));
7046 m = 0.5[begpt, endpt] + whatever*(cd rotated 90);
7047 begpt{cd rotated (-sweep/2)}..m{cd}..endpt{cd rotated (sweep/2)}
7048 else:
7049 setnumeric (ang) 90 - ((sweep/2) mod 180);
7050 if abs(ang) = 90:
7051 GBwarn "undefined arc. A line segment will be used instead.";
7052 begpt--endpt
7053 else:
7054 save c; pair c;
7055 c = begpt + whatever*(cd rotated ang);
7056 c = if abs(ang) < 30:
7057 (0.5)[begpt, endpt] + whatever*(cd rotated 90)
7058 else:
7059 endpt + whatever*(-cd rotated -ang)
7060 fi;
7061 mkarc (c, begpt, endpt, sweep)
7062 fi
7063 fi
7064 fi
7065 enddef;
7066
7067 % \end{macrocode}
7068 %
7069 % \DescribeRoutine{arcpp}
7070 % In the macro \gbc{arcpp}, two points and the radius of the circle are
7071 % given. Alone, this would determine two circles and therefore 4 arcs. We
7072 % reduce the possibilities to two by assuming the arc is anticlockwise
7073 % from the first point to the second if \gbc{rad} is positive, clockwise
7074 % if negative. Then \gbc{arcpp} produces the one that has absolute value
7075 % no more than 180 degrees if \gbc{small} is true, otherwise the other
7076 % one.
7077 % \DescribeRoutine{arcppr}
7078 % The macro \gbc{arcppr} is just \gbc{arcpp} with the boolean argument
7079 % \gbc{small} last (for compatibility with previous \mfpic{} versions).
7080 %
7081 % The code computes the angle of the arc and calls \gbc{arcpps}. If the
7082 % radius is not larger than half the distance between the points, we make
7083 % the angle $\pm 180$, which produces a half circle.
7084 % \begin{macrocode}
7085 vardef arcpp (expr small, begpt, endpt, rad) =
7086 save full, diam, chord, ang;
7087 full := signof (rad) 360;
7088 diam := 2rad;
7089 chord := abs(endpt-begpt);
7090 if chord < abs(diam):
7091 ang := if not small: full - fi 2*asin (chord/diam);
7092 else: ang := signof (rad) 180;
7093 fi
7094 arcpps (begpt, endpt, ang)
7095 enddef;
7096 def arcppr (expr begpt, endpt, rad, small) =
7097 arcpp (small, begpt, endpt, rad)
7098 enddef;
7099
7100 % \end{macrocode}
7101 %
7102 % \DescribeRoutine{arcplr}
7103 % This one takes the center and polar coordinates of the ends relative to
7104 % the center. We just call \gbc{mkarc} with the obviously computed
7105 % endpoints and sweep.
7106 % \begin{macrocode}
7107 vardef arcplr (expr center, frtheta, totheta, rad) =
7108 if rad = 0: center--center
7109 else:
7110 mkarc (center, center + rad*dir frtheta,
7111 center + rad*dir totheta, totheta - frtheta)
7112 fi
7113 enddef;
7114
7115 % \end{macrocode}
7116 %
7117 % \DescribeRoutine{arcalt}
7118 % This one is the same as above, but with the same argument order as
7119 % \gbc{sector}.
7120 % \begin{macrocode}
7121 vardef arcalt (expr center, radius, frtheta, totheta) =
7122 arcplr (center, frtheta, totheta, radius)
7123 enddef;
7124
7125 % \end{macrocode}
7126 %
7127 % \DescribeRoutine{arcppp}
7128 % This last one finds the arc connecting three points in the order given.
7129 % It works by calling \gbc{arcpps} twice, using first the sweep from
7130 % \gbc{first} to \gbc{second}, and then the sweep from \gbc{second} to
7131 % \gbc{third}. Each of these is twice the opposite angle of the triangle
7132 % formed from these points, and calculated by \gbc{cornerangle}.
7133 % \begin{macrocode}
7134 vardef arcppp (expr first, second, third) =
7135 arcpps (first, second, 2*cornerangle (third, first, second)) &
7136 arcpps (second, third, 2*cornerangle (first, second, third))
7137 enddef;
7138
7139 % \end{macrocode}
7140 %
7141 % \DescribeRoutine{ellipse}
7142 % We get an ellipse by xscaling and yscaling a unit circle, rotating it
7143 % and then shifting it into position. All parameters are coordinate
7144 % independent expressions, with obvious meaning (\gbc{center} is a pair, the
7145 % rest numeric). \gbc{circle} is similar, but we only scale and shift.
7146 %
7147 % If either radius is negative, the sense of the ellipse is reversed and
7148 % the starting point changes. If both are negative, only the starting
7149 % point changes.
7150 % \DescribeRoutine{circle}
7151 % \gbc{circle} acts like \gbc{ellipse} with both radii the same.
7152 % \begin{macrocode}
7153 vardef ellipse (expr center, radx, rady, angle) =
7154 fullcircle xscaled (2*radx) yscaled (2*rady) rotated angle
7155 shifted center
7156 enddef;
7157
7158 vardef circle (expr center, rad) =
7159 fullcircle scaled (2*rad) shifted center
7160 enddef;
7161
7162 % \end{macrocode}
7163 %
7164 % The next four implement different ways of specifying a circle.
7165 % \DescribeRoutine{circlecp}
7166 % The first, \gbc{circlecp}, produces the circle with a given center
7167 % passing through a given point.
7168 % \DescribeRoutine{circleppp}
7169 % The second, \gbc{circleppp}, produces the circle passing through three
7170 % given points.
7171 % \DescribeRoutine{circlepps}
7172 % The third, \gbc{circlepps}, produces the circle passing through two
7173 % given points in such a way that the arc from the first to the second has
7174 % a given angle.
7175 % \DescribeRoutine{circleppr}
7176 % The fourth, \gbc{circleppr}, produces the circle with the given radius
7177 % passing through the two points in such a way that the angle from the
7178 % first point to the second is between $0$ and $180$ degrees if the switch
7179 % \gbc{small} is true. If \gbc{small} is false, then the clockwise arc
7180 % from first to second is between $180$ and $360$. If \gbc{rad} is
7181 % negative, the circles switch and their orientation is reversed.
7182 % \DescribeRoutine{circlepp}
7183 % The last, \gbc{circlepp}, is just \gbc{circleppr} with a different order
7184 % of arguments (for previous \mfpic{} versions).
7185 %
7186 % These could be implemented by finding the center and radius and calling
7187 % \gbc{circle}. However, we call the arc commands so that those points
7188 % specified in the parameters that lie on the circle will be nodes of the
7189 % path produced, in the given order.
7190 % \begin{macrocode}
7191 vardef circlecp (expr center, point) =
7192 mkarc (center, point, point, 360) & cycle
7193 enddef;
7194
7195 vardef circleppp (expr one, two, three) =
7196 arcpps (one, two, 2*cornerangle (three, one, two))
7197 & arcpps (two, three, 2*cornerangle (one, two, three))
7198 & arcpps (three, one, 2*cornerangle (two, three, one))
7199 & cycle
7200 enddef;
7201
7202 vardef circlepps (expr one, two, sweep) =
7203 save ang, full;
7204 full := signof (sweep) 360;
7205 ang := sweep mod full;
7206 arcpps (one, two, ang) & arcpps (two, one, full - ang) & cycle
7207 enddef;
7208
7209 vardef circlepp (expr small, one, two, rad) =
7210 arcpp (small, one, two, rad) & arcpp (not small, two, one, rad)
7211 & cycle
7212 enddef;
7213
7214 def circleppr (expr one, two, rad, small) =
7215 circleppr (one, two, rad, small)
7216 enddef;
7217
7218 % \end{macrocode}
7219 %
7220 % Now we implement a different way to specify an ellipse, essentially
7221 % specifying it by a parallelogram in which it is to be inscribed.
7222 %
7223 % \DescribeRoutine{quarterellipse}
7224 % If an ellipse is inscribed in a parallelogram, tangent to all four
7225 % sides at the midpoints, this command produces one ``corner'' of that
7226 % ellipse. The arguments \mfc{A} and \mfc{C} are the midpoints of two
7227 % adjacent sides and \mfc{B} is the corner between those two sides. This
7228 % quarter-ellipse starts at \mfc{A} in the direction \mfc{B-A} and ends at
7229 % \mfc{C} in the direction \mfc{C-B}. As a path \mfc{p} it has two segments, where
7230 % \mfc{point 0 of p} is \mfc{A}, \mfc{point 2 of p} is \mfc{C}, while
7231 % \mfc{point 1 of p} lies on the diagonal of the parallelogram through
7232 % \mfc{B} and has direction there the same as \mfc{C-A}.
7233 %
7234 % This was created for the purpose of rounding off corners of a polygonal
7235 % path.
7236 % \begin{macrocode}
7237 vardef quarterellipse(expr A,B,C) =
7238 save T_;
7239 transform T_;
7240 (1,0) transformed T_ = A;
7241 (1,1) transformed T_ = B;
7242 (0,1) transformed T_ = C;
7243 quartercircle scaled 2 transformed T_
7244 enddef;
7245
7246 % \end{macrocode}
7247 %
7248 % \DescribeRoutine{halfellipse}
7249 % While \gbc{quarterellipse} is for corners, I don't have much use for
7250 % \gbc{halfellipse}. Nevertheless, it seems wise (and easy) to provide a
7251 % definition.
7252 %
7253 % The pairs \mfc{A}, \mfc{B}, and \mfc{C} are three midpoints of a
7254 % parallelogram with \mfc{A} and \mfc{C} on opposite sides and \mfc{B} on
7255 % a third side. This determines a unique parallelogram, and
7256 % \gbc{halfellipse} starts at \mfc{A}, passing through \mfc{B} then
7257 % \mfc{C}, tangent to the respective sides. It makes a point of building
7258 % it out of two \gbc{quarterellipse}\,s as \mfc{halfcircle} does with
7259 % \mfc{quartercircle} (at least in \MF{}). We just have to compute their
7260 % corners.
7261 % \begin{macrocode}
7262 vardef halfellipse (expr A,B,C) =
7263 save P_; pair P_;
7264 P_ = (C - A)/2;
7265 quarterellipse (A, B - P_, B) & quarterellipse (B, B + P_, C)
7266 enddef;
7267
7268 % \end{macrocode}
7269 %
7270 % \DescribeRoutine{fullellipse}
7271 % For \gbc{fullellipse} we specify the center \mfc{C} of the parallelogram
7272 % and the midpoints \mfc{A} and \mfc{B} of two adjacent sides. We compute
7273 % the midpoints of the other two sides and draw two \gbc{halfellipse}\,s.
7274 %
7275 % Note that the points \gbc{A} and \gbc{B} do not correspond to the
7276 % usual radii of an ellipse unless the corresponding parallelogram is
7277 % actually a rectangle (i.e., only if $\angle ACB$ is a right angle).
7278 % \begin{macrocode}
7279 vardef fullellipse (expr C, A, B) =
7280 save P_; pair P_;
7281 P_ := 2[A,C];
7282 halfellipse (A,B,P_) & halfellipse (P_,2[B,C],A) & cycle
7283 enddef;
7284
7285 % \end{macrocode}
7286 %
7287 % \DescribeRoutine{pathcenter}
7288 % This finds the center of a circle. For other paths, the point found
7289 % may be meaningless (but it will also obtain the center of an arc or a
7290 % rectangle). It takes three or four supposedly distinct points on the
7291 % path and finds the intersection of the perpendicular bisectors of two
7292 % chords.
7293 %
7294 % This code is rather non-robust if applied to an arc that has angular
7295 % measure very close to either 0 or 360.
7296 % \begin{macrocode}
7297 vardef pathcenter expr p =
7298 save a, cntr, n; pair cntr, a[];
7299 n := length p;
7300 a1 = pnt 0 (p);
7301 a3 = pnt [n/2] (p);
7302 if cycle p:
7303 a2 = pnt [ n/4] (p);
7304 a4 = pnt [3n/4] (p);
7305 else:
7306 a2 := a3;
7307 a4 := pnt[n] (p);
7308 fi
7309 cntr = .5[a1, a3] + whatever*((a3 - a1) rotated 90);
7310 cntr = .5[a2, a4] + whatever*((a4 - a2) rotated 90);
7311 cntr
7312 enddef;
7313
7314 % \end{macrocode}
7315 %
7316 % The next four commands create certain circles associated to
7317 % triangles. The triangle is specified as a path expression, so they
7318 % produce results for any path, but make sense only for a cyclic
7319 % triangular path.
7320 %
7321 % \DescribeRoutine{circumcircle}
7322 % This is just the circle through the three corners.
7323 %
7324 % \DescribeRoutine{incircle}
7325 % The command \gbc{incircle} produces the circle that is tangent to all
7326 % three sides of the triangle. It makes use of the fact that the two
7327 % tangent points on the sides adjacent to corner \gbc{A} (for example) are
7328 % equidistant from \gbc{A}. The three equations then express the fact that
7329 % the sum of the two distances from the tangent point to the corners on
7330 % the same side add up to the length of the side.
7331 %
7332 % \DescribeRoutine{excircle}
7333 % In \gbc{excircle}, a corner is given (by number from $0$ to $2$) and the
7334 % circle is produced that is \emph{outside} the triangle and is tangent to
7335 % the side opposite the point and tangent to the extensions of the other
7336 % two sides.
7337 %
7338 % \DescribeRoutine{ninepointcircle}
7339 % The ``nine-point circle'' passes through the following nine points: the
7340 % midpoint of each side, the point on each side (extended, if necessary)
7341 % where the altitude from the opposite corner meets it, and the midpoint
7342 % of the segments connecting each corner to the intersection of the
7343 % altitudes.
7344 % \begin{macrocode}
7345 vardef circumcircle expr t =
7346 circleppp (pnt0 (t), pnt1 (t), pnt2 (t))
7347 enddef;
7348
7349 vardef incircle expr t =
7350 save A, B, C; pair A, B, C;
7351 A := pnt0 (t);
7352 B := pnt1 (t);
7353 C := pnt2 (t);
7354 save a, b, c, D, E, F;
7355 D := abs (B-A) = a + b;
7356 E := abs (C-B) = b + c;
7357 F := abs (A-C) = a + c;
7358 circleppp ((a/D)[A,B], (b/E)[B,C], (c/F)[C,A])
7359 enddef;
7360
7361 vardef excircle expr n of t =
7362 save A, B, C; pair A, B, C;
7363 A := pnt[n] (t);
7364 B := pnt[n + 1] (t);
7365 C := pnt[n + 2] (t);
7366 save a, b, c, D, E, F;
7367 D := abs (B-A) = a - b;
7368 E := abs (C-B) = b + c;
7369 F := abs (C-A) = a - c;
7370 circleppp ((a/D)[A,B], (b/E)[B,C], (c/F)[A,C])
7371 enddef;
7372
7373 vardef ninepointcircle expr t =
7374 circleppp (medianpt 0 of t, medianpt 1 of t, medianpt 2 of t)
7375 enddef;
7376
7377 % \end{macrocode}
7378 %
7379 % \DescribeRoutine{pshcircle}
7380 % Here are a couple of circles maybe only I need. They are the
7381 % pseudohyperbolic circles in the unit disk and upper half-plane.
7382 % One supplies a point that must be inside the unit circle or above
7383 % the $x$-axis, and a radius that must be less than $1$. Some degenerate
7384 % cases will not generate an error. We code this with a boolean that
7385 % determines whether the disk or the half-plane is to be assumed.
7386 %
7387 % If $\alpha=(a,b)$ is the hyperbolic center (the \mfc{ctr} parameter)
7388 % and $\rho$ is the pseudohyperbolic radius (the \mfc{rad parameter}),
7389 % the formula for the (Euclidean) center $C$ and radius $R$ of the circle
7390 % is, for the unit disk:
7391 % $$
7392 % C = \frac{ (1 - \rho^2)a }{1 - \rho^2|a|^2},\quad
7393 % R = \frac{\rho(1 - |a|^2)}{1 - \rho^2|a|^2}
7394 % $$
7395 % and for the half-plane:
7396 % $$
7397 % C = a + \frac{(1 + \rho^2}{1 - \rho^2}b,\quad
7398 % R = \frac{2\rho b}{1 - \rho^2}
7399 % $$
7400 % \begin{macrocode}
7401 vardef pshcircle (expr disk, ctr, rad) =
7402 if disk:
7403 if rad >= 1 :
7404 if rad > 1:
7405 GBerrmsg ("Impossible radius of pseudohyperbolic circle.")
7406 "The radius of a pseudohyperbolic circle can be at most 1.";
7407 fi
7408 circle ((0,0),1)
7409 elseif abs(ctr) >= 1 :
7410 if abs(ctr) > 1:
7411 GBerrmsg ("Impossible center of pseudohyperbolic circle.")
7412 "The center of this pseudohyperbolic circle must be in "
7413 & "the unit disk.";
7414 fi
7415 onepointpath (true,ctr)
7416 else:
7417 save _r, _dnm;
7418 _r := abs(ctr);
7419 _dnm := 1 - _r*_r*rad*rad;
7420 circle ((1 - rad*rad)/_dnm*ctr, rad*(1 - _r*_r)/_dnm)
7421 fi
7422 else:
7423 if rad >= 1 :
7424 GBerrmsg ("Impossible radius of pseudohyperbolic circle.")
7425 "The radius of a pseudohyperbolic circle must be less than 1.";
7426 onepointpath (true,ctr)
7427 elseif ypart ctr <= 0:
7428 if ypart ctr < 0:
7429 GBerrmsg ("Impossible center of pseudohyperbolic circle.")
7430 "The center of this pseudohyperbolic circle must be in "
7431 & "the upper half-plane.";
7432 fi
7433 onepointpath (true,ctr)
7434 else:
7435 save _y, _dnm;
7436 _y := ypart ctr;
7437 _dnm := 1 - rad*rad;
7438 circle ((xpart ctr, (1 + rad*rad)/_dnm * _y), 2rad/_dnm*_y)
7439 fi
7440 fi
7441 enddef;
7442
7443 % \end{macrocode}
7444 %
7445 % \DescribeRoutine{UHPgeodesic}
7446 % Here is another arc-producing command. What it produces is the
7447 % hyperbolic geodesic from one point to another in the \emph{upper
7448 % half-plane} (UHP). While, theoretically, the points should both be in
7449 % the UHP, where the hyperbolic geometry is defined, the computations make
7450 % sense for any pair of points. This could be useful, so I do not enforce
7451 % this theoretical requirement.
7452 %
7453 % Unless two points have the same xpart, there is a unique circle passing
7454 % through them that meets the $x$-axis at a right angle. The hyperbolic
7455 % geodesic is an arc of that circle. The path starts at the first listed
7456 % point and ends at the second. Of the two possible arcs that connect
7457 % these points, it is the one that doesn't cross the $x$-axis (if there
7458 % is one). Our computations simply determine the angle of the arc and call
7459 % \gbc{arcpps}.
7460 %
7461 % When the points have the same xpart, the hyperbolic geodesic is the
7462 % line segment connecting them. When the points have yparts with opposite
7463 % signs, both arcs cross the $x$-axis. Our code produces the shorter one.
7464 % If both are $180$ degrees, the one that lies all on the same side of the
7465 % vertical line through $A$ is produced ($A$ being the first argument).
7466 %
7467 % Our method is based on the fact that the reflection $C$ of $A$ (to the
7468 % other side of the $x$-axis) lies on the circle on which the arc lies.
7469 % The angle between $A$ and $B$ when viewed from this point is therefore
7470 % half the angle of the arc. We actually reflect the point farthest from
7471 % the $x$-axis, as this produces better results.
7472 %
7473 % If $A$ and $B$ are on opposite sides of the $x$-axis, then $C$ might
7474 % coincide with one of the points. In this case $A$ and $B$ would
7475 % necessarily have equal xparts, a case we will already have processed.
7476 %
7477 % If both points lie on the $x$-axis, the computations produce the
7478 % semicircle from the first to the second in the upper half-plane.
7479 % \begin{macrocode}
7480 vardef UHPgeodesic (expr A, B) =
7481 if xpart A = xpart B:
7482 A--B
7483 else:
7484 save ang_, C_; pair C_;
7485 if abs(ypart A) < abs(ypart B):
7486 C_ := conj B;
7487 else:
7488 C_ := conj A;
7489 fi
7490 if ypart C_ = 0: % both on x-axis
7491 ang_ := anglefromto(up, B - A);
7492 else:
7493 ang_ := anglefromto(A - C_, B - C_);
7494 fi
7495 arcpps(A, B, 2ang_)
7496 fi
7497 enddef;
7498
7499 % \end{macrocode}
7500 %
7501 % \DescribeRoutine{UDgeodesic}
7502 % There is a hyperbolic geometry defined for any simply connected open
7503 % set. The standard examples of such are the UHP and the unit disk (UD).
7504 % This next macro produces the geodesic in the UD. Once again it is the
7505 % arc of a circle and, if the two points do not lie on the same diameter,
7506 % that circle is the unique one through the two points that meets the
7507 % boundary of $UD$ at a right angle. When the two points do lie on the
7508 % same then the geodesic is the straight line connecting the points.
7509 %
7510 % The method we use is also based on reflection, where the `reflection' of
7511 % a point $A$ is given by $C = A/|A|^2$. Computing this can cause overflow
7512 % if $|A|$ too near $0$. Unfortunately, overflow can also occur if either
7513 % point lies are outside the UD. That is because, even for modest sizes of
7514 % $A$ and $B$, the part of the mentioned circle that lies outside the UD
7515 % can approach \gbc{infinity} in size, making the arc itself impossible to
7516 % draw. While it is feasible to compute when this will occur, we try to
7517 % keep it simple by using an approach that is only guaranteed to work when
7518 % the points lie in the unit disk. A minor modification allows it to to
7519 % always work when only one of the points is outside. This is because the
7520 % geodesic is not unique and we can easily choose one that doesn't
7521 % overflow.
7522 %
7523 % We isolate several special cases: if either point is the origin or if
7524 % the points have the same angle, a straight line is produced. If either
7525 % point is on the boundary, the computation is based on the fact that the
7526 % arc is tangent to the direction of that point. In the remaining cases,
7527 % we compute two angles based on reflecting both points. In the case where
7528 % both points lie inside or both lie outside, these angles are
7529 % theoretically equal, but when one point lies inside and the other
7530 % outside, these angles have opposite signs and their absolute values sum
7531 % to 360. They correspond to going opposite ways around the circle. We
7532 % choose the shorter arc as being more ``geodesic-like''.
7533 %
7534 % If $C$ is the point being reflected, but it is close enough to the
7535 % origin to make overflow a significant problem, we rescale the triangle
7536 % used to find the angle: we compute the angle between $|C|A$ and $|C|B$
7537 % as viewed from $C/|C|$.
7538 % \begin{macrocode}
7539 vardef UDgeodesic (expr A, B) =
7540 save a_, b_;
7541 a_ := abs(A); b_ = abs(B);
7542 if (a_ = 0) or (b_ = 0):
7543 A--B
7544 elseif angle A = angle B:
7545 A--B
7546 else: % note: A, B and B-A are all nonzero from this point
7547 save ang_;
7548 if a_ = 1:
7549 ang_ := anglefromto (if b_>1: A else: -A fi, B-A)
7550 elseif b_ = 1:
7551 ang_ := anglefromto (A-B, if a_>1: B else: -B fi)
7552 else:
7553 save C_; pair C_;
7554 % reflecting A
7555 if a_ < eps:
7556 C_ := unitvector A;
7557 ang_1 := anglefromto(a_*A - C_, a_*B - C_);
7558 else:
7559 C_ := (1/a_)*unitvector A;
7560 ang_1 := anglefromto(A - C_, B - C_);
7561 fi
7562 % reflecting B
7563 if b_ < eps:
7564 C_ := unitvector B;
7565 ang_2 := anglefromto(b_*A - C_, b_*B - C_);
7566 else:
7567 C_ := (1/b_)*unitvector B;
7568 ang_2 := anglefromto(A - C_, B - C_);
7569 fi
7570 ang_ := if abs(ang_1) < abs(ang_2): ang_1 else: ang_2 fi;
7571 fi
7572 arcpps(A, B, 2ang_)
7573 fi
7574 enddef;
7575
7576 % \end{macrocode}
7577 %
7578 % \DescribeRoutine{barycenter}
7579 % This is the average of the three corners of the triangle, or of all the
7580 % nodes of any path. If \gbc{t} is an open path with length $n$ and the
7581 % nodes are $x\sb0$ through $x\sb n$, the barycenter is
7582 % $$ \frac{1}{n+1}\sum\sb{j=0}\sp{n} x\sb j. $$
7583 % If \gbc{t} is a cycle with $x\sb n = x\sb0$, then it is
7584 % $$ \frac{1}{n}\sum\sb{j=0}\sp{n-1} x\sb j. $$
7585 %
7586 % For a triangle the barycenter is the intersection of the medians. I
7587 % don't recall if this is the center of any important circle.
7588 %
7589 % The centers of the various circles associated with triangles can be
7590 % found with \gbc{pathcenter}. Or by intersecting various lines: the
7591 % \emph{incenter} (center of the inscribed circle)is the intersection of
7592 % the angle bisectors; the \emph{circumcenter} is the intersection of the
7593 % prependicular bisectors.
7594 % \begin{macrocode}
7595 vardef barycenter expr t =
7596 save m; m := length t if not cycle t: + 1 fi;
7597 pnt0(t)/m for k = 1 upto m - 1: + pnt[k](t)/m endfor
7598 enddef;
7599
7600 % \end{macrocode}
7601 %
7602 % \DescribeRoutine{sector}
7603 % \gbc{sector} produces the closed path consisting of a straight line
7604 % of length \gbc{rad} from \gbc{center} in the direction \gbc{frtheta},
7605 % thence along an arc of the circle centered at \gbc{center} to angle
7606 % \gbc{totheta}, and then along the straight line back to \gbc{center}.
7607 % \begin{macrocode}
7608 vardef sector (expr center, rad, frtheta, totheta) =
7609 center -- arcalt (center, rad, frtheta, totheta) -- cycle
7610 enddef;
7611
7612 % \end{macrocode}
7613 %
7614 % \DescribeRoutine{mkbrace}
7615 % Because it doesn't really fit anywhere else, and because it is not
7616 % really enough to waste a whole subsection on, we put \gbc{mkbrace} here.
7617 % It is a command to draw a brace (i.e., a ``$\lbrace$'' shape) with its
7618 % ends and its cusp at given points. The start is at \gbc{S}, the end at
7619 % \gbc{E} and the cusp at \gbc{C}. \gbc{C} should be close to, but not
7620 % on, the line from \gbc{S} to \gbc{E}. It should also not be too close to
7621 % \gbc{S} or \gbc{E}, as we need room to draw two quarter circles on
7622 % either side of \gbc{C} and one at each of \gbc{S} and \gbc{E}.
7623 % \begin{macrocode}
7624 vardef mkbrace (expr S, C, E) =
7625 save R_, U_, V_, Z_;
7626 pair U_, V_, Z_[];
7627 U_ := unitvector (E-S);
7628 V_ := U_ rotated 90;
7629
7630 R_ := 0.5*(C-S) dotprod V_;
7631 if R_ = 0:
7632 S--C
7633 else:
7634 if R_ < 0 : V_ := -V_; R_ := -R_; fi
7635 V_ := R_*V_; U_ := R_*U_;
7636 Z_1 := S + V_ + U_;
7637 Z_2 := C - V_ - U_;
7638 Z_3 := C - V_ + U_;
7639 Z_4 := E + V_ - U_;
7640 S{V_}..{U_}Z_1--Z_2{U_}..{V_}C{-V_}..{U_}Z_3--Z_4{U_}..{-V_}E
7641 fi
7642 enddef;
7643
7644 % \end{macrocode}
7645 %
7646 %
7647 % \subsection{Plotting of functions}\label{functionplots}
7648 %
7649 % In these macros, if the boolean argument \gbc{sm} is true then the
7650 % path returned will be a B\'ezier, otherwise it will be a polyline. If a
7651 % \gbc{tens} parameter exists, then the smooth version will have that
7652 % value of tension, otherwise the value of \gbc{default_tension} is used.
7653 % These two parameters are simply passed to \gbc{mkpath} by \gbc{mkfcn},
7654 % and all these macros call \gbc{mkfcn}.
7655 %
7656 % \DescribeRoutine{mkfcn}
7657 % In this command the text parameter \gbc{pf} should be the name of a
7658 % function of some sort that can take a numeric value in parentheses and
7659 % return a pair expression. The parameters \gbc{bmin}, \gbc{bmax} and
7660 % \gbc{bst} determine a sequence of numeric values starting at \gbc{bmin},
7661 % stepping by \gbc{bst} and ending with \gbc{bmax}. These are fed to
7662 % \gbc{pf} and the resulting pairs stored in an array. Then either
7663 % \gbc{mkpoly} or \gbc{mksmooth} is called with the tension \gbc{tens} and
7664 % the name of the array.
7665 %
7666 % For stability, we don't actually step by \gbc{bst}, but round
7667 % \gbc{(bmax-bmin)/bst} and step that many equal steps. We first adjust
7668 % the step size upward so the number of steps doesn't exceed
7669 % \gbc{infinity}. The path is forced to begin at \gbc{pf(bmin)} and
7670 % end at \gbc{pf(bmax)} even if that is not an integer multiple of
7671 % \gbc{bst}.
7672 %
7673 % \DescribeRoutine{tfcn}
7674 % The macro \gbc{tfcn} is included for backward compatibility.
7675 % \begin{macrocode}
7676 vardef mkfcn (expr sm, tens) (expr bmin, bmax, bst) (text pf) =
7677 save _p; pair _p[]; _p := 0;
7678 save _dx, _n, _r; numeric _dx, _n, _r;
7679 if bmax = bmin: _n := 1;
7680 else:
7681 _r := bmax - bmin;
7682 _dx := max (abs(bst), nottoosmall*abs(_r), epsilon);
7683 _n := emax (round(abs(_r)/_dx), 1);
7684 fi
7685 for _i = 0 upto _n: _p[incr _p] := pf(bmin + _i/_n*_r); endfor
7686 mkpath (sm, tens, false, _p)
7687 enddef;
7688
7689 def tfcn (expr sm) = mkfcn (sm, default_tension) enddef;
7690
7691 % \end{macrocode}
7692 %
7693 % \DescribeRoutine{parafcn}
7694 % This is like \gbc{mkfcn}, but the text argument is not a pair
7695 % valued function, but rather a text parameter containing code that, when
7696 % copied literally into a vardef, defines a function in which \gbc{t} is
7697 % the argument, and which returns a pair.
7698 %
7699 % Older files are supported with a definition of \gbc{parafcn} that calls
7700 % \gbc{tparafcn} with \gbc{default_tension}. I should have made this easier
7701 % by reversing the smoothness and tension arguments, but for backward
7702 % compatibility I have to leave it thus. Other commands implement \mfpic's
7703 % tension options: \gbc{function} and \gbc{plrfcn}. They also have forms
7704 % that accept a tension argument (\gbc{tfunction} and \gbc{tplrfcn}) and
7705 % call them with the default tension.
7706 % \begin{macrocode}
7707 def parafcn (expr sm) = tparafcn (sm, default_tension) enddef;
7708 vardef tparafcn (expr sm, tn) (expr bmin, bmax, bst) (text pf) =
7709 save _fp; vardef _fp (expr t) = pf enddef;
7710 mkfcn (sm, tn) (bmin, bmax, bst) (_fp)
7711 enddef;
7712
7713 % \end{macrocode}
7714 %
7715 % \DescribeRoutine{xfcn}
7716 % This first converts its final argument, which should be a numeric
7717 % valued function \gbc{f}, to a pair valued function \gbc{(x, f(x))}, then
7718 % calls \gbc{mkfcn} to return the path that should be the graph of $f(x)$.
7719 % \begin{macrocode}
7720 vardef xfcn (expr sm) (expr xmin, xmax, st) (text _fx) =
7721 save _fp; vardef _fp (expr _x) = (_x, _fx(_x)) enddef;
7722 mkfcn (sm, default_tension) (xmin, xmax, st) (_fp)
7723 enddef;
7724
7725 % \end{macrocode}
7726 %
7727 % \DescribeRoutine{function}
7728 % This is like \gbc{xfcn} but its last argument, instead of a function,
7729 % is a text argument that can be copied literally it into a vardef so as
7730 % to define a pair valued function with a literal \gbc{x} as the argument.
7731 %
7732 % \DescribeRoutine{btwnfcn}
7733 % This is mainly for the sake of simpler \mfpic{} output, implementing
7734 % the \cs{btwnfcn} macro. One could code it in \mfpic{} macros with two
7735 % calls to \gbc{function}.
7736 %
7737 % \DescribeRoutine{belowfcn}
7738 % This is essentially \gbc{btwnfcn} with the first function identically
7739 % 0, but it more efficiently graphs $0$ with one straight line
7740 % rather than several end-to-end.
7741 % \begin{macrocode}
7742 def function (expr sm) = tfunction (sm, default_tension) enddef;
7743 vardef tfunction (expr sm, tens, xmin, xmax, st) (text _fx) =
7744 save _fp; vardef _fp (expr x) = (x, _fx) enddef;
7745 mkfcn (sm, tens) (xmin, xmax, st) (_fp)
7746 enddef;
7747
7748 def btwnfcn (expr sm) = tbtwnfcn (sm, default_tension) enddef;
7749 vardef tbtwnfcn (expr sm, tn, xlo, xhi, st)(text _fx)(text _gx) =
7750 tfunction (sm, tn) (xlo, xhi, st) (_fx) --
7751 ( reverse tfunction (sm, tn) (xlo, xhi, st) (_gx) ) -- cycle
7752 enddef;
7753
7754 def belowfcn (expr sm) = tbelowfcn (sm, default_tension) enddef;
7755 vardef tbelowfcn (expr sm, tn, xlo, xhi, st)(text _fx) =
7756 (xlo,0)--(xhi,0)--
7757 (reverse tfunction (sm, tn, xlo, xhi, st)(_fx))--cycle
7758 enddef;
7759
7760 % \end{macrocode}
7761 %
7762 % \DescribeRoutine{rfcn}
7763 % This takes the name of a function \gbc{f} which is a numeric
7764 % valued function of a numeric parameter. It interprets it as a polar
7765 % curve $(\theta, f(\theta))$, converts that to a curve in rectangular
7766 % coordinates and calls \gbc{mkfcn} on it.
7767 % \begin{macrocode}
7768 vardef rfcn (expr sm, tmin, tmax, st) (text ft) =
7769 save _fq; vardef _fq (expr t) = (ft(t)) * (dir t) enddef;
7770 mkfcn (sm, default_tension) (tmin, tmax, st) (_fq)
7771 enddef;
7772
7773 % \end{macrocode}
7774 %
7775 % \DescribeRoutine{plrfcn}
7776 % This is like \gbc{rfcn}, but with a text argument containing code that
7777 % can be copied literally into a \mfc{vardef} creating a numeric function
7778 % with a literal \gbc{t} as the parameter (representing $\theta$).
7779 %
7780 % \DescribeRoutine{btwnplrfcn}
7781 % The macro \gbc{btwnplrfcn} is the polar version of \gbc{btwnfcn}.
7782 % \begin{macrocode}
7783 def plrfcn (expr sm) = tplrfcn (sm, default_tension) enddef;
7784 vardef tplrfcn (expr sm, tens, tmin, tmax, st) (text ft) =
7785 save _fq; vardef _fq (expr t) = (ft) * (dir t) enddef;
7786 mkfcn (sm, tens) (tmin, tmax, st) (_fq)
7787 enddef;
7788
7789 def btwnplrfcn (expr sm) = tbtwnplrfcn (sm, default_tension) enddef;
7790 vardef tbtwnplrfcn (expr sm, tn, tlo, thi, st)(text _ft)(text _gt)=
7791 tplrfcn (sm, tn, tlo, thi, st) (_ft) --
7792 ( reverse tplrfcn (sm, tn, tlo, thi, st) (_gt) ) -- cycle
7793 enddef;
7794
7795 def plrregion (expr sm) = tplrregion (sm, default_tension) enddef;
7796 vardef tplrregion (expr sm, tn, tlo, thi, st) (text _ft) =
7797 (0,0)--tplrfcn (sm, tn, tlo, thi, st ) (_ft)--cycle
7798 enddef;
7799
7800 % \end{macrocode}
7801 %
7802 % \DescribeRoutine{mklevelset}
7803 % This command assumes \gbc{inside_levelset} has been defined, which
7804 % should be a boolean-valued function of two variables. It tries to create
7805 % a path such that the expression is true inside the path and false
7806 % outside it. The intended application is to obtain a path surrounding a
7807 % region like $\lbrace (x,y) \mid F(x,y) > 0 \rbrace$.
7808 %
7809 % The parameters are
7810 % \begin{itemize}
7811 % \item \gbc{sm}: Boolean, smooth path (true) or polyline.
7812 % \item \gbc{tens}: Numeric, the tension (if \gbc{sm} is true).
7813 % \item \gbc{X} and \gbc{Y}: A starting point where \gbc{_inside_}
7814 % should return true.
7815 % \item \gbc{t}: Numeric, a step size.
7816 % \item \gbc{a}, \gbc{b}, \gbc{c}, and \gbc{d}: Numeric, the limits
7817 % beyond which the search routine will not go. This is needed to
7818 % get a starting range for the binary chop method of \mfc{solve}.
7819 % In practice, the extent of the \mfpic{} figure will be used.
7820 % \end{itemize}
7821 %
7822 % We use \mfc{solve} to find the first point $z\sb1$ to the right of the
7823 % given point that is on the edge of the region. Then we find the first
7824 % point of intersection between the circle at $z\sb1$ with radius \gbc{t}
7825 % and the edge of the region. Continue from this new point to the next
7826 % until (one hopes) we are within a distance \gbc{t} of the first point.
7827 % The radius \gbc{t} should be in coordinates appropriate for the use:
7828 % graph coordinates when used in \mfpic{} figures.
7829 %
7830 % The tolerance used in the first \mfc{solve} is \gbc{t/50}. In later uses
7831 % it is an angle parameter and is set to a number of degrees sufficient to
7832 % give a distance tolerance at least that.
7833 %
7834 % If the starting point \gbc{(X,Y)} does not actually satisfy the
7835 % condition, a one point path is returned.
7836 % \begin{macrocode}
7837 numeric tolerancefactor;
7838 tolerancefactor := .02;
7839
7840 vardef mklevelset (expr sm, tens, X, Y, t, a, b, c, d) =
7841 save _inside_;
7842 vardef _inside_ (expr U, V) =
7843 inside_levelset(U, V) and between(a, b)(U) and between(c, d)(V)
7844 enddef;
7845 if not _inside_ (X, Y):
7846 GBwarn "Invalid seed point for levelset.";
7847 pairmax((a,c), pairmin((X,Y), (b,d)))&cycle
7848 else:
7849 save ls, W, A, B, prev, curr, seed;
7850 pair ls[], prev, curr, seed;
7851 seed := (X,Y);
7852 ls := 0; W := 0;
7853
7854 save _first_, _next_, get_next;
7855 vardef _first_ (expr U) = _inside_ (U, Y) enddef;
7856 vardef _next_ (expr ang) =
7857 _inside_ (X_curr + t * cosd ang, Y_curr + t * sind ang)
7858 enddef;
7859 def get_next (expr angA, angB) =
7860 X_curr := xpart curr; Y_curr := ypart curr;
7861 ls[incr ls] := curr + t * dir (solve _next_ (angA, angB));
7862 prev := curr; curr := ls[ls];
7863 W := W + anglefromto (prev - seed, curr - seed);
7864 enddef;
7865
7866 interim tolerance := t*tolerancefactor;
7867 ls[incr ls] := (solve _first_ (X, b), Y);
7868 curr := ls[ls];
7869 interim tolerance := radian*tolerancefactor;
7870 get_next (180, 0);
7871 for n = 3 upto max_points:
7872 A := angle (curr - prev);
7873 get_next (A + 120, A - 120);
7874 exitif ((abs(W) > 180) or (ls > 10))
7875 and (abs(ls[ls] - ls1) < 1.2t);
7876 endfor
7877 mkpath (sm, tens, true) (ls)
7878 fi
7879 enddef;
7880
7881 % \end{macrocode}
7882 %
7883 % \DescribeRoutine{levelset}
7884 % This is the \mfpic{} interface. It checks the \gbc{t} parameter before
7885 % passing it to \gbc{mklevelset}, making sure it is not zero, it passes
7886 % appropriate limits, and defines boolean function \gbc{mklevelset}
7887 % expects with literal \mfc{x} and \mfc{y} as parameters, using the text
7888 % parameter \gbc{cond}.
7889 % \begin{macrocode}
7890 numeric max_points;
7891 max_points := 2000;
7892
7893 def levelset (expr s) = tlevelset (s, default_tension) enddef;
7894 vardef tlevelset (expr smth, tens, seed, seg) (text cond) =
7895 save inside_levelset, _t;
7896 vardef inside_levelset (expr x, y) = cond enddef;
7897 _t := if seg <= 0: emax (xpos-xneg, ypos-yneg)/max_points * 20
7898 else: seg fi;
7899 mklevelset (smth, tens, xpart seed, ypart seed, _t)
7900 (xneg, xpos, yneg, ypos)
7901 enddef;
7902
7903 % \end{macrocode}
7904 %
7905 % Our next set of macros produce approximations to the solutions of
7906 % differential equations. While we could have several different macros
7907 % each using a different method (Euler, two-step Runge-Kutta, four-step
7908 % Runge-Kutta, etc.), our point of view is that we just want to draw a
7909 % reasonably accurate solution, so we only utilize one method: four-step
7910 % Runge-Kutta. The variations we allow are the following:
7911 % \begin{enumerate}
7912 % \item Drawing the graph of a one-dimensional differential
7913 % equation,
7914 % \[ \frac{dy}{dx} = g(x,y)\,.\]
7915 %
7916 % \item Drawing the trajectory of a two-dimensional differential
7917 % equation,
7918 % \[ \left( \frac{dx}{dt},\frac{dy}{dt} \right) =
7919 % (f(x,y,t), g(x,y,t))\,.\]
7920 % \end{enumerate}
7921 % The first of these is implemented using the second with $f(x,y,t) \equiv
7922 % 1$ and $g(x,y,t)$ not depending on $t$. The parameters passed include
7923 % the starting point, the step size, the number of steps and an expression
7924 % representing the right side of the equation.
7925 %
7926 % We do not use exactly the traditional Runge-Kutta method: we use the
7927 % Runge-Kutta algorithm, but with a variable step size. The time step
7928 % $\Delta t$ is chosen so that $|\mathbf{F}(x,y,t)|\Delta t$ equals the
7929 % given step size parameter, and thus the parameter passed is actually a
7930 % distance step. This makes drawing more stable, especially if the DE is
7931 % one that produces an infinite path in finite time.
7932 %
7933 % This modification is itself unstable if $|\mathbf{F}|$ is very
7934 % small (and impossible if it is zero), so we never use a $\Delta t$
7935 % larger than the given step size parameter $\Delta s$. That is, we
7936 % actually use $\Delta t = \Delta s/\max(1,|\mathbf{F}|)$.
7937 %
7938 % As with our other function-like paths, we offer two variants. The basic
7939 % version has a final text parameter which is the name of a pair-valued
7940 % function of a numeric (representing $t$) and a pair variable
7941 % (representing $x$ and $y$). The other version takes a text
7942 % parameter, which must be a pair-valued expression in \mfc{x}, \mfc{y}
7943 % and \mfc{t}. This parameter is copied into the definition text of a
7944 % function and then the first form is called with that function's name.
7945 %
7946 % Also like other function-like paths, we offer polygonal or smooth
7947 % versions controlled by a boolean argument, and the smooth versions make
7948 % use of a tension parameter.
7949 % \begin{macrocode}
7950 def RKIV (expr sm) = tRKIV (sm, default_tension)
7951 enddef;
7952 vardef tRKIV (expr sm, tens, zstart, ds, N) (text _RHS_) =
7953 save _trj, _ztr, _dz, _ztmp, _ctm;
7954 pair _trj[], % The trajectory
7955 _ztr, % current point
7956 _dz[], % array[4] of displacements
7957 _ztmp; % current point for calculating velocity
7958 %
7959 _trj := N+1; % ultimate size of _trj array
7960 _trj1 := _ztr := zstart;
7961 save _tt, % current time
7962 _dt, % current time step
7963 _th; % current time plus half a step
7964 _tt := 0;
7965 for _idx := 2 upto _trj:
7966 _dt := ds/emax(1,abs(_RHS_(_tt,_ztr)));
7967 _th := _tt + .5_dt;
7968 _dz1 := _dt*_RHS_(_tt, _ztr); % displacement for current point
7969 _ztmp := _ztr + .5_dz1; % 1st midpoint
7970 % use _th instead of twice calculating (_tt + .5_dt)
7971 _dz2 := _dt*_RHS_(_th, _ztmp); % displacement for 1st midpoint
7972 _ztmp := _ztr + .5_dz2; % 2nd midpoint
7973 _dz3 := _dt*_RHS_(_th, _ztmp); % displacement for 2nd midpoint
7974 _ztmp := _ztr + _dz3; % temporary end point
7975 % get time for next loop now since we need it in the next line:
7976 _tt := _tt + _dt;
7977 _dz4 := _dt*_RHS_(_tt, _ztmp); % displacement for end point
7978 % get next point
7979 _ztr := _ztr + (_dz1 + 2_dz2 + 2_dz3 + _dz4)/6;
7980 _trj[_idx] := _ztr;
7981 endfor
7982 mkpath (sm, tens, false, _trj)
7983 enddef;
7984
7985 def xyRKIV (expr sm) = txyRKIV (sm, default_tension)
7986 enddef;
7987 vardef txyRKIV (expr sm, tens, zstart, ds, N) (text _RHS_) =
7988 save _fgxy, __fgxy;
7989 vardef __fgxy (expr t, x, y) = _RHS_ enddef;
7990 vardef _fgxy (expr t, Z) = __fgxy(t, xpart Z, ypart Z) enddef;
7991 tRKIV (sm, tens, zstart, ds, N) (_fgxy)
7992 enddef;
7993
7994 def odeRKIV (expr sm) = todeRKIV (sm, default_tension)
7995 enddef;
7996 vardef todeRKIV (expr sm, tens, xstart, ystart, ds, N)
7997 (text _fxy) =
7998 txyRKIV (sm, tens, (xstart, ystart), ds, N) ((1, _fxy))
7999 enddef;
8000
8001 % \end{macrocode}
8002 %
8003 %
8004 %
8005 % \section{Modification of Paths}\label{modification}
8006 %
8007 %
8008 % \subsection{Closing a path}\label{closing}
8009 %
8010 % In \MF{} one closes a path with any legal path connection between the
8011 % last point and the keyword \mfc{cycle}. Connecting the last point to the
8012 % first point is not enough. \Grafbase{} commands provide a few different
8013 % ways. All the commads take an undelimited path expression as the last
8014 % parameter and return a cycle (closed path). If the path is already
8015 % closed, it is returned unchanged.
8016 %
8017 % All the closure commands have a version with a tension parameter when
8018 % that makes sense. Those versions create the join with the supplied
8019 % tension. The ones where it doesn't make sense are \gbc{lclosed},
8020 % \gbc{cbclosed} and \gbc{qbclosed}. The first always uses a straight line
8021 % and the other two require explicit controls.
8022 %
8023 % \DescribeRoutine{lclosed}
8024 % This closes with a line segment. If the first and last point are
8025 % already equal, we just use the \mfc{\&} path join.
8026 % \begin{macrocode}
8027 vardef lclosed expr f =
8028 f
8029 if not cycle f:
8030 if pnt0(f) = pnt[infinity](f): & else: -- fi cycle
8031 fi
8032 enddef;
8033
8034 % \end{macrocode}
8035 %
8036 % \DescribeRoutine{sclosed}
8037 % This closes the path in the manner that \gbc{mksmooth} creates a path.
8038 % This will change the first and last segment of the original path. In
8039 % particular, if there are fewer than three segments, the whole path can
8040 % be different.
8041 % \DescribeRoutine{sclosedt}
8042 % It has a variant \gbc{sclosedt} that takes a tension argument.
8043 % \begin{macrocode}
8044 def sclosed = sclosedt (default_tension) enddef;
8045 vardef sclosedt (expr t) expr f =
8046 if cycle f: f
8047 else: save n; n := length f;
8048 if n = 0: f&cycle
8049 elseif n = 1: pnt0(f)..tension t..pnt1(f)..tension t..cycle
8050 else:
8051 (pnt0 (f)) { (pnt1(f)) - (pnt[n] (f)) }..tension t
8052 ..(subpath (1, n-1) of f)..tension t
8053 ..(pnt[n](f)) { pnt0(f) - pnt[n-1](f) }
8054 ..tension t..cycle
8055 fi
8056 fi
8057 enddef;
8058
8059 % \end{macrocode}
8060 %
8061 % \DescribeRoutine{bclosed}
8062 % This closes with the basic default \MF{} Bezi\'er. It is a smooth
8063 % closure, but it does not have the same direction at the endpoints
8064 % that \gbc{mksmooth (true)} would have produced. It has a tense variant
8065 % \DescribeRoutine{bclosedt}
8066 % \gbc{bclosedt}
8067 % \begin{macrocode}
8068 def bclosed = bclosedt (default_tension) enddef;
8069 vardef bclosedt (expr t) expr f =
8070 f
8071 if not cycle f:
8072 if pnt0(f) = pnt[infinity](f): & else: ..tension t.. fi cycle
8073 fi
8074 enddef;
8075
8076 % \end{macrocode}
8077 %
8078 % \DescribeRoutine{uclosed}
8079 % Same as \gbc{bclosed}. Retained for backward compatibility. There is
8080 % a tense variant only for
8081 % \DescribeRoutine{uclosedt}
8082 % consistency.
8083 % \begin{macrocode}
8084 def uclosed = bclosed enddef;
8085 def uclosedt = bclosedt enddef;
8086
8087 % \end{macrocode}
8088 %
8089 % \DescribeRoutine{cbcontrols}
8090 % This utility is for use in \gbc{cbclosed}. It converts Bezier segment
8091 % key points of a path \gbc{f}, to cubic B-spline control points stored
8092 % in an array \gbc{b}. The data needed are the first point and first two
8093 % control points of a path. It is used twice in \gbc{cbclosed} on a path
8094 % and on its reverse. The appropriate three points are passed in the array
8095 % \gbc{t}.
8096 % The B-spline points needed are \gbc{b1} and \gbc{b4}. The extra two
8097 % points \gbc{b2} and \gbc{b3} divide the line from \gbc{b1} to \gbc{b4}
8098 % into thirds and will be turned into Bezier control points of a new path
8099 % segment.
8100 % \begin{macrocode}
8101 def cbcontrols (suffix b, t) =
8102 b1 := 2[t3, t2];
8103 b2 := 2[t2, t1];
8104 b3 := 2[b1, b2];
8105 b4 := 2[b2, b3];
8106 enddef;
8107
8108 % \end{macrocode}
8109 %
8110 % \DescribeRoutine{cbclosed}
8111 % This closes a path with a cubic B-spline. If the path \gbc{f} had been
8112 % produced by \gbc{opencbs}, then \gbc{q1} and \gbc{q4} would have been the
8113 % last two points in the argument list, and \gbc{p4} and \gbc{p1} would
8114 % have been the first two. We just use them and mimic the effect of
8115 % \gbc{closedcbs}.
8116 % \begin{macrocode}
8117 vardef cbclosed expr f =
8118 save n; n := length f;
8119 if cycle f: f
8120 elseif n = 0: f&cycle
8121 else:
8122 save p, q, t; pair p[], q[], t[];
8123 t1 := pnt0(f); t2 := post0(f); t3 := pre1(f);
8124 cbcontrols (p, t); % defines p1 to p4
8125 t1 := pnt[n](f); t2 := pre[n](f); t3 := post[n-1](f);
8126 cbcontrols (q, t); % defines q1 to q4
8127 f..controls q2 and q3..opencbs (q1,q4,p4,p1)
8128 ..controls p3 and p2..cycle
8129 fi
8130 enddef;
8131
8132 % \end{macrocode}
8133 %
8134 % \DescribeRoutine{qbclosed}
8135 % It seemed wrong to be able to close with a cubic B-spline but not a
8136 % quadratic B-spline; therefore I have add such a possibility. We
8137 % calculate B-spline controls \gbc{p[n]} that will agree with those of
8138 % \gbc{f}, if \gbc{f} had been created as a quadratic B-spline. Note
8139 % that \gbc{cbclosed} required three \MF{} links to close the curve;
8140 % \gbc{qbclosed} only requires two (\gbc{mkqbs} on an array of $n$
8141 % points makes $n-2$ links).
8142 % \begin{macrocode}
8143 vardef qbclosed expr f =
8144 if cycle f: f
8145 else: save n; n := length f;
8146 if n = 0: f&cycle
8147 else:
8148 save p; pair p[]; p := 4;
8149 p1 := (3/2)[pnt[n](f), pre[n](f)];
8150 p2 := 2[p1, pnt[n](f)];
8151 p4 := (3/2)[pnt 0 (f), post0 (f)];
8152 p3 := 2[p4, pnt 0 (f)];
8153 f & mkqbs (p) & cycle
8154 fi
8155 fi
8156 enddef;
8157
8158 % \end{macrocode}
8159 %
8160 % \DescribeRoutine{makesector}
8161 % This makes sense only if the path being modified is an arc. It closes
8162 % the arc by connecting its ends to the center of the circle, as
8163 % computed by \gbc{pathcenter}.
8164 % \begin{macrocode}
8165 vardef makesector expr p = (pathcenter p)--p--cycle enddef;
8166
8167 % \end{macrocode}
8168 %
8169 % \DescribeRoutine{arccomplement}
8170 % Getting the complement of an arc is easy if the arc is specified by
8171 % three points. So we just select three points on the arc and do that.
8172 % The \gbc{setpairs} statement makes \gbc{pp1}, \gbc{pp2} and \gbc{pp3}
8173 % three points on the arc \gbc{p} in order. The arc we want goes from
8174 % \gbc{pp3} to \gbc{pp1} with angle twice that of the corner angle at
8175 % \gbc{pp2}. This function can be applied to an arbitrary path, and its
8176 % result will be an arc, but not necessarily a meaningful one.
8177 % \begin{macrocode}
8178 vardef arccomplement expr p =
8179 if cycle p: onepointpath (false, pnt0(p))
8180 else:
8181 setnumeric (nn) length p;
8182 setpairs (pp) (pnt0(p), pnt[.5nn](p), pnt[nn](p));
8183 arcpps (pp3,pp1,2*cornerangle(pp2,pp3,pp1))
8184 fi
8185 enddef;
8186
8187 % \end{macrocode}
8188 %
8189 %
8190 % \subsection{Trimming a path}\label{trimming}
8191 %
8192 % \DescribeRoutine{cutoffbefore}
8193 % This is a useful utility operation present in \file{plain.mp} (as
8194 % \mfc{cutbefore}) but missing from \file{plain.mf}. We write a different
8195 % version for our purposes: it has the syntax of most of our path
8196 % modification commands, plus the first loop tries to avoid a bug (or
8197 % perhaps inaccuracy) in \mfc{intersectiontimes} which can return an
8198 % intersection time in a later segment of \gbc{f} than the first
8199 % intersection point.
8200 %
8201 % \DescribeRoutine{cutoffafter}
8202 % What it and \gbc{cutoffafter} do is return the second path with the
8203 % part before\slash after the first path removed.
8204 % \begin{macrocode}
8205 %<MF>path cuttings;
8206 vardef cutoffbefore (expr b) expr f =
8207 save t, n; n := length f;
8208 if n > 0:
8209 for k = 1 upto n:
8210 exitif (subpath (0,k) of f) intersects b;
8211 endfor
8212 if _Xtime < 0:
8213 cuttings := pnt0 (f){0,0};
8214 f
8215 else:
8216 cuttings := subpath (0,_Xtime) of f;
8217 subpath (_Xtime, n) of f
8218 fi
8219 else: f
8220 fi
8221 enddef;
8222
8223 vardef cutoffafter (expr b) expr f =
8224 setpath (g) cutoffbefore (b) reverse f;
8225 cuttings := reverse cuttings;
8226 reverse g
8227 enddef;
8228
8229 % \end{macrocode}
8230 %
8231 % \DescribeRoutine{trimmedpath}
8232 % This takes two lengths and a path and trims off the ends of the path
8233 % that lie within the given lengths of the endpoints. The lengths are in
8234 % device coordinates, the path in graph coordinates.
8235 % \begin{macrocode}
8236 vardef trimmedpath (expr btrim, etrim) expr f =
8237 save g, h; path g, h;
8238 g := invvconv (fullcircle scaled 2btrim) shifted pnt0(f);
8239 h := invvconv (fullcircle scaled 2etrim) shifted pnt[length f] (f);
8240 cutoffafter (h) cutoffbefore (g) f
8241 enddef;
8242
8243 % \end{macrocode}
8244 %
8245 %
8246 % \subsection{Creating arrows}\label{arrows}
8247 %
8248 % First, some better \mfc{direction} commands. They makes use of the fact
8249 % (easily proved) that a cubic B\'ezier
8250 % \[
8251 % z\sb0(1 - t)^3 + 3z\sb1(1-t)^2t + 3z\sb2(1-t)t^2 + z\sb3t^3
8252 % \]
8253 % has a tangent at $z\sb0$ equal to the first one of $z\sb{j} -z\sb0$
8254 % that is nonzero.
8255 %
8256 % \gbc{__dir} gets the direction at point 0 for an arbitrary path.
8257 % \gbc{postdirection}
8258 % \DescribeRoutine{postdirection}
8259 % reduces to this case using \mfc{subpath}. If the postdirection is
8260 % $(0,0)$, that means the path is trivial from that point to the end so we
8261 % are effectively at an endpoint (noncyclic path) and we use the incoming
8262 % direction. If that is $(0,0)$, the path is trivial.
8263 % \DescribeRoutine{predirection}
8264 % \gbc{predirection} just runs \gbc{postdirection} on the reversed path.
8265 %
8266 % \DescribeRoutine{trivial}
8267 % This returns \mfc{true} if a path has direction vector $(0,0)$ (as
8268 % determined by \gbc{__dir}).
8269 % \begin{macrocode}
8270 vardef predirection@# (expr p) =
8271 - postdirection[length p - @#] (reverse p)
8272 enddef;
8273
8274 vardef postdirection@# (expr p) =
8275 save _n; _n := length (p);
8276 setpair (v) __dir (subpath (@#, @# + _n) of p);
8277 if v = origin:
8278 v := - __dir (subpath (@#, @# - _n) of p);
8279 fi
8280 v
8281 enddef;
8282
8283 vardef __dir (expr p) =
8284 save v, w; pair v, w; w := pnt0 (p);
8285 v := origin;
8286 for n = 1 upto length (p):
8287 v := post[n-1] (p) - w; exitif v <> origin;
8288 v := pre [ n ] (p) - w; exitif v <> origin;
8289 v := pnt [ n ] (p) - w; exitif v <> origin;
8290 endfor
8291 sgn v
8292 enddef;
8293
8294 vardef trivial expr p = (__dir (p) = origin) enddef;
8295
8296 % \end{macrocode}
8297 %
8298 % Arrowheads can be just two straight lines at an angle placed on the end
8299 % of a curve, or it can be a filled triangle. \grafbase{} permits both,
8300 % but it also allows the two lines (or the corresponding sides of the
8301 % triangle) to be gracefully concave and tangent to the path at the
8302 % endpoint of the path. The parameters controlling the shape of the arrowhead
8303 % are the two numerics \gbc{hdwdr}, the ratio of the length to width of the
8304 % arrowhead, and \gbc{hdten}, the tension in the two angled curves. By
8305 % default, one side of an arrowhead is just the \MF{} path
8306 % \mfc{a..b\marg{\meta{tangent}}}, where \mfc{a} is the base of the
8307 % arrowhead (calculated from \gbc{hdwdr}) and \gbc{b} is the end of the
8308 % path and \meta{tangent} is the direction of the path at that
8309 % point. The curve can be straightened by increasing \gbc{hdten}, the
8310 % head widened by increasing \gbc{hdwdr}
8311 %
8312 % The arrowhead is drawn by drawing two of the curves described above. If
8313 % \gbc{hfilled} is \mfc{true}, the two base points (\gbc{a} above) are
8314 % connected and the three sided region filled.
8315 % \begin{macrocode}
8316 newinternal hdwdr, hdten;
8317 boolean hfilled;
8318
8319 % \end{macrocode}
8320 %
8321 % \DescribeRoutine{headshape}
8322 % The following utility not only adjusts the above parameters, but
8323 % creates the arrowhead paths as it does so. Call it with two pure numbers
8324 % \gbc{wr} and \gbc{tens} for the \gbc{hdwdr} and \gbc{hdten}, and a
8325 % boolean \gbc{fil} for \gbc{hfilled}. The paths include two harpoon
8326 % tips, an arrowhead, and the paths that give regions that will be erased
8327 % when requested.
8328 % \begin{macrocode}
8329 def headshape (expr wr, tens, fil) =
8330 interim hdwdr := wr;
8331 interim hdten := if tens>0: tens else: default_tension fi;
8332 if hdten < .75: hdten := .75; fi
8333 setboolean (hfilled) fil;
8334 mkheadpaths;
8335 enddef;
8336 def mkheadpaths =
8337 save Arrowhead, Leftharpoon, Rightharpoon;
8338 path Arrowhead, Leftharpoon, Rightharpoon,
8339 Arrowhead.clear, Leftharpoon.clear, Rightharpoon.clear;
8340 Rightharpoon := (0,0){down}..tension hdten..(.5hdwdr,-1);
8341 Rightharpoon.clear := Rightharpoon--(.5hdwdr,0)--cycle;
8342 Leftharpoon := (reverse Rightharpoon) xscaled -1;
8343 Leftharpoon.clear := (reverse Rightharpoon.clear) xscaled -1;
8344 Arrowhead := Leftharpoon & Rightharpoon;
8345 Arrowhead.clear := Leftharpoon.clear & Rightharpoon.clear & cycle;
8346 if hfilled:
8347 Arrowhead := Arrowhead--cycle;
8348 Rightharpoon := Rightharpoon--(0,-1)--cycle;
8349 Leftharpoon := Leftharpoon--(0,-1)--cycle;
8350 fi
8351 enddef;
8352 headshape (1,1,false);
8353
8354 % \end{macrocode}
8355 %
8356 % \DescribeRoutine{ahead}
8357 % This command draws an arrowhead. Current code for arrows no longer uses
8358 % it. \gbc{front} and \gbc{back} are in device coordinates. They are the
8359 % point of the arrowhead (\gbc{front}) and the point such that \gbc{front
8360 % - back} is as long as the arrowhead and points in the direction of the
8361 % arrow. We use the ratio \gbc{hwr} to compute the other two corners. So
8362 % \gbc{side} is the vector from \gbc{back} to one of the corners \gbc{p1},
8363 % and the other corner is on the other side. \gbc{f} is the path of the
8364 % arrowhead.
8365 %
8366 % If \gbc{filled} is true we close the curve draw it and fill it,
8367 % otherwise we just draw it. (To only fill it, make the pen width $0$.)
8368 % \gbc{clr} is the color used to draw or fill it.
8369 %
8370 % For backward compatibility we define \gbc{head}. In \MF{} \gbc{head}
8371 % didn't have a color parameter, while in \MP{} it has always had one,
8372 % in retrospect, this was not a good idea, and I should have followed
8373 % the pattern of other macros. However, \gbc{head} was never a user-level
8374 % macro and it didn't seem to mattered at the time.
8375 % \begin{macrocode}
8376 %<MF>def head = ahead (headcolor) enddef;
8377 %<MP>def head = ahead enddef;
8378
8379 vardef ahead (expr clr, front, back, hwr, tens, filled) =
8380 settension (_tn) tens; fixtension (_tn);
8381 if front <> back:
8382 setpair (side) (hwr/2) * ((front-back) rotated 90);
8383 setpath (f) (back + side)..tension _tn..
8384 {front-back}front{back-front}..tension _tn..(back - side);
8385 if clearhead:
8386 safeunfill (back - side)--(front-side)--(front+side)--
8387 (back+side) & f & cycle;
8388 colorsafedraw (background) (back - side)--(front-side)--
8389 (front+side)--(back+side) & f & cycle;
8390 fi
8391 if filled:
8392 f := f--cycle;
8393 colorsafefill (clr) f;
8394 fi
8395 colorsafedraw (clr) f;
8396 fi
8397 enddef;
8398
8399 % \end{macrocode}
8400 %
8401 % It is a fact of life that, unless the path to which the head is added is
8402 % a straight line, the arrowhead may appear to point in the wrong
8403 % direction. But I know of no automatic way of making it always look
8404 % correct. Therefore \grafbase{} and \mfpic{} have provided a means to
8405 % micro-adjust the head.
8406 %
8407 % The various arrow creation commands take a path expression \gbc{f} in
8408 % graph coordinates, puts a head/tail/decoration on it and returns
8409 % \gbc{f}. There are also four parameters determining (i)~the color,
8410 % (ii)~the size, (iii)~a rotation adjustment, and (iv)~a position
8411 % adjustment.
8412 %
8413 % \DescribeRoutine{headpath}
8414 % \RoutineIndex{colorheadpath}
8415 % \RoutineIndex{headpathx}
8416 % \RoutineIndex{colorheadpathx}
8417 % \gbc{headpath} calls \gbc{Gheadpath}, a more general command that takes
8418 % a boolean expression and a shape (path) suffix as arguments. It
8419 % supplies \mfc{false} for the boolean and \gbc{Arrowhead} for the shape.
8420 % The \gbc{headpathx} version differs only in that the boolean is
8421 % \mfc{true}. The \gbc{color...} versions call \gbc{colorGheadpath} in the
8422 % same way, but require that a color parameter follow.
8423 % \begin{macrocode}
8424 def headpath = Gheadpath (false) (Arrowhead) enddef;
8425 def headpathx = Gheadpath (true) (Arrowhead) enddef;
8426
8427 def colorheadpath = colorGheadpath (false) (Arrowhead) enddef;
8428 def colorheadpathx = colorGheadpath (true) (Arrowhead) enddef;
8429
8430 % \end{macrocode}
8431 %
8432 % \DescribeRoutine{Gheadpath}
8433 % \RoutineIndex{colorGheadpath}
8434 % \RoutineIndex{Gheadpathx}
8435 % \RoutineIndex{colorGheadpathx}
8436 % For general arrowhead shapes we require two paths; one giving the shape
8437 % of the head and the other the shape that is cleared when the boolean
8438 % parameter \gbc{trim} is true. We pass this information by name with a
8439 % suffix parameter \gbc{ah} that names the head shape. Then \gbc{ah.clear}
8440 % names the cleared region. If \gbc{ah} is a cycle, the head is filled,
8441 % otherwise it is drawn with the current \gbc{drawpen}.
8442 % If one wants it drawn and center erased, one could place first the
8443 % solid (filled) version with color \mfc{background}, then the outline
8444 % (drawn only) version.
8445 %
8446 % We also need to know which point on the path is the tip, and
8447 % \gbc{ah.tip} provides that. If \gbc{ah.clear} is undefined, the clearing
8448 % is silently skipped. If \gbc{ah.tip} is unknown, it is taken to be
8449 % \mfc{(0,0)}. The head shape is assumed to be initially defined
8450 % pointing \mfc{up} (to match predefined shapes like \gbc{Triangle} and
8451 % \gbc{Diamond}).
8452 %
8453 % The standard symbols for \gbc{plot} have both the clearing path and
8454 % the tip defined. Thus one can produce \gbc{Diamond}-tipped arrows. The
8455 % old arrow heads are given by \gbc{Arrowhead}, which is redefined with
8456 % every call to \gbc{headshape}.
8457 %
8458 % If the \gbc{rot} and \gbc{pos} parameters are zero, the head is placed
8459 % with its tip at the end of the path, pointing in the direction of the
8460 % path at that point. Otherwise, the head is rotated around the tip by the
8461 % amount \gbc{rot} and \emph{then} shifted backward along its new
8462 % direction by the amount \gbc{pos}.
8463 %
8464 % We have a version that takes a color parameter. The simpler version
8465 % simply calls it with \gbc{clr} equal to \gbc{headcolor}.
8466 % \begin{macrocode}
8467 def Gheadpath (expr trim) (suffix ah) =
8468 colorGheadpath (trim) (ah) (headcolor)
8469 enddef;
8470 vardef colorGheadpath
8471 (expr trim) (suffix ah) (expr clr, sc, rot, pos) expr f =
8472 if (sc <> 0) and (known ah) and (path ah):
8473 convertpath (_g) f;
8474 setpair (_P) predirection[length _g] (_g);
8475 if _P <> origin:
8476 _P := _P rotated rot;
8477 setnumeric (_ang) anglefromto (up, _P);
8478 _P := pnt[length _g] (_g) - pos * _P;
8479 setpair (_tip) if known ah.tip: ah.tip else: origin fi;
8480
8481 if trim:
8482 if known ah.clear:
8483 safeunfill (ah.clear shifted - _tip)
8484 scaled sc
8485 rotated _ang
8486 shifted _P;
8487 fi
8488 setnumeric (_ys) max(bp, penwd, last_dot_size);
8489 safeunfill cut_path
8490 %<MP> xscaled sc yscaled _ys
8491 %<MF> xscaled ceiling sc yscaled ceiling _ys
8492 rotated _ang shifted _P;
8493 fi
8494 if cycle ah: colorsafefill else: colorsafedraw fi (clr)
8495 (ah shifted -_tip)
8496 scaled sc
8497 rotated _ang
8498 shifted _P;
8499 fi
8500 fi
8501 f
8502 enddef;
8503
8504
8505 % \end{macrocode}
8506 %
8507 % \DescribeVariable{cut_path}
8508 % Additional clearing path, almost the same as plain.mf's \gbc{cut_} (no
8509 % \gbc{cut_} in plain.mp) but rotated, and scaled differently. The odd
8510 % scaling is so that if yscaled by the diameter of a dot, and the dot
8511 % happens to be digitized to a square shape, then the \gbc{cut_path},
8512 % centered at the center of the dot and rotated 45 degrees, will encompass
8513 % the whole square (theoretically).
8514 % \begin{macrocode}
8515 path cut_path;
8516 cut_path := (.5,0)--(.5,.71)--(-.5,.71)--(-.5,0)--cycle;
8517
8518 % \end{macrocode}
8519 %
8520 % \DescribeRoutine{tailpath}
8521 % \RoutineIndex{colortailpath}
8522 % The macro \gbc{tailpath} places a tail at the start of a path. It is
8523 % almost like \gbc{Gheadpath} except there is no clearing done and the tip
8524 % is at the start (point 0) of the path. Also, the position parameter
8525 % \gbc{pos} is a forward shift.
8526 %
8527 % \DescribeRoutine{midpath}
8528 % \RoutineIndex{colormidpath}
8529 % The macro \gbc{midpath} is just like \gbc{tailpath} except it puts the
8530 % given shape somewhere in the middle of the path. Its position parameter
8531 % indicates the fraction of the length of the path where the shape is to
8532 % be placed. This works best in two cases: the shape has a definite
8533 % direction (like the \gbc{Arrowhead}) and the tip is placed at the given
8534 % position, or the shape has a center of symmetry and that is placed at
8535 % the given position. We obtain this in most cases by shifting $(0,0)$ to
8536 % that position. The standard arrowhead has its tip at this point, and the
8537 % standard symbols (with the exception of \gbc{Circle}) have their center
8538 % of symmetry there.
8539 % \begin{macrocode}
8540 def tailpath (suffix sh) = colortailpath (sh) (headcolor) enddef;
8541 vardef colortailpath (suffix sh) (expr clr, sc, rot, pos) expr f =
8542 if (sc <> 0) and (known sh) and (path sh):
8543 convertpath (_g) f;
8544 setpair(_P) postdirection0 (_g);
8545 if _P <> origin:
8546 _P := _P rotated rot;
8547 if cycle sh: colorsafefill else: colorsafedraw fi (clr)
8548 (sh if known sh.tip: shifted -sh.tip fi)
8549 scaled sc
8550 rotated anglefromto (up, _P)
8551 shifted (pnt0 (_g) + pos * _P);
8552 fi
8553 fi
8554 f
8555 enddef;
8556
8557 def midpath (suffix sh) = colormidpath (sh) (headcolor) enddef;
8558 vardef colormidpath (suffix sh) (expr clr, sc, rot, pos) expr f =
8559 if (sc <> 0) and (known sh) and (path sh):
8560 convertpath (_g) f;
8561 setnumeric (_t) pathtime[pos] (_g);
8562 setpair (_P) postdirection[_t] (_g);
8563 if _P <> origin:
8564 _P := _P rotated rot;
8565 if cycle sh: colorsafefill else: colorsafedraw fi (clr)
8566 sh scaled sc
8567 rotated anglefromto (up, _P)
8568 shifted (pnt[_t] (_g));
8569 fi
8570 fi
8571 f
8572 enddef;
8573
8574 % \end{macrocode}
8575 %
8576 %
8577 % \subsection{Randomizing a path}
8578 %
8579 % In order to randomly change a path, we need to randomly change its
8580 % points and its controls. If we just apply independent random shifts to
8581 % every point and control point, it could happen that the direction from a
8582 % point to a control changes dramatically, introducing a wild change even
8583 % with a small shift (if point and control were very close to begin with).
8584 % Also, this method would almost guarantee that a smooth path would
8585 % randomize into one with all corners. Our solution to these problems is
8586 % in the following paragraph.
8587 %
8588 % If $z\sb0$ and $z\sb3$ are the start and end points, with controls
8589 % $z\sb1$ and $z\sb2$, then we randomize $z\sb0$ and $z\sb3$ using a
8590 % random shift with size supplied as a parameter. If there was a
8591 % preceeding segment, its ending angle and the angle of $z\sb1-z\sb0$
8592 % determine an angle difference which we multiply by a random factor.
8593 % This determines the direction to the new control point. If there was no
8594 % preceeding segment we rotate $z\sb1-z\sb0$ a random amount. Finally we
8595 % randomly scale $|z\sb1-z\sb0|$.
8596 %
8597 % The following `\gbc{deviate}s' are analogous to \MF{}'s
8598 % \mfc{uniformdeviate}.
8599 % \DescribeRoutine{signeddeviate}
8600 % The first, \gbc{signeddeviate X}, produces a random number uniformly
8601 % distributed in $(-X, X)$. The second,
8602 % \DescribeRoutine{scaledeviate}
8603 % \gbc{scaledeviate (W, A)}, produces a pair in a particular direction
8604 % with length distributed in $(2^{-w}, 2^w)$.
8605 % \DescribeRoutine{polardeviate}
8606 % The third, \gbc{polardeviate R} produces a pair whose polar coordinates
8607 % are separately uniformly distributed, the radius over the interval $(0,
8608 % R)$ the angle over $(0,360)$.
8609 % \DescribeRoutine{xydeviate}
8610 % The last, \gbc{xydeviate (X,Y)}, produces a pair uniformly distributed
8611 % over the rectangle with corners at $(-X,-Y)$ and $(X,Y)$.
8612 %
8613 % \DescribeRoutine{randompair}
8614 % Finally, \gbc{randompair} runs \gbc{polardeviate} if \gbc{X} is
8615 % numeric and \gbc{pairdeviate} if it is a pair.
8616 % \begin{macrocode}
8617 vardef signeddeviate primary X =
8618 (uniformdeviate 1)[-X,X]
8619 enddef;
8620 vardef scaledeviate (expr W, A) =
8621 2 ** (signeddeviate W) * dir A
8622 enddef;
8623 vardef polardeviate primary R =
8624 (uniformdeviate abs(R)) * dir uniformdeviate 360
8625 enddef;
8626 vardef xydeviate primary Z =
8627 (signeddeviate (xpart Z), signeddeviate (ypart Z))
8628 enddef;
8629
8630 vardef randompair (expr maxshift) =
8631 if numeric maxshift: polardeviate (maxshift)
8632 elseif pair maxshift: xydeviate (maxshift)
8633 else: (0,0)
8634 fi
8635 enddef;
8636
8637 % \end{macrocode}
8638 %
8639 % \DescribeRoutine{randompath}
8640 % The \gbc{randompath} macro returns a path formed from \gbc{f} by
8641 % shifting each of its point with independent instances of
8642 % \gbc{randompair (maxshift)}. Its control points are also modified, but
8643 % the algorithm is not as simple.
8644 %
8645 % Let $X$ be one of the points of \gbc{f}, with precontrol $X-U$ and
8646 % postcontrol $X+V$. We create random $X'$, $U'$ and $V'$ as follows.
8647 %
8648 % Let $S$ be the pair that results from \gbc{randompair(maxshift)}, let
8649 % $w$ be the value of \gbc{weirdness}, let $\eta\sb j(w)$ be the value of
8650 % the $j$th instance of \gbc{signeddeviate ($w$)}.
8651 % Then $X' = X + S$, $U'$ is $U$ rotated $\beta=30\eta\sb1(w)$ and scaled
8652 % $\sigma = 2^{\eta\sb2(w)}$. Let $\alpha$ be the angle between the two
8653 % vectors $U$ and $V$. Then $V'$ is $\sigma V$ rotated to make the angle
8654 % between $U'$ and $V'$ equal to $\alpha 2^{\eta\sb3(w)}$.
8655 % In the new path, the point is $X'$ with precontrol $X'-U'$ and
8656 % postcontrol $X' + V'$. Note that if the path is smooth at $X$, then
8657 % $\alpha = 0$ and the new angle is also $0$.
8658 %
8659 % \DescribeRoutine{randomlines}
8660 % This is a simpler version that simply shifts the nodes and connects
8661 % the results with straight lines. It is intended to be applied to
8662 % polyline paths.
8663 %
8664 % \DescribeRoutine{detrivialized}
8665 % We start with a routine that strips out trivial segments from a path.
8666 % This makes some loops a lot easier. It would be weird to differently
8667 % shift the two (equal) endpoints of a trivial segment.
8668 % \begin{macrocode}
8669 vardef detrivialized expr f =
8670 save g; path p, g[]; g := 0;
8671 for k = 1 upto length f:
8672 p := subpath (k-1,k) of f;
8673 if not trivial p: g[incr g] := p; fi
8674 endfor
8675 if g = 0: onepointpath (cycle f, pnt0(f))
8676 else: g1 for k = 2 upto g: &g[k] endfor if cycle f: &cycle fi
8677 fi
8678 enddef;
8679
8680 vardef randompath (expr maxshift, weirdness) expr f =
8681 save g, n; path g;
8682 g := detrivialized f;
8683 n := length g;
8684 if n = 0:
8685 f shifted randompair (maxshift)
8686 else:
8687 save X, U, V;
8688 pair X[], U[], V[];
8689 if cycle g: n := n - 1; fi
8690 for k = 0 upto n:
8691 X[k] := pnt[k](g);
8692 U[k] := X[k] - pre[k](g);
8693 V[k] := post[k](g) - X[k];
8694 endfor
8695 save A, B;
8696 for k := 0 upto n:
8697 X[k] := X[k] shifted randompair (maxshift);
8698 A := anglefromto (U[k],V[k]);
8699 B := signeddeviate (30weirdness);
8700 U[k] := X[k] - (U[k] zscaled scaledeviate (weirdness,B));
8701 B := B - A + A * (2 ** signeddeviate weirdness);
8702 V[k] := X[k] + (V[k] zscaled scaledeviate (weirdness,B));
8703 endfor
8704 X0 for k = 1 upto n:
8705 .. controls V[k-1] and U[k] .. X[k]
8706 endfor
8707 if cycle g:
8708 .. controls V[n] and U0 .. cycle
8709 fi
8710 fi
8711 enddef;
8712
8713 vardef randomlines (expr maxshift) expr f =
8714 save g, n; path g;
8715 g := detrivialized f;
8716 n := length g;
8717 if n = 0:
8718 f shifted randompair (maxshift)
8719 else:
8720 if cycle g: n := n - 1; fi
8721 (pnt0(g) shifted randompair (maxshift))
8722 for k = 1 upto n:
8723 -- (pnt[k](g) shifted randompair (maxshift))
8724 endfor
8725 if cycle g:
8726 -- cycle
8727 fi
8728 fi
8729 enddef;
8730
8731 % \end{macrocode}
8732 %
8733 %
8734 % \subsection{Interpolating paths}
8735 %
8736 % Given two cubic B\'eziers, it is straightforward to create a path that
8737 % is ``half-way between'' them: just take its control points to be
8738 % at the midpoint between corresponding control points of the two
8739 % B\'eziers. Two paths made up of an equal number of B\'ezier are also
8740 % easily interpolated. However, two paths with different numbers of
8741 % B\'ezier segments need to be subdivided until they have an equal
8742 % number.
8743 %
8744 % \DescribeRoutine{interpolatedpath}
8745 % This command accepts a number \gbc{num}, a path or pair \gbc{P} and a
8746 % path \gbc{Q}. It returns a path which is somewhere ``between'' \gbc{P}
8747 % and \gbc{Q} if the number is between $0$ and $1$. The case where \gbc{P}
8748 % or \gbc{Q} is trivial is passed on to another command which is
8749 % considerably more efficient for that case. In the more general case, the
8750 % paths are rewritten so that they have equal length. For example, if
8751 % \gbc{P} has length 2 and \gbc{Q} has length 1, then \gbc{Q} is rewritten
8752 % as\\
8753 % \indent \gbc{subpath (0,1/2) of Q \& subpath (1/2,1) of Q}\\
8754 % which follows the same course as \gbc{Q} but has the same number of
8755 % B\'ezier parts as \gbc{P}.
8756 %
8757 % The splitting of \gbc{Q} shown above can, for reasons unknown to me,
8758 % produce adjacent subpaths that do not always share an endpoint. One
8759 % would think that \gbc{subpath (s,t) of Q} and
8760 % \gbc{subpath (t,u) of Q} would obviously end and start, respectively,
8761 % at \gbc{point t of Q}. Alas, they don't always. Hence, we employ
8762 % \gbc{force_equal_ends} to to make them equal, shifting their endpoints a
8763 % microscopic amount.
8764 %
8765 % If \gbc{Q} is a cycle we want the returned path to also be a cycle
8766 % (but not otherwise). This is possible whenever the ends of \gbc{P} are
8767 % equal.
8768 % \begin{macrocode}
8769 vardef interpolatedpath (expr t, P) expr Q =
8770 if not path Q:
8771 GBerrmsg ("Improper argument to interpolatedpath.")
8772 "The last argument to interpolatedpath must be a path.";
8773 if pair P: onepointpath(false, P)
8774 else:
8775 if path P:
8776 P
8777 else:
8778 onepointpath (false, origin)
8779 fi
8780 fi
8781 elseif pair P:
8782 interpolated_pair_path (t, cycle Q, P, Q)
8783 elseif not path P:
8784 GBerrmsg ("Improper argument to interpolatedpath.")
8785 "The second argument to interpolatedpath must be a pair "
8786 & "or a path.";
8787 Q
8788 else:
8789 if t=0: Q
8790 elseif t=1: P
8791 else:
8792 save P_, Q_; path P_, Q_;
8793 P_ := detrivialized P;
8794 Q_ := detrivialized Q;
8795 if length P_ = 0:
8796 interpolated_pair_path (t, cycle Q, pnt0(P_), Q)
8797 elseif length Q_ = 0:
8798 interpolated_pair_path (t, cycle Q, pnt0(Q_), P)
8799 else:
8800 save G, H, n, m, k, r;
8801 path G[], H[];
8802 G := H := 0;
8803 n := length P_; m := length Q_;
8804 k := gcd(n, m);
8805 r := m/k;
8806 for I=0 upto n-1:
8807 for J=0 upto r-1:
8808 G[incr G] := subpath (I+J/r, I+(J+1)/r) of P_;
8809 endfor
8810 endfor
8811 r := n/k;
8812 for I=0 upto m-1:
8813 for J=0 upto r-1:
8814 H[incr H] := subpath (I+J/r, I+(J+1)/r) of Q_;
8815 endfor
8816 endfor
8817 for N = 1 upto G-1:
8818 force_equal_ends(G[N], G[N+1]);
8819 force_equal_ends(H[N], H[N+1]);
8820 endfor
8821 interpolated_segment (t, G1, H1)
8822 for N = 2 upto G: & interpolated_segment (t, G[N], H[N])
8823 endfor if (pnt0(G1)=pnt1(G[G])) and (cycle Q): & cycle fi
8824 fi
8825 fi
8826 fi
8827 enddef;
8828
8829 % \end{macrocode}
8830 % \DescribeRoutine{interpolated_pair_path}
8831 % Since we cannot rely on the cyclicity of \gbc{Q}, we pass a boolean
8832 % parameter . That is because the second argument here might actually
8833 % have been the first argument of \gbc{interpolatedpath}.
8834 % \begin{macrocode}
8835 vardef interpolated_pair_path (expr t, cyclic, P, Q) =
8836 save N; N := length Q;
8837 if N=0: onepointpath (cyclic, (t)[pnt0(Q),P])
8838 else:
8839 (t)[pnt0(Q),P]..controls (t)[post0(Q),P] and
8840 for n=1 upto N - 1:
8841 (t)[pre[n](Q),P]..(t)[pnt[n](Q),P]..controls (t)[post[n](Q),P]
8842 and
8843 endfor
8844 (t)[pre[N](Q),P].. if cyclic: cycle else: (t)[pnt[N](Q),P] fi
8845 fi
8846 enddef;
8847
8848 vardef interpolated_segment (expr t, S, T) =
8849 (t)[ pnt0(S), pnt0(T)]..controls
8850 (t)[ post0(S), post0(T)] and (t)[ pre1(S), pre1(T)]..
8851 (t)[ pnt1(S), pnt1(T)]
8852 enddef;
8853
8854 % \end{macrocode}
8855 %
8856 % \subsection{Parallelling a path}
8857 %
8858 % \DescribeRoutine{parasegment}
8859 % This creates a path parallel to a given cubic B\'ezier segment \gbc{f}.
8860 % It should be called by a command (such as \gbc{parapath}) that makes
8861 % sure \gbc{f} is nontrivial (meaning the directions are non-zero). It
8862 % splits the segment into subsegments for accuracy. Its arguments are the
8863 % distance the original path is shifted, the number of subsegments to
8864 % split into, and the path.
8865 % \begin{macrocode}
8866 vardef parasegment (expr d, segs, f) =
8867 if d = 0: f
8868 else:
8869 save u, v, t; pair u[], v[];
8870 for n = 0 upto segs:
8871 t := n/segs;
8872 u[n] := postdirection [t] (f);
8873 v[n] := pnt[t] (f) + (u[n] zscaled (0,d));
8874 endfor
8875 v0{u0}
8876 for n = 1 upto segs: ...v[n]{u[n]} endfor
8877 fi
8878 enddef;
8879
8880 % \end{macrocode}
8881 %
8882 % \DescribeRoutine{parapath}
8883 % Attempt to parallel one path with another at a distance \gbc{d}. The
8884 % algorithm is as follows:
8885 % \begin{enumerate}
8886 % \item Create an array of paths that parallel each segment of \gbc{f}.
8887 % \item Redo the array by adding a half circle at each end. The purpose
8888 % of the half circle is to force consecutive elements of the array
8889 % to intersect (I hope).
8890 % \item Do something like \mfc{buildcycle}: where consecutive array
8891 % elements intersect, strip the the elements to the subpaths between
8892 % intersection points, and join them directly.
8893 % \item If \gbc{f} is a cycle, process the joining at the endpoints in
8894 % the same way.
8895 % \end{enumerate}
8896 % We use \gbc{force_equal_ends} to force exact equality of endpoints so
8897 % we can join segments with \mfc{\&}. The reason for prefering the
8898 % \mfc{\&} join is to permit better performance of macros (such as this
8899 % one) that take a path apart into segments. If we used `\mfc{..}' instead
8900 % then the returned path would have a great many added segments, nearly
8901 % all of which are nearly trivial. For similar reasons we drop trivial
8902 % segments of \gbc{f}.
8903 % \begin{macrocode}
8904 vardef parapath (expr d) expr f =
8905 if d = 0:
8906 f
8907 else:
8908 save a, g, h, p, q, s, t, u, v, w;
8909 path g[], h, p[], q[];
8910 numeric a, s, t;
8911 pair u, v, w, w[];
8912 s := emax(3, emin(segment_split, ceiling(max_points/5/length f)));
8913 p := 0;
8914 for i = 1 upto length f:
8915 h := subpath (i-1, i) of f;
8916 if not trivial h:
8917 q[incr p] := h;
8918 p[p] := parasegment (d, s, h);
8919 fi
8920 endfor
8921 if p = 0:
8922 f
8923 else:
8924 a := if d>0: - fi 180;
8925 h := p1;
8926 for i = 1 upto p-1:
8927 u := predirection 1 (q[i]);
8928 v := postdirection 0 (q[i+1]);
8929 w1 := pnt 1 (q[i]) - (u zscaled (0,d));
8930 w2 := pnt 0 (q[i+1]) - (v zscaled (0,d));
8931 w3 := pnt [infinity] (h);
8932 w4 := pnt 0 (p[i+1]);
8933 g0 := arcpps(w3, w1, a);
8934 g1 := h & g0;
8935 g2 := arcpps(w2, w4, a) & p[i+1];
8936 if (p[i] & g0) intersects reverse g2:
8937 s := length g2 - _Ytime;
8938 t := length h - length p[i] + _Xtime;
8939 g1 := subpath (0, t) of g1;
8940 g2 := subpath (s, length g2) of g2;
8941 force_equal_ends (g1, g2);
8942 h := g1 & g2;
8943 else:
8944 h := h .. p[i+1];
8945 fi
8946 endfor
8947
8948 if cycle f:
8949 u := predirection 1 (q[p]);
8950 v := postdirection 0 (q[1]);
8951 w1 := pnt 1 (q[p]) - (u zscaled (0,d));
8952 w2 := pnt 0 (q[1]) - (v zscaled (0,d));
8953 w3 := pnt [infinity] (h);
8954 w4 := pnt 0 (p[1]);
8955 g3 := arcpps(w3, w1, a);
8956 g0 := arcpps(w2, w4, a);
8957 g1 := g0 & h & g3;
8958 g2 := g0 & p[1];
8959 if (p[p] & g3) intersects reverse g2:
8960 s := length g2 - _Ytime;
8961 t := length g0 + length h - length p[p] + _Xtime;
8962 g1 := subpath (s, t) of g1;
8963 force_equal_ends (g1, g1);
8964 h := g1 & cycle;
8965 else:
8966 h := h..cycle;
8967 fi
8968 fi
8969 h
8970 fi
8971 fi
8972 enddef;
8973
8974 vardef turnangle@# (expr f) =
8975 anglefromto(predirection@# (f), postdirection@#(f))
8976 enddef;
8977
8978 % \end{macrocode}
8979 %
8980 %
8981 % \section{Miscellaneous}\label{misc}
8982 %
8983 % \subsection{Implementation of \mfpic{}'s \cs{plotdata} command}%
8984 % \label{plotdata}
8985 %
8986 % In \mfpic, the \cs{plotdata} command draws several curves with one
8987 % command. The curves are drawn with changeable methods of rendering.
8988 % There are three schemes. The first draws the curves with different dash
8989 % patterns. Another scheme is to plot the curves with different symbols.
8990 % Still another is to use different colors (\MP{} only).
8991 %
8992 % We implement the changing of patterns (symbols, colors) by defining
8993 % arrays of such things and changing the index into the array. For
8994 % example, when the user has selected dashes, the first curve is
8995 % \gbc{gendashed} with the pattern \gbc{dashtype0}, the next with
8996 % \gbc{dashtype1}, etc.
8997 %
8998 % \DescribeRoutine{setdatadashes}
8999 % We have this method for users to select their own dash patterns. The
9000 % \gbc{setdatadashes} command requires a list of suffixes previously
9001 % defined by the \gbc{dashpat} command. Since a dash pattern need only
9002 % be an array, we check if it is one and, if it is, we copy it to the
9003 % next \gbc{dashtype[n]}. We actually copy it to a temporary array and
9004 % make sure there are at least two patterns before we overwrite
9005 % \gbc{dashtype}.
9006 %
9007 % \DescribeRoutine{getdashpat}
9008 % We have removed this mod-ing operation from \TeX, where it is
9009 % cumbersome, to \MF, where it is trivial.
9010 % \begin{macrocode}
9011 def setdatadashes (text lst) =
9012 save __type; __type := 0;
9013 forsuffixes _itm = lst:
9014 if knownnumericarray _itm :
9015 copyarray (_itm) (__type[__type]);
9016 next __type;
9017 else: GBwarn "Improper dash pattern in setdatadashes.";
9018 fi
9019 endfor
9020 if __type > 1:
9021 save dashtype; dashtype := __type;
9022 for _j = 0 upto dashtype - 1:
9023 copyarray (__type[_j]) (dashtype[_j]);
9024 endfor
9025 else:
9026 SetdataWarn "dashes";
9027 fi
9028 enddef;
9029 def getdashpat expr n = dashtype[n mod dashtype] enddef;
9030
9031 def SetdataWarn expr s =
9032 GBwarn "command setdata"& s &"() failed. Previous values retained.";
9033 enddef;
9034
9035 % \end{macrocode}
9036 %
9037 % \DescribeRoutine{defaultdashes}
9038 % These are the default dash patterns. Their setting is done by a macro
9039 % so the user may easily restore them. The spaces are apparently larger
9040 % than the dashes, but taking the thickness of the pen into account
9041 % (\mfc{.5bp}) the dashes will appear about \mfc{.5bp} larger than stated
9042 % and the spaces about \mfc{.5bp} smaller (unless the user inexplicably
9043 % sets \mfc{linecap} to \mfc{butt}).
9044 % \begin{macrocode}
9045 numeric Solid, Simpledash, Simpledot, Dotdash, Dotdashdot, Dotdashdash;
9046 dashpat (Solid) (0);
9047 dashpat (Simple_dash) (3bp, 4bp);
9048 dashpat (Simple_dot) (0, 4bp);
9049 dashpat (Dot_dash) (0, 4bp, 3bp, 4bp);
9050 dashpat (Dot_dash_dot) (0, 4bp, 3bp, 4bp, 0, 4bp);
9051 dashpat (Dot_dash_dash) (0, 4bp, 3bp, 4bp, 3bp, 4bp);
9052
9053 numeric dashtype, dashtype[], dashtype[][];
9054 def defaultdashes =
9055 setdatadashes (Solid, Simple_dash, Simple_dot,
9056 Dot_dash, Dot_dash_dot, Dot_dash_dash);
9057 enddef;
9058 defaultdashes;
9059
9060 % \end{macrocode}
9061 %
9062 % \DescribeRoutine{setdatasymbols}
9063 % This can be used to define the sequence of point plotting styles for
9064 % \mfpic's \cs{plotdata} command. It is quite similar to
9065 % \gbc{setdatadashes} above and \gbc{setdatacolors} below.
9066 %
9067 % \DescribeRoutine{getsymbol}
9068 % This is similar to \gbc{getdashpat}. In fact we could write a
9069 % single macro to do both, but I think we get a more readable \mfpic{}
9070 % output file if we have separate commands.
9071 % \begin{macrocode}
9072 def setdatasymbols (text lst) =
9073 save __type; path __type[];
9074 __type := 0;
9075 for _itm = lst:
9076 if (known _itm) and (path _itm):
9077 __type[__type] := _itm;
9078 next __type;
9079 else:
9080 GBwarn "Improper symbol in setdatasymbols().";
9081 fi
9082 endfor
9083 if __type > 1:
9084 save pointtype; pointtype := __type;
9085 path pointtype[];
9086 for _j = 0 upto pointtype - 1:
9087 pointtype[_j] := __type[_j];
9088 endfor
9089 else:
9090 SetdataWarn "symbols";
9091 fi
9092 enddef;
9093 def getsymbol expr n := pointtype[n mod pointtype] enddef;
9094
9095 % \end{macrocode}
9096 %
9097 % Before we can set the default symbols we need to define some. They need
9098 % to be paths. The ones below named with `\gbc{Solid}' are closed paths.
9099 % Since the drawing commands that use them feed the path to \gbc{setdot},
9100 % they end up filled if they are cyclic, merely drawn if not.
9101 %
9102 % All are intended to have roughly the area (when area makes sense) of a
9103 % circle with diameter 1. The scaling factors are the square root of the
9104 % ratios of the areas.
9105 %
9106 % Associated with each is a another path with the same basename and the
9107 % suffix \gbc{clear} and a pair with the suffix \gbc{tip}. Moreover,
9108 % they are (mostly) symmetric about the $y$-axis pointing (where that
9109 % makes sense) in the direction \mfc{up}. The purpose of all this is so
9110 % that they can be plugged into code for adding arrowheads/tails of
9111 % different shapes.\VariableIndex{Triangle}\VariableIndex{Square}
9112 % \VariableIndex{Circle}\VariableIndex{Diamond}\VariableIndex{Star}
9113 % \VariableIndex{Plus}\VariableIndex{Cross}\VariableIndex{Asterisk}
9114 % \VariableIndex{Crossbar}\VariableIndex{Leftbar}\VariableIndex{Rightbar}
9115 % \VariableIndex{Righthook}\VariableIndex{Lefthook}
9116 % \VariableIndex{SolidTriangle}\VariableIndex{SolidSquare}
9117 % \VariableIndex{SolidCircle}\VariableIndex{SolidDiamond}
9118 % \VariableIndex{SolidStar}
9119 % \begin{macrocode}
9120 def DeclareGBSymbols (text S) =
9121 forsuffixes _itm = S:
9122 path _itm;
9123 path _itm.clear;
9124 pair _itm.tip;
9125 endfor
9126 enddef;
9127 DeclareGBSymbols(
9128 Triangle, Square, Circle, Diamond, Star, Plus, Cross,
9129 Asterisk, Crossbar, Leftbar, Rightbar, Righthook,
9130 Lefthook, SolidTriangle, SolidSquare, SolidCircle,
9131 SolidDiamond, SolidStar
9132 );
9133
9134 vardef undo_cycle expr f = subpath (0, length f) of f enddef;
9135
9136 SolidTriangle := (up--(dir 210)--(dir -30)--cycle) scaled .78;
9137 Triangle := undo_cycle SolidTriangle;
9138
9139 Triangle.clear := SolidTriangle.clear :=
9140 ((dir -30)--(cosd 30,1)--(cosd 210,1)--(dir 210)--up--cycle)
9141 scaled .78;
9142
9143 SolidSquare := (up--(-1,1)--(-1,-1)--(1,-1)--(1,1)--cycle) scaled .443;
9144 Square := undo_cycle SolidSquare;
9145
9146 SolidCircle := fullcircle rotated 90;
9147 Circle := undo_cycle SolidCircle;
9148 Circle.clear := SolidCircle.clear :=
9149 halfcircle--(-.5,.5)--(.5,.5)--cycle;
9150
9151 SolidDiamond := (up--left--down--right--cycle)
9152 scaled .522 yscaled 1.44;
9153 Diamond := undo_cycle SolidDiamond;
9154 Diamond.clear := SolidDiamond.clear :=
9155 (right--(1,1)--(-1,1)--left--up--cycle) scaled .522 yscaled 1.44;
9156
9157 Plus := ((0,0)--up--down--(0,0)--left--right) scaled .65;
9158 Plus.clear := (right--(1,1)--(-1,1)--(left)--cycle) scaled .65;
9159
9160 Cross := ((0,0)--(dir 45)--(dir -135)--(0,0)--(dir -45)--(dir 135))
9161 scaled .65;
9162 Cross.clear :=
9163 ((0,0)--(dir -45)--dir(45)--(dir 135)--(dir -135)--cycle) scaled .65;
9164
9165 Asterisk := ((0,0)--up--down--(0,0)--(dir 30)--(dir -150)
9166 --(0,0)--(dir -30)--(dir 150)) scaled .6;
9167 Asterisk.clear := ((0,0)--(dir -30)--(cosd 30,1)--(cosd 150,1)
9168 --(dir -150)--cycle) scaled .6;
9169
9170 Crossbar := ((0,0)--left--right) scaled .65;
9171 Crossbar.clear := rect (right,(-1,.5)) scaled .65;
9172
9173 Leftbar := ((0,0)--left);
9174 Rightbar := ((0,0)--right);
9175 Leftbar.clear := rect((0,0),(-1,.5));
9176 Rightbar.clear := rect((0,0),(1,.5));
9177
9178 Righthook := arcpps((0,0),(1,0),180);
9179 Lefthook := Righthook xscaled -1;
9180 Righthook.clear := Righthook--cycle;
9181 Lefthook.clear := Lefthook--cycle;
9182
9183 % \end{macrocode}
9184 %
9185 % We do some computations to find the vertices of an n-pointed
9186 % star. We assume that \mfc{A1} is \mfc{up} and the line from there
9187 % to \mfc{A[1 + m]} determines one side of the top point of the star.
9188 % We must have $2 \le {}$\gbc{m}${}\le{}$\gbc{n}${}-2$. The rest of the
9189 % vertices are determined by symmetry. \gbc{Star} is made with \gbc{n=5}
9190 % and \gbc{m=2}. We store the points in an array so we can use them for
9191 % the \gbc{Star.clear} path.
9192 % \begin{macrocode}
9193 vardef mkstar (expr n, m) (suffix A) =
9194 save ang; ang := 360/n;
9195 A1 := up; A3 := up rotated ang;
9196 A2 = (whatever)[A1, A1 rotated ( ang*m)];
9197 A2 = (whatever)[A3, A3 rotated (-ang*m)];
9198 for i = 4 upto 2n:
9199 A[i] := A[i-2] rotated ang;
9200 endfor
9201 A := 2n;
9202 mkpoly (true, A)
9203 enddef;
9204
9205 save _A; pair _A[];
9206 SolidStar := mkstar (5, 2, _A) scaled .84;
9207 Star := undo_cycle SolidStar;
9208 Star.clear := polyline (true)
9209 (_A9, _A10, _A1, _A2, _A3, (xpart _A3, 1), (xpart _A9, 1))
9210 scaled .84;
9211 SolidStar.clear := Star.clear;
9212
9213 forsuffixes S =
9214 Triangle, Square, Circle, Diamond, Star, Plus, Cross,
9215 Asterisk, Crossbar, Leftbar, Rightbar, Righthook,
9216 Lefthook, SolidTriangle, SolidSquare, SolidCircle,
9217 SolidDiamond, SolidStar :
9218 S.tip := point 0 of S;
9219 endfor
9220
9221 % \end{macrocode}
9222 %
9223 % \DescribeRoutine{gcd}
9224 % I thought I was going to use \gbc{gcd} for the \gbc{mkstar} routine
9225 % above, but went another way. Still, it might have a future use. Once we
9226 % have it,
9227 % \DescribeRoutine{lcm}
9228 % \gbc{lcm} is a snap. Since \gbc{gcd} always returns a positive result,
9229 % \gbc{lcm} satisfies the rule for signs of products. Note that these both
9230 % silently accept noninteger arguments, though the results may not be very
9231 % meaningful.
9232 % \begin{macrocode}
9233 vardef gcd (expr n, m) =
9234 save a, b, r;
9235 a := emax (abs(m), abs(n));
9236 b := emin (abs(m), abs(n));
9237 if b > 0:
9238 forever:
9239 r := a mod b;
9240 exitif r < 1;
9241 a := b; b := r;
9242 endfor
9243 b
9244 else:
9245 a
9246 fi
9247 enddef;
9248
9249 vardef lcm (expr n, m) =
9250 n/gcd(n, m)*m
9251 enddef;
9252
9253 % \end{macrocode}
9254 %
9255 % \DescribeRoutine{defaultsymbols}
9256 % The command for restoring the default symbols.
9257 % \begin{macrocode}
9258 numeric pointtype; path pointtype[];
9259 def defaultsymbols =
9260 setdatasymbols( Circle, Cross, SolidDiamond, Square, Plus,
9261 Triangle, SolidCircle, Star, SolidTriangle);
9262 enddef;
9263 defaultsymbols;
9264
9265 % \end{macrocode}
9266 %
9267 % \DescribeRoutine{setdatacolors}
9268 % Finally, for \MP, we do a similar pair of commands for setting
9269 % the colors for the \cs{plotdata} command, and for
9270 % \DescribeRoutine{getcolor}
9271 % getting the next one. The odd indirection (\gbc{colortype[]} is an array
9272 % of strings, the names of variables having color values) is because \MP{}
9273 % now has three different data types for colors. Arrays must be all one
9274 % type.
9275 %
9276 % \DescribeRoutine{defaultcolors}
9277 % These default colors were tested on screen and on an inkjet printer.
9278 % The adjustments away from pure colors is based on a compromise between
9279 % those experiments.
9280 % \begin{macrocode}
9281 %<*MP>
9282 def setdatacolors (text lst) =
9283 setnumeric (__type) 0;
9284 % First, just count and store the known colors in the list
9285 for _itm = lst:
9286 if knowncolor _itm :
9287 if __type = 0 : def _datacolors = _itm enddef;
9288 else:
9289 expandafter def
9290 expandafter _datacolors
9291 expandafter = _datacolors, _itm enddef;
9292 fi
9293 next __type;
9294 else: GBwarn "Improper color in setdatacolors().";
9295 fi
9296 endfor
9297 if __type > 1:
9298 save colortype, _tmpstr;
9299 colortype := 0;
9300 % colortype[] is an array of strings:
9301 string colortype[], _tmpstr;
9302 for _itm = _datacolors: %
9303 % Each string is the name of some color variable
9304 _tmpstr := "colortype_" & GBromannumeral(colortype);
9305 setcolor (scantokens(_tmpstr)) _itm;
9306 colortype[colortype] := _tmpstr;
9307 next colortype;
9308 endfor
9309 else:
9310 SetdataWarn "colors";
9311 fi
9312 enddef;
9313 def getcolor expr n = (scantokens (colortype[n mod colortype])) enddef;
9314
9315 numeric colortype; string colortype[];
9316
9317 setcolor (dRed) (1, 0, 0);
9318 setcolor (dBlue) (.2,.2,1);
9319 setcolor (dOrange) (1,.34,0);
9320 setcolor (dGreen) (0,.80,0);
9321 setcolor (dBlack) cmykblack;
9322 if has_cmyk :
9323 setcolor (dCyan) cyan;
9324 setcolor (dMagenta) magenta;
9325 setcolor (dYellow) yellow;
9326 else: % rgb colors seem to be lighter than the cmyk equivalents.
9327 setcolor (dCyan) cmyk(.85,0,0,.15);
9328 setcolor (dMagenta) cmyk(0,.85,0,.15);
9329 setcolor (dYellow) cmyk(0,0,.85,.15);
9330 fi
9331 def defaultcolors =
9332 setdatacolors(dBlack, dRed, dBlue, dOrange,
9333 dGreen, dMagenta, dCyan, dYellow);
9334 enddef;
9335 defaultcolors;
9336
9337 %</MP>
9338 % \end{macrocode}
9339 %
9340 %
9341 % \subsection{Pie Charts and Bar Charts}\label{charts}
9342 %
9343 % \DescribeRoutine{computepie}
9344 % The \gbc{computepie} command calculates the wedges of a pie from the text
9345 % parameter \gbc{data}. It should be a list of positive numerics, and the
9346 % result will be one wedge for each datum, the area of the wedge being
9347 % proportional to the corresponding datum. The wedge for each datum has
9348 % its point at \gbc{cent} and the wedge for the first datum begins at
9349 % angle \gbc{ang}. Each wedge is clockwise from the preceding one if
9350 % \gbc{sign = -1}, otherwise anticlockwise. The radius of the pie is
9351 % \gbc{rad}.
9352 %
9353 % \DescribeRoutine{piechart}
9354 % This calls \gbc{computepie} to calculate the angles and store that in
9355 % the array \gbc{_dat}, then \gbc{mkpiewedges} creates the actual user
9356 % level arrays. This separation allows us (in a future enhancement) to
9357 % easily handle named piecharts, so there can be more than one defined at
9358 % a time.
9359 % \begin{macrocode}
9360 def computepie (suffix dat) (expr sign, ang, cent, rad) (text data) =
9361 begingroup
9362 save _tot, _max, _toobig;
9363 _max := 0; dat := 0;
9364 for _val = data:
9365 dat[incr dat] := _val;
9366 _max := emax (_max, _val);
9367 endfor
9368 if dat=0: GBwarn "piechart attempted with empty list.";
9369 _toobig := 1;
9370 else:
9371 _toobig := infinity/dat;
9372 fi
9373 if _max > _toobig:
9374 for _idx = 1 upto dat:
9375 dat[_idx] := dat[_idx]/_toobig;
9376 endfor
9377 fi
9378 for _idx = 2 upto dat:
9379 dat[_idx] := dat[_idx - 1] + dat[_idx];
9380 endfor
9381 _tot := dat[dat];
9382 for _idx = dat downto 2:
9383 dat[_idx] := ang + sign*dat[_idx-1]/_tot*360;
9384 endfor
9385 dat1 := ang; dat[dat + 1] := ang + 360sign;
9386 endgroup
9387 enddef;
9388
9389 def piechart (expr sign, ang, cent, rad) (text data) =
9390 save _dat;
9391 computepie (_dat) (sign, ang, cent, rad) (data);
9392 mkpiewedges (_dat, cent, rad);
9393 enddef;
9394
9395 % \end{macrocode}
9396 %
9397 % \DescribeRoutine{mkpiewedges}
9398 % The wedges (closed sectors) are stored in the array \gbc{piewedge[\,]}
9399 % with the numeric \gbc{piewedge} holding the number of wedges. The center
9400 % is saved in \gbc{piecenter}, the directions of the wedges (the bisecting
9401 % rays) are stored in \gbc{piedirection[\,]}, the starting angles of the
9402 % wedges in \gbc{pieangle[\,]}
9403 % \begin{macrocode}
9404 def mkpiewedges (suffix dat) (expr cent, rad) =
9405 numeric piewedge, piedirection, pieangle, pieangle[];
9406 pair piecenter, piedirection[];
9407 path piewedge[];
9408 piecenter := cent;
9409 piedirection := pieangle := piewedge := dat;
9410 for _idx = 1 upto dat:
9411 pieangle[_idx] := dat[_idx];
9412 piewedge[_idx] := sector (piecenter, rad, dat[_idx], dat[_idx+1]);
9413 piedirection[_idx] := dir(0.5[ dat[_idx], dat[_idx+1] ]);
9414 endfor
9415 enddef;
9416
9417 % \end{macrocode}
9418 %
9419 % \DescribeRoutine{namedpiechart}
9420 % This is a future enhancement. It takes a suffix, the name of the chart
9421 % which will be the base name of the various arrays and key values, and
9422 % will be a numeric equal to the number of wedges. The first part is
9423 % identical to that of \gbc{piechart} above. Note that some elements
9424 % of the chart are not (yet) directly accessible. Those needed by mfpic
9425 % are: the paths, the directions and the center. The rest would be easy
9426 % to add.
9427 % \begin{macrocode}
9428 def namedpiechart (suffix nm) (expr sign, ang, cent, rad) (text data) =
9429 save _dat;
9430 computepie (_dat) (sign, ang, cent, rad) (data);
9431 setnumeric (nm) _dat;
9432 pair nm.center, nm.direction[];
9433 path nm.wedge[];
9434 nm.center := cent;
9435 for _idx = 1 upto _dat:
9436 nm.wedge[_idx] := sector (cent, rad, _dat[_idx], _dat[_idx+1]);
9437 nm.direction[_idx] := dir(0.5[ _dat[_idx], _dat[_idx+1] ]);
9438 endfor
9439 enddef;
9440
9441 % \end{macrocode}
9442 %
9443 % \DescribeRoutine{barchart}
9444 % I was told that there are better ways (than piecharts) to represent
9445 % quantitative data. Perhaps bar charts are better. \gbc{barchart}
9446 % calculates the bars from the text parameter, \gbc{data}. These bars are
9447 % vertical if \gbc{vert} is true, otherwise horizontal.
9448 %
9449 % \gbc{firstbar} is the location (on the appropriate axis) of the start of
9450 % the first bar. \gbc{sep} is the separation between bar centers. \gbc{r}
9451 % is the ratio of the width of the bars to their separation.
9452 %
9453 % After the calculations, the array of paths \gbc{chartbar[\,]} holds the
9454 % rectangles, \gbc{barend[\,]} holds their rightmost or topmost
9455 % coordinates (which is just the items in \gbc{data} or their yparts),
9456 % \gbc{barbegin[\,]} holds their leftmost or bottommost coordinates (either
9457 % 0 or the xparts of the data), \gbc{barstart[\,]} holds the appropriate
9458 % coordinate of the leading edge of the bar, and \gbc{barwd = r*sep}.
9459 %
9460 % If the data are pair data, this command uses the xpart as the beginning
9461 % of the bar and the ypart as the end. Thus Gantt diagrams can be
9462 % created. We keep \gbc{barlength} for backward compatibility (formerly
9463 % all data had to be numeric and bars went from 0 to \gbc{barlength[\,]}).
9464 % \gbc{barlength[\,]} was made available to help place some label or symbol
9465 % at the end of a bar and existing code might break if we omit it.
9466 % \begin{macrocode}
9467 def barchart (expr firstbar, sep, r, vert)(text data) =
9468 numeric barbegin, barbegin[],
9469 barend, barend[],
9470 barlength, barlength[],
9471 barstart, barstart[],
9472 chartbar, barwd;
9473 path chartbar[];
9474 chartbar := 0; barwd := r*sep;
9475 for _itm = data:
9476 barend[incr chartbar]
9477 := if pair _itm: ypart _itm else: _itm fi;
9478 barbegin[chartbar] := if pair _itm: xpart _itm else: 0 fi;
9479 endfor
9480 barbegin := barend := barlength := barstart := chartbar;
9481 for _nn = 1 upto chartbar:
9482 barstart[_nn] := firstbar + sep*(_nn-1);
9483 barlength[_nn] := barend[_nn];
9484 chartbar[_nn] := rect ((barbegin[_nn], 0), ( barend[_nn], barwd))
9485 shifted (0, barstart[_nn]) if vert: xyswap fi;
9486 endfor
9487 enddef;
9488
9489 % \end{macrocode}
9490 %
9491 % \DescribeRoutine{namedbarchart}
9492 % This is a future enhancement. It takes a suffix, the name of the chart,
9493 % which will be the base name of the path array. Note that the various key
9494 % elements (ends of the bar, etc.) are not (yet) directly accessible as in
9495 % the above version, but they would be easy to add.
9496 % \begin{macrocode}
9497 def namedbarchart (suffix nm) (expr first, sep, r, vert) (text data) =
9498 save nm;
9499 begingroup
9500 save _bb, _ee, _ww;
9501 path nm.bar[];
9502 nm := 0; _ww := r*sep;
9503 for _itm = data:
9504 _ee := if pair _itm: ypart _itm else: _itm fi;
9505 _bb := if pair _itm: xpart _itm else: 0 fi;
9506 nm.bar[incr nm] := rect ((_bb, 0), ( _ee, _ww) )
9507 shifted (0, first + sep*(nm-1)) if vert: xyswap fi;
9508 endfor
9509 endgroup
9510 enddef;
9511
9512 % \end{macrocode}
9513 %
9514 %
9515 %^^A Overlays - taken from MFbook, p 295. (Bruce Leban)
9516 %
9517 %
9518 % \subsection{Overlays}\label{overlays}
9519 %
9520 % This final code predates me. When I inherited \mfpic{} it contained no
9521 % use of \gbc{keepit}. For the \MP{} version I just tried to make sure
9522 % everything was defined in \MP{} or \file{plain.mp} and otherwise left it
9523 % alone. One might presumably issue \gbc{keepit} periodically, clearing
9524 % \mfc{currentpicture} after adding it onto \gbc{totalpicture}. This would
9525 % save some memory because manipulating \mfc{currentpicture} often
9526 % requires a couple of copies to be around simultaneously. Right now we
9527 % treat currentpicture as the place to save things and manipulate local
9528 % picture variables.
9529 % \begin{macrocode}
9530 picture totalpicture;
9531 boolean totalnull, currentnull;
9532 def clearit =
9533 currentpicture := totalpicture := nullpicture;
9534 currentnull := totalnull := true;
9535 enddef;
9536
9537 def keepit =
9538 addto totalpicture also currentpicture;
9539 %<MF> mono (totalpicture);
9540 currentpicture := nullpicture;
9541 totalnull := totalnull or currentnull;
9542 currentnull := true;
9543 enddef;
9544
9545 def addto_currentpicture =
9546 currentnull := false;
9547 addto currentpicture
9548 enddef;
9549
9550 def mergeit (text do) =
9551 if totalnull:
9552 do currentpicture
9553 elseif currentnull:
9554 do totalpicture
9555 else:
9556 begingroup
9557 save _v_; picture _v_;
9558 _v_ := currentpicture;
9559 addto _v_ also totalpicture;
9560 do _v_
9561 endgroup
9562 fi
9563 enddef;
9564
9565 % \end{macrocode}
9566 % This implements \mfpic{}'s \cs{stopshipping} and \cs{resumeshipping}
9567 % commands. It used to be that those commands wrote a redefinition of
9568 % \gbc{shipit}, now we write a boolean assignment and the \cs{shipit}
9569 % command tests it.
9570 % \begin{macrocode}
9571 boolean noship; noship := false;
9572 def shipit = if noship: else: mergeit (shipout) fi enddef;
9573
9574 %<*MF>
9575 def showit_ = mergeit (show_) enddef;
9576 def show_ suffix v = display v inwindow currentwindow enddef;
9577
9578 %</MF>
9579 % \end{macrocode}
9580 %
9581 % Here we initialize \gbc{gcode} (which current versions of mfpic do not
9582 % use) for hacked \mfpic{} files that require it. In \MP{} we load the
9583 % color definitions. And thats all.
9584 % \begin{macrocode}
9585 numeric gcode; gcode := 0;
9586
9587 %<MF>% end grafbase.mf
9588 %<MP>input dvipsnam.mp;
9589 %<MP>% end grafbase.mp
9590 %</MF|MP>
9591 % \end{macrocode}
9592 %
9593 %
9594 % \subsection{Dvips names for colors}\label{dvipsnam}
9595 %
9596 % In order to make \file{dvipsnam.mp} useful outside grafbase, we give
9597 % here a definition for \gbc{cmyk} when \gbc{grafbaseversion} is unknown.
9598 % \begin{macrocode}
9599 %<*dvips>
9600 if unknown grafbaseversion:
9601 if unknown mpversion:
9602 let cmykcolor=color;
9603 vardef cmyk (expr c, m, y, k) =
9604 (max(1-c-k,0), max(1-m-k,0), max(1-y-k,0))
9605 enddef;
9606 else:
9607 vardef cmyk (expr c, m, y, k) = (c, m, y, k) enddef;
9608 fi
9609 fi
9610
9611 % \end{macrocode}
9612 %
9613 % The following code was borrowed from the the standard \LaTeX{} graphics
9614 % package (\file{dvipsname.def} by David Carlisle and Sebastian Rahtz). In
9615 % fact it was mostly generated automatically by some editor macros that
9616 % replaced \prog{graphics} package code with the \grafbase{} code.
9617 %
9618 %^^A This file may be distributed under the terms of the LaTeX Project Public
9619 %^^A License, as described in \file{lppl.txt} in the base LaTeX
9620 %^^A distribution, either version 1.0 or, at your option, any later version.
9621 %
9622 % Declare all the dvips color names to be color variables, and define
9623 % them as in \file{dvipsnam.def}:
9624 % \begin{macrocode}
9625 cmykcolor Apricot, Aquamarine, Bittersweet, Black, Blue, BlueGreen,
9626 BlueViolet, BrickRed, Brown, BurntOrange, CadetBlue, CarnationPink,
9627 Cerulean, CornflowerBlue, Cyan, Dandelion, DarkOrchid, Emerald,
9628 ForestGreen, Fuchsia, Goldenrod, Gray, Green, GreenYellow, JungleGreen,
9629 Lavender, LimeGreen, Magenta, Mahogany, Maroon, Melon, MidnightBlue,
9630 Mulberry, NavyBlue, OliveGreen, Orange, OrangeRed, Orchid, Peach,
9631 Periwinkle, PineGreen, Plum, ProcessBlue, Purple, RawSienna, Red,
9632 RedOrange, RedViolet, Rhodamine, RoyalBlue, RoyalPurple, RubineRed,
9633 Salmon, SeaGreen, Sepia, SkyBlue, SpringGreen, Tan, TealBlue, Thistle,
9634 Turquoise, Violet, VioletRed, White, WildStrawberry, Yellow,
9635 YellowGreen, YellowOrange;
9636
9637 Apricot := cmyk(0,0.32,0.52,0);
9638 Aquamarine := cmyk(0.82,0,0.30,0);
9639 Bittersweet := cmyk(0,0.75,1,0.24);
9640 Black := cmyk(0,0,0,1);
9641 Blue := cmyk(1,1,0,0);
9642 BlueGreen := cmyk(0.85,0,0.33,0);
9643 BlueViolet := cmyk(0.86,0.91,0,0.04);
9644 BrickRed := cmyk(0,0.89,0.94,0.28);
9645 Brown := cmyk(0,0.81,1,0.60);
9646 BurntOrange := cmyk(0,0.51,1,0);
9647 CadetBlue := cmyk(0.62,0.57,0.23,0);
9648 CarnationPink := cmyk(0,0.63,0,0);
9649 Cerulean := cmyk(0.94,0.11,0,0);
9650 CornflowerBlue := cmyk(0.65,0.13,0,0);
9651 Cyan := cmyk(1,0,0,0);
9652 Dandelion := cmyk(0,0.29,0.84,0);
9653 DarkOrchid := cmyk(0.40,0.80,0.20,0);
9654 Emerald := cmyk(1,0,0.50,0);
9655 ForestGreen := cmyk(0.91,0,0.88,0.12);
9656 Fuchsia := cmyk(0.47,0.91,0,0.08);
9657 Goldenrod := cmyk(0,0.10,0.84,0);
9658 Gray := cmyk(0,0,0,0.50);
9659 Green := cmyk(1,0,1,0);
9660 GreenYellow := cmyk(0.15,0,0.69,0);
9661 JungleGreen := cmyk(0.99,0,0.52,0);
9662 Lavender := cmyk(0,0.48,0,0);
9663 LimeGreen := cmyk(0.50,0,1,0);
9664 Magenta := cmyk(0,1,0,0);
9665 Mahogany := cmyk(0,0.85,0.87,0.35);
9666 Maroon := cmyk(0,0.87,0.68,0.32);
9667 Melon := cmyk(0,0.46,0.50,0);
9668 MidnightBlue := cmyk(0.98,0.13,0,0.43);
9669 Mulberry := cmyk(0.34,0.90,0,0.02);
9670 NavyBlue := cmyk(0.94,0.54,0,0);
9671 OliveGreen := cmyk(0.64,0,0.95,0.40);
9672 Orange := cmyk(0,0.61,0.87,0);
9673 OrangeRed := cmyk(0,1,0.50,0);
9674 Orchid := cmyk(0.32,0.64,0,0);
9675 Peach := cmyk(0,0.50,0.70,0);
9676 Periwinkle := cmyk(0.57,0.55,0,0);
9677 PineGreen := cmyk(0.92,0,0.59,0.25);
9678 Plum := cmyk(0.50,1,0,0);
9679 ProcessBlue := cmyk(0.96,0,0,0);
9680 Purple := cmyk(0.45,0.86,0,0);
9681 RawSienna := cmyk(0,0.72,1,0.45);
9682 Red := cmyk(0,1,1,0);
9683 RedOrange := cmyk(0,0.77,0.87,0);
9684 RedViolet := cmyk(0.07,0.90,0,0.34);
9685 Rhodamine := cmyk(0,0.82,0,0);
9686 RoyalBlue := cmyk(1,0.50,0,0);
9687 RoyalPurple := cmyk(0.75,0.90,0,0);
9688 RubineRed := cmyk(0,1,0.13,0);
9689 Salmon := cmyk(0,0.53,0.38,0);
9690 SeaGreen := cmyk(0.69,0,0.50,0);
9691 Sepia := cmyk(0,0.83,1,0.70);
9692 SkyBlue := cmyk(0.62,0,0.12,0);
9693 SpringGreen := cmyk(0.26,0,0.76,0);
9694 Tan := cmyk(0.14,0.42,0.56,0);
9695 TealBlue := cmyk(0.86,0,0.34,0.02);
9696 Thistle := cmyk(0.12,0.59,0,0);
9697 Turquoise := cmyk(0.85,0,0.20,0);
9698 Violet := cmyk(0.79,0.88,0,0);
9699 VioletRed := cmyk(0,0.81,0,0);
9700 White := cmyk(0,0,0,0);
9701 WildStrawberry := cmyk(0,0.96,0.39,0);
9702 Yellow := cmyk(0,0,1,0);
9703 YellowGreen := cmyk(0.44,0,0.74,0);
9704 YellowOrange := cmyk(0,0.42,1,0);
9705
9706 % End of file `dvipsnam.mp'.
9707 %</dvips>
9708 % \end{macrocode}
9709 % \clearpage
9710 %\Finale