Home
The Metafun manual - (La)TeX Navigator
Contents
1. Table 7 2 hashed table This table is defined as bTABLE frame off meta hash linecolor darkyellow offset 3ex bTR bTD background meta hash right right eTD bTD background meta hash left left eTD bTD background meta hash horizontal horizontal eTD bTD background meta hash vertical vertical eTD eTR eTABLE The graphics themselves are defined in a METAPOST module In this particular example the macro some hash is defined in the file mp back mp This macro takes six arguments some hash width height linewidth linecolor angle gap Preliminary Version October 27 2000 Because we don t want to define a specific overlay for each color and linewidth we will use vari ables in the definition of the unique graphic NstartuniqueMPgraphic meta hash linewidth linecolor angle gap input mp back some hash overlaywidth overlayheight MPvar linewidth MPvar linecolor MPvar angle MPvar gap stopuniqueMPgraphic F These variables are preset using setupMPvariables setupMPvariables meta hash gap 25 bodyfontsize angle 45 linewidth overlaylinewidth linecolor overlaylinecolor The last step in this process is to define the different alternatives as overlay
2. Preliminary Version October 27 2000 Typesetting in offe 35 59 N ta o Da a e NstartuseMPgraphic followtokens path RotPath RotPath 3cm 0 3cm lcm stopuseMPgraphic We now follow RUM o arbitrary c NstartuseMPgraphic followtokens path RotPath RotPath 3cm 0 1cm locm 3cm 0 stopuseMPgraphic golow some arb tra 0 45 NstartuseMPgraphic followtokens path RotPath RotPath 3cm 0 1em 1cm 0cm 2cem 0 stopuseMPgraphic Ww e9 fo o 2 06 When turned on tracing will produce bouding boxes as well as draw the path Tracing can be turned on by saying NstartMPinclusions boolean TraceRot stopMPinclusions 9 5 Talking to TEK TraceRot true Sometimes others may say oftentimes we are in need for some fancy typesetting If we want to typeset a paragraph of text in a non standard shape like a circle we have to fall back on pu Preliminary Version October 27 2000 parshape Unfortunately TEK is not that strong in providing the specifications of more compli cated shapes unless you are willing to do some complicated arithmetic Given that METAPOST knows how to deal with shapes the question is Can metarost be of help In the process of finding out h
3. syah Preliminary Version October 27 2000 path expression list path expression path expressionlist path expression on off list on off list on off clause on off clause on off clause on numeric tertiary o numeric tertiary boolean expression expression color expression expression numeric atom atom numeric expression expression numeric primary primary numeric tertiary tertiary numeric variable variable internal variable pair expression expression path expression expression path subexpression subexpression expression expression picture expression expression picture variable variable string expression expression suffix parameter parameter pair primary primary transform primary primary program statement list end statement list empty statementlist statement statement empty equation assignment declaration compound pseudo procedure macro definition command Preliminary Version October 27 2000 compound begingroup statement list endgroup beginfig numericexpression statement list endfig equation
4. Preliminary Version October 27 2000 endfig enddef The definition of mark rt angle is copied from the METAPOST manual and shows how compact a definition can be angle radius 10pt def mark rt angle expr a b c draw 1 0 1 1 0 1 zscaled angle radius unitvector a b shifted b enddef We are going to draw a lot of pictures so we define an extra macro This time we hard code some values The fractions i and j are responsible for the visual iteration process def do draw problem expr n i j draw problem 4000 n 400pt 400pt 300pt 600pt i 300pt 600pt 550pt 800pt j 400pt 400pt 550pt 500pt enddef The beginfig and endfig macros package the code into a graphic capsule which is output to the resulting file We will spend some more words on that later Of course we could have used some loop here but defining an auxiliary macros probably takes more time than simply calling the drawing macro directly The results are shown on a separate page It does not need that much imagination to see the four sided problem converges to a three sided one which itself converges to a two sided one In the two sided alternative it s not that hard to prove that the angle is indeed 90 degrees do draw problem 40 1 0 1 0 do draw problem 41 0 8 1 0 do draw problem 42 0 6 1 0 do draw problem 43 0 4 1 0 do draw problem 44 0 2 1 0 do dra
5. It may make more sense to rotate the shape around its center This can easily be achieved with the rotatedaround command Again we move the path to the right afterwards p rotatedaround center p 15 shifted 4cm 0cm ND 2 Yet another transformation is slanting Just like characters can be upright slanted a graphic can be p slanted 1 5 shifted 4cm lt A The slant operation s main application is in tilting fonts The x coodinates are increased by a percentage of their y coordinate so here every x becomes x 1 5 The y coordinate is left untouched The following table summarizes the most important primitive transformations that METRPOST supports METRPOST code mathematical equivalent shifted a b x y scaled s sx sy x y xscaled s sx y x y yscaled s x zscaled u v yv xv yu x y slanted s x sy y x y rotated r x cos r y sin r x sin r y cos r The previously mentioned rotatedaround is not a primitive but a macro defined in terms of shifts and rotations Another transformation macro is mirroring or in METRPOST terminology reflectedabout Preliminary Version October 27 2000 The reflection axis is specified by a pair of points For example in the graphic above we used the following command to reflect the square about a line through the given
6. Knuth has spent the past several years working on a system allowing him to control many of the design of his forthcoming books from the typesetting and layout down to the very apes of the letters Seldom has an author had anything remotely like this power to control th 1 appearance of his or her work Knuth s typesetting system has become well known ane wailable in many countries around the world By contrast his varo system for designing milies of typefaces has not become as well known or available In his article The Concept of a Meta Font Knuth sets forth for the first time the underlying hilosophy of wersror as well as some of its products Not only is the concept exiting and clearh ell executed but in my opinion the article is charmingly written as well However despite my werall enthusiasm for Knuth s idea and article there are some points in it that 1 feel might 1 iken wrongly by many readers and since they are points that touch close to my deepest interes artificial intelligence and esthetic theory 1 felt compelled to make some comments to clarify ertain important issues raised by The Concept of a Meta Font Version October 17 2000 even odd Figure 6 6 A quick way to draw all used areas Advanced features Coming up with some more advanced graphics is not so much a problem of definition as well as
7. 222 138 Chemistry 222 139 Growing graphics 223 13 10 Simple Logos 230 1311 Animations 235 14 MetaFunmacros 237 15 Example graphics 239 A Programs 241 METRPOST 2 252 4522 241 A2 paeka akh a 241 3 COMTEX 222252226 ness 241 4 242 A5 MPtoPDF 242 A6 Testcase 243 B METRPOST syntax OP Seb a 245 B 1 Syntaxdiagrams 245 B 2 Listofthings 254 C Thisdocument 255 D Reference 257 Di Paths Bae ees 257 0 2 Transformations 265 POIs lee oes 273 DA Attributes 275 DS ext sirro be E va 280 E Literature 283 E 2 E 3 4 METAFONT METRPOST 283 gabag e rer Pei 283 CONTEXT 555 554 283 Tools aise sdb aa AJA 283 Distributions 283 285 Preliminary Version October 27 2000 Conventions When reading this manual you may be tempted to test the examples shown This can be done in several ways You can make a file and process that file METAPOST Such a file looks like input mp tool some initializations and auxiliary macros 9 o input mp
8. The points that are used to construct the paths are defined using the constants w h ww and hh These are defined as follows w 4cm h 2cm ww 1cm hh 1 5cm In this case we draw two shapes that leave part of the rectangle uncovered If you have a back ground this technique allows the background to show through the graphic A not uncommon practice when making complicated graphics is to use unfill operations Since METRPOST provides one let us see what happens if we apply this command fill 0 0 w 0 w h 0 h cycle unfill ww 0 w hh ww hh cycle This does not always give the desired effect because METAPOSTS unfill is not really an unfill but a ill with color background Since this color is white by default we get what we just showed So if we set background to black using background black we get Of course you can set the variable background to a different color but this does not hide the fact that METAPOST lacks a real unfill operation Since we don t consider this un i11 a suitable operator you may wonder how we achieved the above result Preliminary Version October 27 2000 fill 0 0 0 n w h w 0 ww 0 hh ww hh ww 0 cycle This feature depends on the POSTSCRIPT way of filling closed paths which comes down to filling either the left or the right hand side of a curve The following alter
9. Welcome lo METAPOST Preliminary Version October 27 2000 1 4 z0 zl cycle cutafter directionpoint 1 1 of z0 zl cycle We will apply these commands in the next chapters but first we will finish our introduction in METRPOST We have seen how a path is constructed and what can be done with it Now it is time to demonstrate how such a path is turned into a graphic Drawing pictures Once a path is defined either directly or as a variable you can turn it into a picture You can draw a path like we did in the previous examples or you can fill it but only if it is closed 1 1 Drawing is done by applying the draw command to a path as in draw 0cm l1cm 2cm 2cm 4cm 0cm cycle The rightmost graphic was made with 111 fill Ocm 1lcm 2cm 2cm 4cm 0cm cycle If you try to duplicate this drawing you will notice that you will get black lines instead of red and a black fill instead of a gray one When drawing or filling a path you can give it a color use all kinds of pens and achieve special effects like dashes or arrows Preliminary Version October 27 2000 These two graphics were defined and drawn using the following commands Later we will explain how you can set the line width or penshape in terms of METAPOST path p p 0cm 1cm 2cm 2cm 4cm 2cm 1em cycle drawarrow p withcolor 625r
10. Preliminary Version October 27 2000 Welcome to METAB The arrows are drawn using the previously defined macros Watch the positive and negative offsets in call to pointarrow drawarrow leftarrow p point 1 of p 2cm withcolor red j drawarrow centerarrow p point 2 of p 2cm withcolor blue A drawarrow rightarrow p point 3 of p 2cm withcolor green H drawarrow pointarrow p 60 4cm 5cm withcolor yellow drawarrow pointarrow p 75 3cm 5om withcolor cyan drawarrow centerarrow p 90 3cm withcolor magenta Preliminary Version October 27 2000 2 1 A few more details In this chapter we will see how to define a METAPOST graphic and how to include it in a document Since the exact dimensions of graphics play an important role in the placement of a graphic we will explore the way a bounding box is constructed We will also pay attention to the usage of units and the side effects of scaling and shifting since they can contradict our expectations in unexpected ways Furthermore we will explore a few obscure areas Making graphics We will use METAPOST in a rather straightforward way and as much as possible we will try to avoid complicated math We will do a bit of drawing clipping and moving around Occasionally we will see some more complicated manipulations When defined as stand alone graphic a fi
11. 2 2 5u 4 x 3 w 3 5u 4 y 3 3 5u 5 x 4 w 4 5u 5 4 4 5u Because we are going to repeat ourselves we draw the areas using a macro Depending on its importance we color it red or yellow def do it expr xx yy cc draw unitsquare xyscaled w xx h yy shifted withcolor if cc 625red else 625yellow fi enddef fill unitsquare xyscaled width height withcolor 85white do it 1 1 false do it 5 1 false do it 2 1 false do it 3 1 false do it 4 1 false do it 1 2 false do it 5 2 false do it 2 2 true do ijt 3 2 true do it 4 2 tr e do it 1 3 false do it 5 3 false do it 2 3 true do it 3 3 true do it 4 3 true do it 1 4 false do it 5 4 false do it 2 4 true do it 3 4 true do it 4 4 true Preliminary Version October 27 2000 edge margin text margin edge 9 ede UI CC CC CAC we DC E E P gebadkgroundssl Preliminary Version October 27 2000 6 2 do 15 1 5 false do 5 5 false do it 2 5 false do it 3 5 false do it 4 5 false This picture in itself is not yet explanatory so we add some labels Again we use a macro which we feed with a picture generated by S
12. these units are hard coded and han dled by the parser where the internal unit of length is the scaled point sp something on the nanometer range Because METRPOST is focused on POSTSCRIPT output its internal unit is the big point bp All other units are derived from this unit and available as numeric instead of hard coded Preliminary Version October 27 2000 mm 2 83464 pt 0 99626 dd 1 06601 bp 1 cm 28 34645 11 95517 12 79213 in 72 Careful reading reveals that only the bp and in are fixed while the rest of the dimensions are scalar multiples of bp Since we are dealing with graphics the most commonly used dimensions are pt bp mm cm and in 27pt bp 25 4mm 2 54 lin The text in the center of the leftmost graphic is typeset by METAPOST as a label fill fullsquare scaled 72 27pt withcolor 625yellow fill fullcircle scaled 72 27pt withcolor white label 72 27pt center currentpicture In METAPOST the following lines are identical draw fullcircle scaled 100 draw fullcircle scaled 100bp You might be tempted to omit the unit but this can be confusing particularly if you also program in a language like METAFONT where the pt is the base unit This means that a circle scaled to 100 in METPPOST is not the same as a circle scaled to 100 in METAFONT Consider the next definition
13. This picture demonstrates that we can also position textext s and label s on the baseline For this purpose the repertoire of positioning directives top 1ft etc is extended with a origin directive picture textext origin MPstring 2 picture r r thelabel origin MMPtext 3 origin We will now apply this knowledge of text inclusion in graphics to a more advanced example The next definitions are the asnwer to a question on the CONTEXT mailinglist with regards to framed texts with titles Preliminary Version October 27 2000 Coming back to the use of typefaces in electronic publishing many of the new typographers receive their knowledge and information about the rules of typography from books from computer maga zines or the instruction manuals which they get with the purchase of a PC or software In this example the title is positioned on top of the frame Title and text are entered as FrameTitle Zapf 1 StartFrame Coming back to the use of typefaces in electronic publishing many of the new typographers receive their knowledge and information about the rules of typography from books from computer magazines or the instruction manuals which they get with the purchase of a PC or software StopFrame The implementation is not that complicated and uses the frame commands that are built in CONTEXT Instead of letting draw the frame
14. Preliminary Version October 27 2000 Welcome jo ye Taros i 1 8 drawdot i cm j cm n n 1 done i j n fi exitif n 10 endfor Here we remain in the loop until we have 10 points placed We use an array to keep track of placed points The METAPOST macro uniformdeviate n returns a random number between 0 and n and the round command is used to move the result toward the nearest integer The unknown primitive allows us to test if the array element already exists otherwise we exit the conditional This saves a bit of computational time as each point is drawn and indexed only once The loop terminator exitif and its companion exitunless can be usedin for forsuffixes and forever Macros In the previous section we introduced upto Actually this is not part of the built in syntax but a sort of shortcut defined by def upto step 1 until enddef You just saw a macro definition where upto is the name of the macro The counterpart of upto is downto Whenever you use upto itis replaced by step 1 until This replacement is called expansion There are several types of macros A primary macro is used to define your own operators For example primarydef p doublescaled s p xscaled s 2 yscaled s 2 enddef Once defined the doublescaled macro is implemented as in the following example draw somepath doublescaled 2cm withcolor red When this command is e
15. Save x y z 1 1 p zI21I1 9 zIS3II1 zl4 1 for i 1 upto 4 z i 1 x i Ylil 1 z if i l 4 else 1 1 fi 2 z i 2 xlil 2 vlil 21 z i 3 x i 2 y i 2 y Li 1 ylill 21 1 x lill2 xlil 11 z i 4 x i y ilI 2 y ilI 1 vIil i x ilI2 x il 11 z i O 5 z i 72 1 3 endfor 2 0 2 1 2 3 whatever z 2 z 4 pickup pencircle scaled 5pt for i 1 upto 4 draw z i 1 z i 2 z i 3 z i 4 cycle draw z i 1 z i 3 draw z i 2 z i 4 if i 3 draw z i z i 2 dashed evenly fi endfor draw 1 0 1 1 0 1 zscaled unitvector z 1 z 0 10pt shifted z 0 endfig enddef I think that we could argue quite some time about the readability of this code If you start from a sketch and the series of equations does a good job there is hardly any need for such improve ments to the code On the other hand there are situations where the simplified reduced case can be extended more easilly for instance to handle 10 points instead of 4 It all depends on how you want to spend your free hours Preliminary Version October 27 2000 Welco 10 1 14 Clipping For applications that do something with a drawing for instance embedding a graphic in a text flow it is important to know the dimensions of the graphic The max
16. The double dash is also a macro used to connect two points with a straight line segment However cycle is a primitive which connects the last point of the unitsquare to the first on unitsquare s path Path variables must first be declared as in path unitsquare A large collection of such macros is available when you launch METAPOST Consult the METAPOST manual for details In the first line of our example we set the drawing pen to 5cm You can also specify such dimension in other units like points pt When no unit is provided METAPOST will use a big point bp the POSTSCRIPT approximation of a point The second line does just as it says it draws a rectangle of certain dimensions in a certain color In the third line we draw a colored dot at the origin of the coordinate system in which we are drawing Finally we set up a smaller pen and draw the bounding box of the current picture using the variable currentpicture Normally all drawn shapes end up in this picture variable Bounding boxes If you take a close look at the last picture in the previous section you will notice that the bounding box is larger than the picture This is one of the nasty side effects of MeTAPOST s bbox macro This macro draws a box but with a certain offset The next example shows how we can manipulate few more details Preliminary Version October 27 2000 this offset Remember that in
17. V The next step in the construction of the perpendicular bisector requires that we find and label the points of intersection of the two circles centered at points A and B The intersection points are calculated as follows Watch the reverse operation which makes sure that we get the second intersection point startbuffer e def draw_intersection pair pointC pointD pointC circleA intersectionpoint circleB pointD reverse circleA intersectionpoint reverse circleB draw dot pointC label lft btex C etex pointC shifted 2w 0 draw dot pointD label lft btex D etex pointD shifted 2w 0 enddef stopbuffer In placing the label we must make sure that the text runs free of the lines and curves Again move the stand_out macro just prior to draw_intersection macro so that this step is highlighted in the drawing color while prior steps are drawn in the default color in this case black Preliminary Version October 27 2000 A few applications startbuffer 3 start_everything draw_basics draw_circles stand_out draw_intersection stop_everything stopbuffer A V The line drawn through points C and D will be the perpendicular bisector of the line segment connecting points A and B In the next step we will draw a line using the plain METAPOST drawdblarrow macro that draws arrowheads at each end of a path
18. rh unfilldraw unfilldraw fullcircle metapost macro undrawfill undrawfill fullcircle 7 ao 4 metapost macro c z S 5 2 undrawdot origin metapost macro Preliminary Version October 27 2000 c E 5 5 origin 1 1 butt metapost macro linecap butt rounded amp squared 5 4 lt Preliminary Version October 27 2000 metapost variable linecap rounded metapost variable linecap squared metapost variable linejoin mitered metapost variable DS rounded 2 em Text linejoin rounded metapost variable linejoin beveled metapost variable label MetaFun origin metapost macro label top MetaFun origin metapost macro label bot label bot MetaFun origin metapost macro label lft label 1 t MetaFun origin metapost macro label rt MetaFun origin metapost macro Preliminary Version October 27 2000 label llft etaFun label lrt label llft MetaFun origin metapost macro label lrt MetaFun origin label urt metapost macro label urt MetaFun origin VletaFun label ulft metapost macro label ulft MetaFun origin MetaFun btex text etex Meta Preliminary Version October 27 2000 metapost macro draw btex MetaTeX etex metapost primitive
19. setupbackgrounds text rightmargin background copyright In both cases we slightly scale down the graphic We do so because otherwise a small portion of the text if clipped off This is unrelated to TEK or METAPOST but a characteristic of the font Compare the following Palatino Computer Modern and Times 0 s the Palatino is the body font of this text Ndefinefont fP Palatino Roman at 5cm Ndefinefont fC ComputerModern at 5cm Ndefinefont fT Times Roman at 5cm showboxes hbox hbox fP o hbox fC o hbox fT The dashed line is the baseline Watch how the bounding boxes differ and sometimes cross the shape So in order not to loose part of a glyph when clipping you need to add a bit space Figure 6 1 shows the two backgrounds in action Preliminary Version October 27 2000 Edward R Tufte into w the wheat from the chaff and separate the sheep the new system must not only betheimplementer ent the past Several y ars working of his forthcoming books from th Preliminary Version October 17 2000 Preliminary Version October 17 2000 concept copyright Figure 6 1 Two examples of annoying backgrounds If you really want to add such texts to a document in CONTEXT we don t have to use the page background b
20. 3cm 1cm drawarrow origin a drawarrow origin b drawarrow anglebetween a b scaled lcm withcolor 625red where anglebetween is defined as def anglebetween expr a b unitvector a a rotated 90 unitvector enddef Both unitvectors return just a point on the line positioned 1 unit later scaled to 1cm from the origin We connect these points by a curve that starts in the direction on the first point If we omitthea rotated 90 direction specifier we get These definitions of anglebetween far from perfect If we don t start in the origin we get the curve in the wrong place and when we swap both points we get the wrong curve The solution for the displacement is given in the METAPOST manual and looks like this we package the macro a bit different def anglebetween expr endofa endofb common length unitvector endofa common endofa common rotated 90 unitvector endofb common scaled length shifted common enddef As you can see we compensate for the origin of both vectors This macro is called with a few more parameters We need to pass the length since we want to add the shift to the macro and the shift takes place after the scaling A few applications Preliminary Version October 27 2000 pair c a 2ecm 1om b 3cm 1 c lem 5cm drawarrow c a drawarrow c b drawarrow anglebetween a
21. Nstartbuffer f def draw bisector path lineCD lineCD origin origin shifted 2 distance 0 lineCD lineCD rotated 90 shifted 0 5 pointA pointB lineCD lineCD shifted 0 distance drawdblarrow lineCD enddef stopbuffer startbuffer 4 start_everything draw_basics draw_circles draw_intersection stand_out draw_bisector stop_everything stopbuffer IN M The following code draws the intersection of line C D and line segment A B which can be shown to be the midpoint of segment A B A jew applications Preliminary Version October 27 2000 startbuffer g def draw_midpoint pair pointM pointM lineCD intersectionpoint lineAB draw dot pointM label llft btex M etex pointM enddef stopbuffer startbuffer 5 start_everything draw_basics draw_circles draw_intersection draw_bisector stand_out draw_midpoint stop_everything stopbuffer dh M As long as we place the graphics as individual insertions in our document everything is fine However if we wish to place them all at once or as we shall see later place them on top of one another in a fieldstack it makes sense to give them all the same bounding box We can do this by completing the start everything and stop everything commands startbuffer a def start_everything path bb draw_basics draw_
22. a calculates a vector starting at a and ending at b In METAPOST the expression a b is identical to Va b Thus the expression xpart ypart b a calculates the length of the vector b a Because the un scaled spring has length n 2h scaling by the expression xpart b a ypart b a n 2h gives the spring the same length as the vector b a Because we have drawn our spring in the vertical position we first rotate it 90 degrees clock wise to a horizontal position and then rotate it through an angle equal to the angle in which the vector b a is pointing After that we shift it to the first point The main complications are that we also want to draw connecting lines at the beginning and end as well as support springs that connect arbitrary points Since no check is done on the parameters you should be careful in using this macro When we want to improve the readability we have to use intermediate variables Since the macro is expected to return a path we must make sure that the content matches this expectation EA few applications Preliminary Version October 27 2000 vardef spring expr a b w h n pair vec path pat numeric len numeric ang vec b a pat for i 1 upto n 1 if odd i fi w 2 i endfor 0 n pat 0 0 0 h pat shifted 0 h 0 nth 0 n 2h len xpart vec ypart vec n 2h ang 90 angl
23. top lftert bot The command thelabel returns a picture with the label so that you can say pair a 3cm 3cm pickup pencircle scaled 1mm drawdot a withcolor 625yellow draw thelabel rt the right way a withcolor 625red You can of course rotate slant and manipulate such a label picture like any other picture ethe right way Welcome to Preliminary Version October 27 2000 The font can be specified in the string default font and the scale in defaultscale Labels are defined using the low level operator infont The next statement returns a picture draw this string will become a sequence of glyphs MP infont defaultfont scaled defaultscale The infont operator is not that clever and does not apply kerning Also typesetting math or accented characters is not supported The way out of this problem is using btex etex draw btex this string will become a sequence of glyphs NTeX etex The difference between those two methods is shown below this string will become a sequence of glyphs MP this string will become a sequence of glyphs The second line is typeset by TEK and is properly kerned As we may expect from the command becomes the logo Instead of passing strings to infont you can also pass characters using char for example char 73 When you use infont you normally expect the font
24. defineoverlay nextpage overlaybutton nextpage An overlaybutton is just a button with all attributes color frame etc set to nothing having the dimensions of the overlay The argument is one of the permitted destinations like next page firstpage SearchDocument and alike For efficiency reasons the backgrounds areas like text text 1 are calculated only when their definition has changed When a background changes per page we have to recalculate it on each page In the next example the macro overlaybutton generates a different button on each page But since we don t explicitly set the background at each page there is no way the background drawing mechanism can know that this button has changed Therefore we must force recalculation with setupbackgrounds state repeat You can test this concept yourself with the following code Here we assume that you have a file called tufte tex on your system which is the case if you have CONTEXT installed However you can just as easily use any file having a paragraph of two of text starttext setupinteraction state start setupbackgrounds state repeat defineoverlay nextpage overlaybutton nextpage setupbackgrounds text text background nextpage dorecurse 20 input tufte par stoptext Note that you can move forward from page to page in the resulting PDF file by clicking on each page with the mouse Now compile this file without setting the back
25. defineoverlay test 1 useMPgraphic test 1 defineoverlay test 2 useMPgraphic test 2 defineoverl test 3 test 4 useMPgraphic test 3 useMPgraphic test 4 defineoverlay As text we use a quote from Douglas R Hofstadter s book Metamagical Themas Questing for the Essence of Mind and Pattern Watch how we pass a list of shapes startshapetext test 1 test 2 test 3 test 4 input douglas Douglas R Hofstadter stopshapetext Finally we combine text and shapes Since we also want a background we use framed The macros parwidth and parheight are automatically set to the current shape dimensions The normal result is shown in figure 9 2 startbuffer setupframed offset overlay align normal frame off Preliminary Version October 27 2000 _ width parwidth height Nparheight startcombination 2 2 getshapetext test 1 framed background test 1 getshapetext test 2 1 framed background test 2 framed background test 3 framed background test 4 getshapetext test 3 getshapetext test 4 stopcombination stopbuffer By using a buffer we keep placefigure readable placefigure here fig shapes A continuous text typeset in a non standard shape Spread over four areas and right alligned getbuffer The traced alternative is sh
26. label labelsuffix expression pairexpression dotlabel label suffix expression pair expression labels label suffix point number list dotlabels labelsuffix point number list freelabel expression pairexpression pairexpression freedotlabel expression pairexpression pairexpression point number list suffix point number list suffix label suffix empty lft top bot ulft urt 11ft Irt Preliminary Version October 27 2000 command clip picture variable to path expression interim internal variable right hand side let symbolic token symbolic token newinternal symbolic token list pickup expression randomseed numeric expression save symbolic token list setbounds picture variable to path expression shipout picture expression special string expression addto command drawing command font metric command show command tracing command mpxbreak verbatimtex typesetting command etex show command show expression list showvariable symbolic token list showtoken symbolic token list showdependencies symbolic token list symbolic token symbolic token symbolic token list expression list expression expression list expression addto command addto picture variable also pict
27. path p p fullcircle scaled 3cm q p shifted 7cm 0cm f f center p center g We draw these paths with draw p withpen pencircle scal draw q withpen pencircle scal ed 10pt withcolor ed 10pt withcolor draw withpen pencircle scal ed 20pt withcolor 625red 625yellow 625white The line is drawn from center to center and since the line has a non zero width and a round line cap it extends beyond this point If we want to line to stop at the circular paths we can cut off the pieces that extend beyond those paths pair pr qr pr p intersectionpoint r qr q intersectionpoint Preliminary Version October 27 2000 i r cutbefore pr cutafter qr This time we get Due to the thicker line width used when drawing the straight line part of that line is still visible inside the circles So we need to clip off a bit more r r cutbefore point 5pt r r cutafter point 5pt on r The point on operation is a MetaFun macro that takes a dimension In order to save you some typing MetaFun provides a macro cutends that does the same job r cutends 5pt This time we draw the path in a different order draw r withpen pencircle scaled 20pt withcolor 625white draw p withpen pencircle scaled 10pt withcolor 625red draw withpen pencircle scaled 10pt withcolor 625yellow That way
28. For them I owe much inspiration to both my parents My mother Jannie constantly demonstrates me that computer graphics will never improve nature She also converted one of my first METRPOST graphics into a patchwork that will remind me forever that handcraft is more vivid than computer artwork My father Hein has spent a great deal of his life teaching math and I m sure he would have loved METAPOST I inherited his love for books I therefore dedicate this document to them Colofon This manual is typeset with CONTEXT and METAPOST No special tricks are used and everything you see in here is available for CONTEXT users The text is typeset in Palatino and Courier We used as processing engine Since this document is meant to be printed in color some examples will look sub optimal when printed in black and white Copyright Hans Hagen PRAGMA Advanced Document Engineering Hasselt NL copyright October 27 2000 Info internet www pragma ade com support ntg contextGntg nl email pragmaQwxs nl Introduction This document is about METAPOST and TEK The former is a graphic programming language the latter a typographic programming language However in this document we will not focus on real programming but more on how we can interface between those two languages We will do so by using CONTEXT a macro package written in where support for METAPOST is integrated in the core The macros are integrate
29. Preliminary Version October 27 2000 E 2 E3 E 4 ES Literature There is undoubtly more literature about METAPOST and the tools discribed in this document than is mentioned below More information METAFONT and METAPOST can be found at the internet sites of the local user groups There are definitely references missing here but so far I only read wrote saw these METRFONT and METAPOST Knuth D E 1986 The METRFONT book Reading MA Addison Wesley Hobby J D 1997 A User s Manual for Murray Hill NJ AT amp T Bell Laboratories TEK Knuth 1986 The TgXbook Reading MA Addison Wesley CONTEXT Otten amp Hagen J 1998 an Excursion Hasselt Pragma ADE Hagen J 1999 ConTgXt the Manual Hasselt Pragma ADE Hagen J 1999 Con TEXt up to date 3 Flowcharts Hasselt Pragma ADE Hagen J 1997 Puzzling Graphics in MetaPost Petten NTG Maps Tools H n Th Th nh amp Rahtz S P Q amp Hagen J 1998 The manual Brno Hasselt Oxford Hagen J 1999 explained Hasselt Pragma ADE Hagen J 2000 Making Stand Alone MetaPost graphics Amsterdam NTG Maps Distributions Rahtz S P Q amp Goosens M 1999 The Live Guide 4th edition The Whole World TUG s Hagen J 1999 How to Install ConTgXt Hasselt Pragma ADE Dol W amp Frambach E 1999 4TpX for Windows Amster
30. The five points that METAPOST can report for each path or picture are 1 lower left corner lrcorner lower right corner urcorner upper right corner ulcorner upper leftcorner center intersection of the diagonals If we want to typeset text inside this circle we need to know where a line starts and ends Given that lines are horizontal and straight we therefore need to calculate the intersection points of the lines and the path As a first step we calculate the top and bottom of the path and after that we split off the left and right path startuseMPgraphic text split pair t b path 1 t ulcorner p urcorner p intersectionpoint b llcorner p lrcorner p intersectionpoint p l cutbefore t 1 1 cutafter b r p cutbefore r cutafter t stopuseMPgraphic The intersectionpoint macro returns the point where two paths cross If the paths don t cross an error is reported when the paths cross more times just one point is returned The cutafter and cutbefore commands do as their names say and return a path In the text split code fragment t and b are the top points of the main path while 1 and r become the left and right half of path p We now draw the original path using a thick pen and both halves with a thinner pen on top of the original The arrows show the direction startuseMPgraphic text draw draw p withpen pencircle scaled 3pt withcolor red d
31. expression right hand side assignment variable right hand side internal variable right hand side right and side expression equation assignment declaration type declaration list declaration list generic variable declaration list generic variable generic variable Symbolic token generic suffix generic suffix empty generic suffix tag generic suffix macro de nition macro heading replacement text enddef macro heading def Symbolic token delimited part undelimited part vardef generic variable delimited part undelimited part vardef generic variable delimited part undelimited part binary def parameter symbolic token parameter delimited part empty delimited part parameter type parameter tokens parameter type expr suffix text Preliminary Version October 27 2000 parameter tokens parameter parameter tokens parameter parameter Symbolic token undelimited part empty parameter type parameter precedence level parameter expr parameter of parameter precedence level gt primary secondary tertiary binary def primarydef secondarydef tertiarydef pseudo procedure drawoptions optionlist
32. if string str thelabel str loc else str shifted center str shifted loc fi setbounds s to boundingbox s enlarged freelabeloffset p fullcircle scaled 2 length loc ori shifted ori freesquare xyscaled urcorner s llcorner s l point xpart p intersectiontimes ori 10c s shifted 1 enddef A few applications _ Preliminary Version October 27 2000 122 We will now test this macro a slightly rotated circle using labels typeset by TEK The reverse is there purely for cosmetic reasons to suit the label texts funny macros defining Can t we M We can and on goon pickup pencircle scaled 1mm path p p reverse fullcircle rotated 25 scaled 3cm draw p withcolor 625yellow pair cp cp center p draw freedotlabel btex strut We can etex point 0 of p cp draw freedotlabel btex strut go on etex point 1 of p cp draw freedotlabel btex Nstrut and on etex point 2 of p cp draw freedotlabel btex Nstrut in etex point 3 of p cp draw freedotlabel btex strut defining etex point 4 of p cp draw freedotlabel btex strut funny etex point 5 of p cp draw freedotlabel btex strut macros etex point 6 of p cp draw freedotlabel btex strut Can t we etex point 7 of p cp Marking angles A convenient METAPOST macro is unitvector When we draw a line segment from the origin to the point re
33. numeric size delta size 2 5cm delta size 3 color mainshade topshade bottomshade centershade mainshade MPcolor funcolor topshade 9mainshade bottomshade 5mainshade centershade 5 topshade bottomshade stopuseMPgraphic applications _ Preliminary Version October 27 2000 The color funcolor is provided by CONTEXT and since we want to use this graphic with dif ferent colors this kind of mapping is quite convenient The bunch of graphics is packaged in a combination with empty captions Note how we set the color before we include the graphic startcombination 5 2 Ndefinecolor funcolor red useMPgraphic second definecolor funcolor green useMPgraphic second definecolor funcolor blue useMPgraphic second definecolor funcolor yellow useMPgraphic second Go Mae as ae eu definecolor funcolor white useMPgraphic second definecolor funcolor red useMPgraphic third definecolor funcolor green useMPgraphic third Ndefinecolor funcolor blue useMPgraphic third definecolor funcolor yellow useMPgraphic third definecolor funcolor white useMPgraphic third stopcombination We use a similar arrangement for the following graphic where we have replaced the definitions of first second and third by new definiti
34. path p p unitsquare xscaled overlaywidth yscaled overlayheight superellipsed 85 pickup pencircle scaled overlaylinewidth fill p withcolor MPcolor overlaycolor draw p withcolor MPcolor overlaylinecolor stopuniqueMPgraphic defineoverlay super ellipse uniqueMPgraphic super ellipse This background demonstrated that a super ellipse is rather well suited as frame Enhancing te layout Preliminary Version October 27 2000 4 5 framed background super ellipse frame off width 3cm align middle framecolor darkyellow rulethickness 2pt backgroundcolor darkgray white This is a Super Ellipsed sentence Such a super ellipse looks quite nice and is a good candidate for backgrounds for which the superness should be at least 85 Typesetting graphics I have run into people who consider it kind of strange when you want to use for non mathe matical typesetting If you agree with them you may skip this section with your eyes closed One of the CONTEXT presentation styles number 15 tagged as balls stepwise builds screens full of sentences quotes or concepts packages in balloons and typeset as a paragraph We will demonstrate that can typeset graphics using the following statement As you may know 5 ambassador is a lion while METAFONT is represented by a lioness It is still unclea
35. 1 1 z4 Here the macro spring takes 5 arguments two points the width of the winding the length of the connecting pieces and the number of elements half windings The definition of spring is less complicated than readable Preliminary Version October 27 2000 A fel applications def spring expr a b w h n 0 0 0 h for i l upto n 1 if odd i fi w 2 i h endfor 0 n h 0 n 2h yscaled xpart ypart b a n 2h rotatedaround origin 90 1 b a shifted a enddef First we build a path starting in the origin going left or right depending on the counter being an odd number pat 0 0 for i l upto n 1 if odd i pat pat w 2 i else pat pat w 2 i fij endfor pat pat 0 n Once you are accustomed to the way METAPOST interprets specialists may say expand the source code you will start using if and for statements in assignments The previous code can be converted in a one liner using the pattern pat for i 1 upto n 1 x y endfor 0 n The loop splits out a series of x y but the last point is added outside the loop Otherwise pat would have ended with a dangling Of course we need to replace by something meaningful so we get pat for i 1 upto n 1 if odd i fi w 2 i endfor 0 n We scale this path to the length needed The expression 5
36. In his article Concept of a Meta Font Knuth sets forth for the first time the underlying philosophy of METRFONT as well as some of its products Not on ly is the concept exiting and clearly well executed but in my opinion the arti cle is charmingly written as well However despite my over test 3 trol the final ap pearance of his or her work Knuth s typesetting system has become well known and avail able in many countries around the world By contrast his META FONT system for design ing families of type faces has not become as test 2 all enthusiasm for Knuth s idea and article there are some points in it that I feel might be taken wrongly by many readers and since they are points that touch close to my deepest interests in ar tificial intelligence and es thetic theory I felt com pelled to make some com ments to clarify certain impor tant issues raised by The Con test 4 Figure 9 2 A continuous text typeset in a non standard shape spread over four areas and right alligned rotatedaround origin 90 xscaled overlaywidth ysca 625r drawoptions withcolor stopuseMPgraphic followtokens This is just a dummy text led overlayheight ed kerned by T kern Preliminary Version October 27 2000 1667em lower 5ex hbox E kern 125emX and typeset in a circle using setMFPfont M setM
37. StartPage path p pickup pencircle scaled 3pt p Field Text Text enlarged 36pt superellipsed 90 fill Page withcolor MPcolor yellow fill p withcolor MPcolor white draw p withcolor MPcolor red p Field Text Text enlarged 48pt superellipsed 90 def right menu button expr nn rr pp xx yy ww hh dd if gt 0 and rr gt 0 q rightsuperbutton p xx yy RightEdgeWidth hh Preliminary Version October 27 2000 jdez uue wH ayn u pieMpg ymuy 7d 19 pelsJOH 0007 1snSny suey owd 214416 y OTHO ODEN AMOH V Figure 111 The auxiliary lines used to calculate the button shapes Preliminary Version October 27 2000 syle fill withcolor MPcolor white draw withcolor if rr 2 MPcolor gray else MPcolor red fi EX 5 enddef MPmenubuttons right StopPage stopuseMPgraphic The macro MPmenubuttons expands into a list of in this case four calls to the METAPOST macro right_menu_button This list is generated by CONTEXT when it generates the menu Because the page background is applied last this list is available at that moment expr nn rr yy ww hh dd This rather long list of arguments represents the following variables number referre
38. Such a point is identified by two numbers which represent the horizontal and vertical position often referred to as x and y or x y Because there are two numbers involved in METAPOST this point is called a pair Its related datatype is therefore pair The following statements assigns the point we showed previously to a pair variable pair somepoint somepoint lcm 1 5cm A pair can be used to identify a point in the two dimensional coordinate space but it can also be used to denote a vector being a direction or displacement For instance 0 1 means go up Looking through math glasses you may consider them vectors and if you know how to deal with them METAPOST may be your friend since it knows how to manipulate them You can connect points and the result is called a path A path is a straight or bent line and is not necessarily a smooth curve An example of a simple rectangular path is In the next examples we use the debugging features discussed in chapter 10 to visualize the points paths and bounding boxes Preliminary Version October 27 2000 This path is constructed out of four points A path can be open or closed The previous path is an example of a closed path An open path looks like this When we close this path and in a moment we will see how to do this the path looks like Preliminary Version October
39. cycle draw p withcolor nsblue draw withcolor nsblue addto currentpicture also currentpicture rotatedaround 5 z2 z3 180 shifted height 4 height 2 picture savedpicture savedpicture currentpicture clip currentpicture to r setbounds currentpicture to r savedpicture currentpicture currentpicture nullpicture fill s withcolor nsyellow addto currentpicture also savedpicture For practical use it makes sense to package this definition in a macro to which we pass the dimen sions Animations Although METAPOST is not that well suited for free hand drawings you can use it to make stylistics animations Preliminary Version October 27 2000 Preliminary Version October 27 2000 14 MetaFun macros CONTEXT comes with a series of modules In this chapter we will summarize the most important Tek and METAPOST macros More information can be found in the documentation of the modules Unless you want to write low level CONTEXT code yourself there is no real reason to look into the modules that deal with METAPOST support supp mps tex low level inclusion macros and housekeeping supp mpe tex experimental extensions like specials supp pdf tex METAPOST to PDF conversion meta ini tex high level inclusion macros and interfacing meta tex subsystems and handy macros The last category will certainly grow Some of thes
40. enddef method 1 method 2 method 3 Figure 131 Three ways of marking angles Figure 131 shows the three alternative methods implemented here Instead of using unitvectors we now calculate the points using the arctime and arclength primitives In stead of complicated expressions we use the MetaFun operators along and on The following expressions are equivalent pointa point anglelength on middle point 5 along curve pointa point arctime anglelength of a of middle arctime 5 arclength curve of curve of curve The third method can be implemented in different more math intensive ways but the current implementation suits rather well and is understood by the author Preliminary Version October 27 2000 13 4 Color circles In chapter 3 we showed a few color circles Drawing such a graphic can be done in several ways and here we will show a few methods First we will demonstrate how you can apply cutafter and curbe fore next we will show how the METRPOST macro buildpath can be used and finally we will present a clean solution using subpath We will assume that the circle is called with the macro colorcircle 4cm red green blue We need to calculate seven paths The first implementation does all the handywork itself and thereby is rather long complicated and unreadable It does not really use the strenghth of META POST yet vardef colorcircle expr
41. enlarged if alternative 1 36pt superellipsed superness elseif alternative 2 36pt squeezed Squeezeness elseif alternative 3 36pt randomized randomness else 36pt fi pickup pencircle scaled 3pt fill Page withcolor MPcolor yellow fill p withcolor MPcolor white draw p withcolor MPcolor red randomseed seed Field Text Text enlarged if alternative 1 48pt superellipsed superness lseif alternative 2 48pt squeezed Squeezeness elseif alternative 3 36pt randomized randomness else 48pt fi transformed t def right menu button expr nn rr pp xx yy ww hh dd if gt 0 and rr gt 0 q rightsuperbutton p xx yy RightEdgeWidth hh fill withcolor MPcolor white draw withcolor if rr 2 MPcolor gray else MPcolor red fi EL 3 enddef MPmenubuttons right StopPage stopuseMPgraphic When we choose the alternatives 21 and 22 we get this result A Few Nice Quotes Simple Style Demo Hans Hagen August 2000 A Few Nice Quotes Simple Style Demo Hang Hagen August 2000 page 1 page 2 page 3 page 4 page 5 Preliminary Version October 27 2000 12 Functions METAPOST provides a wide range of functions like sind and floor We will discuss most of them here and define a few more We will use some of the Calculator Demo graphics to make this chapter more reada
42. for x 0 upto length p 1 point x of p b postcontrol x of p d point 1 of c precontrol x l of dodrawmidpoints a b c d n endfor enddef We demonstrate these macros on two paths first we show how the depth of the recursion im proves the resolution for i 1 upto 7 drawmidpoints fullcircle xscaled 100pt i 5pt yscaled 40pt i 5pt i endfor Preliminary Version October 27 2000 points first order curve second order curve third order curve left side curves right side curves Preliminary Version October 27 2000 e points first order points e e e second order points left side points Preliminary Version October 27 2000 right side points e 2 e e e first iteration second iteration e e e e 2 27 e e LJ e e e e e e 4 third iteration fourth iteration Clee 4 e e e e e 2 Y 2 e 9 4 P 4 4 6000000099 fifth iteration sixths iteration Preliminary
43. fullcircle shifted a b rotated c scaled d You always need a starting point in this case the identity matrix identity 0 0 1 0 0 1 By the way in POSTSCRIPT the zero vector is 1 0 0 1 0 0 So unless you want to extract the compo nents using xpart xypart xxpart ypart yxpart and or yypart you may as well forget about the internal representation You can invert a transformation using the inverse macro which is defined as follows using an equation vardef inverse primary T transform T T transformed T identity T enddef Using transform matrices makes sense when similar transformations need to be applied on many paths pictures pens or other transforms However in most cases you will use the predefined commands scaled shifted rotated and alike We will now demonstrate the most common transformations in a text example draw btex bfd MetaFun etex draw boundingbox currentpicture withcolor 625yellow Before a METRPOST run the btex etex s are filtered from the file and passed on to TEX After that the DVI file is converted to a list of pictures which is consulted by METAPOST We can manipulate these pictures like any graphic as well as draw it with draw MetaFun We show the transformations in relation to the origin and make the origin stand out a bit more by painting it a bit larger in white first draw origin withpen pencircle scaled 1 5mm withcolor white draw origin withpen pencirc
44. fullcircle zscaled 2 25 metapost primitive path xyscaled numeric AN PA path xyscaled pair D path shifted pair O O path enlarged numeric path enlarged pair fullcircle xyscaled 25 metapost primitive fullcircle xyscaled 2 25 metapost primitive fullcircle shifted 2 25 metapost primitive fullcircle enlarged 25 metafun macro fullcircle enlarged 1 25 metafun macro Preliminary Version October 27 2000 path llenlarged numeric le path lrenlarged numeric C path urenlarged numeric 2 path ulenlarged numeric O path llenlarged pair Preliminary Version October 27 2000 fullcircle llenlarged 25 metafun macro fullcircle lrenlarged 25 metafun macro fullcircle urenlarged 25 metafun macro fullcircle ulenlarged 25 metafun macro fullcircle llenlarged 1 25 metafun macro path lrenlarged pair gt path urenlarged pair lt path ulenlarged pair path llmoved numeric path Irmoved numeric fullcircle 1 1 1 25 metafun macro fullcircle urenlarged 1 25 metafun macro fullcircle ulenlarged 1 25 metafun macro fullcircle llmoved 25 metafun macro fullcircle lrmoved 25 metafun macro Preliminary Version October 27 2000 path urmoved numeric path ulmoved numeric ge 3 56 a
45. group pair merge harmonize synthesize focus organize condense reduce boil down choose categorize catalog classify list abstract scan look into idealize isolate discriminate distinguish screen pigeonhole pick over Sort integrate blend inspect filter lump skip smooth chunk average approximate cluster aggregate outline summarize itemize review dip into flip through browse glance into leaf through skim refine enumerate glean synopsize winnow the wheat from thel chaff and separate the sheep from the goats This font has far less kerning Even more interesting is the Lucida Bright Handwriting font which is defined in such a way that no kerning is needed at all Preliminary Version October 27 2000 Aew more details We thrwe W imnfor matton thick worlds because our marvelous and everyday capacity to select edit singlerout structure highlight group pair merge harmonize synthesize focus organize condense reduce boil down choose categorize catalog classify list abstract scary look into idealize
46. knowing how to combine features Here we will demonstrate how page backgrounds can contain foreground graphics like menus Preliminary Version October 27 2000 71 Shapes symbols and buttons One can use METRPOST to define symbols and enhance buttons Here we introduce some of the gadgets that come with CONTEXT as well as explain how to integrate such gadgets yourself Interfacing to TEX In the early days of METAPOST support in CONTEXT Tobias Burnus asked me if it was possible to define English rules What exactly does an english rule look like Here is one As you can see such a rule has to adapt itself to the current text width normally hsize in or on request localhsize in CONTEXT We need to set the height to a reasonable size related to the font size and we also need to take care of proper spacing Of course we want to run METRPOST as less times as possible so we need to use unique graphics Let s start with the graphic setupMPvariables EnglishRule height lex width localhsize color darkgray startuniqueMPgraphic EnglishRule height width color height MPvar height xl 0 x3 MPvar width 2 x4 5x3 yl y3 0 y2 y4 height 2 fill 21 22 23 amp z3 z4 zl 6 cycle withcolor MPvar color stopuniqueMPgraphic As you can see we pass two arguments to the graphic definition The first argument is the name the second argument is a comma
47. lcm In a similar fashion we can define linear shaded This time we only pass two points and two colors def test_shade expr a b pickup pencircle scaled 1mm Preliminary Version October 27 2000 8 2 color ca ca MMPcolor a color cb cb MPcolor b color cc cc MPcolor c sh define linear shade a b ca cb fill fullsquare scaled 2cm withshade sh draw a withcolor draw b withcolor cc enddef Although one can control shading to a large extend in practice only a few cases really make sense test shade origin origin shifted 1cm 0 test shade origin shifted 1cm 0 origin shifted 1cm 0 test_shade origin shifted 1cm 1cm origin shifted 1cm l1cm Clipping In this chapter we will use the graphic representation although simplified of a Dutch cow to demonstrate clipping Figure 81 cow Since this cow is defined as a METRPOST graphic we use the suffix mps instead of eps or a number although CONTEXT will recognize each as being METAPOST output The placement of the cow is defined as placefigure A cow externalfigure cow mps width 4cm Clipping is combined with a matrix as in figure 8 2 The content to be clipped is divided in nx by ny rectangles For instance nx 5 and ny 8 will produce a 40 cell grid with 5 columns of 8 rows Preliminary Version October 27 2000 1 1 3 1 Figure 8 2
48. numeric primary xysized pair primary randomshifted numeric or pair primary numeric or pair primary numeric primary pair primary nullary op false normaldeviate nullpicture pencircle true whatever unary op type abs angle arclength ASCII bbox bluepart bot bounded boundingbox ceiling center char clipped cosd cycle dashpart decimal dir filled floor fontpart fontsize greenpart hex innerboundingbox inverse known length 1ft llcorner lrcorner makepath makepen mexp mlog not oct odd outerboundingbox pathpart penpart redpart reverse round rt sind sqrt stroked textpart textual top ulcorner uniformdeviate unitvector unknown urcorner xpart xxpart xypart ypart yxpart yypart type boolean color numeric pair path pen picture string transform primary binop gt and dotprod div infont mod Preliminary Version October 27 2000 secondary binop gt or intersectionpoint intersectiontimes tertiary binop gt 6 lt lt lt gt cutafter cutbefore of operator gt arctime direction directiontime directionpoint penoffset point postcontrol precontrol subpath substring variable tag suffix suffix e
49. nx 1 ny 1 mp text clip externalfigure sample type buffer width 4cm Preliminary Version October 27 2000 Spec METRPOST clip is 1 the same as a video clip although we can use METAPOST to aduce a video cl Figure8 5 A clipped buffer text The next few lines demonstrate that we can combine techniques like backgrounds and clip ping startuseMPgraphic clip outline draw fullcircle xscaled overlaywidth yscaled overlayheight withpen pencircle scaled 4mm withcolor 625red stopuseMPgraphic defineoverlay clip outline useMPgraphic clip outline placefigure here fig clipped text 2 A clipped buffer text framed background clip outline offset overlay frame off clip nx 1 ny 1 mp text clip externalfigure sample type buffer width 4cm We could have avoided the framed here by using the clip outline overlay as a background of the sample In that case the resulting linewidth would have been 2 5 mm instead of 5 mm since the clipping path goes through the center of the line METAPOST clip 15 the same as a video clip although we can use METAPOST to sduce a video cli Figure8 6 A clipped buffer text In most cases the clip path will be a rather simple path and defining such a path every time you need it can be annoying Figure 8 7 shows a collection of predefined clipping paths These ar
50. pickup pencircle scaled 0 fill unitsquare xscaled 400pt yscaled 5cm withcolor 625red fill unitsquare xscaled 400bp yscaled 5cm withcolor 625yellow drawoptions withcolor white label rt 400 pt origin shifted 0 25cm label rt 400 bp origin shifted 0 25cm When processed the difference between a pt and bp shows rather well Watch how we use rt to move the label to the right you can compare this with 8 macro rlap You might want to experiment with 1ft top bot ulft urt llftand lrt The difference between both bars is exactly 1 5pt as calculated by TEN 400 bp 400 pt Where is anchored in tradition and therefore more or less uses the pt as the default unit Post much like POSTSCRIPT has its roots in the computer sciences There to simplify calculations an inch is divided in 72 big points and 72pt is sacrificed Preliminary Version October 27 2000 2 4 When you consider that POSTSCRIPT is a high end graphic programming language you may wonder why this sacrifice was made Although the difference between 1 and 1pt is miniscule this difference is the source of much unknown confusion When users talk about a 10pt font a desktop publisher hears 10bp In a similar vein when we define a papersize having a width of 600pt and a height of 450pt which is papersize 6 in CONTEXT a POSTS
51. possible in the sense that you need to provide as few s as possible When in doubt or when surprised by unexpected results use parentheses Pens When drawing three attributes can be applied to it a dashpattern a pen and or a color You may consider an arrowhead an attribute but actually it is just an additional drawing appended to the path The predefined pencircle attribute looks like withpen pencircle where pencircle is a special kind of path stored in a pen variable Like any path you can transform it You can scale it equally in all directions withpen pencircle scaled 1mm You can also provide unequal scales creating an elliptically shaped and rotated pen withpen pencircle xscaled 2mm yscaled 4mm rotated 30 In the following graphic the circle in the center is drawn without any option which means that the default pen is used being a pencircle with a radius of half a base point The other three circles are drawn with different pen specifications Preliminary Version October 27 2000 If you forget about the colors the METAPOST code to achieve this is as follows path draw draw draw draw te SSO tg 7 scal sca sca fullcircle scaled led 2 withpen pencirc led 3 withpen pencirc led 4 withpen pencirc lcm le le scaled 1mm le xscaled 2mm yscaled 4mm rotated 30 If this were the only way of specifying
52. r hsize xpart lrcorner p xpart llcorner p vsize ypart urcorner p ypart lrcorner q p xscaled hsize 2offset hsize yscaled vsize 2offset vsize hsize xpart lrcorner xpart llcorner vsize ypart urcorner ypart lrcorner stopuseMPgraphic We adapt the text split code to use the reduced path instead of the original Preliminary Version October 27 2000 Typesetting ia MeTARGET startuseMPgraphic text split t ulcorner q urcorner intersectionpoint b llcorner q lrcorner intersectionpoint l cutbefore t 1 1 cutafter b r cutbefore r cutafter t stopuseMPgraphic In order to test what we have reached so far we draw the original path the left and right part of the reduced path and both the top and bottom point startuseMPgraphic text draw drawarrow p withpen pencircle scaled lpt withcolor red draw t withpen pencircle scaled 2pt draw b withpen pencircle scaled 2pt drawarrow 1 withpen pencircle scaled withcolor green 0000 0 drawarrow withpen pencircle scaled lpt withcolor blue stopuseMPgraphic Again we use includeMPgraphic to combine the components into a graphic startuseMPgraphic text includeMPgraphic text path includeMPgraphic text vars includeMPgraphic text move includeMPgraphic text split
53. the TEK user groups distribute TEK in such a way that installation is nearly automatic There are well written manuals available for installing If you are free to choose what you use we advise to use PDF e TeX ConTpxt The installation of CONTEXT is described in the manual that is included in the distribution If you want to update to a more recent version you can fetch a new archive from one of the sites that Preliminary Version October 27 2000 AA A D host CONTEXT You need to unzip this zipped archive in the root of the texmf or texmf local tree After that you need to generate a format file by saying texexec mak Unfortunately Tex lacks a real command line interface This means that when we want to process a file under a different regime we need to adapt the document source For this reason we wrote the PERL script TEXEXEC This script is meant to make using a bit more user friendly and it will be no surprise that METAPOST is supported as well Unless you have enabled runtime generation of graphics after each run you have to process the files mpgraph mp mprun mp However when you use the files will be processed automatically You can disable this feature with the switch nomprun This can be handy when debugging files since by default CONTEXT will run METAPOST in batch mode texexec
54. 1 However when we draw them using the right linewidth and color you will notice that we re not yet done applications Preliminary Version October 27 2000 The second curve is similar to the first one but rotated over 180 degrees addto currentpicture also currentpicture rotatedaround 5 z2 z3 180 shifted height 4 height 2 In order to get the sharp edges we need to clip off part of the curves and at first sight we may consider using a scaled bounding box However when we show the natural bounding box you will notice that a more complicated bit of calculations is needed The right clip path is calculated using the following expressions Watch how we use rt and top to correct for the linewidth numeric d 1x ly ux uy d line 2 lx 3d d 3 ly d ux rt x5 d 3 uy top path r 1x ly ux ly 1x uy cycle The clipping path is applied by saying clip currentpicture to r The result is quite acceptable But if you watch closely to how this graphic extends into to left margin of this document you will see that the bounding box is not yet right Preliminary Version October 27 2000 LA fei setbounds currentpicture to r We use the same path r to correct the bounding box There are a few subtle points involved like setting the 1ine join v
55. 27 2000 applications fill rr withcolor red fill cc withcolor white red fill gg withcolor green fill mm withcolor white green fill bb withcolor blue fill yy withcolor white blue for 1 rr gg bb cc mm yy draw i withcolor 5white endfor currentpicture currentpicture xsized size enddef In determining the right intersection points you need to know where the path starts and in what direction it moves In case of doubt drawing the path as an arrow helps If you want to see the small paths used you need to comment the lines with the i11 s and uncomment the lines with draw s Due to the symmetry and the fact that we keep the figure centered around the origin we only need to calculate two paths since we can rotate them There are for sure more efficient ways to draw such a figure but this one demonstrates a few new tricks like grouping We use grouping here because we want to use mm to indicate the magenta path and mm normally means millimeter Within a group you can save variables These get their old values when the group is left With for we process multiple paths after each other In this case it hardly saves tokens but it looks more clever One of the more efficient methods is using the buildcycle macro This macro takes two or more paths and calculates the combined path Although this is a rather clever macro you should be pre
56. 3 If you have installed CONTEXT somewhere on your system there resides a file mp tool mp If you make a stand alone graphic it s best to put the following line at the top of your file Preliminary Version October 27 2000 A few 2 2 input mp tool By loading this file the resulting graphic will provide a high resolution bounding box which enables more accurate placement The file also sets the prologues 1 so that viewers like GHOSTVIEW can refresh the file when it is changed In the next chapter we will explain in detail how to embed the METAPOST code in your TEK file but first we will introduce some more METAPOST commands From now we will omit the encapsulating beginfig and endfig macros If you want to process these examples yourself you should add those commands pickup pencircle scaled 5cm draw unitsquare xscaled 8cm yscaled 1cm withcolor 625white draw origin withcolor 625yellow pickup pencircle scaled 1 draw bbox currentpicture withcolor 625red In this example we see a mixture of so called primitives as well as macros A primitive is some thing hard coded a built in command while a macro is a collection of such primitives pack aged in a way that they can be recalled easily Where scaled is a primitive and draw a macro unitsquare isa path variable an abbreviation for unitsquare 0 0 1 0 1 1 0 1 cycle
57. 625white We draw this path using a non standard pen In the METAFONT manual you will find methods to draw shapes with similar pens where the pen is also turning as it does in real calligraphy Here we stick to a more simple one We construct the inner path from the points that make up the curve Watch how we use a for loop to compose the new path When used this way no semi colon may be used to end the loop since it would isolate the color directive draw point 0 of p for i 1 upto length p point i of p endfor withcolor 625red The points are still located on the original path We can move the points to the inside by shifting them over the penwidth in the direction perpen dicular to the point which is a good approximation Because we use this transformation more than once we wrap it into a macro This also keeps the code readable vardef inside expr pnt of p point pnt of p shifted penoffset direction pnt of p of currentpen enddef Preliminary Version October 27 2000 Hi draw inside 0 of p for i 1 upto length p inside i of p endfor withcolor 625red Whenever you define a pen METAPOST stores its characteristics in some private variables which used in the top and alike directives The penoffset is a built in primitive and is defined as the point on the pen furthest to the right of the given direction Deep down in METAPOST pens are actually si
58. A METRPOST graphic often has a number as suffix so embedding such a graphic is done by externalfigure graphic 123 width 4cm An alternative method is to separate the definition from the inclusion An example of a definition is useexternalfigure pentastar star 803 height 4cm useexternalfigure octostar star 804 pentastar Here the second definition inherits the characteristics from the first one These graphics can be summoned like placefigure A five point star drawn by METAPOST externalfigure pentastar the stars are defined as stand alone graphics in a file called star mp Such a file can look like def star expr size n pos for a 0 step 360 n until round 360 1 1 n draw origin size 2 0 rotatedaround origin a shifted pos endfor enddef beginfig 803 pickup pencircle scaled 2mm star 2cm 5 origin endfig beginfig 804 pickup pencircle scaled 1mm star lcm 8 origin pickup pencircle scaled 2mm star 2cm 7 3cm 0 endfig end This star macro will produce graphics like KK KK Embedded gtaphics Preliminary Version October 27 2000 33 Integrated graphics An integrated graphic is defined in the document source or in a style definition file The most primitive way of doing this is beginning with the definition of the graphic startMPgraphic fill fullcircle scaled 200pt withc
59. Given that red is already defined we also could have said withcolor 625red Because for METAPOST colors are just vectors you can do things similar to points A color halfway red and green is therefore accomplished with withcolor 5 red green Since only the RGB color space is supported this is about all we can tell about colors for this moment Later we will discuss some nasty details Dashes A dash pattern is a simple picture that is build out of straight lines Any slightly more complicated picture will be reduced to straight lines and a real complicated one is rejected and in this respect METRPOST considers a circle to be a complicated path The next example demonstrates how to get a dashed line First we built picture p that we apply to a path Here we use a straight path but dashing can be aplied to any path picture p p nullpicture addto p doublepath 0 0 3mm 3mm shifted 6mm 6mm draw 0 0 10cm 0 dashed p withpen pencircle scaled 1mm This way of defining a pattern is not that handy especially if you start wondering why you need to supply a slanted path Therefore METAPOST provides a more convenient mechanism to define a pattern picture p p dashpattern on 3mm off 3mm draw 0 0 10cm 0 dashed p withpen pencircle scaled 1mm Preliminary Version October 27 2000 LI Most dashpatterns be defined in terms of on and off
60. Instead of hard coded points you will find points defined in terms of being the same as this point or touching that point In this section we will spend some time on this touchy aspect This rectangle is a scaled instance of the predefined MetaFun path fullsquare which is cen tered around the origin pickup pencircle scaled 2mm path p p fullsquare scaled 2cm draw p withcolor 625white On this path halfway between two of its corners we define a point a pair q q 5 llcorner p lrcorner We draw this point in red using draw q withcolor 625red As you can see this point is drawn on top of the path There are four of those midpoints and when we connect them we get Preliminary Version October 27 2000 Because path p is centered around the origin we can simply rotate point q a few times draw q q rotated 90 q rotated 180 q rotated 270 cycle withcolor 625red There are situations where you don t want the red path to be drawn inside another path or more general where you want points to touch instead of being overlayed We can achieve this by defining point q to be located on top of the midpoint pair q top 5 llcorner p lrcorner The predefined macro top moves the point over the distance similar to the current pen width Because we are dealing with two drawing operations and since the path inside is drawn through the
61. Preliminary Version October 27 2000 A few applications pper right lower left Although any automatic mechanism will be sub optimal we can give it a try to write a macro that deals with arbitrary locations This macro will accept three arguments and returns a picture thefreelabel some string or picture a position the origin Our testcase is just a simple for loop that places a series of labels The freedot label macro is derived from thefreelabel pickup pencircle scaled 1mm path p p fullcircle scaled 3cm draw p withcolor 625yellow for i20 step 5 until 7 5 freedotlabel text point i of p center p endfor As a first step we will simply place the labels without any correction We also visualize the bound ing box vardef thefreelabel expr str loc ori save s picture s thelabel str loc draw boundingbox s withpen pencircle scaled 5pt S enddef To make our lives more easy we also define a macro that draws the dot as well as a macro that draws the label vardef freedotlabel expr str loc ori drawdot loc freelabel str loc ori enddef vardef freelabel expr str loc ori drawdot loc draw thefreelabel str loc ori enddef Now we get A few applications Preliminary Version October 27 2000 The original
62. We will now draw a few extreme tensions and show the control points as METAPOST calculates them sample zl tension 0 75 z2 sample zl tension 2 00 z2 sample 271 Z2 s First we will show the symmetrical tensions Preliminary Version October 27 2000 z3 625red 23 625yellow z3 625white The asymetrical tensions are less prominent We use the following values sample 21 tension 75 and 10 Z se Z3 625xXe6d 7 sample 721 tension 10 and 75 z2 23 625yellow sample 21 ZA 2025whate You may try yourself what happens when we use METRPOST maximum value of infinity instead of 10 A third magic directive is curl The curl is attached to a point between like curl 2 Anything between curly braces is a direction specifier so instead of a curl you may specify a vector like 2 3 a pair of numbers as in 2 3 or a direction like dir 30 Because vectors and angles are straightforward we will focus a bit on curi 2025 21 22 2 20 curl 1 zl curl 1 22 So a curl of 1 is the default When set to 1 the begin and or end points are approached Given the following definitions Preliminary Version October 27 2000 u locom 21 0 0 22 2u 4u 23 4u 0 def sample expr p draw p withpen pencircle scaled 2 5mm withcolor white draw p withpen pencircle scaled 2 0mm wit
63. a string the latter expecting a numeric to be used in the scaling of the font Should you choose not to set these yourself they default to cmr10 and 1 0 respectively However you can change the defaults as follows defaultfont tir 1 22 defaultscale These settings select Adobe Times at about 12pt You can also set these variables to CONTEXT related values For CONTEXT graphics they are set to defaultfont truefontname Regular the bodyfontsize 10 defaultscale This means that they will adapt themselves to the current body font in this document uplr8t and the current size of the bodyfont here 10 0pt 10 text In the next example we will use a special mechanism for building graphics step by step The ad vantage of this method is that we can do intermediate calculations in TEK Our objective is to write a macro that draws text along a circular path While doing so we want to achieve the following e the text should be properly kerned i e the spacing between characters should be optimal e the position on the circle should vary and e the radius of the circle should vary Preliminary Version October 27 2000 This implementation is not the most straightforward one but by doing it step by step at least we see what is involved Later we will see a better method If you run these examples yours
64. a superellipsed 95 fill b withcolor OverlayColor draw b withcolor OverlayLineColor b boundingbox p superellipsed 95 fill b withcolor OverlayColor draw b withcolor OverlayLineColor draw p withcolor black setbounds currentpicture to a stopuseMPgraphic Many people are just fascinated by their PC s tricks and think that a widely praised pro gram called up on the screen will make everything automatic from now on We used the following command to pass the settings setupframedtexts FunnyText backgroundcolor lightgray framecolor darkred rulethickness 2pt offset bodyfontsize before blank big medium after blank big width textwidth In a real implementation we should also take care of some additional spacing before the text which is why we have added more space before than after the framed text We demonstrated that when defining graphics that are part of the layout you need to have access to information known to the typesetting engine Take figure 4 4 The line height needs to match the font and the two thin horizontal should match the x height We also need to position the baseline being the lowest one of a pair of lines in such a way that it suits the proportions of the line as specified by the strut A strut is an imaginary large character with no width setupbodyfont lbr hw startMPenvironment setupbodyfont lbr hw stopMPenvironment startMPpage
65. and native gray scales although gray colors are reduced to the more efficient POSTSCRIPT set gray operators in the output the macro MP color takes care of the translation from CMYK to RGB as well as gray to RGB However there is a fundamental difference between a yellow as defined in CONTEXT using CMYK and an RGB yellow in METAPOST Ndefinecolor cmyyellow 1 Ndefinecolor rgbyellow 1 4 11 Preliminary Version October 27 2000 definecolor cmydarkyellow y 625 definecolor rgbdarkyellow r 625 g 625 Figure 3 2 demonstrates what happens when we multiply colors by a factor Since we are not dealing with real CMYK colors multiplication gives different results for CMYK colors passed as MPcolor yellow 1 1 0 MPcolor rgbyellow MPcolor rgbdarkyellow 5 MPcolor rgbyellow MPcolor cmyyellow MPcolor cmydarkyellow 5 MPcolor cmyyellow Figure 3 2 kinds of yellow So 625red is the same as r 5 but 625yellow is not the same as y 5 but matches 5 51 Figure 3 3 shows the pure and half reds 17 00 625 0 0 MPcolor red MPcolor darkred 625 MPcolor red Figure 3 3 Some kinds of red In order to prevent problems we advise you to stick to RGB color specifications when possible That way you prevent not only conversion problems but the also often obscure ways printing and viewing devices handle CMYK 3 6 Common definit
66. b c lcm withcolor 625red That the results are indeed correct is demonstrated by the output of following example However when we swap the points we get This means that instead of rotating over 90 degrees we have to rotate over 90 or 270 degrees That way the arrow will also point in the other direction There are undoubtly more ways to determine the direction but the following method also demonstrates the use of turningnumber which reports the direction of a path For this purpose we compose a dummy cyclic path vardef anglebetween expr endofa endofb common length save tn tn turningnumber common ndofa ndofb cycle show tn unitvector endofa common endofa common rotated tn 90 unitvector endofb common enddef scaled length shifted common Because we use an intermediate variable just to keep things readable we have to use vardef to hide the assignment for the outside world We demonstrate this macro using the following code pair uv pickup pencircle scaled 1mm autoarrows true draw fullcircle scaled 2cm withcolor 625red for 10 35 40 20 85 15 draw origin i dashed evenly withcolor 625white drawarrow origin unitvector i scaled lcm withcolor 625yellow endfor draw origin withcolor 625red Watch how both arrows point in the direction of the line that is determined by the second point t Preliminary Version October 27 2000 TA fe
67. by The Concept of a Meta Font fe thrive in information thick worlds because of our marvelous and everyday capacity to select dit single out structure highlight group pair merge harmonize synthesize focus organize Fondense reduce boil down choose categorize catalog classify list abstract scan look into idealize isolate discriminate distinguish screen pigeonhole pick over sort integrate blend spect filter lump skip smooth chunk average approximate cluster aggregate outline sum itemize review dip into flip through browse glance into leaf through skim refine numerate glean synopsize winnow the wheat from the chaff and separate the sheep from the oats Donald E Knuth Thus I came to the conclusion that the designer of a new system must not only be the implemente pind first large scale user the designer should also write the first user manual The separation of any of these four components would have hurt significantly 1 I ha i participated fully in all these activities literally hundreds of improvements would never hav ween made because 1 would never have thought of them or perceived why they were important But a system cannot be successful if it is too strongly influenced by a single person On initial design is complete and fairly robust the real test begins as people with many different iewpoints undertake their own experiments Douglas R Hostadter
68. code is valid addto currentpicture also pic You can add pictures to existing picture variables where currentpicture is the picture that is flushed to the output file Watch the subtle difference between adding a doublepath contour picture Variables At this point you may have noted that METAPOST is a programming language Contrary to some of today s languages METAPOST is a simple and clean language Actually it is a macro language Although METAPOST and are a couple the languages differ in many aspects If you are using both you will sometimes wish that features present in one would be available in the other When using both languages in the end you will understand why the conceptual differences make sense Being written in PASCAL it will be no surprise that METAPOST has some PASCAL like features although some may also recognize features from ALGOL68 in it First there is the concept of variables and assignments There are several data types some of which we already have seen numeric real number in the range 4096 4096 boolean a variable that takes one of two states true or false pair point or vector in 2 dimensional space path a piecewise collection of curves and line segments picture collection of stroked or filled paths string sequence of characters like met apost There are too additional types transform and pen but we will not discuss these in depth transform transformation vector with six elem
69. consistently apply color to text as well as graphics In CONTEXT colors are called by name The next definitions demonstrate that we can define a color using different color models RGB or Depending on the configuration CONTEXT will convert one color system to the other RGB to CMYK or vice versa The full repertoire of color components that can be set is as follows definecolor color one G 2 3 m r 1 definecolor color two c 4 s 8 ws definecolor color three The numbers are limited to the range 0 1 and represent percentages Black is represented by definecolor black 1 r 0 g 0 b 0 definecolor black 2 c 0 m 0 y 0 k 1 definecolor black 3 s 0 Predefined colors are passed to METAPOST graphics via the MPcolor First we define some colors definecolor darkyellow y 625 a CMYK color definecolor darkred r 625 a RGB color definecolor darkgray s 625 a gray scale These are the colors we used in this document The next example uses two of them startuseMPgraphic color demo pickup pencircle scaled 1mm path p p fullcircle xscaled 10cm yscaled lcm fill p withcolor MPcolor darkgray draw p withcolor MPcolor darkred stopuseMPgraphic useMPgraphic color demo The previous example uses a pure RGB red shade combined with a gray fill Since METAPOST does not support the CMYK color space
70. cumpla d y rau viewpoints undertake their own experiments viewpoints undertake their own experiments Douglas R Hostadter Douglas R Hostadter Donald Knuth has spent the past several years working on system allowing him to control many books from certain important issues raised by The Concept ofa Meta Font carats import bum ried by The Coesptofa Moe even odd Figure 6 2 A background with combined areas StartPage fill Field Text Text withcolor 85white StopPage The location of an area is available in Location so the previous definition is the same as StartPage fill Area Text Text shifted Location Text Text withcolor 85white StopPage The following definition fills and draws the margin and text areas startuseMPgraphic page StartPage pickup pencircle scaled 2pt fill Page withcolor 625white fill Field OuterMargin Text withcolor 850white fill Field Text Text withcolor 850white draw Field OuterMargin Text withcolor 625red draw Field Text Text withcolor 625red StopPage stopuseMPgraphic This background is assigned to the page layer by saying Preliminary Version October 27 2000 defineoverlay page useMPgraphic page setupbackgrounds page background page As you can see in figure 6 3 the text is typeset rather tightly between the left and right margins tain important issues raised by The Concept
71. do more advanced things Here we limit ourselves to the more common cases In the previous examples we used an arrow to indicate the direction and magnitude of the shade The next macro demonstrates the principles in a different way def test shade expr a b ra rb pickup pencircle scaled 1mm color ca ca MMPcolor a color cb cb MPcolor b color cc cc MPcolor c path pa pa fullcircle scaled 2 shifted path pb pb fullcircle scaled 2rb shifted b sh define circular shade a b ra rb ca cb Preliminary Version October 27 2000 Sbeciatef ecis fill pb withshade sh draw pb withcolor draw pa withcolor enddef The shade is distributed between two circles each with a radius and center point All four can be set but as the next calls demonstrate we can normally do with less which is why we provided the macro with less parameters test shade origin origin lcm test shade origin origin 25cm lcm test shade origin origin 50cm lcm test shade origin origin shifted 25cm 0 Ocm lcm test_shade origin origin shifted 25cm 0 25cm lcm test_shade origin origin shifted 25cm 0 50cm lcm test_shade origin shifted 25cm 0 origin lcm test_shade origin shifted 25cm 0 origin 25cm lcm test_shade origin shifted 25cm 0 origin 50cm
72. following manner path mypath mypath randomscaledpath unitsquare 4cm Note that we send randomscaledpath a path unitsquare and a scaling factor 4cm The macro returns a scaled path which is then stored in the path variable mypat h The following argument types are accepted expr something that can be assigned to a variable text arbitrary METRPOST code ending with a suffix a variable bound to another variable An expression is passed by value This means that in the body of the macro a copy is used and the original is left untouched On the other hand any change to a variable passed as suffix is also applied to the original Local variables must be handled in a special manner since they may conflict with variables used elsewhere Thisis because all variables are global by default The way out of this problem is using grouping in combination with saving variables The use of grouping is not restricted to macros and may be used anywhere in your code Variables saved and declared in a group are local to that group Once the group is exited the variables cease to exist Grouping is not bound to macros and may be used anywhere in your code vardef randomscaledpath expr p s begingroup save r numeric r r round 1 uniformdeviate 4 p xscaled s r yscaled s r endgroup enddef Preliminary Version October 27 2000 Welcome 1 9 In this particular case
73. for i topskip step baselineskip until vsize line ulcorner q urcorner q shifted 0 i 111 found point line l true rrr found point line r false stopuseMPgraphic Here we divide the available space in lines The first line starts st rutheight from the top We can now finish our graphic by visualizing the lines Both the height and depth of the lines are shown startuseMPgraphic text line fill 1 rrr rrr shifted 0 strutheight 111 shifted 0 strutheight cycle withcolor 5white fill lll rrr rrr shifted 0 strutdepth 11 shifted 0 strutdepth cycle withcolor 7white draw lll withpen pencircle scaled 2pt draw rrr withpen pencircle scaled 2pt draw lll rrr withpen pencircle scaled 5pt stopuseMPgraphic startuseMPgraphic text done endfor stopuseMPgraphic The result is still a bit disappointing startuseMPgraphic text includeMPgraphic text path includeMPgraphic text vars includeMPgraphic text move includeMPgraphic text split Preliminary Version October 27 2000 includeMPgraphic text cutoff includeMPgraphic text draw includeMPgraphic text calc includeMPgraphic text step includeMPgraphic text line includeMPgraphic text done stopuseMPgraphic In order to catch the overflow at the bottom we need to change the or
74. grid backgroundcolor red In the last three cases of course you have to define circle cow and grid as overlay These items are packed in a comma separated list which is to be surrounded by Preliminary Version October 27 2000 Enhancing the layout 4 4 Foregrounds The overlay system is actually a system of layers Sometimes we are confronted with a situation in which we want the text behind another layer This can be achieved by explicitly placing the foreground layer as in figure 4 3 frame on top layer frame on bottom layer Figure 4 3 Foreground material moved backwards The graphic layer is defined as follows startuniqueMPgraphic backfore draw fullcircle xscaled overlaywidth yscaled overlayheight withpen pencircle scaled 2pt withcolor 625yellow stopuniqueMPgraphic defineoverlay backfore uniqueMPgraphic backfore The two framed texts have a slightly different definition The leftmost graphic is defined as framed background backfore backgroundoffset 4pt one two three unknown The rightmost graphic is specified as framed background foreground backfore backgroundoffset 4pt one two three unknown The current values of the frame color and frame width are passed to the overlay It often makes more sense as well as is more consistent to use colors defined at the document level startuniqueMPgraphic super ellipse
75. includeMPgraphic text draw stopuseMPgraphic Then we use useMPgraphic text to call up the picture The offset is not optimal Note the funny gap at the top We could try to fix this but there is a better way to optimize both paths We lower the top edge of q s bounding box by topskip then cut any part of the left and right pieces of q that lie above it Similarly we raise the bottom edge and cut off the pieces that fall below this line startuseMPgraphic text cutoff path tt tt ulcorner q urcorner shifted 0 topskip bb llcorner q lrcorner shifted 0 strutdepth Abi Preliminary Version October 27 2000 1 cutbefore 1 intersectionpoint tt 1 cutafter 1 intersectionpoint bb r r cutbefore intersectionpoint bb r r cutafter intersectionpoint tt stopuseMPgraphic Because we use includeMPgraphic to construct the graphic we can redefine text draw to show the result of this effort startuseMPgraphic text draw drawarrow p withpen pencircle scaled lpt withcolor red drawarrow 1 withpen pencircle scaled lpt withcolor green drawarrow r withpen pencircle scaled lpt withcolor blue stopuseMPgraphic The text graphic now becomes startuseMPgraphic text includeMPgraphic text path includeMPgraphic text vars includeMPgraphic text move i
76. into two parts In order to force consis tency we isolate the code that fills and draws The left page code looks like startreusableMPgraphic left page StartPage path Main Main llcorner Field OuterMargin Text lrcorner Field Text Text urcorner Field Text Text ulcorner Field OuterMargin Text cycle includeMPgraphic draw page StopPage stopreusableMPgraphic The right page text looks similar startreusableMPgraphic right page StartPage path Main Main lrcorner Field OuterMargin Text llcorner Field Text Text ulcorner Field Text Text urcorner Field OuterMargin Text cycl includeMPgraphic draw page StopPage stopreusableMPgraphic Watch how we used a reusable graphic first and a simple usable one next Actually the graphic is not a stand alone graphic startuseMPgraphic draw page Main Main enlarged 6pt pickup pencircle scaled 2pt fill Page withcolor 625white fill Main withcolor 850white draw Main withcolor 625red stopuseMPgraphic next We have seen some predefined paths and locations Apart from the Page path they take two arguments that specify their position on the layout grid Preliminary Version October 27 2000 path Area pair Location path Field path Page an area similar to a CONTEXT one the position of this area the ar
77. isolate discriminate distinguish screen igeonhole pickover sort integrate blend inspect filter lump skip smooth chunk average approximate cluster aggregate outline summarize itemize review dip into flip through browse glance into leaf through skimi refine enumerate glean synopsize winnow the wheat from the chaff and separate the sheep fromthe You can ask for the number of components with length A component can be a stroked or filled path or a text resulting from an infont operation If the last path is a clip path or when the whole picture has an forced boundingbox the picture is treated as a whole We will demonstrate this later You may wonder if this within loop construct has any real application and as you can ex pect it has In section 13 4 a macro is defined that draws a color circle If you want the inverted alternative you can pass the inverted color specification but wouldn t it be more convenient if there was an operator
78. label macros permit us to align the label at positions 4 corners and 4 points halfway the sides It happens that circles are also composed of 8 points Because in most cases the label is to be positioned in the direction of the center of a curve and the point at hand it makes sense to take circles as the starting points for positioning the labels To help us in positioning we define a special square path reesquare This path is con structed out of 8 points that match the positions that are used to align labels path freesquare freesquare 1 0 1 1 0 1 1 1 1 0 1 1 0 1 1 E cycle scaled 5 We now show this free path together with a circle using the following definitions drawpath fullcircle scaled 3cm drawpoints fullcircle scaled 3cm drawpointlabels fullcircle scaled 3cm currentpicture currentpicture shifted 5cm 0 drawpath freesquare scaled 3cm drawpoints freesquare scaled 3cm drawpointlabels freesquare scaled 3cm We use two drawing macros that are part of the suite of visual debugging macros 7 6 5 4 2 b 3 1 0e 8 4 e e 4 8 0 5 7 1 2 3 e 6 e e As you can see point 1 is the corner point that suits best for alignment when a label is put at point 1 of the circle We will now rewrite the reelabel in such a way that the appropriate point of the associated freesquare is found vardef thef
79. label rt bluepart 6 decimal bluepart p 4cm 5cm The result has no typographic beauty keep in mind that here we use METAPOST to typeset the text but serves its purpose 4 N redpart 0 625 d greenpart 0 7 bluepart 0 s r We can also ask for the path itself pathpart the pen penpart and the dashpattern dashpart but these can only be assigned to variables of the corresponding type A path can be stroked or filled in which case it is a cyclic path It can have a non natural bounding box be a clip path consist of line segments or contain text All these characteristics can be tested label rt filled amp condition filled p 4cm 1 25cm label rt stroked amp condition stroked 4cm 0 75cm label rt textual amp condition textual 4cm 0 25cm label rt clipped amp condition clipped 4cm 0 25cm label rt bounded amp condition bounded p 4cm 0 75cm label rt cycle amp condition cycle pathpart p 4cm 1 25cm filled false 2 ee EN stroked true textual false N dipped false Na bounded false cycle true Preliminary Version October 27 2000 LA fei In this code snippet condition is a macro that takes care of translating a boolean value into a string like decimal does with a numeric value def condition primary b if b true else false fi endde
80. md E Ne D H ge D A T Ne 3 9 x D B 2 ia 9 3 54 9 x 3 2 S lt outerboundingbox path 2 urcorner fullcircle metapost primitive ulcorner fullcircle metapost primitive center fullcircle metapost macro boundingbox fullcircle metafun macro innerboundingbox fullcircle metafun macro outerboundingbox fullcircle metafun macro Preliminary Version October 27 2000 D 3 path picture xsized numeric path picture ysized numeric path picture xysized numeric Points center path Preliminary Version October 27 2000 currentpicture xsized 5cm metafun macro currentpicture ysized 2cm metafun macro currentpicture xysized 3cm 2cm metafun macro center fullcircle metapost primitive top center fullcircle metapost macro bot pair NY rt pair 2 5 5 SAE NZE E E BE 5 d d e 5 d B 2 center fullcircle metapost macro lft center fullcircle metapost macro rt center fullcircle metapost macro point 2 of fullcircle metapost primitive point 5 on fullcircle metafun macro point lcm along fullcircle metafun macro Preliminary Version October 27 2000 D 4 precontro
81. nomprun myfile When you run this way you must not forget to process the two files mentioned especially if their content has changed It is possible to run METAPOST in so called batch mode If you pass the switch both programs will not send messages to the screen texexec batch myfile Stand alone graphics that have btex etex directives embedded can be processed by by saying texexec mptex myfile mp what extend this feature works well depends on the TeX implementation you use You can set up some METAPOST specific variables the initialization file texexec ini By default these variables are set up as follows set MpExecutable to mpost set MpToTeXExecutable to mpto set DviToMpExecutable to dvitomp Also when using the WEB2C implementation you can set the following variables in the file texmf cnf MPXCOMMAND texexec mptex TEX texexec onc batch nomp MPtoPDF The small suite of macros in the file mpt opdf provides a quick way to convert METAPOST files to PDF using a slightly stripped down plain PDFTEX and a few CONTEXT modules Although Preliminary Version October 27 2000 A 6 CONTEXT can handle METAPOST files directly this conversion is seldom needed However it can be handy to convert the file to be able to preview it Before we can apply this conversion we have to generate a format which
82. of the label The thelabel command returns a picture top upper left upper right left right lower left lower right bottom A few applications Preliminary Version October 27 2000 There is a numeric constant 1abeloffset that can be set to influence the distance between the point given and the content of the label When we set the offset to zero we get the following output This kind of positioning works well as long as we know where we want the label to be placed However when we place labels automatically for instance in a macro we have to apply a few clever tricks There are fore sure many ways to accomplish this goal but here we will follow the mathless method The previous graphic visualizes the bounding box of the labels This bounding box is rather tight and therefore the placement of labels will always be suboptimal Compare the alignment of the left and rightmost labels The btex etex method is better since then we can add struts like btex strut right etex to force labels with uniform depths and heights The next graphic demonstrates that this looks better indeed Spending some time on such details pays back in better graphics Now what happens when we want to place labels in other positions In the worst case given that we place the labels manually we end up in vague arguments in favour for one or the other placement
83. of the rule in the middle matches the height of a character with no ascenders and descenders Why is this called an English line Is it because they cannot draw a straight one This could be true after a few strong beers but then how do Germans draw a line Random graphics Given enough time and paper we can probably give you some MT LAT IH LIH LHT AHA LT IAT LH AH LHT AT LAT TT MT LH LHA IMA HIT IHT AHT LHT LAT IHT IHT WAT HT WA YAA HT IT MT HT PAT IHT LAT Lat MT WA IHT LHT WAT MT LH HT IE HT MT ME IH DAT MT LAT HT LT IHT LHE LHT ME MT IHT HT HT IT HT AHY Mo MT HT 1 HT 1H AT HT MT LHT T LH IHT WH MT T LHT HT HT LHT VT JH LHT WH WAT LE HAT TA Jtt LH A HIT Aff JT Mff MAT T IT IHT PM PT IHA JE VET MT MIT LHT LAT HT LET JT reasons why METAPOST is fun To mention a few you can enhance the layout with graphic or naments you can tune your graphics at runtime and simple high quality graphics can be very effective The previous graphics draws exactly 1001 lines in a scratch numbers in a wall fashion In 1998 the NTG did a survey among its members and in the report we used this fuz
84. or according to a user defined function Circular and linear shades look like this i there I m Circul Whow this is Li As you can see the shade lays behind the text as background overlay These overlays are unique METRPOST graphics so they will adapt themselves to the dimensions of the foreground defineoverlay circular shade uniqueMPgraphic CircularShade defineoverlay linear shade uniqueMPgraphic LinearShade The two framed texts are defined as framed background circular shade frame off b white Hi there I m Circular and framed background linear shade frame off b Nwhite Whow this is Linear We still have to define the graphics Here we use a macro that takes four arguments a path a number identifying the center of shading and the colors to start and end with Preliminary Version October 27 2000 startuniqueMPgraphic CircularShade path pj p unitsquare xscaled overlaywidth yscaled overlayheight circular_shade p 0 MPcolor a MPcolor b stopuniqueMPgraphic startuniqueMPgraphic LinearShade path pj p unitsquare xscaled overlaywidth yscaled overlayheight linear_shade p 0 MPcolor a MPcolor b stopuniqueMPgraphic The METAPOST macros circular shade and linear shade add information to the METAPOST output file which is interpreted by the converter built in CONTEXT Shading comes
85. path you can apply transformations to it like reversing Close reading of the previous code learns that the macro handles both directions Multiples of 90 degrees are often identified by a rectangular symbol We will now extend the previously defined macro in such a way that more types can be drawn numeric anglelength anglelength 20pt numeric anglemethod anglemethod L vardef anglebetween b str path path string save pointa pointb common middle curve where pair pointa pointb common middle path curve bounds numeric where if round point 0 of a round point 0 of b common point 0 of a else common a intersectionpoint b frs pointa point anglelength on Preliminary Version October 27 2000 A few applications pointb point anglelength on where turningnumber common pointa pointb cycle if anglemethod 1 curve pointa pointa rotated where 90 pointb middle point 5 along curve elseif anglemethod 2 middle common rotatedaround 5 pointa pointb 180 curve pointa middle pointb elseif anglemethod 3 middle common pointa rotatedaround pointa where 90 intersectionpoint common pointb rotatedaround pointb where 90 curve pointa middle pointb draw thefreelabel str middle common withcolor black curve
86. pos wid 0 len 0 pos 0 n 0 stopMPdrawing We also started fresh by resetting the drawing From now on each start command will add some more to this graphic The next macro is responsible for collecting the data Each element is passed on to using the bt ex construct So METAPOST itself will call TEx def whatever 1 appendtoks 1 to MPtoks setbox MPbox hbox bfd the MPtoks 3 Preliminary Version October 27 2000 NstartMPdrawing 1 len n the wd MPbox stopMPdrawing NstartMPdrawing pic n btex bfd 1 etex stopMPdrawing handletokens MetaPost is Fun with whatever We use the low level CONTEXT macro appendtoks to extend the token list MPtoks The handletokens macro passes each token character of MetaPost is Fun to the macro Whatever The tokens are appended to the token register MPtoks already defined Then we typeset the content of MPtoks in MPbox also already defined The width of the box is passed to METAPOST and stored in len By default the content of the drawing is expanded which means that the macro is replaced by its current meaning so the current width ends up in the metarost file The next part of the drawing starting with btex puts the token in a picture This time we don t expand the drawing since we want to pass font information Here the suppresses expansion of b
87. reason the header text and footer areas together make up the height of the text A close look at the left picture will reveal that the two arrows point to the center of the lines This is achieved by the top and 1ft directives If we would not have clipped the picture the arrow would have stuck half a line width outside the gray area that represents the page When constructing such pictures one should really pay attention to such details since it pays off in the overall look and feel of the document The vertical arrow represents the top space while the horizontal arrow denotes the distance to the back of the cover back space By changing their values you can shift the main body text on the page In a double sided layout scheme the back space is automatically mirrored on even pages Since we want to teach a bit of METAPOST now and then we will also show how these graphics were drawn An advanced METAPOST user may wonder why we hard code the dimensions and Preliminary Version October 27 2000 avoid metarost s powerful mechanisms for defining relations Our experience has taught us that in pictures like this providing a general solution seldom pays large dividents or savings in time startuseMPgraphic layout 1 pickup pencircle scaled 1mm fill unitsquare xyscaled 7cm 8cm withcolor 85white fill unitsquare xyscaled 5cm 5cm shifted 1cm 1 5ocm withcolor 625yellow fill unitsquare xyscaled 5c
88. that did this for you automatically Unfortunately there isn t one so we have to define one ourselve a macro o6 These circles were drawn using colorcircle 4cm 4 6 8 4 8 06 6 4 8 addto currentpicture also inverted currentpicture shifted 5cm 0 When we draw a path or stroke a path as it is called officially we actually perform an addition addto currentpicture doublepath somepath 111 command is actually addto currentpicture contour somepath We will need both doublepath and contour operations in the definition of inverted When wererosr has digested a path into a picture it keeps track of some characteristics We can ask for them using part operators The following operators can be applied to a transform vector one of METAPOST data types but also to a picture Say that we have drawn a circle Preliminary Version October 27 2000 draw fullcircle xscaled 3cm yscaled 2cm dashed dashpattern on 3mm off 3mm withpen pencircle scaled 1mm withcolor 625red picture p p currentpicture This circle looks like d N 7 We now ask for some of the characteristics of currentpicture like its color We could write the values to the log file but it is more convenient to put them on paper label rt redpart amp decimal redpart 4cm 5cm label rt greenpart amp decimal greenpart p 4cm Ocm
89. the q 4 pu X 4 L Figure 9 4 One more time Hofstadter s quotation Here also I will rewrite things a bit so that we can avoid startMPdrawing outside the macro and thereby avoid problems I can also add the maps cdrom cover as example Preliminary Version October 27 2000 10 Debugging Those familiar with CONTEXT will know that it has quite some visual debugging features build in So what may you expect of the METAPOST macros that come with CONTEXT In this chapter we will introduce a few commands that show some insight in what METAPOST is doing to your paths Since the outcome of METRPOST code is in many respects more predictable than that of TEK code we don t need that advanced visual debugging features Nevertheless we provide a few that are all based on visualizing paths This visualization is achieved by using dedicated drawing commands path p p fullcircle scaled 4cm drawpath p drawpoints p drawpointlabels p Since control points play an important role in defining the shape visualizing them may shed some insight in what METRPOST is doing path p p fullcircle xscaled 4cm yscaled 3cm drawpath p drawcontrollines p drawpoints p drawcontrolpoints p drawpointlabels p The pre and post control points show up as small dots and are connected to their parent point with thin lines oe AN 4 s o MB You can deduce t
90. unwanted expansion Preliminary Version October 27 2000 RotatedText rotation 165 Some Rotated Text That this method works equally well is demonstrated below 1 Pay Joy There are three ways to access a text defined with setMPtext Imagine that we have the follow ing definitions setMPtext 1 Now is this TeX or not setMPtext 2 See what happens here setMPtext 3 Text streams become pictures The MPbetex macro returns a btex etex construct The MPstring returns the text as a METAPOST string between quotes The raw text can be fetched with MPtext startMPcode picture p p MPbetex 1 2 picture textext MPstring 2 MEE picture r r thelabel MMPtext 3 origin for i p boundingbox p draw i withcolor 625red endfor for i q boundingbox draw i withcolor 625yellow endfor for i r boundingbox draw i withcolor 625white endfor currentpicture currentpicture scaled 2 draw origin withpen pencircle scaled 2 0mm withcolor white draw origin withpen pencircle scaled 1 5mm withcolor black stopMPcode The first two lines return text typeset by Tex while the last line leaves this to METAPOST ext MOSES or not If you watch closely you will notice that the first red alternative is positioned with the baseline on the origin pictures
91. was not to show them side by side but to present them as field stack in a document to be viewed at the computer screen For this purpose we have to define the graphics as symbols Ndefinesymbol step NprocessMPbuffer a b c d e f g 1 LE 1 Ndefinesymbol step 2 processMPbuffer a b c d e f g 2 Ndefinesymbol step 3 processMPbuffer a b c d e f g 3 LE 4 11 LE 51 11 Ndefinesymbol step processMPbuffer a b c d e f g 4 step definesymbol processMPbuffer a b c d e f g 5 A field stack is a sequence of overlayed graphics We will arrange to manually cycle with clicks of the mouse through the sequence of graphs depicting the construction of the midpoint of segment A fg applications Preliminary Version October 27 2000 A B So in fact we are dealing with a manual simulation The definition of such a stack is as follows definefieldstack midpoint construction step 1 step 2 step 3 step 4 step 5 frame on offset 3pt framecolor darkyellow rulethickness 1pt The first argument is to be a unique identifier the second argument takes a list of symbols while the third argument accepts settings More on this command can be found in the CONTEXT manuals The stack is shown as figure 13 6 Its caption provides a button which enables the reader to cycle though the stack We call this a stack because the graphics are positioned on top of each
92. we could have omitted the grouping since vardef macros are always grouped automatically Therefore we could have defined the macro as vardef randomscaledpath expr p s save r numeric r round 1 uniformdeviate 4 p xscaled s r yscaled s r enddef The command save declares that the variable is local to the macro Thus any changes to the new numeric variable r are local and will not interfere with a variable r defined outside the macro This is important to understand as variables outside the macro are global and accessible to the code within the body of the macro Macro definitions may be nested but since most METRPOST code is relatively simple it is seldom needed Nesting is discouraged as it makes your code less readable Besides def and vardef METAPOST also provides the classifiers primarydef secondarydef and tertiarydef You can use these classifiers to define macros like those provided by META POST itself primarydef x mod y enddef secondarydef p intersectionpoint q enddef tertiarydef softjoin q enddef A primary macro acts like the binary operators or scaled and shifted Secondary macros are like and logical or and take less precedence The tertiary operators like lt or the path and string concatenation operator amp have tertiary macros as companions More details can be found in the METAFONT book When it comes to taking precedence METAPOST tries to be as natural as
93. z21 z22 z23 z24 cycle draw z21 z23 draw z22 z24 draw z31l z32 z33 z34 cycle draw z31 z33 draw z32 z34 draw z4l z42 z43 z44 cycle draw z4l z43 draw z42 z44 The mid points can be calculated by METAPOST too The next lines define that those points are positioned halfway the extremes 21 O 5 zii z13 2 2 0 5 z21 223 gt 23 0 5 z31 z33 z4 0 5 z41 z43 To make them stand out we choose an alternative linestyle draw zl z3 dashed evenly draw z2 z4 dashed evenly Just to be complete we add a symbol that marks the right angle First we determine the common point of the two lines that lays at whatever point METAPOST finds suitable Preliminary Version October 27 2000 _Waleomeatte wc reos 20 whatever z1 z3 whatever z2 z4 mark rt angle 21 20 22 22 is not used at all So far most equations were rather simple and in order to solve them METAPOST did not have to work real hard The only boundary condition is that in order to find a solution METAPOST must be able to solve all dependencies The previous lines showing the whatever variable is a typical example of a situation where METRPOST has to be more clever The whatever variable is defined as a sort of anonymous vari able and it is left to METAPOST to make sure that it s solved somehow We will never really use it The macro mark rt angle draws the angle sy
94. 000 L spec Preliminary Version October 27 2000 91 9 2 Typesetting in METAPOST You can add text to METAPOST graphics and you can choose whether or not to have it typeset by Let s take a closer look at how this in itself a rather tricky feature is implemented The process You can let METRPOST process text that is typeset by TEK Such text is first embedded in the METAPOST file in the following way btex Some text to be typeset by etex This returns a picture but only after METAPOST has made sure that TEK has converted it into some thing useful This process of conversion is slightly system dependent and even a bit obscure First METAPOST calls a program that filters the btex etex commands next it calls TEK by passing the output routine in order to make sure that each piece of text ends up on its own page and afterwards it again calls a program that converts the DVI pages into METRPOST pictures In CONTEXT when using WEB2C you can generate the graphics at run time This takes more time than processing the graphics afterwards but has the advantage that TEK knows immediately what graphic it is dealing with When enabled CONTEXT will call either METAPOST or when the graphic contains btex etex commands call TEXEXEC which in turn makes sure that the right auxiliary programs are executed CONTEXT METRPOST Figure 91 How and
95. 22 23 z3 cycle l pasa 20 21 22 23 cycl 0 i 1 3 If you compare this graphic with the one using the result is the same but there is a clear difference in control points As a result combining with or makes a big difference Here we get a non smooth connection between the curves and the straight line Preliminary Version October 27 2000 z0 21 22 z3 cycle As you can see in the next graphic when we use we get a smooth connection between the straight line and the rest of the curve 20 21 22 23 1 So far we have joined the four points as one path Alternatively we subpaths and connect them using the ampersand symbol amp 21 22 amp z2 z3 z0 amp cycle So far we have created closed path Closing is done by cycle The following path may look closed but is in fact open ener 0 Only a closed path can be filled The closed alternative looks as follows We will see many exam ples of filled closed path later on Welcbme owe rapak Preliminary Version October 27 2000 Z0 21 22 23 4 20 cycle Here the final will try to make a smooth connection but because we already are at the starting point this is not possible However the cycle command can automatically connects to the first poin
96. 27 2000 Preliminary Version October 27 2000 Content Conventions 1 Welcome to METAPOST 11 Paths 2225 aa 12 Transformations 13 Constructing paths 1 4 Drawing pictures 1 5 Variables 1 6 Conditions 17 LOOPS sasadan Een 1 8 Macros 1 9 nasi aaa aa yadda ced 110 Colors 111 Dashes LIZ Lext id Lebe ER 113 Linearequations 114 Clipping 115 Cutting and pasting 2 Afew more details 21 Making graphics 22 Bounding boxes 2 3 Units sa es eal BAN ES ee RR dd 2 4 Scaling and shifting 2 5 Curve construction 2 6 Inflection tension and curl 2 7 Transformations 2 8 Only this far 2 9 Directions 210 Analyzingpictures 211 Additional operators 3 Embeddedgraphics 31 Getting started 3 2 External graphics 3 3 Integrated graphics 3 4 Graphic buffers 3 5 Communicating color 3 6 Common definitions 3 7 One page graphics 3 8 Managing resources Preliminary Version October 27 2000 4 41 4 2 4 3 4 4 4 5 4 6 5 1 5 2 5 3 6 1 6 2 6 3 6 4 6 5 71 72 73 74 75
97. 27 2000 1 1 1 5 1 5 2 The double period connector tells METAPOST that we want to connect the lines a smooth curve If you want to connect points with straight line segments you should use Closing the path is done by connecting the first and last point using the cycle command 1cm 1cm 1 5cm 1 5cm 2cm cycle Feel free to use at any point in your path 1cm 1cm 1 5cm 1 5cm 2cm 0cm cycle This path when drawn looks like this As you can see in some of the previous examples METRPOST is capable of drawing a smooth curve through the three points that make up the path We will now examine how this is done la The six small points are the so called control points These points pull their parent point in a certain direction The further away such a point is the stronger the pull Each point has at most two control points As you can see in the following graphic the end points of a non closed curve have only one control point m This time we used the path 1 5cm 1 5cm 2cm 0cm 1 1cm When you connect points by a smooth curve METAPOST will calculate the control points itself unless you specify one or more of them Preliminary Version October 27 2000 Welcome L2 4 This path is specified as lecm 1cm 1 5cm 1 5cm controls 3cm 2cm 2cm 0o
98. 4cm yscaled 3cm tickstep tickstep 2 ticklength ticklength 2 drawticks fullsquare xscaled 4cm yscaled 3cm The ticklength variable specifies the length of a tick Here we manipulated both the variables to get a more advanced system Preliminary Version October 27 2000 If visualizing a path would mean that we would have to key in al those draw commands you could hardly call it a comfortable tool Therefore we can say drawwholepath fullsquare scaled 3cm rotated 30 randomized 5mm The drawwholepath command shows everything except the axis If even this is too much labour you may say visualizepaths This redefines the draw and 111 command in such way that they also show all the information visualizepaths draw fullsquare scaled 3cm rotated 30 randomized 2mm You may compare this feature to the showmakeup command available in CONTEXT that redefines the TEK primitives that deal with boxes glues penalties and alike Preliminary Version October 27 2000 Of course you may want to take a look at the METAPOST manual for its built in more verbose tracing options One command that may prove to be useful is show that you can apply to any variable This command reports the current value if known to the terminal and log file The previous picture shows what is typeset when we also say showmakeup This command visual
99. 5 EX 5 B 2 E 2 a 5 5 5 Y E B a Preliminary Version October 27 2000 fullcircle urmoved 25 metafun macro fullcircle ulmoved 25 metafun macro fullcircle llmoved 1 25 metafun macro fullcircle lrmoved 1 25 metafun macro fullcircle urmoved 1 25 metafun macro path ulmoved pair fullcircle ulmoved 1 25 metafun macro 2 path slanted numeric fullcircle slanted 5 metapost primitive fullsquare rotated 45 metapost primitive path rotatedaround pairjnumeric fullsquare rotatedaround 25 5 45 metapost macro path reflectedabout pair pair fullcircle reflectedabout 25 1 25 1 metapost macro N N wa A Preliminary Version October 27 2000 reverse path 7 wy counterclockwise path a 2 3 NS e T E subpath numeric numeric of path NI Q o a 5 H BS E N Ne E 5 H d ET N Ne Preliminary Version October 27 2000 reverse fullcircle shifted 5 0 metapost primitive counterclockwise fullcircle shifted 5 0 metapost macro tensepath fullcircle metapost macro subpath 1 5 of fullcircle metapost primitive llcorner fullcircle metapost primitive lrcorner fullcircle metapost primitive urcorner path Ne o o 5 5 H ge
100. 81 8 2 8 3 8 4 91 92 9 3 Enhancing the layout Overlays Overlay variables Stacking overlays Foregrounds Typesetting graphics Graphics and macros Positional graphics The concept Anchors and layers Some examples Page backgrounds The basic layout Setting up backgrounds Multiple overlays Crossing borders Advanced features Shapes symbols and buttons Interfacing to Random graphics Graphic variables Shape libraries Symbol collections PONS asian e ate a te Typesetting in METAPOST The process Environments Labels 115 115 116 119 121 94 TEtext 156 9 5 Talking to 166 10 Debugging 183 1 Defining styles 189 111 Adaptivebuttons 189 12 Functions 197 13 A few applications 199 131 Simple drawings 199 132 Freelabels 202 133 Marking angles 207 134 Color circles 213 135 Fool yourself 218 136 Puzzles 222 137 Flow charts
101. CRIPT or PDF viewer will report slightly smaller values as page dimensions This is because those programs claim the pt to be a bp This confusion can lead to interesting discussions with desktop publishers when they have to use TEK They often think that their demand of a baseline distance of 13 4 is met when we set it to 13 4pt while actually they were thinking of 13 4bp which of course in other programs is specified using a pt suffix Therefore when embedding graphics in CONTEXT we strongly recommend that you use pt as the base unit instead The main reason why we spend so many words on this issue is that when neglected large graphics may look inaccurate Actually when taken care of it is one of the many reasons why documents always look so accurate Given that the eye is sensitive to distortions of far less than 1pt you can be puzzled by the fact that many drawing programs only provide a bounding box in rounded units Thereby they round to the next position to prevent unwanted cropping For some reason this low resolution has made it into the high end POSTSCRIPT standard In CONTEXT we try to deal with these issues as well as possible Scaling and shifting When we draw a shape METAPOST will adapt the bounding box accordingly This means that a graphic has its natural dimensions unless of course we adapt the bounding box manually When you limit your graphic to a simple shape say a rectangle shifting it to some place can g
102. FPfont E setMFPfont T setMFPfont A setMFPfont P setMFPfont O setMFPfont S setMFPfont T quad stopbuffer test 3 test 4 Figure9 3 continuous text typeset in a non standard shape spread over four areas tracing on defineoverlay edge getbuffer circle The text and graphics come together in a framed text startbuffer quote framed offset 6pt background edge frame off getshapetext stopbuffer placefigure One more time Hofstadter s quotation getbuffer quote Preliminary Version October 27 2000 Preliminary Version October 27 2000 amp Ta Thi S 1 EU Donald Knuth has gt spent the past several years work ing on a system allowing him to control many aspects of the design of his forthcom ing books from the typesetting and layout 5 down to the very shapes of the letters Seldom hasanauthor had anything remotely like this pow 3 er to control the final appearance of his or her work lt Knuth s typesetting system has become well known and available in many countries around the world By contrast his METAFONT system for designing families of typefaces has not y become as well known or available In his article The Concept of Ph 9 e circl 9 a Meta Font Knuth sets 2 forth for
103. METAPOST work together Environments In case you want to pass code that is shared by all btex et ex pictures METAPOST provides verbatimtex DefineSomeCommands etex However in CONTEXT one has a better mechanism available The advantage of using that method is that otherwise all graphics let METAPOST or invoke even if no TEK pictures constructed The best way to pass environments is the following As an example we switch to the 15 basic POSTSCRIPT fonts startMPenvironment setupbodyfont pos stopMPenvironment Preliminary Version October 27 2000 _ Typesettinggin Merseost 9 3 9 4 This means that in code like the following a Times Roman will be used startMPcode draw btex Meta is a female lion etex xysized the textwidth the textheight stopMPcode We have included the graphic on the next page in a slightly different look You may consider coloring the dots to be an exercise in clipping An environment can be reset with resetMPenvironment or by passing reset as key to startMPenvironment startMPenvironment reset setupbodyfont pos stopMPenvironment Labels In METAPOST you can use the label macro to position text at certain points label x origin The font and scale are determined by two variables defaultfont and defaultscale the former expecting the name of a font in the form of
104. October 27 2000 3 8 setupMPpage offset lpt background color backgroundcolor gray Ndefinecolor gray 5 625 Ndefinecolor red r 625 definecolor yellow r 625 g 625 startuseMPgraphic test fill fullsquare rotated 45 scaled 4cm withcolor MPcolor yellow stopuseMPgraphic starttext startMPpage includeMPgraphic test fill fullcircle scaled 3cm withcolor MPcolor red stopMPpage stoptext Given that the CONTEXT english interface format is present on your system you can process this file with TEXEXEC for instance using PDFTEX The once directive saves some runtime texexec onc pdf mfun 888 You can define many graphics in one file The TEXEXEC manual describes how to selectively process pages If you use PDFTEX you can include individual pages from PDF files placefigure A silly figure demonstrating that stand lalone graphics can be made externalfigure mfun 888 page 1 In this case the page 1 specification is not really needed You can scale and manipulate the figure in any way supported by the macro package that you use Managing resources A graphic consists of curves either or not filled with a given color A graphic can also include text which means that fonts are used Finally a graphic can have special effects like a shaded fill Colors fonts and special effects go under the name resources since they may demand special care or suppor
105. RightEdge Edge 625red We use two nested for loops to step over the areas A for loop with a step of 1 will fail be cause the indices are defined in a rather special way On the other hand the mechanism is rather tolerant in the sense that i j and j i are both accepted Preliminary Version October 27 2000 Page backgrounds 6 5 Edward R Tufte thrive in information thick worlds because of our marvelous and everyday capacity to select buit single out structure highlight group pair merge harmonize synthesize focus organize educe boil down choose categorize catalog classify list abstract scan ook into late discriminate distinguish pigeonhole pick over sort integrate blend spect filter lump skip smooth chunk average approximate cluster aggregate outline sum ize itemize review dip into through browse glance into leaf through skim refine numerate glean synopsize winnow the wheat from the chaff and separate the sheep from th ws I came to the conclusion that the designer of a new system must not only be the implemente d first large scale user the designer should also write the first user manual The separation of any of these four components would have hurt TEK significantly If 1 hac ot participated fully in all these activities literally hundreds of improvements would never hav sen made because I w
106. RightEdgeDistance RightEdgeWidth Since using these variables to construct paths is not that handy the areas are available as prede fined paths which we will demonstrate here In figure 6 2 you see two pages odd and even with a background spanning the outer margin and the text area You can access an area in two ways The area itself is available as Area StartPage fill Area Text Text withcolor 85white StopPage If you use an area this way you will notice that it is not positioned at the right place An Area is just a rectangle If you want a positioned area you should use the Field array Preliminary Version October 27 2000 Page Edward R Tufte Edward R Tufte We thrive in information thick worlds because of our marvelous and everyday capacity to select We thrive in information thick worlds because of our marvelous and everyday capacity to select Teao E an a Ka pa a Ed the designer should also write the first user first user the designer should also write the firs ifthad any ie cons e DM MT had mot participated fully in all these activities literally hundreds of improvements would never have not participated fully in all these activities literally hundreds of improvements would never have influenced But a system cannot be successful if it is too strongly influenced by a single person Once the initial design is 20 with many different oris design
107. StartPage path numeric 1 n 1 5LineHeight n 0 origin shifted 1 0 origin shifted PaperWidth 1 0 Preliminary Version October 27 2000 Enfanging the Figure 4 4 Penalty lines for i PaperHeight 1 step l until 1 p mor ds drawoptions withcolor 85white fill p shifted 0 1i StrutHeight reverse p shifted 0 i StrutDepth cycle drawoptions withpen pencircle scaled 25pt withcolor 5white draw p shifted 0 1 draw p shifted 0 i tExHeight draw textext origin How are those penalty lines called in english I may not steal candies amp decimal n shifted 1 1 endfor StopPage stopMPpage This code demonstrates the use of LineHeight ExHeight StrutHeight and StrutDepth We set the interline spacing to 1 5 so that we get a bit more loose layout The variables mentioned are set each time a graphic is processed and thereby match the current font settings Preliminary Version October 27 2000 Positional graphics In this chapter we will explore stepwise some of the more advanced but also conceptually more difficult graphic capabilities of CONTEXT It took quite some experiments to find the right way to support these kind of graphics and you can be sure that in due time extensions will show up The concept After has read a paragraph of text i
108. The label is positioned in the direction opposite to this center of gravity pair destination for whereto up down left right destination scantokens whereto lcm freedotlabel whereto destination origin drawarrow origin destination withpen pencircle scaled 25mm withcolor 625 red endfor So in this code fragment we use the string as string and by means of scantokens as a point or vector Preliminary Version October 27 2000 A few up left right down The previous definition is a stepping stone to the next one This time we don t use points but the dir command This command converts an angle into a unitvector pair destination for whereto 0 step 30 until 330 destination dir whereto 1 5cm freedotlabel decimal whereto destination origin drawarrow origin destination withpen pencircle scaled 25mm withcolor 625 red endfor In METAPOST the angles go counter clockwise which is not that illogical if you look at it from the point of view of vector algebra 90 120 60 210 Analyzing pictures Unless you really want to know all details you can safely skip this section The METAPOST features discussed here are mainly of importance when you write advanced macros In section 1 12 we demonstrated that you can use either METAPOST or TEX to typeset text The METAPOST result looked like this string
109. This simple dashpattern is pre defined as picture even1y Because this is a picture you can and often need to scale it draw 0 0 10cm 0 dashed evenly scaled 1mm withpen pencircle scaled 1mm Opposite to a defaultpen there are no default color and default dash pattern The macro drawoptions provides you a way to set the default attributes drawoptions withcolor red Text Since METAFONT is meant for designing fonts it will be no surprise that the only means for includ ing text are those that permit you to add labels to positions for the sole purpose of documentation Because METAPOST is derived from METAFONT it provides labels too but in order to let users add more sophisticated text like a math formula to a graphic it also provides an interface to Because we will spent a whole chapter on text in METAPOST we will limit ourselves to just some basics pair a 3cm 3cm label top top a label bot bot a label lft lft a label rt rt a These four labels show up at the position specified after the dot If we don t specify a position we will get a centered label top Ift rt bot The command dot label also typesets a point as dot and has the same arguments but swapped which makes using these commands kind of trial and error pair a a 3cm 3cm dotlabel top top a dotlabel bot bot a dotlabel ift lft a dotlabel rt rt a
110. Version October 27 2000 2 6 The next example demonstrates how the resolution depends on the length and nature of the seg ment drawmidpoints fullsquare xscaled 200pt yscaled 40pt randomized 10pt 5 Inflection tension and curl The METAPOST manual describes the meaning of as choose an inflection free path between these points unless the endpoint directions make this impossible When you start searching for nice examples to demonstrate the difference between and you will be surprised that honouring the request for less inflection is more often impossible than you would expect We will demonstrate this to a few graphics In the four figures on the next pages you will see that is not really suited for taming wild curves If you really want to make sure that a curve stays within certain bounds you have to specify it as such using control or intermediate points In the figures the gray curves draw the random path using on top of yellow curves using As you can see only in a few occasions the yellow inflection free curves show up The tension specifier can be used to influence the curvature To quote the METAPOST manual once more The tension parameter can be less than one but it must be at least 3 4 The following paths are the same zl ZA 21 tension 1 22 zl tension 1 and 1 z2 The tripple dot command is actually a macro so that the following two paths are identi
111. a pen we would be faced with a considerable amount of typing particularly in situations where we use pens similar to the fourth specification above For that reason METRPOST supports the concept of a current pen The best way to set this pen is to use the pickup macro pickup pencircle xscaled 2mm yscaled 4mm rotated 30 This macro also stores some characteristics of the pen in variables so that they can be used in the more complicated calculations that are involved in situations like drawing font like graphics If we substitute pencircle by pensquare we get a different kind of shapes In the non rotated pens the top bottom left and right parts of the curve are thinner You should look at pens in the way an artist does He follows a shape and in doing so he or she twists the pen and thereby the nib and puts more or less pressure on it The chance that you have an appropriate pen laying at your desk is not so large but you can simulate the following wErRPOST s by taking two pencils and holding them together in one hand If you position them in a 45 degrees angle and draw a circle you will get something like Preliminary Version October 27 2000 If you take a calligraphic pen with a thin edge of 5cm you will get You can define such a pen yourself path p p fullcircle xscaled 2cm yscaled 3cm pen doublepen doublepen makepen 0 0 3cm 3cm pickup doubl
112. age You may wonder why unique graphics are needed when a single graphic might be used multiple times by scaling it to fit the situation Since a unique graphic is calculated for each distinctive case we can be sure that the current circumstances are taken into account Also scaling would result in incomparable graphics Consider the following definition startMPgraphic draw unitsquare xscaled 5cm yscaled withpen pencircle scaled 2mm withcolor 625red stopMPgraphic Since we reuse the graphic the dimensions are sort of fixed and because the graphic is calculated once scaling it will result in incompatible line widths These graphics were placed with mEmbedded graphics Preliminary Version October 27 2000 hbox bgroup loadcurrentMPgraphic width 5cm height 1cm placeMPgraphic quad loadcurrentMPgraphic width 8cm height lcm placeMPgraphic egroup Imagine what happens when we add some buttons to an interactive document without taking care of this side effect All the frames would look different Consider the following example startuniqueMPgraphic right or wrong pickup pencircle scaled 075 fill unitsquare withcolor 8white draw unitsquare withcolor 625red currentpicture currentpicture xscaled overlaywidth yscaled overlayheight stopuniqueMPgraphic Let s define this graphic as a background to some buttons defineoverlay button
113. any points make up the path 20 21 22 23 cutbefore point 2 of 20 21 22 23 As with subpath you can use fractions to specify the time on the path although the resulting point is not necessarily positioned linearly along the curve 20 21 22 23 cutbefore point 2 5 of 20 21 22 23 If you really want to know the details of where fraction points are positioned you should read the METAFONT book and study the source of METAFONT and METAPOST where you will find the com plicated formulas that are used to calculate smooth curves Preliminary Version October 27 2000 z0 zl cycle Like any closed path this path has points where the tangent is horizontal or vertical Early in this chapter we mentioned that a pair or point can specify a direction or vector Although any angle is possible we often use one of four predefined directions We can use these predefined directions in combination with directionpoint and cutafter The following command locates the first point on the path that has a tangent that points vertically upward and then feeds this point to the cutafter command z0 zl cycle cutafter directionpoint up of z0 zl cycle You are not limited to predefined direction vectors You can provide a pair denoting a direction In the next example we use the following cyclic path z0 zl cycle Using is not mandatory but make the expression look less complicated
114. aphics themselves this is no real problem we can put them all on the page layer if needed in separate overlays How is such a graphic defined In fact these graphics are a special case of the already present mechanism of including METAPOST graphics The circles are defined as follows startMPpositiongraphic mypos circle initialize_box MPpos MPvar self path p p llxy lrxy urxy ulxy cycle pickup pencircle scaled 1pt fill p withcolor 800white draw p withcolor 625yellow anchor box MMPanchor MMPvar self stopMPpositiongraphic Drawing the lines is handled in a similar fashion startMPpositiongraphic mypos line path pa pb pab numeric na nb initialize_box MPpos MPvar from na pa llxy lrxy urxy ulxy cycle initialize_box MPpos MPvar to nb nxy pb llxy lrxy urxy ulxy cycle if na nb pab center pa center pb cutbefore intersectionpoint pa pab cutafter intersectionpoint pb pickup pencircle scaled 1pt draw pab withcolor 625yellow anchor_box MPanchor MPvar from fc stopMPpositiongraphic The command startMPpositiongraphic defines a graphic in this example we have called itmypos circle Positional graphics Preliminary Version October 27 2000 Ga The METAPOST macro initialize_box retu
115. ariable If we had not set it to mitered we would have got round corners We don t set the 1 since flat cap would not extend far enough into the touching curve and would have left a small hole The next example shows what happens if we set these variables to the wrong values In fact we misuse the fact that both curves overlay each other AS The complete logo definition is a bit more extensive since we also want to add a background Because we need to clip the blue foreground graphic we must temporarily store it when we fill the background numeric width height line delta width 5cm height width 2 line height 4 delta line linejoin mitered pickup pencircle scaled line color nsblue nsblue 0 0 1 color nsyellow nsyellow 1 1 0 21 0 height 2 z2 width 2 height 4 yl 23 width 2 height 4 y4 z4 width 0 25 x4theight 2 yl z6 x4 2yl 27 l 5 z5 26 j path p p 21 22 23 24 path 23 24 25 27 numeric d 1x ly ux uy d line 2 1 3d d 3 ly d ux rt x5 d 3 uy top A few applications Preliminary Version October 27 2000 13 11 path r 1x ly ux ly ux uy l1x uy cycle lx lx delta ly ly delta ux uxtdelta uy uytdelta path 1x ly ux ly ux uy l1x uy
116. at a widely praised program called up on the screen will make every thing automatic from now on There are quite some hard coded values in these graphics like the linewidths offsets and colors Some of these can be fetched from the framed environment either by using TEK macros or di mensions or by using their Met aFun counterparts In the following table we summarize both the available METAPOST variables and their TEK counterparts They may be used intermixed METRPOST variable command meaning OverlayWidth overlaywidth current width Overlay Height overlayheight current height OverlayDepth overlayheight current depth often zero OverlayColor MPcolor overlaycolor background color OverlayLineWidth overlaylinewidth width of the frame OverlayLineColor MPcolor color of the frame BaseLineSkip the baselineskip main line distance LineHeight the baselineskip idem BodyFontSize the bodyfontsize font size of the running text StrutHeight strutheight space above the baseline StrutDepth strutdepth space below the baseline Preliminary Version October 27 2000 startuseMPgraphic FunnyFrame picture p numeric o path a b pair c p textext rt MMPstring FunnyFrame BodyFontSize a unitsquare xyscaled OverlayWidth OverlayHeight p shifted 20 O0verlayHeight ypart center p pickup pencircle scaled OverlayLineWidth b
117. ath p p zl z2 z3 z4 Although it is accepted to consider 2 to be a variable it is in fact a vardef macro that expands into a pair x y This means that the previous definitions internally become x1 y1 0 height 2 x2 y2 width 2 height 4 yl x3 y3 width 2 height 4 y4 x4 y4 width 0 Preliminary Version October 27 2000 Aew applications These 8 relations can be solved by METAPOST since all dependencies are known 1 0 yl height 2 x2 width 2 height 4 y2 yl x3 width 2 height 4 y3 y4 x4 width 4 0 Since we express the variables x and y in terms of relations we cannot reuse them since that would mean that inconsistent relations occur So the following lines will lead to an error message 21 10 20 21 30 50 For similar reasons we may not assign a value using to such a z variable Within mETRPOST figure z variables are automatically saved which means that they can be reused for each figure So far we have defined the following segment of the logo 2 3 The next expressions are used to define the second segment The third expression determines z 7 to be positioned on the line 25 26 where we extend this line by 50 25 x4theight 2 yl 26 x4 2yl 27 1 5 z5 z6 path q z3 z4 z5 z 3 2 e 0 1 e 3 e 0 1 e e e 2 2 3 e e 0
118. ay backgraphics positionoverlay backgraphics setupbackgrounds page background backgraphics foreground foregraphics Preliminary Version October 27 2000 T positionaligraphiess In this definition the predefined overlay foreground inserts the page data itself so the fore ground graphics end up on top This example also demonstrates that you should be well aware of the way CONTEXT builds a page There are six main layers in some cases with sublayers The body text goes into the main text layer which unless forced otherwise lays on top 1 paper background 3 page backgrounds 5 logo areas 2 area backgrounds 4 text areas 6 main text The paper background is used for special sometimes internal purposes There are three page backgrounds left right and both The text areas logo areas and backgrounds are a 5 x 5 matrices leftedge leftmargin text rightmargin rightedge x top header text footer and bottom The main text is what you are reading now Since the page background is applied last the previous layers can considered to be the fore ground to the page background layer And indeed it is available as an overlay under the name foreground as we already saw in the example Foregrounds are available in most cases but for the moment not when we are dealing with the text area Since anchoring the graphics is imple mented rather independent of the position of the gr
119. background lions 1 We can add a supperellipsed frame using the following definition startuniqueMPgraphic lions a path p p fullsquare xyscaled overlaywidth overlayheight superellipsed 85 pickup pencircle scaled 1pt fill p withcolor 850white draw p withcolor 625yellow stopuniqueMPgraphic defineoverlay lions uniqueMPgraphic lions a 8 startuseMPgraphic lions b path p p fullsquare xyscaled overlaywidth overlayheight randomized 5pt pickup pencircle scaled 1pt fill p withcolor 850white draw p withcolor 625yellow stopuseMPgraphic defineoverlay lions uniqueMPgraphic lions b startuniqueMPgraphic lions c path p p fullsquare xyscaled overlaywidth overlayheight squeezed 2pt pickup pencircle scaled 1pt fill p withcolor 850white draw p withcolor 625yellow stopuniqueMPgraphic defineoverlay lions uniqueMPgraphic lions cJ Ehhan ing ie Jayotit Preliminary Version October 27 2000 4 6 yd Jas Jd a M X Jen Bat X Hess je Jed je id Y Pani 13133446 These paragraphs were typeset with the following settings setupalign broad right Nveryraggedright setupalign broad middle Nveryraggedcenter setupalign broad left Nveryraggedleft The broad increases the raggedness We defined three
120. become start everything 1 stand out draw basics stop everything start everything 2 draw basics stand out draw circles stop everything start everything 3 draw basics draw circles stand out draw intersection stop everything start everything 4 draw basics draw circles draw intersection stand out draw bisector stop everything start everything 5 draw basics draw circles draw intersection draw bisector stand out draw midpoint stop everything The definitions of the symbols now refer to an external figure step Nexternalfigure step step Nexternalfigure step Ndefinesymbol 117 LE 2 I 2 1 definesymbol step 3 Nexternalfigure step 3 L 4 41 LE Sd 511 Ndefinesymbol step Nexternalfigure step step Nexternalfigure step definesymbol definesymbol Which method is used depends on the way the graphics are used In this example we wanted to change the definition of everything so here the third method was quite useful 13 10 Simple Logos Many company logos earn their beauty from their simplicity One of the logos that most dutch people have imprinted in their mind is that of the Dutch Railway Company NS An interesting feature of this logo is that although it is widely known drawing it on a piece of paper from mind is a task that many people fail fei applications _ Preliminary Version Octobe
121. better alternative is path unitslant unitslant origin origin shifted 1 1 draw unitslant xscaled 5cm yscaled 1cm withpen pencircle scaled 5mm withcolor 625yellow 2 5 Curve construction Chapter 3 of the METAFONT book explains the mathematics behind the construction of curves Both METRFONT and METRPOST implement B zier curves The fact that these curves are called after Pierre B zier obscures the fact that the math behind them originates with Sergei Bernshtein The points on the curve are determined by the following formula z t 1 Hz 31 ttz 301 tz za Here the parameter t runs from 0 1 As you can see we are dealing with four points In practice this means that when we construct a curve from multiple points we act on two points and the two control points in between So the segment that goes from 21 to 24 is calculated using these two points and the points that METAFONT METAPOST calls post control point and pre control point 27 26 25 more Tas Preliminary Version October 27 2000 The previous curve is constructed from the three points 21 24 and z7 The curve is drawn in META POST by 21 24 27 and is made up out of two segments The first segment is determined by the following points point z of the curve the postcontrol point 22 of zi the precontrol point z3 of z4 4 point z4 of the curve mro On the next pages we w
122. ble Preliminary Version October 27 2000 sd Preliminary Version October 27 2000 13 131 few applications For those who need to be inspired we will demonstrate how wEraPosr can be used to enhance your document with simple graphics In these examples we will try to be not too clever simply because we lack the experience to be that clever The real tricks can be found in the files that come with METAPOST Simple drawings In the words of John Hobby the creator of METAPOST METRPOST is particularly well suited for generating figures for technical documents where some aspects of a picture may be controlled by mathematical or geometrical constraints that are best expressed symbolically In other words METRPOST is not meant to take the place of a freehand drawing tool or even an interactive graphics editor An example of such a picture is the following one which is dedicated to David Arnold who asked me once how to draw a spring So imagine that we want to draw a schematic view of a system of four springs A rather natural way to define such a system is 21 2cm 0 z2 0 2cm 23 2cm 0 z4 0 2cm pickup pencircle scaled 1 5pt drawoptions withcolor 625red draw spring zl z2 75cm 2 10 draw zl 1 5 21 draw spring 22 z3 75cm 2 9 draw z2 1 1 22 draw spring 23 24 75cm 2 8 draw z3 1 5 z3 draw spring 24 21 75cm 2 7 draw z4
123. bles indicates the presence of conditionals Indeed the general form of METRPOST S if then else conditional follows if 10 draw p else draw q fi Watch the colons after the if and else clause They may not be omitted The semi colons on the other hand are optional and depend on the context You may say things like draw if n 10 else q fi Here we can omit a few semi colons draw if n 10 p else q fi withcolor red Adding semi colons after p and q will definitely result in an error message since the semi colon ends the draw operation and withcolor red becomes an isolated piece of nonsense There is no case statement available but for most purposes the following extension is ade quate draw p withcolor if n 10 red elseif n 10 green else blue fi There is a wide repertoire of boolean tests available if picture p if known n if odd i if cycle q Of course you can use and or not and to construct very advanced boolean expressions If you have a bit of programming experience you will appreciate the extensive support of condi tionals in METRPOST Welcome Preliminary Version October 27 2000 1 7 Loops Yet another programming concept present in METRPOST is the loop statement the familiar for loop of all programming languages for i 0 step 2 until 20 draw 0 i endfor As explained convincingly in Niklaus Wirt
124. bounding box is part of this data Internally METAPOST keeps track of two bounding boxes the natural one and the forced one The forced one is actually a component of the picture which applies to all previously added graphics You can calculate the bounding box from the 11 corner and urcorner or if you like ul corner and 1 and the Met aFun command boundingbox does so The four corners that make up the bounding box are either the natural ones or the ones forced by setbounds You can force METAPOST to report the natural ones by setting t ruecorners to 1 The next example demonstrates this feature pickup pencircle scaled 2mm path p draw fullcircle scaled 4cm slanted 5 withcolor 625white setbounds currentpicture to boundingbox currentpicture enlarged 5mm interim truecorners 0 p boundingbox currentpicture interim truecorners 1 boundingbox currentpicture pickup pencircle scaled 1mm draw p withcolor 625red draw q withcolor 625yellow gt Preliminary Version October 27 2000 We use interimbecause truecorners is an internal METAPOST variable Since METRPOST can handle fonts it can even generate font metric files it is no surprise that we can also ask for the natural size of a font For this we use fontsize However you should beware of the fact that the size reported is in base points Since this is METAPOST s native unit this is no pr
125. cal zd Z2 zl tension atleast 1 z2 The at least directive tells METAPOST to do some magic behind the screens Both the 3 4 and the atleast lead to the question what exactly is the influence of tension directive We will try to demystify tension by drawing the next graphic Preliminary Version October 27 2000 A few u lom zl 0 0 22 2u 4u z3 4u 0 def sample expr p c draw p withpen pencircle scaled 2 5mm withcolor white draw p withpen pencircle scaled 2 0mm withcolor c enddef for i 75 step 05 until 1 sample zl tension i z2 z3 625red endfor for i l step 05 until 2 sample zl tension i z2 z3 625yellow endfor sample zl z2 z3 625white sample zl z2 z3 625white Indeed values less than 75 give an error message but large values are okay As you can see the two gray curves are the same So here atleast 1 means 1 even if larger values are useful Curves are made up out of points and each point has two control points Since the tension specifier finaly becomes a control point it will be no surprise that you may specify two tension values If we replace the tension in the previous example by tension i and 2i we get the following graphic Preliminary Version October 27 2000 We mentioned control points
126. center of points we need to repeat this move in order to draw the red path really inside the other one pair q top top 5 llcorner p lrcorner Operations like top and its relatives bot 1ft and rt can be applied sequentally We already showed that q was defined as a series of rotations draw q q rotated 90 q rotated 180 q rotated 270 cycle withcolor 625red As an intermezzo we will show an alternative definition of q Because each point is rotated 90 degrees more we can define a macro that expands into the point and rotates of afterwards Be cause each consecutive point on the path is rotated an additional 90 degrees we use the METAPOST macro hide to isolate the assignment The hide command executes the hidden command and afterwards continues as if it were never there You must confuse this with grouping since the hidden commands are visible to its surroundings A few more details Preliminary Version October 27 2000 def qq hide q q rotated 90 enddef draw qq gq gq cycle withcolor 625red The macro top uses the characteristics of the current pen to determine the displacement Howev er for the more complicated pen shapes we need a different trick to get an inside path Let s start by defining a elliptical path pickup pencircle xscaled 3mm yscaled 5mm rotated 30 path p p fullcircle xscaled yscaled 3cm draw p withcolor
127. circle scaled 3mm e n 1 length 1 stroked false clipped true bounded false n 2 length 1 stroked true clipped false bounded false Preliminary Version October 27 2000 TEAR setbounds currentpicture to fullcircle draw fullcircle withpen pencircle scaled 3mm clip currentpicture to fullcircle n 1 length 0 stroked false clipped false bounded true n 2 length 1 stroked true clipped false bounded false The description lines were generated by the following loop n 0 for i within currentpicture no n 1 label rns amp decimal n amp amp length amp decimal length i amp amp stroked amp condition stroked i amp amp Clipped amp condition clipped i amp 6 bounded amp condition bounded i 0 n 5cm endfor If we have a textual picture we can also ask for the text and font Take the following picture picture p p MetaFun infont defaultfont scaled 2 rotated 30 slanted 5 shifted 0 ypart center p currentpicture p Here we can ask for label rt textpart amp textpart p amp fontpart p 4cm 0 25cm 0 25 label rt fontpart and get textpart MetaFun fontpart uplr8t pu If we re dealing with a path the transformations have ended up in the path specification If we hav
128. circles draw_intersection draw_bisector draw_midpoint bb boundingbox currentpicture currentpicture nullpicture enddef def stop_everything setbounds currentpicture to bb enddef stopbuffer Preliminary Version October 27 2000 A few In figure 13 5 we demonstrate the effect of this redefinition For this purpose we scale down the graphic to a comformatble 40 of course by using an additional buffer We also visualize the bounding box startbuffer h def stop_everything setbounds currentpicture to bb draw bb withpen pencircle scaled 5pt withcolor 625yellow currentpicture currentpicture scaled 4 enddef stopbuffer The graphic itself is defined as follows Watch how we use the default buffer to keep the defini tions readable startbuffer startcombination 5 1 NprocessMPbuffer a b c h d e f g 1 step 1 processMPbuffer a b c h d e f g 2 step 2 processMPbuffer a b c h d e f g 3 step 3 processMPbuffer a b c h d e f g 4 step 4 processMPbuffer a b c h d e f g 5 step 5 stopcombination stopbuffer placefigure here fig 1 till 5 The five graphics each with the same bounding box getbuffer A ea AN V M V V step 1 step 2 step 3 step 4 step 5 Figure 13 5 The five graphics each with the same bounding box As the original purpose of these graphics
129. cle buildcycle reverse r b g buildcycle buildcycle b reverse g r rr gg transformed t bb rr transformed t cc transformed t mm yy transformed t fill fullcircle scaled radius withcolor white fill rr withcolor red fill cc withcolor white red H fill gg withcolor green fill mm withcolor white green fill bb withcolor blue fill yy withcolor white blue Preliminary Version October 27 2000 for i rr gg bb cc mm yy draw i withcolor 5white endfor currentpicture currentpicture xsized size enddef This rather nice circle is defined as colorcircle 4cm 4 6 8 8 4 6 6 8 4 The final implementation which is part of Met aFun is slightly more efficient vardef colorcircle expr size red green blue save r g b c m y w Save radius path b c m y numeric radius radius 5cm pickup pencircle scaled radius 25 transform t t identity rotatedaround origin 120 r fullcircle rotated 90 scaled radius shifted 0 radius 4 rotatedaround origin 135 b r transformed t g b transformed t buildcycle subpath 1 7 of g subpath 1 7 of b y c transformed t m y transformed t w buildcycle subpath 3 5 of r subpath 3 5 of g subpath 3 5 of b pushcurrentpicture fill r withcolor red E fill g withcolo
130. cle scaled gap draw 0 0 0 height withcolor white stopuseMPgraphic The third row graphics again extend the first graphic First we copy the picture constructed so far Wath the double assignment Next we clip the pictures in half and shift the right half down over the width of the circle startuseMPgraphic third includeMPgraphic first picture p p q currentpicture clip p to unitsquare xscaled width yscaled height clip q to unitsquare xscaled width yscaled height currentpicture addto currentpicture also q shifted 0 radius 2 stopuseMPgraphic Puzzles Maybe Flow charts Instead of starting anew every time you can use predefined macros like those in the flow chart module Let s see how we can influence the METAPOST code Maybe not here Chemistry METAPOST can do it s work unseen as in the chemistry module that comes with CONTEXT There METAPOST is used as one of the graphical plug ins It demonstrates that we can put METAPOST to work without seeing any code applications Preliminary Version October 27 2000 13 9 Growing graphics Although METAPOST is not really suited an a simulation engine it is possible to build graphics that are built and displayed incrementally with a sequence of mouse clicks The following example is the result of an email discussion David Arnold and the author had while Met aFun evolved Instead of def
131. clipped cow Here we have divided the cow in sik cells so that we can clip its head and tail This kind of clipping enables you to zoom in or focus on a specific part of a graphic Nsetupclipping nx 3 ny 2 startcombination clip x 1 y 1 externalfigure cow mps width 4cm 1 1 clip x 3 y 1 externalfigure cow mps width 4cm 3 1 stopcombination Alternatively we can specify a width height hoffset and voffset as demonstrated in figure 8 3 f Figure 8 3 Another clipped cow placefigure here fig clipped cow 2 Another clipped cow clip width 2cm height 2cm hoffset 0cm voffset 0cm externalfigure cow mps width 4cm Because METAPOST supports clipping it will be no surprise that both techniques can be combined In the next example we will zoom in on the head of the cow We also use this opportunity to demonstrate how you can package a clip in a figure definition startMPclip head clip w width h height clip currentpicture to 0 n w h down left 0 0 cycle stopMPclip placefigure here fig circular clipped cowhead A quarter circle applied to a cows head ruledhbox clip nx 2 ny 2 x 1 y 1 mp head clip externalfigure cow mps width 4cm Preliminary Version October 27 2000 A more advanced clip is demonstrated in figure 8 4 We added ruledhbox to demonstra
132. cm In this path the second and third point share a control point Watch how the curve is pulled in that direction It is possible to pull a bit less by choosing a different control point lecm 1cm 1 5cm 1 5cm controls 2 75cm 1 25cm 2cm O0ocm Now we get Es We can also specify a different control point for each connecting segment N This path is defined as 1cm 1cm controls 5cm 2cm 2 5cm 2cm 2cm 5cm Transformations We can store a path in a path variable Before we can use such a variable we have to allocate its memory slot with path path p p 1cm 1cm 1 5cm 2cm 2cm 0cm Although we can manipulate any path in the same way using a variable saves us the effort to key in a path more than once Preliminary Version October 27 2000 In this graphic the path stored in p is drawn twice once in its displaced form The displacement is defined as p shifted 4cm 2cm In a similar fashion you can rotate a path You can even combine shifts and rotations First we rotate the path 15 degrees counter clockwise about the origin p rotated 15 Y Z This rotation becomes more visible when we also shift the path to the right by saying rotated 15 shifted 4cm Now we get 2 Note that rotated 15 is equivalent to p rotatedaround origin 15 gt lt Preliminary Version October 27 2000
133. ctober 27 2000 startMPdrawing for i 1 upto n pic i pic i shifted 0 ypart 5 ulcorner pic i llcorner pic il endfor stopMPdrawing So now we have Ow LB e When we typeset on a half circle we should map the actual length onto a partial circle We denote the radius with an r and shift the pictures to the left startMPdrawing r len n Pi for i 1 upto n 1 pic i shifted r 0 endfor stopMPdrawing You can now use the following code to test the current state of the pictures Of course this code should not end up in the final definitions startMPdrawing draw origin withpen pencircle scaled 5pt withcolor red for i l upto n draw pic i draw boundingbox pic i withpen pencircle scaled 25pt withcolor red endfor stopMPdrawing Boc Later we will write a compact efficient macro to take care of rotation However for the moment so as not to overwhelm you with complicated code we will rotate each individual picture with the following code fragment startMPdrawing numeric delta extra radius rot delta extra radius 0 for i 1 upto n rot i extratdelta pos i 5wid i len n 180 2delta endfor stopMPdrawing Preliminary Version October 27 2000 Byoestttiherin wereeoe Here we introduce a few variables that we can us
134. d flexible commands of CONTEXT is framed We can use the back ground features of this command to invoke and position graphics that adapt themselves to the current situation Once understood overlays will become a natural part of the CONTEXT users toolkit Overlays Many CONTEXT commands support overlays The term overlay is a bit confusing since such an overlay in most cases will lay under the text However because there can be many layers on top of each other the term suits its purpose When we want to put a METAPOST graphic under some text we go through a three step process First we define the graphic itself startuniqueMPgraphic demo circle path p p fullcircle xscaled overlaywidth yscaled overlayheight fill p withcolor 85white draw p withpen pencircle scaled 2pt withcolor 625red stopuniqueMPgraphic This graphic will adapt itself to the width and height of the overlay Both overlaywidth and overlayheight are macros that return a dimension followed by a space The next step is to register this graphic as an overlay defineoverlay demo circle uniqueMPgraphic demo circle We can now use this overlay in any command that provides the framed functionality Since this graphic is defined as unique CONTEXT will try to reuse already calculated and embedded graphics when possible framed background demo circle This text is overlayed The background can be set to color screen an overlay iden
135. d in CONTEXT and the METAPOST macros are bundled in MetaFun When Donald Knuth wrote his typographical programming language he was in need for fonts especially mathematical fonts So as a side track he started writing METAFONT a graphical language When you read between the lines in the METAFONT book and the source code the name John Hobby is mentioned alongside complicated formulas It will be no surprise then that since he was tightly involved in the development of METAFONT after a few years his mEraPosr showed up While its ancestor METAFONT was originally targeted at designing fonts METAPOST is more ori ented to drawing graphics as used in scientific publications Since METAFONT produced bitmap out put some of its operators make use of this fact METAPOST on the other hand produces POSTSCRIPT code which means that it has some features not present in METRFONT and vise versa With Met aFun I will demonstrate that METAPOST can also be used or misused for less technical drawing purposes We will see that METAPOST can fill in some gaps in especially its lack of graphic capabilities We will demonstrate that graphics can make a document more attractive even if it is processed in a batch processing system like TEX Most of all we will see that embedding METAPOST definitions in the TEK source enables a smooth communication between both programs The best starting point for using METAPOST is the manual written by its author Joh
136. d page cur rent page x coordinate y coordinate width height and depth The last six variables originate in the positioning mechanism Because the variables are only available after a second TEK pass we only draw a button shape when the test for the page numbers succeeds startuseMPgraphic rightsuperbutton vardef rightsuperbutton expr pat xpos ypos wid hei save p ptop pbot t b edge shift width height path p ptop pbot pair t b numeric edge shift width height edge xpos wid shift ypos hei p rightpath pat ptop infinity shift edge shift pbot infinity shift hei edge shift hei t p intersectionpoint ptop b p intersectionpoint pbot subpath 0 xpart p intersectiontimes ptop of p subpath xpart p intersectiontimes pbot length p of p p t point 1 of ptop amp point 1 of ptop point 1 of pbot amp point 1 of pbot b cycle enddef stopuseMPgraphic The calculation of the button itself comes down to a combining segments of the main shape and auxiliary lines The rightpath macro returns the right half of the path provided This half is shown as non dashed line Preliminary Version October 27 2000 Topics are identified with NTopic which isan instance of chapter headings The number is made invisible Since it still is a numbered section header CONTEXT will write the header to t
137. dam Preliminary Version October 27 2000 Preliminary Version October 27 2000 Index Concepts The main index will be prepared when the document is finished Commands The command index will be prepared when the document is finished Preliminary Version October 27 2000 m Ly Preliminary Version October 27 2000 To do real unfill support define some variables as internal breaks compatibility attributes to text along a path attributes to text shapes more positional things e g funny buttun style a few styles better equation explanation more auxiliary macros documenting metafun macros summary of commands check on completeness in covering commands text overlayed over mp hyperlinks and so expr a b c versus expr a b expr c shading etc in ps driver straight copy to file the logic behind grouping and global assignments 0 QQ and no in vardefs clearxy mpgraph or mp graph miterlimit dir angle counterclockwise turningnumber hide labeloffset interim labeloffset 0 joinup vardef newpath suffix path 5 enddef Qi Preliminary Version October 27 2000 Preliminary Version October 27 2000
138. ddef Preliminary Version October 27 2000 A few ZA Because this macro is defined global and therefore can be used apart from infont we predefine the size numeric lastfontsize lastfontsize fontsize defaultfont When defined this way at a comfortable 20 points the string Met aFun comes out as follows MetaFun Additional operators In this section we will introduce a few MetaFun operators like enlarged squeezed randomized xyscaled sized and superellipsed We can hardly cover them all since MetaFun is evolving Aew more details Preliminary Version October 27 2000 3 1 Embedded graphics In addition to the beginfig endfig method there are other ways to define and include META POST graphic Each method has its advantages and disadvantages In the previous chapter we were still assuming that the graphic was defined in its own file In this chapter we will introduce the interface between CONTEXT and METARPOST and demonstrate how the definitions of the graphics can be embedded in the document source Getting started From now on we will assume that you have CONTEXT running on your platform Since PDF has full graphics support we also assume that you use PDFTEX or know how to go from DVI to PDF Since this document is not meant as a CONTEXT tutorial we will limit this introduction to the basics needed to r
139. defines the following macros that way def curl 1 curl 1 enddef def tension infinity enddef def tension atleast 1 enddef These definitions also point out why you cannot add directives to the left or right side of and they are directives themselves Transformations A transform is a vector that is used in what is called an affine transformation To quote the METAPOST manual Tf p px py is a pair and is a transform then p transform T is a pair of the form ty tyx Px try Py ty fyx px tyy Dy where the six numeric quantities tx ty txx try tyx tyy determine In literature concerning POSTSCRIPT and PDF you will find many references to such transformation matrices A matrix of sx 0 0 sy 0 0 is scaling by s in the horizontal direction and s in the vertical direction while 1 0 tx 1 0 ty is a shift over Of course combinations are also possible Although these descriptions seem in conflict with each other in the nature and order of the transform components in the vectors the concepts are the same You normally populate transfor mation matrices using scaled shifted rotated A few more details Preliminary Version October 27 2000 transform t t identity shifted a b rotated c scaled path p p fullcircle transformed t The previous lines of code are equivalent to path p p
140. different viewpoints undertake their own experiments Douglas R Hostadter Donald Knuth has spent the past several years working on a system allowing him to control many aspects of the design of his books from the typesetting and layout down to the very shapes of the letters Seldom has an author had anything remotely like this power to control the final appearance of his or her work Knuth s x typesetting system has become well known and available in many countries around the world By contrast his werarowr system for designing families of typefaces has not become as well known or available In his article The Concept of a Meta Font Knuth sets forth for the first time the underlying philosophy of werarosr as well as some of its products Not only is the concept exiting and clearly well executed but in my opinion the article is charmingly written as well However my overall enthusiasm for Knuth s idea and article there are some points in it that I feel might be taken wrongly by many readers and since they are points that touch close to my deepest interests in artificial intelligence and esthetic theory I felt compelled to make some comments to clarify in artificial intelligence and esthetic theory 1 felt compelled to make some comments to clarify certain important issues raised by The Concept of a Meta Font certain important issues raised by Concept of a Meta Font even odd Figure 64 A background wit
141. different graphics a b and c because we want some to be unique which saves some processing Of course we don t reuse the random graphics In the definition of processword we have to use noindent because otherwise will put each graphic on a line of its own Watch the space at the end of the macro Graphics and macros Because TgX s typographic engine and metarost s graphic engine are separated interfacing be tween them is not as natural as you may expect In CONTEXT we have tried to integrate both as good as possible but using the interface is not always as convenient as it should be What method you follow depends on the problem at hand The official METAPOST way to embed TEK code into graphics is to use btex etex As soon as CONTEXT writes the graphic data to the intermediate METAPOST file it looks for these commands When it has encountered an et ex CONTEXT will make sure that the text that is to be typeset by TEK is not expanded This is what you may expect because when you would embed those commands in a stand along graphic they would also not be expanded if only because METAPOST does not know With expansion we mean that commands are replaced by their meaning which can be quite extensive When METAPOST sees an bt ex command it will consult a so called mpx file This file holds the METAPOST representation of the text typeset by TEK Before METRPOST processes a graphic definition file it first calls another p
142. dletokens 1 with processfollowingtoken startMPdrawing numeric al pl at wid pos pair ap ad al arclength RotPath pl al len n n 1 for i 1 upto n wid abs xpart lrcorner pic i xpart llcorner pic i pos len i wid 2 4 i 1 pl APOST Preliminary Version October 27 2000 at arctime pos of RotPath ap point at of RotPath ad direction at of RotPath draw pic i shifted wid 2 0 rotated angle ad shifted ap endfor stopMPdrawing MPdrawingdonetrue getMPdrawing resetMPdrawing egroup So how does this compare to earlier results The original full text as typeset by TEK looks like We now follow some arbitrary path In the examples the text is typeset along the path with followtokens We now follow some arbitrary path We now follow some arbitrary path Since we did not set a path a dummy path is used We can provide a path by re defining the graphic followtokens NstartuseMPgraphic followtokens path RotPath RotPath fullcircle stopuseMPgraphic mban Ua Ma NS E NstartuseMPgraphic followtokens path RotPath RotPath reverse fullcircle stopuseMPgraphic startuseMPgraphic followtokens path RotPath RotPath 3cm 1om stopuseMPgraphic 0 1cm 3cm 1em
143. down to inter polation between two or more points or user supplied ranges A poor mans way of doing this is to build the graphics piecewise with slightly changing colors But instead of manually stepping through the color values we can use the more efficient and generalized POSTSCRIPT level 2 and PDF level 1 3 shading feature circular 0 circular 1 circular 2 circular 3 circular 4 linear 0 linear 1 linear 2 linear 3 Because shading support is not built in METAPOST it has to be implemented using so called spe cials directives that end up in the output file Unfortunately these are not coupled to the specific path which means that we have to do a significant amount of internal bookkeeping Also in PDF we have to make sure that the graphics and their resources being the shading functions are packaged together Because of this implementation shading may behave somewhat unexpected at times A rather normal case is the next one where we place 5 shaded circles in a row path p p fullcircle scaled for i 0 step 2cm until 8cm circular_shade p shifted i 0 0 MPcolor a MPcolor b endfor Preliminary Version October 27 2000 At first sight in the next situation we would expect something similar because we simply copy the same circle 5 times However due to the way we have implemented shading in CONTEXT we do indeed copy the circles but the shade definition is frozen and the same o
144. e available after loading the metarost clipping library NuseMPlibrary clp We already saw how the circular clipping path was defined The diamond is defined in a similar way using the predefined path diamond Preliminary Version October 27 2000 startMPclip diamond clip currentpicture to unitdiamond xscaled width yscaled height stopMPclip The definition of the negated ellipse negellipse uses the primary peepholed This primary is defined in one of the METAPOST modules that come with CONTEXT startMPclip negellipse clip currentpicture to unitcircle peepholed unitsquare xscaled width yscaled height stopMPclip The definition of peepholed is rather dirty and using peepholed is restricted to well defined situations like here It s called a primary because it acts as an operator at the same level as and scaled urellipse ulellipse llellipse lrellipse ellipse negellipse tellipse bellipse lellipse rellipse urtriangle ultriangle lltriangle Irtriangle diamond negdiamond Figure 8 7 collection of predefined clipping paths 8 3 Patterns Like shades patterns can be implemented using specials Before I discuss this I first have to sort out how this can be implemented in a comfortable way 8 4 Fonts This section will demonstrate how we can manipulate fonts in METAPOST Don t expect too much from this section Preliminary Version October 27 2
145. e vec pat yscaled len rotatedaround origin ang shifted a enddef If you use vardef then the last statement is the return value Here whenp spring 21 22 75 2 10 is being parsed the macro is expanded the variables are kept invisible for the assignment and the path at the end is considered to be the return value In a def the whole body of the macro is pasted in the text while in a vardef only the last line is visible We will demonstrate this with a simple example 5 B p def one n n n n l enddef def two n n enddef Now when we say pair b numeric n n 10 a two we definitely get an error message This is because when macro two is expanded METAPOST sees something b n 1 By changing the second definition in vardef two n n 1 n n enddef the increment is expanded out of sight for b and the pair n n is returned We can draw a slightly better looking spring by drawing twice with a different pen The following commands use the spring macro implemented by the vardef path p p i 0 0 spring 5cm 0 2 5cm 0 5cm 0 10 3em 0 draw p withpen pencircle scaled 2pt draw p withpen pencircle scaled 1pt withcolor 8white This time we get Since the spring macro returns a path you can do whatever is possible with a path like drawing an arrow WW Prel
146. e 7 4 and are called up with the CONTEXT commands like symbol menu left If needed we can collect these button symbols in a so called symbol set which permits us to instantly switch between sets with similar symbols Preliminary Version October 27 2000 d gt E E l k v v E left right list index person stop info down up print Table 74 collection of button symbols Preliminary Version October 27 2000 8 1 Special effects Sometimes we want to go beyond METAPOSTS native features An example of such an extension is shading Although features like this should be used with care sometimes the documents look and feel can profit from it If you don t want the whole graphic but only a part of it clipping comes into play In addition to the standard clipping features we can use METAPOST to provide a decent clipping path In this chapter we will uncover the details Shading In this section we introduce different kind of shadings Since METAPOST does not support this feature directly we have to fall back on a few tricks For the moment shading is only supported in PDF In the following examples we will use the next three colors definecolor a darkyellow definecolor b s 8 definecolor c darkred A shade is a fill with a stepwise change in color In POSTSCRIPT level 2 the way this color changes can be circular linear
147. e a text picture we can explicitly ask for the transform components label rt xpart 6 decimal xpart p 4cm 1 25cm label rt ypart 6 decimal ypart p 4cm 0 75cm label rt xxpart amp decimal xxpart p 4cm 0 25cm label rt xypart amp decimal xypart p 4cm 0 25cm label rt yxpart amp decimal yxpart p 4cm 0 75cm label rt yypart amp decimal yypart p 4cm 1 25cm Preliminary Version October 27 2000 xpart 0 ypart 25 72203 uar xxpart 2 23206 0 13397 yxpart 1 yypart 1 73206 We will now define the inverted macro using these primitives Because we have to return a picture we cannot use draw and 111 but need to use the low level operators Because a picture can consist of more than one path we need a temporary picture pp vardef inverted expr p save pp picture pp pp nullpicture for i within p addto pp if stroked i or filled i if filled i contour else doublepath fi pathpart i dashed dashpart i withpen penpart i else also i fi withcolor white redpart i greenpart i bluepart i endfor enddef We probably need to handle a few more border cases but for general purposes this macro works as expected From the previous examples it may be clear that each picture has some associated data stored with it From the bounded boolean test we can deduce that the
148. e as pre organic If you use CONTEXT you can load this style with Nusemodule pre organic At the end of this file there is a small test file so when you process the file s pre 19 tex with and the options mode demo and you will get a demo document We use one of the standard screen paper sizes and map it onto the same size so that we get a nicely cropped page Other screen sizes are 54 and 55 setuppapersize S6 S6 Like in this Met aFun manual we use the Palatino as main bodyfont This font is quite readable on even low resolution screens although I admit that this style is developed using an 1400 x 1050 pixel LCD screen so the author may be a little biased setupbodyfont ppl The layout specification sets up a text area and a right edge area where the menus will go see chapter 6 for a more in depth discussion on the layout areas Watch how we use a rather large edge distance By setting the header and footer dimensions to zero we automatically get rid of page body ornaments like the page number This style is the 19 presentation style Those numbered styles are internally mapped onto more meaningful names like in this case pre organic Preliminary Version October 27 2000 setuplayout topspace 48pt backspace 48pt cutspace 12pt width 400pt margin 0ocm rightedge 88pt rightedgedistance 48pt header 0cm footer 0cm heig
149. e files In that case we give them names This time we should say t ypebuffer mfun to typeset the code verbatim Instead of TEK code we can put METAPOST definitions in buffers Buffers can be used to stepwise build graphic By putting code in multiple buffers you can selectively process this code startbuffer red drawoptions withcolor 625red stopbuffer startbuffer yellow drawoptions withcolor 625yellow stopbuffer We can now include the same graphic in two colors by simply using different buffers This time we use the special command processMPbuf fer since getbuf fer will typeset the code frag ment which is not what we want startlinecorrection blank processMPbuffer red graphic stoplinecorrection The line correction macros take care of proper spacing around the graphic The blank directive tells CONTEXT to add more space before and after the graphic Nstartlinecorrection blank processMPbuffer yellow graphic stoplinecorrection Which mechanism you use multiple buffers or re usable graphics depends on your prefer ences Buffers are slower but don t take memory while re usable graphics are stored in memory which means that they are accessed faster Preliminary Version October 27 2000 SEmbgdded graphics 259 Communicating color Now that color has moved to the desktop even simple documents have become more colorful so we need a way to
150. e later to tune the result a bit With delta the space between the characters can be increased while extra rotates the whole string around the origin The radius variable can be used to increase the distance to the origin Without these variables the assignment would have been rot i pos i t 5wid i len n 180 Placing the pictures is now rather easy startMPdrawing for i 1 upto n draw pic i shifted radius 0 rotatedaround origin rot i endfor stopMPdrawing The pictures are now positioned on half a circle properly kerned This was defined as follows The path variable t cycle is predefined to the top half of a fullcircle startMPdrawing def moved expr i shifted radius 0 rotatedaround origin rot i enddef pickup pencircle scaled 5pt for i l upto n draw pic i moved i draw boundingbox pic i moved i withcolor red draw origin center pic i moved i withcolor green endfor draw tcircle scaled 2r withcolor blue stopMPdrawing We will now package all of this into a nice efficient macro using of course the predefined scratch registers MPtoks and MPbox First we define the token processor Note again the expansion inhibition switch in Preliminary Version October 27 2000 def processrotationtoken 1 appendtoks 1 to MPtoks setbox MPbox hbox RotFont the MPtoks startMPdrawin
151. e modules are preloaded others can be loaded using the command useMP library like useMPlibrary clp txt for loading the predefined clipping paths and text tricks The METAPOST code is organized in files named mp mp The core file is mp tool mp and this file can comfortably be used in stand alone graphics The collection of METAPOST code files will grow in due time but as long as you use the MetaFun format you don t have to keep track of the organization of files Most files relate to subsystems and are loaded automatically like the files that implement page layout support and flow charts I will also add some information on how to generate documented sources Preliminary Version October 27 2000 MetaFun macros Preliminary Version October 27 2000 15 Example graphics In this chapter we will show some of the graphics that we made the last few years using METAPOST They give an impression of what kind of non mathematical drawings can be made Preliminary Version October 27 2000 Preliminary Version October 27 2000 2 Programs After a graphics is defined in the METAPOST language you have to compile it into a POSTSCRIPT graphic using METAPOST the program An additional next step is conversion into PDF In this chap ter we will discuss the programs involved in this process METRPOST Of course we
152. ea positioned at theright place the page itself Some less used and more obscure variables are the following numeric Hstep numeric Vstep numeric Hsize numeric Vsize the horizontal distance to the previous area the horizontal distance to the previous area the width of an area the height of an area The array variables are accessed by using constants horizontal LeftEdge LeftEdgeSeparator LeftMargin LeftMarginSeparator Text RightMarginSeparator RightMargin RightEdgeSeparator RightEdge vertical Top TopSeparator Header HeaderSeparator Text FooterSeparator Footer BottomSeparator Bottom In addition to these there are Margin InnerMargin and OuterMargin which adapt them selves to the current odd or even page The same is true for Edge Innerl Edge and Outer although these will seldom be used since interactive documents are always single sided We started this chapter with spending a lot of code to simulate the page areas It will be clear now that in practice this is much easier using the mechanism described here In figure 6 6 we see all used areas Areas that are not used are not drawn which saves some testing This background was defined as startuseMPgraphic page StartPage for i Top H for j Left eld i j withpen pencircle scaled 2pt withcolor draw Fi endfor endfor StopPage stopuseMPgraph ader Text Footer Bottom Edge LeftMargin Text RightMargin
153. ead of hard coding their corner points we use METRPOST s equation solver Watch the use of which means that we just state dependencies So where in languages like PERL the equal sign is used in assignments in METRPOST it is used to express an relationship loe AP Preliminary Version October 27 2000 In a first version we will just name a lot of simple relations as we can read them from a sketch drawn on paper 211 242 221 212 231 222 r 241 232 x12 x11 b y12 yll x22 x21 y22 y21 x32 x31 f y32 y31 42 41 h y42 y41 211 x11 11 712 x12 12 P 213 x12 b 12 214 xll b yllta 221 x21 21 22 x22 22 gt 223 x22 d 22 224 x21 d 21 231 x31 y31 732 x32 y32 E 233 x32 f y32te 234 x31 f y3lte 241 x41 41 42 x42 42 gt 243 x42 h 42 9 244 41 y41 9 The line that involve the pairs upto h can be written in a more compact way a b 212 z11 c d 222 221 z32 z31 g h z42 z41 Hh ll Now we can draw the lines but first we choose ourselves an acceptable line thickness pickup pencircle scaled 5pt The lines are draw with the following code draw zll z12 z13 z14 cycle draw 211 213 draw z12 z14 draw
154. ed draw p shifted 7cm 0 dashed withdots withcolor 625yellow Once we have drawn one or more paths we can store them in a picture variable The straightfor ward way to store a picture is to copy it from the current picture picture pic pic currentpicture The following command effectively clears the picture memory and allows us to start anew currentpicture nullpicture We can shift rotate and slant the picture stored in pic as we did with paths We can say draw pic rotated 45 withcolor red A picture can hold multiple paths You may compare a picture to grouping as provided by draw ing applications draw 0cm 0cm 1cm 1cm draw 1cm 0cm 0cm 1cm picture pic pic currentpicture draw pic shifted 3cm 0cm draw pic shifted pic currentpicture draw pic shifted Ocm 2cm We first draw two paths and store the resulting cross in a picture variable Then we draw this pic ture two times so that we now have three copies of the cross We store the accumulated drawing again so that after duplication we finally get six crosses NL NL NL ZN ZN NL NL NL 7 ZSN You can often follow several routes to reach the same solution Consider for instance the following graphic fill 0 0 ww 0 ww hh hh w h 0 cycle fill ww 0 w 0 w hh cycle Preliminary Version October 27 2000
155. ed 1mm Preliminary Version October 27 2000 As you can see the transformations are applied in series Sometimes this is not what we want in which case we can use parentheses to force the desired behaviour The lesson learned is that scaling and shifting is not always the same as shifting and scaling draw origin origin shifted 4cm 0cm shifted 4cm 0cm withpen pencircle scaled lcm withcolor 625white draw origin origin shifted 4cm 0cm shifted 4cm withpen pencircle scaled 8mm withcolor 625yellow draw origin origin shifted 4cm 0cm shifted 4cm 0cm withpen pencircle scaled 6mm withcolor 625red draw origin origin shifted 4cm 0cm shifted 4cm 0ocm withpen pencircle scaled 4mm withcolor white Especially when path results from a call to macro using parentheses around path may help as in the following example def unitslant origin origin shifted 1 1 enddef draw unitslant xscaled 5cm yscaled lcm withpen pencircle scaled lcm withcolor 625red draw unitslant xscaled 5cm yscaled 1cm withpen pencircle scaled 5mm withcolor 625yellow The next definition of unitslant is therefore better Preliminary Version October 27 2000 def unitslant origin origin shifted 1 1 enddef draw unitslant xscaled 5cm yscaled lcm withpen pencircle scaled 5mm withcolor 625red An even
156. eight strutdepth strutheight draw p withpen pencircle scaled 1 stopuseMPgraphic The third and fourth shape demonstrate that providing a suitable offset is not always trivial Melee Preliminary Version October 27 2000 startuseMPgraphic test 3 numeric h w h 6cm path p p 5w h 0 h 0 0 0 amp w 0 75w 5h w h amp w h cycle build parshape 0 0 baselinedistance strutheight strutdepth strutheight draw p withpen pencircle scaled 1 stopuseMPgraphic Contrary to the first third shapes here we use a different path for the calculations and the draw ing Watch carefully If instead of an offset we pass a path METAPOST is able to calculate the right dimensions and offsets This is needed since we need these later on startuseMPgraphic test 4 numeric w h o def shape 0 0 w o o amp w o o 75w o 5h w 20 h o 8 w 20 h o o h 0o cycl enddef w h 6cm o 6pt path p p shape w h 6cm o Opt path dj q shape build parshape p q 6pt baselinedistance strutheight strutdepth strutheight draw withpen pencircle scaled lpt stopuseMPgraphic Since we also want these graphics as backgrounds we define them as overlays If you don t want to show the graphic you may omit this step
157. elf you must make sure that the TEK environment of your document matches the one used by METAPOST Here we used startMPenvironment setupbodyfont loc mt ppl pcr 10pt definefont RotFont RegularBold stopMPenvironment We let the bodyfont match the font used in this document and define Rot Font to be the regular typeface the one you are reading right now but bold Since METAPOST is unaware of kerning we have to use TEK to keep track of the positions We will split the text into tokens often characters and store the result in an array of pictures pic We will also store the accumulated width in an array len The number of characters is stored in n Ina few paragraphs we will see why the other arrays are needed While defining the graphic we need TEK to do some calculations Therefore we will use startMP drawing to stepwise construct the definition The basic pattern we will follow is resetMPdrawing startMPdrawing metapost code stopMPdrawing tex code startMPdrawing metapost code stopMPdrawing MPdrawingdonetrue getMPdrawing In the process we will use a few variables We will store the individual characters of the text in the variable pic it s width in wid and the length of the string so far in len Later we will use the pos array to store the position where a character ends up The variable n holds the number of tokens resetMPdrawing startMPdrawing picture pic numeric wid len
158. ents pen pen specification You can achieve interesting effects by using pens with certain shapes For the moment you may consider a pen to be a path itself that is applied to the path that is drawn The numeric data type is used so often that it is the default type of any non declared variable This means that n 10 is the same as numeric n n 10 When writing collections of macros it makes sense to use the second method because you can never be sure if n isn t already declared as a picture variable and assigning a numeric to a picture variable is not permitted Preliminary Version October 27 2000 Welcome to 1 6 Because we often deal with collections of objects such asa series of points all variables can be organized in arrays For instance numeric n n 3 10 n 5 13 An array is a collection of variables of the same type that are assigned and accessed by indexing the variable name as in n 3 5 Multi dimensional arrays are also supported Since you need a bit of imagination to find an application for 5 dimensional arrays we restrict ourselves to a two dimensional example numeric n n 21 3 10 A nice feature is that the bounds of such an array an array need not be set beforehand This also means that each cell that you access is reported as unknown unless you have assigned it a value Conditions The existence of boolean varia
159. epen draw p Here we define a new pen using the pen command Then we define a path and make a pen out of it using the makepen macro The path should be a relatively simple one otherwise 5 will complain You can use makepen with the previously introduced withpen draw p withpen makepen 0 0 3cm 3cm and pickup pickup makepen 0 0 3cm 3cm draw p You can use makepen and makepath to convert paths into pens and vice versa Pens are very important when defining fonts which is why METAFONT was created Since META POST has a slightly different audience it lacks some features in this area but offers a few others instead Nevertheless one can try to design a font using METRPOST Of course pens are among the designers best kept secrets But even then not every O is a nice looking one 3 Preliminary Version October 27 2000 1 10 111 Colors So far we have seen some colors in graphics It must be said that METAPOST color model is not that advanced although playing with colors in the Metarost way can be fun In later chapters we will discuss some extensions that provide shading Colors are defined as vectors with three components a red green and blue one Like pens colors have their with command withcolor 4 5 6 You can define color variables like color darkred darkred 625 0 0 You can now use this color as withcolor darkred
160. er gt lt pagenumber gt lt x gt lt y gt lt width gt lt height gt lt depth gt The page number is needed in order to let the graphics engine determine boundary conditions Backgrounds like shown here can span multiple pages In order to calculate the right back grounds some additional information must be available like the top and bottom of the current text area In fact these are just normal points that can be saved while processing the split off page So apart from positioning anchors in the text we need anchors on crucial points of the layout This means that this kind of support cannot be fully integrated into the TEK kernel unless we also add extensive support for layout definitions and that is probably not what we want As soon as something x y shows up a logical question is where 0 0 is located Although this is a valid question the answer is less important than you may expect Even if we know that 0 0 is officially located in the bottom left corner of the page the simple fact that in CONTEXT we are dealing with a mixed page concept like paper size and print paper size or left and right pages forces us to think in relative positions instead of absolute ones Therefore graphics even those that involve multiple positions are anchored to a position on the layer on which they are located The MPanchor macro takes care of this Users who simply want to use these features may wonder why we go into so much detail The mai
161. eralization but we used it for demonstrating how to build graphics in a stepwise way If you put the steps in buffers you can even combine steps and replace them at will This is how we made the previous step by step examples We put each sub graphic in a buffer and then called the ones we wanted We now present a more general approach to typesetting along a given path This method is not only more robust and general it is also a more compact definition especially if we omit the tracing and testing code We use a familiar auxiliary definition The setstrut and strut commands ensure that the lines have the proper depth and height def processfollowingtoken 1 appendtoks 1 to MPtoks setbox MPbox hbox RotFont setstrut strut the MPtoks startMPdrawing 1 len n the wd MPbox stopMPdrawing startMPdrawing pic n btex RotFont setstrut strut l etex stopMPdrawing The definition of followtokens is as follows Keep in mind that RotFont is defined in the METRPOST environment You may notice that we have added a directive to include the META post graphic called followtokens Storing the path in a graphic container instead of using NstartMPdrawing is less sensitive for interference with other drawing processes def followtokens 1 vbox bgroup MPtoks emptytoks resetMPdrawing startMPdrawing includeMPgraphic followtokens picture pic numeric len n 0 stopMPdrawing han
162. ere Take for instance a so called super ellipse These graphics provide a lot of information In this picture the crosshair in the center is the origin and the dashed rectangle is the bounding box of the super ellipse The bounding box specifies the position of the graphic in relation to the origin as well as its width and height In the graphic on the right you can see the points that make up the closed path as well as the control points Each point has a number with the first point numbered zero Because the path is closed the first and last point coincide We ve used the commands and as path connecting directives In the next series of examples we will demonstrate a few more However before doing that we define a few points using the predefined z variables 20 0 5cm 1 5cm zl 2 5cm 2 5cm z2 6 5cm 0 5cm 23 2 5cm 1 5cm Here z1 is a short way of saying x1 x2 When a z variable is called the corresponding x and y variables are available too Later we will discuss METAPOST capability to deal with expressions which are expressed usin an instead of In this case the expression related to 20 is expanded into 20 0 0 0 5cm 1 5cm But let s for this moment forget about their expressive nature and simply see them as points which we will now connect by straight line segments METRROST Preliminary Version October 27 2000 22 23
163. ersion October 27 2000 ulcircle ulcircle D tcircle metafun variable tcircle D bcircle Icircle C rcircle V lltriangle 4 Irtriangle N Preliminary Version October 27 2000 metafun variable bcircle metafun variable lcircle metafun variable rcircle metafun variable lltriangle metafun variable lrtriangle metafun variable urtriangle urtriangle metafun variable VA ultriangle ultriangle metafun variable N flex pair pair pair flex 0 0 1 1 1 0 metapost macro Q superellipse pair pair pair pair numeric supereiiipse 1 5 5 1 0 5 5 0 75 metapost macro path superellipsed numeric unitsquare scaled 1 5 superellipsed 75 metafun macro path randomized numeric pair unitsquare scaled 1 5 randomized 2 2 metafun macro Preliminary Version October 27 2000 path squeezed numeric pair L1 Transformations D i ES un 5 G z zi n lt P 3 5 s ONE V NJ N 5 B 2 3 3 o a D J Q N E N un gt Preliminary Version October 27 2000 unitsquare scaled 1 5 squeezed 2 1 metafun macro fullcircle scaled 25 metapost primitive fullcircle xscaled 25 metapost primitive fullcircle yscaled 25 metapost primitive
164. et obscured by this fact Therefore the following series of shapes appear to be the same draw unitsquare xscaled 6cm yscaled 1 5cm withpen pencircle scaled 2mm withcolor 625red draw unitsquare shifted 5 5 xscaled 6cm yscaled 1 5cm withpen pencircle scaled 2mm withcolor 625red draw unitsquare shifted 5 5 xscaled 6cm yscaled 1 5cm withpen pencircle scaled 2mm withcolor 625red Preliminary Version October 27 2000 A few draw unitsquare xscaled 6cm yscaled 1 5cm shifted 1 withpen pencircle scaled 2mm withcolor 625red draw unitsquare xscaled 6cm yscaled 1 5cm shifted 1 5cm 1cm withpen pencircle scaled 2mm withcolor 625red However when we combine such graphics into one we will see in what respect the scaling and shifting actually takes place draw unitsquare xscaled 6cm yscaled 2cm withpen pencircle scaled 3 0mm withcolor 625yellow draw unitsquare shifted 5 5 xscaled 6cm yscaled 2cm withpen pencircle scaled 3 0mm withcolor 625red draw unitsquare xscaled 6cm yscaled 2cm shifted 1cm locom withpen pencircle scaled 3 0mm withcolor 625white draw unitsquare xscaled 6cm yscaled 2cm shifted 1 5cm 1cm withpen pencircle scaled 1 5mm withcolor white draw unitsquare shifted 5 5 xscaled 6cm yscaled 2cm withpen pencircle scaled 1mm withcolor black draw origin withpen pencircle scal
165. ext 1 2 startuseMPgraphic RotatedText draw btex 2 etex rotated 1 stopuseMPgraphic useMPgraphic RotatedText This macro takes two arguments the identifies an argument RotatedText 15 Some Rotated Text The text is rotated over 15 degrees counter clockwise In CONTEXT we seldom pass settings like the angle of rotation in this way The next alternative is therefore better def RotatedText 41 422 setupMPvariables RotatedText rotation 90 1 startuseMPgraphic RotatedText draw btex 2 etex rotated MPvar rotation stopuseMPgraphic useMPgraphic RotatedText We now need to pass the angle as a key value pair RotatedText rotation 15 Some Rotated Text The rotated text becomes Sog e Rotated Text In this case the graphic is rather simple but when a large graphic is used it makes sense to keep its definition outside the macro In order to do so we need a way to pass the argument to the graphic def RotatedText 41 2 setupMPvariables RotatedText 1 setMPtext RotatedText 2 useMPgraphic RotatedText setupMPvariables RotatedText rotation 90 startuseMPgraphic RotatedText draw MPbetex RotatedText rotated MPvar rotation stopuseMPgraphic You may wonder why we don t use the variable mechanism here The main reason is that the text mechanism offers a few more features one of which is that is passes the text straight on without the danger of
166. ext cutoff includeMPgraphic text draw includeMPgraphic text calc includeMPgraphic text loop includeMPgraphic text save enddef stopuseMPgraphic We have to adapt the for loop to register the information about the lines After the loop we write those values to a file using another loop startuseMPgraphic text loop path line pair lll rrr numeric vvsize n 0 if strutheight strutdepth lt baselineskip vvsize vsize else vvsize vsize div baselineskip baselineskip fT for i topskip step baselineskip until vvsize line ulcorner urcorner shifted 0 i Preliminary Version October 27 2000 lll found point line l true rrr found point line r false 1 indent n abs xpart lll xpart llcorner q width n abs xpart rrr xpart 111 endfor stopuseMPgraphic startuseMPgraphic text save write parshape amp decimal n to data_file for i l upto n write decimal indent i amp bp 6 decimal width i amp bp to data file endfor stopuseMPgraphic We can call this macro using the part we used in the previous examples startuseMPgraphic text includeMPgraphic text macro path p p 0 1 1 0 1 0 cycle scaled 65pt provide parshape 5 Nbaselinedistance baselinedistance strutheight strutdepth strutheight stopuseMP
167. f Clip paths and bounding boxes are kind of special in the sense that they can obscure components The following examples demonstrate this In case of a clip path or bounding box the pathpart operator returns this path In any case that asking for a value does not make sense a clipping path for instance has no color a zero null value is returned draw fullcircle withpen pencircle scaled 3mm clip currentpicture to fullcircle setbounds currentpicture to fullcircle n 1 length 1 stroked false clipped true bounded false draw fullcircle withpen pencircle scaled 3mm setbounds currentpicture to fullcircle clip currentpicture to fullcircle n 1 length 1 stroked false clipped false bounded true clip currentpicture to fullcircle draw fullcircle withpen pencircle scaled 3mm setbounds currentpicture to fullcircle 1 length 0 stroked false clipped true bounded false n 2 length 1 stroked true clipped false bounded false clip currentpicture to fullcircle setbounds currentpicture to fullcircle draw fullcircle withpen pencircle scaled 3mm 1 length 1 stroked false clipped false bounded true n 2 length 1 stroked true clipped false bounded false setbounds currentpicture to fullcircle clip currentpicture to fullcircle draw fullcircle withpen pen
168. fa point length a of aj endofb point length b of b if round point 0 of a round point 0 of b common point 0 of else common a intersectionpoint fX x where turningnumber common ndofa ndofb cycle curve unitvector endofa common endofa common rotated where 90 unitvector endofb common scaled anglelength shifted common draw thefreelabel str point 5 of curve common withcolor black A few applications Preliminary Version October 27 2000 curve enddef This macro has a few more i s than its predecessor First we test if the label is a string and if so we calculate the picture ourselves otherwise we leave this to the user path f f origin 2cm lcm b origin lem 2cm C origin 2cm 2cm d origin 2cm 1cm e origin 1cm 2cm f origin 1cm 2cm for i a b drawarrow i endfor anglelength 1 0cm drawoptions withcolor 625red drawarrow anglebetween a b btex alpha etex drawarrow anglebetween c d btex gamma 6 etex drawarrow anglebetween e f btex Nepsilon etex anglelength 1 5cm drawoptions withcolor 625yellow drawdblarrow anglebetween b c btex beta etex drawarrow reverse anglebetween d e btex delta 5 etex drawarrow anglebetween a f btex zeta etex Because anglebetween returns a
169. for currentpicture currentpicture xsized size enddef Since we don t want to duplicate a graphic this time we show the dark alternatives colorcircle 4cm 5red 5green 5blue This kind of unsafe path calculations are very sensitive to breaking Changing the radius 4 into something else demonstrates this but we will not challenge this macro that much Therefore the 50 color circle shows up as This command is part of MetaFun and can be used to determine nice color combinations by also looking at their complementary colors colorcircle 4cm 7red 5green 3blue Preliminary Version October 27 2000 The next circle that we draw shows the three main colors used in this document This circle is not that beautiful colorcircle 4cm 625red 625yellow 625white This definition can be cleaned up a bit by using t rans form but the fuzzy buildcycle s remain vardef colorcircle expr size red green blue save r g b rr gg bb cc mm yy save radius path r g b rr bb gg cc mm yy numeric radius radius 5cm pickup pencircle scaled radius 25 transform t t identity rotatedaround origin 120 r fullcircle scaled radius shifted 0 radius 4 rotatedaround origin 15 g r transformed t b transformed t rotatedaround center r 90 g rotatedaround center g 90 gg buildcy
170. g 1 len n the wd MPbox stopMPdrawing startMPdrawing pic n btex RotFont 1 etex stopMPdrawing The main macro is a bit more complicated but by using a few scratch numerics we can keep it readable def rotatetokens 1 2 3 4 3 delta extra radius tokens vbox bgroup MPtoks emptytoks resetMPdrawing startMPdrawing picture pic numeric wid len rot numeric delta extra radius n r len 0 n 0 delta 1 extra 2 radius 3 stopMPdrawing handletokens 4 with processrotationtoken startMPdrawing r len n Pi for i 1 upto n wid abs xpart lrcorner pic i xpart llcorner pic il rot extra delta len i 5wid len n 180 2delta draw pic i rotatedaround origin 270 shifted r radius ypart 5 ulcorner pic i llcorner pic i rotatedaround origin rot endfor stopMPdrawing MPdrawingdonetrue getMPdrawing resetMPdrawing egroup We can use this macro as follows Nstartcombination 3 1 Nrotatetokens 0 0 0 Does it work ok rotatetokens 20 0 0 Does it work ok B Preliminary Version October 27 2000 _ Typesetting in METARDET rotatetokens 20 30 0 Does it work ok C stopcombination work xt Wo v E Worg 2 a 40 5 C The previous macro is not really an example of gen
171. ge that you need additional runs If you generate the graphics at run time you should consider to turn on graphic slot recycling which means that you often end up with fewer intermediate files recycleMPslotstrue There are a few more low level switches and features but these go beyond the purpose of this manual Some of these features like the option to add tokens to everyMPgraphic are for experts only and fooling around with them can interfere with existing features One page graphics Although all of what is demonstrated in this document is done in CONTEKT some of the features discussed here can also be done in plain In the Met aFun distribution there is a file called plainfun tex which loads the appropriate CONTEXT modules Many low level macros are rather generic and can be used in plain TEK without problems However the big advantage of using CONTEXT is that graphics can be part of the text flow and that you can put them on layers If you don t want this and only want to make stand alone graphics you may still consider using CONTEXT for that purpose Another advantage is that when using CONTEXT you don t have to bother about specials font inclusion and all those nasty things that can spoil a good day An example of such a graphic is the file n un 888 that resides on the computer of the author 9 output pdftex setupcolors state start Embedied graphite Preliminary Version
172. graphic o9 099 oe shape path offset distance between lines height of a line depth of a line height of first line After we called NuseMPgraphic text the resulting file looks as follows You can call up this file by its anonymous name MPdatafile since this macro gets the value of the graphic at hand parshape 8 20 52388bp 47 26309bp 16 02335bp 55 46606bp 5 80312bp 78 9083bp 1 01128bp 96 9222bp 2 63644bp 108 51901 8 43073bp 101 52484bp 19 31705bp 79 75218bp 19 31705bp 79 75218bp So reading in this file at the start of a paragraph will setup TEK to follow this shape The final implementation is a bit more complicated since it takes care of paths that are not centered around the origin and don t start at the top point We achieve this by moving the path to the center Preliminary Version October 27 2000 EE IIR cp center p q p shifted The arbitrary starting point is taken care of by a slightly more complicated path cutter First we make sure that the path runs counterclockwise if xpart directionpoint t of q lt 0 q reverse fi Knowing this we can split the path in two using a slightly different splitter cutbefore t if xpart point 0 of q lt 0 amp q fi cutafter b cutbefore b Q if xpart point 0 of gt 0 amp q i cutafter t As always when implementing a feature
173. ground state to repeat and note the difference as you click pages with the mouse Setting the state was not needed when we used the page background setupbackgrounds page background nextpage Page backgrounds Preliminary Version October 27 2000 6 4 The Ndorecurse macro is handy for testing since it saves us typing One can nest this macro as in dorecurse 20 dorecurse 10 Hello World par The current step is available in recurselevel and the depth nesting level recursedepth Crossing borders In many cases the previously mentioned background areas will suffice but in the case of more complicated backgrounds you may wish to use METAPOST to draw graphics that combine or span these areas At runtime CONTEXT saves information on the layout that can be picked up by metarost The framework for a page graphic is StartPage all kind of commands StopPage Between the StartPage and StopPage command you have access to a wide range of variables page PaperHeight PaperWidth PrintPaperHeight PrintPaperWidth PageOffset PageDepth margins TopSpace BackSpace text MakeupHeight MakeupWidth vertical TopHeight TopDistance HeaderHeight HeaderDistance TextHeight FooterDistance FooterHeight BottomDistance BottomHeight horizontal LeftEdgeWidth LeftEdgeDistance LeftMarginWidth LeftMarginDistance TextWidth RightMarginDistance RightMarginWidth
174. h enlarged text area ulcorner Field Text Text urcorner Field OuterMargin Text cycle else Main llcorner Field OuterMargin Text lrcorner Field Text Text urcorner Field Text Text ulcorner Field OuterMargin Text cycle fi Main Main enlarged 6pt pickup pencircle scaled 2pt fill Page withcolor 625white fill Main withcolor 850white draw Main withcolor 625red StopPage stopuseMPgraphic In this definition we calculate a different path for odd and even pages When done we enlarge the path a bit If you want to use different offsets in all directions you can use moved corner points startuseMPgraphic page StartPage def somewhere uniformdeviate lcm uniformdeviate 1cm enddef path Main Main Field Text Text lrmoved somewhere Preliminary Version October 27 2000 Field Text Text Field Text Text Field Text Text pickup pencircle scaled 2pt fij fil draw Main withcolor l u u Page withcolor Main withcolor 625red StopPage stopuseMPgraphic 625white 850white lmoved somewhere lmoved somewhere rmoved somewhere cycle 4 rd Here we displace the corners randomly which leads to backgrounds like figure 6 5 The following definition would have worked as well startuseMPgraphic page StartPage path Main Main Field Text Text rando
175. h s book on algorithms and datastructures the for loop is the natural companion to an array Given an array of length n you can construct a path out of the points that make up the array draw for i 0 step 1 until n 1 p i endfor pin If the step increment is not explicitly stated it has an assumed value of 1 We can shorten the previous loop construct as follows draw for i 0 upto n 1 p i endfor pin After seeing if in action the following for loop will be no surprise draw origin for i 0 step 10 until 100 down 1i 0 endfor This gives the zig zag curve You can use a loop to iterate over a list of objects simple 3 step iteration is for i p q r fill i withcolor 8white draw i withcolor red endfor Using or in this manner can sometimes save a bit of typing The list can contain any expression and they may be of different types In the previous example the i is an independent variable local to the for loop If you want to change the loop variable itself you need to use forsuffixes In the next loop the paths p q and r are all shifted forsuffixes i i shifted 3cm 2cm endfor Sometimes you may want to loop forever until a specific condition occurs For this METAPOST provides a special looping mechanism numeric done i j n n 0 forever i round uniformdeviate 10 j round uniformdeviate 2 if unknown done i jl
176. hcolor c enddef We can draw three curved paths sample 21 curl 0 z2 curl 0 23 625red sample 21 curl 2 z2 curl 2 z3 625yellow sample 21 curl 1 z2 curl 1 z3 625white These third gray curve is the default situation so here we could have left the cur1 specifier out of the expression The curly specs have a lower bound of zero and no upper bound When we use METAPOST maxi mum value of infinity instead of 2 we get These curves were defined as sample 21 curl OF xus 22 curl 0 z3 625red sample 21 curl infinity z2 curl infinity 23 625yellow sample zl curl 13 5 22 curl 1 z3 625white It may sound strange but internally METAPOST can handle larger values than infinity sample 21 curl infinit sample 21 curl 4infinit sample 21 curl 8infinit Preliminary Version October 27 2000 y 22 curl infinity 23 625red yl 22 curl 4infinity 23 625yellow yl 22 curl 8infinity 23 625white 2 7 Although this is quite certainly undefined behaviour interesting effects be achieved When you turn off METAPOST S first stage overflow catcher you can go upto 8 times infinity which being some 32K is still far from what everyday s infinity is supposed to be QU With as built in METAPOST command that accepts curl and tension directive as described in this section you will now probably understand why plain METAPOST
177. he table of contents Ndefinehead Topic chapter setuphead Topic number no We will use a bold font in the table of contents We also force a complete list setuplist Topic criterium all style bold before after The TitlePage macro looks horrible because we want to keep the interface simple a list of small sentences separated by def TitlePage 1 startstandardmakeup switchtobodyfont big def vfill bfb let par bfd setupinterlinespace gray vskip 5cm 1 vskip 5cm NN is really needed stopstandardmakeup An presentation that uses this style may look like the one below You can choose among three alternatives useenvironment pre organic setupoutput pdftex setupMPvariables page alternative 1 starttext TitlePage A Few Nice Quotes A Simple Style Demo Hans Hagen August 2000 Topic Rudolf D Hofstadter input douglas page Topic Donald E Knuth input knuth page Topic Edward R Tufte input tufte page Topic Hermann Zapf input zapf page stoptext We will not implement the two other alternative shapes squeezed and randomized Defining styles Preliminary Version October 27 2000 Rudolf D Hofstadter page 1 page 2 page 3 page 4 page 5 Rudolf D Hofstadter page 1 page 2 page 3 page 4 page 5 We combine all alternatives into one page graphic The alternative
178. he direction ofa path from the way the points are numbered but using an arrow to indicate the direction is more clear path p p fullcircle xscaled 4cm yscaled 3cm drawarrowpath p drawcontrollines p drawpoints p drawcontrolpoints p drawpointlabels p Preliminary Version October 27 2000 The drawarrowpath is responsible for the arrow Especially when you are in the process of defining macros that have to calculate intersections or take subpaths knowing the direction may be of help AUN la 840 NG I The next table summarizes the special drawing commands drawpath the path drawarrowpath the direction of the path drawcontrollines thelines to the control points drawpoints the points that make up the path drawcontrolpoints the control points of the points drawpointlabels the numbers of the points You can set the characteristics of these like you set drawoptions The default settings are as follows drawpathoptions withpen pencircle scaled 5 withcolor 8white Scaled 4 withcolor black drawpointoptions withpen pencircl Scaled 2 5 withcolor black 000 drawlineoptions withpen pencircle scaled 1 withcolor 5white drawcontroloptions withpen pencircl drawlabeloptions Two more options are draworiginoptions and drawboundoptions which are used when visualizing
179. height span drift d cp height 3 5 baselinedistance span 1 3 height drift 1 10 height pickup pencircle scaled 1 12 height def d uniformdeviate drift enddef for i 1 upto MPvar n draw if i mod 5 0 d 4 5span d d 0 5span height d else d d d height d fi shifted span i d drift endfor picture cp cp currentpicture for readability setbounds currentpicture to llcorner cp shifted 0 ypart llcorner cp lrcorner cp shifted 0 ypart lrcorner cp urcorner cp ulcorner cp cycle endgroup stopuseMPgraphic The core of the macro is the for loop Within this loop we draw groups of four plus one lines The draw path s look a bit complicated but this has to do with the fact that a mod returns 0 4 while we like to deal with 1 5 The height adapts itself to the height of the line The bounding box correction at the end ensures that the baseline is consistent and that the random vertical offsets fall below the baseline Because we want to be sure that n has a value we preset it by saying se Preliminary Version October 27 2000 tupMPvariables fuzzycount n 10 In the table it makes sense to adapt the drawing to the lineheight but a more general solution is to adapt the height to the fontsize height 3 4 Nthe bodyfontsize currentf
180. hsiz the hsize vstep the lineheight xmax hsize div 5span pickup pencircle scaled 1 12 height def d uniformdeviate drift enddef for i 1 upto MMPvar n xpos i 1 mod 5 xmax span ypos i 1 div 5 xmax vstep draw Preliminary Version October 27 2000 A 74 if i mod 5 0 d 4 5span d d 0 5span height d else fi shifted xpos ypos d drift endfor picture cp cp currentpicture if ypart ulcorner cp ypart llcorner cp lt vstep setbounds currentpicture to llcorner cp shifted 0 ypart llcorner cp lrcorner cp shifted 0 ypart lrcorner cp urcorner cp ulcorner cp cycle fi endgroup stopuseMPgraphic Graphic variables In the previous sections we have seen that we can pass information to the graphic by means of variables How exactly does this mechanism work To do an explanation of the mechanism to pass variables Shape libraries Unfortunately it takes some effort to define graphics attach them to an overlay and invoke the background However the good news is that since in many cases we want a consistent layout we only have to do it once The next table has some hashed backgrounds More information about how to define tables can be found in the CONTEXT documentation and Up To Date documents
181. ht middle We use a moderate about a line height inter paragraph white space setupwhitespace big Of course we use colors since on computer displays they come for free setupcolors state start definecolor red r 75 definecolor yellow r 75 g 75 definecolor gray s 50 definecolor white s 85 Because it is an interactive document we have to enable hyperlinks and alike However in this style we disable the viewer s highlight a hyperlink when it s clicked on feature We will use menu so we enable menus Later we will see the contract color hyperlinks gets that color when we are already on the location in action setupinteraction state start click off color red contrastcolor gray menu on The menu itself is set up as follows Because we will calculate menu buttons based on their position on the page we have to keep track of the positions Therefore we set the position variable to yes setupinteractionmenu right frame off position yes align middle topoffset 75cm bottomoffset 75ocm color gray contrastcolor gray Preliminary Version October 27 2000 style bold before after The menu content is rather sober just a list of topics and a close button Later we will define the command that generates topic entries The alternative right lets the topic list inherit its characteristics from the menu startinte
182. icture da ta structure We explicitly have to set this picture to nothing using the built in primitive nullpicture Later on we will add the drawn paths as accumulated in currentpicture to this finalpicture the following manner addto finalpicture also currentpicture shifted n 3cm 0 Since we want to add a few more and don t want them to overlap we shift them Therefore we have to erase the current picture as well as increment the shift counter currentpicture nullpicture n ntl The drawfill macro is one of the MetaFun macros Another handy macro is boundingbox When used instead of bbox you don t have to set the margin to zero Figure 2 2 The influence of pens on fill There is a subtle point in filling a shape In figure 2 2 you see the influence of the pen on a i11 operation An indirect specification has no influence and results in a filled rectangle with sharp corners The third rectangle is drawn with a direct pen specification which results in a larger shape with rounds corners However the bounding box is the same in all three cases The graphic is defined as follows This time we don t use a complicated macro drawoptions withcolor 625white path p p unitsquare scaled 2cm fill p shifted 3cm 0 pickup pencircle scaled 5cm fill p shifted 6cm 0 fill p shifted 9cm 0 withpen pencircle scaled 5cm Units Like METAPOST supports multiple units of length In
183. ill see how the whole curve is constructed from these quadruples of points The process comes down to connecting the mid points of the straight lines connecting the points mentioned We do this three times which is why these curves have are classified as third order approximations The first series of graphics demonstrates the process of determining the mid points The third order midpoint is positioned on the final curve The second series focuses on the results new sets of four points that will be used in a next stage The last series only shows the third order midpoints As you can see after some six iterations we have already reached a rather good fit of the final curve The exact number of interactions depends on the resolution needed You will notice that the construction speed density differs per segment Just in case you are interested how such graphical simulations can be organized we show the simplified code We loop over all segments of the curve where for each segment the left and right side sub curves are handled recursive upto the requested depth here n vardef dodrawmidpoints expr a b d save e f g i j paire f g h i j i Slab E r amp 5 b c p g r 5 c d 5 etf v9 5 fdl Jj t 5 h i j draw j f n dodrawmidpoints a e h j n 1 dodrawmidpoints j i g d n 1 fT enddef vardef drawmidpoints expr p n save d pair b c
184. iminary Version October 27 2000 A feWapplications_ 15 2 Or even watch how we use the neutral unit u to specify the dimensions v 7 This was as drawarrow 0 0 spring 5cm 0 2 5cm 0 5cm 0 10 3em 0 withpen pencircle scaled 2pt withcolor 625red and numeric u u 1mm pickup pencircle scaled u 2 drawoptions withcolor 625red draw 0 0 spring 5u 0 250 0 5 0 10 300 0 drawoptions dashed evenly withcolor 5white draw 0 0 spring 5u 0 35u 0 25 35 5u 0 10 40u 0 Free labels The METAPOST label macro enables you to position text at certain points This macro is kind of special since it also enables you to influence the positioning For that purpose it uses a special kind of syntax which we will not discuss here in detail pickup pencircle scaled 1mm path p p fullcircle scaled 3cm draw p withcolor 625yellow dotlabel rt right point 0 of p dotlabel urt upper right point 1 of p dotlabel top top point 2 of p dotlabel ulft upper left point 3 of p dotlabel lft left point 4 of p dotlabel llft lower left point 5 of p dotlabel bot bottom point 6 of p dotlabel lrt lower right point 7 of p label command just typesets a text while dot Label also draws a dot at the position
185. imum dimensions of a graphic are specified by its bounding box A bounding box is defined by its lower left and upper right corners If you open the POSTSCRIPT file produced by METAPOST you may find lines like 5BoundingBox 46 46 46 46 or when supported sHiResBoundingBox 45 35432 45 35432 45 35432 45 35432 The first two numbers define the lower left corner and the last two numbers the upper right corner From these values you can calculate the width and height of the graphic A graphic may extend beyond its bounding box It depends on the application that uses the graphic if that part of the graphic is shown In METAPOST you can ask for the all four points of the bounding box of a path or picture as well as the center llcorner p lower left corner lrcorner p lower right corner urcorner p upper right corner ulcorner p upper left corner center p the center point You can construct the bounding box of path p out of the four points mentioned llcorner p lrcorner p urcorner p ulcorner p cycl You can set the bounding box of a picture which can be handy if you want to build a picture in steps and show the intermediate results using the same dimensions as the final picture or when you want to show only a small piece fill fullcircle scaled 2cm withcolor 625yellow setbounds currentpicture to unitsquare scaled lcm draw unitsquare scaled lcm withcolor 625red Here we set the bound
186. in WEB2C looks like pdftex ini mptopdf Since this conversion only works with or its amp alternative the session is aborted when another is used When finished the resulting fmt file should be moved to the right location When is properly set up you can also use this PERL script to handle the generation of the format and move texexec mak alon tex pdftex format mptopdf The conversion itself is accomplished by pdftex amp mptopdf relax filename number The 1 is needed since we don t want to process the file directly Instead we pick up the filename using Neverypar Because this file is still the first one we load although delayed the jobname is as we expect So at least in WEB2C the result of the conversion comes available in the file ilename pdf This conversion process is roughly compatible with texexec pdf fig c result filename filename number This uses CONTEXT and is therefore slower but fortunately there is a small PERL script that does a faster job using the minimal format Given that the previously mentioned format is generated you can say mptopdf somefile mptopdf somefile 123 mptopdf mp The results are copied into files named somefile number This mechanism will also be avail able in a next release of TEXUTIL a file manipulation script that comes with CONTEXT Since ACROBAT has troubles with figures smaller than 1 inch we issue a warn
187. in the mEraPosr manual The represents means and the symbol stands for or The diagrams describe the hard coded METAPOST syntax as well as most of the macros and variables defined in the plain METAPOST format that belong to the core of the system They also include some of the more fundamental Met aFun commands atom variable argument number or fraction internal variable expression begingroup statementlist expression endgroup nullary op btex typesetting command etex pseudo function primary atom numeric expression numeric expression numeric expression numeric expression numeric expression of operator expression of primary of operator expression along primary ofoperator expression on primary unary op primary str suffix z suffix numeric atom expression expression scalar multiplication op primary secondary primary secondary primary binop primary secondary transformer tertiary secondary tertiary secondary binop secondary Preliminary Version October 27 2000 METAPOS subexpression tertiary path expression pathjoin path knot expression subexpression expression tertiary binop tertiary path subexpression direction specifier path subex
188. ince these pictures are filtered from the source and processed we cannot embed the btex etex in the macro do it and pass a string It has to be done this way def do it expr yy tt path p p unitsquare xyscaled w 1 h yy shifted x 1 ylyyl label lft tt center p shifted w 1 2 u 25cm 0 enddef do it 1 btex bottom etex do it 2 btex footer etex do it 3 btex text tex do it 4 btex header etex do it 5 btex top etex In the horizontal direction we have edges margins and text There are left and right edges and margins which are swapped on even pages when you typeset a double sided document def do it expr xx tt path p p unitsquare xyscaled w xx h 1 shifted 1 label tt center p shifted 0 height h 1 2 enddef do it 1 btex edg tex do it 2 btex margin etex do it 3 btex text tex do it 4 btex margin etex do it 5 btex edg tex Since we want the graphic to match the dimensions of the text area of the current page we have to make sure that the bounding box is adapted accordingly By this action the labels will fall outside the bounding box When we directly embed a graphic this works ok but when we start scaling and reusing due to the object reuse mechanism the graphic will be clipped to the bounding box setbounds currentpicture to unitsquare xyscaled width height In the following sections we will demo
189. inecorrection Here a few layout thingies follow Preliminary Version October 27 2000 Preliminary Version October 27 2000 D Reference In this chapter we will demonstrate most of the drawing related primitives and macros as present in plain METAPOST and the CONTEXT extensions If a path is shown and or a transformation is applied we show the original in red and the transformed path or point in yellow The small dark gray crosshair is the origin and the black rectangle the bounding box In some drawings in light gray we show the points that makeup the path Thist list is still incomplete and needs to be checked against the formal syntax diagrams EXT Paths pair 1 5 metapost concept pair pair 0 0 75 0 1 25 1 1 metapost macro 0 0 5 5 7540 c Ly c25 s CLE metapost macro pair pair 0 0 75 0 1 25 1 1 metapost macro Preliminary Version October 27 2000 pair pair S C pair softjoin pair L controls pair E controls pair and pair tension numeric 07 0 75 0 77 1 525 1 1 metapost macro 0 0 75 0 Soft Join 1 25 1 1 metapost macro 0 0 controls 75 0 1 1 metapost primitive 0 0 controls 75 0 and 1 25 1 1 metapost primitive 0 0 75 0 tension 2 5 1 25 1 1 metapost primitive Preliminary Versi
190. ing When em bedding graphics in documents a size less that 1 inch does not harm In order to overload runtime directives in the configuration file we set the offsets and output method in the macro The resulting PDF file is about as efficient as such a self contained file can be However if needed this PDF file can be converted to EPS using for instance the pdftops program in WEB2C or GHOSTSCRIPT Test case If you want to test of your installation is working properly you may construct a file called test tex that contains the following lines starttext setupcolors state start startMPpage colorcircle 10cm red green blue Preliminary Version October 27 2000 stopMPpage stoptext Given that you have PDFIEX TEXEXEC and CONTEXT installed you can now say texexec pdf test When processing is finished there should be a file test pdf that contains a graphic that shows the color circles defined in a previous chapter Preliminary Version October 27 2000 B METAPOST syntax In the METAFONT book as well as the manual you can find the exact specification of the language Below you find the full wEraPosr syntax to which we add the basic Met aFun extensions If this page looks too cryptic you can safely skip to the next chapter B Syntax diagrams The following syntax diagrams are derived from the diagrams
191. ing box with the command setbounds which takes a path TABORI Preliminary Version October 27 2000 1 15 raphic extends beyond the bounding box but the bounding box determines the placement nd therefore the spacing around the graphic We can get rid of the artwork outside the bounding box by clipping it fill fullcircle scaled 2cm withcolor 625yellow clip currentpicture to unitsquare scaled 1cm The resulting picture is just as large but shows less of the picture Cutting and pasting When enhancing or building a graphic often parts of already constructed paths are needed The subpath cutbefore and cutafter operators can be used to split paths in smaller pieces In order to do so we must know where we are on the path that is involved For this we use points on the path Unfortunately we can only use these points when we know where they are located In this section we will combine some techniques discussed in previous sections We will define a few macros manipulate some paths and draw curves and points e 2 e 3 1 4 8 5 7 6 e This circle is drawn by scaling the predefined path fullcircle This path is constructed using 8 points As you can see these points are not distributed equally along the path In the following graphic the second and third point of the curve are colored red and point 2 5 is colored yellow Point 0 is marked in black This point is posi
192. ining the graphics in a separate METAPOST file we will incorporate them in the document source in which they are used We can use several methods 1 Define macros and figures in a separate file and include the graphics as external graphics 2 Define everything in the document source as usable graphics and include the graphics using NuseMPgraphic 3 Package the graphic components in buffers and paste those together as graphics that can be processed at run time The first method is the most independent one which has its advantages if we want to use the graphics in other applications too The second method works well in graphics where parts of the definitions change between invocations of the graphic This method follows the template startuseMPgraphic whatever stopuseMPgraphic startuseMPgraphic result includeMPgraphic whatever stopuseMPgraphic useMPgraphic result The disadvantage of this method is that it cannot be combined with btex etex since it is near ly impossible to determine when how and to what extent the content of a graphic should be expanded before writing it to the temporary METAPOST file Therefore we will demonstrate how buffers can be used This third method closely parallels the first way of defining graphics A nice side effect is that we can easily typeset these buffers verbatim which we did to typeset this document We are going to do a classic compass and straightedge construction the bisectio
193. into account This was needed because we don t use a background fill The next definition does so there we can use a more straightforward approach by just drawing and filling the small rectangle on top of the big one startuseMPgraphic FunnyFrame picture p numeric o path a b pair c p textext rt MMPstring FunnyFrame a unitsquare xyscaled OverlayWidth OverlayHeight BodyFontSize p shifted 20 O0verlayHeight ypart center p drawoptions withpen pencircle scaled lpt withcolor 625red b a randomized 0 2 fill b withcolor 85white draw b b boundingbox p randomized 0 8 fill b withcolor 85white draw b draw p withcolor black setbounds currentpicture to a stopuseMPgraphic There is not so much basic instruction as of now as there was in the old days showing the differences between good and bad typograph ic design Because we use a random graphic we cannot on forehand guarantee that the left and right edges of the small shape touch the horizontal lines in a nice way The next alternative displaces the small shape plus text so that its center lays on the line On the average this looks better startuseMPgraphic FunnyFrame picture p numeric o path a b pair p textext rt MMPstring FunnyFrame a unitsquare xyscaled OverlayWidth OverlayHeight BodyFontSize p shifted 20 O0verlayHeight ypart center p drawo
194. ions When using many graphics there is a chance that they share common definitions Such shared components can be defined by startMPinclusions color mycolor mycolor 625red stopMPinclusions Preliminary Version October 27 2000 KA METAPOST graphics defined in the document end up in the files mpgraph mp and mprun mp When processed they produce sometimes many graphic files When using to process documents these two files are processed automatically after a run so that in a next run the right graphics are available When you are using the web2c distribution CONTEXT can call METAPOST at runtime and thereby use the right graphics instantaneously In order to use this feature you have to enable write18 in the file texmf cnf Also in the file cont sys tex that holds local preferences or in the document source you should say runMPgraphicstrue This enables runtime generation of graphics using the low level command write18 First make sure that your local brand of supports this feature A simple test is making a file with the following line immediate writel8 echo It works If this fails you should consult the manual that comes with your system locate an expert or ask around on the CONTEXT mailing list Of course you can also decide to let TEXEXEC take care of pro cessing the graphics afterwards This has the advantage of being faster but has the disadvanta
195. is chosen by setting the alternative variable as we demonstrated in the example startuseMPgraphic page includeMPgraphic rightsuperbutton StartPage numeric alternative seed superness squeezeness randomness path transform t This is one of those cases where a transform variable is useful We need to store the random seed value because we want the larger path that is used in the calculations to have the same shape alternative MPvarf alternative seed uniformdeviate 100 if alternative 10 superness 85 realfolio 1 lastpage 25 squeezeness 12pt realfolio 1 lastpage 10pt else superness 90 squeezeness 12pt fi randomness squeezeness alternative alternative mod 10 If you read closely you will notice that when we add 10 to the alternative we get a page dependant graphic So in fact we have five alternatives We use CONTEXT macros to fetch the real page number and the number of the last page In further calculations we use the lower alternative numbers which is why we apply a mod The rest of the code is not so much different from the previous definition The hard coded point sizes match the page dimensions 600pt by 450pt quite well t identity if alternative 3 shifted 9pt 9pt fi Preliminary Version October 27 2000 randomseed seed p Field Text Text
196. itional and DVI but since PDFTEX came around and the lack of a postprocessing stage forced new primitives into the core the third option mentioned before more and more became reality Much of what I will discuss here can be realized in DVI using a dedicated postprocessor to extract the information needed Although we think that the PDFTEX way is the natural way to go CONTEXT also supports the same mechanism DVI nis focussed on breaking paragraphs into lines and lines is a dvnamaic process The space between words is flexible and we don t know in advance d or piece of a word maybe it s best to talk of instead will up on the page It might even cross the page boundary In the previous paragraph and plobs are encircled and connected by an arrow This graphic can only be drawn when the positions and dimensions are known which is after the paragraph is typeset and the best breakpoints are chosen Because the text must be laid on top o the graphic the graphic must precede the first word in the typeset stream or it must be positioned on a separate layer In the latter case it can be calculated directly after the paragraph is typeset bu in the former case a second pass is needed Because such graphics are not bound to one paragraph the multi pass option suits better because it gives us more control the more we know about he Preliminary Version October 27 2000 Posi
197. izes boxes skips kerns and penalties As you can see there are some boxes involved which is due to the conversion of METAPOST output to PDF startlinecorrection blank the graphic stoplinecorrection The small bar is a kern and the small rectangles are penalties More details on this debugger can be found in the CONTEXT manuals and the documentation of the modules involved Preliminary Version October 27 2000 Preliminary Version October 27 2000 11 11 1 Defining styles A document style can gain a lot by using a few graphics In this chapter we will introduce some style elements and their usage Adaptive buttons So far we have seen a lot of graphic ingredients that you can use to make your documents more attractive In this chapter we will define a simple document style This style was written for the PDFTEX presentations at the TUG 2000 conference in Oxford UK This style exploits a few tricks like graphics calculated using positional information It also demonstrates how you can make menu buttons that dynamically adapt their shapes to the rest of the page layout page 1 page 2 page 3 page 4 page 5 Later we will see an instance with some more randomness in the graphics While writing this style the random alternative made me think of those organic building with non equal windows we have a few of those in The Netherlands so I decided to label this styl
198. l numeric of path N x postcontrol numeric of path x 4 directionpoint pair of path 9 numeric pair pair path intersectionpoint path 2 Attributes Preliminary Version October 27 2000 precontrol 2 of fullcircle metapost primitive postcontrol 2 of fullcircle metapost primitive directionpoint 2 3 of fullcircle metapost primitive 5 0 0 1 1 metapost concept fullcircle intersectionpoint fulldiamond metapost macro withcolor color NY dashed withdots withcolor 5 0 0 metapost primitive dashed withdots metapost primitive dashed evenly metapost primitive withpen pencircle scaled 2mm metapost macro withpen pensquare scaled 2mm metapost macro withpen penrazor scaled 2mm metapost macro Preliminary Version October 27 2000 withpen penspeck transform withpen penspeck metapost macro draw draw fullcircle metapost macro NI M jamah fill fullcircle metapost macro filldraw filldraw fullcircle y x hd metapost macro drawfill drawfill fullcircle metapost macro drawdot drawdot origin metapost macro Preliminary Version October 27 2000 drawarrow drawarrow fullcircle undraw undraw fullcircle Va N metapost macro Q metapost macro AN unfill fullcircle metapost macro o
199. lay variables The communication between and embedded metarost graphics takes place by means of some macros overlay status macro meaning overlaywidth the width of the graphic as calculated from the actual width and back ground offset overlayheight the height of the graphic as calculated from the actual height depth and background offset overlaydepth the depth of the graphic if available overlaycolor the background color if given overlaylinecolor the color of the frame overlaylinewidth the width of the frame The dimensions of the overlay are determined by dimensions of the background which nor mally is the natural size of a framed When a background offset is specified it is added to overlayheight and overlaywidth Colors can be converted by MPcolor and in addition to the macros mentioned you can use all macros that expand into a dimension or dimen registers prefixed by the TEX primitive the this and other primitives are explained in The TEXbook by Donald Knuth Stacking overlays A background can be a gray scale screen a color color a previously defined overlay identi fier or any combination of these The next assignments are therefore legal framed background color backgroundcolor red framed background screen backgroundscreen 8 framed background circle framed background color cow backgroundcolor red framed background color cow
200. le looks like this 9 Let s draw a circle beginfig 7 draw fullcircle scaled 3cm withpen pencircle scaled lcm endfig end The main structuring components in such a file are the beginfig and endfig macros Like in one big story the file has many sub sentences where each sub sentence ends with a semi colon Although the end command at the end of the file concludes the story putting a period there is a finishing touch Actually after the end command you can put whatever text you wish your comments your grocery list whatever Comments in METAPOST prefixed by a percent sign asin Let s draw a circle are ignored by the interpreter but useful reminders for the programmer If the file is saved as yourfile mp then the file is processed by METAPOST by issuing the following command mpost yourfile after which you will have a graphic called yourfile 7 which contains a series of POSTSCRIPT commands Because METAPOST does all the work this file is efficient and compact The number of distinct POSTSCRIPT operators used is limited which has the advantage that we can postprocess this file rather easily We can view this file in a POSTSCRIPT viewer like GHOSTVIEW or convert the graphic to PDF and view the result in a suitable PDF viewer like ACROBAT Of course you can embed such a file in a CONTEXT document using a command like externalfigure yourfile 7 We will go in more detail about embedding graphics in chapter
201. le scaled 1mm withcolor 625red The origin is in the lower left corner of the picture MetaFun Because the transformation keywords are proper english we let the pictures speak for themselves currentpicture currentpicture shifted 0 lcm MetaFun Preliminary Version October 27 2000 A fewemore details currentpicture ll currentpicture d currentpicture currentpicture ll currentpicture currentpicture rotated 180 currentpicture rotatedaround origin 30 currentpicture scaled 1 75 MetaFun currentpicture scaled 1 currentpicture xscaled 3 50 TRA lt currentpicture riu 1619 M currentpicture currentpicture currentpicture Metafun currentpicture currentpicture currentpicture currentpicture currentpicture currentpicture currentpicture currentpicture xscaled yscaled yscaled slanted slanted zscaled 1 2 Preliminary Version October 27 2000 2 8 currentpicture currentpicture reflectedabout llcorner currentpicture urcorner currentpicture Only this far When you take a close look at the definitions of the Computer Modern Roman fonts defined in the METAFONT book you will notice a high level of abstraction
202. like this some effort goes into a proper user interface In doing so we need some TEK trickery that goes beyond this text like collecting text and splitting of the part needed Also we want to be able to handle multiple shapes at once like the next example demonstrates The macro is included in one of the METAPOST libraries so we first have to say useMP library txt We define four shapes They are not really beautiful but they demonstrate what happens in border cases For instance too small first lines are ignored First we define a circle Watch how the dimensions are set in the graphic The arguments passed to build_parshape are path an offset an additional horizontal and vertical displacement the baseline distance the height and depth of the line and the height of the first line topskip in terminology The height and depth of a line are often called strut height and depth with a strut being an invisible character with maximum dimensions startuseMPgraphic test 1 path p p fullcircle scaled 6cm build parshape 0 0 baselinedistance strutheight strutdepth strutheight draw p withpen pencircle scaled lpt stopuseMPgraphic The second shape is a diamond This is a rather useless shape unless the text suits the small lines at the top and bottom startuseMPgraphic test 2 path p p fullsquare rotated 45 scaled 5cm build parshape 0 0 baselinedistance struth
203. loop a bit so that the number of lines does not exceed the available space The test that surrounds the assignment of vvsize makes sure that we get better results when we on purpose take a smaller height startuseMPgraphic text step path line pair lll rrr numeric vvsize if strutheight strutdepth lt baselineskip vvsize vsize else vvsize vsize div baselineskip baselineskip fi for i topskip step baselineskip until vvsize line ulcorner q urcorner q shifted 0 i lll found point line 1l true rrr found point line r false stopuseMPgraphic We can manipulate the heigth and depth of the line to give different and maybe better results startuseMPgraphic text vars baselineskip 8pt Preliminary Version October 27 2000 E strutheight 4pt strutdepth 2pt offset 4pt topskip Spot stopuseMPgraphic This kind of graphic trickery in itself is not enough to get into typesetting within the bounds of a closed curve Since METAPOST can write information to a file and Tx can read such a file natural way to handle this is to let METAPOST write a parshape specification startuseMPgraphic text macro def provide_parshape expr p offset baselineskip strutheight strutdepth topskip includeMPgraphic text move includeMPgraphic text split includeMPgraphic t
204. lor mechanism off If you want your graphics to have color you should say Nsetupcolors state start Preliminary Version October 27 2000 Preliminary Version October 27 2000 1 1 Welcome to METAPOST In this chapter we will introduce the most important METAPOST concepts as well as demonstrate some drawing primitives and operators This chapter does not replace the METAFONT book or META Posr manual both of which provide a lot of explanations examples and dirty tricks As its title says the METAFONT book by Donald E Knuth is about fonts Nevertheless buying a copy is worth the money because as a METAPOST user you can benefit from the excellent chapters about curves algebraic expressions and linear equations The following sections are incomplete in many aspects More details on how to define your own macros can be found in both the META FONT book and wErarosr manual but you will probably only appreciate the nasty details if you have written a few simple ones yourself This chapter will give you a start Many of the concepts introduced here will be discussed in more detail in later chapters So you may consider this chapter to be an appetizer for the following chapters If you want to get started quickly you can safely skip this chapter now Paths Paths are the building blocks of METAPOST graphics In its simplest form a path is a single point Q cml5em
205. lt is available in the file mprun 21 This file can be included in the normal way using Nexternalfile mprun 21 width 5cm Figure3 1 The logo is defined in the file mylogos mp as figure 21 and processed by means of the mprun method 3 4 Graphic buffers In addition to the macros defined in the previous section you can use CONTEXT s buffers to handle graphics This can be handy when making documentation so it makes sense to spend a few words on them A buffer is a container for content that is to be re used later on The main reason for their existence is that they were needed for typesetting manuals and articles on TEK By putting the code snippets in buffers we don t have to key in the code twice since we can either show the Preliminary Version October 27 2000 code of buffers verbatim or process the code as part of the text flow This means that the risk of mismatch between the code shown and the typeset text is minimized startbuffer You are reading the METAFUN manual stopbuffer This buffer can be typeset verbatim using t ypebuffer and processed using getbuffer as we will do now An other advantage of using buffers is that they help you keeping the document source clean In a many places in this manual we put table or figure definitions in a buffer and pass the buffer to another command like placefigure A very big table getbuffer Sometimes it makes sense to collect buffers in separat
206. m lcm shifted lcm 5cm withcolor 625red fill unitsquare xyscaled 5cm lcm shifted lcm 6 5cm withcolor 625red draw unitsquare xyscaled 5cm 7cm shifted lcm 5cm withcolor 25white drawarrow 2cm 8cm top 2cm 7 5cm drawarrow 0cm 7cm lft 1cm 7cm clip currentpicture to unitsquare xyscaled 7cm 8cm stopuseMPgraphic As you can see the left graphic is defined as a series of rectangles The xyscaled macro is part of the files and saves some typing and space It is defined as a primary requiring both left and right operands primarydef p xyscaled q p xscaled xpart q yscaled ypart q enddef Zooming in on the top left corner only takes a few lines First we clip the correct part next we scale it up and finally we let the bounding box suit the left picture startuseMPgraphic layout 2 includeMPgraphic layout 1 clip currentpicture to unitsquare scaled 3cm shifted 0 5cm currentpicture currentpicture scaled 2 shifted 0 8cm setbounds currentpicture to unitsquare xyscaled 6cm 8cm stopuseMPgraphic This code demonstrates how you can reuse a graphic inside another one This strategy can easily be used to stepwise build or extend graphics The two graphics were put side by side with the following command Watch the use of line correction commands They optimize the white space around the graphic startlinecorrection blank hb
207. mbol and later we will see how it is defined First we draw the labels Unfortunately we cannot package btex etex into a macro because it is processed in a rather special way Therefore we have to put a lot of code here if show labels We use a bigger pen for drawing the dots pickup pencircle scaled 5pt The macro dot label draws dot and places the typeset label dotlabe btex 2 11 5 etex 211 ft dotlabel ulft btex 57 12 etex 212 dotlabel ulft btex 57 13 etex z13 llft dot label t btex 67 14 5 etex z14 dotlabel lrt btex 57 21 etex z21 dotlabel llft btex 57 22 etex z22 btex 2 23 5 etex z23 btex 62 24 etex 224 dotlabel urt Fh dotlabel ul dotlabel ur btex Z_ 31 etex 231 btex 57 32 etex 232 btex 57 33 etex 233 btex 57 34 etex 234 c4 dotlabel ul dotlabel urt dotlabel urt btex 652 41 5 etex 241 btex 657 42 5 etex 242 btex 57 43 6 etex 243 btex Z_ 44 etex 244 dotlabel lrt dotlabel urt dotlabel llft dotlabel lrt dotlabel urt btex 57 0 5 etex 20 dotlabel lft btex Z2 1 6 etex 21 dotlabel top btex 527 12 5 etex z2 dotlabel rt btex 57 3 etex 23 dotlabel bot btex 57 4 5 etex z4 Now we can end the condition that enables us to hide the labels and the macro Watch how we also end the figure fT
208. mized lcm pickup pencircle scaled 2pt fill Page withcolor 625white fill Main withcolor 850white draw Main withcolor 625red StopPage stopuseMPgraphic Edward R Tufte eee co harmonize synthesize focus organize Ha ie ose al an first large scale user the designer should also write the first user is would never have the initial design is complete and fairly robust the real test begins as people with many different viewpoints undertake their own experiments Douglas R Hostadter Donald Knuth has spent the past several years working on a system allowing him to control many aspects of the design of his forthcoming books from the typesetting and layout down to the very shapes of the letters Seldom has an author had anything remotely like this power to control the final appearance of his or her work Knuth s typesetting system has become well known and many countries around the world By contrast his system for designing Coeur tabu a ee In his article The Concept of a Meta Font Knuth sets forth for the first time the underlying hilosophy of vereronr as well as some ofits products Not only is the concept exiting and clearly certain important issues raised by The Concept of a Meta Font even Figure 6 5 The previous graphics are defined as usable Edward R Tufte not participated fully in all these activitie
209. mple paths and therefore METAPOST has a notion of a point on the penpath In the METRFONT book and METAPOST manual you can find in depth discussions on pens We re still not there Like in a previous example we need to shift over twice the pen width To get good results we should determine the width of the pen at that particular point which is not trivial The more general solution which permits us to specify the amount of shifting is as follows vardef penpoint expr pnt of p save n d numeric n d n d if pair pnt pnt else 1 fi point n of p shifted penoffset direction n of p of currentpen scaled d enddef When the point specification is extended with a distance in which case we have a pair expression the point and distance are derived from this specification First we demonstrate the simple case draw penpoint 0 of p for i 1 upto length p 1 penpoint i of p endfor cycle withcolor 625red In the next graphic we draw both an inner and and outer path Preliminary Version October 27 2000 draw penpoint 0 2 of p upto length p 1 625red 0 2 for i 1 withcolor draw penpoint of p for i 1 upto length p 1 625yellow withcolor penpoint penpoint i 2 i 2 of p endfor cycle of p endfor cycle Another case when t op and friends cannot be applied in a general way is the following Consider the three paths
210. mpty suffix subscript suffix tag suffix parameter subscript number numeric expression internal variable ahangle ahlength bboxmargin charcode day defaultpen defaultscale labeloffset linecap linejoin miterlimit month pausing prologues showstopping time tracingoutput tracingcapsules tracingchoices tracingcommands tracingequations tracinglostchars tracingmacros tracingonline tracingrestores tracingspecs tracingstats tracingtitles truecorners warningcheck year symbolic token defined by newinternal pseudo function min expression list max hexpression list incr numeric variable decr numeric variable dashpattern on offlist interpath numericexpression pathexpression pathexpression buildcycle path expression list thelabel label suffix expression pair expression thefreelabel expression pairexpression pairexpression anglebetween pathexpression pathexpression expression pointarrow pathexpression numericor pair primary numericexpression numeric expression leftarrow pathexpression numericor pair primary numeric expression centerarrow pathexpression numeric or pair primary numeric expression rightarrow path expression numeric or pair primary numeric expression paired numericor pair
211. n Hobby You can find this manual at every main repository Also a copy of the METAFONT book from Donald Knuth is worth every penny if only because it will give you the feeling that many years of graphical fun lays ahead In this MetaFun manual we will demonstrate how you can embed graphics a docu ment but we will also introduce most of the features of METAPOST For this reason you will see a lot of METRPOST code For sure there are better methods to solve problems but I have tried to demonstrate different methods and techniques as much as possible I started using metarost long after I started using and I never regret it Although I like TEK very much I must admit that sometimes using METAPOST is even more fun Therefore before we start exploring both in depth I want to thank their creators Donald Knuth and John Hob by for providing me these fabulous tools Of course I also need to thank Han Th Thanh for giving the community as well as providing me the hooks I considered neccessary for implementing some of the features presented here I also want to thank David Arnold and Ton Otten for their fast proofreading for providing me useful input and for testing the examples Without Davids patience and help this document would be far from perfect English and less complete Without Tons help many small typo s would have gone unnoticed Hans Hagen October 27 2000 Preliminary Version October
212. n of a line segment joining two arbitrary points We will construct 5 graphics where each one displays one step of the construction We will embed each graphic in a start stop command Later we will see the advantage of this strategy startbuffer a def start_everything enddef def stop_everything enddef stopbuffer We are going to draw a few dots and to force consistency we first define a macro draw_dot The current step will be highlighted in red using stand_out Preliminary Version October 27 2000 A few Nstartbuffer b numeric u w u 5cm w lpt pickup pencircle scaled w def draw dot expr p draw p withpen pencircle scaled 3w enddef def stand_out drawoptions withcolor 625red enddef stopbuffer First we construct the macro that will plot two points A and B and connect them with a line segment startbuffer c def draw_basics pair pointA pointB path lineAB pointA origin pointB pointA shifted 5u 0 lineAB pointA pointB draw lineAB draw dot pointA label lft btex A etex pointA draw dot pointB label rt btex B etex pointB enddef stopbuffer The code in this buffer executes the preceding macros everything commands are still undefined but later we can use these hooks for special purposes startbuffer 1 start_everything stand_out draw_basics stop_eve
213. n reason is that in the end many users will want to go beyond the simple cases and when dealing with these issues you must be aware and when defining graphics sometimes needs to take care too not only of height depth and width but also of the crossing of a page boundary and the height and depth of lines Given that unique identifiers are used for anchor points in CONTEXT you can have access to all the information needed Anchors and layers In a previous section we saw that some Arrow As with most things in CONTEXT marking these i ated from declaring what tode with those words This paragraph is keyed in as Preliminary Version October 27 2000 In a previous section we saw that some hpos X 1 words were hpos X 2 circled and connected by an hpos X 3 arrow As with most things in NCONTEXT marking these words is separated from declaring what to do with those words This paragraph is keyed in as We see three so called position anchors each marked by an identifier X 1 X 2 and X 3 Each of these anchors can be associated with a series of graphic operations Here we defined NsetMPpositiongraphic X 1 mypos arrow to X 2 NsetMPpositiongraphic X 2 mypos arrow to X 3 These examples clearly demonstrate that we are not in complete control over to what extend graphics will cover text and vise versa A solution to this problem is using so called position
214. native works too fill 0 0 0 hn w h w hh ww hh ww 0 hh w 0 cycle The next alternative will fail This has to do with the change in direction at point 0 0 halfway through the path Sometimes changing direction can give curious but desirable effects but here it brings no good fill 0 0 0 h w h w 0 0 0 ww 0 ww hh w hh ww 0 cycle This path fails because of the way POSTSCRIPT implements its fill operator More details on how POSTSCRIPT interpreters handle fills can be found in the reference manuals Some of the operations we have seen are hard coded into METAPOST and are called primitives Others are defined as macros that is a sequence of METAPOST commands Since they are used often you may expect draw and 111 to be primitives but they not They are macros defined in terms of primitives Given a path pat you can consider a draw to be defined in terms of addto currentpicture doublepath pat The 111 command on the other hand is defined as addto currentpicture contour pat Preliminary Version October 27 2000 15 Both macros are actually a bit more complicated but this is mainly due to the fact that they also have to deal with attributes like the pen and color they draw with You can use doublepath and contour directly but we will use draw and fi11 whenever possible Given a picture pic the following
215. ncircle scaled 5cm def shape unitsquare scaled 2cm withcolor 625white draw bbox currentpicture withpen pencircle scaled 5mm withcolor 625red addto finalpicture also currentpicture shifted n 3cm 0 currentpicture nullpicture n ntl enddef fill shape draw shape filldraw shape drawfill shape currentpicture finalpicture Here we introduce a macro definition shape In METAPOST the start of a macro definition is indicated with the keyword def Thereafter you can insert other variables and commands even other macro definitions The keyword enddef signals the end of the macro definition The result is shown in figure 2 1 watch the bounding boxes Close reading of the macro will reveal that the fill draw filldraw and drawfill macros are applied to the first unitsquare path in the macro Figure 2 1 Afill draw filldrawand drawfill applied to the same square Preliminary Version October 27 2000 2 4 In this macro bbox calls a macro that returns the enlarged bounding box of a path By setting bboxmargin we can influence how much the bounding box is enlarged Since this is an exist ing variable we don t have to allocate it like we do with numeric n Unless you take special precautions variables are global by nature and persistent outside macros picture finalpicture finalpicture nullpicture Just as numeric allocates an integer variable the picture primitive allocates a p
216. ncludeMPgraphic text split includeMPgraphic text cutoff includeMPgraphic text draw stopuseMPgraphic Or as graphic We are now ready for an attempt to calculate the shape of the text For each line we have to calculate the left and right intersection points and since a line has a height and depth we have to determine which part touches first startuseMPgraphic text calc vardef found_point expr lin pat sig pair a b a pat intersection point lin shifted 0 strutheight if intersection found a a shifted 0 strutheight else a pat intersection point lin fi b pat intersection point lin shifted 0 strutdepth Preliminary Version October 27 2000 if intersection found if sig if xpart b xpart a a b shifted 0 strutdepth fi else if xpart b xpart a a b shifted 0 strutdepth fi enddef stopuseMPgraphic Instead of using METRPOST s intersectionpoint macro we use one that comes with CONTEXT That way we don t get an error message when no point is found and can use a boolean flag to take further action Since we use a vardef all calculations are hidden and the a at the end is returned so that we can use this macro in an assignment The sig variable is used to distinguish between the beginning and end of a line the left and right subpath startuseMPgraphic text step path line pair lll rrr
217. ne is used for all 5 circles This means that the center of the shading stays at the first circle circular shade fullcircle scaled lcm 0 MPcolor a MPcolor b picture s S currentpicture currentpicture nullpicture for i 0 step 2cm until 8cm addto currentpicture also s shifted 1 0 endfor Unlike METRPOST does not keep its specials attached to the current path and flushes them before the graphic data Since we use these specials to register shading information it is rather hard to tightly connect a specific shade with a certain fill especially if an already performed fill is not accessible which is the case when we copy a picture This may seem a disadvantage but fortunately it also has its positive side In the next example we don t copy but reuse an already defined shade By storing the reference to this shade and referring to it by using withshade we can use a shade that operates on multiple shapes sh define circular shade origin origin 0 MPcolor a MPcolor b for i 0 step 2cm until 8cm fill fullcircle scaled 1cm shifted i 0 withshade sh endfor The low level macro de ine circular shade is fed with two pairs points two radius and two colors The shade is distributed between the colors according to the radius Shading can hardly be called an easy issue The macros that we provide here are in fact sim plifications which means that at a lower level one can
218. nge CONTEXT provides reusable graphics startreusableMPgraphic name fill fullcircle scaled 200pt withcolor 625yellow stopreusableMPgraphic This definition is accompanied by reuseMPgraphic name Imagine that we use a graphic as a background for a button We can create a unique and reusable graphic by saying Preliminary Version October 27 2000 embedded graphics def MyGraphic startreusableMPgraphic name overlaywidth overlayheight path p p unitsquare xscaled overlaywidth yscaled overlayheight fill p withcolor 625yellow draw p withcolor 625red stopreusableMPgraphic reuseMPgraphic name overlaywidth overlayheight After this we can say defineoverlay my graphic MyGraphic button background my graphic frame off Go Home firstpage Say that we have a 30pt by 20pt button then the identifier will be name 30pt 20pt Different dimensions will lead to other identifiers so this sort of makes the graphics unique We can bypass the ugly looking def by using a third class of embedded graphics the unique graphics startuniqueMPgraphic name path p unitsquare xscaled overlaywidth yscaled overlayheight fill p withcolor 625yellow draw p withcolor 625red stopuniqueMPgraphic Now we can say defineoverlay my graphic uniqueMPgraphic name button background my graphic frame off Go Home firstp
219. nstrate how you can put graphics behind these 25 areas as well as behind the left and right page Setting up backgrounds One way of protecting a document for unwanted usage is to put an annoying word in the back ground If you like this you may try the following The macro ysizedis part of the macros that come with CONTEXT and scales a picture to a specific size Preliminary Version October 27 2000 page backgrounds startuniqueMPgraphic concept draw btex bf CONCEPT etex rotated 60 withcolor 8white currentpicture currentpicture ysized Noverlayheight 5cm stopuniqueMPgraphic defineoverlay concept uniqueMPgraphic concept You can now put this graphic in the page background by saying setupbackgrounds page background concept You may consider the next alternative a bit better but still it renders the text unreadable Like xysized the macro enlarged is not part of standard metarost but comes with CONTEXT startuniqueMPgraphic copyright picture p p btex COPYRIGHT etex rotated 90 setbounds p to boundingbox p enlarged 1 draw p withcolor 8white currentpicture currentpicture xysized overlaywidth overlayheight stopuniqueMPgraphic defineoverlay copyright uniqueMPgraphic copyright Again we put this graphic in the background By using a unique graphic we make sure that it s rendered only once and reused when possible
220. o For reasons of convenience the current position is assigned automatically to from and self This means that in the line we saw in the graphic initialize_box MPpos MPvar self MPvar self will return the current position which fed to MPpos will return the list of positional numbers We already warned the reader this is not an easy chapter Some examples In due time there will a few more examples here For that the interface has to be more frozen than it currently is Preliminary Version October 27 2000 Positionaligraphics Preliminary Version October 27 2000 6 1 Page backgrounds Especially in interactive documents adding backgrounds to the page and text areas not only en hances readability but also makes it more convenient to identify header footers and navigational areas In this chapter we will demonstrate that with METAPOST we can go beyond the based features present in CONTEXT The basic layout In the CONTEXT manual you can find many details on the composition of the page When TEK typesets text crossing the page boundary triggers X s output routine This routine is responsible for pasting the body text that goes onto a page into the correct area A simple representation of such a page is The red areas are the header and footer while the yellow areas contains the text flow We can turn headers on and off and or hide them For this
221. o but first we show one more time the path that we take as starting point Z zl 22 23 c0ycle This path is made up out of five points where the cycle duplicates the first point and connects the loose ends The first point has number zero We can use these points in the subpath command which takes two arguments specifying the range of points to cut of the path specified after the keyword of subpath 2 4 of z0 z1 z2 z3 cycle The new sub path is a new path with its own points that start numbering at zero The next graphic shows both the original and the subpath from point 1 upto 3 z0 z1 z22 z3 cycle subpath 1 3 In spite of what you may think a point is not fixed This is why in Metarost a point along a path is officially called a time The next example demonstrates that we can specify any time on the path Preliminary Version October 27 2000 Z 0 z2l 422 23 c0ycle subpath 2 45 3 85 Often we want to take a slice starting at a specific point This is provided by cutafter and its companion cutbefore Watch out this time we use a non cyclic path z0 zl z2 z3 cutafter 22 Preliminary Version October 27 2000 20 21 22 23 cutbefore 71 is a somewhat silly way of accomplishing the same thing but it is a nice introduction to METRPOST s point operation In order to use this command effectively you need to know how m
222. oblem in calculations but to may look confusing when you show this size on your terminal and get less that 10 reported for a cmr10 font show fontsize cmr10 In order to demonstrate that font size is useful we extend the infont command In the process we show a few macro definition tricks What we want is a like specification of a font size draw MetaFun infont defaultfont at 20pt We store the current meaning of a primitive or macro in a new macro We do so with infont let normalinfont infont We can only know the size if we know the name of the font so we have to redefine infont to pick up this name def infont primary name hide lastfontsize fontsize name normalinfont name enddef Because we are replacing an operator and since METAPOST expects one we have to use def instead of vardef which is actually a kind of variable For the same reason we have to pick up a primary If we would use a expr name we would end up in an unwanted look ahead The hide macro hides the assignment and makes this macro behave like a vardef with respect to hiding expressions We may not put a semi colon after the because it would stop METAPOST from reading on and thereby invoke an error message We can now define at This macro picks up an expression which can me more than just a number and return a scale transform that normalized the given size to the design size def at expr size Scaled size lastfontsize en
223. of a Meta Font ertain important issues raised by The Concept of a Meta Font even odd Figure 6 3 A background with split areas This can easily be solved by enlarging the areas a bit The next example demonstrates this on the text area which is shown in figure 6 4 startuseMPgraphic page StartPage pickup pencircle scaled 2pt fill Page withcolor 625white fill Field Text Text enlarged 5cm withcolor 850white draw Field Text Text enlarged 5cm withcolor 625red StopPage stopuseMPgraphic The enlarged macro can be used like shifted and accepts either a numeric or a pair How do we define a background as in figure 6 2 Because Field provides us the positioned areas we can use the corners of those startuseMPgraphic page StartPage path Main if OnRightPage Main lrcorner Field OuterMargin Text llcorner Field Text Text Preliminary Version October 27 2000 Edward R Tufte We thrive in information thick worlds because of our marvelous and everyday capacity to select edit single out structure highlight group pair merge harmonize synthesize focus organize condense reduce boil down choose categorize catalog classify list abstract scan look into Thus I came to the conclusion that the designer of a new system must not only be the implementer and first large scale user the designer should also write the first user manual The
224. olor 625white stopMPgraphic Next the graphic can be loaded using loadcurrentMPgraphic optional setups Finally the graphic is placed in the document with placeMPgraphic The optional setups are passed on to the figure inclusion macro which in CONTEXT is the command externalfigure Since every definition replaces the previous one this method forces you to embed the defini tions in the running text In this document we also generate graphic while we finish a page so there is a good change that when we have constructed a graphic which will be called the next page the wrong graphic is placed Therefore you may as well forget these commands since there are more convenient ways of defining and using graphics which have the added advantage that you can predefine multiple graphics thereby separating the definitions from the usage The first alternative is a usable graphic Such a graphic is calculated anew each time it is used An example of a usable graphic is startuseMPgraphic name fill fullcircle scaled 200pt withcolor 625yellow stopuseMPgraphic When you put this definition in the preamble of your document you can place this graphic any where in the file saying useMPgraphic name As said this graphic is calculated each time it is placed which can be time consuming Apart from the time aspect this also means that the graphic itself is incorporated many times Therefore for graphics that don t cha
225. on So definesymbol yes Nem Yes creates a symbol that lets symbol yes expand into Yes Since nearly anything can be a sym bol we can also say definesymbol yes mathematics star or even the already defined symbol 4 by saying definesymbol yes symbol star It may be clear that we can use a graphic as well def metabuttonsymbol 1 uniqueMPgraphic meta button type 1 definesymbol menu left metabuttonsymbol 101 Ndefinesymbol menu right metabuttonsymbol 102 definesymbol menu list metabuttonsymbol 103 definesymbol menu index metabuttonsymbol 104 definesymbol menu person metabuttonsymbol 105 definesymbol menu stop metabuttonsymbol 106 definesymbol menu info metabuttonsymbol 107 definesymbol menu down metabuttonsymbol 108 definesymbol menu up metabuttonsymbol 109 Ndefinesymbol menu print metabuttonsymbol 110 Since we have collected some nice buttons in a METAPOST file already we can use a rather simple definition startuniqueMPgraphic meta button type size linecolor fillcolor input mp butt some_button MPvar type MPvar size MPvar linecolor MPvar fillcolor stopuniqueMPgraphic This leaves a few settings setupMPvariables meta button type 1 size 2 bodyfontsize fillcolor gray linecolor darkred These symbols are collected in tabl
226. on October 27 2000 tension numeric and numeric curl numeric dir numeric Preliminary Version October 27 2000 0 0 75 0 tension 2 5 and 1 5 1 25 1 1 metapost primitive 0 0 75 0 tension atleast 1 1 25 1 1 metapost primitive 0 0 1 0 1 1 cycle metapost primitive 0 0 curl 1 75 0 1 25 1 1 metapost primitive 0 0 dir 30 1 1 metapost primitive 0 0 left 1 1 metapost macro 0 0 right 1 1 metapost macro 0 0 up 1 1 metapost macro 0 0 down 1 1 metapost macro Preliminary Version October 27 2000 path amp path unitvector N fullcircle x 2 unitcircle fullsguare B unitsquare Preliminary Version October 27 2000 0 0 675 25 a Tg 2S aa 1 1 metapost primitive origin unitvector 1 1 metapost variable fullcircle metapost variable unitcircle metafun variable fullsquare metafun variable unitsquare metapost variable fulldiamond unitdiamond e halfcircle guartercircle llcircle M Ircircle D urcircle D N fulldiamond metafun variable unitdiamond metafun variable halfcircle metapost variable quartercircle metapost variable llcircle metafun variable lrcircle metafun variable urcircle metafun variable Preliminary V
227. ons Figure 13 4 Koffka s examples of manipulating contrast by changing the spatial configuration The definition of the first row of figure 13 4 is used in the second and third and therefore is the most complicated We use quite some scratch variables to reach a high level of abstraction The xyscaled operator is a Met aFun macro startuseMPgraphic first numeric height width radius gap gap 1mm height 2 5cm width height 2 radius height 2 5 Preliminary Version October 27 2000 A few 13 6 127 13 8 color mainshade leftshade rightshade centershade mainshade MPcolor funcolor leftshade 9mainshade rightshade 5mainshade centershade 5 leftshade rightshade fill unitsquare xyscaled width height withcolor leftshade fill unitsquare xyscaled width height withcolor rightshade draw fullcircle scaled radius shifted 0 height 2 withpen pencircle scaled radius 2 withcolor centershade stopuseMPgraphic The graphics of the second row extend those of the first by drawing a white line through the middle In this example setting the linecap is not really needed because rounded top and bottoms in white are invisible and the part that extends beyond the points does not count in calculating the bounding box startuseMPgraphic second includeMPgraphic first interim linecap butt pickup pencir
228. ontscale In the table we called the graphic directly but how about making it available as a conversion macro In CONTEXT this is not that hard def fuzzycount 1 tx useMPgraphic fuzzycount n 1 defineconversion fuzzy fuzzycount Because such a counter should not be that large we use t x to switch to a smaller font This also demonstrates how the graphic adapt itself to the font size We can now use this conversion for instance is an itemize To save space we use three columns and no white space between the lines The 2 broad directive makes sure that we have enough room for the number l one ll four WI seven ll two M five WI eight Ill three six nine startitemize fuzzy pack 2 broad columns three item two item three item fiv item seven item item one item four item six ight item nine stopitemize A careful reader will have noticed that the previous definition of the fuzzy counter drawing is not suited to generate the graphics we started with useMPgraphic fuzzycount n 1001 This time we want to limit the width to the current hsize We only need to add a few lines of code Watch how we don t recalculate the bounding box when more lines are used startuseMPgraphic fuzzycount begingroup save height vstep hsize span drift d cp height 3 4 the bodyfontsize currentfontscale span 1 3 height drift 1 10 height
229. order to process the next examples you should embed the code in beginfig and endfig macros Also in stand alone graphics don t forget to say Ninput mp tool first pickup pencircle scaled 5cm draw unitsquare xscaled 8cm yscaled 1cm withcolor 625white path bb bboxmargin Opt bb bbox currentpicture draw bb withpen pencircle scaled 1pt withcolor 625red In the third line we define a path variable We assign the current bounding box to this variable but first we set the offset to zero The last line demonstrates how to draw such a path Instead of setting the pen as we did in the first line we pass the dimensions directly Where draw draws a path the 111 macro fills one In order to be filled a path should be closed which is accomplished by the cycle primitive as we saw in constructing the unit square path pickup pencircle scaled 5cm fill unitsquare xscaled 8cm yscaled lcm withcolor 625white path bb bboxmargin Opt bb bbox currentpicture draw bb withpen pencircle scaled 1pt withcolor 625red This example demonstrates that when we fill the path the resulting graphic is smaller Where draw follows the center of a path 111 stays inside the path A third alternative is the illdraw macro From the previous examples we would expect a bounding box that matches the one of the drawn path pickup pencircle scaled 5cm filldraw unitsquare xscaled 8cm yscaled 1cm withcolor 625whi
230. other Only one of them is visible at any time placefigure here fig steps Bisecting a line segment with compass and straightedge Just click Ngoto here JS Walk_Field midpoint construction to walk through the construction This stack is only visible in a PDF viewer that supports widgets fieldstack midpoint construction Figure 13 6 Bisecting a line segment with compass and straightedge Just click here to walk through the construction This stack is only visible in a PDF viewer that supports wid gets At the start of this section we mentioned three methods When we use the first method of putting all the graphics an external metarost file the following framework suits We assume that the file is called step mp and that it is kept by the user along with his document source We start with the definitions of the graphic steps These are the same as the ones shown previously def draw_basics enddef def draw_circles enddef def draw_intersection enddef def draw_bisector enddef Preliminary Version October 27 2000 A few applications def draw midpoint enddef def stand out enddef We can safe some code by letting everything take care of the beginfig and endfig macros def start everything expr n beginfig n enddef def stop everything endfig enddef The five graphics now
231. ould never have thought of them or perceived why they were important But a system cannot be successful if it is too strongly influenced by a single person One e initial design is complete and fairly robust the real test begins as people with many different viewpoints undertake their own experiments ouglas Hostadter Donald Knuth has spent the past several years working on a system allowing him to control mar of the design of his forthcoming books from the typesetting and layout down to the ver Jhapes of the letters Seldom has an author had anything remotely like this power to control th final appearance of his or her work Knuth s typesetting system has become well known an wailable in many countries around the world By contrast his METAFONT system for designin lies of typefaces has not become as well known or available In his article The Concept of a Meta Font Knuth sets forth for the first time the underly hilosophy of as well as some of its products Not only is the concept exiting and clearly ell executed but in my opinion the article is charmingly written as well However despite my verall enthusiasm for Knuth s idea and article there are some points in it that I feel might b jaken wrongly by many readers and since they are points that touch close to my deepest interests artificial intelligence and esthetic theory 1 felt compelled to make some comments to clarif ertain important issues raised
232. overlays We can define such an overlay as follows Nstartpositionoverlay backgraphics setMPpositiongraphic G 1 mypos circle setMPpositiongraphic G 2 mypos circle setMPpositiongraphic G 3 mypos circle setMPpositiongraphic G 4 mypos circle stoppositionoverlay startpositionoverlay foregraphics setMPpositiongraphic G 1 mypos line to G 2 setMPpositiongraphic G 2 mypos line to G 3 setMPpositiongraphic G 3 mypos line to G 4 stoppositionoverlay First we have defined an can be attached to some overlay layer like in our case the We define e are drawn as soon as the page overlay is typeset B catise they are located in the baeKground they don t cove fext while the lines do The previous paragraph was typeset by saying First we have defined an hpos 16 1 overlay This overlay can be attached to some overlay layer like in our case the hpos G 2 page We define four small hpos G 3 circles These are drawn as soon as the page overlay is typeset Because they are located in the background they don t cover the hpos G 4 text while the lines do The previous paragraph was typeset by saying As said the circles are on the background layer but the lines are not They are positioned on top of the text This is a direct result of the definition of the page background Ndefineoverlay foregraphics positionoverlay foregraphics Ndefineoverl
233. ow to deal with this we first define a simple path Because we are going to replace pieces of code we will compose the graphic from components First we create the path startuseMPgraphic text path path p p 0 1 1 0 1 0 cycle scaled 65pt stopuseMPgraphic This shape is not that beautiful but it has a few characteristics that will help us to identify bor dercases startuseMPgraphic text draw drawarrow p withpen pencircle scaled 1pt withcolor red stopuseMPgraphic Now we use CONTEXT s NincludeMPgraphics command to build our graphic from the previ ously defined components startuseMPgraphic text includeMPgraphic text path includeMPgraphic text draw stopuseMPgraphic When called with useMPgraphic text we get For the moment we start the path at x 0 y gt 0 but later using more complicated macros we will see that we can use arbitrary paths We are going to split the path in two and will use the point that make up the bounding box as calcutated by The next graphic shows one of these points the lower left corner available as point 11corner p startuseMPgraphic text draw draw p withpen pencircle scaled 3pt withcolor red draw boundingbox p withpen pencircle scaled lpt draw llcorner p withpen pencircle scaled 5pt stopuseMPgraphic Preliminary Version October 27 2000 Typesetting in
234. own in figure 9 3 This one is defined as placefigure here fig traced shapes A continuous text typeset in a non standard shape spread over four areas tracing on startMPinclusions boolean trace_parshape trace_parshape true stopMPinclusions getbuffer This mechanism is still somewhat experimental and will be optimized and extended with name spaces and more We can combine all those tricks although the input is somewhat fuzzy First we define a quote typeset in a circular paragraph shape startuseMPgraphic center build parshape fullcircle scaled 8cm 0 0 0 baselinedistance strutheight strutdepth strutheight stopuseMPgraphic startshapetext center input douglas stopshapetext defineoverlay center useMPgraphic center We will surround this text with a circular line that we define as follows By using a buffer we keep things organized startbuffer circle startuseMPgraphic followtokens path RotPath RotPath reverse fullcircle Preliminary Version October 27 2000 Donald Knuth has spent the past several years working on a system allow ing him to control many aspects of the design of his forthcoming books from the typesetting and layout down to the very shapes of the letters Seldom has an au thor had anything remote ly like this power to con test 1 well known or available
235. ox useMPgraphic layout 1 hskiplcm useMPgraphic layout 2 stoplinecorrection backgrounds Preliminary Version October 27 2000 As soon as you want to make an electronic document you will want to use different areas of the screen for different purposes text menus buttons etc For this reason CONTEXT provides not only left and right margins but also additional left and right edge areas and top and bottom margins These areas are shown in the figure on the next page When defining this graphic all areas have related dimensions Here it makes sense to let METRPOST calculate these dimensions as much as possible First we define the five by five matrix of areas We pass the width and height of the main text area Because they are stored in TEx dimension registers we have to prefix them by Nt he pickup pencircle scaled 2pt numeric wi h xf u u 5cm numeric width width NtheNtextwidth numeric height height the textheight We now specify the lower left corners using instead of the which means that METAPOST will calculate w 3 and 3 for us 2u w 2 3u w 4 w 5 24 lu h 2 lu h 4 lu h 5 14 w 1 w 2 w 3 w 4 w 5 4u width h 1 h 2 h 3 h 4 h 5 4u height xii lu 1 10 2 x 1 w 1 5u 2 y 1 1 5u 3 x 2 w 2 5u
236. pared to help it a bit when paths have multiple intersection points Again we could follow a more secure mathematical method but the next one took only a few minutes of trial and error To save some memory we redefine the colors graphic When we call this macro as colorcircle 4cm red green blue we get vardef colorcircle expr size red green blue save r g b rr gg bb cc mm yy save radius path r g b rr bb gg cc mm yy numeric radius radius 5cm pickup pencircle scaled radius 25 r g b fullcircle scaled radius shifted 0 radius 4 r rotatedaround origin 15 g rotatedaround origin 135 b rotatedaround origin 255 Preliminary Version October 27 2000 r rotatedaround center r 90 g g rotatedaround center g 90 gg buildcycle buildcycle reverse r b g buildcycle buildcycle b reverse g r rr gg rotatedaround origin 120 bb gg rotatedaround origin 240 yy cc rotatedaround origin 120 mm cc rotatedaround origin 240 fill fullcircle scaled radius withcolor white fill rr withcolor red fill cc withcolor white red fill gg withcolor green fill mm withcolor white green fill bb withcolor blue fill yy withcolor white blue for 1 rr gg bb cc mm yy draw i withcolor 5white end
237. plementation is a bit more advanced vardef pointarrow expr pat loc len off save l r S t path 1 r numeric s pair t t if pair loc loc else point loc along pat fi S len 2 off if s 0 0 elseif s gt len s len fi r pat cutbefore t r r cutafter point arctime s of of r S len 2 off if 5 lt 0 s 0 elseif s gt len s len fi l reverse pat cutafter t l reverse 1 cutafter point arctime s of 1 of 1 1 1 enddef This code fragment also demonstrates how we can treat the 10c argument as pair coordinates or fraction of the path We calculate the piece of path before and after the given point separately and paste them afterwards as 1 r By adding braces we can manipulate the path in expressions without the danger of handling r alone We can now implement left center and right arrows by providing this macro the right param eters The offset the fourth parameter is responsible for a backward displacement This may seem strange but negative values would be even more confusing def rightarrow expr p t l pointarrow p t l 1 enddef def leftarrow expr p t l pointarrow p t l 1 enddef def centerarrow expr p t l pointarrow p t l 0 enddef We can now apply this macro as follows Watch how we can passa point point 5 of well as a fraction 4 The following graphic demonstrates a few more alternatives
238. points p reflectedabout 2 4cm 5 2 4cm The line about which the path is mirrored Mirroring does not have to be parallel to an axis p reflectedabout 2 4cm 5 2 6cm The rectangle now becomes The table also mentioned zscaled A zscaled specification takes a vector as argument p zscaled 2 5 The result looks like a combination of scaling and rotation and conforms to the formula in the previous table Transformations can be defined in terms of a transform matrix Such a matrix is stored in a transform variable For example transform t t identity scaled 2cm shifted 4cm 1cm We use the associated keyword t rans formed to apply this matrix to a path or picture Preliminary Version October 27 2000 Welcome to MEP 13 p transformed t In this example we ve taken the identity matrix as starting point but you can use any prede fined transformation The identity matrix is defined in such a way that it scales by a factor of one in both directions and shifts over the zero vector Transform variables can save quite some typing and may help you to force consistency when many similar transformations are to be done Instead of changing the scaling shifting and other transformations you can then stick to just changing the one transform variable Constructing paths In most cases a path will have more points than the few shown h
239. pression path join cycle path knot tertiary path join EE c direction specifier basic path join direction specifier direction specifier empty curl numeric expression pairexpression numeric expression numeric expression basic path join tension tension controls tension tension numeric primary tension atleast numeric primary tension numeric primary and numeric primary controls controls pair primary controls pair primaryiandhpair primary argument symbolic token number or fraction number number number not followed numberi Preliminary Version October 27 2000 scalar multiplication op gt number fractioni not followed by add op number transformer rotated numeric primary scaled numeric primary shifted pair primary slanted numeric primary transformed transform primary xscaled numeric primary yscaled numeric primary zscaled pair primary xyscaled numeric primary reflectedabout pairexpression pairexpressioni rotatedaround pairexpression numericexpression enlarged numeric or pair primary randomized numeric or pair primary Sqeezed numeric or pair primary superellipsed numeric primary xsized numeric primary ysized
240. ptions withpen pencircle scaled lpt withcolor 625red b a randomized 0 2 fill b withcolor 85white draw b Go Center P 2 b intersectionpoint shifted 0 shifted 0 0 p shifted c center p b boundingbox p randomized 0 8 fill b withcolor 85white draw b draw p withcolor black setbounds currentpicture to a stopuseMPgraphic Preliminary Version October 27 2000 Enhancing the layout _ There is not so much basic instruction as of now as there was in the old days showing the differences between good and bad typograph ic design Yet another definition uses super ellipsed shapes instead of random ones We need a high degree of superness 95 in order to make sure that the curves don t touch the texts startuseMPgraphic FunnyFrame picture p numeric o path a b pair c p textext rt MMPstring FunnyFrame BodyFontSize a unitsquare xyscaled OverlayWidth OverlayHeight p shifted 20 O0verlayHeight ypart center p drawoptions withpen pencircle scaled lpt withcolor 625red b superellipsed 95 fill b withcolor 85white draw b b boundingbox p superellipsed 95 fill b withcolor 85white draw b draw p withcolor black setbounds currentpicture to a stopuseMPgraphic Many people are just fascinated by their PC s tricks and think th
241. r 27 2000 This logo makes a good candidate for demonstrating a few fine points of drawing graphics like using linear equations setting line drawing characteristics clipping and manipulating bounding boxes The implementation below is quite certainly not according to the official specifications but it can nevertheless serve as an example of defining such logos As always we need to determine the dimensions first Here both the height and line width depend on the width of the graphic Instead of calculating the blue shape such that it will be a filled outline we will draw the logo shape using line segments This is why we need the 1ine parameter numeric width width 3cm numeric height height width 2 height 4 numeric line gt Lane We want sharp corners which can be achieved by setting line join to mitered linejoin mitered pickup pencircle scaled line The colors are rather primary blue and yellow At the time of writing this manual Dutch trains are still painted yellow so we will use that shade as background color color nsblue nsblue 0 071 3 color nsyellow nsyellow 1 1 0 We will now describe the main curves Although these expressions are not that advanced they demonstrate that we can express relationships instead of using assignments zl 0 height 2 z2 width 2 height 4 yl z3 width 2 height 4 y4 z4 width 0 p
242. r green fill b withcolor blue fill c withcolor white red H fill m withcolor white green fill y withcolor white blue fill w withcolor white for r g b c m y draw i withcolor 5white endfor currentpicture currentpicture xsized size Preliminary Version October 27 2000 13 5 popcurrentpicture enddef Here we first fill the primary circles next we fill the secondary ones which also cover the center which is why finally we fill the center with white The circle uses the following colors colorcircle 4cm 2 5 98 8 5 2 5 5 5 8 2 The next graphic demonstrates how the subpaths look that build the shapes We did not mention what the push and pop commands are responsible for Scaling the current picture is well defined as long as we deal with one graphic However if the current picture already has some content this content is also scaled The push and pop commands let us add content to the current picture as well as manipulating the picture as a whole without any side effects The final result is put on top of the already drawn content Fool yourself When doing a literature search on the human perception of black white edges I ran into several articles with graphics that I remember having seen before in books on psychology physiology Preliminary Version October 27 2000 and or ergonomics One of the article
243. r if they have a relationship but if so and if a baby is born may it enjoy MetaFun The low level CONTEXT macro processwords provides a mechanism to treat the individual words of its argument The macro is called as follows processwords As you may know NTEX s ambassador is a lion while METAFONT is represented by a lioness It is still unclear if they have a relationship but if so and if a baby is born may it enjoy METAFUN In order to perform a task you should also define a macro processword which takes one argument The previous quote was typeset with the following definition in place def processword 1 1 A slightly more complicated definition is the following def processword 1 noindent framed 1 space We now get Preliminary Version October 27 2000 _Enhan ing thel yout As may know TEX s jambassador is a while METRFONT is represented by 16 is still unclear they have a relationship but if so land if Jal baby is born may it enjoy MetaFun If we can use V framed we can also use backgrounds def processword 1 noindent framed frame off
244. ractionmenu right placelist Topic alternative right vfill but CloseDocument close NN stopinteractionmenu We have now arrived at the more interesting part of the style definition the graphic that goes in the page background Because this graphic will change we define a useable METAPOST graphic Page backgrounds are recalculated each page opposite to the other backgrounds that are calcu lated when a new background is defined or when repetitive calculation is turned on setupbackgrounds page background page defineoverlay page useMPgraphic page setupMPvariables page alternative 3 We will implement three alternative backgrounds First we demonstrate the relatively simple super ellipsed one The main complication is that we want the button shapes to follow the right edge of the curve that surrounds the text We don t know in advance how many lines of text there will be in a button and we also don t know at what height it will end up Therefore we need to calculate each button shape independently and for that purpose we need to know its position see chapter 5 In figure 11 1 you can see what auxiliary lines we need in order to be calculate the button shapes We separate the calculation of the button shape from the rest by embedding it in its own usable graphic container The StartPage StopPage pair takes care of proper placement of the whole graphic startuseMPgraphic page includeMPgraphic rightsuperbutton
245. rawarrow 1 withpen pencircle scaled withcolor green drawarrow withpen pencircle scaled lpt withcolor blue stopuseMPgraphic We use includeMPgraphic to assemble the components epos Preliminary Version October 27 2000 startuseMPgraphic text includeMPgraphic text path includeMPgraphic text split includeMPgraphic text draw stopuseMPgraphic This graphic is typeset with useMPgraphic text Before we are going to use them we define some variables that specify the text We use a baseline distance of 8 points The part of the line above the baseline is 7 2 points while the maximum depth is 2 8 points These ratios are the ones we use in CONTEXT Because we don t want the text to touch the circle so we also define an offset too startuseMPgraphic text vars baselineskip 8pt strutheight 7 2 10 baselineskip strutdepth 2 8 10 baselineskip offset baselineskip 2 topskip strutheight stopuseMPgraphic We more of less achieve the offset by scaling the path In doing so we use the width and height which we call hsize and vsize thereby conforming to naming scheme First we calculate both dimensions from the bounding box of the path Next we down scale the path to compensate for the offset When done we recalculate the dimensions startuseMPgraphic text move pair t b path 1
246. reelabel expr str loc ori save 5 p d 1 picture S path p pair 1 S thelabel str loc p fullcircle scaled 2 length loc ori shifted ori freesquare xyscaled urcorner s llcorner s l point xpart p intersectiontimes ori loc Preliminary Version October 27 2000 WA few applications draw q shifted loc withpen pencircle scaled 5pt draw 1 shifted loc withcolor 625yellow draw loc withcolor 625red S enddef The macro xyscaled is part of Met aFun and scales in two directions at once The METAPOST prim itive intersectiontimes returns a pair of time values of the point where two paths intersect The first part of the pair concerns the first path We are now a small step from the exact placement If we change the last line of the macro into s shifted 1 we get the displacement we want Although the final look and feel is also determined by the text itself the average result is quite acceptable Because we also want to pass pictures and add a bit of offset too the final implementation is slightly more complicated The picture is handled with an additional condition and the offset with the MetaFun macro enlarged numeric freelabeloffset freelabeloffset 3pt vardef thefreelabel expr str loc ori save s p 1 picture path p pair 1 interim labeloffset freelabeloffset S
247. rns the characteristics of the box as identified by MPpos After this call the corners are available in 11xy 1 urxy and ulxy The center is defined by cxy and the path stored in pxy When we are finished drawing the graphic we can anchor the result with anchor_box This macro automatically handles positioning on specific layers The position macro MPpos returns the current characteristics of a position The previously defined G positions return position page x y width height depth G 1 121 182 83447pt 370 73158pt 31 94986pt 7 28491pt 2 81995pt G2 121 114 09833pt 357 59975pt 21 16978pt 4 84497pt 2 81995pt G3 121 24437132pt 35759975pt 27 57951 7 28491pt 0 21497 GA 121 395 46603pt 344 46791pt 16 29967pt 6 05992pt 0 21497 The numbers represent the pagenumber p the current position x y and the dimensions of the box w h d if known These values are fed directly into METAPOST graphics but the individual components can be asked for MPp MPx MPy MPw MPh and MPd In the previous definition of the graphic we saw another macro MPvar When we invoke a graphic or attach a graphic to a layer we can pass variables We can also set specific variables in other ways as we will see later setMPpositiongraphic G 1 mypos circle setMPpositiongraphic G 1 mypos line to G 2 In the second definition we let the variable to point to another position When needed we can ask for the value of to by MPvar t
248. rogram that filters the btex commands from the file and generates file from them Next this file is processed by and after that converted to a mpx file In CONTEXT we let take care of this whole process Because the btex etex commands are filtered from the raw METAPOST source code they can not be part of macro definitions and loop constructs When used that way only one instance would be found while in practice multiple instances may occur This drawback is overcome by MetaFun s textext command This commands still uses btex etex but writes those commands to a separate file each time it is used After the first METRPOST run this file is merged with the original file and METAPOST is called again So at the cost of an additional run we can use text typeset by TEK in a more versatile way Because METRPOST runs are much faster than runs the price to pay in terms if run time is acceptable Opposite to btex etex the TEK code in text ext command is expanded but as long as CONTEXT is used this is seldom a problem because most commands are kind of protected If we define a graphic with text to be typeset by TEK there is a good change that this text is not frozen but passes as argument A rather TEK like solution for passing arbitrary content to such graphic is the following Preliminary Version October 27 2000 HEnhancitigthe layout _ def RotatedT
249. rongly by many readers and since they are points that touch close to my deepest interests Edward R Tufte We thrive in information thick worlds because of our marvelous and everyday capacity to select edit single out structure highlight group pair merge harmonize synthesize focus organize condense reduce boil down choose categorize catalog classify list abstract scan look into idealize isolate discriminate distinguish screen pigeonhole pick over sort integrate blend inspect filter lump skip smooth chunk average approximate cluster aggregate outline sum marize itemize review dip into flip through browse glance into leaf through skim refine enumerate glean synopsize winnow the wheat from the chaff and separate the sheep from the goats Donald E Knuth Thus came to the conclusion that the designer of a new system must not only be the implementer and first large scale user the designer should also write the first user manual The separation of any of these four components would have hurt TEX significantly If I had not participated fully in all these activities literally hundreds of improvements would never have been made because I would never have thought of them or perceived why they were important But a system cannot be successful if it is too strongly influenced by a single person Once the initial design is complete and fairly robust the real test begins as people with many
250. ructure highlight group pair merge harmonize synthesize focus organize condense reduce boil down choose categorize catalog classify list abstract scan look into idealize isolate discriminate distinguish screen pigeonhole pick over sort integrate blend inspect filter lump skip smooth chunk average approximate cluster aggregate outline summarize itemize review dip into flip through browse glance into leaf through skim refine enumerate glean synopsize winnow the wheat from the chaff and separate the sheep from the goats You may also notice that rules produced by 1 are converted to straight line segments Because the line extends 50 of its linewidth beyond a point there is a slight overshoot This picture was defined in a few lines draw btex framed width fit align middle input tufte relax etex for i within currentpicture draw boundingbox i withpen pencircle scaled 2pt withcolor 625yellow endfor If we use a Times Roman instead of a Palatino we get quite different results thrive in informationZthick worlds because of marvelous and everyday capacity to select edit single put structure highlight
251. ry Version October 27 2000 suffix list suffix suffixlist suffix B2 List of things Maybe I ll add an extended version of the commands and variables here Preliminary Version October 27 2000 This document This document is produced in CONTEXT and can serve as an example of how to integrate METAPOST graphics into TEX In this appendix we will discuss some details of producing this document We did not use any special tricks so most of the examples you have seen were coded just as shown We use buffers to ensure that the code used to produce the accompanying graphic is identical to the typeset code in the document Here is an example startbuffer dummy draw fullcircle xscaled 3cm yscaled 2cm rotatedaround origin 30 withcolor 625red stopbuffer Instead of using get buffer we used the following command startlinecorrection blank processMPbuf fer dummy stoplinecorrection The line correction commands take care of proper spacing around the graphic If you want to process more buffers at once you can pass their names as a comma separated list Alternatively we could have said startuseMPgraphic dummy draw fullcircle xscaled 3cm yscaled 2cm rotatedaround origin 30 withcolor 625red stopuseMPgraphic When including this graphic we again take care of spacing startlinecorrection blank useMPgraphic dummy stopl
252. rything stopbuffer This graphic can now be embedded by the CONTEXT command processMPbuffer This com mand like the ordinary buffer inclusion commands accepts a list of buffers Nstartlinecorrection blank Nruledhbox NprocessMPbuffer a b c 1 stoplinecorrection We use ruledhbox to show the tight bounding box of the graphic The line correction takes care of proper spacing around non textual content like graphics This is only needed when the graphic is part of the text flow A B These spacing commands try to get the spacing around the content visually compatible and take the height and depth of the preceding and following text into account applications Preliminary Version October 27 2000 Next we draw two circles of equal radius one centered at point A the other at point B Nstartbuffer d def draw circles path circleA circleB numeric radius distance distance xpart pointB xpart pointA radius 2 3 distance circleA fullcircle scaled 2 radius circleB circleA shifted pointB draw circleA draw circleB enddef stopbuffer As you can see we move down the stand_out macro so that only the additions are colored red startbuffer 2 start_everything draw_basics stand_out draw_circles stop_everything stopbuffer We now use processMPbuffer a b c d 2 to include the latest step
253. s def metahashoverlay 1 uniqueMPgraphic meta hash angle 1 metahashoverlay 45 defineoverlay meta hash left metahashoverlay 45 defineoverlay meta hash horizontal metahashoverlay 180 defineoverlay meta hash right metahashoverlay 90 defineoverlay meta hash vertical As we can see in the definition of the table we can pass settings to the bTABLE command Ac tually we can pass such settings to each command that supports backgrounds or more precisely framed Table 73 is for instance defined as bTABLI bTR bTD background meta hash left meta hash right meta hash linecolor darkyellow left par amp par right eTD bTD background meta hash horizontal meta hash vertical meta hash linecolor darkred horizontal par amp vertical eTD frame off meta hash linewidth 4pt alignemiddle offset 2ex eTR eTABLE The long names are somewhat cumbersome but in that way we can prevent name clashes Also since the METAPOST interface is english the variables are also english Table 7 3 A double hashed table Shapes Symbolsand Buttons Preliminary Version October 27 2000 tan Symbol collections In CONTEXT a symbol can de defined without much coding The advantage of using symbols is that you can redefine them depending on the situati
254. s literally hundreds of improvements would never have been made because I would never have thought of them or perceived why they were important But a system cannot be successful if it is too strongly influenced by a single person Once the initial design is complete and fairly robust the real test begins as people with many different viewpoints undertake their own experiments Douglas R Hostadter ae at ee aspects of the design of years working on a system allowing him to control many T Say Enemy ie ony ar pois nt artificial intelligence and 2 make some comments to clarify E The Concept of a Meta Font p Pose et eraan random text area ones which means that they will be recalculated each page This is rather inefficient when the shapes don t change But using a reusable graphic Preliminary Version October 27 2000 instead would result in only one graphic for both pages Since the layout for the left and right page differs another method is needed Instead of putting the same graphic on the page layer we put two different ones on the left and right page layer defineoverlay left page useMPgraphic left page defineoverlay right page useMPgraphic right page setupbackgrounds leftpage background left page setupbackgrounds rightpage background right page Now we only have to split the previously defined graphic
255. s defined as an internal variable we have to use interim to overload its value Because u is a rather commonly used scratch variable we don t save its value Preliminary Version October 27 2000 A few Watch how we use u as the loop step In spite of what you eyes tell you this graphic only has two explicit color directives both being 50 black In the next example we will use some real colors Figure 13 3 simultaneous contrast effect In figure 13 3 the small squares in the center of each colored pair of big squares have the same shade but the way we perceive them is influenced by their surroundings Both set of squares are defined using usable graphics The top squares are defined as startuseMPgraphic second includeMPgraphic first fill fullsquare scaled siz withcolor topshade fill fullsquare scaled delta withcolor centershade stopuseMPgraphic and the bottom squares are coded as startuseMPgraphic third includeMPgraphic first fill fullsquare scaled siz withcolor bottomshade fill fullsquare scaled delta withcolor centershade stopuseMPgraphic Because both graphics share code we have defined that code as a separate graphic that we in clude The only point of interest in this definition is the fact that we let METAPOST interpolate between the two colors 5 startuseMPgraphic first
256. s macro has an educational purpose we will add some labels to the points that we use However generating these labels is optional and controlled by a boolean boolean show labels show labels false The macro accepts four pair of coordinates that determine the central four sided shape All of them are expressions Preliminary Version October 27 2000 Welcome lomer amp gosr 223 243 244 Figure 11 The problem def draw problem expr Yr 5 beginfig n We did not yet discuss the beginfig macro In a mETRPOST file you can put many graphics Each graphic is surrounded by beginfig and endfig The number here the variable n will become the prefix of the output file Because we want to call this macro more than once we have to save the locally used values Instead of declaring local variables one can hide their use for the outside world In most cases variables behave global If we don t save them the next call will lead to errors due to conflicting equations We can omit the grouping commands because we wrap the graphic in a figure and figures are grouped already We will use the predefined z variable or actually a macro that returns a variable This variable has two components an x and y coordinate So we don t save z but the related variables x and y save x b d e f h We draw four squares and inst
257. s was by Edward H Adelson of MIT and we will use a few of his example graphics in our exploration to what extend METAPOST can be of help in those disciplines Since such graphic normally occur in typeset documents we will define them in the document source Figure 13 2 White s illusion Unless you belong to the happy few whose visual capabilities are not distorted by neural opti mizations in figure 13 2 the gray rectangles at the left look lighter than those on the right Alas you can fool yourself but METAPOST does not cheat This graphic referred to as White s illusion is defined as follows startbuffer interim linecap butt numeric u u pickup pencircle scaled 5u for i 1u step u until 5u draw 0 i 5u i endfor for i 2u step u until 4u draw u i 2u i withcolor 5white draw 3u i 4u i shifted 0 5u withcolor 5white endfor stopbuffer Watch how we include the code directly We have packaged this graphic in a buffer which we include as a floating figure placefigure here fig tricked 1 White s illusion processMPbuf fer When passed to METAPOST this code is encapsulated in its beginfig and endfig macros and thereby grouped But any change to a variable that is not explicitly saved migrates to the outer level In order to prevent all successive graphics to have butt d linecaps we have to change this line characteristic locally Because 1inecap i
258. separated list of variables This list serves two purposes First this list is used to create a unique profile for the graphic This means that when we change the value of a variable a new graphic is generated that reflects the change A second purpose of the list is to convert data structures into METAPOST ones especially dimensions and colors The graphic itself is not that spectacular We use amp because we don t want smooth connections defineblank EnglishRule medium def EnglishRule startlinecorrection EnglishRule setlocalhsize noindent reuseMPgraphic EnglishRule stoplinecorrection When setting the variables we used localhsize This variable is set by setlocalhsize We need to use noindent a rather familiar primitive that we use here to start non indent ed paragraph being the graphic The line correction is needed to get the spacing around the rule graphic right We pass a blank skip identifier that is mapped to a convenient medium skip Preliminary Version October 27 2000 7 2 Why is this called English line startnarrower EnglishRule Is it because they cannot draw a straight one This could be true after a few strong beers but then how do Germans draw a line EnglishRule stopnarrower As expected the rule adapts itself to the current width of the text The height
259. separation of any of these four components would have hurt TEK significantly If I had mot participated fully in all these activities literally hundreds of improvements would never have been made because I would never have thought of them or perceived why they were important But a system cannot be successful if it is too strongly influenced by a single person Once the initial design is complete and fairly robust the real test begins as people with many different viewpoints undertake their own experiments Douglas R Hostadter Donald Knuth has spent the past several years working on a system allowing him to control many aspects of the design of his forthcoming books from the typesetting and layout down to the very shapes of the letters Seldom has an author had anything remotely like this power to control the final appearance of his or her work Knuth s TX typesetting system has become well known and available in many countries around the world By contrast his weraranr system for designing families of typefaces has not become as well known or available In his article The Concept of a Meta Font Knuth sets forth for the first time the underlying philosophy of verneonr as well as some of its products Not only is the concept exiting and clearly well executed but in my opinion the article is charmingly written as well However my overall enthusiasm for Knuth s idea and article there are some points in it that I feel might be taken w
260. size red green blue save r g b rr gg bb cc mm yy save b_g g_r g_b save radius path r g b rr bb gg cc mm yy pair b_r g_r numeric radius radius 3cm pickup pencircle scaled radius 20 g b fullcircle scaled radius shifted 0 radius 4 rotatedaround origin 15 drawarrow withcolor red g g rotatedaround origin 135 drawarrow g withcolor green b rotatedaround origin 255 drawarrow b withcolor blue b r b intersectionpoint r draw b r bg b intersectionpoint g draw b g g_r reverse g intersectionpoint r draw r g b reverse g intersectionpoint b draw g b bb cutafter bb bb cutbefore bg drawarrow bb gg cutbefore gg gg cutafter drawarrow gg rr r cutbefore g r amp cutafter drawarrow rr cc b cutbefore cc cutafter drawarrow br yy g cutbefore g yy yy cutafter b drawarrow rg mm cutbefore g r amp cutafter br drawarrow gb bb gg Ir reverse bb cycle gg bb rotatedaround origin 120 rr bb rotatedaround origin 240 cc mm CC reverse yy cycle yy CC rotatedaround origin 120 mm cc rotatedaround origin 240 fill fullcircle scaled radius withcolor white Preliminary Version October
261. spec macros that support special features beginfig 1 fill fullcircle scaled 5cm withcolor red a graphic endfig end Don t forget the semi colons that end the statements If the file is saved as yourfile mp then the file is processed by mpost yourfile The results are available in yourfile 1 be viewed with GHOSTSCRIPT You don t need to close the file so reprocessing is very convenient Alternatively you can use CONTEXT In that case a simple file looks like starttext startuseMPgraphic dummy fill fullcircle scaled 5cm withcolor red stopuseMPgraphic useMPgraphic dummy stoptext If the file is saved as yourfile tex then you can produce a DVI file with texexec yourfile A PDF file viewable in ACROBAT or GHOSTVIEW is produced with texexec pdf yourfile Depending on how your system is set up CONTEXT will run metaPost during the TEK run or after wards If you want to process a METAPOST file separately using TEXEXEC you should say texexec mptex yourfile mp This is the preferred way when a graphic contains directives btex cum suis or when the METRPOST file is generated by CONTEXT We will use lots of color Don t worry if your red is not our red or your yellow does not match ours We ve made color definitions to match the overall design of this document but you should feel free to use any color of choice in the upcoming examples By default CONTEXT has turned its co
262. t TeX tt offset l1pt framed offset 2pt TeX tt offset 2pt N ramed offset 4pt TeX tt offset 4pt framed offset 3pt TeX tt offset 3pt framed frameoffset 3pt TeX tt frameoffset 3pt framed backgroundoffset 3pt TeX tt backgroundoffset 3pt stopcombination oss e SS offset none offset overlay offset 0pt offset lpt offset 2pt offset 4pt offset 3pt frameoffset 3pt backgroundoffset 3pt Figure 4 1 The three offsets As the first row in figure 4 1 demonstrates instead of a value one can pass a keyword The overlay keyword implies that there is no offset at all and that the lines cover the content With none the frame is drawn tight around the content When the offset is set to Opt or more the text is automatically set to at least the height of a line You can turn this feature of by saying strut off More details can be found in the CONTEXT manual In figure 4 2 we have set offset to 3pt frameoffset to 6pt and backgroundoffset to 9pt Both the frame and background offset are sort of imaginary since they don t contribute to the size of the box layout Preliminary Version October 27 2000 4 2 4 3 ruledhbox framed offset 3pt frameoffset 6pt backgroundoffset 9pt background screen backgroundscreen 85 Welcome the hall of frame Welcome in the hall of frame Figure 4 2 The three offsets Over
263. t Watch the difference between the previous and the next path z0 z21 22 23 cycle It is also possible to combine two paths into one that don t have common head and tails First we define an open path 2 22 i z0 z3 zl cycle Preliminary Version October 27 2000 With buildcycle we can combine two path into one buildcycle z0 zl1 z2 z0 z3 zl cycle We would refer readers to the METAFONT book and the METAPOST manual for an explanation of the intricacies of the buildcycle command It is an extremely complicated command and there is just not enough room here to do it justice We suffice with saying that the paths should cross at least once before the buildcycle command can craft a combined path from two given paths We encourage readers to experiment with this command In order to demonstrate another technique of joining paths we first draw a few strange paths The last of these three graphics demonstrates the use of soft join 20 21 22 3 20 21 22 3 Watch how soft join removes a point in the process of smoothing a connection The smoothness is accomplished by adapting the control points of the neighbouring points in the appropriate way 20 21 softjoin z2 z3 Preliminary Version October 27 2000 Once a path is known you can cut off a slice of it We will demonstrate a few alternative ways of doing s
264. t a length was requested meant that the solution should be sought in using the primitives and macros we introduced a few paragraphs before Say that we want to call for such an arrow as follows path p p fullcircle scaled 3cm pair q point 4 along pickup pencircle scaled 2mm draw p withcolor 625white drawarrow somearrow p q 2cm withcolor 625red draw q withcolor 625yellow Because we want to follow the path we need to construct the arrow from this path Therefore we first reduce the path by cutting off the part before the given point Next we cut off the end of the resulting path so that we keep a slice that has the length that was asked for Since we can only cut at points we determine this point using the arctime primitive to METAPOST Preliminary Version October 27 2000 vardef somearrow expr pat loc len save path p p pat cutbefore loc p cutafter point arctime len of p of p enddef By using a vardef we hide the intermediate assignments Such vardef is automatically sur rounded by begingroup and endgroup so the save is local to this macro When processed this code produces the following graphic This graphic shows that we need a bit more control over the exact position of the arrow It would be nice if we could start the arrow at the point or end there or center the arrow around the point Therefore the real im
265. t from the viewing or printing device When fonts are used a METAPOST file is not self contained This means that the postprocess ing program has to deal with the fonts In CONTEXT the special driver and PDFTEK support is considered as such takes care of this We will discuss text related issues in chapter 1 12 Special effects like shading are supported by dedicated METAPOST modules These are includ ed in the CONTEXT distribution and will be discussed later in chapter 8 Preliminary Version October 27 2000 Embedded rapphies Figure3 4 A silly figure demonstrating that stand alone graphics can be made Since METRPOST supports color an embedded graphic can be rather colorful However when color support is disabled or set up to convert colors to gray scales CONTEXT will convert the colors in the graphic to gray scales You may wonder what the advantage is of weighted gray conversion Figure 3 5 shows the difference between natural colors weighted gray scaled and straightforward non weighted gray 506 full color weighted gray linear gray Figure3 5 The advantage of weighted gray over linear gray When we convert color to gray we use the following formula This kind of conversion also takes place in black and white televisions 30r 59g 11b Preliminary Version October 27 2000 4 1 Enhancing the layout One of the most powerful an
266. t will try to break this paragraph into lines When this is done the result is flushed and after that TEK will check if a page should be split off As a result we can hardly predict how a document will come out Therefore when we want graphics to adapt themselves to this text we have to deal with this asynchronous feature of TEK in a rather advanced way Before we present one way of dealing with this complexity we will elaborate on the nature of such graphics When entered the world of typesetting desktop printers were not that common let alone color desktop printers But times have changed and nowadays we want color and graphics if possible integrated in the text To accomplish this several options are open 1 Usea backend that acts on the typeset text this is the traditional way using specials to embed directives in the DVI output file 2 Use the power of a second language and pass snippets of code to the backend which takes care of proper handling of those snippets impressive results are booked by passing POSTSCRIPT to the DvI file 3 Extend Tex in such a way that TEK itself takes care of these issues this is the way works The first method is rather limited although for business graphics acceptable results are booked The second method is very powerful but hardly portable since it depends on the DVI to POSTSCRIPT postprocessor But what about the third method There has been some reluctance to divert from trad
267. te path bb bboxmargin Opt bb bbox currentpicture draw bb withpen pencircle scaled 1pt withcolor 625red The resulting graphic has the bounding box of the fill Note how the path because it is stroked with a 5cm pen extends beyond the border of the bounding box The way this image shows up depends on the viewer settings you use to render the graphic For example in GHOSTVIEW if you disable clipping to the bounding box only the positive quadrant of the graphic is shown Further if you enable clipping to the bounding box this image will look exactly like the previous image created with the fill command In many cases it may be best to avoid the filldraw command Preliminary Version October 27 2000 From the previous examples you can deduce that the following alternative results in a proper bounding box pickup pencircle scaled 5cm path p p unitsquare xscaled 8cm yscaled lcm fill p withcolor 625white draw p withcolor 625white path bb bboxmargin Opt bb bbox currentpicture draw bb withpen pencircle scaled lpt withcolor 625red The CONTEXT distribution comes with set of 5 modules one of which contains the drawfill macro which provides the outer bounding box We will demonstrate its use in an other more complicated example picture finalpicture finalpicture nullpicture numeric n 0 bboxmargin Opt pickup pe
268. te the dimensions of the resulting graphic Putting something in such a ruled box is often a quick way to test spacing Figure 8 4 A quarter circle applied to a cows head Although a clip path definition can contain any METRPOST command even graphics it must con tain at least one clipping path The first one encountered in the resulting graphic is used In the example we used a path that is built out of three subpaths 0 h w h down 1eft 0 0 cycle We start in the top left corner and draw a straight line Next we draw a curve to the origin Directives like down and right force the curve in a certain direction With cycle we close the path Because we use this path as a clipping path we use clip instead of draw or fill Clipping as such is not limited to graphics Take for instance the text buffer startbuffer sample framed align middle width 4cm background screen frame off A METAPOST clip is not the same as a video clip although we can use METAPOST to produce a video clip stopbuffer We can call up such a buffer as if it were an external figure Figure 8 5 shows the result This time we use a different clip path startMPclip text clip clip currentpicture to fullcircle shifted 5 5 xscaled width yscaled height stopMPclip To load a buffer we have to specify its name and type as in placefigure here fig clipped text 1 A clipped buffer text clip
269. tex bfd 1 etes The process is iterated by handletokens for each character of the text MetaPost is Fun Before we typeset the text now available in pieces in pic in a circle we will first demonstrate what they look like You may like to take a look at the file mpgraph mp to see what is passed to METRPOST startMPdrawing pair len len origin for i 1 upto n draw pic i shifted len draw boundingbox pic i shifted len withpen pencircle scaled 25pt withcolor red len lrcorner pic i xpart llcorner pic i 0 endfor stopMPdrawing We can call up this drawing with getMPdrawing but first we inform the compiler that our METAPOST drawing is completed MP drawingdonetrue getMPdrawing This results in MetaPost is Fun Compare this text with the text as typeset by TEK MetaPost is Fun and you will see that the text produced by METAPOST is not properly kerned When putting charac ters after each other TEK uses the information available in the font to optimize the spacing between characters while METAPOST looks at characters as separate entities But since we have stored the Preliminary Version October 27 2000 Typesetting optimal spacing in 1en we can let METAPOST do a better job Let s first calculate the correction needed startMPdrawing for i 1 upto n wid i abs
270. the bounding box and origin swappointlabels true path p p fullcircle xscaled 4cm yscaled 3cm drawarrowpath p drawcontrollines p drawpoints p drawcontrolpoints p drawpointlabels p drawboundingbox p draworigin In this example we have set swappointlabels to change the place of the labels You can set the variable originlength to tune the appearance of the origin Preliminary Version October 27 2000 You can pass options directly like you do with draw and fill Those options override the defaults Here we used the options path p p fullcircle xscaled 6cm yscaled 3cm rotated 15 drawarrowpath p drawcontrollines withcolor 625red drawpoints withcolor 625yellow p p drawcontrolpoints p withcolor 625yellow p p drawpointlabels withcolor 625yellow drawboundingbox draworigin withcolor 625red Sometimes it makes sense to draw a simple coordinate system and for that purpose we have three more macros They draw axis and tickmarks drawticks unitsquare xscaled 4cm yscaled 3cm shifted 1cm 1cm The system drawn is based on the bounding box specification of the path passed to the macro You can also draw one axis using drawxticks or drawyticks Here we show the previous command By default the ticks are placed at 5cm distance but you can change this by setting tickstep to a different value tickstep lcm ticklength 2mm drawticks fullsquare xscaled
271. tifier like demo circle ora comma separated list of those his text is overlayed The framed command automatically draws a ruled box which can be quite useful when debug ging a graphic However in this case we want to turn the frame off framed background demo circle frame off This text is overlayed This text is overlayed Preliminary Version October 27 2000 _Bhhan ingthelayout In this case it would have made sense to either set the offset to a larger value or to set backgroundoffset In the latter case the ellipse is positioned outside the frame The difference between the three offsets of fset frameoffset and backgroundoffset is demonstrated in figure 4 1 While the offset is added to the natural or specified dimensions of the content of the box the other two are applied to the frame and background and don t add to the dimensions In the first row we only set the o set while in the second row the text offset is set to 3pt When not specified the of fset has a comfortable default value of 25ex some 25 of the height of an x setupframed width 3 textwidth background demo circle startcombination 3 3 framed offset none TeX tt offset none N ramed offset overlay TeX tt offset overlay framed offset 0pt TeX tt offset 0pt framed offset lp
272. tionalgraphics 32 final state the better we can act upon it Think of graphics on the first page that depend on the content of the last page br as in this paragraph backgrounds that depend on the typeset text It may be clear now that we need some positional information in order to provide features like the one shown here The fact that we will act upon in a second pass simplifies the task although it forces us to store the positional information in some place between runs This may look uncomfortable at first sight but it also enables us to store some additional information Now why is that needed A position has no dimensions it s just a place somewhere on the page In order to do tricks like shown here we also need to know the height and depth of lines at a specific point as well as the width of the box es we re dealing with In the encircled examples the dimensions of the box following the positional node are stored along with the position In the background example we store the current height and depth of the strut an imaginary character with maximum height and depth and no width along with the current text width In order to process the graphics we tag each point with a name so that we can attach actions to those points In fact they become trigger points As we will demonstrate we also need to store the current page number This brings the data stored with a point to lt identifi
273. tioned halfway point 2 and 3 It is clear that unless you know exactly how the path is constructed other methods should be available A specific point on a path is accessed by point of butthe next example demon strates two more alternatives Preliminary Version October 27 2000 path p p fullcircle scaled 3cm xscaled 2 pickup pencircle scaled 5mm draw p withcolor 625white draw point 3 of p withcolor 625red draw point 6 along p withcolor 625yellow draw point 3cm on p So in addition to on to specify a point by number in METAPOST terminology called time we have along to specify a point as fraction of the path and on to specify the position in a dimension The on and along operators are macros and can be defined as primarydef len on pat arctime len of pat of pat enddef primarydef pct along pat arctime pct arclength pat of pat of pat enddef These macros introduce two new primitives arct ime and arclength While arctime returns a number denoting the time of the point on the path arclength returns a dimension When mathematicians draw parametric curves they frequently need to indicate the direction of motion I often have need of a little macro that will put an arrow of requested length anchored at a point on the curve and bending with the curve in the direction of motion When David Arnold asked me how this could be achieved the fact tha
274. to be ASCII conforming If this is not the case you must make sure that the encoding of the font that you use matches your expectations In this respect the TEK based method is more safe because when set up properly normally knows what it is dealing with 113 Linear equations In the previous sections we used the assignment operator to assign a value to a variable Although for most of the graphics that we will present in later chapters an assignment is appro priate specifying a graphic in terms of expressions is not only more flexible but also more in the spirit of the designers of METAFONT and METAPOST The METAFONT book and METAPOST manual provide lots of examples some of which involve math that we don t consider to belong to everyones repertoire But even for non mathematicians using expressions can be a rewarding challenge The next introduction to linear equations is based on my first experiences with METAPOST and involves a mathematical problem someone chalenged me with It did not take me much time to see that a sort of graphical proof was far more easy than some proof with a lot of sin this and cos that and long forgotten formulas I was expected to prove that the angle between the lines connecting the mid points of four squares drawn upon the four sides of a box is ninety degrees see figure 1 1 Because we have seen most of the METAPOST commands and features we will package the solution in a macro Also because thi
275. turned by this macro the segment has a length of 1 base point This macro has a wide range of applications but some basic knowlegde of vector algebra is handy The following lines of METAPOST code demonstrate the basics behind unitvectors pair uv pickup pencircle scaled 1mm autoarrows true draw fullcircle scaled 2cm withcolor 625red for 10 35 40 20 85 15 draw origin i dashed evenly withcolor 625white drawarrow origin unitvector i scaled 1cm withcolor 625yellow endfor draw origin withcolor 625red The circle has a radius of 1cm and the three line segments are drawn from the origin in the direction of the points that are passed as arguments Because the vector has length of 1 we scale it to the radius to let it touch the circle By setting autoarrows we make sure that the arrowheads are scaled proportionally to the linewidth of 1 mm Preliminary Version October 27 2000 An application of this macro is drawing the angle between two lines In the METAPOST manual you can find two macros for drawing angles mark angle and mark rt angle You may want to take a look at their definitions before we start developing our own alternatives The previous graphic demonstrates what we want to accomplish a circular curve indicating the angle between two straight lines The lines and curve are drawn with the code pair b 2em 1cm b
276. ty applications We now have the framework of an angle drawing macro ready and can start working placing the label vardef anglebetween expr endofa endofb common length str save curve where path curve numeric where where turningnumber common ndofa ndofb cycle curve unitvector endofa common endofa common rotated where 90 unitvector endofb common scaled length shifted common draw thefreelabel str point 5 of curve common withcolor black curve enddef The macro thefreelabel is part of MetaFun and is explained in detail in section 13 2 This macro tries to place the label as good as possible without user interference pair a a 2cm 1cm drawarrow origin a pair 3cm 1cm drawarrow origin b drawarrow anglebetween a b origin l1cm btex alpha etes withcolor 625red Instead of a picture we may also pass a string but using by means of btex etex often leads to better results Because most cases we want the length to be consistent between figures because passing two paths is more convenient than passing three points the final definition looks slightly differ ent numeric anglelength anglelength 20pt 9 vardef anglebetween expr a b str path path string save endofa endofb common curve where pair endofa endofb common path curve numeric where endo
277. un the examples A simple document looks like starttext Some text stoptext You can process this document with the PERL based command line interface to CONTEXT If the source code is embedded in the file mytext tex you can say texexec pdf mytext As an alternative to pdf you can explicitly set the output driver in your document setupoutput pdftex starttext Some text and or graphics stoptext Yet another alternative is interface english output pdftex starttext Some text and or graphics stoptext Here the interface directive tells TEXEXEC that it should force the english user interface We will use color and since traditionally is rather unaware of color this feature is turned off by default so if you want to see color you should type setupcolors state start starttext Some color blue text and or color green graphics stoptext As an alternative you can run like Preliminary Version October 27 2000 Embedded graphies 32 texexec pdf color mytext In later chapters we will occasionally see some more CONTEXT commands show up If you want to know more about what CONTEXT can do for you we recommend the beginners manual and the reference manual as well as the manual that comes with External graphics Since has no graphic capabilities built in a graphic is referred to as an external figure
278. uniqueMPgraphic right or wrong setupbuttons background button frame of hbox button previous button next button index button table of contents previouspage quad nextpage quad index quad content oa a The buttons will look like Compare these with Here the graphic was defined as startuniqueMPgraphic wrong or right pickup pencircle scaled 3pt path p p unitsquare xscaled overlaywidth yscaled overlayheight fill p withcolor 8white draw p withcolor 625red stopuniqueMPgraphic The last class of embedded graphics are the runtime graphics When a company logo is defined in a separate file mylogos mp you can run this file by saying startMPrun input mylogos stopMP run Preliminary Version October 27 2000 Erie ded Braphics The source for the logo is stored in a file named mylogos mp beginfig 21 draw fullsquare withcolor 625red draw fullsquare rotated 45 withcolor 625red picture cp cp currentpicture def copy addto currentpicture also cp enddef copy scaled 9 withcolor 625white copy scaled 7 withcolor 625yellow copy scaled 6 withcolor 625white copy scaled 4 withcolor 625red copy scaled 3 withcolor 625white fill fullcircle scaled 2 withcolor 625yellow currentpicture currentpicture scaled 50 endfig end In this example the resu
279. ure expression option list addto picture variable contour path expression option list addto picture variable doublepath path expression option list option list empty drawing option option list drawing option witcolor color expression withpen pen expression dashed picture expression APOST syntax Preliminary Version October 27 2000 drawing command draw picture expression option list fill type path expression option list fill type gt fill draw filldraw drawfill unfill undraw unfilldraw drawarrow drawdblarrow cutdraw tracing command gt tracingall loggingall tracingnone if test if boolean expression balanced tokens alternatives fi alternatives empty else balanced tokens elseif boolean expression balanced tokens alternatives loop loop header loop text endfor loop header for symbolic token progression for symbolic token for list for symbolic token within picture expression forsuffixes symbolic token suffix list forever progression numeric expression upto numeric expression numeric expression downto numeric expression numeric expression step numeric expression until numeric expression for list expression for list expression Prelimina
280. use METRPOST This program can be found in most distributions and the binary is called mpost It uses a few auxiliary programs to prepare files that are passed on to TEX and if you can locate the METRPOST binary you may assume that its companion programs are around somewhere too When you use the macros that come with CONTEXT you may wish to package them in a mem ory dump file that can be loaded fast You can do that by the following command mpost ini metafun You have to move the resulting mem file to the location where METAPOST expects to find it If you want to be sure that everything is done correctly you may try texexec mak alone metafun Depending on how you want to process your graphic in the file cont sys tex which you can put in a place where CONTEXT can find it you may set one or more of the following switches runMPgraphicstrue process graphics at run time runMPTEXgraphicstrue atrun time process graphics that contain text that is to be typeset by by calling TEXEXEC recycleMPslotstrue use a less temporary files as possible useMETAFUNformattrue useaMetaFun format file instead of loading all modules separate ly It makes much sense to process the graphics directly because then will know the right dimen sions at once if you process the graphics afterwards Tex will run much faster but additional runs may be needed The installation of Tpx is not trivial Fortunately
281. ut can use one of the layout areas instead like text text or text leftmargin setupframedtexts FunnyText backgroundcolor lightgray framecolor darkred rulethickness 2pt offset bodyfontsize before blank big medium after blank big width textwidth There is one drawback when your left and rightmargin have different dimensions the text will be scaled differently on odd and even pages Normally this is no problem for a draft As an alternative you can use the setuptexts command and wraps the graphic in a box with the right dimensions using code like startuniqueMPgraphic copyright picture p p btex COPYRIGHT etex rotated 90 setbounds p to boundingbox p enlarged 1 draw p withcolor 8white xyscale_currentpicture the leftmarginwidth the textheight stopuniqueMPgraphic setuptexttexts margin uniqueMPgraphic copyright Preliminary Version October 27 2000 6 3 The graphic goes into the outer margin The second argument can be used to put something in the inner margin Multiple overlays You can stack overlays Consider the next case where we assume that you have enabled interac tion support using setupinteraction state start setupbackgrounds page background color nextpage backgroundcolor darkyellow Here the page gets a colored background and a hyperlink to the next page previously defined by
282. w problem 45 0 0 1 0 do draw problem 30 0 0 1 0 do draw problem 31 0 0 0 8 do draw problem 32 0 0 0 6 do draw problem 33 0 0 0 4 do draw problem 34 0 0 0 2 do draw problem 35 0 0 0 0 We already showed a picture with coordinates This picture was generated using some alternative coordinates def do draw problem expr n i j draw problem 4000 n 400pt 400pt 400pt 600pt i 400pt 600pt 550pt 600pt jL 400pt 400pt 550pt 400pt enddef Preliminary Version October 27 2000 1 0 1 0 0 8 1 0 0 6 1 0 0 0 1 0 0 0 0 8 0 0 0 6 0 0 0 4 0 0 0 2 0 0 0 0 Figure 1 2 The solution Preliminary Version October 27 2000 show labels true do draw problem 50 0 6 1 0 As soon as you can see a clear pattern in some code it s time to consider using loops In the previous code we used semi indexes like 12 in z12 In this case 12 does reflect something related to square 1 and 2 but in reality the 12 is just twelve This does not harm our expressions A different approach is to use a two dimensional array In doing so we can access the variables more easily using loops If we omit the labels and angle macro the previously defined macro can be reduced a lot def draw problem expr n p d r S number and 4 positions beginfig n
283. we hide the still remaining overlapping part of the line 2 This problem was posted at the coNTEXT mailing list by Marc van Dongen Preliminary Version October 27 2000 29 Directions Quite often you have to tell METAPOST in what direction a line should be drawn A direction is specified as a vector There are four predefined vectors up down left right These are defined as follows pair up down left right up down 0 1 right left 1 0 We can use these predefined pairs as specification and in calculations n dotlabel top dotlabel bot dotlabel lft dotlabel rt up up lcm down down lcm left left lcm right right lcm drawoptions withpen pencircle scaled 25mm withcolor 625 red drawarrow origin up lcm drawarrow origin down lem drawarrow origin left lcm drawarrow origin right lcm up left right down This graphic can also be defined in a more efficient but probably more cryptic way The next definition demonstrates a few nice tricks Instead of looping over the four directions we loop over their names Inside the loop we convert these names or strings into a pair by scanning the string using scantokens freedotlabel macro is part of MetaFun and takes three arguments a label string or alternatively a picture a point location and the center of gravity
284. we use METAPOST which we also use for handling the title The graphic is defined as follows startuseMPgraphic FunnyFrame picture p numeric w h o p textext rt MMPstring FunnyFrame w OverlayWidth h OverlayHeight o BodyFontSize p shifted 20 h ypart center p draw p drawoptions withpen pencircle scaled lpt withcolor 625red draw 20 h 0 0 0 w 0 w h xpart urcorner p h draw boundingbox p withcolor 625red setbounds currentpicture to unitsquare xyscaled w h stopuseMPgraphic The macros that use this graphic combine some techniques of defining macros using predefined CONTEXT classes and passing information to graphics Ndefineoverlay FunnyFrame NuseMPgraphic FunnyFrame Ndefineframedtext FunnyText frame off background FunnyFrame def StartFrame startFunnyText def StopFrame stopFunnyText def FrameTitle 1 setMPtext FunnyFrame hbox spread lem hss strut 1 hss setMPtext FunnyFrame There is a little bit of low level TEK code involved like an horizontal box hbox that stretches one em space beyond its natural size spread lem with a centered text to times hss We could also have taken care of the offset in the graphic itself _Bhhancing tHe layout Preliminary Version October 27 2000 In the previous graphic we calculated the big rectangle taking the small one
285. will become a sequence of glyphs MP The same string typeset by Tpx showed up as this string will become a sequence of glyphs The following metarost features are not covered by the METAPOST manual but most of them are discussed in the appendix of the graph package written by John Hobby It is possible to disassemble a picture by means of a special for loop using the within specifier The following code walks over a picture and draws the components with their bounding boxes Aew nior details Preliminary Version October 27 2000 for i within currentpicture draw boundingbox i withcolor 625yellow endfor We can use the disassemble loop feature to look into the previously shown example text this string will become a sequence of glyphs MP this string will become sequence of glyphs The second line is typeset by TEK The resulting DVI code is converted into a series of pictures which METAPOST pastes into one picture You may also notice that in the set of pictures that origi nate in the space is replaced by a shift this is because knows no space An interesting aspect of this loop over a picture feature is that it can provide your insight in how is composing a paragraph We thrive in information thick worlds because of our marvelous and everyday capacity to select edit single out st
286. xecuted the macro is expanded Thus the actual content of this com mand becomes draw somepath xscaled lcm yscaled 4cm withcolor red If we had added a semi colon after s 2 we could not have set the color because the semicolon ends the statement The draw expects a path so the macro can best return one A macro can take one or more arguments as in Preliminary Version October 27 2000 def drawrandomscaledpath expr p s draw p xscaled s 2 yscaled s 2 enddef When using this macro it is expected that you will pass it two parameters the first being a path the second a numeric scale factor drawrandomscaledpath fullsquare 3cm Sometimes we want to return a value from a macro In that case we must make sure that any calculations don t interfere with the expectations Consider vardef randomscaledpath expr p s numeric r r round 1 uniformdeviate 4 p xscaled s r yscaled s r enddef Because we want to use the same value of r twice we have to use an intermediate variable By using a vardef we hide everything but the last statement It is important to distinguish def macros from those defined with vardef In the latter case vardef macros are not a simple expansion and replacement Rather vardef macros return the value of their last statement In the case of the randomscaledpath macro a path is returned This macro is used in the
287. xpart lrcorner pic i xpart llcorner pic il pos i len i wid i endfor stopMPdrawing This compares well to the text as typeset by TEK MetaPost is Fun We can now use the values in pos to position the pictures according to what considered to be the best relative position NstartMPdrawing for i 1 upto n draw pic i shifted pos il 0 draw boundingbox pic i shifted pos i 0 withpen pencircle scaled 25pt withcolor red endfor stopMPdrawing That this correction is adequate is demonstrated in the next graphic If you look closely you will see that for instance the o is moved to the left under the capital P MetaPost is Fun When we want to position the pictures along a circle we need to apply some rotations espe cially because we want to go clockwise Since we don t want to use complicated math or more advanced metarost code yet we will do it in steps startMPdrawing for i l upto n pic i pic i rotatedaround origin 270 endfor stopMPdrawing 2 We will now center the pictures around the baseline Centering comes down to shifting over half the height of the picture This can be expressed by ypart 5 ulcorner pic i llcorner pic i but different ways of calculating the distance are possible too Typesetting in ver APOST Preliminary Version O
288. zy counter to enhance the rather dull tables system fstusers Atari 104 MSDOS 491 IM LAT LAT at HE LHT LE JT LU OS 2 94 MacOS 57 UNIX 51 9 UAT LHT MIT Jt WINDOWS 642 Jut LAT WH IHI JH IHT VAT HT 11 Table 71 Operating system n 106 Table 71 demonstrates how scratch numbers can be used An interesting side effect is that when you look long enough to these kind of graphics it looks like the lines are no longer horizontal This table is defined as follows symbols and bution sm Preliminary Version October 27 2000 Nstarttabulate l c l1 NC system NC NG NC users NC NR HL NC Atari NC 10 4 NC useMPgraphic fuzzycount n 11 NC NR NC MSDOS NC 49 1 NC useMPgraphic fuzzycount n 52 NC NR NC 05 2 NC 79 4 ANC useMPgraphic fuzzycount n 10 NC NR NC MacOS NC 75 7 NC useMPgraphic fuzzycount n 6 NC NR NC UNIX NC 51 9 ANC useMPgraphic fuzzycount n 55 NC NR NC WINDOWS NC 64 2 NC useMPgraphic fuzzycount n 68 NC NR HL stoptabulate You will notice that we pass a variable to the graphic using a second argument We can access this variable with MPvar The graphic is defined as usable graphic because we want to generate a unique random one each time startuseMPgraphic fuzzycount begingroup save
Download Pdf Manuals
Related Search
Related Contents
取扱説明書 - エー・アンド・デイ JetNet 4706_series_User Manual v1.02 As abordagens sobre população na Geografia Brasileira 不均一系微小粒子の 生物活性測定システムの開発 User Manual - Innovative Energies Ltd Manual de Usuario de la ENRIAP 9” BAND SAW Copyright © All rights reserved.
Failed to retrieve file