1\input texinfo   @c -*-texinfo-*-
2@setfilename asymptote.info
3@settitle Asymptote: the Vector Graphics Language
4@include version.texi
5@finalout
6
7@copying
8This file documents @code{Asymptote}, version @value{VERSION}.
9
10@url{http://asymptote.sourceforge.net}
11
12Copyright @copyright{} 2004-14 Andy Hammerlindl, John Bowman, and Tom Prince.
13
14@quotation
15Permission is granted to copy, distribute and/or modify this document
16under the terms of the @acronym{GNU} Lesser General Public License (see the
17file LICENSE in the top-level source directory).
18
19@end quotation
20@end copying
21
22@dircategory Languages
23@direntry
24* asymptote: (asymptote/asymptote). Vector graphics language.
25@end direntry
26
27@titlepage
28@title Asymptote: the Vector Graphics Language
29@subtitle For version @value{VERSION}
30@sp 1
31@center @image{logo}
32
33@page
34@vskip 0pt plus 1filll
35@insertcopying
36
37@end titlepage
38
39@c So the toc is printed at the start.
40@contents
41
42@ifnottex
43@node Top
44@top Asymptote
45
46@insertcopying
47@end ifnottex
48
49@menu
50* Description::                 What is @code{Asymptote}?
51* Installation::                Downloading and installing
52* Tutorial::                    Getting started
53* Drawing commands::            Four primitive graphics commands
54* Bezier curves::               Path connectors and direction specifiers
55* Programming::                 The @code{Asymptote} vector graphics language
56* LaTeX usage::                 Embedding @code{Asymptote} commands within @code{LaTeX}
57* Base modules::                Base modules shipped with @code{Asymptote}
58* Options::                     Command-line options
59* Interactive mode::            Typing @code{Asymptote} commands interactively
60* GUI::                         Graphical user interface
61* PostScript to Asymptote::     @code{Asymptote} backend to @code{pstoedit}
62* Help::                        Where to get help and submit bug reports
63* Debugger::                    Squish those bugs!
64* Credits::                     Contributions and acknowledgments
65* Index::                       General index
66
67@detailmenu
68 --- The Detailed Node Listing ---
69
70Installation
71
72* UNIX binary distributions::   Prebuilt @code{UNIX} binaries
73* MacOS X binary distributions::  Prebuilt @code{MacOS X} binaries
74* Microsoft Windows::           Prebuilt @code{Microsoft Windows} binary
75* Configuring::                 Configuring @code{Asymptote} for your system
76* Search paths::                Where @code{Asymptote} looks for your files
77* Compiling from UNIX source::  Building @code{Asymptote} from scratch
78* Editing modes::               Convenient @code{emacs} and @code{vim} modes
79* Subversion::                  Getting the latest development source
80* Uninstall::                   Goodbye, @code{Asymptote}!
81
82Drawing commands
83
84* draw::                        Draw a path on a picture or frame
85* fill::                        Fill a cyclic path on a picture or frame
86* clip::                        Clip a picture or frame to a cyclic path
87* label::                       Label a point on a picture
88
89Programming
90
91* Data types::                  void, bool, int, real, pair, triple, string
92* Paths and guides::            Bezier curves
93* Pens::                        Colors, line types, line widths, font sizes
94* Transforms::                  Affine transforms
95* Frames and pictures::         Canvases for immediate and deferred drawing
96* Files::                       Reading and writing your data
97* Variable initializers::       Initialize your variables
98* Structures::                  Organize your data
99* Operators::                   Arithmetic and logical operators
100* Implicit scaling::            Avoiding those ugly *s
101* Functions::                   Traditional and high-order functions
102* Arrays::                      Dynamic vectors
103* Casts::                       Implicit and explicit casts
104* Import::                      Importing external @code{Asymptote} modules
105* Static::                      Where to allocate your variable?
106
107Operators
108
109* Arithmetic & logical::        Basic mathematical operators
110* Self & prefix operators::     Increment and decrement
111* User-defined operators::      Overloading operators
112
113Functions
114
115* Default arguments::           Default values can appear anywhere
116* Named arguments::             Assigning function arguments by keyword
117* Rest arguments::              Functions with a variable number of arguments
118* Mathematical functions::      Standard libm functions
119
120
121Arrays
122
123* Slices::                      Python-style array slices
124
125Base modules
126
127* plain::                       Default @code{Asymptote} base file
128* simplex::                     Linear programming: simplex method
129* math::                        Extend @code{Asymptote}'s math capabilities
130* interpolate::                 Interpolation routines
131* geometry::                    Geometry routines
132* trembling::                   Wavy lines
133* stats::                       Statistics routines and histograms
134* patterns::                    Custom fill and draw patterns
135* markers::                     Custom path marker routines
136* tree::                        Dynamic binary search tree
137* binarytree::                  Binary tree drawing module
138* drawtree::                    Tree drawing module
139* syzygy::                      Syzygy and braid drawing module
140* feynman::                     Feynman diagrams
141* roundedpath::                 Round the sharp corners of paths
142* animation::                   Embedded @acronym{PDF} and @acronym{MPEG} movies
143* embed::                       Embedding movies, sounds, and 3D objects
144* slide::                       Making presentations with @code{Asymptote}
145* MetaPost::                    @code{MetaPost} compatibility routines
146* unicode::                     Accept @code{unicode} (UTF-8) characters
147* latin1::                      Accept @code{ISO 8859-1} characters
148* babel::                       Interface to @code{LaTeX} @code{babel} package
149* labelpath::                   Drawing curved labels
150* labelpath3::                  Drawing curved labels in 3D
151* annotate::                    Annotate your @acronym{PDF} files
152* CAD::                         2D CAD pen and measurement functions (DIN 15)
153* graph::                       2D linear & logarithmic graphs
154* palette::                     Color density images and palettes
155* three::                       3D vector graphics
156* obj::                         3D obj files
157* graph3::                      3D linear & logarithmic graphs
158* grid3::                       3D grids
159* solids::                      3D solid geometry
160* tube::                        3D rotation minimizing tubes
161* flowchart::                   Flowchart drawing routines
162* contour::                     Contour lines
163* contour3::                    Contour surfaces
164* slopefield::                  Slope fields
165* ode::                         Ordinary differential equations
166
167Graphical User Interface
168
169* GUI installation::            Installing @code{xasy}
170* GUI usage::
171
172@end detailmenu
173@end menu
174
175@node Description
176@chapter Description
177@cindex description
178
179@code{Asymptote} is a powerful descriptive vector graphics language that
180provides a mathematical coordinate-based framework for technical drawing.
181Labels and equations are typeset with @code{LaTeX}, for overall document
182consistency, yielding the same high-quality level of typesetting that
183@code{LaTeX} provides for scientific text. By default it produces
184@code{PostScript} output, but it can also generate any format that the
185@code{ImageMagick} package can produce.
186
187A major advantage of @code{Asymptote} over other graphics packages is
188that it is a high-level programming language, as opposed to just a graphics
189program: it can therefore exploit the best features of the script
190(command-driven) and graphical-user-interface (@acronym{GUI}) methods for
191producing figures. The rudimentary @acronym{GUI} @code{xasy} included with the
192package allows one to move script-generated objects
193around. To make @code{Asymptote} accessible to the average user, this
194@acronym{GUI} is currently being developed into a full-fledged interface
195that can generate objects directly. However, the script portion of the language
196is now ready for general use by users who are willing to learn a few
197simple @code{Asymptote} graphics commands (@pxref{Drawing commands}).
198
199@code{Asymptote} is mathematically oriented (e.g.@ one can
200use complex multiplication to rotate a vector) and uses
201@code{LaTeX} to do the
202typesetting of labels. This is an important feature for scientific
203applications. It was inspired by an earlier drawing program (with a weaker
204syntax and capabilities) called @code{MetaPost}.
205
206The @code{Asymptote} vector graphics language provides:
207
208@itemize @bullet
209@item a standard for typesetting mathematical figures, just
210as @TeX{}/@code{LaTeX} is the de-facto standard for typesetting equations.
211
212@item @code{LaTeX} typesetting of labels, for overall document consistency;
213
214@item the ability to generate and embed 3D vector @acronym{PRC}
215graphics within @acronym{PDF} files;
216
217@item a natural coordinate-based framework for technical drawing,
218inspired by @code{MetaPost}, with a much cleaner, powerful C++-like programming
219syntax;
220
221@item compilation of figures into virtual machine code for speed, without
222sacrificing portability;
223
224@item the power of a script-based language coupled to the convenience of
225a @acronym{GUI};
226
227@item customization using its own C++-like graphics programming language;
228
229@item sensible defaults for graphical features, with the ability to override;
230
231@item a high-level mathematically oriented interface to the
232@code{PostScript} language for vector graphics, including affine transforms
233and complex variables;
234
235@item functions that can create new (anonymous) functions;
236
237@item deferred drawing that uses the simplex method to solve overall size
238constraint issues between fixed-sized objects (labels and arrowheads) and
239objects that should scale with figure size;
240
241@end itemize
242
243Many of the features of @code{Asymptote} are written in the
244@code{Asymptote} language itself. While the stock version of
245@code{Asymptote} is designed for mathematics typesetting needs, one can
246write @code{Asymptote} modules that tailor it to specific
247applications. A scientific graphing module has already been written
248(@pxref{graph}). Examples of @code{Asymptote} code and output,
249including animations, are available at
250@quotation
251@url{http://asymptote.sourceforge.net/gallery/}.
252@end quotation
253@noindent
254Links to many external resources, including an excellent user-written
255@code{Asymptote} tutorial can be found at
256@quotation
257@url{http://asymptote.sourceforge.net/links.html}.
258@end quotation
259@cindex reference
260@cindex quick reference
261A quick reference card for @code{Asymptote} is available at
262@quotation
263@url{http://asymptote.sourceforge.net/asyRefCard.pdf}.
264@end quotation
265
266@node Installation
267@chapter Installation
268@cindex installation
269
270@menu
271* UNIX binary distributions::   Prebuilt @code{UNIX} binaries
272* MacOS X binary distributions::  Prebuilt @code{MacOS X} binaries
273* Microsoft Windows::           Prebuilt @code{Microsoft Windows} binary
274* Configuring::                 Configuring @code{Asymptote} for your system
275* Search paths::                Where @code{Asymptote} looks for your files
276* Compiling from UNIX source::  Building @code{Asymptote} from scratch
277* Editing modes::               Convenient @code{emacs} and @code{vim} modes
278* Subversion::                  Getting the latest development source
279* Uninstall::                   Goodbye, @code{Asymptote}!
280@end menu
281
282After following the instructions for your specific distribution,
283please see also @ref{Configuring}.
284
285@noindent
286We recommend subscribing to new release announcements at
287@quotation
288@url{http://freecode.com/projects/asy}
289@end quotation
290@noindent
291Users may also wish to monitor the @code{Asymptote} forum:
292@quotation
293@url{http://sourceforge.net/p/asymptote/discussion/409349}
294@end quotation
295@noindent
296
297@node UNIX binary distributions
298@section UNIX binary distributions
299@cindex UNIX binary distributions
300
301@cindex @acronym{RPM}
302@cindex @code{tgz}
303We release both @code{tgz} and @acronym{RPM} binary distributions of
304@code{Asymptote}. The root user can install the @code{Linux i386} @code{tgz}
305distribution of version @code{x.xx} of @code{Asymptote} with the commands:
306@verbatim
307tar -C / -zxf asymptote-x.xx.i386.tgz
308texhash
309@end verbatim
310@noindent
311The @code{texhash} command, which installs LaTeX style files, is optional.
312The executable file will be @code{/usr/local/bin/asy}) and example code
313will be installed by default in @code{@value{Datadir}/doc/asymptote/examples}.
314
315@noindent
316@cindex Fedora
317Fedora users can easily install the most recent version of @code{Asymptote}
318with the command
319@verbatim
320yum --enablerepo=rawhide install asymptote
321@end verbatim
322
323@cindex Debian
324@noindent
325To install the latest version of @code{Asymptote} on a Debian-based distribution
326(e.g.@ Ubuntu, Mepis, Linspire) follow the instructions for compiling
327from @code{UNIX} source (@pxref{Compiling from UNIX source}).
328Alternatively, Debian users can install one of Hubert Chan's
329prebuilt @code{Asymptote} binaries from
330@quotation
331@url{http://ftp.debian.org/debian/pool/main/a/asymptote}
332@end quotation
333
334@node MacOS X binary distributions
335@section MacOS X binary distributions
336@cindex @code{MacOS X} binary distributions
337@code{MacOS X} users can either compile the @code{UNIX} source code
338(@pxref{Compiling from UNIX source})
339or install the @code{Asymptote} binary available at
340
341@url{http://www.macports.org/}
342
343@noindent
344Note that many @code{MacOS X} (and FreeBSD) systems lack the
345@acronym{GNU} @code{readline} library. For full interactive
346functionality, @acronym{GNU} @code{readline} version 4.3 or later must
347be installed.
348
349@node Microsoft Windows
350@section Microsoft Windows
351@cindex Microsoft Windows
352Users of the @code{Microsoft Windows} operating system can install the
353self-extracting @code{Asymptote} executable @code{asymptote-x.xx-setup.exe},
354where @code{x.xx} denotes the latest version.
355
356A working @TeX{} implementation (such as the one available at
357@url{http://www.miktex.org}) will be required to typeset labels.
358You will also need to install @code{GPL Ghostscript} version 9.14 or
359later from @url{http://downloads.ghostscript.com/public}.
360
361To view the default @code{PostScript} output, you can install the
362program @code{gsview} available from
363@url{http://www.cs.wisc.edu/~ghost/gsview/}.
364@cindex @code{psview}
365@anchor{psview}
366A better (and free) @code{PostScript} viewer available at
367@url{http://psview.sourceforge.net/} (which in particular works properly
368in interactive mode) unfortunately currently requires some manual
369configuration. Specifically, if version @code{x.xx} of @code{psview} is
370extracted to the directory @code{c:\Program Files} one needs to put
371@verbatim
372import settings;
373psviewer="c:\Program Files\psview-x.xx\psv.exe";
374@end verbatim
375@noindent
376in the optional @code{Asymptote} configuration file;
377@pxref{configuration file}).
378
379The @code{ImageMagick} package from
380
381@url{http://www.imagemagick.org/script/binary-releases.php}
382
383@noindent
384is required to support output formats other than @acronym{EPS},
385@acronym{PDF}, @acronym{SVG}, and @acronym{PNG} (@pxref{convert}).
386The @code{Python 2} interpreter from @url{http://www.python.org} is only required
387if you wish to try out the graphical user interface (@pxref{GUI}).
388
389@noindent
390Example code will be installed by default in the @code{examples}
391subdirectory of the installation directory (by default,
392@code{C:\Program Files\Asymptote}).
393
394@node Configuring
395@section Configuring
396@cindex configuring
397@cindex @code{-V}
398@cindex @code{psviewer}
399@cindex @code{pdfviewer}
400@cindex @code{gs}
401In interactive mode, or when given the @code{-V} option (the default
402when running @code{Asymptote} on a single file under @code{MSDOS}),
403@code{Asymptote} will automatically invoke the @code{PostScript}
404viewer @code{gv} (under @code{UNIX}) or @code{gsview} (under
405@code{MSDOS} to display graphical output. These defaults may be
406overridden with the configuration variable @code{psviewer}.
407The @code{PostScript} viewer should be capable of automatically
408redrawing whenever the output file is updated. The default @code{UNIX}
409@code{PostScript} viewer @code{gv} supports this (via a @code{SIGHUP}
410signal). Version @code{gv-3.6.3} or later (from
411@url{http://ftp.gnu.org/gnu/gv/}) is required for interactive mode to
412work properly.
413Users of @code{ggv} will need to enable @code{Watch file} under
414@code{Edit/Postscript Viewer Preferences}.
415Users of @code{gsview} will need to enable @code{Options/Auto Redisplay}
416(however, under @code{MSDOS} it is still necessary to click on the
417@code{gsview} window; under @code{UNIX} one must manually redisplay by
418pressing the @code{r} key). A better (and free) multiplatform
419alternative to @code{gsview} is @code{psview} (@pxref{psview}).
420
421@cindex @code{settings}
422@cindex configuration file
423Configuration variables are most easily set as @code{Asymptote}
424variables in an optional configuration file @code{config.asy}
425@pxref{configuration file}).
426Here are the default values of several important configuration
427variables under @code{UNIX}:
428
429@noindent
430@verbatim
431import settings;
432psviewer="gv";
433pdfviewer="acroread";
434gs="gs";
435@end verbatim
436
437@noindent
438@cindex @code{cmd}
439Under @code{MSDOS}, the (installation-dependent) default values of
440these configuration variables are determined automatically from the
441@code{Microsoft Windows} registry. Viewer settings (such as
442@code{psviewer} and @code{pdfviewer}) can be set to the string
443@code{cmd} to request the application normally associated with the
444corresponding file type.
445
446For @acronym{PDF} format output, the @code{gs} setting specifies the
447location of the @code{PostScript}-to-@acronym{PDF} processor @code{Ghostscript},
448available from @url{http://downloads.ghostscript.com/public}.
449
450The setting @code{pdfviewer} specifies the location of the @acronym{PDF}
451viewer. On @code{UNIX} systems, to support automatic document
452reloading in @code{Adobe Reader}, we recommend copying the file
453@code{reload.js} from the @code{Asymptote} system directory (by default,
454@code{@value{Datadir}/asymptote} under @code{UNIX} to
455@code{~/.adobe/Acrobat/x.x/JavaScripts/},
456where @code{x.x} represents the appropriate @code{Adobe Reader}
457version number. The automatic document reload feature must then be
458explicitly enabled by putting
459@verbatim
460import settings;
461pdfreload=true;
462pdfreloadOptions="-tempFile";
463@end verbatim
464@noindent
465in the @code{Asymptote} configuration file. This reload feature is not
466useful under @code{MSDOS} since the document cannot be updated anyway on
467that operating system until it is first closed by @code{Adobe Reader}.
468
469The configuration variable @code{dir} can be used to adjust the
470search path (@pxref{Search paths}).
471
472@cindex @code{papertype}
473@cindex @code{paperwidth}
474@cindex @code{paperheight}
475@cindex @code{letter}
476@cindex @code{a4}
477By default, @code{Asymptote} attempts to center the figure on the
478page, assuming that the paper type is @code{letter}. The default paper
479type may be changed to @code{a4} with the configuration variable
480@code{papertype}. Alignment to other paper sizes can be obtained by setting the
481configuration variables @code{paperwidth} and @code{paperheight}.
482
483@cindex @code{config}
484@cindex @code{texpath}
485@cindex @code{texcommand}
486@cindex @code{dvips}
487@cindex @code{dvisvgm}
488@cindex @code{libgs}
489@cindex @code{convert}
490@cindex @code{display}
491@cindex @code{animate}
492@cindex @code{ImageMagick}
493The following configuration variables normally do not require adjustment:
494@verbatim
495config
496texpath
497texcommand
498dvips
499dvisvgm
500libgs
501convert
502display
503animate
504@end verbatim
505@noindent
506
507Warnings (such as "unbounded" and "offaxis") may be enabled or disabled with
508the functions
509@verbatim
510warn(string s);
511nowarn(string s);
512@end verbatim
513@noindent
514or by directly modifying the string array @code{settings.suppress}, which lists
515all disabled warnings.
516
517@cindex command-line options
518Configuration variables may also be set or overwritten with a
519command-line option:
520@verbatim
521asy -psviewer=gsview -V venn
522@end verbatim
523
524@cindex environment variables
525Alternatively, system environment versions of the above configuration
526variables may be set in the conventional way. The corresponding
527environment variable name is obtained by converting the configuration
528variable name to upper case  and prepending @code{ASYMPTOTE_}:
529for example, to set the environment variable
530@verbatim
531ASYMPTOTE_PSVIEWER="C:\Program Files\Ghostgum\gsview\gsview32.exe";
532@end verbatim
533@noindent
534under @code{Microsoft Windows XP}:
535@enumerate
536@item Click on the @code{Start} button;
537@item Right-click on @code{My Computer};
538@item Choose @code{View system information};
539@item Click the @code{Advanced} tab;
540@item Click the @code{Environment Variables} button.
541@end enumerate
542
543@node Search paths
544@section Search paths
545@cindex search paths
546
547In looking for @code{Asymptote} system
548files, @code{asy} will search the following paths, in the order listed:
549@enumerate
550@item
551The current directory;
552@item
553@cindex @code{dir}
554A list of one or more directories specified by the configuration
555variable @code{dir} or environment variable @code{ASYMPTOTE_DIR}
556(separated by @code{:} under UNIX and
557@code{;} under @code{MSDOS});
558@item
559@cindex @code{.asy}
560The directory specified by the environment variable
561@code{ASYMPTOTE_HOME}; if this variable is not set,
562the directory @code{.asy} in the user's home directory
563(@code{%USERPROFILE%\.asy} under @code{MSDOS}) is used;
564@item
565The @code{Asymptote} system directory (by default,
566@code{@value{Datadir}/asymptote} under @code{UNIX} and
567@code{C:\Program Files\Asymptote} under @code{MSDOS}).
568@end enumerate
569
570@node Compiling from UNIX source
571@section Compiling from UNIX source
572@cindex Compiling from UNIX source
573
574To compile and install a @code{UNIX} executable from
575the source release @code{asymptote-x.xx.src.tgz} in the subdirectory
576@code{x.xx} under
577
578@url{http://sourceforge.net/projects/asymptote/files/}
579
580execute the commands:
581@verbatim
582gunzip asymptote-x.xx.src.tgz
583tar -xf asymptote-x.xx.src.tar
584cd asymptote-x.xx
585@end verbatim
586By default the system version of the Boehm garbage collector will be
587used; if it is old we recommend first putting
588@url{http://hboehm.info/gc/gc_source/gc-7.4.2.tar.gz}
589@url{http://www.ivmaisoft.com/_bin/atomic_ops/libatomic_ops-7.4.2.tar.gz}
590in the @code{Asymptote} source directory.
591
592On @code{UNIX} platforms (other than @code{MacOS X}), we recommend
593using version @code{2.8.1} of the @code{freeglut} library. To compile
594@code{freeglut}, download
595@quotation
596@url{http://prdownloads.sourceforge.net/freeglut/freeglut-2.8.1.tar.gz}
597@end quotation
598@noindent
599and type (as the root user):
600@verbatim
601gunzip freeglut-2.8.1.tar.gz
602tar -xf freeglut-2.8.1.tar
603cd freeglut-2.8.1
604./configure --prefix=/usr
605make install
606cd ..
607@end verbatim
608@noindent
609
610Then compile @code{Asymptote} with the commands
611@verbatim
612./configure
613make all
614make install
615@end verbatim
616@noindent
617Be sure to use @acronym{GNU} @code{make} (on non-@acronym{GNU} systems
618this command may be called @code{gmake}).
619To build the documentation, you may need to install the
620@code{texinfo-tex} package. If you get errors from a broken @code{texinfo}
621or @code{pdftex} installation, simply put
622@quotation
623@url{http://asymptote.sourceforge.net/asymptote.pdf}
624@end quotation
625@noindent
626in the directory @code{doc} and repeat the command @code{make all}.
627
628@noindent
629For a (default) system-wide installation, the last command should be
630done as the root user. To install without root privileges, change the
631@code{./configure} command to
632@verbatim
633./configure --prefix=$HOME/asymptote
634@end verbatim
635One can disable use of the Boehm garbage collector by configuring
636with @code{./configure --disable-gc}. For a list of other configuration
637options, say @code{./configure --help}. For example, one can tell
638configure to look for header files and libraries in nonstandard locations:
639@verbatim
640./configure CFLAGS=-I/opt/usr/include LDFLAGS=-L/opt/usr/lib
641@end verbatim
642
643If you are compiling @code{Asymptote} with @code{gcc}, you will need a
644relatively recent version (e.g.@ 3.4.4 or later).  For full interactive
645functionality, you will need version 4.3 or later of the @acronym{GNU}
646@code{readline} library.
647The file @code{gcc3.3.2curses.patch} in the @code{patches} directory can
648be used to patch the broken curses.h header file (or a local copy thereof
649in the current directory) on some @code{AIX} and @code{IRIX} systems.
650
651@cindex @code{FFTW}
652@cindex @code{GSL}
653The @code{FFTW} library is only required if you want @code{Asymptote}
654to be able to take Fourier transforms of data (say, to compute an
655audio power spectrum). The @code{GSL} library is only required if you
656require the special functions that it supports.
657
658If you don't want to install @code{Asymptote} system wide, just make
659sure the compiled binary @code{asy} and @acronym{GUI} script @code{xasy} are in
660your path and set the configuration variable @code{dir} to point
661to the directory @code{base} (in the top level directory of the
662@code{Asymptote} source code).
663
664@node Editing modes
665@section Editing modes
666@cindex Editing modes
667@cindex @code{emacs}
668@cindex @code{asy-mode}
669@cindex @code{lasy-mode}
670Users of @code{emacs} can edit @code{Asymptote} code with the mode
671@code{asy-mode}, after enabling it by putting the following lines in their
672@code{.emacs} initialization file, replacing @code{ASYDIR} with the
673location of the @code{Asymptote} system directory (by default,
674@code{@value{Datadir}/asymptote} or @code{C:\Program Files\Asymptote}
675under @code{MSDOS}):
676@verbatim
677(add-to-list 'load-path "ASYDIR")
678(autoload 'asy-mode "asy-mode.el" "Asymptote major mode." t)
679(autoload 'lasy-mode "asy-mode.el" "hybrid Asymptote/Latex major mode." t)
680(autoload 'asy-insinuate-latex "asy-mode.el" "Asymptote insinuate LaTeX." t)
681(add-to-list 'auto-mode-alist '("\\.asy$" . asy-mode))
682
683@end verbatim
684@noindent
685Particularly useful key bindings in this mode are @code{C-c C-c}, which compiles
686and displays the current buffer, and the key binding @code{C-c ?}, which
687shows the available function prototypes for the command at the cursor.
688For full functionality you should also install the Apache Software Foundation
689package @code{two-mode-mode}:
690@quotation
691@url{http://www.dedasys.com/freesoftware/files/two-mode-mode.el}
692@end quotation
693@noindent
694Once installed, you can use the hybrid mode @code{lasy-mode} to edit a
695LaTeX file containing embedded @code{Asymptote} code (@pxref{LaTeX usage}).
696This mode can be enabled within @code{latex-mode}
697with the key sequence @code{M-x lasy-mode <RET>}.
698On @code{UNIX} systems, additional keywords will be generated from
699all @code{asy} files in the space-separated list of directories
700specified by the environment variable @code{ASYMPTOTE_SITEDIR}.
701Further documentation of @code{asy-mode} is available within
702@code{emacs} by pressing the sequence keys @code{C-h f asy-mode <RET>}.
703
704@cindex @code{vim}
705@cindex @code{asy.vim}
706Fans of @code{vim} can customize @code{vim} for @code{Asymptote} with
707
708@noindent
709@code{cp @value{Datadir}/asymptote/asy.vim ~/.vim/syntax/asy.vim}
710
711@noindent
712and add the following to their @code{~/.vimrc} file:
713@verbatim
714augroup filetypedetect
715au BufNewFile,BufRead *.asy     setf asy
716augroup END
717filetype plugin on
718@end verbatim
719
720If any of these directories or files don't exist, just create them.
721To set @code{vim} up to run the current asymptote script using @code{:make}
722just add to @code{~/.vim/ftplugin/asy.vim}:
723@verbatim
724setlocal makeprg=asy\ %
725setlocal errorformat=%f:\ %l.%c:\ %m
726@end verbatim
727
728@cindex @code{KDE editor}
729@cindex @code{Kate}
730@cindex @code{asymptote.xml}
731Syntax highlighting support for the @acronym{KDE} editor @code{Kate}
732can be enabled by running @code{asy-kate.sh} in the
733@code{@value{Datadir}/asymptote} directory and putting the generated
734@code{asymptote.xml} file in @code{~/.kde/share/apps/katepart/syntax/}.
735
736@node Subversion
737@section Subversion (SVN)
738@cindex Subversion
739@cindex SVN
740
741The following commands are needed to install the latest development version of
742@code{Asymptote} using @code{Subversion}:
743@verbatim
744svn co http://svn.code.sf.net/p/asymptote/code/trunk/asymptote
745cd asymptote
746./autogen.sh
747./configure
748make all
749make install
750@end verbatim
751
752@noindent
753To compile without optimization, use the command @code{make CFLAGS=-g}.
754
755@node Uninstall
756@section Uninstall
757@cindex Uninstall
758
759To uninstall an @code{Linux i386} binary distribution, use the commands
760@verbatim
761tar -zxvf asymptote-x.xx.i386.tgz | xargs --replace=% rm /%
762texhash
763@end verbatim
764
765@noindent
766To uninstall all @code{Asymptote} files installed from a source
767distribution, use the command
768@verbatim
769make uninstall
770@end verbatim
771
772@node Tutorial
773@chapter Tutorial
774@cindex tutorial
775@cindex batch mode
776@section Drawing in batch mode
777To draw a line from coordinate (0,0) to coordinate (100,100),
778create a text file @code{test.asy} containing
779@verbatiminclude diagonal.asy
780
781@noindent
782Then execute the command
783@verbatim
784asy -V test
785@end verbatim
786@noindent
787Alternatively, @code{MSDOS} users can drag and drop @code{test.asy} onto the
788Desktop @code{asy} icon (or make @code{Asymptote} the default
789application for the extension @code{asy}).
790
791@noindent
792@cindex @code{-V}
793This method, known as @emph{batch mode}, outputs a @code{PostScript}
794file @code{test.eps}. If you prefer @acronym{PDF} output, use
795the command line
796@verbatim
797asy -V -f pdf test
798@end verbatim
799In either case, the @code{-V} option opens up a viewer window so you
800can immediately view the result:
801@sp 1
802@center @image{diagonal}
803@cindex @code{bp}
804@noindent
805Here, the @code{--} connector joins the two points @code{(0,0)} and
806@code{(100,100)} with a line segment.
807
808@section Drawing in interactive mode
809Another method is @emph{interactive mode}, where @code{Asymptote} reads
810individual commands as they are entered by the user. To try this out, enter
811@code{Asymptote}'s interactive mode by clicking on the
812@code{Asymptote} icon or typing the command @code{asy}.
813Then type
814@verbatim
815draw((0,0)--(100,100));
816@end verbatim
817@noindent
818followed by @code{Enter}, to obtain the above image.
819@cindex tab completion
820@cindex arrow keys
821@cindex erase
822@cindex quit
823@noindent
824At this point you can type further @code{draw} commands, which will be added
825to the displayed figure, @code{erase} to clear the canvas,
826@verbatim
827input test;
828@end verbatim
829@noindent
830to execute all of the commands contained in the file @code{test.asy},
831or @code{quit} to exit interactive mode.
832You can use the arrow keys in interactive mode to edit previous lines.
833The tab key will automatically complete unambiguous words;
834otherwise, hitting tab again will show the possible choices. Further
835commands specific to interactive mode are described in @ref{Interactive mode}.
836
837@section Figure size
838@cindex @code{pair}
839In @code{Asymptote}, coordinates like @code{(0,0)} and @code{(100,100)},
840called @emph{pairs},
841are expressed in @code{PostScript} "big points" (1 @code{bp} = 1/72
842@code{inch}) and the default line width is @code{0.5bp}.
843However, it is often inconvenient to work directly in
844@code{PostScript} coordinates.
845The next example produces identical output to the previous example, by
846scaling the line @code{(0,0)--(1,1)} to fit a rectangle of width
847@code{100.5 bp} and height @code{100.5 bp} (the extra @code{0.5bp}
848accounts for the line width):
849@verbatim
850size(100.5,100.5);
851draw((0,0)--(1,1));
852@end verbatim
853@sp 1
854@center @image{diagonal}
855
856@cindex @code{inches}
857@cindex @code{cm}
858@cindex @code{mm}
859@cindex @code{pt}
860One can also specify the size in @code{pt} (1 @code{pt} = 1/72.27 @code{inch}),
861@code{cm}, @code{mm}, or @code{inches}.
862Two nonzero size arguments (or a single size argument) restrict the
863size in both directions, preserving the aspect ratio.
864If 0 is given as a size argument, no restriction is made in that direction;
865the overall scaling will be determined by the other direction (@pxref{size}):
866@verbatiminclude bigdiagonal.asy
867@sp 1
868@center @image{bigdiagonal}
869
870@cindex @code{cycle}
871To connect several points and create a cyclic path, use the
872@code{cycle} keyword:
873@verbatiminclude square.asy
874@sp 1
875@center @image{square}
876@noindent
877For convenience, the path @code{(0,0)--(1,0)--(1,1)--(0,1)--cycle}
878may be replaced with the predefined variable
879@code{unitsquare}, or equivalently, @code{box((0,0),(1,1))}.
880
881@cindex user coordinates
882@cindex @code{unitsize}
883To make the user coordinates represent multiples of exactly @code{1cm}:
884@verbatim
885unitsize(1cm);
886draw(unitsquare);
887@end verbatim
888@noindent
889
890@section Labels
891Adding labels is easy in @code{Asymptote}; one specifies the
892label as a double-quoted @code{LaTeX} string, a
893coordinate, and an optional alignment direction:
894@verbatiminclude labelsquare.asy
895@sp 1
896@center @image{labelsquare}
897
898@cindex compass directions
899@cindex @code{N}
900@cindex @code{E}
901@cindex @code{W}
902@cindex @code{S}
903@code{Asymptote} uses the standard compass directions @code{E=(1,0)},
904@code{N=(0,1)}, @code{NE=unit(N+E)}, and @code{ENE=unit(E+NE)}, etc.,
905which along with the directions @code{up}, @code{down}, @code{right},
906and @code{left} are defined as pairs in the @code{Asymptote} base
907module @code{plain} (a user who has a local variable named @code{E}
908may access the compass direction @code{E} by prefixing it with the name
909of the module where it is defined: @code{plain.E}).
910
911@section Paths
912This example draws a path that approximates a quarter circle,
913terminated with an arrowhead:
914@verbatiminclude quartercircle.asy
915@sp 1
916@center @image{quartercircle}
917@noindent
918Here the directions @code{up} and @code{left} in braces specify the
919incoming and outgoing directions at the points @code{(1,0)} and
920@code{(0,1)}, respectively.
921
922In general, a path is specified as a list of points (or other paths)
923interconnected with
924@cindex @code{cycle}
925@cindex @code{--}
926@cindex @code{..}
927@code{--}, which denotes a straight line segment, or @code{..}, which
928denotes a cubic spline (@pxref{Bezier curves}).
929@cindex @code{unitcircle}
930@anchor{unitcircle}
931@cindex @code{unitcircle}
932Specifying a final @code{..cycle} creates a cyclic path that
933connects smoothly back to the initial node, as in this approximation
934(accurate to within 0.06%) of a unit circle:
935@verbatim
936path unitcircle=E..N..W..S..cycle;
937@end verbatim
938
939@cindex @code{PostScript} subpath
940@cindex @code{^^}
941@cindex @code{path[]}
942@cindex superpath
943@noindent
944An @code{Asymptote} path, being connected, is equivalent to a
945@code{Postscript subpath}. The @code{^^} binary operator, which
946requests that the pen be moved (without drawing or affecting
947endpoint curvatures) from the final point of the left-hand path to the
948initial point of the right-hand path, may be used to group several
949@code{Asymptote} paths into a @code{path[]} array (equivalent to a
950@code{PostScript} path):
951@verbatiminclude superpath.asy
952@sp 1
953@center @image{superpath}
954
955@cindex evenodd
956@noindent
957The @code{PostScript} even-odd fill rule here specifies that only the
958region bounded between the two unit circles is filled (@pxref{fillrule}).
959In this example, the same effect can be achieved by using the default
960zero winding number fill rule, if one is careful to alternate the
961orientation of the paths:
962@verbatim
963filldraw(unitcircle^^reverse(g),yellow,black);
964@end verbatim
965
966@cindex @code{unitbox}
967The @code{^^} operator is used by the @code{box(triple, triple)} function in
968the module @code{three.asy} to construct the edges of a
969cube @code{unitbox} without retracing steps (@pxref{three}):
970@verbatiminclude cube.asy
971@sp 1
972@center @image{cube}
973
974See section @ref{graph} (or the online @code{Asymptote} gallery and
975external links posted at @url{http://asymptote.sourceforge.net}) for
976further examples, including two-dimensional and interactive
977three-dimensional scientific graphs. Additional examples have been
978posted by Philippe Ivaldi at @url{http://www.piprime.fr/asymptote}.
979Excellent user-written @code{Asymptote} tutorials are also available:
980
981@url{http://www.artofproblemsolving.com/Wiki/index.php/Asymptote:_Basics}
982
983@url{http://math.uchicago.edu/~cstaats/Charles_Staats_III/Notes_and_papers_files/asymptote_tutorial.pdf}
984@node Drawing commands
985@chapter Drawing commands
986@cindex drawing commands
987
988All of @code{Asymptote}'s graphical capabilities are based on four primitive
989commands. The three @code{PostScript} drawing commands @code{draw},
990@code{fill}, and @code{clip} add objects to a picture in the order in
991which they are executed, with the most recently drawn object appearing on top.
992The labeling command @code{label} can be used to add text
993labels and external @acronym{EPS} images, which will appear on top of the
994@code{PostScript} objects (since this is normally what one wants), but
995again in the relative order in which they were executed. After drawing
996objects on a picture, the picture can be output with the
997@code{shipout} function (@pxref{shipout}).
998
999@cindex @code{layer}
1000If you wish to draw @code{PostScript} objects on top of labels (or verbatim
1001@code{tex} commands; @pxref{tex}), the @code{layer} command may be
1002used to start a
1003new @code{PostScript/LaTeX} layer:
1004@verbatim
1005void layer(picture pic=currentpicture);
1006@end verbatim
1007
1008The @code{layer} function gives one full control over the order in which
1009objects are drawn. Layers are drawn sequentially, with the most recent
1010layer appearing on top. Within each layer, labels, images, and
1011verbatim @code{tex} commands are always drawn after the
1012@code{PostScript} objects in that layer.
1013
1014While some of these drawing commands take many options, they all have sensible
1015default values (for example, the picture argument defaults to
1016currentpicture).
1017
1018@cindex legend
1019@cindex @code{draw}
1020@cindex @code{arrow}
1021@menu
1022* draw::                        Draw a path on a picture or frame
1023* fill::                        Fill a cyclic path on a picture or frame
1024* clip::                        Clip a picture or frame to a cyclic path
1025* label::                       Label a point on a picture
1026@end menu
1027
1028@node draw
1029@section draw
1030@verbatim
1031void draw(picture pic=currentpicture, Label L="", path g,
1032          align align=NoAlign, pen p=currentpen,
1033          arrowbar arrow=None, arrowbar bar=None, margin margin=NoMargin,
1034          Label legend="", marker marker=nomarker);
1035@end verbatim
1036
1037Draw the path @code{g} on the picture @code{pic} using pen @code{p}
1038for drawing, with optional drawing attributes (Label @code{L},
1039explicit label alignment @code{align},
1040arrows and bars @code{arrow} and @code{bar}, margins @code{margin},
1041legend, and markers @code{marker}). Only one parameter, the path, is
1042required. For convenience, the arguments @code{arrow} and @code{bar} may be
1043specified in either order. The argument @code{legend} is a Label to
1044use in constructing an optional legend entry.
1045
1046@cindex @code{None}
1047@cindex @code{BeginBar}
1048@cindex @code{EndBar}
1049@cindex @code{Bar}
1050@cindex @code{Bars}
1051@cindex @code{barsize}
1052Bars are useful for indicating dimensions. The possible values of
1053@code{bar} are @code{None}, @code{BeginBar}, @code{EndBar} (or
1054equivalently @code{Bar}), and @code{Bars} (which draws a bar at both
1055ends of the path). Each of these bar specifiers (except for
1056@code{None}) will accept an optional real argument that denotes the
1057length of the bar in @code{PostScript} coordinates. The default
1058bar length is @code{barsize(pen)}.
1059
1060@cindex arrows
1061@anchor{arrows}
1062@cindex @code{None}
1063@cindex @code{Blank}
1064@cindex @code{BeginArrow}
1065@cindex @code{MidArrow}
1066@cindex @code{EndArrow}
1067@cindex @code{Arrow}
1068@cindex @code{Arrows}
1069@cindex @code{FillDraw}
1070@cindex @code{Fill}
1071@cindex @code{Draw}
1072@cindex @code{NoFill}
1073@cindex @code{UnFill}
1074@cindex @code{BeginArcArrow}
1075@cindex @code{MidArcArrow}
1076@cindex @code{EndArcArrow}
1077@cindex @code{ArcArrow}
1078@cindex @code{ArcArrows}
1079
1080@cindex @code{DefaultHead}
1081@cindex @code{SimpleHead}
1082@cindex @code{HookHead}
1083@cindex @code{TeXHead}
1084The possible values of @code{arrow} are @code{None}, @code{Blank}
1085(which draws no arrows or path), @code{BeginArrow}, @code{MidArrow},
1086@code{EndArrow} (or equivalently @code{Arrow}),
1087and @code{Arrows} (which draws an arrow at both ends of the path).
1088All of the arrow specifiers except for @code{None} and @code{Blank}
1089may be given the optional arguments arrowhead @code{arrowhead} (one of
1090the predefined arrowhead styles @code{DefaultHead}, @code{SimpleHead},
1091@code{HookHead}, @code{TeXHead}),
1092real @code{size} (arrowhead size in @code{PostScript} coordinates),
1093real @code{angle} (arrowhead angle
1094in degrees), filltype @code{filltype} (one of @code{FillDraw}, @code{Fill},
1095@code{NoFill}, @code{UnFill}, @code{Draw}) and (except for
1096@code{MidArrow} and @code{Arrows}) a real @code{position} (in the
1097sense of @code{point(path p, real t)}) along the path where the tip of
1098the arrow should be placed. The default arrowhead size when drawn
1099with a pen @code{p} is @code{arrowsize(p)}. There are also arrow versions with
1100slightly modified default values of @code{size} and @code{angle} suitable for
1101curved arrows: @code{BeginArcArrow}, @code{EndArcArrow} (or equivalently
1102@code{ArcArrow}), @code{MidArcArrow}, and @code{ArcArrows}.
1103
1104@cindex @code{NoMargin}
1105@cindex @code{BeginMargin}
1106@cindex @code{EndMargin}
1107@cindex @code{Margin}
1108@cindex @code{Margins}
1109@cindex @code{BeginPenMargin}
1110@cindex @code{EndPenMargin}
1111@cindex @code{PenMargin}
1112@cindex @code{PenMargins}
1113@cindex @code{BeginDotMargin}
1114@cindex @code{EndDotMargin}
1115@cindex @code{DotMargin}
1116@cindex @code{DotMargins}
1117@cindex @code{Margin}
1118@cindex @code{TrueMargin}
1119Margins can be used to shrink the visible portion of a path by
1120@code{labelmargin(p)} to avoid overlap with other drawn objects.
1121Typical values of @code{margin}
1122are @code{NoMargin}, @code{BeginMargin}, @code{EndMargin} (or
1123equivalently @code{Margin}), and @code{Margins} (which leaves a margin
1124at both ends of the path). One may use @code{Margin(real begin, real end)}
1125to specify the size of the beginning and ending margin, respectively,
1126in multiples of the units @code{labelmargin(p)} used for aligning labels.
1127Alternatively, @code{BeginPenMargin}, @code{EndPenMargin}
1128(or equivalently @code{PenMargin}), @code{PenMargins},
1129@code{PenMargin(real begin, real end)} specify a margin in units of
1130the pen line width, taking account of the pen line width when drawing
1131the path or arrow. For example, use @code{DotMargin}, an
1132abbreviation for @code{PenMargin(-0.5*dotfactor,0.5*dotfactor)},
1133to draw from the usual beginning point just up to the boundary of an
1134end dot of width @code{dotfactor*linewidth(p)}.  The qualifiers
1135@code{BeginDotMargin}, @code{EndDotMargin}, and @code{DotMargins} work
1136similarly. The qualifier @code{TrueMargin(real begin, real end)} allows one to
1137specify a margin directly in @code{PostScript} units, independent of
1138the pen line width.
1139
1140The use of arrows, bars, and margins is illustrated by the examples
1141@code{Pythagoras.asy}, @code{sqrtx01.asy}, and @code{triads.asy}.
1142
1143The legend for a picture @code{pic} can be fit and aligned to a frame
1144with the routine:
1145@cindex @code{legend}
1146@verbatim
1147frame legend(picture pic=currentpicture, int perline=1,
1148             real xmargin=legendmargin, real ymargin=xmargin,
1149             real linelength=legendlinelength,
1150             real hskip=legendhskip, real vskip=legendvskip,
1151             real maxwidth=0, real maxheight=0,
1152             bool hstretch=false, bool vstretch=false, pen p=currentpen);
1153@end verbatim
1154@noindent
1155Here @code{xmargin} and @code{ymargin} specify the surrounding @math{x}
1156and @math{y} margins, @code{perline} specifies the number of entries
1157per line (default 1; 0 means choose this number automatically),
1158@code{linelength} specifies the length of the path lines, @code{hskip}
1159and @code{vskip} specify the line skip (as a multiple of the legend entry
1160size), @code{maxwidth} and @code{maxheight} specify optional upper limits
1161on the width and height of the resulting legend (0 means unlimited),
1162@code{hstretch} and @code{vstretch} allow the legend to stretch
1163horizontally or vertically, and @code{p} specifies the pen used to draw
1164the bounding box. The legend frame can then be added and aligned about a
1165point on a picture @code{dest} using @code{add} or @code{attach}
1166(@pxref{add about}).
1167
1168@cindex @code{dot}
1169To draw a dot, simply draw a path containing a single point.
1170The @code{dot} command defined in the module @code{plain} draws a
1171dot having a diameter equal to an explicit pen line width or the
1172default line width magnified by @code{dotfactor} (6 by default),
1173using the specified filltype (@pxref{filltype}):
1174@verbatim
1175void dot(picture pic=currentpicture, pair z, pen p=currentpen,
1176         filltype filltype=Fill);
1177void dot(picture pic=currentpicture, Label L, pair z, align align=NoAlign,
1178         string format=defaultformat, pen p=currentpen, filltype filltype=Fill);
1179void dot(picture pic=currentpicture, Label[] L=new Label[], pair[] z,
1180         align align=NoAlign, string format=defaultformat, pen p=currentpen,
1181         filltype filltype=Fill)
1182void dot(picture pic=currentpicture, Label L, pen p=currentpen,
1183         filltype filltype=Fill);
1184@end verbatim
1185
1186@cindex @code{Label}
1187If the variable @code{Label} is given as the @code{Label}
1188argument to the second routine, the @code{format} argument will be
1189used to format a string based on the dot location (here @code{defaultformat}
1190is @code{"$%.4g$"}).
1191The third routine draws a dot at every point of a pair array @code{z}.
1192One can also draw a dot at every node of a path:
1193@verbatim
1194void dot(picture pic=currentpicture, Label[] L=new Label[],
1195         path g, align align=RightSide, string format=defaultformat,
1196         pen p=currentpen, filltype filltype=Fill);
1197@end verbatim
1198See @ref{pathmarkers} and @ref{markers} for more general
1199methods for marking path nodes.
1200
1201To draw a fixed-sized object (in @code{PostScript} coordinates) about
1202the user coordinate @code{origin}, use the routine
1203@cindex @code{draw}
1204@verbatim
1205void draw(pair origin, picture pic=currentpicture, Label L="", path g,
1206          align align=NoAlign, pen p=currentpen, arrowbar arrow=None,
1207          arrowbar bar=None, margin margin=NoMargin, Label legend="",
1208          marker marker=nomarker);
1209@end verbatim
1210
1211@cindex @code{fill}
1212@node fill
1213@section fill
1214@verbatim
1215void fill(picture pic=currentpicture, path g, pen p=currentpen);
1216@end verbatim
1217
1218Fill the interior region bounded by the cyclic path @code{g} on the picture
1219@code{pic}, using the pen @code{p}.
1220
1221@cindex @code{filldraw}
1222There is also a convenient @code{filldraw} command, which fills the path
1223and then draws in the boundary. One can specify separate pens for each
1224operation:
1225@verbatim
1226void filldraw(picture pic=currentpicture, path g, pen fillpen=currentpen,
1227              pen drawpen=currentpen);
1228@end verbatim
1229
1230@cindex @code{fill}
1231This fixed-size version of @code{fill} allows one to fill an object
1232described in @code{PostScript} coordinates about the user coordinate
1233@code{origin}:
1234@verbatim
1235void fill(pair origin, picture pic=currentpicture, path g, pen p=currentpen);
1236@end verbatim
1237
1238@noindent
1239This is just a convenient abbreviation for the commands:
1240@verbatim
1241picture opic;
1242fill(opic,g,p);
1243add(pic,opic,origin);
1244@end verbatim
1245
1246The routine
1247@cindex @code{filloutside}
1248@verbatim
1249void filloutside(picture pic=currentpicture, path g, pen p=currentpen);
1250@end verbatim
1251@noindent
1252fills the region exterior to the path @code{g}, out to the current
1253boundary of picture @code{pic}.
1254
1255@anchor{gradient shading}
1256@cindex gradient shading
1257
1258@cindex shading
1259@cindex @code{latticeshade}
1260Lattice gradient shading varying smoothly over a two-dimensional
1261array of pens @code{p}, using fill rule @code{fillrule}, can be produced with
1262@verbatim
1263void latticeshade(picture pic=currentpicture, path g, bool stroke=false,
1264                  pen fillrule=currentpen, pen[][] p)
1265@end verbatim
1266@cindex @code{stroke}
1267If @code{stroke=true}, the region filled is the same as the region that
1268would be drawn by @code{draw(pic,g,fillrule+zerowinding)}; in this case the path
1269@code{g} need not be cyclic.
1270The pens in @code{p} must belong to the same color space. One can use the
1271functions @code{rgb(pen)} or @code{cmyk(pen)} to promote pens to a
1272higher color space, as illustrated in the example file
1273@code{latticeshading.asy}.
1274
1275@cindex @code{axialshade}
1276Axial gradient shading varying smoothly from @code{pena} to @code{penb} in the
1277direction of the line segment @code{a--b} can be achieved with
1278@verbatim
1279void axialshade(picture pic=currentpicture, path g, bool stroke=false,
1280                pen pena, pair a, bool extenda=true,
1281                pen penb, pair b, bool extendb=true);
1282@end verbatim
1283@noindent
1284The boolean parameters @code{extenda} and @code{extendb} indicate
1285whether the shading should extend beyond the axis endpoints @code{a}
1286and @code{b}.
1287
1288@cindex @code{radialshade}
1289Radial gradient shading varying smoothly from
1290@code{pena} on the circle with center @code{a} and radius @code{ra} to
1291@code{penb} on the circle with center @code{b} and radius @code{rb}
1292is similar:
1293@verbatim
1294void radialshade(picture pic=currentpicture, path g, bool stroke=false,
1295                 pen pena, pair a, real ra, bool extenda=true,
1296                 pen penb, pair b, real rb, bool extendb=true);
1297@end verbatim
1298@noindent
1299The boolean parameters @code{extenda} and @code{extendb} indicate
1300whether the shading should extend beyond the radii @code{a} and @code{b}.
1301Illustrations of radial shading are provided in the example files
1302@code{shade.asy}, @code{ring.asy}, and @code{shadestroke.asy}.
1303
1304@cindex @code{gouraudshade}
1305Gouraud shading using fill rule @code{fillrule} and the vertex colors in the
1306pen array @code{p} on a triangular lattice defined by the vertices
1307@code{z} and edge flags @code{edges} is implemented with
1308@verbatim
1309void gouraudshade(picture pic=currentpicture, path g, bool stroke=false,
1310                  pen fillrule=currentpen, pen[] p, pair[] z,
1311                  int[] edges);
1312void gouraudshade(picture pic=currentpicture, path g, bool stroke=false,
1313                  pen fillrule=currentpen, pen[] p, int[] edges);
1314@end verbatim
1315@noindent
1316In the second form, the elements of @code{z} are taken to be successive
1317nodes of path @code{g}. The pens in @code{p} must belong to the same
1318color space. Illustrations of Gouraud shading are provided in the example file
1319@code{Gouraud.asy} and in the solid geometry module @code{solids.asy}.
1320The edge flags used in Gouraud shading are documented here:
1321@quotation
1322@url{http://partners.adobe.com/public/developer/en/ps/sdk/TN5600.SmoothShading.pdf}.
1323@end quotation
1324
1325@cindex Coons shading
1326@cindex tensor product shading
1327@cindex @code{tensorshade}
1328Tensor product shading using fill rule @code{fillrule} on patches
1329bounded by the @math{n} cyclic paths of length 4 in path array @code{b},
1330using the vertex colors specified in the @math{n \times 4} pen array
1331@code{p} and internal control points in the @math{n \times 4}
1332array @code{z}, is implemented with
1333@verbatim
1334void tensorshade(picture pic=currentpicture, path[] g, bool stroke=false,
1335                 pen fillrule=currentpen, pen[][] p, path[] b=g,
1336                 pair[][] z=new pair[][]);
1337@end verbatim
1338@noindent
1339If the array @code{z} is empty, Coons shading, in which the color
1340control points are calculated automatically, is used.
1341The pens in @code{p} must belong to the same color space.
1342A simpler interface for the case of a single patch (@math{n=1}) is also
1343available:
1344@verbatim
1345void tensorshade(picture pic=currentpicture, path g, bool stroke=false,
1346                 pen fillrule=currentpen, pen[] p, path b=g,
1347                 pair[] z=new pair[]);
1348@end verbatim
1349One can also smoothly shade the regions between consecutive paths of a
1350sequence using a given array of pens:
1351@verbatim
1352void draw(picture pic=currentpicture, pen fillrule=currentpen, path[] g,
1353          pen[] p);
1354@end verbatim
1355@noindent
1356Illustrations of tensor product and Coons shading are provided in the
1357example files @code{tensor.asy}, @code{Coons.asy}, @code{BezierSurface.asy},
1358and @code{rainbow.asy}.
1359
1360@cindex Function shading
1361@cindex function shading
1362@cindex @code{functionshade}
1363More general shading possibilities are available using @TeX{} engines
1364that produce PDF output (@pxref{texengines}): the routine
1365@verbatim
1366void functionshade(picture pic=currentpicture, path[] g, bool stroke=false,
1367                   pen fillrule=currentpen, string shader);
1368@end verbatim
1369@noindent
1370shades on picture @code{pic} the interior of path @code{g} according
1371to fill rule @code{fillrule} using the @code{PostScript} calculator routine
1372specified by the string @code{shader}; this routine takes 2 arguments,
1373each in [0,1], and returns @code{colors(fillrule).length} color components.
1374Function shading is illustrated in the example @code{functionshading.asy}.
1375
1376@cindex unfill
1377The following routine uses @code{evenodd} clipping together with the
1378@code{^^} operator to unfill a region:
1379
1380@verbatim
1381void unfill(picture pic=currentpicture, path g);
1382@end verbatim
1383
1384@cindex @code{clip}
1385@cindex @code{stroke}
1386@node clip
1387@section clip
1388@verbatim
1389void clip(picture pic=currentpicture, path g, stroke=false,
1390          pen fillrule=currentpen);
1391@end verbatim
1392
1393Clip the current contents of picture @code{pic} to the region bounded
1394by the path @code{g}, using fill rule @code{fillrule} (@pxref{fillrule}).
1395If @code{stroke=true}, the clipped portion is the same as the region
1396that would be drawn with @code{draw(pic,g,fillrule+zerowinding)}; in
1397this case the path @code{g} need not be cyclic. For an illustration of
1398picture clipping, see the first example in @ref{LaTeX usage}.
1399
1400@cindex @code{label}
1401@node label
1402@section label
1403@verbatim
1404void label(picture pic=currentpicture, Label L, pair position,
1405           align align=NoAlign, pen p=currentpen, filltype filltype=NoFill)
1406@end verbatim
1407
1408Draw Label @code{L} on picture @code{pic} using pen @code{p}. If
1409@code{align} is @code{NoAlign}, the label will be centered at user
1410coordinate @code{position}; otherwise it will be aligned in the
1411direction of @code{align} and displaced from @code{position} by
1412the @code{PostScript} offset @code{align*labelmargin(p)}.
1413@cindex @code{Align}
1414The constant @code{Align} can be used to align the
1415bottom-left corner of the label at @code{position}.
1416@cindex @code{nullpen}
1417@cindex @code{Label}
1418@anchor{Label}
1419The Label @code{L} can either be a string or the structure obtained by calling
1420one of the functions
1421@verbatim
1422Label Label(string s="", pair position, align align=NoAlign,
1423            pen p=nullpen, embed embed=Rotate, filltype filltype=NoFill);
1424Label Label(string s="", align align=NoAlign,
1425            pen p=nullpen, embed embed=Rotate, filltype filltype=NoFill);
1426Label Label(Label L, pair position, align align=NoAlign,
1427            pen p=nullpen, embed embed=L.embed, filltype filltype=NoFill);
1428Label Label(Label L, align align=NoAlign,
1429            pen p=nullpen, embed embed=L.embed, filltype filltype=NoFill);
1430@end verbatim
1431The text of a Label can be scaled, slanted, rotated, or shifted by
1432multiplying it on the left by an affine transform (@pxref{Transforms}).
1433For example, @code{rotate(45)*xscale(2)*L} first scales @code{L} in the
1434@math{x} direction and then rotates it counterclockwise by 45
1435degrees. The final position of a Label can also be shifted by a
1436@code{PostScript} coordinate translation: @code{shift(10,0)*L}.
1437An explicit pen specified within the Label overrides other pen arguments.
1438The @code{embed} argument determines how the Label should transform with the
1439embedding picture:
1440@table @code
1441@item Shift
1442@cindex @code{Shift}
1443only shift with embedding picture;
1444
1445@item Rotate
1446@cindex @code{Rotate}
1447only shift and rotate with embedding picture (default);
1448
1449@item Rotate(pair z)
1450@cindex @code{Rotate(pair z)}
1451rotate with (picture-transformed) vector @code{z}.
1452
1453@item Slant
1454@cindex @code{Slant}
1455only shift, rotate, slant, and reflect with embedding picture;
1456
1457@item Scale
1458@cindex @code{Scale}
1459shift, rotate, slant, reflect, and scale with embedding picture.
1460
1461@end table
1462
1463To add a label to a path, use
1464@verbatim
1465void label(picture pic=currentpicture, Label L, path g, align align=NoAlign,
1466           pen p=currentpen, filltype filltype=NoFill);
1467@end verbatim
1468@cindex @code{Relative}
1469By default the label will be positioned at the midpoint of the path.
1470An alternative label position (in the sense of @code{point(path p, real t)})
1471may be specified as a real value for @code{position} in constructing
1472the Label. The position @code{Relative(real)} specifies a location
1473relative to the total arclength of the path. These convenient
1474abbreviations are predefined:
1475@cindex @code{BeginPoint}
1476@cindex @code{MidPoint}
1477@cindex @code{EndPoint}
1478@verbatim
1479position BeginPoint=Relative(0);
1480position MidPoint=Relative(0.5);
1481position EndPoint=Relative(1);
1482@end verbatim
1483
1484@cindex @code{Relative}
1485@cindex @code{LeftSide}
1486@cindex @code{Center}
1487@cindex @code{RightSide}
1488Path labels are aligned in the direction @code{align}, which may
1489be specified as an absolute compass direction (pair) or a direction
1490@code{Relative(pair)} measured relative to a north axis
1491in the local direction of the path. For convenience @code{LeftSide},
1492@code{Center}, and @code{RightSide} are defined as @code{Relative(W)},
1493@code{Relative((0,0))}, and @code{Relative(E)}, respectively.
1494Multiplying @code{LeftSide} and @code{RightSide} on the
1495left by a real scaling factor will move the label further away from or
1496closer to the path.
1497
1498A label with a fixed-size arrow of length @code{arrowlength} pointing
1499to @code{b} from direction @code{dir} can be produced with the routine
1500@cindex @code{arrow}
1501@verbatim
1502void arrow(picture pic=currentpicture, Label L="", pair b, pair dir,
1503           real length=arrowlength, align align=NoAlign,
1504           pen p=currentpen, arrowbar arrow=Arrow, margin margin=EndMargin);
1505@end verbatim
1506If no alignment is specified (either in the Label or as an explicit
1507argument), the optional Label will be aligned in the direction @code{dir},
1508using margin @code{margin}.
1509
1510@cindex including images
1511@cindex @code{graphic}
1512@cindex @acronym{EPS}
1513The function @code{string graphic(string name, string options="")}
1514returns a string that can be used to include an encapsulated
1515@code{PostScript} (@acronym{EPS}) file. Here, @code{name} is the name
1516of the file to include and @code{options} is a string containing a
1517comma-separated list of optional bounding box (@code{bb=llx lly urx
1518ury}), width (@code{width=value}), height (@code{height=value}),
1519rotation (@code{angle=value}), scaling (@code{scale=factor}), clipping
1520(@code{clip=bool}), and draft mode (@code{draft=bool}) parameters. The
1521@code{layer()} function can be used to force future objects to be
1522drawn on top of the included image:
1523@verbatim
1524label(graphic("file.eps","width=1cm"),(0,0),NE);
1525layer();
1526@end verbatim
1527
1528@cindex @code{baseline}
1529The @code{string baseline(string s, string template="\strut")}
1530function can be used to enlarge the bounding box of labels to match a
1531given template, so that their baselines will be typeset on a
1532horizontal line. See @code{Pythagoras.asy} for an example.
1533
1534One can prevent labels from overwriting one another with the
1535@code{overwrite} pen attribute (@pxref{overwrite}).
1536
1537The structure @code{object} defined in @code{plain_Label.asy} allows Labels
1538and frames to be treated in a uniform manner.
1539A group of objects may be packed together into single frame with the routine
1540@cindex @code{pack}
1541@verbatim
1542frame pack(pair align=2S ... object inset[]);
1543@end verbatim
1544@noindent
1545To draw or fill a box (or ellipse or other path) around a Label and
1546return the bounding object, use one of the routines
1547@verbatim
1548object draw(picture pic=currentpicture, Label L, envelope e,
1549            real xmargin=0, real ymargin=xmargin, pen p=currentpen,
1550            filltype filltype=NoFill, bool above=true);
1551object draw(picture pic=currentpicture, Label L, envelope e, pair position,
1552            real xmargin=0, real ymargin=xmargin, pen p=currentpen,
1553            filltype filltype=NoFill, bool above=true);
1554@end verbatim
1555@noindent
1556Here @code{envelope} is a boundary-drawing routine such as @code{box},
1557@code{roundbox}, or @code{ellipse} defined in @code{plain_boxes.asy}
1558(@pxref{envelope}).
1559
1560@cindex @code{texpath}
1561The function @code{path[] texpath(Label L)} returns the path array that
1562@TeX{} would fill to draw the Label @code{L}.
1563
1564@cindex @code{minipage}
1565The @code{string minipage(string s, width=100pt)} function can be used
1566to format string @code{s} into a paragraph of width @code{width}.
1567This example uses @code{minipage}, @code{clip}, and @code{graphic} to
1568produce a CD label:
1569@sp 1
1570@center @image{CDlabel}
1571@verbatiminclude CDlabel.asy
1572
1573@node Bezier curves
1574@chapter Bezier curves
1575@cindex Bezier curves
1576@cindex direction specifier
1577Each interior node of a cubic spline may be given a
1578direction prefix or suffix @code{@{dir@}}: the direction of the pair
1579@code{dir} specifies the direction of the incoming or outgoing tangent,
1580respectively, to the curve at that node. Exterior nodes may be
1581given direction specifiers only on their interior side.
1582
1583A cubic spline between the node @math{z_0}, with postcontrol point
1584@math{c_0}, and the node @math{z_1}, with precontrol point @math{c_1},
1585is computed as the Bezier curve
1586@sp 1
1587@center @image{bezier,,,(1-t)^3*z_0+3t(1-t)^2*c_0+3t^2(1-t)*c_1+t^3*z_1 for 0 <=t <= 1.}
1588
1589As illustrated in the diagram below, the third-order midpoint (@math{m_5})
1590constructed from two endpoints @math{z_0} and @math{z_1} and two control points
1591@math{c_0} and @math{c_1}, is the point corresponding to @math{t=1/2} on
1592the Bezier curve formed by the quadruple (@math{z_0}, @math{c_0},
1593@math{c_1}, @math{z_1}). This allows one to recursively construct the
1594desired curve, by using the newly extracted third-order midpoint as an
1595endpoint and the respective second- and first-order midpoints as control
1596points:
1597@sp 1
1598@center @image{bezier2}
1599
1600Here @math{m_0}, @math{m_1} and @math{m_2} are the first-order
1601midpoints, @math{m_3} and @math{m_4} are the second-order midpoints, and
1602@math{m_5} is the third-order midpoint.
1603The curve is then constructed by recursively applying the algorithm to
1604(@math{z_0}, @math{m_0}, @math{m_3}, @math{m_5}) and
1605(@math{m_5}, @math{m_4}, @math{m_2}, @math{z_1}).
1606
1607In fact, an analogous property holds for points located at any
1608fraction @math{t} in @math{[0,1]} of each segment, not just for
1609midpoints (@math{t=1/2}).
1610
1611The Bezier curve constructed in this manner has the following properties:
1612@itemize @bullet
1613
1614@item It is entirely contained in the convex hull of the given four points.
1615
1616@item It starts heading from the first endpoint to the first control point
1617and finishes heading from the second control point to the second endpoint.
1618
1619@end itemize
1620
1621@cindex @code{controls}
1622The user can specify explicit control points between two nodes like this:
1623@verbatim
1624draw((0,0)..controls (0,100) and (100,100)..(100,0));
1625@end verbatim
1626
1627However, it is usually more convenient to just use the
1628@code{..} operator, which tells @code{Asymptote} to choose its own
1629control points using the algorithms described in Donald Knuth's
1630monograph, The MetaFontbook, Chapter 14.
1631The user can still customize the guide (or path) by specifying
1632direction, tension, and curl values.
1633
1634The higher the tension, the straighter the curve is, and the more
1635it approximates a straight line.
1636@cindex @code{tension}
1637@cindex @code{and}
1638@cindex @code{atleast}
1639One can change the spline tension from its default value of 1 to any
1640real value greater than or equal to 0.75 (cf. John D. Hobby, Discrete and
1641Computational Geometry 1, 1986):
1642@verbatim
1643draw((100,0)..tension 2 ..(100,100)..(0,100));
1644draw((100,0)..tension 3 and 2 ..(100,100)..(0,100));
1645draw((100,0)..tension atleast 2 ..(100,100)..(0,100));
1646@end verbatim
1647
1648In these examples there is a space between @code{2} and @code{..}.
1649This is needed as @code{2.} is interpreted as a numerical constant.
1650
1651@cindex @code{curl}
1652The curl parameter specifies the curvature at the endpoints of a path
1653(0 means straight; the default value of 1 means approximately circular):
1654@verbatim
1655draw((100,0){curl 0}..(100,100)..{curl 0}(0,100));
1656@end verbatim
1657
1658@cindex @code{MetaPost ...@ }
1659@cindex @code{::}
1660The @code{MetaPost ...} path connector, which requests, when possible, an
1661inflection-free curve confined to a triangle defined by the
1662endpoints and directions, is implemented in @code{Asymptote} as the
1663convenient abbreviation @code{::} for @code{..tension atleast 1 ..}
1664(the ellipsis @code{...} is used in @code{Asymptote} to indicate a
1665variable number of arguments; @pxref{Rest arguments}).  For example,
1666compare
1667@verbatiminclude dots.asy
1668@sp 1
1669@center @image{dots}
1670@noindent
1671with
1672@verbatiminclude colons.asy
1673@sp 1
1674@center @image{colons}
1675
1676@cindex @code{---}
1677@cindex @code{&}
1678The @code{---} connector is an abbreviation for @code{..tension atleast
1679infinity..} and the @code{&} connector concatenates two paths, after
1680first stripping off the last node of the first path (which normally
1681should coincide with the first node of the second path).
1682
1683@node Programming
1684@chapter Programming
1685@cindex programming
1686
1687Here is a short introductory example to the @code{Asymptote} programming
1688language that highlights the similarity of its control structures
1689with those of C, C++, and Java:
1690@cindex declaration
1691@cindex assignment
1692@cindex conditional
1693@cindex loop
1694@cindex @code{if}
1695@cindex @code{else}
1696@cindex @code{for}
1697@verbatim
1698// This is a comment.
1699
1700// Declaration: Declare x to be a real variable;
1701real x;
1702
1703// Assignment: Assign the real variable x the value 1.
1704x=1.0;
1705
1706// Conditional: Test if x equals 1 or not.
1707if(x == 1.0) {
1708  write("x equals 1.0");
1709} else {
1710  write("x is not equal to 1.0");
1711}
1712
1713// Loop: iterate 10 times
1714for(int i=0; i < 10; ++i) {
1715  write(i);
1716}
1717
1718@end verbatim
1719
1720@cindex @code{while}
1721@cindex @code{do}
1722@cindex @code{break}
1723@cindex @code{continue}
1724@code{Asymptote} supports @code{while}, @code{do}, @code{break}, and
1725@code{continue} statements just as in C/C++. It also supports the Java-style
1726shorthand for iterating over all elements of an array:
1727
1728@cindex array iteration
1729@anchor{array iteration}
1730@verbatim
1731// Iterate over an array
1732int[] array={1,1,2,3,5};
1733for(int k : array) {
1734  write(k);
1735}
1736@end verbatim
1737@noindent
1738In addition, it supports many features beyond the ones found in those languages.
1739
1740@menu
1741* Data types::                  void, bool, int, real, pair, triple, string
1742* Paths and guides::            Bezier curves
1743* Pens::                        Colors, line types, line widths, font sizes
1744* Transforms::                  Affine transforms
1745* Frames and pictures::         Canvases for immediate and deferred drawing
1746* Files::                       Reading and writing your data
1747* Variable initializers::       Initialize your variables
1748* Structures::                  Organize your data
1749* Operators::                   Arithmetic and logical operators
1750* Implicit scaling::            Avoiding those ugly *s
1751* Functions::                   Traditional and high-order functions
1752* Arrays::                      Dynamic vectors
1753* Casts::                       Implicit and explicit casts
1754* Import::                      Importing external @code{Asymptote} modules
1755* Static::                      Where to allocate your variable?
1756@end menu
1757
1758@node Data types
1759@section Data types
1760@cindex data types
1761@code{Asymptote} supports the following data types (in addition to
1762user-defined types):
1763
1764@table @code
1765
1766@item void
1767@cindex @code{void}
1768The void type is used only by functions that take or return no arguments.
1769
1770@item bool
1771@cindex @code{bool}
1772a boolean type that can only take on the values @code{true} or
1773@code{false}. For example:
1774@verbatim
1775bool b=true;
1776@end verbatim
1777
1778@noindent
1779defines a boolean variable @code{b} and initializes it to the value
1780@code{true}. If no initializer is given:
1781@verbatim
1782bool b;
1783@end verbatim
1784
1785@noindent
1786the value @code{false} is assumed.
1787
1788@item bool3
1789@cindex @code{bool3}
1790an extended boolean type that can take on the values
1791@code{true}, @code{default}, or @code{false}. A bool3 type can be cast
1792to or from a bool. The default initializer for bool3 is @code{default}.
1793
1794@item int
1795@cindex @code{int}
1796@cindex @code{intMin}
1797@cindex @code{intMax}
1798an integer type; if no initializer is given, the implicit value @code{0}
1799is assumed. The minimum allowed value of an integer is @code{intMin} and the
1800maximum value is @code{intMax}.
1801
1802@item real
1803@cindex @code{real}
1804@cindex @code{realMin}
1805@cindex @code{realMax}
1806@cindex @code{realEpsilon}
1807@cindex @code{realDigits}
1808@cindex @code{mask}
1809@cindex @code{inf}
1810@cindex @code{isnan}
1811a real number; this should be set to the highest-precision native
1812floating-point type on the architecture. The implicit initializer for
1813reals is @code{0.0}. Real numbers have precision
1814@code{realEpsilon}, with @code{realDigits} significant digits.
1815The smallest positive real number is @code{realMin} and the largest
1816positive real number is @code{realMax}.
1817The variable @code{inf} and function @code{bool isnan(real x)}
1818are useful when floating-point exceptions are masked with
1819the @code{-mask} command-line option (the default in interactive mode).
1820
1821@item pair
1822@cindex @code{pair}
1823complex number, that is, an ordered pair of real components @code{(x,y)}.
1824The real and imaginary parts of a pair @code{z} can read as @code{z.x}
1825and @code{z.y}. We say that @code{x} and @code{y} are virtual members of
1826the data element pair; they cannot be directly modified, however.
1827The implicit initializer for pairs is @code{(0.0,0.0)}.
1828
1829There are a number of ways to take the complex conjugate of a pair:
1830@example
1831pair z=(3,4);
1832z=(z.x,-z.y);
1833z=z.x-I*z.y;
1834z=conj(z);
1835@end example
1836
1837Here @code{I} is the pair @code{(0,1)}.
1838A number of built-in functions are defined for pairs:
1839
1840@table @code
1841@item pair conj(pair z)
1842@cindex @code{conj}
1843returns the conjugate of @code{z};
1844
1845@item real length(pair z)
1846@cindex @code{length}
1847@cindex @code{abs}
1848returns the complex modulus @code{|z|} of its argument @code{z}.
1849For example,
1850@example
1851pair z=(3,4);
1852length(z);
1853@end example
1854returns the result 5. A synonym for @code{length(pair)} is @code{abs(pair)};
1855
1856@item real angle(pair z, bool warn=true)
1857@cindex @code{angle}
1858returns the angle of @code{z} in radians in the interval
1859[-@code{pi},@code{pi}] or @code{0} if @code{warn} is @code{false} and
1860@code{z=(0,0)} (rather than producing an error);
1861
1862@item real degrees(pair z, bool warn=true)
1863@cindex @code{degrees}
1864returns the angle of @code{z} in degrees in the interval [0,360)
1865or @code{0} if @code{warn} is @code{false} and @code{z=(0,0)} (rather than
1866producing an error);
1867
1868@item pair unit(pair z)
1869@cindex @code{unit}
1870returns a unit vector in the direction of the pair @code{z};
1871
1872@item pair expi(real angle)
1873@cindex @code{expi}
1874returns a unit vector in the direction @code{angle} measured in radians;
1875
1876@item pair dir(real degrees)
1877@cindex @code{dir}
1878returns a unit vector in the direction @code{degrees} measured in degrees;
1879
1880@item real xpart(pair z)
1881@cindex @code{xpart}
1882returns @code{z.x};
1883
1884@item real ypart(pair z)
1885@cindex @code{ypart}
1886returns @code{z.y};
1887
1888@item pair realmult(pair z, pair w)
1889@cindex @code{realmult}
1890returns the element-by-element product @code{(z.x*w.x,z.y*w.y)};
1891
1892@item real dot(explicit pair z, explicit pair w)
1893@cindex @code{dot}
1894returns the dot product @code{z.x*w.x+z.y*w.y};
1895
1896@item real cross(explicit pair z, explicit pair w)
1897@cindex @code{cross}
1898returns the 2D scalar product @code{z.x*w.y-z.y*w.x};
1899
1900@cindex @code{orient}
1901@item real orient(pair a, pair b, pair c);
1902returns a positive (negative) value if @code{a--b--c--cycle} is oriented
1903counterclockwise (clockwise) or zero if all three points are colinear.
1904Equivalently, a positive (negative) value is returned if
1905@code{c} lies to the left (right) of the line through @code{a} and @code{b}
1906or zero if @code{c} lies on this line.
1907The value returned can be expressed in terms of the 2D scalar cross product
1908as @code{cross(a-c,b-c)}, which is the determinant
1909@verbatim
1910|a.x a.y 1|
1911|b.x b.y 1|
1912|c.x c.y 1|
1913@end verbatim
1914
1915@cindex @code{incircle}
1916@item real incircle(pair a, pair b, pair c, pair d);
1917returns a positive (negative) value if @code{d} lies inside (outside)
1918the circle passing through the counterclockwise-oriented points @code{a,b,c}
1919or zero if @code{d} lies on the this circle.
1920The value returned is the determinant
1921@verbatim
1922|a.x a.y a.x^2+a.y^2 1|
1923|b.x b.y b.x^2+b.y^2 1|
1924|c.x c.y c.x^2+c.y^2 1|
1925|d.x d.y d.x^2+d.y^2 1|
1926@end verbatim
1927
1928@item pair minbound(pair z, pair w)
1929@cindex @code{minbound}
1930returns @code{(min(z.x,w.x),min(z.y,w.y))};
1931
1932@item pair maxbound(pair z, pair w)
1933@cindex @code{maxbound}
1934returns @code{(max(z.x,w.x),max(z.y,w.y))}.
1935
1936@end table
1937
1938@item triple
1939@cindex @code{triple}
1940an ordered triple of real components @code{(x,y,z)} used for
1941three-dimensional drawings. The respective components of a triple
1942@code{v} can read as @code{v.x}, @code{v.y}, and @code{v.z}.
1943The implicit initializer for triples is @code{(0.0,0.0,0.0)}.
1944
1945Here are the built-in functions for triples:
1946@table @code
1947@item real length(triple v)
1948@cindex @code{length}
1949returns the length @code{|v|} of the vector @code{v}.
1950A synonym for @code{length(triple)} is @code{abs(triple)};
1951
1952@item real polar(triple v, bool warn=true)
1953@cindex @code{polar}
1954returns the colatitude of @code{v} measured from the @math{z} axis in radians
1955or @code{0} if @code{warn} is @code{false} and @code{v=O} (rather than
1956producing an error);
1957
1958@item real azimuth(triple v, bool warn=true)
1959@cindex @code{azimuth}
1960returns the longitude of @code{v} measured from the @math{x} axis in radians
1961or @code{0} if @code{warn} is @code{false} and @code{v.x=v.y=0} (rather than
1962producing an error);
1963
1964@item real colatitude(triple v, bool warn=true)
1965@cindex @code{colatitude}
1966returns the colatitude of @code{v} measured from the @math{z} axis in degrees
1967or @code{0} if @code{warn} is @code{false} and @code{v=O} (rather than
1968producing an error);
1969
1970@item real latitude(triple v, bool warn=true)
1971@cindex @code{latitude}
1972returns the latitude of @code{v} measured from the @math{xy} plane in degrees
1973or @code{0} if @code{warn} is @code{false} and @code{v=O} (rather than
1974producing an error);
1975
1976@item real longitude(triple v, bool warn=true)
1977@cindex @code{longitude}
1978returns the longitude of @code{v} measured from the @math{x} axis in degrees
1979or @code{0} if @code{warn} is @code{false} and @code{v.x=v.y=0} (rather than
1980producing an error);
1981
1982@item triple unit(triple v)
1983@cindex @code{unit}
1984returns a unit triple in the direction of the triple @code{v};
1985
1986@item triple expi(real polar, real azimuth)
1987@cindex @code{expi}
1988returns a unit triple in the direction @code{(polar,azimuth)}
1989measured in radians;
1990
1991@item triple dir(real colatitude, real longitude)
1992@cindex @code{dir}
1993returns a unit triple in the direction @code{(colatitude,longitude)}
1994measured in degrees;
1995
1996@item real xpart(triple v)
1997@cindex @code{xpart}
1998returns @code{v.x};
1999
2000@item real ypart(triple v)
2001@cindex @code{ypart}
2002returns @code{v.y};
2003
2004@item real zpart(triple v)
2005@cindex @code{zpart}
2006returns @code{v.z};
2007
2008@item real dot(triple u, triple v)
2009@cindex @code{dot}
2010returns the dot product @code{u.x*v.x+u.y*v.y+u.z*v.z};
2011
2012@item triple cross(triple u, triple v)
2013@cindex @code{cross}
2014returns the cross product
2015
2016@code{(u.y*v.z-u.z*v.y,u.z*v.x-u.x*v.z,u.x*v.y-v.x*u.y)};
2017
2018@item triple minbound(triple u, triple v)
2019@cindex @code{minbound}
2020returns @code{(min(u.x,v.x),min(u.y,v.y),min(u.z,v.z))};
2021
2022@item triple maxbound(triple u, triple v)
2023@cindex @code{maxbound}
2024returns @code{(max(u.x,v.x),max(u.y,v.y),max(u.z,v.z)}).
2025
2026@end table
2027
2028@item string
2029@cindex @code{string}
2030@cindex @TeX{} string
2031a character string, implemented using the STL @code{string} class.
2032
2033Strings delimited by double quotes (@code{"}) are subject to the
2034following mappings to allow the use of double quotes in @TeX{} (e.g.@ for
2035using the @code{babel} package, @pxref{babel}):
2036
2037@itemize @bullet
2038@item \" maps to "
2039@item \\ maps to \\
2040@end itemize
2041
2042@cindex @code{C} string
2043Strings delimited by single quotes (@code{'}) have the same mappings as
2044character strings in ANSI @code{C}:
2045
2046@itemize @bullet
2047@item \' maps to '
2048@item \" maps to "
2049@item \? maps to ?
2050@item \\ maps to backslash
2051@item \a maps to alert
2052@item \b maps to backspace
2053@item \f maps to form feed
2054@item \n maps to newline
2055@item \r maps to carriage return
2056@item \t maps to tab
2057@item \v maps to vertical tab
2058@item \0-\377 map to corresponding octal byte
2059@item \x0-\xFF map to corresponding hexadecimal byte
2060@end itemize
2061
2062The implicit initializer for strings is the empty string @code{""}.
2063Strings may be concatenated with the @code{+} operator. In the following
2064string functions, position @code{0} denotes the start of the string:
2065@table @code
2066
2067@cindex @code{length}
2068@item int length(string s)
2069returns the length of the string @code{s};
2070
2071@cindex @code{find}
2072@item int find(string s, string t, int pos=0)
2073returns the position of the first occurrence of string @code{t} in string
2074@code{s} at or after position @code{pos}, or -1 if @code{t} is not a
2075substring of @code{s};
2076
2077@cindex @code{rfind}
2078@item int rfind(string s, string t, int pos=-1)
2079returns the position of the last occurrence of string @code{t} in string
2080@code{s} at or before position @code{pos} (if @code{pos}=-1, at the end
2081of the string @code{s}), or -1 if @code{t} is not a substring of @code{s};
2082
2083@cindex @code{insert}
2084@item string insert(string s, int pos, string t)
2085returns the string formed by inserting string @code{t} at position
2086@code{pos} in @code{s};
2087
2088@cindex @code{erase}
2089@item string erase(string s, int pos, int n)
2090returns the string formed by erasing the string of length @code{n}
2091(if @code{n}=-1, to the end of the string @code{s}) at
2092position @code{pos} in @code{s};
2093
2094@cindex @code{substr}
2095@item string substr(string s, int pos, int n=-1)
2096returns the substring of @code{s} starting at position @code{pos}
2097and of length @code{n} (if @code{n}=-1, until the end of the
2098string @code{s});
2099
2100@cindex @code{reverse}
2101@item string reverse(string s)
2102returns the string formed by reversing string @code{s};
2103
2104@item string replace(string s, string before, string after)
2105@cindex @code{replace}
2106returns a string with all occurrences of the string @code{before} in the
2107string @code{s} changed to the string @code{after};
2108
2109@item string replace(string s, string[][] table)
2110returns a string constructed by translating in string @code{s} all
2111occurrences of the string @code{before} in an array @code{table} of
2112string pairs @{@code{before},@code{after}@} to the corresponding
2113string @code{after};
2114
2115@cindex @code{split}
2116@item string[] split(string s, string delimiter="")
2117returns an array of strings obtained by splitting @code{s} into substrings
2118delimited by @code{delimiter} (an empty delimiter signifies a space,
2119but with duplicate delimiters discarded);
2120
2121@anchor{format}
2122@item string format(string s, int n, string locale="")
2123@cindex @code{format}
2124returns a string containing @code{n} formatted according to the C-style
2125format string @code{s} using locale @code{locale} (or the current locale if an
2126empty string is specified);
2127
2128@item string format(string s=defaultformat, string s=defaultseparator, real x, string locale="")
2129returns a string containing @code{x} formatted according to the C-style format
2130string @code{s} using locale @code{locale} (or the current locale if an
2131empty string is specified), following the behaviour of the C function
2132@code{fprintf}), except that only one data field is allowed, trailing
2133zeros are removed by default (unless @code{#} is specified), and
2134(if the format string specifies math mode) @TeX{} is used to typeset
2135scientific notation using the @code{defaultseparator="\!\times\!";};
2136
2137@cindex @code{hex}
2138@cindex @code{hexidecimal}
2139@item int hex(string s);
2140casts a hexidecimal string @code{s} to an integer;
2141
2142@cindex @code{ascii}
2143@cindex @code{ascii}
2144@item int ascii(string s);
2145returns the ASCII code for the first character of string @code{s};
2146
2147@cindex @code{string}
2148@item string string(real x, int digits=realDigits)
2149casts @code{x} to a string using precision @code{digits} and the C locale;
2150
2151@cindex @code{locale}
2152@item string locale(string s="")
2153sets the locale to the given string, if nonempty, and returns the
2154current locale;
2155
2156@item string time(string format="%a %b %d %T %Z %Y")
2157@cindex @code{time}
2158@cindex @code{date}
2159@cindex @code{strftime}
2160returns the current time formatted by the ANSI C routine
2161@code{strftime} according to the string @code{format} using the current
2162locale. Thus
2163@verbatim
2164time();
2165time("%a %b %d %H:%M:%S %Z %Y");
2166@end verbatim
2167
2168@noindent
2169are equivalent ways of returning the current time in the default
2170format used by the @code{UNIX} @code{date} command;
2171
2172@cindex @code{seconds}
2173@cindex @code{strptime}
2174@item int seconds(string t="", string format="")
2175returns the time measured in seconds after the Epoch (Thu Jan 01
217600:00:00 UTC 1970) as determined by the ANSI C routine @code{strptime}
2177according to the string @code{format} using the current locale, or the
2178current time if @code{t} is the empty string.
2179Note that the @code{"%Z"} extension to the POSIX @code{strptime}
2180specification is ignored by the current GNU C Library. If an error occurs, the
2181value -1 is returned. Here are some examples:
2182@verbatim
2183seconds("Mar 02 11:12:36 AM PST 2007","%b %d %r PST %Y");
2184seconds(time("%b %d %r %z %Y"),"%b %d %r %z %Y");
2185seconds(time("%b %d %r %Z %Y"),"%b %d %r "+time("%Z")+" %Y");
21861+(seconds()-seconds("Jan 1","%b %d"))/(24*60*60);
2187@end verbatim
2188The last example returns today's ordinal date, measured from the
2189beginning of the year.
2190
2191@cindex @code{time}
2192@cindex @code{strftime}
2193@item string time(int seconds, string format="%a %b %d %T %Z %Y")
2194returns the time corresponding to @code{seconds} seconds after the Epoch
2195(Thu Jan 01 00:00:00 UTC 1970) formatted by the ANSI C routine
2196@code{strftime} according to the string @code{format} using the current
2197locale. For example, to return the date corresponding to 24 hours ago:
2198@verbatim
2199time(seconds()-24*60*60);
2200@end verbatim
2201
2202@cindex @code{system}
2203@item int system(string s)
2204@item int system(string[] s)
2205if the setting @code{safe} is false, call the arbitrary system command @code{s};
2206
2207@cindex @code{asy}
2208@item void asy(string format, bool overwrite=false ... string[] s)
2209conditionally process each file name in array @code{s} in a new environment,
2210using format @code{format}, overwriting the output file only if
2211@code{overwrite} is true;
2212
2213@cindex @code{abort}
2214@item void abort(string s="")
2215aborts execution (with a non-zero return code in batch mode); if string
2216@code{s} is nonempty, a diagnostic message constructed from the source
2217file, line number, and @code{s} is printed;
2218
2219@cindex @code{assert}
2220@item void assert(bool b, string s="")
2221aborts execution with an error message constructed from @code{s} if
2222@code{b=false};
2223
2224@cindex @code{exit}
2225@item void exit()
2226exits (with a zero error return code in batch mode);
2227
2228@cindex @code{sleep}
2229@item void sleep(int seconds)
2230pauses for the given number of seconds;
2231
2232@cindex @code{usleep}
2233@item void usleep(int microseconds)
2234pauses for the given number of microseconds;
2235
2236@cindex @code{beep}
2237@item void beep()
2238produces a beep on the console;
2239
2240@end table
2241
2242@cindex @code{typedef}
2243
2244@end table
2245
2246As in C/C++, complicated types may be abbreviated with @code{typedef}
2247(see the example in @ref{Functions}).
2248
2249@node Paths and guides
2250@section Paths and guides
2251
2252@table @code
2253
2254@item path
2255@cindex @code{path}
2256a cubic spline resolved into a fixed path.
2257The implicit initializer for paths is @code{nullpath}.
2258
2259@cindex @code{circle}
2260@anchor{circle}
2261For example, the routine @code{circle(pair c, real r)}, which returns a
2262Bezier curve approximating a circle of radius @code{r} centered on @code{c},
2263is based on @code{unitcircle} (@pxref{unitcircle}):
2264@verbatim
2265path circle(pair c, real r)
2266{
2267  return shift(c)*scale(r)*unitcircle;
2268}
2269@end verbatim
2270If high accuracy is needed, a true circle may be produced with the
2271routine @code{Circle} defined in the module @code{graph.asy}:
2272@cindex @code{Circle}
2273@verbatim
2274import graph;
2275path Circle(pair c, real r, int n=nCircle);
2276@end verbatim
2277
2278A circular arc consistent with @code{circle} centered on
2279@code{c} with radius @code{r} from @code{angle1} to @code{angle2}
2280degrees, drawing counterclockwise if @code{angle2 >= angle1}, can be
2281constructed with
2282@cindex @code{arc}
2283@verbatim
2284path arc(pair c, real r, real angle1, real angle2);
2285@end verbatim
2286One may also specify the direction explicitly:
2287@verbatim
2288path arc(pair c, real r, real angle1, real angle2, bool direction);
2289@end verbatim
2290Here the direction can be specified as CCW (counter-clockwise) or CW
2291(clockwise). For convenience, an arc centered at @code{c} from pair
2292@code{z1} to @code{z2} (assuming @code{|z2-c|=|z1-c|}) in the may also
2293be constructed with
2294@verbatim
2295path arc(pair c, explicit pair z1, explicit pair z2,
2296         bool direction=CCW)
2297@end verbatim
2298
2299If high accuracy is needed, true arcs may be produced with routines
2300in the module @code{graph.asy} that produce Bezier curves with @code{n}
2301control points:
2302@cindex @code{Arc}
2303@verbatim
2304import graph;
2305path Arc(pair c, real r, real angle1, real angle2, bool direction,
2306         int n=nCircle);
2307path Arc(pair c, real r, real angle1, real angle2, int n=nCircle);
2308path Arc(pair c, explicit pair z1, explicit pair z2,
2309         bool direction=CCW, int n=nCircle);
2310@end verbatim
2311
2312An ellipse can be drawn with the routine
2313@cindex @code{ellipse}
2314@verbatim
2315path ellipse(pair c, real a, real b)
2316{
2317  return shift(c)*scale(a,b)*unitcircle;
2318}
2319@end verbatim
2320
2321A brace can be constructed between pairs @code{a} and @code{b} with
2322@cindex @code{brace}
2323@verbatim
2324path brace(pair a, pair b, real amplitude=bracedefaultratio*length(b-a));
2325@end verbatim
2326
2327This example illustrates the use of all five guide connectors discussed
2328in @ref{Tutorial} and @ref{Bezier curves}:
2329@verbatiminclude join.asy
2330@sp 1
2331@center @image{join}
2332
2333Here are some useful functions for paths:
2334
2335@table @code
2336
2337@cindex @code{length}
2338@item int length(path p);
2339This is the number of (linear or cubic) segments in path @code{p}.
2340If @code{p} is cyclic, this is the same as the number of nodes in @code{p}.
2341
2342@cindex @code{size}
2343@item int size(path p);
2344This is the number of nodes in the path @code{p}.
2345If @code{p} is cyclic, this is the same as @code{length(p)}.
2346
2347@cindex @code{cyclic}
2348@item bool cyclic(path p);
2349returns @code{true} iff path @code{p} is cyclic.
2350
2351@cindex @code{straight}
2352@item bool straight(path p, int i);
2353returns @code{true} iff the segment of path @code{p} between node
2354@code{i} and node @code{i+1} is straight.
2355
2356@cindex @code{piecewisestraight}
2357@item bool piecewisestraight(path p)
2358returns @code{true} iff the path @code{p} is piecewise straight.
2359
2360@cindex @code{point}
2361@item pair point(path p, int t);
2362If @code{p} is cyclic, return the coordinates of node @code{t} mod
2363@code{length(p)}. Otherwise, return the coordinates of node @code{t},
2364unless @code{t} < 0 (in which case @code{point(0)} is returned) or
2365@code{t} > @code{length(p)} (in which case @code{point(length(p))}
2366is returned).
2367
2368@item pair point(path p, real t);
2369This returns the coordinates of the point between node @code{floor(t)}
2370and @code{floor(t)+1} corresponding to the cubic spline parameter
2371@code{t-floor(t)} (@pxref{Bezier curves}). If @code{t} lies outside the range
2372[0,@code{length(p)}], it is first reduced modulo @code{length(p)}
2373in the case where @code{p} is cyclic or else converted to the corresponding
2374endpoint of @code{p}.
2375
2376@cindex @code{dir}
2377@item pair dir(path p, int t, int sign=0, bool normalize=true);
2378If @code{sign < 0}, return the direction (as a pair) of the incoming tangent
2379to path @code{p} at node @code{t}; if @code{sign > 0}, return the
2380direction of the outgoing tangent. If @code{sign=0}, the mean of these
2381two directions is returned.
2382
2383@item pair dir(path p, real t, bool normalize=true);
2384returns the direction of the tangent to path @code{p} at the point
2385between node @code{floor(t)} and @code{floor(t)+1} corresponding to the
2386cubic spline parameter @code{t-floor(t)} (@pxref{Bezier curves}).
2387
2388@item pair dir(path p)
2389returns dir(p,length(p)).
2390
2391@item pair dir(path p, path q)
2392returns unit(dir(p)+dir(q)).
2393
2394@cindex @code{accel}
2395@item pair accel(path p, int t, int sign=0);
2396If @code{sign < 0}, return the acceleration of the incoming path
2397@code{p} at node @code{t}; if @code{sign > 0}, return the
2398acceleration of the outgoing path. If @code{sign=0}, the mean of these
2399two accelerations is returned.
2400
2401@cindex @code{accel}
2402@item pair accel(path p, real t);
2403returns the acceleration of the path @code{p} at the point @code{t}.
2404
2405@cindex @code{radius}
2406@item real radius(path p, real t);
2407returns the radius of curvature of the path @code{p} at the point @code{t}.
2408
2409@cindex @code{precontrol}
2410@item pair precontrol(path p, int t);
2411returns the precontrol point of @code{p} at node @code{t}.
2412
2413@item pair precontrol(path p, real t);
2414returns the effective precontrol point of @code{p} at parameter @code{t}.
2415
2416@cindex @code{postcontrol}
2417@item pair postcontrol(path p, int t);
2418returns the postcontrol point of @code{p} at node @code{t}.
2419
2420@item pair postcontrol(path p, real t);
2421returns the effective postcontrol point  of @code{p} at parameter @code{t}.
2422
2423@cindex @code{arclength}
2424@item real arclength(path p);
2425returns the length (in user coordinates) of the piecewise linear
2426or cubic curve that path @code{p} represents.
2427
2428@cindex @code{arctime}
2429@item real arctime(path p, real L);
2430returns the path "time", a real number between 0 and the length of
2431the path in the sense of @code{point(path p, real t)}, at which the
2432cumulative arclength (measured from the beginning of the path) equals @code{L}.
2433
2434@cindex @code{arcpoint}
2435@item real arcpoint(path p, real L);
2436returns @code{point(p,arctime(p,L))}.
2437
2438@cindex @code{dirtime}
2439@item real dirtime(path p, pair z);
2440returns the first "time", a real number between 0 and the length of
2441the path in the sense of @code{point(path, real)}, at which the tangent
2442to the path has the direction of pair @code{z}, or -1 if this never happens.
2443
2444@cindex @code{reltime}
2445@item real reltime(path p, real l);
2446returns the time on path @code{p} at the relative fraction @code{l} of
2447its arclength.
2448
2449@cindex @code{relpoint}
2450@item pair relpoint(path p, real l);
2451returns the point on path @code{p} at the relative fraction @code{l} of its
2452arclength.
2453
2454@cindex @code{midpoint}
2455@item pair midpoint(path p);
2456returns the point on path @code{p} at half of its arclength.
2457
2458@cindex @code{reverse}
2459@item path reverse(path p);
2460returns a path running backwards along @code{p}.
2461
2462@cindex @code{subpath}
2463@item path subpath(path p, int a, int b);
2464returns the subpath of @code{p} running from node @code{a} to node @code{b}.
2465If @code{a} < @code{b}, the direction of the subpath is reversed.
2466
2467@item path subpath(path p, real a, real b);
2468returns the subpath  of @code{p} running from path time @code{a} to path
2469time @code{b}, in the sense of @code{point(path, real)}. If @code{a} <
2470@code{b}, the direction of the subpath is reversed.
2471
2472@cindex @code{intersect}
2473@item real[] intersect(path p, path q, real fuzz=-1);
2474If @code{p} and @code{q} have at least one intersection point, return a
2475real array of length 2 containing the times representing the respective
2476path times along @code{p} and @code{q}, in the sense of
2477@code{point(path, real)}, for one such intersection point (as chosen by
2478the algorithm described on page 137 of @code{The MetaFontbook}).
2479The computations are performed to the absolute error specified by @code{fuzz},
2480or if @code{fuzz < 0}, to machine precision. If the paths do not
2481intersect, return a real array of length 0.
2482
2483@cindex @code{intersections}
2484@item real[][] intersections(path p, path q, real fuzz=-1);
2485Return all (unless there are infinitely many) intersection times of
2486paths @code{p} and @code{q} as a sorted array of real arrays of length 2
2487(@pxref{sort}). The computations are performed to the absolute error
2488specified by @code{fuzz}, or if @code{fuzz < 0}, to machine precision.
2489
2490@cindex @code{intersections}
2491@item real[] intersections(path p, explicit pair a, explicit pair b, real fuzz=-1);
2492Return all (unless there are infinitely many) intersection times of path
2493@code{p} with the (infinite) line through points @code{a} and @code{b}
2494as a sorted array. The intersections returned are guaranteed to be
2495correct to within the absolute error specified by @code{fuzz}, or if
2496@code{fuzz < 0}, to machine precision.
2497
2498@cindex @code{times}
2499@item real[] times(path p, real x)
2500returns all intersection times of path @code{p} with the vertical line
2501through @code{(x,0)}.
2502
2503@cindex @code{times}
2504@item real[] times(path p, explicit pair z)
2505returns all intersection times of path @code{p} with the horizontal line
2506through @code{(0,z.y)}.
2507
2508@cindex @code{mintimes}
2509@item real[] mintimes(path p)
2510returns an array of length 2 containing times at which path @code{p}
2511reaches its minimal horizontal and vertical extents, respectively.
2512
2513@cindex @code{maxtimes}
2514@item real[] maxtimes(path p)
2515returns an array of length 2 containing times at which path @code{p}
2516reaches its maximal horizontal and vertical extents, respectively.
2517
2518@cindex @code{intersectionpoint}
2519@item pair intersectionpoint(path p, path q, real fuzz=-1);
2520returns the intersection point @code{point(p,intersect(p,q,fuzz)[0])}.
2521
2522@cindex @code{intersectionpoints}
2523@item pair[] intersectionpoints(path p, path q, real fuzz=-1);
2524returns an array containing all intersection points of the paths
2525@code{p} and @code{q}.
2526
2527@anchor{extension}
2528@cindex @code{whatever}
2529@cindex @code{extension}
2530@item pair extension(pair P, pair Q, pair p, pair q);
2531returns the intersection point of the extensions of the line segments
2532@code{P--Q} and @code{p--q}, or if the lines are parallel,
2533@code{(infinity,infinity)}.
2534
2535@cindex @code{cut}
2536@cindex @code{slice}
2537@item slice cut(path p, path knife, int n);
2538returns the portions of path @code{p} before and after the @code{n}th
2539intersection of @code{p} with path @code{knife} as a structure
2540@code{slice} (if no intersection exist is found, the entire path is
2541considered to be `before' the intersection):
2542@verbatim
2543struct slice {
2544  path before,after;
2545}
2546@end verbatim
2547The argument @code{n} is treated as modulo the number of intersections.
2548
2549@cindex @code{firstcut}
2550@cindex @code{slice}
2551@item slice firstcut(path p, path knife);
2552equivalent to @code{cut(p,knife,0);}
2553@cindex @code{MetaPost cutbefore}
2554Note that @code{firstcut.after} plays the role of the @code{MetaPost
2555cutbefore} command.
2556
2557@cindex @code{lastcut}
2558@item slice lastcut(path p, path knife);
2559equivalent to @code{cut(p,knife,-1);}
2560@cindex @code{MetaPost cutafter}
2561Note that @code{lastcut.before} plays the role of the
2562@code{MetaPost cutafter} command.
2563
2564@cindex @code{buildcycle}
2565@item path buildcycle(... path[] p);
2566This returns the path surrounding a region bounded by a list of two or more
2567consecutively intersecting paths, following the behaviour of the
2568@code{MetaPost buildcycle} command.
2569
2570@cindex @code{min}
2571@item pair min(path p);
2572returns the pair (left,bottom) for the path bounding box of path @code{p}.
2573
2574@cindex @code{max}
2575@item pair max(path p);
2576returns the pair (right,top) for the path bounding box of path @code{p}.
2577
2578@cindex @code{windingnumber}
2579@cindex @code{undefined}
2580@item int windingnumber(path p, pair z);
2581returns the winding number of the cyclic path @code{p} relative to the point
2582@code{z}. The winding number is positive if the path encircles @code{z} in the
2583counterclockwise direction. If @code{z} lies on @code{p} the constant
2584@code{undefined} (defined to be the largest odd integer) is returned.
2585
2586@cindex @code{interior}
2587@item bool interior(int windingnumber, pen fillrule)
2588returns true if @code{windingnumber} corresponds to an interior point
2589according to @code{fillrule}.
2590
2591@cindex @code{inside}
2592@item bool inside(path p, pair z, pen fillrule=currentpen);
2593returns @code{true} iff the point @code{z} lies inside or on the edge of
2594the region bounded by the cyclic path @code{p} according to the fill
2595rule @code{fillrule} (@pxref{fillrule}).
2596
2597@cindex @code{inside}
2598@item int inside(path p, path q, pen fillrule=currentpen);
2599returns @code{1} if the cyclic path @code{p} strictly contains @code{q}
2600according to the fill rule @code{fillrule} (@pxref{fillrule}), @code{-1}
2601if the cyclic path @code{q} strictly contains @code{p}, and @code{0}
2602otherwise.
2603
2604@cindex @code{inside}
2605@item pair inside(path p, pen fillrule=currentpen);
2606returns an arbitrary point strictly inside a cyclic path @code{p}
2607according to the fill rule @code{fillrule} (@pxref{fillrule}).
2608
2609@cindex @code{strokepath}
2610@item path[] strokepath(path g, pen p=currentpen);
2611returns the path array that @code{PostScript} would fill in drawing path
2612@code{g} with pen @code{p}.
2613
2614@end table
2615
2616@item guide
2617@cindex @code{guide}
2618an unresolved cubic spline (list of cubic-spline nodes and control points).
2619The implicit initializer for a guide is @code{nullpath}; this is useful
2620for building up a guide within a loop.
2621
2622A guide is similar to a path except that the computation of the cubic spline is
2623deferred until drawing time (when it is resolved into a path); this allows
2624two guides with free endpoint conditions to be joined together smoothly.
2625The solid curve in the following example is built up incrementally as
2626a guide, but only resolved at drawing time; the dashed curve is
2627incrementally resolved at each iteration, before the entire set of nodes
2628(shown in red) is known:
2629
2630@verbatiminclude mexicanhat.asy
2631@sp 1
2632@center @image{mexicanhat}
2633
2634We point out an efficiency distinction in the use of guides and paths:
2635@verbatim
2636guide g;
2637for(int i=0; i < 10; ++i)
2638  g=g--(i,i);
2639path p=g;
2640@end verbatim
2641
2642@noindent
2643runs in linear time, whereas
2644@verbatim
2645path p;
2646for(int i=0; i < 10; ++i)
2647  p=p--(i,i);
2648@end verbatim
2649
2650@noindent
2651runs in quadratic time, as the entire path up to that point is copied at each
2652step of the iteration.
2653
2654The following routines can be used to examine the individual elements of
2655a guide without actually resolving the guide to a fixed path (except for
2656internal cycles, which are resolved):
2657
2658@table @code
2659
2660@cindex @code{size}
2661@item int size(guide g);
2662Analogous to @code{size(path p)}.
2663
2664@cindex @code{length}
2665@item int length(guide g);
2666Analogous to @code{length(path p)}.
2667
2668@cindex @code{cyclic}
2669@item bool cyclic(path p);
2670Analogous to @code{cyclic(path p)}.
2671
2672@cindex @code{point}
2673@item pair point(guide g, int t);
2674Analogous to @code{point(path p, int t)}.
2675
2676@cindex @code{reverse}
2677@item guide reverse(guide g);
2678Analogous to @code{reverse(path p)}. If @code{g} is cyclic and
2679also contains a secondary cycle, it is first solved to a
2680path, then reversed. If @code{g} is not cyclic but contains an internal
2681cycle, only the internal cycle is solved before reversal. If there are
2682no internal cycles, the guide is reversed but not solved to a path.
2683
2684@cindex @code{dirSpecifier}
2685@item pair[] dirSpecifier(guide g, int i);
2686This returns a pair array of length 2 containing the outgoing (in
2687element 0) and incoming (in element 1) direction specifiers (or
2688@code{(0,0)} if none specified) for the segment of guide @code{g}
2689between nodes @code{i} and @code{i+1}.
2690
2691@cindex @code{controlSpecifier}
2692@item pair[] controlSpecifier(guide g, int i);
2693If the segment of guide @code{g} between nodes @code{i} and @code{i+1}
2694has explicit outgoing and incoming control points, they are returned as
2695elements 0 and 1, respectively, of a two-element array. Otherwise, an
2696empty array is returned.
2697
2698@cindex @code{tensionSpecifier}
2699@item tensionSpecifier tensionSpecifier(guide g, int i);
2700This returns the tension specifier for the segment of guide @code{g} between
2701nodes @code{i} and @code{i+1}. The individual components of the
2702@code{tensionSpecifier} type can be accessed as the virtual members
2703@code{in}, @code{out}, and @code{atLeast}.
2704
2705@cindex @code{curlSpecifier}
2706@item real[] curlSpecifier(guide g);
2707This returns an array containing the initial curl specifier (in element 0)
2708and final curl specifier (in element 1) for guide @code{g}.
2709
2710@end table
2711
2712As a technical detail we note that a direction specifier given to
2713@code{nullpath} modifies the node on the other side: the guides
2714@verbatim
2715a..{up}nullpath..b;
2716c..nullpath{up}..d;
2717e..{up}nullpath{down}..f;
2718@end verbatim
2719are respectively equivalent to
2720@verbatim
2721a..nullpath..{up}b;
2722c{up}..nullpath..d;
2723e{down}..nullpath..{up}f;
2724@end verbatim
2725
2726@end table
2727
2728@node Pens
2729@section Pens
2730
2731@cindex @code{pen}
2732@cindex @code{currentpen}
2733@cindex @code{MetaPost pickup}
2734In @code{Asymptote}, pens provide a context for the four basic drawing
2735commands (@pxref{Drawing commands}). They are used to specify the
2736following drawing attributes: color, line type, line width, line cap,
2737line join, fill rule, text alignment, font, font size, pattern,
2738overwrite mode, and calligraphic transforms on the pen nib. The
2739default pen used by the drawing routines is called
2740@code{currentpen}. This provides the same functionality as the
2741@code{MetaPost} command @code{pickup}.
2742The implicit initializer for pens is @code{defaultpen}.
2743
2744@cindex @code{+}
2745@cindex @code{*}
2746Pens may be added together with the nonassociative binary
2747operator @code{+}. This will add the colors of the two pens.
2748All other non-default attributes of the rightmost pen will
2749override those of the leftmost pen. Thus, one can obtain a yellow
2750dashed pen by saying @code{dashed+red+green} or @code{red+green+dashed}
2751or @code{red+dashed+green}. The binary operator @code{*}
2752can be used to scale the color of a pen by a real number, until it
2753saturates with one or more color components equal to 1.
2754
2755@itemize @bullet
2756
2757@item Colors are specified using one of the following colorspaces:
2758@cindex color
2759@table @code
2760@item pen gray(real g);
2761@cindex @code{gray}
2762@cindex grayscale
2763This produces a grayscale color, where the intensity @code{g} lies in the
2764interval [0,1], with 0.0 denoting black and 1.0 denoting white.
2765
2766@item pen rgb(real r, real g, real b);
2767@cindex @code{rgb}
2768This produces an @acronym{RGB} color, where each of the red, green,
2769and blue intensities @code{r}, @code{g}, @code{b}, lies in the interval [0,1].
2770
2771@item pen cmyk(real c, real m, real y, real k);
2772@cindex @code{cmyk}
2773This produces a @acronym{CMYK} color, where each of the cyan, magenta,
2774yellow, and black intensities @code{c}, @code{m}, @code{y}, @code{k},
2775lies in the interval [0,1].
2776
2777@item pen invisible;
2778@cindex @code{invisible}
2779This special pen writes in invisible ink, but adjusts the bounding
2780box as if something had been drawn (like the @code{\phantom}
2781command in @TeX{}). The function @code{bool invisible(pen)} can be used
2782to test whether a pen is invisible.
2783
2784@end table
2785
2786@cindex @code{defaultpen}
2787The default color is @code{black}; this may be changed with the routine
2788@code{defaultpen(pen)}. The function @code{colorspace(pen p)} returns
2789the colorspace of pen @code{p} as a string (@code{"gray"}, @code{"rgb"},
2790@code{"cmyk"}, or @code{""}).
2791
2792@cindex @code{colors}
2793The function @code{real[] colors(pen)} returns the color components of a pen.
2794The functions @code{pen gray(pen)}, @code{pen rgb(pen)},  and
2795@code{pen cmyk(pen)} return new pens obtained by converting their
2796arguments to the respective color spaces.
2797@cindex @code{colorless}
2798The function @code{colorless(pen=currentpen)} returns a copy of its argument
2799with the color attributes stripped (to avoid color mixing).
2800
2801A 6-character RGB hexidecimal string can be converted to a pen with
2802the routine
2803@cindex @code{rgb}
2804@cindex @code{hexidecimal}
2805@verbatim
2806pen rgb(string s);
2807@end verbatim
2808@noindent
2809A pen can be converted to a hexidecimal string with
2810@cindex @code{hex}
2811@item string hex(pen p);
2812
2813Various shades and mixtures of the grayscale primary colors
2814@code{black} and @code{white}, @acronym{RGB} primary colors
2815@code{red}, @code{green}, and @code{blue}, and
2816@acronym{RGB} secondary colors @code{cyan}, @code{magenta}, and @code{yellow}
2817are defined as named colors, along with the @acronym{CMYK} primary
2818colors @code{Cyan}, @code{Magenta}, @code{Yellow}, and @code{Black}, in
2819the module @code{plain}:
2820@sp 1
2821@center @image{colors}
2822
2823The standard 140 @acronym{RGB} @code{X11} colors can be imported with
2824the command
2825@verbatim
2826import x11colors;
2827@end verbatim
2828and the standard 68 @acronym{CMYK} @TeX{} colors can be imported with
2829the command
2830@verbatim
2831import texcolors;
2832@end verbatim
2833Note that there is some overlap between these two standards
2834and the definitions of some colors (e.g.@ @code{Green}) actually disagree.
2835
2836@code{Asymptote} also comes with a @code{asycolors.sty} @code{LaTeX} package
2837that defines to @code{LaTeX} @acronym{CMYK} versions of
2838@code{Asymptote}'s predefined colors, so that they can be used
2839directly within @code{LaTeX} strings. Normally, such colors are
2840passed to @code{LaTeX} via a pen argument; however, to change the
2841color of only a portion of a string, say for a slide presentation,
2842(@pxref{slide}) it may be desirable to specify the color directly to
2843@code{LaTeX}. This file can be passed to @code{LaTeX} with the
2844@code{Asymptote} command
2845@verbatim
2846usepackage("asycolors");
2847@end verbatim
2848
2849The structure @code{hsv} defined in @code{plain_pens.asy} may be used
2850to convert between @acronym{HSV} and @acronym{RGB} spaces, where
2851the hue @code{h} is an angle in @math{[0,360)} and the saturation
2852@code{s} and value @code{v} lie in @code{[0,1]}:
2853@verbatim
2854pen p=hsv(180,0.5,0.75);
2855write(p);           // ([default], red=0.375, green=0.75, blue=0.75)
2856hsv q=p;
2857write(q.h,q.s,q.v); // 180     0.5     0.75
2858@end verbatim
2859
2860@item Line types are specified with the function
2861@code{pen linetype(real[] a, real offset=0, bool scale=true, bool adjust=true)},
2862@cindex @code{solid}
2863@cindex @code{dashed}
2864@cindex @code{dotted}
2865@cindex @code{longdashed}
2866@cindex @code{dashdotted}
2867@cindex @code{longdashdotted}
2868where @code{a} is an array of real array numbers.
2869The optional parameter @code{offset} specifies where in the pattern
2870to begin. The first number specifies how far (if @code{scale} is
2871@code{true}, in units of the pen line width; otherwise in
2872@code{PostScript} units) to draw with the pen on, the second number
2873specifies how far to draw with the pen off, and so on. If
2874@code{adjust} is @code{true}, these spacings are automatically
2875adjusted by @code{Asymptote} to fit the arclength of the path. Here
2876are the predefined line types:
2877@verbatim
2878pen solid=linetype(new real[]);
2879pen dotted=linetype(new real[] {0,4});
2880pen dashed=linetype(new real[] {8,8});
2881pen longdashed=linetype(new real[] {24,8});
2882pen dashdotted=linetype(new real[] {8,8,0,8});
2883pen longdashdotted=linetype(new real[] {24,8,0,8});
2884pen Dotted(pen p=currentpen) {return linetype(new real[] {0,3})+2*linewidth(p);}
2885pen Dotted=Dotted();
2886@end verbatim
2887@sp 1
2888@center @image{linetype}
2889
2890@cindex @code{defaultpen}
2891The default line type is @code{solid}; this may be changed with
2892@code{defaultpen(pen)}.
2893@cindex @code{linetype}
2894@cindex @code{offset}
2895@cindex @code{scale}
2896@cindex @code{adjust}
2897The line type of a pen can be determined with the functions
2898@code{real[] linetype(pen p=currentpen)},
2899@code{real offset(pen p)}, @code{bool scale(pen p)}, and
2900@code{bool adjust(pen p)}.
2901
2902@cindex @code{linewidth}
2903@cindex @code{defaultpen}
2904@item The pen line width is specified in @code{PostScript} units with
2905@code{pen linewidth(real)}. The default line width is 0.5 bp; this value
2906may be changed with @code{defaultpen(pen)}. The line width of a pen
2907is returned by @code{real linewidth(pen p=currentpen)}.
2908For convenience, in the module @code{plain_pens} we define
2909@verbatim
2910void defaultpen(real w) {defaultpen(linewidth(w));}
2911pen operator +(pen p, real w) {return p+linewidth(w);}
2912pen operator +(real w, pen p) {return linewidth(w)+p;}
2913@end verbatim
2914so that one may set the line width like this:
2915@verbatim
2916defaultpen(2);
2917pen p=red+0.5;
2918@end verbatim
2919
2920@cindex @code{linecap}
2921@cindex @code{squarecap}
2922@cindex @code{roundcap}
2923@cindex @code{extendcap}
2924@cindex @code{defaultpen}
2925@item A pen with a specific @code{PostScript} line cap is returned on
2926calling @code{linecap} with an integer argument:
2927@verbatim
2928pen squarecap=linecap(0);
2929pen roundcap=linecap(1);
2930pen extendcap=linecap(2);
2931@end verbatim
2932
2933@noindent
2934The default line cap, @code{roundcap}, may be changed with
2935@code{defaultpen(pen)}. The line cap of a pen is returned by
2936@code{int linecap(pen p=currentpen)}.
2937
2938@cindex @code{linejoin}
2939@cindex @code{miterjoin}
2940@cindex @code{roundjoin}
2941@cindex @code{beveljoin}
2942@item A pen with a specific @code{PostScript} join style is returned on
2943calling @code{linejoin} with an integer argument:
2944@verbatim
2945pen miterjoin=linejoin(0);
2946pen roundjoin=linejoin(1);
2947pen beveljoin=linejoin(2);
2948@end verbatim
2949
2950@noindent
2951The default join style, @code{roundjoin}, may be changed with
2952@code{defaultpen(pen)}.The join style of a pen is returned by
2953@code{int linejoin(pen p=currentpen)}.
2954
2955@cindex @code{miterlimit}
2956@item A pen with a specific @code{PostScript} miter limit is returned by
2957calling @code{miterlimit(real)}.
2958The default miterlimit, @code{10.0}, may be changed with
2959@code{defaultpen(pen)}. The miter limit of a pen is returned by
2960@code{real miterlimit(pen p=currentpen)}.
2961
2962@cindex @code{fillrule}
2963@cindex @code{zerowinding}
2964@cindex @code{evenodd}
2965@anchor{fillrule}
2966@item A pen with a specific @code{PostScript} fill rule is returned on
2967calling @code{fillrule} with an integer argument:
2968@verbatim
2969pen zerowinding=fillrule(0);
2970pen evenodd=fillrule(1);
2971@end verbatim
2972
2973@noindent
2974The fill rule, which identifies the algorithm used to determine the
2975insideness of a path or array of paths, only affects the @code{clip},
2976@code{fill}, and @code{inside} functions. For the @code{zerowinding}
2977fill rule, a point @code{z} is outside the region bounded by a path if
2978the number of upward intersections of the path with the horizontal
2979line @code{z--z+infinity} minus the number of downward intersections
2980is zero. For the @code{evenodd} fill rule, @code{z} is considered to
2981be outside the region if the total number of such intersections is even.
2982The default fill rule, @code{zerowinding}, may be changed with
2983@code{defaultpen(pen)}. The fill rule of a pen is returned by
2984@code{int fillrule(pen p=currentpen)}.
2985
2986@cindex @code{nobasealign}
2987@cindex @code{basealign}
2988@anchor{basealign}
2989@item A pen with a specific text alignment setting is returned on
2990calling @code{basealign} with an integer argument:
2991@verbatim
2992pen nobasealign=basealign(0);
2993pen basealign=basealign(1);
2994@end verbatim
2995
2996@noindent
2997The default setting, @code{nobasealign},which may be changed with
2998@code{defaultpen(pen)}, causes the label alignment routines to use the
2999full label bounding box for alignment. In contrast, @code{basealign}
3000requests that the @TeX{} baseline be respected.
3001The base align setting of a pen is returned by
3002@code{int basealigin(pen p=currentpen)}.
3003
3004@cindex @code{fontsize}
3005@cindex @code{lineskip}
3006@cindex @code{defaultpen}
3007@cindex @code{type1cm}
3008@item The font size is specified in @TeX{} points (1 pt = 1/72.27 inches) with
3009the function @code{pen fontsize(real size, real lineskip=1.2*size)}.
3010The default font size, 12pt, may be changed with @code{defaultpen(pen)}.
3011Nonstandard font sizes may require inserting
3012@verbatim
3013import fontsize;
3014@end verbatim
3015at the beginning of the file (this requires the @code{type1cm} package
3016available from
3017@quotation
3018@url{http://mirror.ctan.org/macros/latex/contrib/type1cm/}
3019@end quotation
3020and included in recent @code{LaTeX} distributions). The font size and line
3021skip of a pen can be examined with the routines
3022@code{real fontsize(pen p=currentpen)} and
3023@code{real lineskip(pen p=currentpen)}, respectively.
3024
3025@cindex @code{font}
3026@cindex @code{LaTeX fonts}
3027@cindex @code{NFSS}
3028@cindex @code{font command}
3029@item A pen using a specific @code{LaTeX} @code{NFSS} font is returned
3030by calling the function @code{pen font(string encoding, string family,
3031string series, string shape)}. The default setting,
3032@code{font("OT1","cmr","m","n")}, corresponds to 12pt Computer Modern Roman;
3033this may be changed with @code{defaultpen(pen)}.
3034The font setting of a pen is returned by
3035@code{string font(pen p=currentpen)}.
3036Support for standardized international characters is provided by the
3037@code{unicode} package (@pxref{unicode}).
3038
3039@cindex @code{TeX fonts}
3040Alternatively, one may select a fixed-size @TeX{} font (on which
3041@code{fontsize} has no effect) like @code{"cmr12"} (12pt Computer Modern
3042Roman) or @code{"pcrr"} (Courier) using the function @code{pen font(string
3043name)}. An optional size argument can also be given to scale the font
3044to the requested size: @code{pen font(string name, real size)}.
3045
3046@cindex @code{fontcommand}
3047A nonstandard font command can be generated with
3048@code{pen fontcommand(string)}.
3049
3050@cindex @code{PostScript fonts}
3051A convenient interface to the following standard @code{PostScript}
3052fonts is also provided:
3053@verbatim
3054pen AvantGarde(string series="m", string shape="n");
3055pen Bookman(string series="m", string shape="n");
3056pen Courier(string series="m", string shape="n");
3057pen Helvetica(string series="m", string shape="n");
3058pen NewCenturySchoolBook(string series="m", string shape="n");
3059pen Palatino(string series="m", string shape="n");
3060pen TimesRoman(string series="m", string shape="n");
3061pen ZapfChancery(string series="m", string shape="n");
3062pen Symbol(string series="m", string shape="n");
3063pen ZapfDingbats(string series="m", string shape="n");
3064@end verbatim
3065
3066@anchor{transparency}
3067@cindex transparency
3068@cindex @code{opacity}
3069@item The transparency of a pen can be changed with the command:
3070@verbatim
3071pen opacity(real opacity=1, string blend="Compatible");
3072@end verbatim
3073The opacity can be varied from @code{0} (fully transparent) to the default
3074value of @code{1} (opaque), and @code{blend} specifies one of the
3075following foreground--background blending operations:
3076@verbatim
3077"Compatible","Normal","Multiply","Screen","Overlay","SoftLight",
3078"HardLight","ColorDodge","ColorBurn","Darken","Lighten","Difference",
3079"Exclusion","Hue","Saturation","Color","Luminosity",
3080@end verbatim
3081as described in
3082
3083@url{http://partners.adobe.com/public/developer/en/pdf/PDFReference16.pdf}.
3084Since @code{PostScript} does not support transparency, this feature is
3085only effective with the @code{-f pdf} output format option; other
3086formats can be produced from the resulting @acronym{PDF} file with the
3087@code{ImageMagick} @code{convert} program.
3088Labels are always drawn with an @code{opacity} of 1.
3089A simple example of transparent filling is provided in the example file
3090@code{transparency.asy}.
3091
3092@cindex patterns
3093@cindex tilings
3094@item @code{PostScript} commands within a @code{picture} may be used
3095to create a tiling pattern, identified by the string @code{name}, for
3096@code{fill} and @code{draw} operations by adding it to the
3097global @code{PostScript} frame @code{currentpatterns},
3098with optional left-bottom margin @code{lb} and right-top margin @code{rt}.
3099@verbatim
3100import patterns;
3101void add(string name, picture pic, pair lb=0, pair rt=0);
3102@end verbatim
3103
3104To @code{fill} or @code{draw} using pattern @code{name}, use
3105the pen @code{pattern("name")}. For example, rectangular tilings
3106can be constructed using the routines
3107@code{picture tile(real Hx=5mm, real Hy=0, pen p=currentpen,
3108filltype filltype=NoFill)},
3109@code{picture checker(real Hx=5mm, real Hy=0, pen p=currentpen)}, and
3110@code{picture brick(real Hx=5mm, real Hy=0, pen p=currentpen)} defined in
3111@code{patterns.asy}:
3112@cindex grid
3113@cindex tile
3114@cindex checker
3115@cindex brick
3116@verbatiminclude tile.asy
3117@sp 1
3118@center @image{tile}
3119
3120@cindex hatch
3121@cindex crosshatch
3122Hatch patterns can be generated with the routines
3123@code{picture hatch(real H=5mm, pair dir=NE, pen p=currentpen)},
3124@code{picture crosshatch(real H=5mm, pen p=currentpen)}:
3125@verbatiminclude hatch.asy
3126@sp 1
3127@center @image{hatch}
3128
3129You may need to turn off aliasing in your @code{PostScript} viewer for
3130patterns to appear correctly. Custom patterns can easily be constructed,
3131following the examples in @code{patterns.asy}. The tiled pattern can
3132even incorporate shading (@pxref{gradient shading}), as illustrated
3133in this example (not included in the manual because not all printers support
3134@code{PostScript} 3):
3135@verbatiminclude shadedtiling.asy
3136
3137@anchor{makepen}
3138@cindex @code{makepen}
3139@item One can specify a custom pen nib as an arbitrary polygonal path
3140with @code{pen makepen(path)}; this path represents the mark to be
3141drawn for paths containing a single point. This pen nib path can be
3142recovered from a pen with @code{path nib(pen)}. Unlike in
3143@code{MetaPost}, the path need not be convex:
3144
3145@verbatiminclude makepen.asy
3146@sp 1
3147@center @image{makepen}
3148
3149The value @code{nullpath} represents a circular pen nib (the default);
3150an elliptical pen can be achieved simply by multiplying the pen by a
3151transform: @code{yscale(2)*currentpen}.
3152
3153@anchor{overwrite}
3154@cindex @code{overwrite}
3155@item One can prevent labels from overwriting one another by using
3156the pen attribute @code{overwrite}, which takes a single argument:
3157
3158@table @code
3159@cindex @code{Allow}
3160@cindex @code{defaultpen}
3161@item Allow
3162Allow labels to overwrite one another. This is the default behaviour (unless
3163overridden with @code{defaultpen(pen)}.
3164
3165@cindex @code{Suppress}
3166@item Suppress
3167Suppress, with a warning, each label that would overwrite another label.
3168
3169@cindex @code{SuppressQuiet}
3170@item SuppressQuiet
3171Suppress, without warning, each label that would overwrite another label.
3172
3173@cindex @code{Move}
3174@item Move
3175Move a label that would overwrite another out of the way and issue a warning.
3176As this adjustment is during the final output phase (in @code{PostScript}
3177coordinates) it could result in a larger figure than requested.
3178
3179@cindex @code{MoveQuiet}
3180@item MoveQuiet
3181Move a label that would overwrite another out of the way, without warning.
3182As this adjustment is during the final output phase (in @code{PostScript}
3183coordinates) it could result in a larger figure than requested.
3184
3185@end table
3186
3187@end itemize
3188
3189@cindex @code{defaultpen}
3190@cindex @code{resetdefaultpen}
3191The routine @code{defaultpen()} returns the current default pen attributes.
3192Calling the routine @code{resetdefaultpen()} resets all pen default
3193attributes to their initial values.
3194
3195@node Transforms
3196@section Transforms
3197
3198@cindex @code{transform}
3199@code{Asymptote} makes extensive use of affine transforms. A pair
3200@code{(x,y)} is transformed by the transform
3201@code{t=(t.x,t.y,t.xx,t.xy,t.yx,t.yy)} to @code{(x',y')}, where
3202@verbatim
3203x' = t.x + t.xx * x + t.xy * y
3204y' = t.y + t.yx * x + t.yy * y
3205@end verbatim
3206@noindent
3207This is equivalent to the @code{PostScript} transformation
3208@code{[t.xx t.yx t.xy t.yy t.x t.y]}.
3209
3210Transforms can be applied to pairs, guides, paths, pens, strings,
3211transforms, frames, and pictures by multiplication (via the binary operator
3212@code{*}) on the left (@pxref{circle} for an example).
3213@cindex @code{inverse}
3214Transforms can be composed with one another and inverted with the
3215function @code{transform inverse(transform t)}; they can also be raised to any
3216integer power with the @code{^} operator.
3217
3218The built-in transforms are:
3219
3220@table @code
3221@item transform identity();
3222@cindex @code{identity}
3223the identity transform;
3224@item transform shift(pair z);
3225@cindex @code{shift}
3226translates by the pair @code{z};
3227@item transform shift(real x, real y);
3228@cindex @code{shift}
3229translates by the pair @code{(x,y)};
3230@item transform xscale(real x);
3231@cindex @code{xscale}
3232scales by @code{x} in the @math{x} direction;
3233@item transform yscale(real y);
3234@cindex @code{yscale}
3235scales by @code{y} in the @math{y} direction;
3236@item transform scale(real s);
3237@cindex @code{scale}
3238scale by @code{s} in both @math{x} and @math{y} directions;
3239@item transform scale(real x, real y);
3240@cindex @code{scale}
3241scale by @code{x} in the @math{x} direction and by @code{y} in the
3242@math{y} direction;
3243@item transform slant(real s);
3244@cindex @code{slant}
3245maps @code{(x,y)} --> @code{(x+s*y,y)};
3246@item transform rotate(real angle, pair z=(0,0));
3247rotates by @code{angle} in degrees about @code{z};
3248@item transform reflect(pair a, pair b);
3249@cindex @code{reflect}
3250reflects about the line @code{a--b}.
3251@end table
3252
3253@cindex @code{shift}
3254@cindex @code{shiftless}
3255The implicit initializer for transforms is @code{identity()}.
3256The routines @code{shift(transform t)} and @code{shiftless(transform t)}
3257return the transforms @code{(t.x,t.y,0,0,0,0)} and
3258@code{(0,0,t.xx,t.xy,t.yx,t.yy)} respectively.
3259
3260
3261@node Frames and pictures
3262@section Frames and pictures
3263
3264@table @code
3265
3266@item frame
3267@cindex @code{frame}
3268@cindex @code{newframe}
3269@cindex @code{empty}
3270@cindex @code{erase}
3271@cindex @code{min}
3272@cindex @code{max}
3273Frames are canvases for drawing in @code{PostScript} coordinates. While working
3274with frames directly is occasionally necessary for constructing deferred
3275drawing routines, pictures are usually more convenient to work with.
3276The implicit initializer for frames is @code{newframe}. The function
3277@code{bool empty(frame f)} returns @code{true} only if the frame @code{f}
3278is empty. A frame may be erased with the @code{erase(frame)} routine.
3279The functions @code{pair min(frame)} and @code{pair max(frame)}
3280return the (left,bottom) and (right,top) coordinates of the frame
3281bounding box, respectively. The contents of frame @code{src} may be
3282appended to frame @code{dest} with the command
3283@verbatim
3284void add(frame dest, frame src);
3285@end verbatim
3286or prepended with
3287@verbatim
3288void prepend(frame dest, frame src);
3289@end verbatim
3290A frame obtained by aligning frame @code{f} in the direction
3291@code{align}, in a manner analogous to the @code{align} argument of
3292@code{label} (@pxref{label}), is returned by
3293@verbatim
3294frame align(frame f, pair align);
3295@end verbatim
3296
3297@cindex @code{box}
3298@cindex @code{ellipse}
3299@anchor{envelope}
3300@cindex @code{envelope}
3301To draw or fill a box or ellipse around a label or frame and return the
3302boundary as a path, use one of the predefined @code{envelope} routines
3303@verbatim
3304path box(frame f, Label L="", real xmargin=0,
3305         real ymargin=xmargin, pen p=currentpen,
3306         filltype filltype=NoFill, bool above=true);
3307path roundbox(frame f, Label L="", real xmargin=0,
3308              real ymargin=xmargin, pen p=currentpen,
3309              filltype filltype=NoFill, bool above=true);
3310path ellipse(frame f, Label L="", real xmargin=0,
3311             real ymargin=xmargin, pen p=currentpen,
3312             filltype filltype=NoFill, bool above=true);
3313@end verbatim
3314
3315@item picture
3316@cindex @code{picture}
3317Pictures are high-level structures (@pxref{Structures}) defined in
3318the module @code{plain} that provide canvases for drawing in user coordinates.
3319The default picture is called @code{currentpicture}. A new picture
3320can be created like this:
3321@verbatim
3322picture pic;
3323@end verbatim
3324@noindent
3325Anonymous pictures can be made by the expression @code{new picture}.
3326
3327The @code{size} routine specifies the dimensions of the desired picture:
3328
3329@anchor{size}
3330@cindex @code{size}
3331@verbatim
3332void size(picture pic=currentpicture, real x, real y=x,
3333          bool keepAspect=Aspect);
3334@end verbatim
3335
3336If the @code{x} and @code{y} sizes are both 0, user coordinates will be
3337interpreted as @code{PostScript} coordinates. In this case, the transform
3338mapping @code{pic} to the final output frame is @code{identity()}.
3339
3340If exactly one of @code{x} or @code{y} is 0, no size restriction
3341is imposed in that direction; it will be scaled the same as the other
3342direction.
3343
3344@cindex @code{keepAspect}
3345@cindex @code{Aspect}
3346If @code{keepAspect} is set to @code{Aspect} or @code{true},
3347the picture will be scaled with its aspect ratio preserved such that
3348the final width is no more than @code{x} and the final height is
3349no more than @code{y}.
3350
3351@cindex @code{keepAspect}
3352@cindex @code{IgnoreAspect}
3353If @code{keepAspect} is set to @code{IgnoreAspect} or @code{false},
3354the picture will be scaled in both directions so that the final width
3355is @code{x} and the height is @code{y}.
3356
3357To make the user coordinates of picture @code{pic}
3358represent multiples of @code{x} units in the @math{x} direction and
3359@code{y} units in the @math{y} direction, use
3360@anchor{unitsize}
3361@cindex @code{unitsize}
3362@verbatim
3363void unitsize(picture pic=currentpicture, real x, real y=x);
3364@end verbatim
3365When nonzero, these @code{x} and @code{y} values override the
3366corresponding size parameters of picture @code{pic}.
3367
3368The routine
3369@cindex @code{size}
3370@verbatim
3371void size(picture pic=currentpicture, real xsize, real ysize,
3372          pair min, pair max);
3373@end verbatim
3374forces the final picture scaling to map the user coordinates
3375@code{box(min,max)} to a region of width @code{xsize} and height @code{ysize}
3376(when these parameters are nonzero).
3377
3378Alternatively, calling the routine
3379@cindex @code{fixedscaling}
3380@verbatim
3381transform fixedscaling(picture pic=currentpicture, pair min,
3382                       pair max, pen p=nullpen, bool warn=false);
3383@end verbatim
3384will cause picture @code{pic} to use a fixed scaling to map user
3385coordinates in @code{box(min,max)} to the (already specified) picture size,
3386taking account of the width of pen @code{p}. A warning will be issued if
3387the final picture exceeds the specified size.
3388
3389A picture @code{pic} can be fit to a frame and output to a file
3390@code{prefix}.@code{format} using image format @code{format}
3391by calling the @code{shipout} function:
3392@anchor{shipout}
3393@cindex @code{shipout}
3394@cindex @code{outprefix}
3395@verbatim
3396void shipout(string prefix=defaultfilename, picture pic=currentpicture,
3397             orientation orientation=orientation,
3398             string format="", bool wait=false, bool view=true,
3399             string options="", string script="",
3400             light light=currentlight, projection P=currentprojection)
3401@end verbatim
3402@noindent
3403The default output format, @code{PostScript}, may be changed
3404with the @code{-f} or @code{-tex} command-line options.
3405The @code{options}, @code{script}, and @code{projection} parameters
3406are only relevant for 3D pictures. If @code{defaultfilename} is an
3407empty string, the prefix @code{outprefix()} will be used.
3408
3409A @code{shipout()} command is added implicitly at file exit if no
3410previous @code{shipout} commands have been executed.
3411@cindex @code{orientation}
3412@cindex @code{Portrait}
3413@cindex @code{Landscape}
3414@cindex @code{UpsideDown}
3415The default page orientation is @code{Portrait}; this may be modified
3416by changing the variable @code{orientation}. To output in landscape
3417mode, simply set the variable @code{orientation=Landscape} or issue
3418the command
3419@verbatim
3420shipout(Landscape);
3421@end verbatim
3422
3423@cindex @code{Seascape}
3424To rotate the page by @math{-90} degrees, use the orientation @code{Seascape}.
3425@cindex @code{UpsideDown}
3426The orientation @code{UpsideDown} rotates the page by 180 degrees.
3427
3428@cindex subpictures
3429@cindex @code{fit}
3430A picture @code{pic} can be explicitly fit to a frame by calling
3431@verbatim
3432frame pic.fit(real xsize=pic.xsize, real ysize=pic.ysize,
3433              bool keepAspect=pic.keepAspect);
3434@end verbatim
3435The default size and aspect ratio settings are those given to the
3436@code{size} command (which default to @code{0}, @code{0}, and
3437@code{true}, respectively).
3438@cindex @code{calculateTransform}
3439The transformation that would currently be used to fit a picture
3440@code{pic} to a frame is returned by the member function
3441@code{pic.calculateTransform()}.
3442
3443In certain cases (e.g.@ 2D graphs) where only an approximate size
3444estimate for @code{pic} is available, the picture fitting routine
3445@verbatim
3446frame pic.scale(real xsize=this.xsize, real ysize=this.ysize,
3447                bool keepAspect=this.keepAspect);
3448@end verbatim
3449(which scales the resulting frame, including labels and fixed-size
3450objects) will enforce perfect compliance with the requested size
3451specification, but should not normally be required.
3452
3453@cindex @code{box}
3454To draw a bounding box with margins around a picture, fit the
3455picture to a frame using the function
3456@verbatim
3457frame bbox(picture pic=currentpicture, real xmargin=0,
3458           real ymargin=xmargin, pen p=currentpen,
3459           filltype filltype=NoFill);
3460@end verbatim
3461@anchor{filltype}
3462Here @code{filltype} specifies one of the following fill types:
3463@table @code
3464@cindex @code{FillDraw}
3465@item FillDraw
3466Fill the interior and draw the boundary.
3467
3468@item FillDraw(real xmargin=0, real ymargin=xmargin, pen fillpen=nullpen,
3469               @code{pen drawpen=nullpen)}
3470@cindex @code{nullpen}
3471If @code{fillpen} is @code{nullpen}, fill with the drawing pen;
3472otherwise fill with pen @code{fillpen}.
3473If @code{drawpen} is @code{nullpen}, draw the boundary with @code{fillpen};
3474otherwise with @code{drawpen}. An optional margin of
3475@code{xmargin} and @code{ymargin} can be specified.
3476
3477@cindex @code{Fill}
3478@item Fill
3479Fill the interior.
3480
3481@cindex @code{nullpen}
3482@item Fill(real xmargin=0, real ymargin=xmargin, pen p=nullpen)
3483If @code{p} is @code{nullpen}, fill with the drawing pen;
3484otherwise fill with pen @code{p}. An optional margin of
3485@code{xmargin} and @code{ymargin} can be specified.
3486
3487@cindex @code{NoFill}
3488@item NoFill
3489Do not fill.
3490
3491@item Draw
3492Draw only the boundary.
3493
3494@cindex @code{Draw}
3495@item Draw(real xmargin=0, real ymargin=xmargin, pen p=nullpen)
3496If @code{p} is @code{nullpen}, draw the boundary with the drawing pen;
3497otherwise draw with pen @code{p}. An optional margin of
3498@code{xmargin} and @code{ymargin} can be specified.
3499
3500@cindex @code{UnFill}
3501@item UnFill
3502Clip the region.
3503
3504@cindex @code{UnFill}
3505@item UnFill(real xmargin=0, real ymargin=xmargin)
3506Clip the region and surrounding margins @code{xmargin} and @code{ymargin}.
3507
3508@cindex @code{RadialShade}
3509@item RadialShade(pen penc, pen penr)
3510Fill varying radially from @code{penc} at the center of the bounding
3511box to @code{penr} at the edge.
3512
3513@cindex @code{RadialShadeDraw}
3514@item RadialShadeDraw(real xmargin=0, real ymargin=xmargin, pen penc,
3515                      @code{pen penr, pen drawpen=nullpen)}
3516Fill with RadialShade and draw the boundary.
3517
3518@end table
3519
3520@cindex bounding box
3521@cindex background color
3522For example, to draw a bounding box around a picture with a 0.25 cm
3523margin and output the resulting frame, use the command:
3524@verbatim
3525shipout(bbox(0.25cm));
3526@end verbatim
3527A @code{picture} may be fit to a frame with the background color
3528pen @code{p}, using the function @code{bbox(p,Fill)}.
3529
3530The functions
3531@verbatim
3532pair min(picture pic, user=false);
3533pair max(picture pic, user=false);
3534pair size(picture pic, user=false);
3535@end verbatim
3536calculate the bounds that picture @code{pic} would
3537have if it were currently fit to a frame using its default size specification.
3538If @code{user} is @code{false} the returned value is in
3539@code{PostScript} coordinates, otherwise it is in user coordinates.
3540
3541The function
3542@verbatim
3543pair point(picture pic=currentpicture, pair dir, bool user=true);
3544@end verbatim
3545is a convenient way of determining the point on the bounding box of
3546@code{pic} in the direction @code{dir} relative to its center, ignoring
3547the contributions from fixed-size objects (such as labels and arrowheads).
3548If @code{user} is @code{true} the returned value is in user coordinates,
3549otherwise it is in @code{PostScript} coordinates.
3550
3551The function
3552@verbatim
3553pair truepoint(picture pic=currentpicture, pair dir, bool user=true);
3554@end verbatim
3555is identical to @code{point}, except that it also accounts for
3556fixed-size objects, using the scaling transform that picture @code{pic}
3557would have if currently fit to a frame using its default size
3558specification. If @code{user} is @code{true} the returned value is in
3559user coordinates, otherwise it is in @code{PostScript} coordinates.
3560
3561@anchor{add}
3562Sometimes it is useful to draw objects on separate pictures and add one
3563picture to another using the @code{add} function:
3564@cindex @code{add}
3565@verbatim
3566void add(picture src, bool group=true,
3567         filltype filltype=NoFill, bool above=true);
3568void add(picture dest, picture src, bool group=true,
3569         filltype filltype=NoFill, bool above=true);
3570@end verbatim
3571@noindent
3572The first example adds @code{src} to @code{currentpicture}; the second
3573one adds @code{src} to @code{dest}.
3574The @code{group} option specifies whether or not the graphical user
3575interface @code{xasy} should treat all of the elements of @code{src}
3576as a single entity (@pxref{GUI}), @code{filltype} requests optional
3577background filling or clipping, and @code{above} specifies
3578whether to add @code{src} above or below existing objects.
3579
3580There are also routines to add a picture or frame @code{src} specified
3581in postscript coordinates to another picture @code{dest} (or
3582@code{currentpicture}) about the user coordinate
3583@code{position}:
3584@anchor{add about}
3585@cindex @code{add}
3586@cindex picture alignment
3587@verbatim
3588void add(picture src, pair position, bool group=true,
3589         filltype filltype=NoFill, bool above=true);
3590void add(picture dest, picture src, pair position,
3591         bool group=true, filltype filltype=NoFill, bool above=true);
3592void add(picture dest=currentpicture, frame src, pair position=0,
3593         bool group=true, filltype filltype=NoFill, bool above=true);
3594void add(picture dest=currentpicture, frame src, pair position,
3595         pair align, bool group=true, filltype filltype=NoFill,
3596         bool above=true);
3597@end verbatim
3598
3599The optional @code{align} argument in the last form specifies a
3600direction to use for aligning the frame, in a manner analogous to the
3601@code{align} argument of @code{label} (@pxref{label}). However, one key
3602difference is that when @code{align} is not specified, labels are
3603centered, whereas frames and pictures are aligned so that their origin is
3604at @code{position}. Illustrations of frame alignment can be found in
3605the examples @ref{errorbars} and @ref{image}. If you want to align three
3606or more subpictures, group them two at a time:
3607
3608@verbatiminclude subpictures.asy
3609@sp 1
3610@center @image{subpictures}
3611
3612Alternatively, one can use @code{attach} to automatically increase the
3613size of picture @code{dest} to accommodate adding a frame @code{src}
3614about the user coordinate @code{position}:
3615@cindex @code{attach}
3616@verbatim
3617void attach(picture dest=currentpicture, frame src,
3618                 pair position=0, bool group=true,
3619                 filltype filltype=NoFill, bool above=true);
3620void attach(picture dest=currentpicture, frame src,
3621                 pair position, pair align, bool group=true,
3622                 filltype filltype=NoFill, bool above=true);
3623@end verbatim
3624
3625@cindex @code{erase}
3626To erase the contents of a picture (but not the size specification), use
3627the function
3628@verbatim
3629void erase(picture pic=currentpicture);
3630@end verbatim
3631
3632@cindex @code{save}
3633To save a snapshot of @code{currentpicture}, @code{currentpen}, and
3634@code{currentprojection}, use the function @code{save()}.
3635
3636@cindex @code{restore}
3637To restore a snapshot of @code{currentpicture}, @code{currentpen}, and
3638@code{currentprojection}, use the function @code{restore()}.
3639
3640Many further examples of picture and frame operations are provided in
3641the base module @code{plain}.
3642
3643@cindex verbatim
3644@cindex @code{postscript}
3645It is possible to insert verbatim @code{PostScript} commands in a picture with
3646one of the routines
3647@verbatim
3648void postscript(picture pic=currentpicture, string s);
3649void postscript(picture pic=currentpicture, string s, pair min,
3650                pair max)
3651@end verbatim
3652Here @code{min} and @code{max} can be used to specify explicit bounds
3653associated with the resulting @code{PostScript} code.
3654
3655@anchor{tex}
3656@cindex @code{tex}
3657Verbatim @TeX{} commands can be inserted in the intermediate
3658@code{LaTeX} output file with one of the functions
3659@verbatim
3660void tex(picture pic=currentpicture, string s);
3661void tex(picture pic=currentpicture, string s, pair min, pair max)
3662@end verbatim
3663Here @code{min} and @code{max} can be used to specify explicit bounds
3664associated with the resulting @TeX{} code.
3665
3666To issue a global @TeX{} command (such as a @TeX{} macro definition) in the
3667@TeX{} preamble (valid for the remainder of the top-level module) use:
3668@cindex @code{texpreamble}
3669@verbatim
3670void texpreamble(string s);
3671@end verbatim
3672
3673The @TeX{} environment can be reset to its initial state, clearing all
3674macro definitions, with the function
3675@cindex @code{texreset}
3676@verbatim
3677void texreset();
3678@end verbatim
3679
3680@cindex @code{usepackage}
3681The routine
3682@verbatim
3683void usepackage(string s, string options="");
3684@end verbatim
3685provides a convenient abbreviation for
3686@verbatim
3687texpreamble("\usepackage["+options+"]{"+s+"}");
3688@end verbatim
3689@noindent
3690that can be used for importing @code{LaTeX} packages.
3691
3692@end table
3693
3694@node Files
3695@section Files
3696
3697@cindex @code{file}
3698@code{Asymptote} can read and write text files (including comma-separated
3699value) files and portable @acronym{XDR} (External Data Representation)
3700binary files.
3701
3702@cindex @code{input}
3703An input file must first be opened with
3704@verbatim
3705input(string name="", bool check=true, string comment="#", string mode="");
3706@end verbatim
3707reading is then done by assignment:
3708@cindex open
3709@cindex @code{input}
3710@cindex reading
3711@verbatim
3712file fin=input("test.txt");
3713real a=fin;
3714@end verbatim
3715
3716@cindex comment character
3717@cindex @code{error}
3718If the optional boolean argument @code{check} is @code{false}, no check will
3719be made that the file exists. If the file does not exist or is not
3720readable, the function @code{bool error(file)} will return @code{true}.
3721The first character of the string @code{comment} specifies a
3722comment character. If this character is encountered in a data file,
3723the remainder of the line is ignored. When reading strings, a comment
3724character followed immediately by another comment character is treated
3725as a single literal comment character.
3726
3727@anchor{cd}
3728@cindex @code{cd}
3729@cindex directory
3730One can change the current working directory for read operations to
3731the contents of the string @code{s} with the function @code{string
3732cd(string s)}, which returns the new working directory. If
3733@code{string s} is empty, the path is reset to the value it had at
3734program startup.
3735
3736@cindex @code{getc}
3737When reading pairs, the enclosing parenthesis are optional.
3738Strings are also read by assignment, by reading characters up to but not
3739including a newline. In addition, @code{Asymptote} provides the function
3740@code{string getc(file)} to read the next character (treating the
3741comment character as an ordinary character) and return it as a string.
3742
3743@cindex @code{output}
3744@cindex @code{update}
3745@cindex append
3746A file named @code{name} can be open for output with
3747@verbatim
3748file output(string name="", bool update=false, string comment="#", string mode="");
3749@end verbatim
3750@noindent
3751If @code{update=false}, any existing data in the file will be erased
3752and only write operations can be used on the file.
3753If @code{update=true}, any existing data will be preserved, the position
3754will be set to the end-of-file, and both reading and writing operations
3755will be enabled. For security reasons, writing to files in directories
3756other than the current directory is allowed only if the @code{-globalwrite}
3757(or @code{-nosafe}) command-line option is specified.
3758@cindex @code{mktemp}
3759The function @code{string mktemp(string s)} may be used to create and
3760return the name of a unique temporary file in the current directory
3761based on the string @code{s}.
3762
3763@cindex @code{stdin}
3764@cindex @code{stdout}
3765There are two special files: @code{stdin}, which reads from the keyboard,
3766and @code{stdout}, which writes to the terminal. The implicit
3767initializer for files is @code{null}.
3768
3769Data of a built-in type @code{T} can be written to an output file by
3770calling one of the functions
3771@cindex @code{write}
3772@verbatim
3773write(string s="", T x, suffix suffix=endl ... T[]);
3774write(file file, string s="", T x, suffix suffix=none ... T[]);
3775write(file file=stdout, string s="", explicit T[] x ... T[][]);
3776write(file file=stdout, T[][]);
3777write(file file=stdout, T[][][]);
3778write(suffix suffix=endl);
3779write(file file, suffix suffix=none);
3780@end verbatim
3781@cindex @code{none}
3782@cindex @code{flush}
3783@cindex @code{endl}
3784@cindex @code{newl}
3785@cindex @code{DOSendl}
3786@cindex @code{DOSnewl}
3787@cindex @code{tab}
3788@cindex @code{comma}
3789If @code{file} is not specified, @code{stdout} is used and
3790terminated by default with a newline. If specified, the optional
3791identifying string @code{s} is written before the data @code{x}.
3792An arbitrary number of data values may be listed when writing scalars
3793or one-dimensional arrays. The @code{suffix} may be one of the following:
3794@code{none} (do nothing), @code{flush} (output buffered data),
3795@code{endl} (terminate with a newline and flush),
3796@code{newl} (terminate with a newline),
3797@code{DOSendl} (terminate with a DOS newline and flush),
3798@code{DOSnewl} (terminate with a DOS newline),
3799@code{tab} (terminate with a tab), or @code{comma} (terminate with a
3800comma). Here are some simple examples of data output:
3801@verbatim
3802file fout=output("test.txt");
3803write(fout,1);                  // Writes "1"
3804write(fout);                    // Writes a new line
3805write(fout,"List: ",1,2,3);     // Writes "List: 1     2     3"
3806@end verbatim
3807@noindent
3808
3809@cindex binary format
3810@cindex single precision
3811@cindex double precision
3812@cindex @code{singlereal}
3813@cindex @code{singleint}
3814@cindex @code{signedint}
3815@cindex @code{mode}
3816@cindex @code{binary}
3817@cindex @code{xdr}
3818A file may be opened with @code{mode="xdr"}, to read or write
3819double precision (64-bit) reals and single precision (32-bit)
3820integers in Sun Microsystem's @acronym{XDR} (External
3821Data Representation) portable binary format (available on all
3822@code{UNIX} platforms).
3823Alternatively, a file may also be opened with @code{mode="binary"}
3824to read or write double precision reals and single
3825precision integers in the native (nonportable) machine binary format.
3826The virtual member functions
3827@code{file singlereal(bool b=true)} and @code{file singleint(bool b=true)}
3828be used to change the precision of real and integer I/O
3829operations, respectively, for an @acronym{XDR} or binary file @code{f}.
3830Similarly, the function @code{file signedint(bool b=true)}
3831can be used to modify the signedness of integer reads and writes for
3832an @acronym{XDR} or binary file @code{f}.
3833
3834@cindex @code{name}
3835@cindex @code{mode}
3836@cindex @code{singlereal}
3837@cindex @code{singleint}
3838@cindex @code{signedint}
3839The virtual members @code{name}, @code{mode}, @code{singlereal},
3840@code{singleint}, and @code{signedint} may be used to query the
3841respective parameters for a given file.
3842
3843@cindex @code{eof}
3844@cindex @code{eol}
3845@cindex @code{error}
3846@cindex @code{flush}
3847@cindex @code{clear}
3848@cindex @code{precision}
3849@cindex @code{seek}
3850@cindex @code{tell}
3851@cindex rewind
3852@cindex @code{seekeof}
3853One can test a file for end-of-file with the boolean function @code{eof(file)},
3854end-of-line with @code{eol(file)}, and for I/O errors with @code{error(file)}.
3855One can flush the output buffers with @code{flush(file)}, clear a
3856previous I/O error with @code{clear(file)}, and close the file with
3857@code{close(file)}. The function
3858@code{int precision(file file=stdout, int digits=0)}
3859sets the number of digits of output precision for @code{file} to @code{digits},
3860provided @code{digits} is nonzero, and returns the previous
3861precision setting. The function @code{int tell(file)} returns
3862the current position in a file relative to the beginning.
3863The routine @code{seek(file file, int pos)} can be used to
3864change this position, where a negative value for the position @code{pos}
3865is interpreted as relative to the end-of-file. For example, one can
3866rewind a file @code{file} with the command @code{seek(file,0)}
3867and position to the final character in the file with @code{seek(file,-1)}.
3868The command @code{seekeof(file)} sets the position to the end of the file.
3869
3870@cindex @code{scroll}
3871@anchor{scroll}
3872Assigning @code{settings.scroll=n} for a positive integer @code{n}
3873requests a pause after every @code{n} output lines to @code{stdout}.
3874One may then press @code{Enter} to continue to the next @code{n} output lines,
3875@code{s} followed by @code{Enter} to scroll without further interruption,
3876or @code{q} followed by @code{Enter} to quit the current output
3877operation. If @code{n} is negative, the output scrolls a page at a time
3878(i.e. by one less than the current number of display lines). The default
3879value, @code{settings.scroll=0}, specifies continuous scrolling.
3880
3881The routines
3882@cindex @code{getstring}
3883@cindex @code{getreal}
3884@cindex @code{getpair}
3885@cindex @code{gettriple}
3886@verbatim
3887string getstring(string name="", string default="", string prompt="",
3888                 bool store=true);
3889int getint(string name="", int default=0, string prompt="",
3890           bool store=true);
3891real getreal(string name="", real default=0, string prompt="",
3892             bool store=true);
3893pair getpair(string name="", pair default=0, string prompt="",
3894             bool store=true);
3895triple gettriple(string name="", triple default=(0,0,0), string prompt="",
3896                 bool store=true);
3897@end verbatim
3898@noindent
3899defined in the module @code{plain} may be used to prompt for a value from
3900@code{stdin} using the @acronym{GNU} @code{readline} library.
3901If @code{store=true}, the history of values for @code{name} is
3902stored in the file @code{".asy_history_"+name} (@pxref{history}). The most
3903recent value in the history will be used to provide a default value
3904for subsequent runs.  The default value (initially @code{default}) is
3905displayed after @code{prompt}. These functions are based on the internal
3906routines
3907@cindex @code{readline}
3908@cindex @code{saveline}
3909@verbatim
3910string readline(string prompt="", string name="", bool tabcompletion=false);
3911void saveline(string name, string value, bool store=true);
3912@end verbatim
3913Here, @code{readline} prompts the user with the default value
3914formatted according to @code{prompt}, while @code{saveline}
3915is used to save the string @code{value} in a local history named
3916@code{name}, optionally storing the local history in a file
3917@code{".asy_history_"+name}.
3918
3919@cindex @code{history}
3920The routine @code{history(string name, int n=1)} can be used to look up
3921the @code{n} most recent values (or all values up to @code{historylines}
3922if @code{n=0}) entered for string @code{name}.
3923The routine @code{history(int n=0)} returns the interactive history.
3924For example,
3925@verbatim
3926write(output("transcript.asy"),history());
3927@end verbatim
3928@noindent
3929outputs the interactive history to the file @code{transcript.asy}.
3930
3931@cindex @code{delete}
3932The function @code{int delete(string s)} deletes the file named by the
3933string @code{s}. Unless the @code{-globalwrite} (or @code{-nosafe})
3934option is enabled, the file must reside in the current directory.
3935@cindex @code{rename}
3936The function @code{int rename(string from, string to)} may be used to
3937rename file @code{from} to file @code{to}.
3938Unless the @code{-globalwrite} (or @code{-nosafe}) option is enabled,
3939this operation is restricted to the current directory.
3940@cindex @code{convert}
3941@cindex @code{animate}
3942The functions
3943@verbatim
3944int convert(string args="", string file="", string format="");
3945int animate(string args="", string file="", string format="");
3946@end verbatim
3947@noindent
3948call the @code{ImageMagick} commands @code{convert} and @code{animate},
3949respectively, with the arguments @code{args} and the file name constructed
3950from the strings @code{file} and @code{format}.
3951
3952@node Variable initializers
3953@section Variable initializers
3954@cindex variable initializers
3955@cindex @code{operator init}
3956@cindex initializers
3957
3958A variable can be assigned a value when it is declared, as in
3959@code{int x=3;} where the variable @code{x} is assigned the value @code{3}.
3960As well as literal constants such as @code{3}, arbitary expressions can be used
3961as initializers, as in @code{real x=2*sin(pi/2);}.
3962
3963A variable is not added to the namespace until after the initializer is
3964evaluated, so for example, in
3965@verbatim
3966int x=2;
3967int x=5*x;
3968@end verbatim
3969@noindent
3970the @code{x} in the initializer on the second line refers to the variable
3971@code{x} declared on the first line.  The second line, then, declares a variable
3972@code{x} shadowing the original @code{x} and initializes it to the value
3973@code{10}.
3974
3975Variables of most types can be declared without an explicit initializer and they
3976will be initialized by the default initializer of that type:
3977
3978@itemize
3979@item Variables of the numeric types @code{int}, @code{real}, and @code{pair}
3980are all initialized to zero; variables of type @code{triple} are
3981initialized to @code{O=(0,0,0)}.
3982@item @code{boolean} variables are initialized to @code{false}.
3983@item @code{string} variables are initialized to the empty string.
3984@item @code{transform} variables are initialized to the identity transformation.
3985@item @code{path} and @code{guide} variables are initialized to
3986@code{nullpath}.
3987@item @code{pen} variables are initialized to the default pen.
3988@item @code{frame} and @code{picture} variables are initialized to empty
3989frames and pictures, respectively.
3990@item @code{file} variables are initialized to @code{null}.
3991@end itemize
3992
3993The default initializers for user-defined array, structure, and function types
3994are explained in their respective sections.  Some types, such as
3995@code{code}, do not have default initializers.  When a variable of such
3996a type is introduced, the user must initialize it by explicitly giving
3997it a value.
3998
3999The default initializer for any type @code{T} can be redeclared by defining the
4000function @code{T operator init()}.  For instance, @code{int} variables are
4001usually initialized to zero, but in
4002@verbatim
4003int operator init() {
4004  return 3;
4005}
4006int y;
4007@end verbatim
4008
4009@noindent
4010the variable @code{y} is initialized to @code{3}.  This example was given for
4011illustrative purposes; redeclaring the initializers of built-in types is not
4012recommended. Typically, @code{operator init} is used to define sensible
4013defaults for user-defined types.
4014
4015@cindex @code{var}
4016The special type @code{var} may be used to infer the type of a variable from
4017its initializer.  If the initializer is an expression of a unique type, then
4018the variable will be defined with that type.  For instance,
4019@verbatim
4020var x=5;
4021var y=4.3;
4022var reddash=red+dashed;
4023@end verbatim
4024@noindent
4025is equivalent to
4026@verbatim
4027int x=5;
4028real y=4.3;
4029pen reddash=red+dashed;
4030@end verbatim
4031
4032@code{var} may also be used with the extended @code{for} loop syntax.
4033
4034@verbatim
4035int[] a = {1,2,3};
4036for (var x : a)
4037  write(x);
4038@end verbatim
4039
4040@node Structures
4041@section Structures
4042@cindex @code{struct}
4043@cindex structures
4044@cindex @code{public}
4045@cindex @code{restricted}
4046@cindex @code{private}
4047@cindex @code{this}
4048@cindex @code{new}
4049@cindex @code{null}
4050
4051Users may also define their own data types as structures, along with
4052user-defined operators, much as in C++. By default, structure members
4053are @code{public} (may be read and modified anywhere in the code), but may be
4054optionally declared @code{restricted} (readable anywhere but writeable
4055only inside the structure where they are defined) or @code{private}
4056(readable and writable only inside the structure). In a structure definition,
4057the keyword @code{this} can be used as an expression to refer to the enclosing
4058structure. Any code at the
4059top-level scope within the structure is executed on initialization.
4060
4061Variables hold references to structures.  That is, in the example:
4062@verbatim
4063struct T {
4064  int x;
4065}
4066
4067T foo;
4068T bar=foo;
4069bar.x=5;
4070@end verbatim
4071
4072The variable @code{foo} holds a reference to an instance of the structure
4073@code{T}.  When @code{bar} is assigned the value of @code{foo}, it too
4074now holds a reference to the same instance as @code{foo} does.  The assignment
4075@code{bar.x=5} changes the value of the field @code{x} in that instance, so
4076that @code{foo.x} will also be equal to @code{5}.
4077
4078The expression @code{new T} creates a new instance of the structure @code{T} and
4079returns a reference to that instance.  In creating the new instance, any code in
4080the body of the record definition is executed.  For example:
4081@verbatim
4082int Tcount=0;
4083struct T {
4084  int x;
4085  ++Tcount;
4086}
4087
4088T foo=new T;
4089T foo;
4090@end verbatim
4091@noindent
4092Here, @code{new T} produces a new instance of the class, which
4093causes @code{Tcount} to be incremented, tracking the
4094number of instances produced. The declarations @code{T foo=new T} and
4095@code{T foo} are equivalent: the second form implicitly creates a new
4096instance of @code{T}.
4097That is, after the definition of a structure @code{T}, a variable of
4098type @code{T} is initialized to a new instance (@code{new T}) by
4099default.  During the definition of the structure, however, variables
4100of type @code{T} are initialized to @code{null} by default. This
4101special behaviour is to avoid infinite recursion of creating new
4102instances in code such as
4103@verbatim
4104struct tree {
4105  int value;
4106  tree left;
4107  tree right;
4108}
4109@end verbatim
4110
4111The expression @code{null} can be cast to any structure type to yield a null
4112reference, a reference that does not actually refer to any instance of the
4113structure.  Trying to use a field of a null reference will cause an error.
4114
4115@cindex alias
4116@cindex @code{==}
4117@cindex @code{!=}
4118The function @code{bool alias(T,T)} checks to see if two structure references
4119refer to the same instance of the structure (or both to @code{null}).
4120In example at the beginning of this section, @code{alias(foo,bar)}
4121would return true, but @code{alias(foo,new T)} would return false, as @code{new
4122T} creates a new instance of the structure @code{T}.  The boolean operators
4123@code{==} and @code{!=} are by default equivalent to @code{alias} and
4124@code{!alias} respectively, but may be overwritten for a particular type
4125(for example, to do a deep comparison).
4126
4127Here is a simple example that illustrates the use of structures:
4128@verbatim
4129struct S {
4130  real a=1;
4131  real f(real a) {return a+this.a;}
4132}
4133
4134S s;                            // Initializes s with new S;
4135
4136write(s.f(2));                  // Outputs 3
4137
4138S operator + (S s1, S s2)
4139{
4140  S result;
4141  result.a=s1.a+s2.a;
4142  return result;
4143}
4144
4145write((s+s).f(0));              // Outputs 2
4146
4147@end verbatim
4148
4149@cindex constructors
4150It is often convenient to have functions that construct new instances of a
4151structure.  Say we have a @code{Person} structure:
4152@verbatim
4153struct Person {
4154  string firstname;
4155  string lastname;
4156}
4157
4158Person joe;
4159joe.firstname="Joe";
4160joe.lastname="Jones";
4161@end verbatim
4162@noindent
4163Creating a new Person is a chore; it takes three lines to create a new instance
4164and to initialize its fields (that's still considerably less effort than
4165creating a new person in real life, though).
4166
4167We can reduce the work by defining a constructor function
4168@code{Person(string,string)}:
4169@verbatim
4170struct Person {
4171  string firstname;
4172  string lastname;
4173
4174  static Person Person(string firstname, string lastname) {
4175    Person p;
4176    p.firstname=firstname;
4177    p.lastname=lastname;
4178    return p;
4179  }
4180}
4181
4182Person joe=Person.Person("Joe", "Jones");
4183@end verbatim
4184
4185While it is now easier than before to create a new instance, we still
4186have to refer to the constructor by the qualified name
4187@code{Person.Person}.  If we add the line
4188@verbatim
4189from Person unravel Person;
4190@end verbatim
4191@noindent
4192immediately after the structure definition, then the constructor can be used
4193without qualification: @code{Person joe=Person("Joe", "Jones");}.
4194
4195The constructor is now easy to use, but it is quite a hassle to define.  If you
4196write a lot of constructors, you will find that you are repeating a lot of code
4197in each of them.  Fortunately, your friendly neighbourhood Asymptote
4198developers have devised a way to automate much of the process.
4199
4200@cindex @code{operator init}
4201If, in the body of a structure, Asymptote encounters the definition of
4202a function of the form @code{void operator init(@var{args})},  it implicitly
4203defines a constructor function of the arguments @code{@var{args}} that
4204uses the @code{void operator init} function to initialize a
4205new instance of the structure.
4206That is, it essentially defines the following constructor (assuming the
4207structure is called @code{Foo}):
4208
4209@example
4210static Foo Foo(@var{args}) @{
4211  Foo instance;
4212  instance.operator init(@var{args});
4213  return instance;
4214@}
4215@end example
4216
4217This constructor is also implicitly copied to the enclosing scope after the end
4218of the structure definition, so that it can used subsequently without qualifying
4219it by the structure name.  Our @code{Person} example can thus be implemented as:
4220@verbatim
4221struct Person {
4222  string firstname;
4223  string lastname;
4224
4225  void operator init(string firstname, string lastname) {
4226    this.firstname=firstname;
4227    this.lastname=lastname;
4228  }
4229}
4230
4231Person joe=Person("Joe", "Jones");
4232@end verbatim
4233
4234The use of @code{operator init} to implicitly define constructors should not be
4235confused with its use to define default values for variables
4236(@pxref{Variable initializers}).  Indeed, in the
4237first case, the return type of the @code{operator init} must be @code{void}
4238while in the second, it must be the (non-@code{void}) type of the variable.
4239
4240@cindex @code{cputime}
4241The function @code{cputime()}
4242returns a structure @code{cputime} with cumulative @acronym{CPU} times
4243broken down into the fields @code{parent.user}, @code{parent.system},
4244@code{child.user}, and @code{child.system}. For convenience, the
4245incremental fields @code{change.user} and @code{change.system} indicate
4246the change in the corresponding total parent and child @acronym{CPU}
4247times since the last call to @code{cputime()}. The function
4248@verbatim
4249void write(file file=stdout, string s="", cputime c,
4250           string format=cputimeformat, suffix suffix=none);
4251@end verbatim
4252@noindent
4253displays the incremental user cputime followed by ``u'',
4254the incremental system cputime followed by ``s'',
4255the total user cputime followed by ``U'', and
4256the total system cputime followed by ``S''.
4257
4258@cindex inheritance
4259@cindex virtual functions
4260Much like in C++, casting (@pxref{Casts}) provides for an elegant
4261implementation of structure inheritance, including virtual functions:
4262@verbatim
4263struct parent {
4264  real x;
4265  void operator init(int x) {this.x=x;}
4266  void virtual(int) {write(0);}
4267  void f() {virtual(1);}
4268}
4269
4270void write(parent p) {write(p.x);}
4271
4272struct child {
4273  parent parent;
4274  real y=3;
4275  void operator init(int x) {parent.operator init(x);}
4276  void virtual(int x) {write(x);}
4277  parent.virtual=virtual;
4278  void f()=parent.f;
4279}
4280
4281parent operator cast(child child) {return child.parent;}
4282
4283parent p=parent(1);
4284child c=child(2);
4285
4286write(c);                       // Outputs 2;
4287
4288p.f();                          // Outputs 0;
4289c.f();                          // Outputs 1;
4290
4291write(c.parent.x);              // Outputs 2;
4292write(c.y);                     // Outputs 3;
4293@end verbatim
4294
4295For further examples of structures, see @code{Legend} and @code{picture} in
4296the @code{Asymptote} base module @code{plain}.
4297
4298@node Operators
4299@section Operators
4300@cindex operators
4301
4302@menu
4303* Arithmetic & logical::        Basic mathematical operators
4304* Self & prefix operators::     Increment and decrement
4305* User-defined operators::      Overloading operators
4306@end menu
4307
4308@node Arithmetic & logical
4309@subsection Arithmetic & logical operators
4310@cindex arithmetic operators
4311@cindex binary operators
4312@cindex boolean operators
4313@cindex logical operators
4314@cindex integer division
4315@cindex @code{quotient}
4316
4317@code{Asymptote} uses the standard binary arithmetic operators.
4318However, when one integer is divided by another, both arguments are
4319converted to real values before dividing and a real quotient is
4320returned (since this is usually what is intended). The function
4321@code{int quotient(int x, int y)} returns the greatest integer less
4322than or equal to @code{x/y}. In all other cases both operands are
4323promoted to the same type, which will also be the type of the result:
4324@table @code
4325@cindex @code{+}
4326@item +
4327addition
4328@cindex @code{-}
4329@item -
4330subtraction
4331@cindex @code{*}
4332@item *
4333multiplication
4334@cindex @code{/}
4335@item /
4336division
4337@cindex @code{%}
4338@item %
4339modulo; the result always has the same sign as the divisor.
4340In particular, this makes @code{q*quotient(p,q)+p%q == p} for all
4341integers @code{p} and nonzero integers @code{q}.
4342@cindex @code{^}
4343@item ^
4344@cindex @code{**}
4345power; if the exponent (second argument) is an int, recursive
4346multiplication is used; otherwise, logarithms and exponentials are used
4347(@code{**} is a synonym for @code{^}).
4348
4349@end table
4350
4351The usual boolean operators are also defined:
4352@table @code
4353@cindex @code{==}
4354@item ==
4355equals
4356@cindex @code{!=}
4357@item !=
4358not equals
4359@cindex @code{<}
4360@item <
4361less than
4362@cindex @code{<=}
4363@item <=
4364less than or equals
4365@cindex @code{>=}
4366@item >=
4367greater than or equals
4368@cindex @code{>}
4369@item >
4370greater than
4371@cindex @code{&&}
4372@item &&
4373and (with conditional evaluation of right-hand argument)
4374@cindex @code{&}
4375@item &
4376and
4377@cindex @code{||}
4378@item ||
4379or (with conditional evaluation of right-hand argument)
4380@cindex @code{|}
4381@item |
4382or
4383@cindex @code{^}
4384@item ^
4385xor
4386@cindex @code{!}
4387@item !
4388not
4389@end table
4390
4391@code{Asymptote} also supports the C-like conditional syntax:
4392@cindex @code{:}
4393@cindex @code{?}
4394@cindex conditional
4395@verbatim
4396bool positive=(pi > 0) ? true : false;
4397@end verbatim
4398
4399@cindex @code{interp}
4400The function @code{T interp(T a, T b, real t)} returns @code{(1-t)*a+t*b}
4401for nonintegral built-in arithmetic types @code{T}. If @code{a} and
4402@code{b} are pens, they are first promoted to the same color space.
4403
4404@cindex @code{AND}
4405@cindex @code{OR}
4406@cindex @code{XOR}
4407@cindex @code{NOT}
4408@cindex @code{CLZ}
4409@cindex @code{CTZ}
4410@code{Asymptote} also defines bitwise functions @code{int AND(int,int)},
4411@code{int OR(int,int)}, @code{int XOR(int,int)}, @code{int NOT(int)},
4412@code{int CLZ(int)} (count leading zeros), and @code{int CTZ(int)}
4413(count trailing zeros).
4414
4415@node Self & prefix operators
4416@subsection Self & prefix operators
4417@cindex self operators
4418@cindex prefix operators
4419@cindex @code{+=}
4420@cindex @code{-=}
4421@cindex @code{*=}
4422@cindex @code{/=}
4423@cindex @code{%=}
4424@cindex @code{^=}
4425@cindex @code{++}
4426@cindex @code{--}
4427
4428As in C, each of the arithmetic operators @code{+}, @code{-}, @code{*},
4429@code{/}, @code{%}, and @code{^} can be used as a self operator.
4430The prefix operators @code{++} (increment by one) and @code{--} (decrement
4431by one) are also defined.
4432For example,
4433@verbatim
4434int i=1;
4435i += 2;
4436int j=++i;
4437@end verbatim
4438
4439@noindent
4440is equivalent to the code
4441@verbatim
4442int i=1;
4443i=i+2;
4444int j=i=i+1;
4445@end verbatim
4446
4447@cindex postfix operators
4448However, postfix operators like @code{i++} and @code{i--} are not defined
4449(because of the inherent ambiguities that would arise with the @code{--}
4450path-joining operator). In the rare instances where @code{i++}
4451and @code{i--} are really needed, one can substitute the expressions
4452@code{(++i-1)} and @code{(--i+1)}, respectively.
4453
4454@node User-defined operators
4455@subsection User-defined operators
4456@cindex user-defined operators
4457@cindex @code{operator}
4458The following symbols may be used with @code{operator} to define or redefine
4459operators on structures and built-in types:
4460@verbatim
4461- + * / % ^ ! < > == != <= >= & | ^^ .. :: -- --- ++
4462<< >> $ $$ @ @@
4463@end verbatim
4464@noindent
4465The operators on the second line have precedence one higher than the
4466boolean operators @code{<}, @code{>}, @code{<=}, and @code{>=}.
4467
4468Guide operators like @code{..} may be overloaded, say, to write
4469a user function that produces a new guide from a given guide:
4470@verbatim
4471guide dots(... guide[] g)=operator ..;
4472
4473guide operator ..(... guide[] g) {
4474  guide G;
4475  if(g.length > 0) {
4476    write(g[0]);
4477    G=g[0];
4478  }
4479  for(int i=1; i < g.length; ++i) {
4480    write(g[i]);
4481    write();
4482    G=dots(G,g[i]);
4483  }
4484  return G;
4485}
4486
4487guide g=(0,0){up}..{SW}(100,100){NE}..{curl 3}(50,50)..(10,10);
4488write("g=",g);
4489@end verbatim
4490
4491@node Implicit scaling
4492@section Implicit scaling
4493@cindex implicit scaling
4494
4495If a numeric literal is in front of certain types of expressions, then the two
4496are multiplied:
4497@verbatim
4498int x=2;
4499real y=2.0;
4500real cm=72/2.540005;
4501
4502write(3x);
4503write(2.5x);
4504write(3y);
4505write(-1.602e-19 y);
4506write(0.5(x,y));
4507write(2x^2);
4508write(3x+2y);
4509write(3(x+2y));
4510write(3sin(x));
4511write(3(sin(x))^2);
4512write(10cm);
4513@end verbatim
4514
4515This produces the output
4516@verbatim
45176
45185
45196
4520-3.204e-19
4521(1,1)
45228
452310
452418
45252.72789228047704
45262.48046543129542
4527283.464008929116
4528@end verbatim
4529
4530@node Functions
4531@section Functions
4532@cindex functions
4533
4534@code{Asymptote} functions are treated as variables with a signature
4535(non-function variables have null signatures). Variables with the
4536same name are allowed, so long as they have distinct signatures.
4537
4538Functions arguments are passed by value. To pass an argument by
4539reference, simply enclose it in a structure (@pxref{Structures}).
4540
4541Here are some significant features of @code{Asymptote} functions:
4542
4543@enumerate
4544@item Variables with signatures (functions) and without signatures
4545(nonfunction variables) are distinct:
4546@verbatim
4547int x, x();
4548x=5;
4549x=new int() {return 17;};
4550x=x();              // calls x() and puts the result, 17, in the scalar x
4551@end verbatim
4552
4553@item Traditional function definitions are allowed:
4554@verbatim
4555int sqr(int x)
4556{
4557  return x*x;
4558}
4559sqr=null;           // but the function is still just a variable.
4560@end verbatim
4561
4562@item Casting can be used to resolve ambiguities:
4563@verbatim
4564int a, a(), b, b(); // Valid: creates four variables.
4565a=b;                // Invalid: assignment is ambiguous.
4566a=(int) b;          // Valid: resolves ambiguity.
4567(int) (a=b);        // Valid: resolves ambiguity.
4568(int) a=b;          // Invalid: cast expressions cannot be L-values.
4569
4570int c();
4571c=a;                // Valid: only one possible assignment.
4572@end verbatim
4573
4574@item Anonymous (so-called "high-order") functions are also allowed:
4575@cindex @code{typedef}
4576@verbatim
4577typedef int intop(int);
4578intop adder(int m)
4579{
4580  return new int(int n) {return m+n;};
4581}
4582intop addby7=adder(7);
4583write(addby7(1));   // Writes 8.
4584@end verbatim
4585
4586@item
4587@cindex overloading functions
4588One may redefine a function @code{f}, even for calls to @code{f} in previously
4589declared functions, by assigning another (anonymous or named)
4590function to it. However, if @code{f} is overloaded by a
4591new function definition, previous calls will still access the original
4592version of @code{f}, as illustrated in this example:
4593@verbatim
4594void f() {
4595  write("hi");
4596}
4597
4598void g() {
4599  f();
4600}
4601
4602g(); // writes "hi"
4603
4604f=new void() {write("bye");};
4605
4606g(); // writes "bye"
4607
4608void f() {write("overloaded");};
4609
4610f(); // writes "overloaded"
4611g(); // writes "bye"
4612@end verbatim
4613
4614@cindex function declarations
4615@item Anonymous functions can be used to redefine a function variable
4616that has been declared (and implicitly initialized to the null function)
4617but not yet explicitly defined:
4618@verbatim
4619void f(bool b);
4620
4621void g(bool b) {
4622  if(b) f(b);
4623  else write(b);
4624}
4625
4626f=new void(bool b) {
4627  write(b);
4628  g(false);
4629};
4630
4631g(true); // Writes true, then writes false.
4632@end verbatim
4633
4634@end enumerate
4635
4636@code{Asymptote} is the only language we know of that treats functions
4637as variables, but allows overloading by distinguishing variables
4638based on their signatures.
4639
4640@cindex @code{libsigsegv}
4641@cindex stack overflow
4642@anchor{stack overflow}
4643@cindex recursion
4644@cindex stack overflow
4645Functions are allowed to call themselves recursively. As in C++, infinite
4646nested recursion will generate a stack overflow (reported as a
4647segmentation fault, unless a fully working version of the @acronym{GNU}
4648library @code{libsigsegv} (e.g.@ 2.4 or later) is installed at
4649configuration time).
4650
4651@menu
4652* Default arguments::           Default values can appear anywhere
4653* Named arguments::             Assigning function arguments by keyword
4654* Rest arguments::              Functions with a variable number of arguments
4655* Mathematical functions::      Standard libm functions
4656
4657@end menu
4658
4659@node Default arguments
4660@subsection Default arguments
4661@cindex default arguments
4662@cindex arguments
4663
4664@code{Asymptote} supports a more flexible mechanism for default function
4665arguments than C++: they may appear anywhere in the function prototype.
4666Because certain data types are implicitly cast to more sophisticated
4667types (@pxref{Casts}) one can often avoid ambiguities by ordering
4668function arguments from the simplest to the most complicated.
4669For example, given
4670@verbatim
4671real f(int a=1, real b=0) {return a+b;}
4672@end verbatim
4673@noindent
4674then @code{f(1)} returns 1.0, but @code{f(1.0)} returns 2.0.
4675
4676The value of a default argument is determined by evaluating the
4677given @code{Asymptote} expression in the scope where the called
4678function is defined.
4679
4680@node Named arguments
4681@subsection Named arguments
4682@cindex keywords
4683@cindex named arguments
4684
4685It is sometimes difficult to remember the order in which arguments
4686appear in a function declaration. Named (keyword) arguments make calling
4687functions with multiple arguments easier. Unlike in the C and C++
4688languages, an assignment in a function argument is interpreted as an
4689assignment to a parameter of the same name in the function signature,
4690@emph{not within the local scope}. The command-line option @code{-d}
4691may be used to check @code{Asymptote} code for cases where a
4692named argument may be mistaken for a local assignment.
4693
4694When matching arguments to signatures, first all of the keywords are
4695matched, then the arguments without names are matched against the
4696unmatched formals as usual. For example,
4697@verbatim
4698int f(int x, int y) {
4699  return 10x+y;
4700}
4701write(f(4,x=3));
4702@end verbatim
4703@noindent
4704outputs 34, as @code{x} is already matched when we try to match the
4705unnamed argument @code{4}, so it gets matched to the next item, @code{y}.
4706
4707For the rare occasions where it is desirable to assign a value to
4708local variable within a function argument (generally @emph{not} a good
4709programming practice), simply enclose the assignment in
4710parentheses. For example, given the definition of @code{f} in the
4711previous example,
4712@verbatim
4713int x;
4714write(f(4,(x=3)));
4715@end verbatim
4716@noindent
4717is equivalent to the statements
4718@verbatim
4719int x;
4720x=3;
4721write(f(4,3));
4722@end verbatim
4723@noindent
4724and outputs 43.
4725
4726@cindex @code{keyword}
4727@cindex keyword-only
4728Parameters can be specified as ``keyword-only'' by putting @code{keyword}
4729immediately before the parameter name, as in @code{int f(int keyword x)} or
4730@code{int f(int keyword x=77)}.  This forces the caller of the function to use
4731a named argument to give a value for this parameter.  That is, @code{f(x=42)}
4732is legal, but @code{f(25)} is not.  Keyword-only parameters must be listed
4733after normal parameters in a function definition.
4734
4735
4736As a technical detail, we point out that, since variables of the same
4737name but different signatures are allowed in the same scope, the code
4738@verbatim
4739int f(int x, int x()) {
4740  return x+x();
4741}
4742int seven() {return 7;}
4743@end verbatim
4744@noindent
4745is legal in @code{Asymptote}, with @code{f(2,seven)} returning 9.
4746A named argument matches the first unmatched formal of the same name, so
4747@code{f(x=2,x=seven)} is an equivalent call, but @code{f(x=seven,2)}
4748is not, as the first argument is matched to the first formal, and
4749@code{int ()} cannot be implicitly cast to @code{int}.  Default
4750arguments do not affect which formal a named argument is matched to,
4751so if @code{f} were defined as
4752@verbatim
4753int f(int x=3, int x()) {
4754  return x+x();
4755}
4756@end verbatim
4757@noindent
4758then @code{f(x=seven)} would be illegal, even though @code{f(seven)}
4759obviously would be allowed.
4760
4761@node Rest arguments
4762@subsection Rest arguments
4763@cindex rest arguments
4764
4765Rest arguments allow one to write functions that take a variable
4766number of arguments:
4767@verbatim
4768// This function sums its arguments.
4769int sum(... int[] nums) {
4770  int total=0;
4771  for(int i=0; i < nums.length; ++i)
4772    total += nums[i];
4773  return total;
4774}
4775
4776sum(1,2,3,4);                       // returns 10
4777sum();                              // returns 0
4778
4779// This function subtracts subsequent arguments from the first.
4780int subtract(int start ... int[] subs) {
4781  for(int i=0; i < subs.length; ++i)
4782    start -= subs[i];
4783  return start;
4784}
4785
4786subtract(10,1,2);                   // returns 7
4787subtract(10);                       // returns 10
4788subtract();                         // illegal
4789@end verbatim
4790
4791@cindex packing
4792Putting an argument into a rest array is called @emph{packing}.
4793One can give an explicit list of arguments for the rest
4794argument, so @code{subtract} could alternatively be implemented as
4795@verbatim
4796int subtract(int start ... int[] subs) {
4797  return start - sum(... subs);
4798}
4799@end verbatim
4800
4801One can even combine normal arguments with rest arguments:
4802@verbatim
4803sum(1,2,3 ... new int[] {4,5,6});   // returns 21
4804@end verbatim
4805@noindent
4806@cindex unpacking
4807This builds a new six-element array that is passed to @code{sum} as
4808@code{nums}. The opposite operation, @emph{unpacking}, is not allowed:
4809@verbatim
4810subtract(... new int[] {10, 1, 2});
4811@end verbatim
4812@noindent
4813is illegal, as the start formal is not matched.
4814
4815If no arguments are packed, then a zero-length array (as opposed to
4816@code{null}) is bound to the rest parameter. Note that default
4817arguments are ignored for rest formals and the rest argument is not
4818bound to a keyword.
4819
4820In some cases, keyword-only parameters are helpful to avoid arguments intended
4821for the rest parameter to be assigned to other parameters.  For example, here
4822the use of @code{keyword} is to avoid @code{pnorm(1.0,2.0,0.3)} matching
4823@code{1.0} to @code{p}.
4824@verbatim
4825real pnorm(real keyword p=2.0 ... real[] v)
4826{
4827  return sum(v^p)^(1/p);
4828}
4829@end verbatim
4830
4831The overloading resolution in @code{Asymptote} is similar to the
4832function matching rules used in C++. Every argument match is given a
4833score.  Exact matches score better than matches with casting, and
4834matches with formals (regardless of casting) score better than packing
4835an argument into the rest array.  A candidate is maximal if all of the
4836arguments score as well in it as with any other candidate.  If there
4837is one unique maximal candidate, it is chosen; otherwise, there is an
4838ambiguity error.
4839
4840@verbatim
4841int f(path g);
4842int f(guide g);
4843f((0,0)--(100,100)); // matches the second; the argument is a guide
4844
4845int g(int x, real y);
4846int g(real x, int x);
4847
4848g(3,4); // ambiguous; the first candidate is better for the first argument,
4849        // but the second candidate is better for the second argument
4850
4851int h(... int[] rest);
4852int h(real x ... int[] rest);
4853
4854h(1,2); // the second definition matches, even though there is a cast,
4855        // because casting is preferred over packing
4856
4857int i(int x ... int[] rest);
4858int i(real x, real y ... int[] rest);
4859
4860i(3,4); // ambiguous; the first candidate is better for the first argument,
4861        // but the second candidate is better for the second one
4862@end verbatim
4863
4864@node Mathematical functions
4865@subsection Mathematical functions
4866@cindex mathematical functions
4867@cindex functions
4868@cindex @code{libm} routines
4869
4870@cindex @code{sin}
4871@cindex @code{cos}
4872@cindex @code{tan}
4873@cindex @code{asin}
4874@cindex @code{acos}
4875@cindex @code{atan}
4876@cindex @code{exp}
4877@cindex @code{log}
4878@cindex @code{pow10}
4879@cindex @code{log10}
4880@cindex @code{sinh}
4881@cindex @code{cosh}
4882@cindex @code{tanh}
4883@cindex @code{asinh}
4884@cindex @code{acosh}
4885@cindex @code{atanh}
4886@cindex @code{sqrt}
4887@cindex @code{cbrt}
4888@cindex @code{fabs}
4889@cindex @code{expm1}
4890@cindex @code{log1p}
4891@cindex @code{identity}
4892@cindex @code{J}
4893@cindex @code{Y}
4894@cindex @code{gamma}
4895@cindex @code{erf}
4896@cindex @code{erfc}
4897@cindex @code{atan2}
4898@cindex @code{hypot}
4899@cindex @code{fmod}
4900@cindex @code{remainder}
4901@code{Asymptote} has built-in versions of the standard @code{libm} mathematical
4902real(real) functions @code{sin}, @code{cos}, @code{tan}, @code{asin},
4903@code{acos}, @code{atan}, @code{exp}, @code{log}, @code{pow10},
4904@code{log10}, @code{sinh}, @code{cosh}, @code{tanh}, @code{asinh},
4905@code{acosh}, @code{atanh}, @code{sqrt}, @code{cbrt}, @code{fabs}, @code{expm1},
4906@code{log1p}, as well as the identity function @code{identity}.
4907@code{Asymptote} also defines the order @code{n} Bessel functions of
4908the first kind @code{Jn(int n, real)} and second kind
4909@code{Yn(int n, real)}, as well as the gamma function @code{gamma},
4910the error function @code{erf}, and the complementary error function
4911@code{erfc}. The standard real(real, real) functions @code{atan2},
4912@code{hypot}, @code{fmod}, @code{remainder} are also included.
4913
4914@cindex @code{degrees}
4915@cindex @code{radians}
4916@cindex @code{Degrees}
4917The functions @code{degrees(real radians)} and @code{radians(real degrees)}
4918can be used to convert between radians and degrees. The function
4919@code{Degrees(real radians)} returns the angle in degrees in the
4920interval [0,360).
4921@cindex @code{Sin}
4922@cindex @code{Cos}
4923@cindex @code{Tan}
4924@cindex @code{aSin}
4925@cindex @code{aCos}
4926@cindex @code{aTan}
4927For convenience, @code{Asymptote} defines variants @code{Sin},
4928@code{Cos}, @code{Tan}, @code{aSin}, @code{aCos}, and @code{aTan} of
4929the standard trigonometric functions that use degrees rather than radians.
4930We also define complex versions of the @code{sqrt}, @code{sin}, @code{cos},
4931@code{exp}, @code{log}, and @code{gamma} functions.
4932
4933@cindex @code{floor}
4934@cindex @code{ceil}
4935@cindex @code{round}
4936@cindex @code{sgn}
4937The functions @code{floor}, @code{ceil}, and @code{round} differ from
4938their usual definitions in that they all return an int value rather than
4939a real (since that is normally what one wants).
4940The functions @code{Floor}, @code{Ceil}, and @code{Round} are
4941respectively similar, except that if the result cannot be converted
4942to a valid int, they return @code{intMax}
4943for positive arguments and @code{intMin} for negative arguments,
4944rather than generating an integer overflow.
4945We also define a function @code{sgn}, which returns the sign of its
4946real argument as an integer (-1, 0, or 1).
4947
4948@cindex @code{abs}
4949There is an @code{abs(int)} function, as well as an @code{abs(real)}
4950function (equivalent to @code{fabs(real)}), an @code{abs(pair)} function
4951(equivalent to @code{length(pair)}).
4952
4953@cindex @code{srand}
4954@cindex @code{rand}
4955@cindex @code{randMax}
4956@cindex @code{unitrand}
4957@cindex @code{Gaussrand}
4958@cindex @code{histogram}
4959@cindex @code{factorial}
4960@cindex @code{choose}
4961Random numbers can be seeded with @code{srand(int)} and generated with
4962the @code{int rand()} function, which returns a random integer between 0
4963and the integer @code{randMax}. The @code{unitrand()} function returns
4964a random number uniformly distributed in the interval [0,1].
4965A Gaussian random number generator
4966@code{Gaussrand} and a collection of statistics routines, including
4967@code{histogram}, are provided in the base file @code{stats.asy}.
4968The functions @code{factorial(int n)}, which returns @math{n!}, and
4969@code{choose(int n, int k)}, which returns @math{n!/(k!(n-k)!)}, are
4970also defined.
4971
4972@cindex @acronym{GNU} Scientific Library
4973@cindex @code{gsl}
4974@cindex Airy
4975@cindex Bessel
4976@cindex Legendre
4977@cindex elliptic functions
4978@cindex exponential integral
4979@cindex trigonometric integrals
4980@cindex Riemann zeta function
4981@cindex @code{Ai}
4982@cindex @code{Bi}
4983@cindex @code{Ai_deriv}
4984@cindex @code{Bi_deriv}
4985@cindex @code{zero_Ai}
4986@cindex @code{zero_Bi}
4987@cindex @code{zero_Ai_deriv}
4988@cindex @code{zero_Bi_deriv}
4989@cindex @code{J}
4990@cindex @code{Y}
4991@cindex @code{I}
4992@cindex @code{K}
4993@cindex @code{i_scaled}
4994@cindex @code{k_scaled}
4995@cindex @code{zero_J}
4996@cindex @code{F}
4997@cindex @code{E}
4998@cindex @code{P}
4999@cindex @code{sncndn}
5000@cindex @code{Ei}
5001@cindex @code{Si}
5002@cindex @code{Ci}
5003@cindex @code{Pl}
5004@cindex @code{zeta}
5005When configured with the @acronym{GNU} Scientific Library (GSL), available from
5006@url{http://www.gnu.org/software/gsl/},
5007@code{Asymptote} contains an internal module @code{gsl} that
5008defines the airy functions @code{Ai(real)},
5009@code{Bi(real)}, @code{Ai_deriv(real)}, @code{Bi_deriv(real)},
5010@code{zero_Ai(int)}, @code{zero_Bi(int)},
5011@code{zero_Ai_deriv(int)}, @code{zero_Bi_deriv(int)}, the Bessel functions
5012@code{I(int, real)}, @code{K(int, real)}, @code{j(int, real)},
5013@code{y(int, real)}, @code{i_scaled(int, real)}, @code{k_scaled(int, real)},
5014@code{J(real, real)}, @code{Y(real, real)}, @code{I(real, real)},
5015@code{K(real, real)}, @code{zero_J(real, int)}, the elliptic functions
5016@code{F(real, real)}, @code{E(real, real)}, and @code{P(real, real)},
5017the Jacobi elliptic functions @code{real[] sncndn(real,real)},
5018the exponential/trigonometric integrals @code{Ei}, @code{Si}, and @code{Ci},
5019the Legendre polynomials @code{Pl(int, real)}, and the Riemann zeta
5020function @code{zeta(real)}. For example, to compute the sine integral
5021@code{Si} of 1.0:
5022@verbatim
5023import gsl;
5024write(Si(1.0));
5025@end verbatim
5026
5027@code{Asymptote} also provides a few general purpose numerical routines:
5028
5029@table @code
5030
5031@cindex @code{newton}
5032@item @code{real newton(int iterations=100, real f(real), real fprime(real), real x, bool verbose=false);}
5033Use Newton-Raphson iteration to solve for a root of a real-valued
5034differentiable function @code{f}, given its derivative @code{fprime} and
5035an initial guess @code{x}. Diagnostics for
5036each iteration are printed if @code{verbose=true}.
5037If the iteration fails after the maximum allowed number of loops
5038(@code{iterations}), @code{realMax} is returned.
5039
5040@cindex @code{newton}
5041@item @code{real newton(int iterations=100, real f(real), real fprime(real), real x1, real x2, bool verbose=false);}
5042Use bracketed Newton-Raphson bisection to solve for a root of a real-valued
5043differentiable function @code{f} within an interval
5044[@code{x1},@code{x2}] (on which the endpoint values of @code{f} have
5045opposite signs), given its derivative @code{fprime}. Diagnostics for
5046each iteration are printed if @code{verbose=true}.
5047If the iteration fails after the maximum allowed number of loops
5048(@code{iterations}), @code{realMax} is returned.
5049
5050@cindex @code{simpson}
5051@item @code{real simpson(real f(real), real a, real b, real acc=realEpsilon, real dxmax=b-a)}
5052returns the integral of @code{f} from @code{a} to @code{b} using adaptive Simpson integration.
5053
5054@end table
5055
5056@node Arrays
5057@section Arrays
5058@cindex arrays
5059
5060@menu
5061* Slices::                      Python-style array slices
5062@end menu
5063
5064Appending @code{[]} to a built-in or user-defined type yields an array.
5065The array element @code{i} of an array @code{A} can be accessed as @code{A[i]}.
5066By default, attempts to access or assign to an array element using a negative
5067index generates an error. Reading an array element with an index
5068beyond the length of the array also generates an error; however,
5069assignment to an element beyond the length of the array causes the
5070array to be resized to accommodate the new element.
5071One can also index an array @code{A} with an integer array @code{B}:
5072the array @code{A[B]} is formed by indexing array @code{A} with
5073successive elements of array @code{B}.
5074A convenient Java-style shorthand exists for iterating over all elements of an
5075array; see @ref{array iteration}.
5076
5077The declaration
5078@verbatim
5079real[] A;
5080@end verbatim
5081
5082@noindent
5083initializes @code{A} to be an empty (zero-length) array. Empty arrays should be
5084distinguished from null arrays. If we say
5085@verbatim
5086real[] A=null;
5087@end verbatim
5088
5089@noindent
5090then @code{A} cannot be dereferenced at all (null arrays have no length
5091and cannot be read from or assigned to).
5092
5093Arrays can be explicitly initialized like this:
5094@verbatim
5095real[] A={0,1,2};
5096@end verbatim
5097
5098Array assignment in @code{Asymptote} does a shallow copy: only
5099the pointer is copied (if one copy if modified, the other will be too).
5100The @code{copy} function listed below provides a deep copy of an array.
5101
5102@cindex @code{length}
5103@cindex @code{cyclic}
5104@cindex @code{keys}
5105@cindex @code{push}
5106@cindex @code{append}
5107@cindex @code{pop}
5108@cindex @code{insert}
5109@cindex @code{delete}
5110@cindex @code{initialized}
5111Every array @code{A} of type @code{T[]} has the virtual members
5112@itemize
5113@item   @code{int length},
5114@item   @code{int cyclic},
5115@item   @code{int[] keys},
5116@item   @code{T push(T x)},
5117@item   @code{void append(T[] a)},
5118@item   @code{T pop()},
5119@item   @code{void insert(int i ... T[] x)},
5120@item   @code{void delete(int i, int j=i)},
5121@item   @code{void delete()}, and
5122@item   @code{bool initialized(int n)}.
5123@end itemize
5124
5125The member @code{A.length} evaluates to the length of the array.
5126Setting @code{A.cyclic=true} signifies that array indices should be reduced
5127modulo the current array length. Reading from or writing to a nonempty
5128cyclic array never leads to out-of-bounds errors or array resizing.
5129
5130The member @code{A.keys} evaluates to an array of integers containing the
5131indices of initialized entries in the array in ascending order.  Hence, for an
5132array of length @code{n} with all entries initialized, @code{A.keys} evaluates
5133to @code{@{0,1,...,n-1@}}.  A new keys array is produced each time
5134@code{A.keys} is evaluated.
5135
5136The functions @code{A.push} and @code{A.append} append their
5137arguments onto the end of the array, while @code{A.insert(int i ... T[] x)}
5138inserts @code{x} into the array at index @code{i}.
5139For convenience @code{A.push} returns the pushed item.
5140The function @code{A.pop()} pops and returns the last element,
5141while @code{A.delete(int i, int j=i)} deletes elements with indices in
5142the range [@code{i},@code{j}], shifting the position of all higher-indexed
5143elements down. If no arguments are given, @code{A.delete()} provides a
5144convenient way of deleting all elements of @code{A}. The routine
5145@code{A.initialized(int n)} can be used to examine whether the element
5146at index @code{n} is initialized. Like all @code{Asymptote} functions,
5147@code{push}, @code{append}, @code{pop}, @code{insert},
5148@code{delete}, and @code{initialized} can be "pulled off" of the array
5149and used on their own. For example,
5150@verbatim
5151int[] A={1};
5152A.push(2);         // A now contains {1,2}.
5153A.append(A);       // A now contains {1,2,1,2}.
5154int f(int)=A.push;
5155f(3);              // A now contains {1,2,1,2,3}.
5156int g()=A.pop;
5157write(g());        // Outputs 3.
5158A.delete(0);       // A now contains {2,1,2}.
5159A.delete(0,1);       // A now contains {2}.
5160A.insert(1,3);     // A now contains {2,3}.
5161A.insert(1 ... A); // A now contains {2,2,3,3}
5162A.insert(2,4,5);   // A now contains {2,2,4,5,3,3}.
5163@end verbatim
5164
5165The @code{[]} suffix can also appear after the variable name; this
5166is sometimes convenient for declaring a list of variables and arrays
5167of the same type:
5168@verbatim
5169real a,A[];
5170@end verbatim
5171@noindent
5172This declares @code{a} to be @code{real} and implicitly declares @code{A} to
5173be of type @code{real[]}.
5174
5175In the following list of built-in array functions, @code{T} represents a
5176generic type. Note that the internal functions @code{alias}, @code{array},
5177@code{copy}, @code{concat}, @code{sequence}, @code{map}, and
5178@code{transpose}, which depend on type @code{T[]}, are defined only after the
5179first declaration of a variable of type @code{T[]}.
5180
5181@table @code
5182
5183@cindex @code{new}
5184@item new T[]
5185returns a new empty array of type @code{T[]};
5186
5187@cindex @code{new}
5188@item new T[] @{list@}
5189returns a new array of type @code{T[]} initialized with @code{list} (a comma
5190delimited list of elements).
5191
5192@item new T[n]
5193returns a new array of @code{n} elements of type @code{T[]}.
5194These @code{n} array elements are not initialized unless they are arrays
5195themselves (in which case they are each initialized to empty arrays).
5196
5197@cindex @code{array}
5198@item T[] array(int n, T value, int depth=intMax)
5199returns an array consisting of @code{n} copies of @code{value}.
5200If @code{value} is itself an array, a deep copy of @code{value} is made
5201for each entry. If @code{depth} is specified, this deep copying only
5202recurses to the specified number of levels.
5203
5204@cindex @code{sequence}
5205@item int[] sequence(int n)
5206if @code{n >= 1} returns the array @code{@{0,1,...,n-1@}} (otherwise returns
5207a null array);
5208
5209@item int[] sequence(int n, int m)
5210if @code{m >= n} returns an array @code{@{n,n+1,...,m@}} (otherwise
5211returns a null array);
5212
5213@item T[] sequence(T f(int), int n)
5214if @code{n >= 1} returns the sequence @code{@{f_i :i=0,1,...n-1@}} given a
5215function @code{T f(int)} and integer @code{int n} (otherwise returns a
5216null array);
5217
5218@cindex @code{map}
5219@item T[] map(T f(T), T[] a)
5220returns the array obtained by applying the function @code{f} to each
5221element of the array @code{a}. This is equivalent to
5222@code{sequence(new T(int i) @{return f(a[i]);@},a.length)}.
5223
5224@cindex @code{reverse}
5225@item int[] reverse(int n)
5226if @code{n >= 1} returns the array @code{@{n-1,n-2,...,0@}} (otherwise
5227returns a null array);
5228
5229@cindex @code{complement}
5230@item int[] complement(int[] a, int n)
5231returns the complement of the integer array @code{a} in
5232@code{@{0,1,2,...,n-1@}}, so that @code{b[complement(a,b.length)]} yields the
5233complement of @code{b[a]}.
5234
5235@cindex @code{uniform}
5236@item real[] uniform(real a, real b, int n)
5237if @code{n >= 1} returns a uniform partition of @code{[a,b]} into
5238@code{n} subintervals (otherwise returns a null array);
5239
5240@cindex @code{find}
5241@item int find(bool[], int n=1)
5242returns the index of the @code{n}th @code{true} value or -1 if not found.
5243If @code{n} is negative, search backwards from the end of the array for the
5244@code{-n}th value;
5245
5246@cindex @code{search}
5247@item int search(T[] a, T key)
5248For built-in ordered types @code{T}, searches a sorted array
5249@code{a} of @code{n} elements for k, returning the index @code{i}
5250if @code{a[i] <= key < a[i+1]}, @code{-1} if @code{key} is
5251less than all elements of @code{a}, or @code{n-1} if @code{key} is
5252greater than or equal to the last element of @code{a}.
5253
5254@cindex @code{search}
5255@item int search(T[] a, T key, bool less(T i, T j))
5256searches an array @code{a} sorted in ascending order such that element
5257@code{i} precedes element @code{j} if @code{less(i,j)} is true;
5258
5259@cindex @code{copy}
5260@item T[] copy(T[] a)
5261returns a deep copy of the array @code{a};
5262
5263@cindex @code{concat}
5264@item T[] concat(... T[][] a)
5265returns a new array formed by concatenating the given one-dimensional
5266arrays given as arguments;
5267
5268@cindex @code{alias}
5269@item bool alias(T[] a, T[] b)
5270returns @code{true} if the arrays @code{a} and @code{b} are identical;
5271
5272@cindex @code{sort}
5273@item T[] sort(T[] a)
5274For built-in ordered types @code{T}, returns a copy of @code{a} sorted in
5275ascending order;
5276
5277@cindex @code{sort}
5278@anchor{sort}
5279@item T[][] sort(T[][] a)
5280For built-in ordered types @code{T}, returns a copy of @code{a} with the rows
5281sorted by the first column, breaking ties with successively higher
5282columns. For example:
5283@verbatim
5284string[][] a={{"bob","9"},{"alice","5"},{"pete","7"},
5285              {"alice","4"}};
5286// Row sort (by column 0, using column 1 to break ties):
5287write(sort(a));
5288@end verbatim
5289
5290produces
5291@verbatim
5292alice   4
5293alice   5
5294bob     9
5295pete    7
5296@end verbatim
5297
5298@cindex @code{sort}
5299@item T[] sort(T[] a, bool less(T i, T j))
5300returns a copy of @code{a} stably sorted in ascending order such that
5301element @code{i} precedes element @code{j} if @code{less(i,j)} is true.
5302
5303@cindex @code{transpose}
5304@item T[][] transpose(T[][] a)
5305returns the transpose of @code{a}.
5306
5307@cindex @code{transpose}
5308@item T[][][] transpose(T[][][] a, int[] perm)
5309returns the 3D transpose of @code{a} obtained by applying the permutation
5310@code{perm} of @code{new int[]@{0,1,2@}} to the indices of each entry.
5311
5312@cindex @code{sum}
5313@item T sum(T[] a)
5314For arithmetic types @code{T}, returns the sum of @code{a}.
5315In the case where @code{T} is @code{bool}, the number of true elements in
5316@code{a} is returned.
5317
5318@cindex @code{min}
5319@item T min(T[] a)
5320@item T min(T[][] a)
5321@item T min(T[][][] a)
5322For built-in ordered types @code{T}, returns the minimum element of @code{a}.
5323
5324@cindex @code{max}
5325@item T max(T[] a)
5326@item T max(T[][] a)
5327@item T max(T[][][] a)
5328For built-in ordered types @code{T}, returns the maximum element of @code{a}.
5329
5330@cindex @code{min}
5331@item T[] min(T[] a, T[] b)
5332For built-in ordered types @code{T}, and arrays @code{a} and @code{b}
5333of the same length, returns an array composed of the minimum of the
5334corresponding elements of @code{a} and @code{b}.
5335
5336@cindex @code{max}
5337@item T[] max(T[] a, T[] b)
5338For built-in ordered types @code{T}, and arrays @code{a} and @code{b}
5339of the same length, returns an array composed of the maximum of the
5340corresponding elements of @code{a} and @code{b}.
5341
5342@cindex @code{pairs}
5343@item pair[] pairs(real[] x, real[] y);
5344For arrays @code{x} and @code{y} of the same length, returns the pair array
5345@code{sequence(new pair(int i) @{return (x[i],y[i]);@},x.length)}.
5346
5347@cindex @code{fft}
5348@item pair[] fft(pair[] a, int sign=1)
5349returns the unnormalized Fast Fourier Transform of @code{a} (if the optional
5350@code{FFTW} package is installed), using the given @code{sign}. Here
5351is a simple example:
5352@verbatim
5353int n=4;
5354pair[] f=sequence(n);
5355write(f);
5356pair[] g=fft(f,-1);
5357write();
5358write(g);
5359f=fft(g,1);
5360write();
5361write(f/n);
5362@end verbatim
5363
5364@cindex @code{dot}
5365@item real dot(real[] a, real[] b)
5366returns the dot product of the vectors @code{a} and @code{b}.
5367
5368@cindex @code{dot}
5369@item pair dot(pair[] a, pair[] b)
5370returns the complex dot product @code{sum(a*conj(b))} of the vectors
5371@code{a} and @code{b}.
5372
5373@anchor{tridiagonal}
5374@cindex @code{tridiagonal}
5375@item real[] tridiagonal(real[] a, real[] b, real[] c, real[] f);
5376Solve the periodic tridiagonal problem @math{L@code{x}=@code{f}} and return the
5377solution @code{x}, where @code{f}
5378is an @math{n} vector and @math{L} is the @math{n \times n} matrix
5379@verbatim
5380[ b[0] c[0]           a[0]   ]
5381[ a[1] b[1] c[1]             ]
5382[      a[2] b[2] c[2]        ]
5383[                ...         ]
5384[ c[n-1]       a[n-1] b[n-1] ]
5385@end verbatim
5386For Dirichlet boundary conditions (denoted here by @code{u[-1]} and
5387@code{u[n]}), replace @code{f[0]} by @code{f[0]-a[0]u[-1]} and
5388@code{f[n-1]-c[n-1]u[n]}; then set @code{a[0]=c[n-1]=0}.
5389
5390@cindex @code{solve}
5391@item real[] solve(real[][] a, real[] b, bool warn=true)
5392Solve the linear equation @math{@code{a}x=@code{b}} by LU decomposition
5393and return the solution @math{x}, where @code{a} is an
5394@math{n \times n} matrix and @code{b} is an array of length @math{n}.
5395For example:
5396@verbatim
5397import math;
5398real[][] a={{1,-2,3,0},{4,-5,6,2},{-7,-8,10,5},{1,50,1,-2}};
5399real[] b={7,19,33,3};
5400real[] x=solve(a,b);
5401write(a); write();
5402write(b); write();
5403write(x); write();
5404write(a*x);
5405@end verbatim
5406If @code{a} is a singular matrix and @code{warn} is @code{false}, return an
5407empty array.
5408If the matrix @code{a} is tridiagonal, the routine @code{tridiagonal} provides
5409a more efficient algorithm (@pxref{tridiagonal}).
5410
5411@anchor{solve}
5412@cindex @code{solve}
5413@item real[][] solve(real[][] a, real[][] b, bool warn=true)
5414Solve the linear equation @math{@code{a}x=@code{b}} and return the
5415solution @math{x}, where @code{a} is an @math{n \times n} matrix and
5416@code{b} is an @math{n \times m} matrix. If @code{a} is a singular
5417matrix and @code{warn} is @code{false}, return an empty matrix.
5418
5419@cindex @code{identity}
5420@item real[][] identity(int n);
5421returns the @math{n \times n} identity matrix.
5422
5423@cindex @code{diagonal}
5424@item real[][] diagonal(... real[] a)
5425returns the diagonal matrix with diagonal entries given by a.
5426
5427@cindex @code{inverse}
5428@item real[][] inverse(real[][] a)
5429returns the inverse of a square matrix @code{a}.
5430
5431@cindex @code{quadraticroots}
5432@item @code{real[] quadraticroots(real a, real b, real c);}
5433This numerically robust solver returns the real roots of the
5434quadratic equation @math{ax^2+bx+c=0}, in ascending order. Multiple
5435roots are listed separately.
5436
5437@cindex @code{quadraticroots}
5438@item @code{pair[] quadraticroots(explicit pair a, explicit pair b, explicit pair c);}
5439This numerically robust solver returns the complex roots of the
5440quadratic equation @math{ax^2+bx+c=0}.
5441
5442@cindex @code{cubicroots}
5443@item @code{real[] cubicroots(real a, real b, real c, real d);}
5444This numerically robust solver returns the real roots of the
5445cubic equation @math{ax^3+bx^2+cx+d=0}. Multiple roots are listed separately.
5446
5447@end table
5448
5449@cindex vectorization
5450@code{Asymptote} includes a full set of vectorized array instructions for
5451arithmetic (including self) and logical operations. These
5452element-by-element instructions are implemented in C++ code for speed. Given
5453@verbatim
5454real[] a={1,2};
5455real[] b={3,2};
5456@end verbatim
5457@noindent
5458then @code{a == b} and @code{a >= 2} both evaluate to the vector
5459@code{@{false, true@}}.
5460@cindex @code{all}
5461To test whether all components of @code{a} and @code{b} agree,
5462use the boolean function @code{all(a == b)}. One can also use conditionals like
5463@code{(a >= 2) ? a : b}, which returns the array @code{@{3,2@}}, or
5464@code{write((a >= 2) ? a : null}, which returns the array @code{@{2@}}.
5465
5466All of the standard built-in @code{libm} functions of signature
5467@code{real(real)} also take a real array as an argument, effectively like an
5468implicit call to @code{map}.
5469
5470As with other built-in types, arrays of the basic data types can be read
5471in by assignment. In this example, the code
5472@verbatim
5473file fin=input("test.txt");
5474real[] A=fin;
5475@end verbatim
5476
5477@cindex @code{eof}
5478@cindex @code{eol}
5479@cindex @code{line}
5480@cindex line mode
5481@noindent
5482reads real values into @code{A} until the end-of-file is reached (or an
5483I/O error occurs).
5484
5485The virtual members @code{dimension}, @code{line}, @code{csv},
5486@code{word}, and @code{read} of a file are useful for reading arrays.
5487@cindex @code{line}
5488For example, if line mode is set with @code{file line(bool b=true)}, then
5489reading will stop once the end of the line is reached instead:
5490@verbatim
5491file fin=input("test.txt");
5492real[] A=fin.line();
5493@end verbatim
5494
5495@cindex reading string arrays
5496@cindex @code{word}
5497@cindex white-space string delimiter mode
5498Since string reads by default read up to the end of line anyway, line mode
5499normally has no effect on string array reads.
5500However, there is a white-space delimiter mode for reading strings,
5501@code{file word(bool b=true)}, which causes string reads to respect
5502white-space delimiters, instead of the default end-of-line delimiter:
5503@verbatim
5504file fin=input("test.txt").line().word();
5505real[] A=fin;
5506@end verbatim
5507
5508@cindex @code{csv}
5509@cindex comma-separated-value mode
5510Another useful mode is comma-separated-value mode,
5511@code{file csv(bool b=true)}, which causes reads to respect comma delimiters:
5512@verbatim
5513file fin=csv(input("test.txt"));
5514real[] A=fin;
5515@end verbatim
5516
5517@cindex @code{dimension}
5518To restrict the number of values read, use the @code{file dimension(int)}
5519function:
5520@verbatim
5521file fin=input("test.txt");
5522real[] A=dimension(fin,10);
5523@end verbatim
5524
5525This reads 10 values into A, unless end-of-file (or end-of-line in line mode)
5526occurs first. Attempting to read beyond the end of the file will produce a
5527runtime error message. Specifying a value of 0 for the integer limit is
5528equivalent to the previous example of reading until end-of-file (or
5529end-of-line in line mode) is encountered.
5530
5531Two- and three-dimensional arrays of the basic data types can be read
5532in like this:
5533@verbatim
5534file fin=input("test.txt");
5535real[][] A=fin.dimension(2,3);
5536real[][][] B=fin.dimension(2,3,4);
5537@end verbatim
5538@noindent
5539Again, an integer limit of zero means no restriction.
5540
5541@cindex @code{read}
5542Sometimes the array dimensions are stored with the data as integer
5543fields at the beginning of an array. Such 1, 2, or 3 dimensional
5544arrays can be read in with the virtual member functions
5545@code{read(1)}, @code{read(2)}, or @code{read(3)}, respectively:
5546@verbatim
5547file fin=input("test.txt");
5548real[] A=fin.read(1);
5549real[][] B=fin.read(2);
5550real[][][] C=fin.read(3);
5551@end verbatim
5552
5553@cindex @code{write}
5554One, two, and three-dimensional arrays of the basic data types can be
5555output with the functions @code{write(file,T[])},
5556@code{write(file,T[][])}, @code{write(file,T[][][])}, respectively.
5557
5558@node Slices
5559@subsection Slices
5560@cindex slices
5561
5562Asymptote allows a section of an array to be addressed as a slice
5563using a Python-like syntax.  If @code{A} is an array, the expression
5564@code{A[m:n]} returns a new array consisting of the elements of @code{A} with
5565indices from @code{m} up to but not including @code{n}. For example,
5566@verbatim
5567int[] x={0,1,2,3,4,5,6,7,8,9};
5568int[] y=x[2:6];  // y={2,3,4,5};
5569int[] z=x[5:10]; // z={5,6,7,8,9};
5570@end verbatim
5571
5572If the left index is omitted, it is taken be @code{0}.  If the right index is
5573omitted it is taken to be the length of the array.  If both are omitted, the
5574slice then goes from the start of the array to the end, producing a non-cyclic
5575deep copy of the array.  For example:
5576@verbatim
5577int[] x={0,1,2,3,4,5,6,7,8,9};
5578int[] y=x[:4];  // y={0,1,2,3}
5579int[] z=x[5:];  // z={5,6,7,8,9}
5580int[] w=x[:];   // w={0,1,2,3,4,5,6,7,8,9}, distinct from array x.
5581@end verbatim
5582
5583If A is a non-cyclic array, it is illegal to use negative values for either of
5584the indices.  If the indices exceed the length of the array, however, they are
5585politely truncated to that length.
5586
5587For cyclic arrays, the slice @code{A[m:n]} still consists of the cells with
5588indices in the set [@code{m},@code{n}), but now negative
5589values and values beyond the length of the array are allowed.  The indices
5590simply wrap around.  For example:
5591
5592@verbatim
5593int[] x={0,1,2,3,4,5,6,7,8,9};
5594x.cyclic=true;
5595int[] y=x[8:15];  // y={8,9,0,1,2,3,4}.
5596int[] z=x[-5:5];  // z={5,6,7,8,9,0,1,2,3,4}
5597int[] w=x[-3:17]; // w={7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6}
5598@end verbatim
5599
5600Notice that with cyclic arrays, it is possible to include the same element of
5601the original array multiple times within a slice.  Regardless of the original
5602array, arrays produced by slices are always non-cyclic.
5603
5604If the left and right indices of a slice are the same, the result is an empty
5605array.  If the array being sliced is empty, the result is an empty array.  Any
5606slice with a left index greater than its right index will yield an error.
5607
5608Slices can also be assigned to, changing the value of the original array.  If
5609the array being assigned to the slice has a different length than the
5610slice itself, elements will be inserted or removed from the array to
5611accommodate it. For instance:
5612@verbatim
5613string[] toppings={"mayo", "salt", "ham", "lettuce"};
5614toppings[0:2]=new string[] {"mustard", "pepper"};
5615    // Now toppings={"mustard", "pepper", "ham", "lettuce"}
5616toppings[2:3]=new string[] {"turkey", "bacon" };
5617    // Now toppings={"mustard", "pepper", "turkey", "bacon", "lettuce"}
5618toppings[0:3]=new string[] {"tomato"};
5619    // Now toppings={"tomato", "bacon", "lettuce"}
5620@end verbatim
5621
5622If an array is assigned to a slice of itself, a copy of the original array
5623is assigned to the slice.  That is, code such as @code{x[m:n]=x} is equivalent
5624to @code{x[m:n]=copy(x)}.  One can use the shorthand @code{x[m:m]=y} to insert
5625the contents of the array @code{y} into the array @code{x} starting at the
5626location just before @code{x[m]}.
5627
5628For a cyclic array, a slice is bridging if it addresses cells up to the end of
5629the array and then continues on to address cells at the start of the array.
5630For instance, if @code{A} is a cyclic array of length 10, @code{A[8:12]},
5631@code{A[-3:1]}, and @code{A[5:25]} are bridging slices whereas @code{A[3:7]},
5632@code{A[7:10]}, @code{A[-3:0]} and @code{A[103:107]} are not.  Bridging slices
5633can only be assigned to if the number of elements in the slice is exactly equal
5634to the number of elements we are assigning to it.  Otherwise, there is no clear
5635way to decide which of the new entries should be @code{A[0]} and an error is
5636reported.  Non-bridging slices may be assigned an array of any length.
5637
5638For a cyclic array @code{A} an expression of the form
5639@code{A[A.length:A.length]} is equivalent to the expression @code{A[0:0]} and
5640so assigning to this slice will insert values at the start of the array.
5641@code{A.append()} can be used to insert values at the end of the array.
5642
5643It is illegal to assign to a slice of a cyclic array that repeats any of the
5644cells.
5645
5646@node Casts
5647@section Casts
5648@cindex casts
5649@cindex implicit casts
5650@cindex @code{explicit}
5651
5652@code{Asymptote} implicitly casts @code{int} to @code{real}, @code{int} to
5653@code{pair}, @code{real} to @code{pair}, @code{pair} to @code{path},
5654@code{pair} to @code{guide}, @code{path} to @code{guide}, @code{guide}
5655to @code{path}, @code{real} to @code{pen},
5656@code{pair[]} to @code{guide[]}, @code{pair[]} to @code{path[]},
5657@code{path} to @code{path[]}, and @code{guide} to @code{path[]},
5658along with various three-dimensional casts defined in @code{three.asy}.
5659Implicit casts are automatically attempted on assignment and when
5660trying to match function calls with possible function
5661signatures. Implicit casting can be inhibited by declaring individual
5662arguments @code{explicit} in the function signature, say to avoid an
5663ambiguous function call in the following example, which outputs 0:
5664@verbatim
5665int f(pair a) {return 0;}
5666int f(explicit real x) {return 1;}
5667
5668write(f(0));
5669@end verbatim
5670
5671@cindex explicit casts
5672Other conversions, say @code{real} to @code{int} or
5673@code{real} to @code{string}, require an explicit cast:
5674@verbatim
5675int i=(int) 2.5;
5676string s=(string) 2.5;
5677
5678real[] a={2.5,-3.5};
5679int[] b=(int []) a;
5680write(stdout,b);     // Outputs 2,-3
5681@end verbatim
5682
5683@cindex @code{operator cast}
5684Casting to user-defined types is also possible using @code{operator cast}:
5685@verbatim
5686struct rpair {
5687  real radius;
5688  real angle;
5689}
5690
5691pair operator cast(rpair x) {
5692  return (x.radius*cos(x.angle),x.radius*sin(x.angle));
5693}
5694
5695rpair x;
5696x.radius=1;
5697x.angle=pi/6;
5698
5699write(x);            // Outputs (0.866025403784439,0.5)
5700@end verbatim
5701
5702One must use care when defining new cast operators. Suppose that in some
5703code one wants all integers to represent multiples of 100. To convert them
5704to reals, one would first want to multiply them by 100. However, the
5705straightforward implementation
5706@verbatim
5707real operator cast(int x) {return x*100;}
5708@end verbatim
5709is equivalent to an infinite recursion, since the result @code{x*100}
5710needs itself to be cast from an integer to a real. Instead, we want to
5711use the standard conversion of int to real:
5712@verbatim
5713real convert(int x) {return x*100;}
5714real operator cast(int x)=convert;
5715@end verbatim
5716
5717@cindex @code{operator ecast}
5718Explicit casts are implemented similarly, with @code{operator ecast}.
5719
5720@node Import
5721@section Import
5722@cindex @code{access}
5723While @code{Asymptote} provides many features by default,
5724some applications require specialized features contained in
5725external @code{Asymptote} modules. For instance, the lines
5726@verbatim
5727access graph;
5728graph.axes();
5729@end verbatim
5730@noindent
5731draw @math{x} and @math{y} axes on a two-dimensional graph.  Here, the
5732command looks up the module under the name @code{graph} in a global dictionary
5733of modules and puts it in a new variable named @code{graph}.
5734The module is a structure, and we can refer to its fields as we usually
5735would with a structure.
5736
5737@cindex @code{from}
5738Often, one wants to use module functions without having to specify
5739the module name.  The code
5740@verbatim
5741from graph access axes;
5742@end verbatim
5743@noindent
5744adds the @code{axes} field of @code{graph} into the local name space,
5745so that subsequently, one can just write @code{axes()}.  If the given name
5746is overloaded, all types and variables of that name are added.  To add
5747more than one name, just use a comma-separated list:
5748@verbatim
5749from graph access axes, xaxis, yaxis;
5750@end verbatim
5751@noindent
5752Wild card notation can be used to add all non-private fields and types of a
5753module to the local name space:
5754
5755@verbatim
5756from graph access *;
5757@end verbatim
5758
5759@cindex @code{unravel}
5760Similarly, one can add the non-private fields and types of a structure
5761to the local environment with the @code{unravel} keyword:
5762@verbatim
5763struct matrix {
5764  real a,b,c,d;
5765}
5766
5767real det(matrix m) {
5768  unravel m;
5769  return a*d-b*c;
5770}
5771@end verbatim
5772Alternatively, one can unravel selective fields:
5773@verbatim
5774real det(matrix m) {
5775  from m unravel a,b,c as C,d;
5776  return a*d-b*C;
5777}
5778@end verbatim
5779
5780@cindex @code{import}
5781The command
5782@verbatim
5783import graph;
5784@end verbatim
5785is a convenient abbreviation for the commands
5786@verbatim
5787access graph;
5788unravel graph;
5789@end verbatim
5790That is, @code{import graph} first loads a module into a structure called
5791@code{graph} and then adds its non-private fields and types to the
5792local environment. This way, if a member variable (or function) is
5793overwritten with a local variable (or function of the same signature),
5794the original one can still be accessed by qualifying it with the
5795module name.
5796
5797Wild card importing will work fine in most cases, but one does not usually know
5798all of the internal types and variables of a module, which can also
5799change as the module writer adds or changes features of the module.
5800As such, it is prudent to add @code{import} commands at the start of an
5801@code{Asymptote} file, so that imported names won't shadow locally
5802defined functions.  Still, imported names may shadow other imported
5803names, depending on the order in which they were imported, and
5804imported functions may cause overloading resolution problems if they
5805have the same name as local functions defined later.
5806
5807@cindex @code{as}
5808To rename modules or fields when adding them to the local environment, use
5809@code{as}:
5810@verbatim
5811access graph as graph2d;
5812from graph access xaxis as xline, yaxis as yline;
5813@end verbatim
5814
5815The command
5816@verbatim
5817import graph as graph2d;
5818@end verbatim
5819is a convenient abbreviation for the commands
5820@verbatim
5821access graph as graph2d;
5822unravel graph2d;
5823@end verbatim
5824
5825Except for a few built-in modules, such as @code{settings}, all modules
5826are implemented as @code{Asymptote} files.  When looking up a module
5827that has not yet been loaded, @code{Asymptote} searches the standard
5828search paths (@pxref{Search paths}) for the matching file.  The file
5829corresponding to that name is read and the code within it is interpreted
5830as the body of a structure defining the module.
5831
5832If the file name contains
5833nonalphanumeric characters, enclose it with quotation marks:
5834
5835@noindent
5836@code{access "@value{Datadir}/asymptote/graph.asy" as graph;}
5837
5838@noindent
5839@code{from "@value{Datadir}/asymptote/graph.asy" access axes;}
5840
5841@noindent
5842@code{import "@value{Datadir}/asymptote/graph.asy" as graph;}
5843
5844It is an error if modules import themselves (or each other in a cycle).
5845The module name to be imported must be known at compile time.
5846
5847@cindex runtime imports
5848@cindex @code{eval}
5849However, you can import an @code{Asymptote} module determined by the
5850string @code{s} at runtime like this:
5851@verbatim
5852eval("import "+s,true);
5853@end verbatim
5854
5855@cindex @code{asy}
5856To conditionally execute an array of asy files, use
5857@verbatim
5858void asy(string format, bool overwrite ... string[] s);
5859@end verbatim
5860The file will only be processed, using output format @code{format}, if
5861overwrite is @code{true} or the output file is missing.
5862
5863One can evaluate an @code{Asymptote} expression (without any return
5864value, however) contained in the string @code{s} with:
5865@cindex @code{eval}
5866@verbatim
5867void eval(string s, bool embedded=false);
5868@end verbatim
5869It is not necessary to terminate the string @code{s} with a semicolon.
5870If @code{embedded} is @code{true}, the string will be evaluated
5871at the top level of the current environment.
5872If @code{embedded} is @code{false} (the default), the string
5873will be evaluated in an independent environment, sharing the same
5874@code{settings} module (@pxref{settings}).
5875
5876@cindex @code{quote}
5877One can evaluate arbitrary @code{Asymptote} code (which may
5878contain unescaped quotation marks) with the command
5879@verbatim
5880void eval(code s, bool embedded=false);
5881@end verbatim
5882Here @code{code} is a special type used with @code{quote @{@}}
5883to enclose @code{Asymptote code} like this:
5884@verbatim
5885real a=1;
5886code s=quote {
5887  write(a);
5888};
5889eval(s,true);        // Outputs 1
5890@end verbatim
5891
5892@cindex @code{include}
5893To include the contents of an existing file @code{graph} verbatim (as if the
5894contents of the file were inserted at that point), use one of the forms:
5895@verbatim
5896include graph;
5897@end verbatim
5898
5899@noindent
5900@code{include "@value{Datadir}/asymptote/graph.asy";}
5901
5902To list all global functions and variables defined in a module named
5903by the contents of the string @code{s}, use the function
5904@verbatim
5905void list(string s, bool imports=false);
5906@end verbatim
5907@noindent
5908Imported global functions and variables are also listed if
5909@code{imports} is @code{true}.
5910
5911@node Static
5912@section Static
5913@cindex @code{static}
5914
5915Static qualifiers allocate the memory address of a variable in a higher
5916enclosing level.
5917
5918For a function body, the variable is allocated in the block where the
5919function is defined; so in the code
5920@verbatim
5921struct s {
5922  int count() {
5923    static int c=0;
5924    ++c;
5925    return c;
5926  }
5927}
5928@end verbatim
5929
5930@noindent
5931there is one instance of the variable @code{c} for each
5932object @code{s} (as opposed to each call of @code{count}).
5933
5934Similarly, in
5935@verbatim
5936int factorial(int n) {
5937  int helper(int k) {
5938    static int x=1;
5939    x *= k;
5940    return k == 1 ? x : helper(k-1);
5941  }
5942  return helper(n);
5943}
5944@end verbatim
5945
5946@noindent
5947there is one instance of @code{x} for every call to
5948@code{factorial} (and not for every call to @code{helper}), so this is
5949a correct, but ugly, implementation of factorial.
5950
5951Similarly, a static variable declared within a structure is allocated in
5952the block where the structure is defined. Thus,
5953@verbatim
5954struct A {
5955  struct B {
5956    static pair z;
5957  }
5958}
5959@end verbatim
5960
5961@noindent
5962creates one object @code{z} for each object of type @code{A} created.
5963
5964In this example,
5965@verbatim
5966int pow(int n, int k) {
5967  struct A {
5968    static int x=1;
5969    void helper() {
5970      x *= n;
5971    }
5972  }
5973  for(int i=0; i < k; ++i) {
5974    A a;
5975    a.helper();
5976  }
5977  return A.x;
5978}
5979@end verbatim
5980
5981@noindent
5982there is one instance of @code{x} for each call to @code{pow}, so this
5983is an ugly implementation of exponentiation.
5984
5985Loop constructs allocate a new frame in every iteration.  This is so that
5986higher-order functions can refer to variables of a specific iteration of a
5987loop:
5988@verbatim
5989void f();
5990for(int i=0; i < 10; ++i) {
5991  int x=i;
5992  if(x==5) {
5993    f=new void () { write(x); }
5994  }
5995}
5996f();
5997@end verbatim
5998
5999Here, every iteration of the loop has its own variable @code{x}, so @code{f()}
6000will write @code{5}.  If a variable in a loop is declared static, it will be
6001allocated where the enclosing function or structure was defined (just as if it
6002were declared static outside of the loop).  For instance, in:
6003@verbatim
6004void f() {
6005  static int x;
6006  for(int i=0; i < 10; ++i) {
6007    static int y;
6008  }
6009}
6010@end verbatim
6011@noindent
6012both @code{x} and @code{y} will be allocated in the same place, which is
6013also where @code{f} is also allocated.
6014
6015Statements may also be declared static, in which case they are run at the place
6016where the enclosing function or structure is defined.
6017Declarations or statements not enclosed in a function or structure definition
6018are already at the top level, so static modifiers are meaningless.  A warning is
6019given in such a case.
6020
6021Since structures can have static fields, it is not always clear for a qualified
6022name whether the qualifier is a variable or a type.  For instance, in:
6023
6024@verbatim
6025struct A {
6026  static int x;
6027}
6028pair A;
6029
6030int y=A.x;
6031@end verbatim
6032@noindent
6033does the @code{A} in @code{A.x} refer to the structure or to the pair variable.
6034It is the convention in Asymptote that, if there is a non-function variable with
6035the same name as the qualifier, the qualifier refers to that variable, and not
6036to the type.  This is regardless of what fields the variable actually possesses.
6037
6038@node LaTeX usage
6039@chapter @code{LaTeX} usage
6040@cindex @code{LaTeX} usage
6041@cindex @code{asymptote.sty}
6042
6043@code{Asymptote} comes with a convenient @code{LaTeX} style file
6044@code{asymptote.sty} that makes @code{LaTeX}
6045@code{Asymptote}-aware. Entering @code{Asymptote} code
6046directly into the @code{LaTeX} source file, at the point where it is
6047needed, keeps figures organized and avoids the need to invent new file
6048names for each figure. Simply add the line
6049@code{\usepackage@{asymptote@}} at the beginning of your file
6050and enclose your @code{Asymptote} code within a
6051@code{\begin@{asy@}...\end@{asy@}} environment. As with the
6052@code{LaTeX} @code{comment} environment, the @code{\end@{asy@}} command
6053must appear on a line by itself, with no trailing commands/comments.
6054A blank line is not allowed after @code{\begin@{asy@}}.
6055
6056The sample @code{LaTeX} file below, named @code{latexusage.tex}, can
6057be run as follows:
6058@verbatim
6059latex latexusage
6060asy latexusage-*.asy
6061latex latexusage
6062@end verbatim
6063
6064@noindent
6065or
6066@verbatim
6067pdflatex latexusage
6068asy latexusage-*.asy
6069pdflatex latexusage
6070@end verbatim
6071@noindent
6072To switch between using inline Asymptote code with @code{latex} and
6073@code{pdflatex} you may first need to remove the files @code{latexusage-*.tex}.
6074
6075@cindex @code{latexmk}
6076@cindex @code{perl}
6077An even better method for processing a @code{LaTeX} file with embedded
6078@code{Asymptote} code is to use the @code{latexmk} utility from
6079@quotation
6080@url{http://mirror.ctan.org/support/latexmk/}
6081@end quotation
6082@noindent
6083after putting the contents of
6084@url{http://sourceforge.net/p/asymptote/code/HEAD/tree/trunk/asymptote/doc/latexmkrc}
6085@noindent
6086in a file @code{latexmkrc} in the same directory. The command
6087@verbatim
6088latexmk -pdf latexusage
6089@end verbatim
6090@noindent
6091will then call @code{Asymptote} automatically, recompiling only the figures
6092that have changed. Since each figure is compiled in a separate
6093system process, this method also tends to use less memory.
6094To store the figures in a separate directory named @code{asy}, one can define
6095@verbatim
6096\def\asydir{asy}
6097@end verbatim
6098in @code{latexusage.tex} and put the contents of
6099@url{http://sourceforge.net/p/asymptote/code/HEAD/tree/trunk/asymptote/doc/latexmkrc_asydir}
6100in a file @code{latexmkrc} in the same directory.
6101@noindent
6102External @code{Asymptote} code in @code{filename.asy} should be included with
6103@cindex @code{asyinclude}
6104@verbatim
6105\asyinclude[<options>]{<filename.asy>}
6106@end verbatim
6107@noindent
6108so that @code{latexmk} will recognize when the code is changed. Note that
6109@code{latemk} requires @code{perl}, available from @url{http://www.perl.org/}.
6110
6111@cindex @code{width}
6112@cindex @code{height}
6113@cindex @code{keepAspect}
6114@cindex @code{viewportwidth}
6115@cindex @code{viewportheight}
6116@cindex @code{attach}
6117@cindex @code{inline}
6118One can specify @code{width}, @code{height}, @code{keepAspect},
6119@code{viewportwidth}, @code{viewportheight}, @code{attach}, and @code{inline}.
6120@code{keyval}-style options to the @code{asy} and @code{asyinclude}
6121environments.
6122Three-dimensional @acronym{PRC} files may either be embedded within
6123the page (the default) or attached as annotated (but printable)
6124attachments, using the @code{attach} option and the @code{attachfile2}
6125(or older @code{attachfile}) @code{LaTeX} package.
6126The @code{inline} option generates
6127inline @code{LaTeX} code instead of @acronym{EPS} or @acronym{PDF}
6128files. This makes 2D LaTeX symbols visible to the
6129@code{\begin@{asy@}...\end@{asy@}} environment.  In this mode,
6130Asymptote correctly aligns 2D LaTeX symbols defined outside of
6131@code{\begin@{asy@}...\end@{asy@}}, but treats their size as zero; an
6132optional second string can be given to @code{Label} to provide an
6133estimate of the unknown label size.
6134
6135Note that if the @code{latex} @TeX{} engine is used with the
6136@code{inline} option, labels might not show up in @acronym{DVI}
6137viewers that cannot handle raw @code{PostScript} code. One can use
6138@code{dvips}/@code{dvipdf} to produce @code{PostScript}/@acronym{PDF}
6139output (we recommend using the modified version of @code{dvipdf} in
6140the @code{Asymptote} patches directory, which accepts the @code{dvips -z}
6141hyperdvi option).
6142
6143Here now is @code{latexusage.tex}:
6144@verbatiminclude latexusage.tex
6145@page
6146@image{latexusage,,25cm}
6147
6148@node Base modules
6149@chapter Base modules
6150@cindex base modules
6151
6152@code{Asymptote} currently ships with the following base modules:
6153
6154@menu
6155* plain::                       Default @code{Asymptote} base file
6156* simplex::                     Linear programming: simplex method
6157* math::                        Extend @code{Asymptote}'s math capabilities
6158* interpolate::                 Interpolation routines
6159* geometry::                    Geometry routines
6160* trembling::                   Wavy lines
6161* stats::                       Statistics routines and histograms
6162* patterns::                    Custom fill and draw patterns
6163* markers::                     Custom path marker routines
6164* tree::                        Dynamic binary search tree
6165* binarytree::                  Binary tree drawing module
6166* drawtree::                    Tree drawing module
6167* syzygy::                      Syzygy and braid drawing module
6168* feynman::                     Feynman diagrams
6169* roundedpath::                 Round the sharp corners of paths
6170* animation::                   Embedded @acronym{PDF} and @acronym{MPEG} movies
6171* embed::                       Embedding movies, sounds, and 3D objects
6172* slide::                       Making presentations with @code{Asymptote}
6173* MetaPost::                    @code{MetaPost} compatibility routines
6174* unicode::                     Accept @code{unicode} (UTF-8) characters
6175* latin1::                      Accept @code{ISO 8859-1} characters
6176* babel::                       Interface to @code{LaTeX} @code{babel} package
6177* labelpath::                   Drawing curved labels
6178* labelpath3::                  Drawing curved labels in 3D
6179* annotate::                    Annotate your @acronym{PDF} files
6180* CAD::                         2D CAD pen and measurement functions (DIN 15)
6181* graph::                       2D linear & logarithmic graphs
6182* palette::                     Color density images and palettes
6183* three::                       3D vector graphics
6184* obj::                         3D obj files
6185* graph3::                      3D linear & logarithmic graphs
6186* grid3::                       3D grids
6187* solids::                      3D solid geometry
6188* tube::                        3D rotation minimizing tubes
6189* flowchart::                   Flowchart drawing routines
6190* contour::                     Contour lines
6191* contour3::                    Contour surfaces
6192* slopefield::                  Slope fields
6193* ode::                         Ordinary differential equations
6194@end menu
6195
6196@node plain
6197@section @code{plain}
6198@cindex @code{plain}
6199
6200This is the default @code{Asymptote} base file, which defines key parts of the
6201drawing language (such as the @code{picture} structure).
6202
6203By default, an implicit @code{private import plain;} occurs before
6204translating a file and before the first command given in interactive
6205mode.  This also applies when translating files for module definitions
6206(except when translating @code{plain}, of course).  This means that
6207the types and functions defined in @code{plain} are accessible in
6208almost all @code{Asymptote} code. Use the @code{-noautoplain} command-line
6209option to disable this feature.
6210
6211@node simplex
6212@section @code{simplex}
6213@cindex @code{simplex}
6214@cindex @code{deferred drawing}
6215This package solves the two-variable linear programming problem using the
6216simplex method. It is used by the module @code{plain} for automatic
6217sizing of pictures.
6218
6219@node math
6220@section @code{math}
6221@cindex @code{math}
6222This package extends @code{Asymptote}'s mathematical capabilities with
6223useful functions such as
6224
6225@table @code
6226
6227@cindex @code{drawline}
6228@item void drawline(picture pic=currentpicture, pair P, pair Q, pen p=currentpen);
6229draw the visible portion of the (infinite) line going through
6230@code{P} and @code{Q}, without altering the size of picture @code{pic},
6231using pen @code{p}.
6232
6233@cindex @code{intersect}
6234@item real intersect(triple P, triple Q, triple n, triple Z);
6235returns the intersection time of the extension of the line segment @code{PQ}
6236with the plane perpendicular to @code{n} and passing through @code{Z}.
6237
6238@cindex @code{intersectionpoint}
6239@item triple intersectionpoint(triple n0, triple P0, triple n1, triple P1);
6240Return any point on the intersection of the two planes with normals
6241@code{n0} and @code{n1} passing through points @code{P0} and @code{P1},
6242respectively. If the planes are parallel, return
6243@code{(infinity,infinity,infinity)}.
6244
6245@cindex @code{quarticroots}
6246@item pair[] quarticroots(real a, real b, real c, real d, real e);
6247returns the four complex roots of the quartic equation
6248@math{ax^4+bx^3+cx^2+dx+e=0}.
6249
6250@cindex @code{fft}
6251@item pair[][] fft(pair[][] a, int sign=1)
6252returns the two-dimensional Fourier transform of a using the given
6253@code{sign}.
6254
6255@cindex @code{time}
6256@item real time(path g, real x, int n=0)
6257returns the @code{n}th intersection time of path @code{g} with the vertical
6258line through x.
6259
6260@cindex @code{time}
6261@item real time(path g, explicit pair z, int n=0)
6262returns the @code{n}th intersection time of path @code{g} with the horizontal
6263line through @code{(0,z.y)}.
6264
6265@cindex @code{value}
6266@item real value(path g, real x, int n=0)
6267returns the @code{n}th @code{y} value of @code{g} at @code{x}.
6268
6269@cindex @code{value}
6270@item real value(path g, explicit pair z, int n=0)
6271returns the @code{n}th @code{x} value of @code{g} at @code{y=z.y}.
6272
6273@cindex @code{slope}
6274@item real slope(path g, real x, int n=0)
6275returns the @code{n}th slope of @code{g} at @code{x}.
6276
6277@cindex @code{slope}
6278@item real slope(path g, explicit pair z, int n=0)
6279returns the @code{n}th slope of @code{g} at @code{y=z.y}.
6280
6281@cindex @code{segment}
6282int[][] segment(bool[] b)
6283returns the indices of consecutive true-element segments of bool[] @code{b}.
6284
6285@cindex @code{partialsum}
6286@item real[] partialsum(real[] a)
6287returns the partial sums of a real array @code{a}.
6288
6289@cindex @code{partialsum}
6290@item real[] partialsum(real[] a, real[] dx)
6291returns the partial @code{dx}-weighted sums of a real array @code{a}.
6292
6293@cindex @code{increasing}
6294@item bool increasing(real[] a, bool strict=false)
6295returns, if @code{strict=false}, whether @code{i > j} implies
6296@code{a[i] >= a[j]}, or if @code{strict=true}, whether @code{i > j} implies
6297implies @code{a[i] > a[j]}.
6298
6299@cindex @code{unique}
6300@item int unique(real[] a, real x)
6301if the sorted array @code{a} does not contain @code{x}, insert it
6302sequentially, returning the index of @code{x} in the resulting array.
6303
6304@cindex @code{lexorder}
6305@item bool lexorder(pair a, pair b)
6306returns the strict lexicographical partial order of @code{a} and @code{b}.
6307
6308@cindex @code{lexorder}
6309@item bool lexorder(triple a, triple b)
6310returns the strict lexicographical partial order of @code{a} and @code{b}.
6311@end table
6312
6313@node interpolate
6314@section @code{interpolate}
6315@cindex @code{interpolate}
6316This module implements Lagrange, Hermite, and standard cubic spline
6317interpolation in @code{Asymptote}, as illustrated in the example
6318@code{interpolate1.asy}.
6319
6320@node geometry
6321@section @code{geometry}
6322@cindex @code{geometry}
6323@cindex @code{triangle}
6324@cindex @code{perpendicular}
6325This module, written by Philippe Ivaldi, provides an extensive set of
6326geometry routines, including @code{perpendicular} symbols and a @code{triangle}
6327structure. Link to the documentation for the @code{geometry} module
6328are posted here:
6329@url{http://asymptote.sourceforge.net/links.html},
6330including an extensive set of examples,
6331@url{http://www.piprime.fr/files/asymptote/geometry/}, and an index:
6332@quotation
6333@url{http://www.piprime.fr/files/asymptote/geometry/modules/geometry.asy.index.type.html}
6334@end quotation
6335
6336@node trembling
6337@section @code{trembling}
6338@cindex @code{trembling}
6339This module, written by Philippe Ivaldi and illustrated in the example
6340@code{floatingdisk.asy}, allows one to draw wavy lines, as if drawn by
6341hand.
6342
6343@node stats
6344@section @code{stats}
6345@cindex @code{stats}
6346@cindex @code{leastsquares}
6347This package implements a Gaussian random number generator
6348and a collection of statistics routines, including @code{histogram}
6349and @code{leastsquares}.
6350
6351@node patterns
6352@section @code{patterns}
6353@cindex @code{patterns}
6354This package implements @code{Postscript} tiling patterns and includes
6355several convenient pattern generation routines.
6356
6357@node markers
6358@section @code{markers}
6359@cindex @code{markers}
6360This package implements specialized routines for marking paths and angles.
6361The principal mark routine provided by this package is
6362@verbatim
6363markroutine markinterval(int n=1, frame f, bool rotated=false);
6364@end verbatim
6365@noindent
6366which centers @code{n} copies of frame @code{f} within uniformly space
6367intervals in arclength along the path, optionally rotated by the angle of the
6368local tangent.
6369
6370The @code{marker} (@pxref{marker}) routine can be used to construct new
6371markers from these predefined frames:
6372
6373@cindex @code{stickframe}
6374@verbatim
6375frame stickframe(int n=1, real size=0, pair space=0, real angle=0,
6376                 pair offset=0, pen p=currentpen);
6377@end verbatim
6378@cindex @code{circlebarframe}
6379@verbatim
6380frame circlebarframe(int n=1, real barsize=0,
6381                     real radius=0,real angle=0,
6382                     pair offset=0, pen p=currentpen,
6383                     filltype filltype=NoFill, bool above=false);
6384@end verbatim
6385@cindex @code{crossframe}
6386@verbatim
6387frame crossframe(int n=3, real size=0, pair space=0,
6388                 real angle=0, pair offset=0, pen p=currentpen);
6389@end verbatim
6390@cindex @code{tildeframe}
6391@verbatim
6392frame tildeframe(int n=1, real size=0, pair space=0,
6393                 real angle=0, pair offset=0, pen p=currentpen);
6394@end verbatim
6395
6396For convenience, this module also constructs the markers
6397@code{StickIntervalMarker},  @code{CrossIntervalMarker},
6398@code{CircleBarIntervalMarker}, and @code{TildeIntervalMarker}
6399from the above frames. The example @code{markers1.asy} illustrates the
6400use of these markers:
6401
6402@sp 1
6403@center @image{markers1}
6404
6405This package also provides a routine for marking an angle @math{AOB}:
6406@cindex @code{markangle}
6407@verbatim
6408void markangle(picture pic=currentpicture, Label L="",
6409               int n=1, real radius=0, real space=0,
6410               pair A, pair O, pair B, arrowbar arrow=None,
6411               pen p=currentpen, margin margin=NoMargin,
6412               marker marker=nomarker);
6413@end verbatim
6414@noindent
6415as illustrated in the example @code{markers2.asy}.
6416
6417@sp 1
6418@center @image{markers2}
6419
6420@node tree
6421@section @code{tree}
6422@cindex @code{tree}
6423This package implements an example of a dynamic binary search tree.
6424
6425@node binarytree
6426@section @code{binarytree}
6427@cindex @code{binarytree}
6428This module can be used to draw an arbitrary binary tree and includes an
6429input routine for the special case of a binary search tree, as
6430illustrated in the example @code{binarytreetest.asy}:
6431@verbatiminclude binarytreetest.asy
6432@sp 1
6433@center @image{binarytreetest}
6434
6435@node drawtree
6436@section @code{drawtree}
6437@cindex @code{drawtree}
6438This is a simple tree drawing module used by the example @code{treetest.asy}.
6439
6440@node syzygy
6441@section @code{syzygy}
6442@cindex @code{syzygy}
6443This module automates the drawing of braids, relations, and syzygies,
6444along with the corresponding equations, as illustrated in the example
6445@code{knots.asy}.
6446
6447@node feynman
6448@section @code{feynman}
6449@cindex @code{feynman}
6450This package, contributed by Martin Wiebusch, is useful for drawing
6451Feynman diagrams, as illustrated by the examples @code{eetomumu.asy}
6452and @code{fermi.asy}.
6453
6454@node roundedpath
6455@section @code{roundedpath}
6456@cindex @code{roundedpath}
6457This package, contributed by Stefan Knorr, is useful for rounding the
6458sharp corners of paths, as illustrated in the example file @code{roundpath.asy}.
6459
6460@node animation
6461@section @code{animation}
6462@cindex @code{animation}
6463@cindex @code{convert}
6464@cindex animation
6465@cindex @code{ImageMagick}
6466This module allows one to generate animations, as illustrated by the
6467files @code{wheel.asy}, @code{wavepacket.asy}, and @code{cube.asy} in
6468the @code{animations} subdirectory of the examples directory. These
6469animations use the @code{ImageMagick} @code{convert} program to
6470merge multiple images into a @acronym{GIF} or @acronym{MPEG}
6471movie.
6472
6473@cindex @code{animate}
6474@anchor{animate}
6475The related @code{animate} module, derived from the @code{animation}
6476module, generates higher-quality portable clickable @acronym{PDF} movies, with
6477optional controls. This requires installing the package
6478@quotation
6479@url{http://mirror.ctan.org/macros/latex/contrib/animate/animate.sty}
6480@noindent
6481@end quotation
6482@noindent
6483(version 2007/11/30 or later) in a new directory @code{animate} in the
6484local @code{LaTeX} directory (for example, in
6485@code{/usr/local/share/texmf/tex/latex/animate}). On @code{UNIX} systems,
6486one must then execute the command @code{texhash}.
6487
6488The example @code{pdfmovie.asy} in the @code{animations}
6489directory, along with the slide presentations @code{slidemovies.asy}
6490and @code{intro.asy}, illustrate the use of embedded @acronym{PDF} movies.
6491The examples @code{inlinemovie.tex} and @code{inlinemovie3.tex}
6492show how to generate and embed @acronym{PDF} movies directly within a
6493@code{LaTeX} file (@pxref{LaTeX usage}).
6494The member function
6495@verbatim
6496string pdf(fit fit=NoBox, real delay=animationdelay, string options="",
6497           bool keep=settings.keep, bool multipage=true);
6498@end verbatim
6499@noindent
6500of the @code{animate} structure accepts any of the @code{animate.sty} options,
6501as described here:
6502@quotation
6503@url{http://mirror.ctan.org/macros/latex/contrib/animate/doc/animate.pdf}
6504@end quotation
6505
6506@node embed
6507@section @code{embed}
6508@cindex @code{embed}
6509This module provides an interface to the @code{LaTeX} package
6510(included with @code{MikTeX})
6511@quotation
6512@url{http://mirror.ctan.org/macros/latex/contrib/media9}
6513@end quotation
6514@noindent
6515for embedding movies, sounds, and 3D objects into a @acronym{PDF} document.
6516
6517@cindex @code{external}
6518A more portable method for embedding movie files, which should work on any
6519platform and does not require the @code{media9} package, is provided
6520by using the @code{external} module instead of @code{embed}.
6521
6522Examples of the above two interfaces is provided in the file
6523@code{embeddedmovie.asy} and @code{externalmovie.asy} in the
6524@code{animations} subdirectory of the examples directory. For a higher
6525quality embedded movie generated directly by @code{Asymptote}, use the
6526@code{animate} module along with the @code{animate.sty} package to
6527embed a portable @acronym{PDF} animation (@pxref{animate}).
6528
6529@cindex @code{U3D}
6530An example of embedding @code{U3D} code is provided in the file
6531@code{embeddedu3d.asy}.
6532
6533@node slide
6534@section @code{slide}
6535@cindex @code{slide}
6536This package provides a simple yet high-quality facility for making
6537presentation slides, including portable embedded @acronym{PDF} animations (see
6538the file @code{slidemovies.asy}). A simple example is provided in the file
6539@code{slidedemo.asy}.
6540
6541@node MetaPost
6542@section @code{MetaPost}
6543@cindex @code{MetaPost}
6544This package provides some useful routines to help @code{MetaPost} users
6545migrate old @code{MetaPost} code to @code{Asymptote}. Further
6546contributions here are welcome.
6547
6548@cindex @code{implicit linear solver}
6549@cindex @code{MetaPost whatever}
6550@cindex @code{extension}
6551Unlike @code{MetaPost}, @code{Asymptote} does not implicitly solve
6552linear equations and therefore does not have the notion of a
6553@code{whatever} unknown. The routine @code{extension} (@pxref{extension})
6554provides a useful replacement for a common use of @code{whatever}: finding the
6555intersection point of the lines through @code{P}, @code{Q} and
6556@code{p}, @code{q}. For less common occurrences of @code{whatever}, one
6557can use the built-in explicit linear equation solver @code{solve} instead.
6558
6559@node unicode
6560@section @code{unicode}
6561@cindex @code{unicode}
6562@cindex international characters
6563Import this package at the beginning of the file to instruct
6564@code{LaTeX} to accept @code{unicode} (UTF-8) standardized international
6565characters.
6566@noindent
6567@cindex Cyrillic
6568@cindex Russian
6569To use Cyrillic fonts, you will need to change the font encoding:
6570@verbatim
6571import unicode;
6572texpreamble("\usepackage{mathtext}\usepackage[russian]{babel}");
6573defaultpen(font("T2A","cmr","m","n"));
6574@end verbatim
6575@noindent
6576@cindex Chinese
6577@cindex Japanese
6578@cindex Korean
6579@cindex CJK
6580Support for Chinese, Japanese, and Korean fonts is provided by the
6581CJK package:
6582@quotation
6583@url{http://mirror.ctan.org/languages/chinese/CJK/}
6584@end quotation
6585@noindent
6586The following commands enable the CJK song family (within a label, you
6587can also temporarily switch to another family, say kai, by prepending
6588@code{"\CJKfamily@{kai@}"} to the label string):
6589@verbatim
6590texpreamble("\usepackage{CJK}
6591\AtBeginDocument{\begin{CJK*}{GBK}{song}}
6592\AtEndDocument{\clearpage\end{CJK*}}");
6593@end verbatim
6594
6595@node latin1
6596@section @code{latin1}
6597@cindex @code{latin1}
6598If you don't have @code{LaTeX} support for @code{unicode} installed,
6599you can enable support for Western European languages (ISO 8859-1) by
6600importing the module @code{latin1}. This module can be used as a
6601template for providing support for other ISO 8859 alphabets.
6602
6603@node babel
6604@section @code{babel}
6605@cindex @code{babel}
6606This module implements the @code{LaTeX} @code{babel} package in
6607@code{Asymptote}. For example:
6608@verbatim
6609import babel;
6610babel("german");
6611@end verbatim
6612
6613@node labelpath
6614@section @code{labelpath}
6615@cindex @code{labelpath}
6616This module uses the @code{PSTricks} @code{pstextpath} macro to fit labels
6617along a path (properly kerned, as illustrated in the example file
6618@code{curvedlabel.asy}), using the command
6619@verbatim
6620void labelpath(picture pic=currentpicture, Label L, path g,
6621               string justify=Centered, pen p=currentpen);
6622@end verbatim
6623@noindent
6624Here @code{justify} is one of @code{LeftJustified}, @code{Centered}, or
6625@code{RightJustified}. The @math{x} component of a shift transform
6626applied to the Label is interpreted as a shift along the curve, whereas
6627the @math{y} component is interpreted as a shift away from the curve.
6628All other Label transforms are ignored. This package requires the
6629@code{latex} tex engine and inherits the limitations of the
6630@code{PSTricks} @code{\pstextpath} macro.
6631
6632@node labelpath3
6633@section @code{labelpath3}
6634@cindex @code{labelpath3}
6635This module, contributed by Jens Schwaiger, implements a 3D version of
6636@code{labelpath} that does not require the @code{PSTricks} package.
6637An example is provided in @code{curvedlabel3.asy}.
6638
6639@node annotate
6640@section @code{annotate}
6641@cindex @code{annotate}
6642This module supports @acronym{PDF} annotations for viewing with
6643@code{Adobe Reader}, via the function
6644@verbatim
6645void annotate(picture pic=currentpicture, string title, string text,
6646              pair position);
6647@end verbatim
6648@noindent
6649Annotations are illustrated in the example file @code{annotation.asy}.
6650Currently, annotations are only implemented for the @code{latex}
6651(default) and @code{tex} @TeX{} engines.
6652
6653@node CAD
6654@section @code{CAD}
6655@cindex @code{CAD}
6656This package, contributed by Mark Henning, provides basic pen
6657definitions and measurement functions for simple 2D CAD drawings
6658according to DIN 15. It is documented separately, in the file
6659@code{CAD.pdf}.
6660
6661@node graph
6662@section @code{graph}
6663@cindex @code{graph}
6664@cindex 2D graphs
6665This package implements two-dimensional linear and logarithmic graphs,
6666including automatic scale and tick selection (with the ability to
6667override manually). A graph is a @code{guide} (that can be drawn with
6668the draw command, with an optional legend) constructed with one of
6669the following routines:
6670
6671@itemize
6672@item
6673@verbatim
6674guide graph(picture pic=currentpicture, real f(real), real a, real b,
6675            int n=ngraph, real T(real)=identity,
6676            interpolate join=operator --);
6677guide[] graph(picture pic=currentpicture, real f(real), real a, real b,
6678             int n=ngraph, real T(real)=identity, bool3 cond(real),
6679             interpolate join=operator --);
6680@end verbatim
6681
6682Returns a graph using the scaling information for picture @code{pic}
6683(@pxref{automatic scaling}) of the function @code{f} on the interval
6684[@code{T}(@code{a}),@code{T}(@code{b})], sampling at @code{n} points
6685evenly spaced in [@code{a},@code{b}], optionally restricted by the
6686bool3 function @code{cond} on [@code{a},@code{b}]. If @code{cond} is:
6687@itemize @bullet
6688@item @code{true}, the point is added to the existing guide;
6689@item @code{default}, the point is added to a new guide;
6690@item @code{false}, the point is omitted and a new guide is begun.
6691@end itemize
6692The points are connected using the interpolation specified by @code{join}:
6693@itemize @bullet
6694
6695@cindex @code{operator --}
6696@cindex @code{Straight}
6697@item @code{operator --} (linear interpolation; the abbreviation
6698@code{Straight} is also accepted);
6699
6700@cindex @code{operator ..}
6701@cindex @code{Spline}
6702@item @code{operator ..} (piecewise Bezier cubic spline interpolation;
6703the abbreviation @code{Spline} is also accepted);
6704
6705@cindex @code{Hermite}
6706@cindex @code{notaknot}
6707@cindex @code{natural}
6708@cindex @code{periodic}
6709@cindex @code{clamped}
6710@cindex @code{monotonic}
6711@cindex @code{Hermite(splinetype splinetype}
6712@item @code{Hermite} (standard cubic spline interpolation using boundary
6713condition @code{notaknot}, @code{natural},  @code{periodic},
6714@code{clamped(real slopea, real slopeb)}), or @code{monotonic}.
6715The abbreviation @code{Hermite} is equivalent to
6716@code{Hermite(notaknot)} for nonperiodic data and
6717@code{Hermite(periodic)} for periodic data).
6718
6719@end itemize
6720
6721@item
6722@verbatim
6723guide graph(picture pic=currentpicture, real x(real), real y(real),
6724            real a, real b, int n=ngraph, real T(real)=identity,
6725            interpolate join=operator --);
6726guide[] graph(picture pic=currentpicture, real x(real), real y(real),
6727              real a, real b, int n=ngraph, real T(real)=identity,
6728              bool3 cond(real), interpolate join=operator --);
6729@end verbatim
6730
6731Returns a graph using the scaling information for picture @code{pic}
6732of the parametrized function
6733(@code{x}(@math{t}),@code{y}(@math{t})) for @math{t} in the interval
6734[@code{T}(@code{a}),@code{T}(@code{b})], sampling at @code{n} points
6735evenly spaced in [@code{a},@code{b}], optionally restricted by the
6736bool3 function @code{cond} on [@code{a},@code{b}], using the given
6737interpolation type.
6738
6739@item
6740@verbatim
6741guide graph(picture pic=currentpicture, pair z(real), real a, real b,
6742            int n=ngraph, real T(real)=identity,
6743            interpolate join=operator --);
6744guide[] graph(picture pic=currentpicture, pair z(real), real a, real b,
6745              int n=ngraph, real T(real)=identity, bool3 cond(real),
6746              interpolate join=operator --);
6747@end verbatim
6748
6749Returns a graph using the scaling information for picture @code{pic}
6750of the parametrized function
6751@code{z}(@math{t}) for @math{t} in the interval
6752[@code{T}(@code{a}),@code{T}(@code{b})], sampling at @code{n} points
6753evenly spaced in [@code{a},@code{b}], optionally restricted by the
6754bool3 function @code{cond} on [@code{a},@code{b}], using the given
6755interpolation type.
6756
6757@item
6758@verbatim
6759guide graph(picture pic=currentpicture, pair[] z,
6760            interpolate join=operator --);
6761guide[] graph(picture pic=currentpicture, pair[] z, bool3[] cond,
6762              interpolate join=operator --);
6763@end verbatim
6764
6765Returns a graph using the scaling information for picture @code{pic}
6766of the elements of the array @code{z}, optionally restricted to
6767those indices for which the elements of the boolean array @code{cond} are
6768@code{true}, using the given interpolation type.
6769
6770@item
6771@verbatim
6772guide graph(picture pic=currentpicture, real[] x, real[] y,
6773            interpolate join=operator --);
6774guide[] graph(picture pic=currentpicture, real[] x, real[] y,
6775              bool3[] cond, interpolate join=operator --);
6776@end verbatim
6777
6778Returns a graph using the scaling information for picture @code{pic}
6779of the elements of the arrays (@code{x},@code{y}), optionally
6780restricted to those indices for which the elements of the boolean
6781array @code{cond} are @code{true}, using the given interpolation type.
6782
6783@item
6784@cindex @code{polargraph}
6785@verbatim
6786guide polargraph(picture pic=currentpicture, real f(real), real a,
6787                 real b, int n=ngraph, interpolate join=operator --);
6788@end verbatim
6789
6790Returns a polar-coordinate graph using the scaling information for
6791picture @code{pic} of the function @code{f} on the interval
6792[@code{a},@code{b}], sampling at @code{n} evenly spaced points, with
6793the given interpolation type.
6794
6795@item
6796@verbatim
6797guide polargraph(picture pic=currentpicture, real[] r, real[] theta,
6798                 interpolate join=operator--);
6799@end verbatim
6800Returns a polar-coordinate graph using the scaling information for
6801picture @code{pic} of the elements of the arrays (@code{r},@code{theta}),
6802using the given interpolation type.
6803
6804@end itemize
6805
6806@verbatim
6807
6808
6809@end verbatim
6810
6811An axis can be drawn on a picture with one of the following commands:
6812
6813@itemize
6814
6815@item
6816@verbatim
6817void xaxis(picture pic=currentpicture, Label L="", axis axis=YZero,
6818           real xmin=-infinity, real xmax=infinity, pen p=currentpen,
6819           ticks ticks=NoTicks, arrowbar arrow=None, bool above=false);
6820@end verbatim
6821
6822Draw an @math{x} axis on picture @code{pic} from @math{x}=@code{xmin} to
6823@math{x}=@code{xmax} using pen @code{p}, optionally labelling it with
6824Label @code{L}. The relative label location along the axis (a real number from
6825[0,1]) defaults to 1 (@pxref{Label}), so that the label is drawn at the
6826end of the axis. An infinite value of @code{xmin}
6827or @code{xmax} specifies that the corresponding axis limit will be
6828automatically determined from the picture limits.
6829The optional @code{arrow} argument takes the same values as in the
6830@code{draw} command (@pxref{arrows}). The axis is drawn before any
6831existing objects in @code{pic} unless @code{above=true}.
6832The axis placement is determined by one of the following @code{axis} types:
6833
6834@table @code
6835
6836@cindex @code{YZero}
6837@item YZero(bool extend=true)
6838Request an @math{x} axis at @math{y}=0 (or @math{y}=1 on a logarithmic axis)
6839extending to the full dimensions of the picture, unless @code{extend}=false.
6840
6841@cindex @code{YEquals}
6842@item YEquals(real Y, bool extend=true)
6843Request an @math{x} axis at @math{y}=@code{Y} extending to the full
6844dimensions of the picture, unless @code{extend}=false.
6845
6846@cindex @code{Bottom}
6847@item Bottom(bool extend=false)
6848Request a bottom axis.
6849
6850@cindex @code{Top}
6851@item Top(bool extend=false)
6852Request a top axis.
6853
6854@cindex @code{BottomTop}
6855@item BottomTop(bool extend=false)
6856Request a bottom and top axis.
6857
6858@end table
6859
6860@cindex custom axis types
6861Custom axis types can be created by following the examples in @code{graph.asy}.
6862One can easily override the default values for the standard axis types:
6863@verbatim
6864import graph;
6865
6866YZero=new axis(bool extend=true) {
6867  return new void(picture pic, axisT axis) {
6868    real y=pic.scale.x.scale.logarithmic ? 1 : 0;
6869    axis.value=I*pic.scale.y.T(y);
6870    axis.position=1;
6871    axis.side=right;
6872    axis.align=2.5E;
6873    axis.value2=Infinity;
6874    axis.extend=extend;
6875  };
6876};
6877YZero=YZero();
6878
6879@end verbatim
6880
6881@anchor{ticks}
6882@cindex @code{ticks}
6883@cindex @code{NoTicks}
6884@cindex @code{LeftTicks}
6885@cindex @code{RightTicks}
6886@cindex @code{Ticks}
6887The default tick option is @code{NoTicks}.
6888The options @code{LeftTicks}, @code{RightTicks}, or @code{Ticks} can be
6889used to draw ticks on the left, right, or both sides of the path,
6890relative to the direction in which the path is drawn.
6891These tick routines accept a number of optional arguments:
6892@verbatim
6893ticks LeftTicks(Label format="", ticklabel ticklabel=null,
6894                bool beginlabel=true, bool endlabel=true,
6895                int N=0, int n=0, real Step=0, real step=0,
6896                bool begin=true, bool end=true, tickmodifier modify=None,
6897                real Size=0, real size=0, bool extend=false,
6898                pen pTick=nullpen, pen ptick=nullpen);
6899@end verbatim
6900
6901If any of these parameters are omitted, reasonable defaults will
6902be chosen:
6903@table @code
6904@item Label format
6905@cindex @code{defaultformat}
6906@cindex @code{trailingzero}
6907override the default tick label format (@code{defaultformat}, initially
6908"$%.4g$"), rotation, pen, and alignment (for example, @code{LeftSide},
6909@code{Center}, or @code{RightSide}) relative to the axis. To enable
6910@code{LaTeX} math mode fonts, the format string should begin and
6911end with @code{$} @pxref{format}. If the format string is @code{trailingzero},
6912trailing zeros will be added to the tick labels; if the format string is
6913@code{"%"}, the tick label will be suppressed;
6914@item ticklabel
6915is a function @code{string(real x)} returning the label (by default,
6916format(format.s,x)) for each major tick value @code{x};
6917@item bool beginlabel
6918include the first label;
6919@item bool endlabel
6920include the last label;
6921@item int N
6922when automatic scaling is enabled (the default; @pxref{automatic scaling}),
6923divide a linear axis evenly into this many intervals, separated by major ticks;
6924for a logarithmic axis, this is the number of decades between labelled ticks;
6925@item int n
6926divide each interval into this many subintervals, separated by minor ticks;
6927@item real Step
6928the tick value spacing between major ticks
6929(if @code{N}=@code{0});
6930@item real step
6931the tick value spacing between minor ticks (if @code{n}=@code{0});
6932@item bool begin
6933include the first major tick;
6934@item bool end
6935include the last major tick;
6936@item tickmodifier modify;
6937an optional function that takes and returns a @code{tickvalue} structure having
6938real[] members @code{major} and @code{minor} consisting of the tick values
6939(to allow modification of the automatically generated tick values);
6940@item real Size
6941the size of the major ticks (in @code{PostScript} coordinates);
6942@item real size
6943the size of the minor ticks (in @code{PostScript} coordinates);
6944@item bool extend;
6945extend the ticks between two axes (useful for drawing a grid on the graph);
6946@item pen pTick
6947an optional pen used to draw the major ticks;
6948@item pen ptick
6949an optional pen used to draw the minor ticks.
6950
6951@end table
6952
6953@cindex @code{OmitTick}
6954@cindex @code{OmitTickInterval}
6955@cindex @code{OmitTickIntervals}
6956For convenience, the predefined tickmodifiers @code{OmitTick(... real[] x)},
6957@code{OmitTickInterval(real a, real b)}, and
6958@code{OmitTickIntervals(real[] a, real[] b)}
6959can be used to remove specific auto-generated ticks and
6960their labels. The @code{OmitFormat(string s=defaultformat ... real[] x)}
6961ticklabel can be used to remove specific tick labels but not the
6962corresponding ticks. The tickmodifier @code{NoZero} is an abbreviation for
6963@code{OmitTick(0)} and the ticklabel @code{NoZeroFormat} is an
6964abbrevation for @code{OmitFormat(0)}.
6965
6966@cindex custom tick locations
6967@cindex @code{LeftTicks}
6968@cindex @code{RightTicks}
6969@cindex @code{Ticks}
6970It is also possible to specify custom tick locations with
6971@code{LeftTicks}, @code{RightTicks}, and @code{Ticks} by passing explicit real
6972arrays @code{Ticks} and (optionally) @code{ticks} containing the
6973locations of the major and minor ticks, respectively:
6974@verbatim
6975ticks LeftTicks(Label format="", ticklabel ticklabel=null,
6976                bool beginlabel=true, bool endlabel=true,
6977                real[] Ticks, real[] ticks=new real[],
6978                real Size=0, real size=0, bool extend=false,
6979                pen pTick=nullpen, pen ptick=nullpen)
6980@end verbatim
6981
6982@item
6983@verbatim
6984void yaxis(picture pic=currentpicture, Label L="", axis axis=XZero,
6985           real ymin=-infinity, real ymax=infinity, pen p=currentpen,
6986           ticks ticks=NoTicks, arrowbar arrow=None, bool above=false,
6987           bool autorotate=true);
6988@end verbatim
6989
6990Draw a @math{y} axis on picture @code{pic} from @math{y}=@code{ymin} to
6991@math{y}=@code{ymax} using pen @code{p}, optionally labelling it with
6992a Label @code{L} that is autorotated unless @code{autorotate=false}.
6993The relative location of the label (a real number from
6994[0,1]) defaults to 1 (@pxref{Label}). An infinite value of @code{ymin}
6995or @code{ymax} specifies that the corresponding axis limit will be
6996automatically determined from the picture limits.
6997The optional @code{arrow} argument takes the same values as in the
6998@code{draw} command (@pxref{arrows}). The axis is drawn before any
6999existing objects in @code{pic} unless @code{above=true}.
7000The tick type is specified by @code{ticks} and the axis placement is
7001determined by one of the following @code{axis} types:
7002
7003@table @code
7004
7005@cindex @code{XZero}
7006@item XZero(bool extend=true)
7007Request a @math{y} axis at @math{x}=0 (or @math{x}=1 on a logarithmic axis)
7008extending to the full dimensions of the picture, unless @code{extend}=false.
7009
7010@cindex @code{XEquals}
7011@item XEquals(real X, bool extend=true)
7012Request a @math{y} axis at @math{x}=@code{X} extending to the full
7013dimensions of the picture, unless @code{extend}=false.
7014
7015@cindex @code{Left}
7016@item Left(bool extend=false)
7017Request a left axis.
7018
7019@cindex @code{Right}
7020@item Right(bool extend=false)
7021Request a right axis.
7022
7023@cindex @code{LeftRight}
7024@item LeftRight(bool extend=false)
7025Request a left and right axis.
7026
7027@end table
7028
7029@item
7030@cindex @code{xequals}
7031@cindex @code{yequals}
7032For convenience, the functions
7033@verbatim
7034void xequals(picture pic=currentpicture, Label L="", real x,
7035             bool extend=false, real ymin=-infinity, real ymax=infinity,
7036             pen p=currentpen, ticks ticks=NoTicks, bool above=true,
7037             arrowbar arrow=None);
7038@end verbatim
7039and
7040@verbatim
7041void yequals(picture pic=currentpicture, Label L="", real y,
7042             bool extend=false, real xmin=-infinity, real xmax=infinity,
7043             pen p=currentpen, ticks ticks=NoTicks, bool above=true,
7044             arrowbar arrow=None);
7045@end verbatim
7046can be respectively used to call @code{yaxis} and
7047@code{xaxis} with the appropriate axis types @code{XEquals(x,extend)} and
7048@code{YEquals(y,extend)}. This is the recommended way of drawing vertical
7049or horizontal lines and axes at arbitrary locations.
7050
7051@item
7052@verbatim
7053void axes(picture pic=currentpicture, Label xlabel="", Label ylabel="",
7054          bool extend=true,
7055          pair min=(-infinity,-infinity), pair max=(infinity,infinity),
7056          pen p=currentpen, arrowbar arrow=None, bool above=false);
7057@end verbatim
7058This convenience routine draws both @math{x} and @math{y} axes
7059on picture @code{pic} from @code{min} to @code{max},
7060with optional labels @code{xlabel} and @code{ylabel}
7061and any arrows specified by @code{arrow}. The axes are drawn on top of
7062existing objects in @code{pic} only if @code{above=true}.
7063
7064@item
7065@verbatim
7066void axis(picture pic=currentpicture, Label L="", path g,
7067          pen p=currentpen, ticks ticks, ticklocate locate,
7068          arrowbar arrow=None, int[] divisor=new int[],
7069          bool above=false, bool opposite=false);
7070@end verbatim
7071
7072This routine can be used to draw on picture @code{pic} a general axis
7073based on an arbitrary path @code{g}, using pen @code{p}.
7074One can optionally label the axis with Label @code{L} and add an arrow
7075@code{arrow}. The tick type is given by @code{ticks}.
7076The optional integer array @code{divisor} specifies what tick divisors
7077to try in the attempt to produce uncrowded tick labels. A @code{true}
7078value for the flag @code{opposite} identifies an unlabelled secondary
7079axis (typically drawn opposite a primary axis). The axis is drawn before
7080any existing objects in @code{pic} unless @code{above=true}.
7081The tick locator @code{ticklocate} is constructed by the routine
7082@verbatim
7083ticklocate ticklocate(real a, real b, autoscaleT S=defaultS,
7084                      real tickmin=-infinity, real tickmax=infinity,
7085                      real time(real)=null, pair dir(real)=zero);
7086@end verbatim
7087@noindent
7088where @code{a} and @code{b} specify the respective tick values at
7089@code{point(g,0)} and @code{point(g,length(g))}, @code{S} specifies
7090the autoscaling transformation, the function @code{real time(real v)}
7091returns the time corresponding to the value @code{v}, and
7092@code{pair dir(real t)} returns the absolute tick direction as a
7093function of @code{t} (zero means draw the tick perpendicular to the axis).
7094
7095@item These routines are useful for manually putting ticks and labels on axes
7096(if the variable @code{Label} is given as the @code{Label}
7097argument, the @code{format} argument will be used to format a string based on
7098the tick location):
7099@cindex xtick
7100@cindex ytick
7101@cindex labelx
7102@cindex labely
7103@cindex tick
7104@cindex Label
7105@verbatim
7106void xtick(picture pic=currentpicture, Label L="", explicit pair z,
7107           pair dir=N, string format="",
7108           real size=Ticksize, pen p=currentpen);
7109void xtick(picture pic=currentpicture, Label L="", real x,
7110           pair dir=N, string format="",
7111           real size=Ticksize, pen p=currentpen);
7112void ytick(picture pic=currentpicture, Label L="", explicit pair z,
7113           pair dir=E, string format="",
7114           real size=Ticksize, pen p=currentpen);
7115void ytick(picture pic=currentpicture, Label L="", real y,
7116           pair dir=E, string format="",
7117           real size=Ticksize, pen p=currentpen);
7118void tick(picture pic=currentpicture, pair z,
7119          pair dir, real size=Ticksize, pen p=currentpen);
7120void labelx(picture pic=currentpicture, Label L="", explicit pair z,
7121            align align=S, string format="", pen p=currentpen);
7122void labelx(picture pic=currentpicture, Label L="", real x,
7123            align align=S, string format="", pen p=currentpen);
7124void labelx(picture pic=currentpicture, Label L,
7125            string format="", explicit pen p=currentpen);
7126void labely(picture pic=currentpicture, Label L="", explicit pair z,
7127            align align=W, string format="", pen p=currentpen);
7128void labely(picture pic=currentpicture, Label L="", real y,
7129            align align=W, string format="", pen p=currentpen);
7130void labely(picture pic=currentpicture, Label L,
7131            string format="", explicit pen p=currentpen);
7132@end verbatim
7133@end itemize
7134
7135Here are some simple examples of two-dimensional graphs:
7136
7137@enumerate
7138
7139@cindex textbook graph
7140@item This example draws a textbook-style graph of
7141@math{y=} exp@math{(x)}, with the @math{y} axis starting at @math{y=0}:
7142@verbatiminclude exp.asy
7143@sp 1
7144@center @image{exp}
7145
7146
7147@item The next example draws a scientific-style graph with a legend.
7148The position of the legend can be adjusted either explicitly or by using the
7149graphical user interface @code{xasy} (@pxref{GUI}). If an
7150@code{UnFill(real xmargin=0, real ymargin=xmargin)} or
7151@code{Fill(pen)} option is specified to @code{add}, the legend will obscure
7152any underlying objects. Here we illustrate how to clip the portion of
7153the picture covered by a label:
7154
7155@cindex scientific graph
7156@verbatiminclude lineargraph0.asy
7157@sp 1
7158@center @image{lineargraph0}
7159
7160@cindex @code{attach}
7161To specify a fixed size for the graph proper, use @code{attach}:
7162@verbatiminclude lineargraph.asy
7163
7164@cindex @code{legend}
7165A legend can have multiple entries per line:
7166@verbatiminclude legend.asy
7167@sp 1
7168@center @image{legend}
7169
7170@item This example draws a graph of one array versus another (both of
7171the same size) using custom tick locations and a smaller font size for
7172the tick labels on the @math{y} axis.
7173@verbatiminclude datagraph.asy
7174@sp 1
7175@center @image{datagraph}
7176
7177@item This example shows how to graph columns of data read from a file.
7178@verbatiminclude filegraph.asy
7179@sp 1
7180@center @image{filegraph}
7181
7182@cindex @code{polygon}
7183@cindex @code{cross}
7184@cindex @code{errorbars}
7185@cindex @code{marker}
7186@cindex @code{marknodes}
7187@cindex @code{markuniform}
7188@cindex @code{mark}
7189@cindex path markers
7190@anchor{pathmarkers}
7191@item The next example draws two graphs of an array of coordinate pairs,
7192using frame alignment and data markers. In the left-hand graph, the
7193markers, constructed with
7194@verbatim
7195marker marker(path g, markroutine markroutine=marknodes,
7196              pen p=currentpen, filltype filltype=NoFill,
7197              bool above=true);
7198@end verbatim
7199using the path @code{unitcircle} (@pxref{filltype}), are drawn
7200below each node. Any frame can be converted to a marker, using
7201@anchor{marker}
7202@verbatim
7203marker marker(frame f, markroutine markroutine=marknodes,
7204              bool above=true);
7205@end verbatim
7206In the right-hand graph, the unit @math{n}-sided regular polygon
7207@code{polygon(int n)} and the unit @math{n}-point cyclic cross
7208@code{cross(int n, bool round=true, real r=0)} (where @code{r} is an
7209optional ``inner'' radius) are used to build a custom marker frame.
7210@anchor{markuniform}
7211Here @code{markuniform(bool centered=false, int n, bool rotated=false)}
7212adds this frame at @code{n} uniformly spaced points along the arclength
7213of the path, optionally rotated by the angle of the local tangent to the path
7214(if centered is true, the frames will be centered within @code{n} evenly
7215spaced arclength intervals). Alternatively, one can use
7216markroutine @code{marknodes} to request that the marks be placed at each
7217Bezier node of the path, or
7218markroutine @code{markuniform(pair z(real t), real a, real b, int n)}
7219to place marks at points @code{z(t)} for n evenly spaced values of
7220@code{t} in @code{[a,b]}.
7221
7222These markers are predefined:
7223@verbatim
7224marker[] Mark={
7225  marker(scale(circlescale)*unitcircle),
7226  marker(polygon(3)),marker(polygon(4)),
7227  marker(polygon(5)),marker(invert*polygon(3)),
7228  marker(cross(4)),marker(cross(6))
7229};
7230
7231marker[] MarkFill={
7232  marker(scale(circlescale)*unitcircle,Fill),marker(polygon(3),Fill),
7233  marker(polygon(4),Fill),marker(polygon(5),Fill),
7234  marker(invert*polygon(3),Fill)
7235};
7236@end verbatim
7237
7238The example also illustrates the @code{errorbar} routines:
7239
7240@verbatim
7241void errorbars(picture pic=currentpicture, pair[] z, pair[] dp,
7242               pair[] dm={}, bool[] cond={}, pen p=currentpen,
7243               real size=0);
7244
7245void errorbars(picture pic=currentpicture, real[] x, real[] y,
7246               real[] dpx, real[] dpy, real[] dmx={}, real[] dmy={},
7247               bool[] cond={}, pen p=currentpen, real size=0);
7248@end verbatim
7249
7250@noindent
7251Here, the positive and negative extents of the error are given by the
7252absolute values of the elements of the pair array @code{dp} and the
7253optional pair array @code{dm}. If @code{dm} is not specified, the
7254positive and negative extents of the error are assumed to be equal.
7255@anchor{errorbars}
7256@cindex error bars
7257@verbatiminclude errorbars.asy
7258@sp 1
7259@center @image{errorbars}
7260
7261@cindex custom mark routine
7262@item A custom mark routine can be also be specified:
7263@verbatiminclude graphmarkers.asy
7264@sp 1
7265@center @image{graphmarkers}
7266
7267@item This example shows how to label an axis with arbitrary strings.
7268@verbatiminclude monthaxis.asy
7269@sp 1
7270@center @image{monthaxis}
7271
7272@item The next example draws a graph of a parametrized curve.
7273@cindex parametrized curve
7274@cindex cropping graphs
7275@cindex @code{xlimits}
7276@cindex @code{ylimits}
7277@cindex @code{limits}
7278@cindex @code{crop}
7279The calls to
7280@verbatim
7281xlimits(picture pic=currentpicture, real min=-infinity,
7282        real max=infinity, bool crop=NoCrop);
7283@end verbatim
7284@noindent
7285and the analogous function @code{ylimits} can be uncommented
7286to set the respective axes limits for picture @code{pic} to the
7287specified @code{min} and @code{max} values. Alternatively, the function
7288@verbatim
7289void limits(picture pic=currentpicture, pair min, pair max, bool crop=NoCrop);
7290@end verbatim
7291can be used to limit the axes to the box having opposite vertices at
7292the given pairs). Existing objects in picture @code{pic} will be cropped to lie
7293within the given limits if @code{crop}=@code{Crop}. The function
7294@code{crop(picture pic)} can be used to crop a graph to the current
7295graph limits.
7296@verbatiminclude parametricgraph.asy
7297@sp 1
7298@center @image{parametricgraph}
7299
7300@cindex scaled graph
7301The next example illustrates how one can extract a common axis scaling
7302factor.
7303@verbatiminclude scaledgraph.asy
7304@sp 1
7305@center @image{scaledgraph}
7306
7307@anchor{automatic scaling}
7308@cindex automatic scaling
7309@cindex @code{scale}
7310@cindex @code{Linear}
7311@cindex @code{Log}
7312@cindex automatic scaling
7313Axis scaling can be requested and/or automatic selection of the
7314axis limits can be inhibited with one of these @code{scale} routines:
7315@verbatim
7316void scale(picture pic=currentpicture, scaleT x, scaleT y);
7317
7318void scale(picture pic=currentpicture, bool xautoscale=true,
7319           bool yautoscale=xautoscale, bool zautoscale=yautoscale);
7320@end verbatim
7321
7322This sets the scalings for picture @code{pic}. The @code{graph} routines
7323accept an optional @code{picture} argument for determining the appropriate
7324scalings to use; if none is given, it uses those set for
7325@code{currentpicture}.
7326
7327Two frequently used scaling routines
7328@code{Linear} and @code{Log} are predefined in @code{graph}.
7329
7330All picture coordinates (including those in paths and those given
7331to the @code{label} and @code{limits} functions) are always treated as linear
7332(post-scaled) coordinates. Use
7333@cindex @code{Scale}
7334@verbatim
7335pair Scale(picture pic=currentpicture, pair z);
7336@end verbatim
7337to convert a graph coordinate into a scaled picture coordinate.
7338
7339The @math{x} and @math{y} components can be individually scaled using
7340the analogous routines
7341@verbatim
7342real ScaleX(picture pic=currentpicture, real x);
7343real ScaleY(picture pic=currentpicture, real y);
7344@end verbatim
7345
7346The predefined scaling routines can be given two optional boolean arguments:
7347@code{automin=false} and @code{automax=automin}. These default to
7348@code{false} but can be respectively set to @code{true} to enable
7349automatic selection of "nice" axis minimum and maximum values. The
7350@code{Linear} scaling can also take as optional final arguments a
7351multiplicative scaling factor and intercept (e.g.@ for a depth axis,
7352@code{Linear(-1)} requests axis reversal).
7353
7354@cindex logarithmic graph
7355@cindex log-log graph
7356For example, to draw a log/log graph of a function, use @code{scale(Log,Log)}:
7357@verbatiminclude loggraph.asy
7358@sp 1
7359@center @image{loggraph}
7360
7361@cindex grid
7362By extending the ticks, one can easily produce a logarithmic grid:
7363@verbatiminclude loggrid.asy
7364
7365@sp 1
7366@center @image{loggrid}
7367
7368One can also specify custom tick locations and formats for logarithmic axes:
7369@verbatiminclude logticks.asy
7370@sp 1
7371@center @image{logticks}
7372
7373@cindex @code{log2} graph
7374It is easy to draw logarithmic graphs with respect to other bases:
7375@verbatiminclude log2graph.asy
7376@sp 1
7377@center @image{log2graph}
7378
7379@cindex broken axis
7380Here is an example of "broken" linear @math{x} and logarithmic
7381@math{y} axes that omit the segments [3,8] and [100,1000], respectively.
7382In the case of a logarithmic axis, the break endpoints are automatically
7383rounded to the nearest integral power of the base.
7384@verbatiminclude brokenaxis.asy
7385@sp 1
7386@center @image{brokenaxis}
7387
7388@cindex secondary axis
7389@cindex @code{secondaryX}
7390@cindex @code{secondaryY}
7391@item @code{Asymptote} can draw secondary axes with the routines
7392@verbatim
7393picture secondaryX(picture primary=currentpicture, void f(picture));
7394picture secondaryY(picture primary=currentpicture, void f(picture));
7395@end verbatim
7396
7397In this example, @code{secondaryY} is used to draw a secondary linear
7398@math{y} axis against a primary logarithmic @math{y} axis:
7399@verbatiminclude Bode.asy
7400@sp 1
7401@center @image{Bode}
7402
7403A secondary logarithmic @math{y} axis can be drawn like this:
7404@verbatiminclude secondaryaxis.asy
7405@sp 1
7406@center @image{secondaryaxis}
7407
7408@item Here is a histogram example, which uses the @code{stats} module.
7409@cindex @code{axis}
7410@verbatiminclude histogram.asy
7411@sp 1
7412@center @image{histogram}
7413
7414@item Here is an example of reading column data in from a file and a
7415least-squares fit, using the @code{stats} module.
7416@cindex @code{leastsquares}
7417@verbatiminclude leastsquares.asy
7418@sp 1
7419@center @image{leastsquares}
7420
7421@item Here is an example that illustrates the general @code{axis} routine.
7422@cindex @code{axis}
7423@verbatiminclude generalaxis.asy
7424@sp 1
7425@center @image{generalaxis}
7426
7427@item To draw a vector field of @code{n} arrows evenly spaced along
7428the arclength of a path, use the routine
7429@cindex @code{vectorfield}
7430@verbatim
7431picture vectorfield(path vector(real), path g, int n, bool truesize=false,
7432                    pen p=currentpen, arrowbar arrow=Arrow);
7433@end verbatim
7434as illustrated in this simple example of a flow field:
7435@verbatiminclude flow.asy
7436@sp 1
7437@center @image{flow}
7438
7439@item To draw a vector field of @code{nx}@math{\times}@code{ny} arrows
7440in @code{box(a,b)}, use the routine
7441@cindex @code{vectorfield}
7442@verbatim
7443picture vectorfield(path vector(pair), pair a, pair b,
7444                    int nx=nmesh, int ny=nx, bool truesize=false,
7445                    real maxlength=truesize ? 0 : maxlength(a,b,nx,ny),
7446                    bool cond(pair z)=null, pen p=currentpen,
7447                    arrowbar arrow=Arrow, margin margin=PenMargin)
7448@end verbatim
7449as illustrated in this example:
7450@verbatiminclude vectorfield.asy
7451@sp 1
7452@center @image{vectorfield}
7453
7454@item The following scientific graphs, which illustrate many features of
7455@code{Asymptote}'s graphics routines, were generated from the examples
7456@code{diatom.asy} and @code{westnile.asy}, using the comma-separated
7457data in @code{diatom.csv} and @code{westnile.csv}.
7458@page
7459
7460@sp 1
7461@center @image{diatom}
7462@sp 1
7463@center @image{westnile,,7.5cm}
7464@end enumerate
7465
7466@page
7467@node palette
7468@section @code{palette}
7469@anchor{images}
7470@cindex images
7471@code{Asymptote} can also generate color density images
7472and palettes. The following palettes are predefined in
7473@code{palette.asy}:
7474
7475@table @code
7476
7477@cindex @code{Grayscale}
7478@item pen[] Grayscale(int NColors=256)
7479a grayscale palette;
7480
7481@cindex @code{Rainbow}
7482@item pen[] Rainbow(int NColors=32766)
7483a rainbow spectrum;
7484
7485@cindex @code{BWRainbow}
7486@item pen[] BWRainbow(int NColors=32761)
7487a rainbow spectrum tapering off to black/white at the ends;
7488
7489@cindex @code{BWRainbow2}
7490@item pen[] BWRainbow2(int NColors=32761)
7491a double rainbow palette tapering off to black/white at the ends, with
7492a linearly scaled intensity.
7493
7494@cindex @code{Wheel}
7495@item pen[] Wheel(int NColors=32766)
7496a full color wheel palette;
7497
7498@cindex @code{Gradient}
7499@item pen[] Gradient(int NColors=256 ... pen[] p)
7500a palette varying linearly over the specified array of pens, using
7501NColors in each interpolation interval;
7502
7503@end table
7504
7505The function @code{cmyk(pen[] Palette)} may be used to convert any
7506of these palettes to the @acronym{CMYK} colorspace.
7507
7508A color density plot using palette @code{palette} can be generated from
7509a function @code{f}(@math{x},@math{y}) and added to a picture @code{pic}:
7510@cindex @code{image}
7511@verbatim
7512bounds image(picture pic=currentpicture, real f(real, real),
7513             range range=Full, pair initial, pair final,
7514             int nx=ngraph, int ny=nx, pen[] palette, bool antialias=false)
7515@end verbatim
7516The function @code{f} will be sampled at @code{nx} and @code{ny}
7517evenly spaced points over a rectangle defined by the points
7518@code{initial} and @code{final}, respecting the current graphical
7519scaling of @code{pic}. The color space is scaled according to the
7520@math{z} axis scaling (@pxref{automatic scaling}). A bounds structure
7521for the function values is returned:
7522@verbatim
7523struct bounds {
7524  real min;
7525  real max;
7526  // Possible tick intervals:
7527  int[] divisor;
7528}
7529@end verbatim
7530@noindent
7531This information can be used for generating an optional palette bar.
7532The palette color space corresponds to a range of values specified by
7533the argument @code{range}, which can be @code{Full}, @code{Automatic},
7534or an explicit range @code{Range(real min, real max)}.
7535Here @code{Full} specifies a range varying from the
7536minimum to maximum values of the function over the sampling interval,
7537while @code{Automatic} selects "nice" limits.
7538The example @code{imagecontour.asy} illustrates how level sets
7539(contour lines) can be drawn on a color density plot (@pxref{contour}).
7540
7541A color density plot can also be generated from an explicit real[][]
7542array @code{data}:
7543@cindex @code{image}
7544@verbatim
7545bounds image(picture pic=currentpicture, real[][] f, range range=Full,
7546             pair initial, pair final, pen[] palette,
7547             bool transpose=(initial.x < final.x && initial.y < final.y),
7548             bool copy=true, bool antialias=false);
7549@end verbatim
7550@noindent
7551If the initial point is to the left and below the final point,
7552by default the array indices are interpreted according to the
7553Cartesian convention (first index: @math{x}, second index: @math{y})
7554rather than the usual matrix convention (first index: @math{-y},
7555second index: @math{x}).
7556
7557To construct an image from an array of irregularly spaced points
7558and an array of values @code{f} at these points, use one of the routines
7559@verbatim
7560bounds image(picture pic=currentpicture, pair[] z, real[] f,
7561             range range=Full, pen[] palette)
7562bounds image(picture pic=currentpicture, real[] x, real[] y, real[] f,
7563             range range=Full, pen[] palette)
7564@end verbatim
7565
7566An optionally labelled palette bar may be generated with the routine
7567@verbatim
7568void palette(picture pic=currentpicture, Label L="", bounds bounds,
7569             pair initial, pair final, axis axis=Right, pen[] palette,
7570             pen p=currentpen, paletteticks ticks=PaletteTicks,
7571             bool copy=true, bool antialias=false);
7572@end verbatim
7573The color space of @code{palette} is taken to be over bounds @code{bounds} with
7574scaling given by the @math{z} scaling of @code{pic}.
7575The palette orientation is specified by @code{axis}, which may be one of
7576@code{Right}, @code{Left}, @code{Top}, or @code{Bottom}.
7577The bar is drawn over the rectangle from @code{initial} to @code{final}.
7578The argument @code{paletteticks} is a special tick type (@pxref{ticks})
7579that takes the following arguments:
7580@verbatim
7581paletteticks PaletteTicks(Label format="", ticklabel ticklabel=null,
7582                          bool beginlabel=true, bool endlabel=true,
7583                          int N=0, int n=0, real Step=0, real step=0,
7584                          pen pTick=nullpen, pen ptick=nullpen);
7585@end verbatim
7586
7587The image and palette bar can be fit to a frame and added and
7588optionally aligned to a picture at the desired location:
7589
7590@anchor{image}
7591@verbatiminclude image.asy
7592@sp 1
7593@center @image{image}
7594
7595Here is an example that uses logarithmic scaling of the function values:
7596
7597@anchor{logimage}
7598@verbatiminclude logimage.asy
7599@sp 1
7600@center @image{logimage}
7601
7602One can also draw an image directly from a two-dimensional pen array
7603or a function @code{pen f(int, int)}:
7604@verbatim
7605void image(picture pic=currentpicture, pen[][] data,
7606           pair initial, pair final,
7607           bool transpose=(initial.x < final.x && initial.y < final.y),
7608           bool copy=true, bool antialias=false);
7609void image(picture pic=currentpicture, pen f(int, int), int width, int height,
7610           pair initial, pair final,
7611           bool transpose=(initial.x < final.x && initial.y < final.y),
7612           bool antialias=false);
7613@end verbatim
7614@noindent
7615as illustrated in the following examples:
7616
7617@anchor{penimage}
7618@verbatiminclude penimage.asy
7619@sp 1
7620@center @image{penimage}
7621
7622@anchor{penfunctionimage}
7623@verbatiminclude penfunctionimage.asy
7624@sp 1
7625@center @image{penfunctionimage}
7626
7627For convenience, the module @code{palette} also defines functions
7628that may be used to construct a pen array from a given function and palette:
7629@verbatim
7630pen[] palette(real[] f, pen[] palette);
7631pen[][] palette(real[][] f, pen[] palette);
7632@end verbatim
7633
7634@node three
7635@section @code{three}
7636@cindex @code{three}
7637@cindex @code{guide3}
7638@cindex @code{path3}
7639@cindex @code{cycle}
7640@cindex @code{curl}
7641@cindex @code{tension}
7642@cindex @code{controls}
7643This module fully extends the notion of guides and paths in @code{Asymptote}
7644to three dimensions. It introduces the new types guide3, path3, and surface.
7645Guides in three dimensions are specified with the same syntax as in two
7646dimensions except that triples @code{(x,y,z)} are used in place of pairs
7647@code{(x,y)} for the nodes and direction specifiers.  This
7648generalization of John Hobby's spline algorithm is shape-invariant under
7649three-dimensional rotation, scaling, and shifting, and reduces in the
7650planar case to the two-dimensional algorithm used in @code{Asymptote},
7651@code{MetaPost}, and @code{MetaFont} [cf.@ J. C. Bowman, Proceedings in
7652Applied Mathematics and Mechanics, 7:1, 2010021-2010022 (2007)].
7653
7654For example, a unit circle in the @math{XY} plane may be filled and
7655drawn like this:
7656@verbatiminclude unitcircle3.asy
7657@sp 1
7658@center @image{unitcircle3}
7659@noindent
7660and then distorted into a saddle:
7661@verbatiminclude saddle.asy
7662@sp 1
7663@center @image{saddle}
7664@noindent
7665
7666Module @code{three} provides constructors for converting two-dimensional
7667paths to three-dimensional ones, and vice-versa:
7668@cindex @code{path3}
7669@cindex @code{path}
7670@verbatim
7671path3 path3(path p, triple plane(pair)=XYplane);
7672path path(path3 p, pair P(triple)=xypart);
7673@end verbatim
7674
7675@cindex @code{surface}
7676@cindex @code{render}
7677@cindex @code{defaultrender}
7678A Bezier surface, the natural two-dimensional generalization of Bezier
7679curves, is defined in @code{three_surface.asy} as a structure
7680containing an array of Bezier patches. Surfaces may drawn with one of
7681the routines
7682@verbatim
7683void draw(picture pic=currentpicture, surface s, int nu=1, int nv=1,
7684          material surfacepen=currentpen, pen meshpen=nullpen,
7685          light light=currentlight, light meshlight=nolight, string name="",
7686          render render=defaultrender);
7687void draw(picture pic=currentpicture, surface s, int nu=1, int nv=1,
7688          material[] surfacepen, pen meshpen,
7689          light light=currentlight, light meshlight=nolight, string name="",
7690          render render=defaultrender);
7691void draw(picture pic=currentpicture, surface s, int nu=1, int nv=1,
7692          material[] surfacepen, pen[] meshpen=nullpens,
7693          light light=currentlight, light meshlight=nolight, string name="",
7694          render render=defaultrender);
7695
7696@end verbatim
7697The parameters @code{nu} and @code{nv} specify the number of subdivisions
7698for drawing optional mesh lines for each Bezier patch. The optional
7699@code{name} parameter is used as a prefix for naming the surface
7700patches in the @acronym{PRC} model tree.
7701Here material is a structure defined in @code{three_light.asy}:
7702@verbatim
7703struct material {
7704  pen[] p; // diffusepen,ambientpen,emissivepen,specularpen
7705  real opacity;
7706  real shininess;
7707...
7708}
7709@end verbatim
7710@noindent
7711These material properties are used to implement @code{OpenGL}-style lighting,
7712based on the Phong-Blinn specular model. Sample Bezier surfaces are
7713contained in the example files @code{BezierSurface.asy}, @code{teapot.asy},
7714and @code{parametricsurface.asy}. The structure @code{render} contains
7715specialized rendering options documented at the beginning of module
7716@code{three.asy}.
7717
7718@cindex patch-dependent colors
7719@cindex vertex-dependent colors
7720The examples
7721@code{elevation.asy} and @code{sphericalharmonic.asy}
7722illustrate how to draw a surface with patch-dependent colors.
7723The examples @code{vertexshading} and @code{smoothelevation} illustrate
7724vertex-dependent colors, which is supported for both
7725@code{Asymptote}'s native @code{OpenGL} renderer and two-dimensional
7726projections. Since the @acronym{PRC} output format does not currently support
7727vertex shading of Bezier surfaces, @acronym{PRC} patches are shaded
7728with the mean of the four vertex colors.
7729
7730@cindex @code{surface}
7731@cindex @code{planar}
7732A surface can be constructed from a cyclic @code{path3} with the constructor
7733@verbatim
7734surface surface(path3 external, triple[] internal=new triple[],
7735                triple[] normals=new triple[], pen[] colors=new pen[],
7736                bool3 planar=default);
7737@end verbatim
7738@noindent
7739and then filled:
7740@verbatim
7741draw(surface(path3(polygon(5))),red,nolight);
7742draw(surface(unitcircle3),red,nolight);
7743draw(surface(unitcircle3,new pen[] {red,green,blue,black}),nolight);
7744@end verbatim
7745@noindent
7746The last example constructs a patch with vertex-specific colors.
7747A three-dimensional planar surface in the plane @code{plane} can be
7748constructed from a two-dimensional cyclic path @code{g} with the constructor
7749@cindex @code{surface}
7750@verbatim
7751surface surface(path p, triple plane(pair)=XYplane);
7752@end verbatim
7753@noindent
7754and then filled:
7755@verbatim
7756draw(surface((0,0)--E+2N--2E--E+N..0.2E..cycle),red);
7757@end verbatim
7758@noindent
7759@cindex @code{bezulate}
7760Planar Bezier surfaces patches are constructed using Orest Shardt's
7761@code{bezulate} routine, which decomposes (possibly nonsimply
7762connected) regions bounded (according to the @code{zerowinding} fill rule)
7763by simple cyclic paths (intersecting only at the endpoints)
7764into subregions bounded by cyclic paths of length @code{4} or less.
7765
7766A more efficient routine also exists for drawing tessellations
7767composed of many 3D triangles, with specified vertices, and optional
7768normals or vertex colors:
7769@cindex @code{draw}
7770@cindex @code{triangles}
7771@cindex @code{tessellation}
7772@verbatim
7773void draw(picture pic=currentpicture, triple[] v, int[][] vi,
7774          triple[] n={}, int[][] ni={}, material m=currentpen, pen[] p={},
7775          int[][] pi={}, light light=currentlight);
7776@end verbatim
7777Here, the triple array @code{v} lists the distinct vertices, while
7778the array @code{vi} lists integer arrays of length 3 containing
7779the indices of @code{v} corresponding to the vertices of each
7780triangle. Similarly, the arguments @code{n} and @code{ni} contain
7781optional normal data and @code{p} and @code{pi} contain optional pen vertex data.
7782An example of this tessellation facility is given in @code{triangles.asy}.
7783
7784@cindex @code{thin}
7785@cindex @code{thick}
7786@cindex @code{tube}
7787Arbitrary thick three-dimensional curves and line caps (which the
7788@code{OpenGL} standard does not require implementations to provide) are
7789constructed with
7790@verbatim
7791tube tube(path3 p, real width, render render=defaultrender);
7792@end verbatim
7793@noindent
7794this returns a tube structure representing a tube of diameter @code{width}
7795centered approximately on @code{g}. The tube structure consists of a
7796surface @code{s} and the actual tube center, path3 @code{center}.
7797Drawing thick lines as tubes can be slow to render,
7798especially with the @code{Adobe Reader} renderer. The setting
7799@code{thick=false} can be used to disable this feature and force all
7800lines to be drawn with @code{linewidth(0)} (one pixel wide, regardless
7801of the resolution). By default, mesh and contour lines in three-dimensions
7802are always drawn thin, unless an explicit line width is given in the pen
7803parameter or the setting @code{thin} is set to @code{false}. The pens
7804@code{thin()} and @code{thick()} defined in plain_pens.asy can also be used
7805to override these defaults for specific draw commands.
7806
7807@noindent
7808There are four choices for viewing 3D @code{Asymptote} output:
7809@enumerate
7810@cindex @code{OpenGL}
7811@cindex @code{render}
7812@cindex @code{outformat}
7813@cindex @code{multisample}
7814@item Use the native @code{Asymptote} adaptive @code{OpenGL}-based
7815renderer (with the command-line option @code{-V} and the default settings
7816@code{outformat=""} and @code{render=-1}). If you encounter warnings
7817from your graphics card driver, try specifying @code{-glOptions=-indirect}
7818on the command line. On @code{UNIX} systems with graphics support for
7819multisampling, the sample width can be
7820controlled with the setting @code{multisample}. An initial screen
7821position can be specified with the pair setting @code{position}, where
7822negative values are interpreted as relative to the corresponding
7823maximum screen dimension. The default settings
7824@cindex mouse bindings
7825@verbatim
7826import settings;
7827leftbutton=new string[] {"rotate","zoom","shift","pan"};
7828middlebutton=new string[] {"menu"};
7829rightbutton=new string[] {"zoom/menu","rotateX","rotateY","rotateZ"};
7830wheelup=new string[] {"zoomin"};
7831wheeldown=new string[] {"zoomout"};
7832@end verbatim
7833bind the mouse buttons as follows:
7834@itemize
7835@item Left: rotate
7836@item Shift Left: zoom
7837@item Ctrl Left: shift viewport
7838@item Alt Left: pan
7839@item Middle: menu (must be unmodified; ignores Shift, Ctrl, and Alt)
7840@item Wheel Up: zoom in
7841@item Wheel Down: zoom out
7842@item Right: zoom/menu (must be unmodified)
7843@item Right double click: menu
7844@item Shift Right: rotate about the X axis
7845@item Ctrl Right: rotate about the Y axis
7846@item Alt Right: rotate about the Z axis
7847@end itemize
7848
7849The keyboard shortcuts are:
7850@cindex keyboard bindings:
7851@itemize
7852@item h: home
7853@item f: toggle fitscreen
7854@item x: spin about the X axis
7855@item y: spin about the Y axis
7856@item z: spin about the Z axis
7857@item s: stop spinning
7858@item m: rendering mode (solid/mesh/patch)
7859@item e: export
7860@item c: show camera parameters
7861@item p: play animation
7862@item r: reverse animation
7863@item  : step animation
7864@item +: expand
7865@item =: expand
7866@item >: expand
7867@item -: shrink
7868@item _: shrink
7869@item <: shrink
7870@item q: exit
7871@item Ctrl-q: exit
7872@end itemize
7873
7874@cindex @code{antialias}
7875@cindex @code{maxviewport}
7876@cindex @code{maxtile}
7877@cindex @code{glOptions}
7878@cindex @code{iconic}
7879@cindex @code{black stripes}
7880@item Render the scene to a specified rasterized format @code{outformat}
7881at the resolution of @code{n} pixels per @code{bp}, as specified by the
7882setting @code{render=n}. A negative value of @code{n} is interpreted
7883as @code{|2n|} for @acronym{EPS} and @acronym{PDF} formats and
7884@code{|n|} for other formats. The default value of @code{render} is -1.
7885By default, the scene is internally rendered at twice the specified
7886resolution; this can be disabled by setting @code{antialias=1}.
7887High resolution rendering is done by tiling the image. If your
7888graphics card allows it, the rendering can be made more efficient by
7889increasing the maximum tile size @code{maxtile} to your screen
7890dimensions (indicated by @code{maxtile=(0,0)}. If your video card
7891generates unwanted black stripes in the output, try setting the
7892horizontal and vertical components of @code{maxtiles} to something
7893less than your screen dimensions. The tile size is also limited by the
7894setting @code{maxviewport}, which restricts the maximum width and
7895height of the viewport. On @code{UNIX} systems some graphics
7896drivers support batch mode (@code{-noV}) rendering in an
7897iconified window; this can be enabled with the setting @code{iconify=true}.
7898Some (broken) @code{UNIX} graphics drivers may require the command line setting
7899@code{-glOptions=-indirect}, which requests (slower) indirect rendering.
7900
7901@cindex @code{prc}
7902@cindex @code{views}
7903@item Embed the 3D @acronym{PRC} format in a @acronym{PDF} file
7904and view the resulting @acronym{PDF} file with
7905version @code{9.0} or later of @code{Adobe Reader}.
7906In addition to the default @code{settings.prc=true}, this requires
7907@code{settings.outformat="pdf"}, which can be specified by the command
7908line option @code{-f pdf}, put in the @code{Asymptote} configuration
7909file (@pxref{configuration file}), or specified in the script before
7910@code{three.asy} (or @code{graph3.asy}) is imported.
7911The @code{media9} LaTeX package is also required (@pxref{embed}).
7912The example @code{pdb.asy} illustrates
7913how one can generate a list of predefined views (see @code{100d.views}).
7914A stationary preview image with a resolution of @code{n} pixels per
7915@code{bp} can be embedded with the setting @code{render=n}; this allows
7916the file to be viewed with other @code{PDF} viewers. Alternatively, the
7917file @code{externalprc.tex} illustrates how the resulting @acronym{PRC} and
7918rendered image files can be extracted and processed in a separate
7919@code{LaTeX} file. However, see @ref{LaTeX usage} for an easier way
7920to embed three-dimensional @code{Asymptote} pictures within @code{LaTeX}.
7921For specialized applications where only the raw @acronym{PRC} file is
7922required, specify @code{settings.outformat="prc"}.
7923The open-source @acronym{PRC} specification is available from
7924@url{http://livedocs.adobe.com/acrobat_sdk/9/Acrobat9_HTMLHelp/API_References/PRCReference/PRC_Format_Specification/}.
7925
7926@item Project the scene to a two-dimensional vector (@acronym{EPS} or
7927@acronym{PDF}) format with @code{render=0}. Only limited hidden surface
7928removal facilities are currently available with this approach
7929(@pxref{PostScript3D}).
7930
7931@end enumerate
7932
7933@cindex @code{double deferred drawing}
7934Automatic picture sizing in three dimensions is accomplished with double
7935deferred drawing. The maximal desired dimensions of the scene in each of
7936the three dimensions can optionally be specified with the routine
7937@cindex @code{size3}
7938@verbatim
7939void size3(picture pic=currentpicture, real x, real y=x, real z=y,
7940          bool keepAspect=pic.keepAspect);
7941@end verbatim
7942@noindent
7943@cindex margins
7944@cindex @code{viewportmargin}
7945@cindex @code{viewportsize}
7946The resulting simplex linear programming problem is then solved to
7947produce a 3D version of a frame (actually implemented as a 3D picture).
7948The result is then fit with another application of deferred drawing
7949to the viewport dimensions corresponding to the usual two-dimensional
7950picture @code{size} parameters. The global pair @code{viewportmargin}
7951may be used to add horizontal and vertical margins to the viewport
7952dimensions. Alternatively, a minimum @code{viewportsize} may be specified.
7953A 3D picture @code{pic} can be explicitly fit to a 3D frame by calling
7954@cindex @code{fit3}
7955@verbatim
7956frame pic.fit3(projection P=currentprojection);
7957@end verbatim
7958@noindent
7959and then added to picture @code{dest} about @code{position} with
7960@cindex @code{add}
7961@verbatim
7962void add(picture dest=currentpicture, frame src, triple position=(0,0,0));
7963@end verbatim
7964
7965@cindex @code{O}
7966@cindex @code{X}
7967@cindex @code{Y}
7968@cindex @code{Z}
7969@cindex @code{unitcircle}
7970For convenience, the @code{three} module defines @code{O=(0,0,0)},
7971@code{X=(1,0,0)}, @code{Y=(0,1,0)}, and @code{Z=(0,0,1)}, along with a
7972unitcircle in the XY plane:
7973@verbatim
7974path3 unitcircle3=X..Y..-X..-Y..cycle;
7975@end verbatim
7976
7977@cindex @code{circle}
7978A general (approximate) circle can be drawn perpendicular to the direction
7979@code{normal} with the routine
7980@verbatim
7981path3 circle(triple c, real r, triple normal=Z);
7982@end verbatim
7983
7984@cindex @code{arc}
7985A circular arc centered at @code{c} with radius @code{r} from
7986@code{c+r*dir(theta1,phi1)} to @code{c+r*dir(theta2,phi2)},
7987drawing counterclockwise relative to the normal vector
7988@code{cross(dir(theta1,phi1),dir(theta2,phi2))} if @code{theta2 > theta1}
7989or if @code{theta2 == theta1} and @code{phi2 >= phi1}, can be constructed with
7990@verbatim
7991path3 arc(triple c, real r, real theta1, real phi1, real theta2, real phi2,
7992          triple normal=O);
7993@end verbatim
7994The normal must be explicitly specified if @code{c} and the endpoints
7995are colinear. If @code{r} < 0, the complementary arc of radius
7996@code{|r|} is constructed.
7997For convenience, an arc centered at @code{c} from triple @code{v1} to
7998@code{v2} (assuming @code{|v2-c|=|v1-c|}) in the direction CCW
7999(counter-clockwise) or CW (clockwise) may also be constructed with
8000@verbatim
8001path3 arc(triple c, triple v1, triple v2, triple normal=O,
8002          bool direction=CCW);
8003@end verbatim
8004@noindent
8005When high accuracy is needed, the routines @code{Circle} and
8006@code{Arc} defined in @code{graph3} may be used instead.
8007See @ref{GaussianSurface} for an example of a three-dimensional circular arc.
8008
8009@cindex @code{plane}
8010The representation @code{O--O+u--O+u+v--O+v--cycle}
8011of the plane passing through point @code{O} with normal
8012@code{cross(u,v)} is returned by
8013@verbatim
8014path3 plane(triple u, triple v, triple O=O);
8015@end verbatim
8016A three-dimensional box with opposite vertices at triples @code{v1}
8017and @code{v2} may be drawn with the function
8018@cindex @code{box}
8019@verbatim
8020path3[] box(triple v1, triple v2);
8021@end verbatim
8022@noindent
8023For example, a unit box is predefined as
8024@cindex @code{box}
8025@cindex @code{unitbox}
8026@verbatim
8027path3[] unitbox=box(O,(1,1,1));
8028@end verbatim
8029@code{Asymptote} also provides optimized definitions for the
8030three-dimensional paths @code{unitsquare3} and @code{unitcircle3},
8031along with the surfaces @code{unitdisk}, @code{unitplane}, @code{unitcube},
8032@code{unitcylinder}, @code{unitcone}, @code{unitsolidcone},
8033@code{unitfrustum(real t1, real t2)}, @code{unitsphere}, and
8034@code{unithemisphere}.
8035
8036@noindent
8037These projections to two dimensions are predefined:
8038@table @code
8039@item oblique
8040@item oblique(real angle)
8041@cindex @code{oblique}
8042@cindex @code{obliqueZ}
8043The point @code{(x,y,z)} is projected to @code{(x-0.5z,y-0.5z)}.
8044If an optional real argument is given, the
8045negative @math{z} axis is drawn at this angle in degrees.
8046The projection @code{obliqueZ} is a synonym for @code{oblique}.
8047
8048@item obliqueX
8049@item obliqueX(real angle)
8050@cindex @code{obliqueX}
8051The point @code{(x,y,z)} is projected to @code{(y-0.5x,z-0.5x)}.
8052If an optional real argument is given, the
8053negative @math{x} axis is drawn at this angle in degrees.
8054
8055@item obliqueY
8056@item obliqueY(real angle)
8057@cindex @code{obliqueY}
8058The point @code{(x,y,z)} is projected to @code{(x+0.5y,z+0.5y)}.
8059If an optional real argument is given, the
8060positive @math{y} axis is drawn at this angle in degrees.
8061
8062@cindex @code{orthographic}
8063@cindex @code{up}
8064@cindex @code{target}
8065@cindex @code{showtarget}
8066@cindex @code{center}
8067@item orthographic(triple camera, triple up=Z, triple target=O, @*@ @ @ @ @ @ @ @ @ @ @ @ @ real zoom=1, pair viewportshift=0, bool showtarget=true, @*@ @ @ @ @ @ @ @ @ @ @ @ @ bool center=false)
8068This projects from three to two dimensions using the view as seen at a point
8069infinitely far away in the direction @code{unit(camera)}, orienting the camera
8070so that, if possible, the vector @code{up} points upwards. Parallel
8071lines are projected to parallel lines. The bounding volume is expanded
8072to include @code{target} if @code{showtarget=true}.
8073If @code{center=true}, the target will be adjusted to the center of the
8074bounding volume.
8075
8076@item orthographic(real x, real y, real z, triple up=Z, triple target=O, @*@ @ @ @ @ @ @ @ @ @ @ @ @ real zoom=1, pair viewportshift=0, bool showtarget=true, @*@ @ @ @ @ @ @ @ @ @ @ @ @ bool center=false)
8077This is equivalent to
8078@verbatim
8079orthographic((x,y,z),up,target,zoom,viewportshift,showtarget,center)
8080@end verbatim
8081
8082The routine
8083@cindex @code{camera}
8084@verbatim
8085triple camera(real alpha, real beta);
8086@end verbatim
8087can be used to compute the camera position with the @math{x} axis below
8088the horizontal at angle @code{alpha}, the @math{y} axis below the horizontal
8089at angle @code{beta}, and the @math{z} axis up.
8090
8091@cindex @code{autoadjust}
8092@item perspective(triple camera, triple up=Z, triple target=O, @*@ @ @ @ @ @ @ @ @ @ @ @ real zoom=1, real angle=0, pair viewportshift=0, @*@ @ @ @ @ @ @ @ @ @ @ @ bool showtarget=true, bool autoadjust=true, @*@ @ @ @ @ @ @ @ @ @ @ @ bool center=autoadjust)
8093@cindex @code{perspective}
8094@cindex @code{NURBS}
8095This projects from three to two dimensions, taking account of
8096perspective, as seen from the location @code{camera} looking at @code{target},
8097orienting the camera so that, if possible, the vector @code{up} points upwards.
8098If @code{render=0}, projection of three-dimensional cubic Bezier splines
8099is implemented by approximating a two-dimensional nonuniform rational B-spline
8100(@acronym{NURBS}) with a two-dimensional Bezier curve containing
8101additional nodes and control points. If @code{autoadjust=true},
8102the camera will automatically be adjusted to lie outside the bounding volume
8103for all possible interactive rotations about @code{target}.
8104If @code{center=true}, the target will be adjusted to the center of the
8105bounding volume.
8106
8107@item perspective(real x, real y, real z, triple up=Z, triple target=O, @*@ @ @ @ @ @ @ @ @ @ @ @ real zoom=1, real angle=0, pair viewportshift=0, @*@ @ @ @ @ @ @ @ @ @ @ @ bool showtarget=true, bool autoadjust=true, @*@ @ @ @ @ @ @ @ @ @ @ @ bool center=autoadjust)
8108This is equivalent to
8109@verbatim
8110perspective((x,y,z),up,target,zoom,angle,viewportshift,showtarget,
8111            autoadjust,center)
8112@end verbatim
8113@end table
8114
8115@cindex @code{currentprojection}
8116@noindent
8117The default projection, @code{currentprojection}, is initially set to
8118@code{perspective(5,4,2)}.
8119
8120@cindex @code{LeftView}
8121@cindex @code{RightView}
8122@cindex @code{FrontView}
8123@cindex @code{BackView}
8124@cindex @code{BottomView}
8125@cindex @code{TopView}
8126We also define standard orthographic views used in technical drawing:
8127@verbatim
8128projection LeftView=orthographic(-X,showtarget=true);
8129projection RightView=orthographic(X,showtarget=true);
8130projection FrontView=orthographic(-Y,showtarget=true);
8131projection BackView=orthographic(Y,showtarget=true);
8132projection BottomView=orthographic(-Z,showtarget=true);
8133projection TopView=orthographic(Z,showtarget=true);
8134@end verbatim
8135@noindent
8136The function
8137@cindex @code{addViews}
8138@verbatim
8139void addViews(picture dest=currentpicture, picture src,
8140              projection[][] views=SixViewsUS,
8141              bool group=true, filltype filltype=NoFill);
8142@end verbatim
8143@noindent
8144adds to picture @code{dest} an array of views of picture @code{src}
8145using the layout projection[][] @code{views}. The default layout
8146@code{SixViewsUS} aligns the projection @code{FrontView} below
8147@code{TopView} and above @code{BottomView}, to the right of
8148@code{LeftView} and left of @code{RightView} and @code{BackView}.
8149The predefined layouts are:
8150@cindex @code{ThreeViewsUS}
8151@cindex @code{SixViewsUS}
8152@cindex @code{ThreeViewsFR}
8153@cindex @code{SixViewsFR}
8154@cindex @code{ThreeViews}
8155@cindex @code{SixViews}
8156@verbatim
8157projection[][] ThreeViewsUS={{TopView},
8158                             {FrontView,RightView}};
8159
8160projection[][] SixViewsUS={{null,TopView},
8161                           {LeftView,FrontView,RightView,BackView},
8162                           {null,BottomView}};
8163
8164projection[][] ThreeViewsFR={{RightView,FrontView},
8165                             {null,TopView}};
8166
8167projection[][] SixViewsFR={{null,BottomView},
8168                           {RightView,FrontView,LeftView,BackView},
8169                           {null,TopView}};
8170
8171projection[][] ThreeViews={{FrontView,TopView,RightView}};
8172
8173projection[][] SixViews={{FrontView,TopView,RightView},
8174                         {BackView,BottomView,LeftView}};
8175
8176@end verbatim
8177
8178A triple or path3 can be projected to a pair or path,
8179with @code{project(triple, projection P=currentprojection)} or
8180@code{project(path3, projection P=currentprojection)}.
8181
8182It is occasionally useful to be able to invert a projection, sending
8183a pair @code{z} onto the plane perpendicular to @code{normal} and passing
8184through @code{point}:
8185@cindex @code{invert}
8186@verbatim
8187triple invert(pair z, triple normal, triple point,
8188              projection P=currentprojection);
8189@end verbatim
8190@noindent
8191A pair @code{z} on the projection plane can be inverted to a triple
8192with the routine
8193@verbatim
8194triple invert(pair z, projection P=currentprojection);
8195@end verbatim
8196@noindent
8197A pair direction @code{dir} on the projection plane can be inverted to
8198a triple direction relative to a point @code{v} with the routine
8199@verbatim
8200triple invert(pair dir, triple v, projection P=currentprojection).
8201@end verbatim
8202
8203@cindex @code{transform3}
8204@cindex @code{identity4}
8205Three-dimensional objects may be transformed with one of the following
8206built-in transform3 types (the identity transformation is @code{identity4}):
8207
8208@table @code
8209@item shift(triple v)
8210@cindex @code{shift}
8211translates by the triple @code{v};
8212@item xscale3(real x)
8213@cindex @code{xscale3}
8214scales by @code{x} in the @math{x} direction;
8215@item yscale3(real y)
8216@cindex @code{yscale3}
8217scales by @code{y} in the @math{y} direction;
8218@item zscale3(real z)
8219@cindex @code{zscale3}
8220scales by @code{z} in the @math{z} direction;
8221@item scale3(real s)
8222@cindex @code{scale3}
8223scales by @code{s} in the @math{x}, @math{y}, and @math{z} directions;
8224@item scale(real x, real y, real z)
8225@cindex @code{scale}
8226scales by @code{x} in the @math{x} direction,
8227by @code{y} in the @math{y} direction, and by @code{z} in the @math{z}
8228direction;
8229@cindex @code{rotate}
8230@item rotate(real angle, triple v)
8231rotates by @code{angle} in degrees about an axis @code{v} through the origin;
8232@item rotate(real angle, triple u, triple v)
8233rotates by @code{angle} in degrees about the axis @code{u--v};
8234@item reflect(triple u, triple v, triple w)
8235reflects about the plane through @code{u}, @code{v}, and @code{w}.
8236@cindex @code{XY}
8237@end table
8238
8239When not multiplied on the left by a transform3, three-dimensional
8240@TeX{} Labels are drawn as Bezier surfaces directly on the projection plane:
8241@cindex @code{label}
8242@verbatim
8243void label(picture pic=currentpicture, Label L, triple position,
8244           align align=NoAlign, pen p=currentpen,
8245           light light=nolight, string name="",
8246           render render=defaultrender, interaction interaction=
8247           settings.autobillboard ? Billboard : Embedded)
8248@end verbatim
8249@noindent
8250@cindex @code{Billboard}
8251@cindex @code{Embedded}
8252The optional @code{name} parameter is used as a prefix for naming the label
8253patches in the @acronym{PRC} model tree.
8254The default interaction is @code{Billboard}, which means that labels
8255are rotated interactively so that they always face the camera.
8256The interaction @code{Embedded} means that the label interacts as a
8257normal @code{3D} surface, as illustrated in the example @code{billboard.asy}.
8258@cindex @code{transform}
8259@cindex @code{XY}
8260@cindex @code{YZ}
8261@cindex @code{ZX}
8262@cindex @code{YX}
8263@cindex @code{ZY}
8264@cindex @code{ZX}
8265Alternatively, a label can be transformed from the @code{XY} plane by an
8266explicit transform3 or mapped to a specified two-dimensional plane with
8267the predefined transform3 types @code{XY}, @code{YZ}, @code{ZX}, @code{YX},
8268@code{ZY}, @code{ZX}. There are also modified versions of these
8269transforms that take an optional argument @code{projection
8270P=currentprojection} that rotate and/or flip the label so that it is
8271more readable from the initial viewpoint.
8272
8273@cindex @code{planeproject}
8274A transform3 that projects in the direction @code{dir} onto the plane
8275with normal @code{n} through point @code{O} is returned by
8276@verbatim
8277transform3 planeproject(triple n, triple O=O, triple dir=n);
8278@end verbatim
8279@noindent
8280One can use
8281@cindex @code{normal}
8282@verbatim
8283triple normal(path3 p);
8284@end verbatim
8285@noindent
8286to find the unit normal vector to a planar three-dimensional path @code{p}.
8287As illustrated in the example @code{planeproject.asy}, a transform3
8288that projects in the direction @code{dir} onto the plane defined by a
8289planar path @code{p} is returned by
8290@verbatim
8291transform3 planeproject(path3 p, triple dir=normal(p));
8292@end verbatim
8293
8294The functions
8295@cindex @code{extrude}
8296@verbatim
8297surface extrude(path p, triple axis=Z);
8298surface extrude(Label L, triple axis=Z);
8299@end verbatim
8300@noindent
8301return the surface obtained by extruding path @code{p} or
8302Label @code{L} along @code{axis}.
8303
8304@cindex @code{length}
8305@cindex @code{size}
8306@cindex @code{point}
8307@cindex @code{dir}
8308@cindex @code{accel}
8309@cindex @code{radius}
8310@cindex @code{precontrol}
8311@cindex @code{postcontrol}
8312@cindex @code{arclength}
8313@cindex @code{arctime}
8314@cindex @code{reverse}
8315@cindex @code{subpath}
8316@cindex @code{intersect}
8317@cindex @code{intersections}
8318@cindex @code{intersectionpoint}
8319@cindex @code{intersectionpoints}
8320@cindex @code{min}
8321@cindex @code{max}
8322@cindex @code{cyclic}
8323@cindex @code{straight}
8324Three-dimensional versions of the path functions @code{length},
8325@code{size}, @code{point}, @code{dir}, @code{accel}, @code{radius},
8326@code{precontrol}, @code{postcontrol},
8327@code{arclength}, @code{arctime}, @code{reverse}, @code{subpath},
8328@code{intersect}, @code{intersections}, @code{intersectionpoint},
8329@code{intersectionpoints}, @code{min}, @code{max}, @code{cyclic}, and
8330@code{straight} are also defined.
8331
8332The routine
8333@cindex @code{intersections}
8334@verbatim
8335real[] intersect(path3 p, surface s, real fuzz=-1);
8336@end verbatim
8337@noindent
8338returns a real array of length 3 containing the intersection times, if any,
8339of a path @code{p} with a surface @code{s}.
8340The routine
8341@verbatim
8342real[][] intersections(path3 p, surface s, real fuzz=-1);
8343@end verbatim
8344@noindent
8345returns all (unless there are infinitey many) intersection times of a
8346path @code{p} with a surface @code{s} as a sorted array of real arrays
8347of length 3, and
8348@cindex @code{intersectionpoints}
8349@verbatim
8350triple[] intersectionpoints(path3 p, surface s, real fuzz=-1);
8351@end verbatim
8352@noindent
8353returns the corresponding intersection points.
8354Here, the computations are performed to the absolute error specified by
8355@code{fuzz}, or if @code{fuzz < 0}, to machine precision.
8356The routine
8357@cindex @code{orient}
8358@verbatim
8359real orient(triple a, triple b, triple c, triple d);
8360@end verbatim
8361@noindent
8362is a numerically robust computation of @code{dot(cross(a-d,b-d),c-d)},
8363which is the determinant
8364@verbatim
8365|a.x a.y a.z 1|
8366|b.x b.y b.z 1|
8367|c.x c.y c.z 1|
8368|d.x d.y d.z 1|
8369@end verbatim
8370
8371The routine
8372@cindex @code{insphere}
8373@verbatim
8374real insphere(triple a, triple b, triple c, triple d, triple e);
8375@end verbatim
8376@noindent
8377returns a positive (negative) value if @code{e} lies inside (outside)
8378the sphere passing through points @code{a,b,c,d} oriented so that
8379@code{dot(cross(a-d,b-d),c-d)} is positive,
8380or zero if all five points are cospherical.
8381The value returned is the determinant
8382@verbatim
8383|a.x a.y a.z a.x^2+a.y^2+a.z^2 1|
8384|b.x b.y b.z b.x^2+b.y^2+b.z^2 1|
8385|c.x c.y c.z c.x^2+c.y^2+c.z^2 1|
8386|d.x d.y d.z d.x^2+d.y^2+d.z^2 1|
8387|e.x e.y e.z e.x^2+e.y^2+e.z^2 1|
8388@end verbatim
8389
8390Here is an example showing all five guide3 connectors:
8391@verbatiminclude join3.asy
8392@sp 1
8393@center @image{join3}
8394
8395@cindex @code{BeginBar3}
8396@cindex @code{EndBar3}
8397@cindex @code{Bar3}
8398@cindex @code{Bars3}
8399@cindex @code{BeginArrow3}
8400@cindex @code{MidArrow3}
8401@cindex @code{EndArrow3}
8402@cindex @code{Arrow3}
8403@cindex @code{Arrows3}
8404@cindex @code{BeginArcArrow3}
8405@cindex @code{MidArcArrow3}
8406@cindex @code{EndArcArrow3}
8407@cindex @code{ArcArrow3}
8408@cindex @code{ArcArrows3}
8409@cindex @code{DefaultHead3}
8410@cindex @code{HookHead3}
8411@cindex @code{TeXHead3}
8412Three-dimensional versions of bars or arrows can be drawn with one of
8413the specifiers @code{None}, @code{Blank},
8414@code{BeginBar3}, @code{EndBar3} (or equivalently @code{Bar3}), @code{Bars3},
8415@code{BeginArrow3}, @code{MidArrow3},
8416@code{EndArrow3} (or equivalently @code{Arrow3}), @code{Arrows3},
8417@code{BeginArcArrow3}, @code{EndArcArrow3} (or equivalently
8418@code{ArcArrow3}), @code{MidArcArrow3}, and @code{ArcArrows3}.
8419Three-dimensional bars accept the optional arguments @code{(real size=0,
8420triple dir=O)}. If @code{size=O}, the default bar length is used; if
8421@code{dir=O}, the bar is drawn perpendicular to the path
8422and the initial viewing direction. The predefined three-dimensional
8423arrowhead styles are @code{DefaultHead3}, @code{HookHead3}, @code{TeXHead3}.
8424Versions of the two-dimensional arrowheads lifted to three-dimensional
8425space and aligned according to the initial viewpoint (or an optionally
8426specified @code{normal} vector) are also defined:
8427@code{DefaultHead2(triple normal=O)}, @code{HookHead2(triple normal=O)},
8428@code{TeXHead2(triple normal=O)}. These are illustrated in the example
8429@code{arrows3.asy}.
8430
8431@cindex @code{NoMargin3}
8432@cindex @code{BeginMargin3}
8433@cindex @code{EndMargin3}
8434@cindex @code{Margin3}
8435@cindex @code{Margins3}
8436@cindex @code{BeginPenMargin2}
8437@cindex @code{EndPenMargin2}
8438@cindex @code{PenMargin2}
8439@cindex @code{PenMargins2}
8440@cindex @code{BeginPenMargin3}
8441@cindex @code{EndPenMargin3}
8442@cindex @code{PenMargin3}
8443@cindex @code{PenMargins3}
8444@cindex @code{BeginDotMargin3}
8445@cindex @code{EndDotMargin3}
8446@cindex @code{DotMargin3}
8447@cindex @code{DotMargins3}
8448@cindex @code{Margin3}
8449@cindex @code{TrueMargin3}
8450Module @code{three} also defines the three-dimensional margins
8451@code{NoMargin3}, @code{BeginMargin3}, @code{EndMargin3},
8452@code{Margin3}, @code{Margins3},
8453@code{BeginPenMargin2}, @code{EndPenMargin2}, @code{PenMargin2},
8454@code{PenMargins2},
8455@code{BeginPenMargin3}, @code{EndPenMargin3}, @code{PenMargin3},
8456@code{PenMargins3},
8457@code{BeginDotMargin3}, @code{EndDotMargin3}, @code{DotMargin3},
8458@code{DotMargins3}, @code{Margin3}, and @code{TrueMargin3}.
8459
8460@cindex @code{pixel}
8461The routine
8462@verbatim
8463void pixel(picture pic=currentpicture, triple v, pen p=currentpen,
8464           real width=1);
8465@end verbatim
8466@noindent
8467can be used to draw on picture @code{pic} a pixel of width @code{width} at
8468position @code{v} using pen @code{p}.
8469
8470Further three-dimensional examples are provided in the files
8471@code{near_earth.asy}, @code{conicurv.asy}, and (in the @code{animations}
8472subdirectory) @code{cube.asy}.
8473
8474@anchor{PostScript3D}
8475@cindex 3D @code{PostScript}
8476Limited support for projected vector graphics (effectively three-dimensional
8477nonrendered @code{PostScript}) is available with the setting
8478@code{render=0}. This currently only works for piecewise planar
8479surfaces, such as those produced by the parametric @code{surface}
8480routines in the @code{graph3} module. Surfaces produced by the
8481@code{solids} package will also be properly rendered if the parameter
8482@code{nslices} is sufficiently large.
8483
8484@cindex hidden surface removal
8485@cindex @code{face}
8486In the module @code{bsp}, hidden surface removal of planar pictures is
8487implemented using a binary space partition and picture clipping.
8488A planar path is first converted to a structure @code{face} derived from
8489@code{picture}. A @code{face} may be given to a two-dimensional drawing
8490routine in place of any @code{picture} argument.  An array of such faces
8491may then be drawn, removing hidden surfaces:
8492@verbatim
8493void add(picture pic=currentpicture, face[] faces,
8494         projection P=currentprojection);
8495@end verbatim
8496Labels may be projected to two dimensions, using projection @code{P},
8497onto the plane passing through point @code{O} with normal
8498@code{cross(u,v)} by multiplying it on the left by the transform
8499@verbatim
8500transform transform(triple u, triple v, triple O=O,
8501                    projection P=currentprojection);
8502@end verbatim
8503
8504Here is an example that shows how a binary space partition may be used to draw a
8505two-dimensional vector graphics projection of three orthogonal
8506intersecting planes:
8507@verbatiminclude planes.asy
8508@sp 1
8509@center @image{planes}
8510
8511@node obj
8512@section @code{obj}
8513@cindex @code{obj}
8514This module allows one to construct surfaces from simple obj files,
8515as illustrated in the example files @code{galleon.asy} and
8516@code{triceratops.asy}.
8517
8518@node graph3
8519@section @code{graph3}
8520@cindex @code{graph3}
8521@cindex 3D graphs
8522This module implements three-dimensional versions of the
8523functions in @code{graph.asy}.
8524@cindex @code{xaxis3}
8525@cindex @code{yaxis3}
8526@cindex @code{zaxis3}
8527@noindent
8528To draw an @math{x} axis in three dimensions, use the routine
8529@verbatim
8530void xaxis3(picture pic=currentpicture, Label L="", axis axis=YZZero,
8531            real xmin=-infinity, real xmax=infinity, pen p=currentpen,
8532            ticks3 ticks=NoTicks3, arrowbar3 arrow=None, bool above=false);
8533@end verbatim
8534@noindent
8535Analogous routines @code{yaxis} and @code{zaxis} can be used to draw
8536@math{y} and @math{z} axes in three dimensions.
8537There is also a routine for drawing all three axis:
8538@verbatim
8539void axes3(picture pic=currentpicture,
8540           Label xlabel="", Label ylabel="", Label zlabel="",
8541           bool extend=false,
8542           triple min=(-infinity,-infinity,-infinity),
8543           triple max=(infinity,infinity,infinity),
8544           pen p=currentpen, arrowbar3 arrow=None);
8545@end verbatim
8546
8547@cindex @code{YZEquals}
8548@cindex @code{XZEquals}
8549@cindex @code{XYEquals}
8550@cindex @code{YZZero}
8551@cindex @code{XZZero}
8552@cindex @code{XYZero}
8553@cindex @code{Bounds}
8554@noindent
8555The predefined three-dimensional axis types are
8556@verbatim
8557axis YZEquals(real y, real z, triple align=O, bool extend=false);
8558axis XZEquals(real x, real z, triple align=O, bool extend=false);
8559axis XYEquals(real x, real y, triple align=O, bool extend=false);
8560axis YZZero(triple align=O, bool extend=false);
8561axis XZZero(triple align=O, bool extend=false);
8562axis XYZero(triple align=O, bool extend=false);
8563axis Bounds(int type=Both, int type2=Both, triple align=O, bool extend=false);
8564@end verbatim
8565@noindent
8566The optional @code{align} parameter to these routines can be used to
8567specify the default axis and tick label alignments. The @code{Bounds}
8568axis accepts two type parameters, each of which must be one of
8569@code{Min}, @code{Max}, or @code{Both}. These parameters specify which
8570of the four possible three-dimensional bounding box edges should be drawn.
8571
8572@cindex @code{NoTicks3}
8573@cindex @code{InTicks}
8574@cindex @code{OutTicks}
8575@cindex @code{InOutTicks}
8576The three-dimensional tick options are @code{NoTicks3}, @code{InTicks},
8577@code{OutTicks}, and @code{InOutTicks}. These specify the tick
8578directions for the @code{Bounds} axis type; other axis types inherit
8579the direction that would be used for the @code{Bounds(Min,Min)} axis.
8580
8581Here is an example of a helix and bounding box axes with ticks
8582and axis labels, using orthographic projection:
8583@verbatiminclude helix.asy
8584@sp 1
8585@center @image{helix}
8586
8587The next example illustrates three-dimensional @math{x}, @math{y}, and
8588@math{z} axes, without autoscaling of the axis limits:
8589@cindex @code{axis}
8590@verbatiminclude axis3.asy
8591@sp 1
8592@center @image{axis3}
8593
8594One can also place ticks along a general three-dimensional axis:
8595@cindex @code{axis}
8596@verbatiminclude generalaxis3.asy
8597@sp 1
8598@center @image{generalaxis3}
8599
8600@cindex @code{surface}
8601@cindex @code{Spline}
8602@cindex parametric surface
8603Surface plots of matrices and functions over the region
8604@code{box(a,b)} in the @math{XY} plane are also implemented:
8605@verbatim
8606surface surface(real[][] f, pair a, pair b, bool[][] cond={});
8607surface surface(real[][] f, pair a, pair b, splinetype xsplinetype,
8608                splinetype ysplinetype=xsplinetype, bool[][] cond={});
8609surface surface(real[][] f, real[] x, real[] y,
8610                splinetype xsplinetype=null, splinetype ysplinetype=xsplinetype,
8611                bool[][] cond={})
8612surface surface(triple[][] f, bool[][] cond={});
8613surface surface(real f(pair z), pair a, pair b, int nx=nmesh, int ny=nx,
8614                bool cond(pair z)=null);
8615surface surface(real f(pair z), pair a, pair b, int nx=nmesh, int ny=nx,
8616                splinetype xsplinetype, splinetype ysplinetype=xsplinetype,
8617                bool cond(pair z)=null);
8618surface surface(triple f(pair z), real[] u, real[] v,
8619                splinetype[] usplinetype, splinetype[] vsplinetype=Spline,
8620                bool cond(pair z)=null);
8621surface surface(triple f(pair z), pair a, pair b, int nu=nmesh, int nv=nu,
8622                bool cond(pair z)=null);
8623surface surface(triple f(pair z), pair a, pair b, int nu=nmesh, int nv=nu,
8624                splinetype[] usplinetype, splinetype[] vsplinetype=Spline,
8625                bool cond(pair z)=null);
8626@end verbatim
8627@noindent
8628The final two versions draw parametric surfaces for a function
8629@math{f(u,v)} over the parameter space @code{box(a,b)},
8630as illustrated in the example @code{parametricsurface.asy}.
8631An optional splinetype @code{Spline} may be specified.
8632The boolean array or function @code{cond} can be used to control which
8633surface mesh cells are actually drawn (by default all mesh cells over
8634@code{box(a,b)} are drawn).
8635Surface lighting is illustrated in the example files
8636@code{parametricsurface.asy} and @code{sinc.asy}.
8637Lighting can be disabled by setting @code{light=nolight}, as in this example
8638of a Gaussian surface:
8639@anchor{GaussianSurface}
8640@verbatiminclude GaussianSurface.asy
8641@sp 1
8642@center @image{GaussianSurface}
8643@noindent
8644A mesh can be drawn without surface filling by specifying @code{nullpen}
8645for the surfacepen.
8646
8647A vector field of @code{nu}@math{\times}@code{nv} arrows on a
8648parametric surface @code{f} over @code{box(a,b)} can be drawn with the routine
8649@cindex @code{vectorfield3}
8650@verbatim
8651picture vectorfield(path3 vector(pair v), triple f(pair z), pair a, pair b,
8652                    int nu=nmesh, int nv=nu, bool truesize=false,
8653                    real maxlength=truesize ? 0 : maxlength(f,a,b,nu,nv),
8654                    bool cond(pair z)=null, pen p=currentpen,
8655                    arrowbar3 arrow=Arrow3, margin3 margin=PenMargin3)
8656@end verbatim
8657as illustrated in the examples @code{vectorfield3.asy} and
8658@code{vectorfieldsphere.asy}.
8659
8660@node grid3
8661@section @code{grid3}
8662@cindex @code{grid3}
8663@cindex 3D grids
8664
8665This module, contributed by Philippe Ivaldi, can be used for drawing
86663D grids. Here is an example (further examples can be found in
8667@code{grid3.asy} and at @url{http://www.piprime.fr/files/asymptote/grid3/}):
8668@verbatiminclude grid3xyz.asy
8669@sp 1
8670@center @image{grid3xyz}
8671
8672@node solids
8673@section @code{solids}
8674@cindex @code{solids}
8675This solid geometry package defines a structure @code{revolution} that
8676can be used to fill and draw surfaces of revolution. The following example
8677uses it to display the outline of a circular cylinder of radius 1
8678with axis @code{O--1.5unit(Y+Z)} with perspective projection:
8679@verbatiminclude cylinderskeleton.asy
8680@sp 1
8681@center @image{cylinderskeleton}
8682
8683Further illustrations are provided in the example files @code{cylinder.asy},
8684@code{cones.asy}, @code{hyperboloid.asy}, and @code{torus.asy}.
8685
8686The structure @code{skeleton} contains the three-dimensional wireframe
8687used to visualize a volume of revolution:
8688@verbatim
8689struct skeleton {
8690  struct curve {
8691    path3[] front;
8692    path3[] back;
8693  }
8694  // transverse skeleton (perpendicular to axis of revolution)
8695  curve transverse;
8696  // longitudinal skeleton (parallel to axis of revolution)
8697  curve longitudinal;
8698}
8699@end verbatim
8700
8701@node tube
8702@section @code{tube}
8703@cindex @code{tube}
8704This package extends the @code{tube} surfaces constructed in
8705@code{three_arrows.asy} to arbitrary cross sections, colors, and spine
8706transformations. The routine
8707@verbatim
8708surface tube(path3 g, coloredpath section,
8709             transform T(real)=new transform(real t) {return identity();},
8710             real corner=1, real relstep=0);
8711@end verbatim
8712@noindent
8713draws a tube along @code{g} with cross section @code{section}, after
8714applying the transformation @code{T(t)} at @code{relpoint(g,t)}.
8715The parameter @code{corner} controls the number of elementary tubes at
8716the angular points of @code{g}. A nonzero value of @code{relstep}
8717specifies a fixed relative time step (in the sense of
8718@code{relpoint(g,t)}) to use in constructing elementary tubes along @code{g}.
8719The type @code{coloredpath} is a generalization of @code{path} to
8720which a @code{path} can be cast:
8721@cindex @code{coloredpath}
8722@verbatim
8723struct coloredpath
8724{
8725  path p;
8726  pen[] pens(real);
8727  int colortype=coloredSegments;
8728}
8729@end verbatim
8730@noindent
8731@cindex @code{coloredSegments}
8732@cindex @code{coloredNodes}
8733Here @code{p} defines the cross section and
8734the method @code{pens(real t)} returns an array of pens (interpreted
8735as a cyclic array) used for shading the tube patches at
8736@code{relpoint(g,t)}. If @code{colortype=coloredSegments}, the tube patches
8737are filled as if each segment of the section was colored with the pen
8738returned by @code{pens(t)}, whereas if @code{colortype=coloredNodes}, the
8739tube components are vertex shaded as if the nodes of the section were colored.
8740
8741A @code{coloredpath} can be constructed with one of the routines:
8742@verbatim
8743coloredpath coloredpath(path p, pen[] pens(real),
8744                        int colortype=coloredSegments);
8745coloredpath coloredpath(path p, pen[] pens=new pen[] {currentpen},
8746                        int colortype=coloredSegments);
8747coloredpath coloredpath(path p, pen pen(real));
8748@end verbatim
8749@noindent
8750In the second case, the pens are independent of the relative time.
8751In the third case, the array of pens contains only one pen, which
8752depends of the relative time.
8753
8754The casting of @code{path} to @code{coloredpath} allows the
8755use of a @code{path} instead of a @code{coloredpath}; in this case the
8756shading behaviour is the default shading behavior for a surface.
8757
8758An example of @code{tube} is provided in the file
8759@code{trefoilknot.asy}. Further examples can be found at
8760@url{http://www.piprime.fr/files/asymptote/tube/}.
8761
8762@node flowchart
8763@section @code{flowchart}
8764@cindex @code{flowchart}
8765This package provides routines for drawing flowcharts. The primary
8766structure is a @code{block}, which represents a single block on the
8767flowchart. The following eight functions return a position on the appropriate
8768edge of the block, given picture transform @code{t}:
8769
8770@verbatim
8771pair block.top(transform t=identity());
8772pair block.left(transform t=identity());
8773pair block.right(transform t=identity());
8774pair block.bottom(transform t=identity());
8775pair block.topleft(transform t=identity());
8776pair block.topright(transform t=identity());
8777pair block.bottomleft(transform t=identity());
8778pair block.bottomright(transform t=identity());
8779@end verbatim
8780@cindex @code{block.top}
8781@cindex @code{block.left}
8782@cindex @code{block.right}
8783@cindex @code{block.bottom}
8784@cindex @code{block.topleft}
8785@cindex @code{block.topright}
8786@cindex @code{block.bottomleft}
8787@cindex @code{block.bottomright}
8788
8789@noindent
8790To obtain an arbitrary position along the boundary of the block in user
8791coordinates, use:
8792@verbatim
8793pair block.position(real x, transform t=identity());
8794@end verbatim
8795@cindex @code{block.position}
8796
8797@noindent
8798@cindex @code{block.center}
8799The center of the block in user coordinates is stored in
8800@code{block.center} and the block size in @code{PostScript} coordinates
8801is given by @code{block.size}.
8802
8803@noindent
8804A frame containing the block is returned by
8805@verbatim
8806frame block.draw(pen p=currentpen);
8807@end verbatim
8808@cindex @code{block.draw}
8809
8810The following block generation routines accept a Label, string, or
8811frame for their object argument:
8812
8813@table @dfn
8814@item rectangular block with an optional header (and padding @code{dx} around header and body):
8815@cindex @code{rectangle}
8816@verbatim
8817block rectangle(object header, object body, pair center=(0,0),
8818                pen headerpen=mediumgray, pen bodypen=invisible,
8819                pen drawpen=currentpen,
8820                real dx=3, real minheaderwidth=minblockwidth,
8821                real minheaderheight=minblockwidth,
8822                real minbodywidth=minblockheight,
8823                real minbodyheight=minblockheight);
8824block rectangle(object body, pair center=(0,0),
8825                pen fillpen=invisible, pen drawpen=currentpen,
8826                real dx=3, real minwidth=minblockwidth,
8827                real minheight=minblockheight);
8828@end verbatim
8829
8830@item parallelogram block:
8831@cindex @code{parallelogram}
8832@verbatim
8833block parallelogram(object body, pair center=(0,0),
8834                    pen fillpen=invisible, pen drawpen=currentpen,
8835                    real dx=3, real slope=2,
8836                    real minwidth=minblockwidth,
8837                    real minheight=minblockheight);
8838@end verbatim
8839
8840@item diamond-shaped block:
8841@cindex @code{diamond}
8842@verbatim
8843block diamond(object body, pair center=(0,0),
8844              pen fillpen=invisible, pen drawpen=currentpen,
8845              real ds=5, real dw=1,
8846              real height=20, real minwidth=minblockwidth,
8847              real minheight=minblockheight);
8848@end verbatim
8849
8850@item circular block:
8851@cindex @code{circle}
8852@verbatim
8853block circle(object body, pair center=(0,0), pen fillpen=invisible,
8854             pen drawpen=currentpen, real dr=3,
8855             real mindiameter=mincirclediameter);
8856@end verbatim
8857
8858@item rectangular block with rounded corners:
8859@cindex @code{roundrectangle}
8860@verbatim
8861block roundrectangle(object body, pair center=(0,0),
8862                     pen fillpen=invisible, pen drawpen=currentpen,
8863                     real ds=5, real dw=0, real minwidth=minblockwidth,
8864                     real minheight=minblockheight);
8865@end verbatim
8866
8867@item rectangular block with beveled edges:
8868@cindex @code{bevel}
8869@verbatim
8870block bevel(object body, pair center=(0,0), pen fillpen=invisible,
8871            pen drawpen=currentpen, real dh=5, real dw=5,
8872            real minwidth=minblockwidth, real minheight=minblockheight);
8873@end verbatim
8874
8875@end table
8876
8877To draw paths joining the pairs in @code{point} with right-angled lines,
8878use the routine:
8879@cindex @code{path}
8880@cindex @code{Horizontal}
8881@cindex @code{Vertical}
8882@verbatim
8883path path(pair point[] ... flowdir dir[]);
8884@end verbatim
8885@noindent
8886The entries in @code{dir} identify whether successive
8887segments between the pairs specified by @code{point} should be drawn
8888in the @code{Horizontal} or @code{Vertical} direction.
8889
8890Here is a simple flowchart example (see also the example
8891@code{controlsystem.asy}):
8892
8893@verbatiminclude flowchartdemo.asy
8894@sp 1
8895@center @image{flowchartdemo}
8896
8897@node contour
8898@section @code{contour}
8899@cindex @code{contour}
8900This package draws contour lines.
8901To construct contours corresponding to the values in a real array @code{c}
8902for a function @code{f} on @code{box(a,b)}, use the routine
8903@verbatim
8904guide[][] contour(real f(real, real), pair a, pair b,
8905                  real[] c, int nx=ngraph, int ny=nx,
8906                  interpolate join=operator --, int subsample=1);
8907@end verbatim
8908@noindent
8909The integers @code{nx} and @code{ny} define the resolution.
8910The default resolution, @code{ngraph x ngraph} (here @code{ngraph}
8911defaults to @code{100}) can be increased for greater accuracy.
8912The default interpolation operator is @code{operator --} (linear). Spline
8913interpolation (@code{operator ..}) may produce smoother
8914contours but it can also lead to overshooting.
8915The @code{subsample} parameter indicates the number of interior points
8916that should be used to sample contours within each @code{1 x 1} box;
8917the default value of @code{1} is usually sufficient.
8918
8919To construct contours for an array of data values on a uniform
8920two-dimensional lattice on @code{box(a,b)}, use
8921@verbatim
8922guide[][] contour(real[][] f, pair a, pair b, real[] c,
8923                  interpolate join=operator --, int subsample=1);
8924@end verbatim
8925
8926To construct contours for an array of data values on a nonoverlapping
8927regular mesh specified by the two-dimensional array @code{z},
8928@verbatim
8929guide[][] contour(pair[][] z, real[][] f, real[] c,
8930                  interpolate join=operator --, int subsample=1);
8931
8932@end verbatim
8933@noindent
8934To construct contours for an array of values @code{f} specified at
8935irregularly positioned points @code{z}, use the routine
8936@verbatim
8937guide[][] contour(pair[] z, real[] f, real[] c, interpolate join=operator --);
8938@end verbatim
8939@noindent
8940The contours themselves can be drawn with one of the routines
8941@verbatim
8942void draw(picture pic=currentpicture, Label[] L=new Label[],
8943          guide[][] g, pen p=currentpen);
8944
8945void draw(picture pic=currentpicture, Label[] L=new Label[],
8946          guide[][] g, pen[] p);
8947@end verbatim
8948
8949The following simple example draws the contour at value @code{1}
8950for the function @math{z=x^2+y^2}, which is a unit circle:
8951@verbatiminclude onecontour.asy
8952@sp 1
8953@center @image{onecontour}
8954
8955The next example draws and labels multiple contours for the function
8956@math{z=x^2-y^2} with the resolution @code{100 x 100}, using a dashed
8957pen for negative contours and a solid pen for positive (and zero) contours:
8958@verbatiminclude multicontour.asy
8959@sp 1
8960@center @image{multicontour}
8961
8962The next example illustrates how contour lines can be drawn on color
8963density images:
8964@verbatiminclude imagecontour.asy
8965@sp 1
8966@center @image{imagecontour}
8967
8968Finally, here is an example that illustrates the construction of contours
8969from irregularly spaced data:
8970@verbatiminclude irregularcontour.asy
8971@sp 1
8972@center @image{irregularcontour}
8973
8974In the above example, the contours of irregularly spaced data are constructed by
8975first creating a triangular mesh from an array @code{z} of pairs:
8976
8977@cindex @code{triangulate}
8978@verbatim
8979int[][] triangulate(pair[] z);
8980@end verbatim
8981
8982@verbatiminclude triangulate.asy
8983@sp 1
8984@center @image{triangulate}
8985
8986The example @code{Gouraudcontour} illustrates how to produce color
8987density images over such irregular triangular meshes.
8988@code{Asymptote} uses a robust version of Paul Bourke's Delaunay triangulation
8989algorithm based on the public-domain exact arithmetic predicates written by
8990Jonathan Shewchuk.
8991
8992@node contour3
8993@section @code{contour3}
8994@cindex @code{contour3}
8995This package draws surfaces described as the null space of real-valued
8996functions of @math{(x,y,z)} or real[][][] matrices.
8997Its usage is illustrated in the example file @code{magnetic.asy}.
8998
8999@node slopefield
9000@section @code{slopefield}
9001@cindex @code{slopefield}
9002To draw a slope field for the differential equation @math{dy/dx=f(x,y)} (or
9003@math{dy/dx=f(x)}), use:
9004@verbatim
9005picture slopefield(real f(real,real), pair a, pair b,
9006                   int nx=nmesh, int ny=nx,
9007                   real tickfactor=0.5, pen p=currentpen,
9008                   arrowbar arrow=None);
9009@end verbatim
9010@noindent
9011Here, the points @code{a} and @code{b} are the lower left and upper
9012right corners of the rectangle in which the slope field is to be drawn,
9013@code{nx} and @code{ny} are the respective number of ticks in the
9014@math{x} and @math{y} directions, @code{tickfactor} is the fraction of
9015the minimum cell dimension to use for drawing ticks, and @code{p} is
9016the pen to use for drawing the slope fields.
9017The return value is a picture that can be added to
9018@code{currentpicture} via the @code{add(picture)} command.
9019
9020The function
9021@cindex @code{curve}
9022@verbatim
9023path curve(pair c, real f(real,real), pair a, pair b);
9024@end verbatim
9025@noindent
9026takes a point (@code{c}) and a slope field-defining function @code{f}
9027and returns, as a path, the curve passing through that point. The points
9028@code{a} and @code{b} represent the rectangular boundaries over which
9029the curve is interpolated.
9030
9031Both @code{slopefield} and @code{curve} alternatively accept a function
9032@code{real f(real)} that depends on @math{x} only, as seen in this example:
9033
9034@verbatiminclude slopefield1.asy
9035@sp 1
9036@center @image{slopefield1}
9037
9038@node ode
9039@section @code{ode}
9040@cindex @code{ode}
9041The @code{ode} module, illustrated in the example @code{odetest.asy},
9042implements a number of explicit numerical integration schemes for
9043ordinary differential equations.
9044
9045@node Options
9046@chapter Command-line options
9047@cindex options
9048@cindex command-line options
9049Type @code{asy -h} to see the full list of command-line options
9050supported by @code{Asymptote}:
9051@verbatiminclude options
9052
9053All boolean options can be negated by prepending @code{no} to the option name.
9054
9055If no arguments are given, @code{Asymptote} runs in interactive mode
9056(@pxref{Interactive mode}). In this case, the default output file
9057is @code{out.eps}.
9058
9059If @code{-} is given as the file argument, @code{Asymptote} reads from
9060standard input.
9061
9062If multiple files are specified, they are treated as separate
9063@code{Asymptote} runs.
9064
9065@cindex @code{autoimport}
9066If the string @code{autoimport} is nonempty, a module with this name is
9067automatically imported for each run as the final step in loading module
9068@code{plain}.
9069
9070@anchor{configuration file}
9071@cindex configuration file
9072@cindex @code{ASYMPTOTE_CONFIG}
9073@cindex @code{config}
9074@cindex @code{settings}
9075@anchor{settings}
9076Default option values may be entered as @code{Asymptote} code in a
9077configuration file named @code{config.asy} (or the file specified by
9078the environment variable @code{ASYMPTOTE_CONFIG} or @code{-config} option).
9079@code{Asymptote} will look for this file in its usual search path
9080(@pxref{Search paths}). Typically the configuration file is placed in the
9081@code{.asy} directory in the user's home directory
9082(@code{%USERPROFILE%\.asy} under @code{MSDOS}).
9083Configuration variables are accessed using the long form of the option names:
9084@verbatim
9085import settings;
9086outformat="pdf";
9087batchView=false;
9088interactiveView=true;
9089batchMask=false;
9090interactiveMask=true;
9091@end verbatim
9092Command-line options override these defaults. Most configuration
9093variables may also be changed at runtime.
9094@cindex @code{dvipsOptions}
9095@cindex @code{hyperrefOptions}
9096@cindex @code{convertOptions}
9097@cindex @code{gsOptions}
9098@cindex @code{psviewerOptions}
9099@cindex @code{pdfviewerOptions}
9100@cindex @code{pdfreloadOptions}
9101@cindex @code{glOptions}
9102@cindex @code{dvisvgmOptions}
9103The advanced configuration variables @code{dvipsOptions},
9104@code{hyperrefOptions}, @code{convertOptions}, @code{gsOptions},
9105@code{psviewerOptions}, @code{pdfviewerOptions}, @code{pdfreloadOptions},
9106@code{glOptions}, and @code{dvisvgmOptions} allow specialized options
9107to be passed as a string to the respective applications or
9108libraries. The default value of @code{hyperrefOptions} is
9109@code{setpagesize=false,unicode,pdfborder=0 0 0}.
9110
9111If you insert
9112@verbatim
9113import plain;
9114settings.autoplain=true;
9115@end verbatim
9116@noindent
9117at the beginning of the configuration file, it can contain arbitrary
9118@code{Asymptote} code.
9119
9120@cindex @code{convert}
9121@cindex @code{output}
9122@cindex @code{format}
9123@cindex @code{ImageMagick}
9124@cindex @code{render}
9125@cindex @code{antialias}
9126@cindex @code{size}
9127@cindex @code{latex}
9128@cindex @code{tex}
9129@cindex @code{pdflatex}
9130@cindex @code{xelatex}
9131@cindex @code{context}
9132@cindex @code{luatex}
9133@cindex @code{lualatex}
9134@cindex @code{EPS}
9135@cindex @code{PDF}
9136@anchor{texengines}
9137@anchor{convert}
9138The default output format is @acronym{EPS} for the (default)
9139@code{latex} and @code{tex} tex engine and @acronym{PDF} for the
9140@code{pdflatex}, @code{xelatex}, @code{context}, @code{luatex}, and
9141@code{lualatex} tex engines. Alternative output formats may be
9142produced using the @code{-f} option (or @code{outformat} setting).
9143
9144@cindex @code{SVG}
9145@cindex @code{dvisvgm}
9146@cindex @code{libgs}
9147To produce @acronym{SVG} output, you will need @code{dvisvgm} (version
91481.5.3 or later) from @url{http://dvisvgm.sourceforge.net} and must use
9149the @code{latex} or @code{tex} tex engine. You might need to adjust
9150the configuration variable @code{libgs} to point to the location of
9151your @code{Ghostscript} library @code{libgs.so} (or to an empty
9152string, depending on how @code{dvisvgm} was configured).
9153
9154@code{Asymptote} can also produce any output format supported
9155by the @code{ImageMagick} @code{convert} program (version 6.3.5 or
9156later recommended; an @code{Invalid Parameter} error message indicates
9157that the @code{MSDOS} utility @code{convert} is being used instead of
9158the one that comes with @code{ImageMagick}).
9159The optional setting @code{-render n} requests
9160an output resolution of @code{n} pixels per @code{bp}. Antialiasing is
9161controlled by the parameter @code{antialias}, which by default
9162specifies a sampling width of 2 pixels.
9163To give other options to @code{convert}, use the
9164@code{convertOptions} setting or call convert manually. This example
9165emulates how @code{Asymptote} produces antialiased @code{tiff} output at
9166one pixel per @code{bp}:
9167@verbatim
9168asy -o - venn | convert -alpha Off -density 144x144 -geometry 50%x eps:- venn.tiff
9169@end verbatim
9170
9171@cindex @code{nosafe}
9172@cindex @code{safe}
9173@cindex @code{system}
9174If the option @code{-nosafe} is given, @code{Asymptote} runs
9175in unsafe mode. This enables the @code{int system(string s)} and
9176@code{int system(string[] s)} calls, allowing one
9177to execute arbitrary shell commands. The default mode, @code{-safe},
9178disables this call.
9179
9180@cindex offset
9181@cindex @code{aligndir}
9182A @code{PostScript} offset may be specified as a pair (in @code{bp}
9183units) with the @code{-O} option:
9184@verbatim
9185asy -O 0,0 file
9186@end verbatim
9187@noindent
9188The default offset is zero. The pair @code{aligndir} specifies
9189an optional direction on the boundary of the page (mapped to the
9190rectangle [-1,1]@math{\times}[-1,1]) to which the picture should be aligned; the
9191default value @code{(0,0)} species center alignment.
9192
9193@cindex @code{-c}
9194The @code{-c} (@code{command}) option may be used to execute arbitrary
9195@code{Asymptote} code on the command line as a string. It is not
9196necessary to terminate the string with a semicolon. Multiple @code{-c}
9197options are executed in the order they are given. For example
9198@verbatim
9199asy -c 2+2 -c "sin(1)" -c "size(100); draw(unitsquare)"
9200@end verbatim
9201@noindent
9202produces the output
9203@verbatim
92044
92050.841470984807897
9206@end verbatim
9207@noindent
9208and draws a unitsquare of size @code{100}.
9209
9210@cindex @code{-u}
9211The @code{-u} (@code{user}) option may be used to specify arbitrary
9212@code{Asymptote} settings on the command line as a string. It is not
9213necessary to terminate the string with a semicolon. Multiple @code{-u}
9214options are executed in the order they are given. Command-line code like
9215@code{-u x=sqrt(2)} can be executed within a module like this:
9216@verbatim
9217real x;
9218usersetting();
9219write(x);
9220@end verbatim
9221
9222@cindex @code{-l}
9223When the @code{-l} (@code{listvariables}) option is used with file
9224arguments, only global functions and variables defined in the specified
9225file(s) are listed.
9226
9227Additional debugging output is produced with each additional @code{-v} option:
9228@table @code
9229@item -v
9230Display top-level module and final output file names.
9231@item -vv
9232Also display imported and included module names and final @code{LaTeX} and
9233@code{dvips} processing information.
9234@item -vvv
9235Also output @code{LaTeX} bidirectional pipe diagnostics.
9236@item -vvvv
9237Also output knot guide solver diagnostics.
9238@item -vvvvv
9239Also output @code{Asymptote} traceback diagnostics.
9240@end table
9241
9242@node Interactive mode
9243@chapter Interactive mode
9244@cindex interactive mode
9245Interactive mode is entered by executing the command @code{asy} with
9246no file arguments. When the @code{-multiline} option is disabled (the default),
9247each line must be a complete @code{Asymptote} statement (unless
9248explicitly continued by a final backslash character @code{\});
9249it is not necessary to terminate input lines with a semicolon.
9250If one assigns @code{settings.multiline=true}, interactive code can be
9251entered over multiple lines; in this mode, the automatic termination of
9252interactive input lines by a semicolon is inhibited. Multiline mode is useful
9253for cutting and pasting @code{Asymptote} code directly into the
9254interactive input buffer.
9255
9256@cindex @code{%}
9257Interactive mode can be conveniently used as a calculator: expressions
9258entered at the interactive prompt (for which a corresponding @code{write}
9259function exists) are automatically evaluated and written to @code{stdout}.
9260If the expression is non-writable, its type signature will be printed out
9261instead. In either case, the expression can be referred to using the symbol
9262@code{%} in the next line input at the prompt.  For example:
9263@verbatim
9264> 2+3
92655
9266> %*4
926720
9268> 1/%
92690.05
9270> sin(%)
92710.0499791692706783
9272> currentpicture
9273<picture currentpicture>
9274> %.size(200,0)
9275>
9276@end verbatim
9277
9278@cindex @code{operator answer}
9279The @code{%} symbol, when used as a variable, is shorthand for the identifier
9280@code{operator answer}, which is set by the prompt after each written
9281expression evaluation.
9282
9283
9284The following special commands are supported only in interactive mode
9285and must be entered immediately after the prompt:
9286
9287@table @code
9288@cindex @code{help}
9289@item help
9290view the manual;
9291@item erase
9292erase @code{currentpicture};
9293@cindex @code{input}
9294@item reset
9295reset the @code{Asymptote} environment to its initial state, except for
9296changes to the settings module (@pxref{settings}), the current directory
9297(@pxref{cd}), and breakpoints (@pxref{Debugger});
9298@cindex @code{input}
9299@item input FILE
9300does an interactive reset, followed by the command
9301@code{include FILE}. If the file name @code{FILE} contains
9302nonalphanumeric characters, enclose it with quotation marks.
9303A trailing semi-colon followed by optional @code{Asymptote} commands may
9304be entered on the same line.
9305@cindex @code{quit}
9306@cindex @code{exit}
9307@cindex @code{history}
9308@anchor{history}
9309@item quit
9310exit interactive mode (@code{exit} is a synonym; the abbreviation
9311@code{q} is also accepted unless there exists a top-level variable named
9312@code{q}).
9313@cindex @code{historylines}
9314A history of the most recent 1000 (this number can be changed with the
9315@code{historylines} configuration variable) previous commands will be retained
9316in the file @code{.asy/history} in the user's home directory (unless
9317the command-line option @code{-localhistory} was specified, in which case
9318the history will be stored in the file @code{.asy_history} in the
9319current directory).
9320
9321@end table
9322
9323Typing @code{ctrl-C} interrupts the execution of @code{Asymptote} code
9324and returns control to the interactive prompt.
9325
9326Interactive mode is implemented with the @acronym{GNU} @code{readline} library,
9327with command history and auto-completion. To customize the key bindings, see:
9328@url{http://cnswww.cns.cwru.edu/php/chet/readline/readline.html}
9329
9330@cindex @code{Python} usage
9331The file @code{asymptote.py} in the @code{Asymptote} system directory
9332provides an alternative way of entering @code{Asymptote} commands
9333interactively, coupled with the full power of @code{Python}. Copy this
9334file to your @code{Python path} and then execute from within
9335@code{Python} the commands
9336@verbatim
9337from asymptote import *
9338g=asy()
9339g.size(200)
9340g.draw("unitcircle")
9341g.send("draw(unitsquare)")
9342g.fill("unitsquare, blue")
9343g.clip("unitcircle")
9344g.label("\"$O$\", (0,0), SW")
9345@end verbatim
9346
9347@node GUI
9348@chapter Graphical User Interface
9349@cindex graphical user interface
9350@cindex @acronym{GUI}
9351@cindex mouse
9352@cindex wheel mouse
9353@cindex @code{Button-1}
9354@cindex @code{Button-2}
9355@cindex @code{xasy}
9356
9357In the event that adjustments to the final figure are required, the
9358preliminary Graphical User Interface (@acronym{GUI}) @code{xasy} included with
9359@code{Asymptote} allows you to move graphical objects and draw new ones.
9360The modified figure can then be saved as a normal @code{Asymptote} file.
9361
9362@menu
9363* GUI installation::            Installing @code{xasy}
9364* GUI usage::
9365@end menu
9366
9367@node GUI installation
9368@section GUI installation
9369@cindex GUI installation
9370
9371As @code{xasy} is written in the interactive scripting language
9372@code{Python/TK}, it requires @code{Python}
9373(@url{http://www.python.org}), the @code{Python Imaging Library}
9374(@url{http://www.pythonware.com/products/pil/}), and the @code{tkinter}
9375package (included with @code{Python} under @code{Microsoft Windows}) be
9376installed. @code{Fedora Linux} users can either install
9377@code{tkinter} with the commands
9378@verbatim
9379yum install tkinter
9380yum install tk-devel
9381@end verbatim
9382@noindent
9383or manually install the @code{tkinter}, @code{tix}, @code{tk},
9384and @code{tk-devel} packages.
9385
9386Pictures are deconstructed into the @acronym{PNG} image format, which
9387supports full alpha channel transparency. Under @code{Microsoft Windows},
9388this requires @code{Python 2.7.4} and the @code{Python Imaging Library}:
9389@quotation
9390@url{http://www.python.org/ftp/python/2.7.4/python-2.7.4.msi}
9391@end quotation
9392@quotation
9393@url{http://effbot.org/downloads/PIL-1.1.7.win32-py2.7.exe}.
9394@end quotation
9395@noindent
9396On @code{UNIX} systems, place
9397@url{http://effbot.org/downloads/Imaging-1.1.7.tar.gz} in the
9398@code{Asymptote} source directory, and type (as the root user):
9399@verbatim
9400tar -zxf Imaging-1.1.7.tar.gz
9401cd Imaging-1.1.7
9402python setup.py install
9403@end verbatim
9404
9405@node GUI usage
9406@section GUI usage
9407@cindex GUI usage
9408@cindex @code{deconstruct}
9409
9410A wheel mouse is convenient for raising and lowering objects within
9411@code{xasy}, to expose the object to be moved. If a wheel mouse is not
9412available, mouse @code{Button-2} can be used to repeatedly lower an
9413object instead. When run from the command line, @code{xasy} accepts
9414a command line option @code{-x n}, which sets the initial magnification
9415to @code{n}.
9416
9417Deconstruction of compound objects (such as arrows) can be prevented
9418by enclosing them within the commands
9419@verbatim
9420void begingroup(picture pic=currentpicture);
9421void endgroup(picture pic=currentpicture);
9422@end verbatim
9423By default, the elements of a picture or frame will be grouped
9424together on adding them to a picture. However, the elements of a frame
9425added to another frame are not grouped together by default: their
9426elements will be individually deconstructed (@pxref{add}).
9427
9428@node PostScript to Asymptote
9429@chapter @code{PostScript} to @code{Asymptote}
9430@cindex @code{pstoedit}
9431The excellent @code{PostScript} editor @code{pstoedit} (version 3.50 or later;
9432available from @url{http://sourceforge.net/projects/pstoedit/}) includes an
9433@code{Asymptote} backend. Unlike virtually all other @code{pstoedit}
9434backends, this driver includes native clipping, even-odd fill rule,
9435@code{PostScript} subpath, and full image support. Here is an example:
9436@noindent
9437@code{asy -V @value{Datadir}/doc/asymptote/examples/venn.asy}
9438@noindent
9439@verbatim
9440pstoedit -f asy venn.eps test.asy
9441asy -V test
9442@end verbatim
9443
9444@noindent
9445If the line widths aren't quite correct, try giving @code{pstoedit} the
9446@code{-dis} option.
9447If the fonts aren't typeset correctly, try giving @code{pstoedit} the
9448@code{-dt} option.
9449
9450@node Help
9451@chapter Help
9452@cindex help
9453@cindex forum
9454
9455A list of frequently asked questions (@acronym{FAQ}) is maintained at
9456@quotation
9457@url{http://asymptote.sourceforge.net/FAQ}
9458@end quotation
9459@noindent
9460Questions on installing and using @code{Asymptote} that are not
9461addressed in the @acronym{FAQ} should be sent to the
9462@code{Asymptote} forum:
9463@quotation
9464@url{http://sourceforge.net/p/asymptote/discussion/409349}
9465@end quotation
9466@noindent
9467Including an example that illustrates what you are trying to do will help
9468you get useful feedback.
9469@code{LaTeX} problems can often be diagnosed with the @code{-vv} or
9470@code{-vvv} command-line options.
9471Contributions in the form of patches or @code{Asymptote} modules can be
9472posted here:
9473@quotation
9474@url{http://sourceforge.net/p/asymptote/patches}
9475@end quotation
9476@noindent
9477To receive announcements of upcoming releases, please subscribe to
9478@code{Asymptote} at
9479@quotation
9480@url{http://freecode.com/projects/asy}
9481@end quotation
9482@cindex bug reports
9483@noindent
9484If you find a bug in @code{Asymptote}, please check (if possible)
9485whether the bug is still present in the latest @code{Subversion}
9486developmental code (@pxref{Subversion}) before submitting a bug
9487report. New bugs can be submitted using the Bug Tracking System at
9488@quotation
9489@url{http://sourceforge.net/projects/asymptote}
9490@end quotation
9491@noindent
9492To see if the bug has already been fixed,
9493check bugs with Status @code{Closed} and recent lines in
9494@quotation
9495@url{http://asymptote.sourceforge.net/ChangeLog}
9496@end quotation
9497@noindent
9498
9499@cindex stack overflow
9500@cindex segmentation fault
9501@cindex @code{libsigsegv}
9502@code{Asymptote} can be configured with the optional @acronym{GNU} library
9503@code{libsigsegv}, available from
9504@url{http://libsigsegv.sourceforge.net}, which allows one to distinguish
9505user-generated @code{Asymptote} stack overflows (@pxref{stack overflow})
9506from true segmentation faults (due to internal C++ programming errors;
9507please submit the @code{Asymptote} code that generates such segmentation
9508faults along with your bug report).
9509
9510@node Debugger
9511@chapter Debugger
9512@cindex debugger
9513Asymptote now includes a line-based (as opposed to code-based)
9514debugger that can assist the user in following flow control. To set a
9515break point in file @code{file} at line @code{line}, use the command
9516
9517@cindex @code{stop}
9518@verbatim
9519void stop(string file, int line, code s=quote{});
9520@end verbatim
9521@noindent
9522The optional argument @code{s} may be used to conditionally set the variable
9523@code{ignore} in @code{plain_debugger.asy} to @code{true}. For example, the
9524first 10 instances of this breakpoint will be ignored (the
9525variable @code{int count=0} is defined in @code{plain_debugger.asy}):
9526@verbatim
9527stop("test",2,quote{ignore=(++count <= 10);});
9528@end verbatim
9529
9530To set a break point in file @code{file} at the first line containing
9531the string @code{text}, use
9532
9533@verbatim
9534void stop(string file, string text, code s=quote{});
9535@end verbatim
9536@noindent
9537To list all breakpoints, use:
9538@cindex @code{breakpoints}
9539@verbatim
9540void breakpoints();
9541@end verbatim
9542@noindent
9543To clear a breakpoint, use:
9544@cindex @code{clear}
9545@verbatim
9546void clear(string file, int line);
9547@end verbatim
9548@noindent
9549To clear all breakpoints, use:
9550@verbatim
9551void clear();
9552@end verbatim
9553
9554The following commands may be entered at the debugging prompt:
9555
9556@table @code
9557@cindex @code{help}
9558@item @code{h}
9559help;
9560@cindex @code{continue}
9561@item @code{c}
9562continue execution;
9563
9564@cindex @code{inst}
9565@item @code{i}
9566step to the next instruction;
9567
9568@cindex @code{step}
9569@item @code{s}
9570step to the next executable line;
9571
9572@cindex @code{next}
9573@item @code{n}
9574step to the next executable line in the current file;
9575
9576@cindex @code{file}
9577@item @code{f}
9578step to the next file;
9579
9580@cindex @code{return}
9581@item @code{r}
9582return to the file associated with the most recent breakpoint;
9583
9584@cindex @code{trace}
9585@item @code{t}
9586toggle tracing (@code{-vvvvv}) mode;
9587
9588@cindex @code{quit}
9589@item @code{q}
9590quit debugging and end execution;
9591
9592@cindex @code{exit}
9593@item @code{x}
9594exit the debugger and run to completion.
9595
9596@end table
9597@noindent
9598Arbitrary @code{Asymptote} code may also be entered at the debugging prompt;
9599however, since the debugger is implemented with @code{eval}, currently
9600only top-level (global) variables can be displayed or modified.
9601
9602The debugging prompt may be entered manually with the call
9603@verbatim
9604void breakpoint(code s=quote{});
9605@end verbatim
9606
9607@node Credits
9608@chapter Acknowledgments
9609@cindex acknowledgments
9610
9611Financial support for the development of @code{Asymptote} was generously
9612provided by the Natural Sciences and Engineering Research Council of
9613Canada, the Pacific Institute for Mathematical Sciences, and the
9614University of Alberta Faculty of Science.
9615
9616We also would like to acknowledge the previous work of John D. Hobby,
9617author of the program @code{MetaPost} that inspired the development of
9618@code{Asymptote}, and Donald E. Knuth, author of @TeX{} and
9619@code{MetaFont} (on which @code{MetaPost} is based).
9620
9621The authors of @code{Asymptote} are Andy Hammerlindl, John Bowman, and
9622Tom Prince. Sean Healy designed the @code{Asymptote} logo. Other
9623contributors include Michail Vidiassov, Radoslav Marinov, Orest Shardt,
9624Chris Savage, Philippe Ivaldi, Olivier Guib@'e, Jacques Pienaar,
9625Mark Henning, Steve Melenchuk, Martin Wiebusch, and Stefan Knorr.
9626
9627@node Index
9628@unnumbered Index
9629
9630@printindex cp
9631
9632@bye
9633
9634@c  LocalWords:  randMax Gaussrand asy cindex indices resized LaTeX TK latin au
9635@c  LocalWords:  latexusage tex bbox PostScript subdirectory gcc emacs ASYDIR
9636@c  LocalWords:  documentclass usepackage subpath shipout sqrt xN  Mx bw AcroRd
9637@c  LocalWords:  xscale xaxis yaxis BeginBar GIF postprocessing fpu de rpair xy
9638@c  LocalWords:  ImageMagick cd asymptote Hy 0pt 1filll 's 3D 2D 'asy
9639@c  LocalWords:  startup natively xasy tkinter VxN yingyang currentpicture toc
9640@c  LocalWords:  MetaPost MetaFont Hammerlindl Healy texinfo autoload setq setf
9641@c  LocalWords:  printindex setfilename settitle dircategory direntry titlepage
9642@c  LocalWords:  vskip filll insertcopying ifnottex detailmenu alist augroup PQ
9643@c  LocalWords:  bool behaviour facto zxf login Debian dev filetypedetect SVN
9644@c  LocalWords:  FFTW bp readline gv eps args Boehm gc evenoddoverlap png joe
9645@c  LocalWords:  boolean initializer expi dir xpart ypart STL substring rfind
9646@c  LocalWords:  pos substr strftime typedef pxref unitcircle yscale Bezier iff
9647@c  LocalWords:  postcontrol precontrol atleast nullpath arclength arctime rgb
9648@c  LocalWords:  dirtime currentpen colorspaces grayscale cmyk defaultpen x cx
9649@c  LocalWords:  linetype longdashed dashdotted longdashdotted linewidth y XP
9650@c  LocalWords:  fontsize defaultfilename keepAspect IgnoreAspect ise flushleft
9651@c  LocalWords:  src dest XDR txt getc fout stdin stdout endl eof js prc ni
9652@c  LocalWords:  Microsystem's eol exponentials postfix sayhi th Ubuntu
9653@c  LocalWords:  sqr intop addby libm asin acos atan sinh tanh asinh acosh cbrt
9654@c  LocalWords:  atanh fabs hypot fmod ceil srand dereferenced alice pete sqrtx
9655@c  LocalWords:  eval fft csv runtime nonalphanumeric labely LeftTicks NoTicks
9656@c  LocalWords:  RightTicks BottomTop LeftRight Ticksize UTF BufNewFile BufRead
9657@c  LocalWords:  ticksize subintervals xlimits filetype plugin setlocal makeprg
9658@c  LocalWords:  ylimits uncommented automin automax cp uninstall reals ecast
9659@c  LocalWords:  scaleT unicode RightSide yx yy NoAlign legendmargin opic CCW
9660@c  LocalWords:  arrowbar LeftSide EndBar BeginArrow lly feynman isi showtarget
9661@c  LocalWords:  EndArrow BeginArcArrow EndArcArrow ArcArrow ArcArrows NoFill
9662@c  LocalWords:  filldraw fillpen drawpen errorformat bigsquare bezier darkblue
9663@c  LocalWords:  quartercircle darkgreen lightblue urx ury texpreamble sgn texi
9664@c  LocalWords:  lineargraph datagraph vertices parametricgraph uncomment ggv
9665@c  LocalWords:  loggraph generalaxis texhash arrowsize arrowangle arrowlength
9666@c  LocalWords:  SuppressQuiet MoveQuiet LIBREADLINE config MacOS prebuilt svn
9667@c  LocalWords:  ghostview gsview SIGHUP PDF acroread xpdf cutbefore strptime
9668@c  LocalWords:  libsigsegv intersectionpoint dotfactor vv firstcut pq logticks
9669@c  LocalWords:  Unisys dvips vvv vvvv vvvvv traceback lastcut cutafter infodir
9670@c  LocalWords:  zxvf xargs cond polargraph xmin xmax plabel YZero labelling ln
9671@c  LocalWords:  ymin ymax XZero xequals tickmin tickmax unlabelled se pq pena
9672@c  LocalWords:  yequals Nobre Barbarosie Schwaiger nearearth conicurv Wiebusch
9673@c  LocalWords:  unfill posterSize ngraph interpolatetype ctrl dt pic getint Ai
9674@c  LocalWords:  NNE jxf linecap linejoin unitsquare shadedtiling ei nomarker
9675@c  LocalWords:  westnile minipage ra penb paletteticks drawline nV FillDraw uv
9676@c  LocalWords:  susceptibleM flushright secondaryX secondaryY secondaryaxis tt
9677@c  LocalWords:  titlelabel columnlabel rb xtick ytick labelx XEquals YEquals
9678@c  LocalWords:  treetest eetomumu fermi backend pstoedit drawtree xFF MSDOS gz
9679@c  LocalWords:  vimrc CFLAGS verbatiminclude online noindent bezier superpath
9680@c  LocalWords:  evenodd squarecap roundcap extendcap miterjoin roundjoin NFSS
9681@c  LocalWords:  beveljoin fillrule zerowinding insideness lineskip cmr pcrr Hx
9682@c  LocalWords:  AvantGarde Bookman Helvetica NewCenturySchoolBook minbound pdf
9683@c  LocalWords:  Palatino TimesRoman ZapfChancery ZapfDingbats german basealign
9684@c  LocalWords:  nondeconstructed backends usr venn labelsquare nobasealign dp
9685@c  LocalWords:  NoMargin BeginMargin EndMargin BeginPenMargin EndPenMargin dm
9686@c  LocalWords:  PenMargin PenMargins TrueMargin labelmargin errorbars errorbar
9687@c  LocalWords:  dpx dpy dmx dmy barsize arrowsize BeginDotMargin DotMargin acc
9688@c  LocalWords:  EndDotMargin DotMargins NColors BWRainbow colorspace labelled
9689@c  LocalWords:  PaletteTicks defaultformat leastsquares bjam fprintf endgroup
9690@c  LocalWords:  begingroup xmargin ymargin pbox box ellipse wget exe Gouraud
9691@c  LocalWords:  multithreaded newframe init emph nums concat xline yline zpart
9692@c  LocalWords:  colatitude zscale cosh nullpen MetaFontbook cyclicflag FreeBSD
9693@c  LocalWords:  nodeps Ghostgum beginlabel endlabel pTick ptick loggrid SAS dy
9694@c  LocalWords:  currentprojection latticeshading subpictures colinear unitcube
9695@c  LocalWords:  Autoscaling solveQuadratic MidArrow MidArcArrow Prebuilt url
9696@c  LocalWords:  pdftex comment getstring getstringprefix getreal defaultS hsv
9697@c  LocalWords:  ticklocate autoscaleT autoscaling vectorfield autolimits dvi
9698@c  LocalWords:  zlimits inline dvipdf hyperdvi autoconf gui zerowindingoverlap
9699@c  LocalWords:  prepended intMax quadraticroots cubicroots filltype prepend dx
9700@c  LocalWords:  ticklabel popup UnFill markroutine marknodes markuniform erf
9701@c  LocalWords:  intersectpoint cyrillic mathtext russian brokenaxis Datadir ds
9702@c  LocalWords:  resetdefaultpen latticeshade axialshade radialshade erfc det
9703@c  LocalWords:  gouraudshade unescaped nmesh surfacepen getpair MikTeX dw YZ
9704@c  LocalWords:  meshpen localhistory axisT roundedpath unitsize aSin accel pre
9705@c  LocalWords:  fontcommand makepen aCos aTan Knorr roundpath BeginPoint nView
9706@c  LocalWords:  MidPoint EndPoint nmask antialiasing autoplain batchMask libgc
9707@c  LocalWords:  batchView clearGUI ignoreGUI interactiveMask interactiveView
9708@c  LocalWords:  listvariables outformat parseonly prepending psviewer nCircle
9709@c  LocalWords:  pdfviewer papertype tabcompletion noautoplain plugins Teixeira
9710@c  LocalWords:  embeddedmovie historylines RadialShade penc penr CJK tgz GPL
9711@c  LocalWords:  legendlinelength legendskip USERPROFILE LDFLAGS currentlight
9712@c  LocalWords:  subsampled sinc kai AtBeginDocument GBK clearpage lasy texpath
9713@c  LocalWords:  AtEndDocument zaxis maxbound truepoint paperwidth paperheight
9714@c  LocalWords:  GSL deriv texcolors fixedscaling UpsideDown texreset slidedemo
9715@c  LocalWords:  subitem newslide realMin realMax realEpsilon realDigits gsl dh
9716@c  LocalWords:  obliqueX asycolors monthaxis xautoscale yautoscale zautoscale
9717@c  LocalWords:  obliqueZ obliqueY cylinderskeleton block llcorner dr py nx CPU
9718@c  LocalWords:  loc topleft topright bottomleft bottomright flowrectangle UTC
9719@c  LocalWords:  chartblock flowdiamond flowcircle xlabel BezierSurface el xyz
9720@c  LocalWords:  flowroundrectangle flowbevel flowpath drawflow blocks ny cpu
9721@c  LocalWords:  multipleView usersetting mediumgray flowchartdemo ylabel nv xf
9722@c  LocalWords:  zlabel slopefields cputime roundrectangle slopefield libgccpp
9723@c  LocalWords:  tickfactor USERNAME writeable imagecontour logimage Dumoulin's
9724@c  LocalWords:  NoCrop parametricsurface realmult SoftLight HardLight interp
9725@c  LocalWords:  ColorDodge ColorBurn Ivaldi buildcycle autorotate mexicanhat
9726@c  LocalWords:  Gouraudcontour pdflatex preconfigured perline linelength hskip
9727@c  LocalWords:  penimage filloutside legendhskip legendvskip maxwidth CDlabel
9728@c  LocalWords:  tensorshade MPEG framepoint nonfunction Radoslav Marinov Mepis
9729@c  LocalWords:  Pienaar Melenchuk finalout Linspire Dpkg sudo dpkg dtx Tcount
9730@c  LocalWords:  windingnumber clickable pdfmovie dfn du animationdelay fprime
9731@c  LocalWords:  slidemovies ifdraft embeddedu externalmovie headerpen bodypen
9732@c  LocalWords:  GaussianSurface multiline binarytree tridiagonal portably AIX
9733@c  LocalWords:  binarytreetest Henning subsample breakpoint locator wireframe
9734@c  LocalWords:  labelpath intersectionpoints PSTricks pstextpath curvedlabel
9735@c  LocalWords:  LeftJustified RightJustified tickmodifier gunzip gmake IRIX dv
9736@c  LocalWords:  texcommand RET SITEDIR filegraph pathmarkers POSIX binput AOB
9737@c  LocalWords:  nonportable markinterval stickframe circlebarframe tix
9738@c  LocalWords:  crossframe tildeframe markangle StickIntervalMarker gswin expm
9739@c  LocalWords:  CrossIntervalMarker CircleBarIntervalMarker Ghostscript syzygy
9740@c  LocalWords:  TildeIntervalMarker autoimport calculateTransform bitwise tk
9741@c  LocalWords:  headersize bodysize minheaderwidth minheaderheight minwidth ZX
9742@c  LocalWords:  minbodywidth minbodyheight minheight mindiameter reltime PNG
9743@c  LocalWords:  relpoint Syzygy syzygies seekeof splinetype notaknot slopea ZY
9744@c  LocalWords:  slopeb nonperiodic circlescale MarkFill ScaleX ScaleY xformat
9745@c  LocalWords:  onecontour multicontour irregularcontour dvipsOptions saveline
9746@c  LocalWords:  dirSpecifier controlSpecifier tensionSpecifier atleastflag bsp
9747@c  LocalWords:  curlSpecifier cputimeformat initializers arbitary redeclaring
9748@c  LocalWords:  firstname lastname multdiagonal Raphson OmitTick OmitFormat sp
9749@c  LocalWords:  NoZero NoZeroFormat abbrevation gsOptions namespace redeclared
9750@c  LocalWords:  atLeast intMin globalwrite quarticroots deconsruct substrings
9751@c  LocalWords:  usleep currentpatterns trailingzero Orest Shardt DefaultHead
9752@c  LocalWords:  SimpleHead HookHead TeXHead multipage NURBS inlinemovie dxmax
9753@c  LocalWords:  simpson NoBox truesize autoscale shadestroke recurses mintimes
9754@c  LocalWords:  nonoverlapping texengine maxtimes maxheight pdb TEXMFCONFIG Jn
9755@c  LocalWords:  piecewisestraight unitrand graphmarkers antialias nolight newl
9756@c  LocalWords:  Delaunay Shewchuk convertOptions APPDATA pdfreload tempFile Yn
9757@c  LocalWords:  pdfreloadOptions deferred OpenGL Phong Blinn renderer unitbox
9758@c  LocalWords:  bezulate Shardt's rasterized viewport unitdisk unitplane devel
9759@c  LocalWords:  unitcylinder unitcone solidcone unitfrustum unitsphere nslices
9760@c  LocalWords:  DPostScript YZZero externalprc nonrendered nosafe KDE
9761@c  LocalWords:  unithemisphere versa XYplane xypart unitsolidcone YZEquals xml
9762@c  LocalWords:  XZEquals XYEquals XZZero XYZero InTicks OutTicks InOutTicks
9763@c  LocalWords:  fitscreen planeproject strokepath meshlight nullpens arrowdir
9764@c  LocalWords:  diffusepen ambientpen emissivepen specularpen arrowbarb keyval
9765@c  LocalWords:  hstretch vstretch roundbox nonconvex miterlimit basealigin cmd
9766@c  LocalWords:  maxviewport maxtile antialiased sphericalharmonic attachfile
9767@c  LocalWords:  vertexshading smoothelevation glOptions iconified iconify kate
9768@c  LocalWords:  psviewerOptions pdfviewerOptions viewportmargin asyattach SVG
9769@c  LocalWords:  multisampling autogen multisample coloredpath relstep flowdir
9770@c  LocalWords:  colortype coloredSegments coloredNodes trefoilknot scaledgraph
9771@c  LocalWords:  minblockwidth minblockheight mincirclediameter nonassociative
9772@c  LocalWords:  nonintegral gettriple enablerepo hexidecimal XeLaTeX xelatex
9773@c  LocalWords:  dvipdfmx autoadjust viewportsize viewportwidth viewportheight
9774@c  LocalWords:  subregions nonsimply functionshade shader floatingdisk TopView
9775@c  LocalWords:  functionshading maxlength LeftView odetest RadialShadeDraw CLZ
9776@c  LocalWords:  vectorfieldsphere RightView FrontView BackView BottomView CTZ
9777@c  LocalWords:  addViews outprefix addAllViews xsplinetype ysplinetype rotateX
9778@c  LocalWords:  usplinetype vsplinetype leftbutton middlebutton rightbutton
9779@c  LocalWords:  rotateY rotateZ wheelup zoomin wheeldown zoomout TeXLive pnorm
9780@c  LocalWords:  viewportshift signedint signedness psview multiplatform nowarn
9781@c  LocalWords:  singlereal singleint writeoverloaded dvisvg reddash lexorder
9782@c  LocalWords:  bigdiagonal autobillboard dvisvgm maxtiles hyperrefOptions xdr
9783@c  LocalWords:  setpagesize pdfborder controlsystem OmitTickInterval SixViews
9784@c  LocalWords:  OmitTickIntervals tickmodifiers autorotated SixViewsUS latexmk
9785@c  LocalWords:  ThreeViewsUS ThreeViewsFR SixViewsFR ThreeViews partialsum
9786@c  LocalWords:  defaultrender Vidiassov latexmkrc mktemp DOSendl DOSnewl perl
9787@c  LocalWords:  filename asyinclude latemk penfunctionimage Affine decrement
9788@c  LocalWords:  affine Redisplay redisplay isnan radians defaultseparator Jens
9789@c  LocalWords:  ascii piecewise arcpoint spacings tilings sncndn resizing
9790@c  LocalWords:  differentiable vectorization vectorized asydir normals quartic
9791@c  LocalWords:  wavepacket kerned parametrized specular hyperboloid Bourke's
9792@c  LocalWords:  Michail 0pt 1filll 's 3D latin1 labelpath3 2D graph3
9793@c  LocalWords:  grid3 contour3 i386 psv a4 gsview32 freeglut 'load '
9794@c  LocalWords:  'asy 'lasy 'auto 5bp 1cm sqrtx01 4g extenda extendb
9795@c  LocalWords:  bb llx 2S 100pt 3t bezier2 bool3 x0 angle1 angle2 z1
9796@c  LocalWords:  z2 before' struct X11 x11colors type1cm 12pt OT1 5mm
9797@c  LocalWords:  cmr12 x' y' xsize ysize 25cm s1 s2 neighbourhood u''
9798@c  LocalWords:  s'' 3x 5x 3y 602e 2x 2y 3sin 10cm 204e addby7 10x Ai
9799@c  LocalWords:  only'' pow10 log10 expm1 log1p atan2 0pt 1filll 's '
9800@c  LocalWords:  x1 x2 graph2d attachfile2 n0 P0 n1 P1 markers1 3D 2D
9801@c  LocalWords:  interpolate1 markers2 inlinemovie3 media9 U3D T2A 5E
9802@c  LocalWords:  embeddedu3d curvedlabel3 value2 tickvalue inner'' 2N
9803@c  LocalWords:  lineargraph0 scalings log2 log2graph 5cm BWRainbow2
9804@c  LocalWords:  guide3 path3 unitcircle3 2E 2n noV 100d PostScript3D
9805@c  LocalWords:  size3 fit3 theta1 phi1 theta2 phi2 v1 v2 unitsquare3
9806@c  LocalWords:  t1 t2 5z 5y transform3 identity4 xscale3 yscale3 0pt
9807@c  LocalWords:  zscale3 scale3 join3 BeginBar3 EndBar3 Bar3 Bars3 's
9808@c  LocalWords:  BeginArrow3 MidArrow3 EndArrow3 Arrow3 Arrows3 axes3
9809@c  LocalWords:  BeginArcArrow3 MidArcArrow3 EndArcArrow3 ArcArrow3 '
9810@c  LocalWords:  ArcArrows3 DefaultHead3 HookHead3 TeXHead3 HookHead2
9811@c  LocalWords:  DefaultHead2 TeXHead2 arrows3 NoMargin3 BeginMargin3
9812@c  LocalWords:  EndMargin3 Margin3 Margins3 BeginPenMargin2 xaxis3 '
9813@c  LocalWords:  EndPenMargin2 PenMargin2 PenMargins2 BeginPenMargin3
9814@c  LocalWords:  EndPenMargin3 PenMargin3 PenMargins3 BeginDotMargin3
9815@c  LocalWords:  EndDotMargin3 DotMargin3 DotMargins3 TrueMargin3 3D
9816@c  LocalWords:  yaxis3 zaxis3 ticks3 NoTicks3 arrowbar3 type2 axis3
9817@c  LocalWords:  generalaxis3 vectorfield3 margin3 grid3xyz 5unit 2D
9818@c  LocalWords:  slopefield1 144x144 1filll 'load 'asy 'lasy 'auto 4g
9819@c  LocalWords:  libgs 'load 'asy 'lasy 'auto 5bp 1cm 2S 100pt 3t 5mm
9820@c  LocalWords:  bracedefaultratio incircle 12pt 25cm 3x 5x 3y 602e '
9821@c  LocalWords:  2x 2y 3sin 10cm 204e 10x Ai 5E offaxis 'load 'lasy
9822@c  LocalWords:  5cm 2N 2E 2n 100d 5z 5y 5unit dvisvgmOptions 144x144
9823@c  LocalWords:  4g texengines coplanar
9824@c  LocalWords:  insphere cospherical 5unit luatex lualatex
9825