metafun-embedding.tex /size: 37 Kb    last modification: 2023-12-21 09:43
1% language=us runpath=texruns:manuals/metafun
2
3\startcomponent metafun-embedding
4
5\environment metafun-environment
6
7\startchapter[reference=sec:embedding,title={Embedded graphics}]
8
9\startintro
10
11In addition to the \type {beginfig}||\type {endfig} method, there are other ways
12to define and include a \METAPOST\ graphic. Each method has its advantages and
13disadvantages.
14
15In the previous chapter we were still assuming that the graphic was defined in
16its own file. In this chapter we will introduce the interface between \CONTEXT\
17and \METAPOST\ and demonstrate how the definitions of the graphics can be
18embedded in the document source.
19
20\stopintro
21
22\startsection[title={Getting started}]
23
24\index{running}
25\index{processing}
26
27From now on, we will assume that you have \CONTEXT\ running on your platform.
28Since \PDF\ has full graphics support, we also assume that you use \LUATEX\ in
29combination with \CONTEXT\ \MKIV, although most will also work with other engines
30and \MKII. Since this document is not meant as a \CONTEXT\ tutorial, we will
31limit this introduction to the basics needed to run the examples.
32
33A simple document looks like:
34
35\starttyping
36\starttext
37  Some text.
38\stoptext
39\stoptyping
40
41You can process this document with the \LUA\ based command line interface to
42\CONTEXT. If the source code is embedded in the file \type {mytext.tex}, you can
43say:
44
45\starttyping
46context mytext
47\stoptyping
48
49We will use color, and in \MKIV\ color is enabled by default. If you don't want
50color you can tell \CONTEXT, so
51
52\starttyping
53\setupcolors[state=stop]
54\starttext
55  Some \color[blue]{text} and/or \color[green]{graphics}.
56\stoptext
57\stoptyping
58
59comes out in black and white.
60
61In later chapters we will occasionally see some more \CONTEXT\ commands show up.
62If you want to know more about what \CONTEXT\ can do for you, we recommend the
63beginners manual and the reference manual, as well as the wiki pages.
64
65\stopsection
66
67\startsection[title={External graphics}]
68
69\index {graphics+external}
70
71Since \TEX\ has no graphic capabilities built in, a graphic is referred to as an
72external figure. A \METAPOST\ graphic often has a number as suffix, so embedding
73such a graphic is done by:
74
75\starttyping
76\externalfigure[graphic.123][width=4cm]
77\stoptyping
78
79An alternative method is to separate the definition from the inclusion. An
80example of a definition is:
81
82\starttyping
83\useexternalfigure[pentastar][star.803][height=4cm]
84\useexternalfigure[octostar] [star.804][pentastar]
85\stoptyping
86
87Here, the second definition inherits the characteristics from the first one.
88These graphics can be summoned like:
89
90\starttyping
91\placefigure
92  {A five||point star drawn by \METAPOST.}
93  {\externalfigure[pentastar]}
94\stoptyping
95
96Here the stars are defined as stand||alone graphics, in a file called \type
97{star.mp}. Such a file can look like:
98
99\starttyping
100def star (expr size, n, pos) =
101  for a=0 step 360/n until round(360*(1-1/n)) :
102    draw (origin -- (size/2,0))
103      rotatedaround (origin,a) shifted pos ;
104  endfor ;
105enddef ;
106
107beginfig(803) ;
108  pickup pencircle scaled 2mm ; star(2cm,5,origin) ;
109endfig ;
110
111beginfig(804) ;
112  pickup pencircle scaled 1mm ; star(1cm,8,origin) ;
113  pickup pencircle scaled 2mm ; star(2cm,7,(3cm,0)) ;
114endfig ;
115
116end.
117\stoptyping
118
119This \type {star} macro will produce graphics like:
120
121\startbuffer
122def star (expr size, n, pos) =
123  for a=0 step 360/n until round(360*(1-1/n)) :
124    draw (origin -- (size/2,0))
125      rotatedaround (origin,a) shifted pos ;
126  endfor ;
127enddef ;
128
129for i=5 upto 10 :
130  drawoptions (withpen pencircle scaled 2mm withcolor .625red) ;
131  star(1cm,i,origin shifted (i*2cm,0)) ;
132endfor ;
133\stopbuffer
134
135\startlinecorrection[blank]
136\processMPbuffer
137\stoplinecorrection
138
139But, now that we have instant \METAPOST\ available in \LUATEX, there is no need
140for external images and we can collect them in libraries, as we will see later
141on.
142
143\stopsection
144
145\startsection[title={Integrated graphics}]
146
147\index{graphics+embedded}
148
149An integrated graphic is defined in the document source or in a style definition
150file. The most primitive way of doing this is just inserting the code:
151
152\starttyping
153\startMPcode
154  fill fullcircle scaled 200pt withcolor .625white ;
155\stopMPcode
156\stoptyping
157
158Such a graphic is used once at the spot where it is defined. In this document we
159also generate graphics while we finish a page, so there is a good chance that
160when we have constructed a graphic which will be called on the next page, the
161wrong graphic is placed.
162
163For this reason there are are more convenient ways of defining and using
164graphics, which have the added advantage that you can predefine multiple
165graphics, thereby separating the definitions from the usage.
166
167The first alternative is a {\em usable} graphic. Such a graphic is calculated
168anew each time it is used. An example of a usable graphic is:
169
170\starttyping
171\startuseMPgraphic{name}
172  fill fullcircle scaled 200pt withcolor .625yellow ;
173\stopuseMPgraphic
174\stoptyping
175
176When you put this definition in the preamble of your document, you can place this
177graphic anywhere in the file, saying:
178
179\starttyping
180\useMPgraphic{name}
181\stoptyping
182
183As said, this graphic is calculated each time it is placed, which can be time
184consuming. Apart from the time aspect, this also means that the graphic itself is
185incorporated many times. Therefore, for graphics that don't change, \CONTEXT\
186provides {\em reusable} graphics:
187
188\starttyping
189\startreusableMPgraphic{name}
190  fill fullcircle scaled 200pt withcolor .625yellow;
191\stopreusableMPgraphic
192\stoptyping
193
194This definition is accompanied by:
195
196\starttyping
197\reuseMPgraphic{name}
198\stoptyping
199
200Imagine that we use a graphic as a background for a button. We can create a
201unique and reusable graphic by saying:
202
203\starttyping
204\def\MyGraphic
205  {\startreusableMPgraphic{name:\overlaywidth:\overlayheight}
206      path p ; p := unitsquare
207        xscaled OverlayWidth yscaled OverlayHeight ;
208      fill p withcolor .625yellow ;
209      draw p withcolor .625red ;
210   \stopreusableMPgraphic
211   \reuseMPgraphic{name:\overlaywidth:\overlayheight}}
212\stoptyping
213
214Notice the use of \type {OverlayWidth} and \type {OverlayHeight}. These variables
215are set for each call to \METAPOST. After this we can say:
216
217\starttyping
218\defineoverlay[my graphic][\MyGraphic]
219\button[background=my graphic,frame=off]{Go Home}[firstpage]
220\stoptyping
221
222Say that we have a 30pt by 20pt button, then the identifier will be \type
223{name:30pt:20pt}. Different dimensions will lead to other identifiers, so this
224sort of makes the graphics unique.
225
226We can bypass the ugly looking \type {\def} by using a third class of embedded
227graphics, the {\em unique} graphics.
228
229\starttyping
230\startuniqueMPgraphic{name}
231  path p ; p := unitsquare
232    xscaled OverlayWidth yscaled OverlayHeight ;
233  fill p withcolor .625yellow ;
234  draw p withcolor .625red ;
235\stopuniqueMPgraphic
236\stoptyping
237
238Now we can say:
239
240\starttyping
241\defineoverlay[my graphic][\uniqueMPgraphic{name}]
242\button[background=my graphic,frame=off]{Go Home}[firstpage]
243\stoptyping
244
245A shorter variant is:
246
247\starttyping
248\startuniqueMPgraphic{name}
249  fill OverlayBox withcolor .625yellow ;
250  draw OverlayBox withcolor .625red ;
251\stopuniqueMPgraphic
252\stoptyping
253
254You may wonder why unique graphics are needed when a single graphic might be used
255multiple times by scaling it to fit the situation. Since a unique graphic is
256calculated for each distinctive case, we can be sure that the current
257circumstances are taken into account. Also, scaling would result in incomparable
258graphics. Consider the following definition:
259
260\startbuffer[a]
261\startuseMPgraphic{demo}
262  draw unitsquare
263    xscaled 5cm yscaled 1cm
264    withpen pencircle scaled 2mm
265    withcolor .625red ;
266\stopuseMPgraphic
267\stopbuffer
268
269\typebuffer[a]
270
271Since we reuse the graphic, the dimensions are sort of fixed, and because the
272graphic is calculated once, scaling it will result in incompatible line widths.
273
274\startbuffer[b]
275\hbox \bgroup
276  \scale[width=5cm,height=1cm]{\useMPgraphic{demo}}\quad
277  \scale[width=8cm,height=1cm]{\useMPgraphic{demo}}%
278\egroup
279\stopbuffer
280
281\startlinecorrection[blank]
282\getbuffer[a,b]
283\stoplinecorrection
284
285These graphics were placed with:
286
287\typebuffer[b]
288
289Imagine what happens when we add some buttons to an interactive document without
290taking care of this side effect. All the frames would look different. Consider
291the following example.
292
293\startbuffer[a]
294\startuniqueMPgraphic{right or wrong}
295  pickup pencircle scaled .075 ;
296  fill unitsquare withcolor .8white ;
297  draw unitsquare withcolor .625red ;
298  currentpicture := currentpicture
299    xscaled OverlayWidth yscaled OverlayHeight ;
300\stopuniqueMPgraphic
301\stopbuffer
302
303\typebuffer[a]
304
305Let's define this graphic as a background to some buttons.
306
307\startbuffer[b]
308\defineoverlay[button][\uniqueMPgraphic{right or wrong}]
309\setupbuttons[background=button,frame=off]
310\stopbuffer
311
312\startbuffer[c]
313\hbox
314  {\button {previous}          [previouspage]\quad
315   \button {next}              [nextpage]\quad
316   \button {index}             [index]\quad
317   \button {table of contents} [content]}
318\stopbuffer
319
320\typebuffer[b,c]
321
322The buttons will look like:
323
324\startlinecorrection[blank]
325\setupinteraction[state=start,color=,contrastcolor=]
326\getbuffer[a,b,c]
327\stoplinecorrection
328
329Compare these with:
330
331\startbuffer[a]
332\startuniqueMPgraphic{wrong or right}
333  pickup pencircle scaled 3pt ;
334  path p ; p := unitsquare
335    xscaled OverlayWidth yscaled OverlayHeight ;
336  fill p withcolor .8white ;
337  draw p withcolor .625red ;
338\stopuniqueMPgraphic
339\stopbuffer
340
341\startlinecorrection[blank]
342\getbuffer[a,b]
343\defineoverlay[button][\uniqueMPgraphic{wrong or right}]
344\setupinteraction[state=start,color=,contrastcolor=]
345\getbuffer[c]
346\stoplinecorrection
347
348Here the graphic was defined as:
349
350\typebuffer[a]
351
352The last class of embedded graphics are the {\em runtime} graphics. When a
353company logo is defined in a separate file \type {mylogos.mp}, you can run this
354file by saying:
355
356\starttyping
357\startMPrun
358  input mylogos ;
359\stopMPrun
360\stoptyping
361
362The source for the logo is stored in a file named \type {mylogos.mp}.
363
364\startbuffer
365beginfig(21) ;
366  draw fullsquare            withcolor .625red ;
367  draw fullsquare rotated 45 withcolor .625red ;
368  picture cp ; cp := currentpicture ;
369  def copy = addto currentpicture also cp enddef ;
370  copy scaled .9 withcolor .625white  ;
371  copy scaled .7 withcolor .625yellow ;
372  copy scaled .6 withcolor .625white  ;
373  copy scaled .4 withcolor .625red    ;
374  copy scaled .3 withcolor .625white  ;
375  fill fullcircle scaled .2 withcolor .625yellow ;
376  currentpicture := currentpicture scaled 50 ;
377endfig ;
378end .
379\stopbuffer
380
381\typebuffer
382
383In this example the result is available in the virtual file \type {mprun.21}.
384This file can be included in the normal way, using:
385
386\starttyping
387\externalfigure[mprun.21][width=5cm]
388\stoptyping
389
390\startuseMPgraphic{dummy logo}
391  draw fullsquare            withcolor .625red ;
392  draw fullsquare rotated 45 withcolor .625red ;
393  picture cp ; cp := currentpicture ;
394  def copy = addto currentpicture also cp enddef ;
395  copy scaled .9 withcolor .625white  ;
396  copy scaled .7 withcolor .625yellow ;
397  copy scaled .6 withcolor .625white  ;
398  copy scaled .4 withcolor .625red    ;
399  copy scaled .3 withcolor .625white  ;
400  fill fullcircle scaled .2 withcolor .625yellow ;
401  currentpicture := currentpicture scaled 3cm ;
402\stopuseMPgraphic
403
404\placefigure
405  {The logo is defined in the file \type {mylogos.mp} as
406   figure~21 and processed by means of the \type {mprun}
407   method.}
408  {\useMPgraphic{dummy logo}}
409
410Optionally you can specify a name and an instance. This has the advantage that
411the graphics don't interfere with the regular inline graphics. Here the instance
412used is \type {extrafun} and the name where the run is stored is \type {mydemo}.
413
414\startbuffer
415\startMPrun{extrafun::mydemo}
416    input mfun-mrun-demo.mp ;
417\stopMPrun
418
419\placefigure
420  {An external file can have multiple graphics. Here we show a few
421   images that we used to use on the \PRAGMA\ \CONTEXT\ website.}
422  {\startcombination[2*2]
423     {\externalfigure[mprun:extrafun::mydemo.1][height=6cm]} {downloads}
424     {\externalfigure[mprun:extrafun::mydemo.2][height=6cm]} {links}
425     {\externalfigure[mprun:extrafun::mydemo.3][height=6cm]} {mirrors}
426     {\externalfigure[mprun:extrafun::mydemo.4][height=6cm]} {team}
427   \stopcombination}
428\stopbuffer
429
430\typebuffer
431
432Keep in mind that the whole file will be processed (using the built in library)
433in order to get one graphic. Normally this is no big deal.
434
435\getbuffer
436
437\stopsection
438
439\startsection[title={Using \METAFUN\ but not \CONTEXT}]
440
441\index{graphics+standalone}
442
443If you don't want to use \CONTEXT\ but still want to use \METAFUN, a rather
444convenient method is the following. Create a file that
445
446\starttyping
447\startMPpage
448    % Your mp code goes here. You can use the textext
449    % macro as discussed later to deal with typeset text.
450\stopMPpage
451\stoptyping
452
453When you process that file with the \type {context} command you will get a \PDF\
454file that you can include in any application that can embed a \PDF\ image. In
455this case your exposure to \CONTEXT\ is minimal.
456
457\stopsection
458
459\startsection[title={Graphic buffers}]
460
461\index{graphics+buffers}
462\index{buffers}
463
464In addition to the macros defined in the previous section, you can use \CONTEXT's
465buffers to handle graphics. This can be handy when making documentation, so it
466makes sense to spend a few words on them.
467
468A buffer is a container for content that is to be (re|)|used later on. The main
469reason for their existence is that they were needed for typesetting manuals and
470articles on \TEX. By putting the code snippets in buffers, we don't have to key
471in the code twice, since we can either show the code of buffers verbatim, or
472process the code as part of the text flow. This means that the risk of mismatch
473between the code shown and the typeset text is minimized.
474
475\startbuffer[a]
476\startbuffer
477You are reading the \METAFUN\ manual.
478\stopbuffer
479\stopbuffer
480
481\typebuffer[a]
482
483This buffer can be typeset verbatim using \type {\typebuffer} and processed using
484\type {\getbuffer}, as we will do now:
485
486\blank \getbuffer[a] \blank
487
488An other advantage of using buffers, is that they help you keeping the document
489source clean. In many places in this manual we put table or figure definitions in
490a buffer and pass the buffer to another command, like:
491
492\starttyping
493\placefigure{A very big table}{\getbuffer}
494\stoptyping
495
496Sometimes it makes sense to collect buffers in separate files. In that case we
497give them names.
498
499\startbuffer
500\startbuffer[mfun]
501You are reading the \METAFUN\ manual.
502\stopbuffer
503\stopbuffer
504
505This time we should say \type {\typebuffer[mfun]} to typeset the code verbatim.
506Instead of \TEX\ code, we can put \METAPOST\ definitions in buffers.
507
508\startbuffer
509\startbuffer[graphic]
510draw fullcircle scaled 2cm ;
511\stopbuffer
512\stopbuffer
513
514Buffers can be used to stepwise build graphics. By putting code in multiple
515buffers, you can selectively process this code.
516
517\startbuffer
518\startbuffer[red]
519drawoptions(withcolor .625red) ;
520\stopbuffer
521
522\startbuffer[yellow]
523drawoptions(withcolor .625yellow) ;
524\stopbuffer
525\stopbuffer
526
527\typebuffer
528
529We can now include the same graphic in two colors by simply using different
530buffers. This time we use the special command \type {\processMPbuffer}, since
531\type {\getbuffer} will typeset the code fragment, which is not what we want.
532
533\startbuffer
534\startlinecorrection[blank]
535\processMPbuffer[red,graphic]
536\stoplinecorrection
537\stopbuffer
538
539\typebuffer
540
541The line correction macros take care of proper spacing around the graphic. The
542\type {[blank]} directive tells \CONTEXT\ to add more space before and after the
543graphic.
544
545\startbuffer
546\startlinecorrection[blank]
547\processMPbuffer[yellow,graphic]
548\stoplinecorrection
549\stopbuffer
550
551\typebuffer
552
553Which mechanism you use, (multiple) buffers or (re|)|usable graphics, depends on
554your preferences. Buffers are slower but don't take memory, while (re|)|usable
555graphics are stored in memory which means that they are accessed faster.
556
557\stopsection
558
559\startsection[title={Communicating color}]
560
561\index{color}
562
563Now that color has moved to the desktop, even simple documents have become more
564colorful, so we need a way to consistently apply color to text as well as
565graphics. In \CONTEXT, colors are called by name.
566
567The next definitions demonstrate that we can define a color using different color
568models, \RGB\ or \CMYK. Depending on the configuration, \CONTEXT\ will convert
569one color system to the other, \RGB\ to \CMYK, or vice versa. The full repertoire
570of color components that can be set is as follows.
571
572\starttyping
573\definecolor[color one]  [r=.1, g=.2, b=.3]
574\definecolor[color two]  [c=.4, m=.5, y=.6, k=.7]
575\definecolor[color three][s=.8]
576\stoptyping
577
578The numbers are limited to the range $0\dots1$ and represent percentages. Black
579is represented by:
580
581\starttyping
582\definecolor[black 1] [r=0, g=0, b=0]
583\definecolor[black 2] [c=0, m=0, y=0, k=1]
584\definecolor[black 3] [s=0]
585\stoptyping
586
587Predefined colors are passed to \METAPOST\ graphics via the \type {\MPcolor}.
588First we define some colors.
589
590\starttyping
591\definecolor[darkyellow][y=.625] % a CMYK color
592\definecolor[darkred]   [r=.625] % a RGB color
593\definecolor[darkgray]  [s=.625] % a gray scale
594\stoptyping
595
596These are the colors we used in this document. The next example uses two of them.
597
598\startbuffer
599\startuseMPgraphic{color demo}
600  pickup pencircle scaled 1mm ;
601  path p ; p := fullcircle xscaled 10cm yscaled 1cm ;
602  fill p withcolor \MPcolor{darkgray} ;
603  draw p withcolor \MPcolor{darkred} ;
604\stopuseMPgraphic
605
606\useMPgraphic{color demo}
607\stopbuffer
608
609\typebuffer
610
611The previous example uses a pure \RGB\ red shade, combined with a gray fill.
612
613\startlinecorrection[blank]
614\getbuffer
615\stoplinecorrection
616
617Originally \METAPOST\ only supported only the \RGB\ and gray color spaces. In \METAFUN\
618we also supported \CMYK\ and spot colors, using an extension mechanism that hooked into
619the backend. At some point \METAPOST\ got native support for \CMYK. When you use mixed
620color models you need to be aware of the fact that their related variables have different
621types:
622
623\starttabulate[||T|T|]
624\NC gray \NC numeric   \NC s         \NC \NR
625\NC rgb  \NC color     \NC (r,g,b)   \NC \NR
626\NC cmyk \NC cmykcolor \NC (c,m,y,k) \NC \NR
627\stoptabulate
628
629Because in \METAFUN\ (\type {mpiv}) we hook deeply into the \CONTEXT\ color
630mechanisms we can use symbolic names instead. and these are just strings.
631
632There is a fundamental difference between a yellow as defined in \CONTEXT\ using
633\CMYK\ and a \RGB\ yellow.
634
635\startbuffer
636\definecolor[cmyyellow]    [y=1]
637\definecolor[rgbyellow]    [r=1,g=1]
638
639\definecolor[cmydarkyellow][y=.625]
640\definecolor[rgbdarkyellow][r=.625,g=.625]
641\stopbuffer
642
643\typebuffer \getbuffer
644
645\in {Figure} [fig:many yellows:pass] demonstrates what happens when we multiply
646colors by a factor. Since we are not dealing with real \CMYK\ colors,
647multiplication gives different results for \CMYK\ colors passed as \type
648{\MPcolor}. \in {Figure} [fig:many yellows:fetch] we show the same colors but
649this time we use a different method, one that avoids the \TEX\ macro. This method
650can be used in \MKIV. We will use both methods in examples.
651
652\def\TestColor#1%
653  {\startuseMPgraphic{yellow}
654     fill unitsquare xscaled (.30*\the\hsize) yscaled 1cm withcolor #1 ;
655   \stopuseMPgraphic
656   \useMPgraphic{yellow}}
657
658\startbuffer
659\setuptype[style=\ttx]%
660\startcombination[3*3]
661  {\TestColor{(0,0,1,0)}}               {\type{(0,0,1,0)}}
662  {\TestColor{(1,1,0)}}                 {\type{(1,1,0)}}
663  {\TestColor{(.5,.5,0)}}               {\type{(.5,.5,0)}}
664  {\TestColor{\MPcolor{rgbyellow}}}     {\type{\MPcolor{rgbyellow}}}
665  {\TestColor{\MPcolor{rgbdarkyellow}}} {\type{\MPcolor{rgbdarkyellow}}}
666  {\TestColor{.5\MPcolor{rgbyellow}}}   {\type{.5\MPcolor{rgbyellow}}}
667  {\TestColor{\MPcolor{cmyyellow}}}     {\type{\MPcolor{cmyyellow}}}
668  {\TestColor{\MPcolor{cmydarkyellow}}} {\type{\MPcolor{cmydarkyellow}}}
669  {\TestColor{.5\MPcolor{cmyyellow}}}   {\type{.5\MPcolor{cmyyellow}}}
670\stopcombination
671\stopbuffer
672
673\placefigure
674  [here][fig:many yellows:pass]
675  {All kinds of yellow (passing valued from \TEX).}
676  {\getbuffer}
677
678\startbuffer
679\setuptype[style=\ttx]%
680\startcombination[3*3]
681  {\TestColor{(0,0,1,0)}}                 {\type{(0,0,1,0)}}
682  {\TestColor{(1,1,0)}}                   {\type{(1,1,0)}}
683  {\TestColor{(.5,.5,0)}}                 {\type{(.5,.5,0)}}
684  {\TestColor{"rgbyellow"}}               {\type{"rgbyellow"}}
685  {\TestColor{"rgbdarkyellow"}}           {\type{"rgbdarkyellow"}}
686  {\TestColor{.5namedcolor("rgbyellow")}} {\type{.5namedcolor("rgbyellow")}}
687  {\TestColor{"cmyyellow"}}               {\type{"cmyyellow"}}
688  {\TestColor{"cmydarkyellow"}}           {\type{"cmydarkyellow"}}
689  {\TestColor{.5namedcolor("cmyyellow")}} {\type{.5namedcolor("cmyyellow")}}
690\stopcombination
691\stopbuffer
692
693\placefigure
694  [here][fig:many yellows:fetch]
695  {All kinds of yellow (fetching values from \TEX).}
696  {\getbuffer}
697
698So, \type {.625red} is the same as \type {[r=.5]}, but \type {.625yellow} is not
699the same as \type {[y=.5]}, but matches \type {[r=.5,g=.5]}. \in {Figure}
700[fig:some reds] shows the pure and half reds.
701
702\def\TestColor#1%
703  {\startMPcode
704     fill unitsquare xscaled (.30*\the\hsize) yscaled 1cm withcolor #1 ;
705   \stopMPcode}
706
707\startbuffer
708\setuptype[style=\ttx]\setupcolors[mpcmyk=no]
709\startcombination[3*2]
710  {\TestColor{red}}                   {\type{red}}
711  {\TestColor{(1,0,0)}}               {\type{(1,0,0)}}
712  {\TestColor{(.625,0,0)}}            {\type{(.625,0,0)}}
713  {\TestColor{"red"}}                 {\type{"red")}}
714  {\TestColor{"darkred"}}             {\type{"darkred")}}
715  {\TestColor{.625namedcolor("red")}} {\type{.625namedcolor("red")}}
716\stopcombination
717\stopbuffer
718
719\placefigure
720  [here][fig:some reds]
721  {Some kinds of red.}
722  {\getbuffer}
723
724In order to prevent problems, we advise you to stick to \RGB\ color
725when you create documents for screen and \CMYK\ when producing for print.
726
727In the \METAFUN\ macro collection there is a macro \type {cmyk} that takes four
728arguments, representing the cyan, magenta, yellow, and black component. Nowadays
729you don't need it as we have native \CMYK.
730
731\startbuffer
732fill unitsquare xyscaled (10cm, 5mm) withcolor cmyk(1,0,.3,.3) ;
733fill unitsquare xyscaled (10cm,-5mm) withcolor     (1,.3,0,.3) ;
734\stopbuffer
735
736\typebuffer
737
738\startlinecorrection[blank]
739\processMPbuffer
740\stoplinecorrection
741
742If you take a close look at the numbers, you will notice that the cyan component
743results in a 100\% ink contribution. You will also notice that 30\% black ink is
744added. This means that we cannot safely convert this color to \RGB\ ($r=1-c-k<0$)
745without losing information. Nevertheless the previous blue bar is presented all
746right. This is due to the fact that in \METAFUN\ the \CMYK\ colors are handled as
747they should, even when \METAPOST\ does not support this color model.
748
749If you use this feature independent of \CONTEXT, you need to enable it by setting
750\type {cmykcolors} to \type {true}. You have to convert the resulting graphic to
751\PDF\ by using for instance the \type {mptopdf} suite.
752
753In \CONTEXT\ you can influence this conversion by changing parameters related to
754color handling:
755
756\starttyping
757\setupcolors[cmyk=yes,rgb=no]
758\stoptyping
759
760Unless you know what you are doing, you don't have to change the default settings
761(both \type {yes}). In the \CONTEXT\ reference manual you can also read how color
762reduction can be handled.
763
764Special care should be paid to gray scales. Combining equal quantities of the
765three color inks will not lead to a gray scale, but to a muddy brown shade.
766
767\startbuffer
768fill fullsquare xyscaled (10cm,  2cm) withcolor .5white ;
769fill fullsquare xyscaled ( 6cm,1.5cm) withcolor cmyk(.5,.5,.5,0) ;
770fill fullsquare xyscaled ( 2cm,  1cm) withcolor cmyk(0,0,0,.5) ;
771\stopbuffer
772
773\typebuffer
774
775\startlinecorrection[blank]
776\processMPbuffer
777\stoplinecorrection
778
779In \in {figure} [fig:cmyk 1] \in {and} [fig:cmyk 2] you can see some more colors
780defined in the \CMYK\ color space. When you display the screen version of this
781document, you will notice that the way colors are displayed can differ per
782viewer. This is typical for \CMYK\ colors and has to do with the fact that some
783assumptions are made with respect to the (print) medium.
784
785\startbuffer[mp]
786  fill fullcircle xyscaled (3cm,1cm) withcolor \MPcolor{test} ;
787\stopbuffer
788
789\startbuffer[cmyk]
790\startcombination[4*1]
791  {\definecolor[test][c=1,y=.3,k=.3] \processMPbuffer[mp]} {c=1 y=.3 k=.3}
792  {\definecolor[test][c=.9,y=.15]    \processMPbuffer[mp]} {c=.9 y=.15}
793  {\definecolor[test][c=.25,y=.8]    \processMPbuffer[mp]} {c=.25 y=.8}
794  {\definecolor[test][c=.45,y=.1]    \processMPbuffer[mp]} {c=.45 y=.1}
795\stopcombination
796\stopbuffer
797
798\placefigure
799  [here][fig:cmyk 1]
800  {\CMYK\ support enabled.}
801  {\getbuffer[cmyk]}
802
803\placefigure
804  [here][fig:cmyk 2]
805  {\CMYK\ support disabled, no support in \METAPOST.}
806  {\setupcolors[cmyk=no]\getbuffer[cmyk]\setupcolors[cmyk=yes]}
807
808\stopsection
809
810% \startsection[title={Common definitions}]
811%
812% \index{inclusions}
813% \index{common definitions}
814%
815% When using many graphics, there is a chance that they share common definitions.
816% Such shared components can be defined by:
817%
818% \starttyping
819% \startMPinclusions
820%   color mycolor ; mycolor := .625red ;
821% \stopMPinclusions
822% \stoptyping
823%
824% {\em The following is only true for \CONTEXT\ \MKII ! Users of \MKIV\ can skip
825% this section.}
826%
827% All \METAPOST\ graphics defined in the document end up in the files \type
828% {mpgraph.mp} and \type {mprun.mp}. When processed, they produce (sometimes many)
829% graphic files. When you use \CONTEXT\ \MKII\ and \TEXEXEC\ to process documents,
830% these two files are processed automatically after a run so that in a next run,
831% the right graphics are available.
832%
833% When you are using the \type {web2c} distribution, \CONTEXT\ can call \METAPOST\
834% at runtime and thereby use the right graphics instantaneously. In order to use
835% this feature, you have to enable \type {\write18} in the file \type {texmf.cnf}.
836% Also, in the file \type {cont-sys.tex}, that holds local preferences, or in the
837% document source, you should say:
838%
839% \starttyping
840% \runMPgraphicstrue
841% \stoptyping
842%
843% This enables runtime generation of graphics using the low level \TEX\ command
844% \type {\write18}. First make sure that your local brand of \TEX\ supports this
845% feature. A simple test is making a \TEX\ file with the following line:
846%
847% \starttyping
848% \immediate\write18{echo It works}
849% \stoptyping
850%
851% If this fails, you should consult the manual that comes with your system, locate
852% an expert or ask around on the \CONTEXT\ mailing list. Of course you can also
853% decide to let \TEXEXEC\ take care of processing the graphics afterwards. This has
854% the advantage of being faster but has the disadvantage that you need additional
855% \TEX\ runs.
856%
857% If you generate the graphics at run time, you should consider to turn on graphic
858% slot recycling, which means that you often end up with fewer intermediate files:
859%
860% \starttyping
861% \recycleMPslotstrue
862% \stoptyping
863%
864% There are a few more low level switches and features, but these go beyond the
865% purpose of this manual. Some of these features, like the option to add tokens to
866% \type {\everyMPgraphic} are for experts only, and fooling around with them can
867% interfere with existing features.
868%
869% \stopsection
870
871\startsection[title={One page graphics}]
872
873An advantage of using \CONTEXT\ to make your \METAPOST\ graphics is you don't
874have to bother about specials, font inclusion and all those nasty things that can
875spoil a good day. An example of such a graphic is the file \type {mfun-800} that
876resides on the computer of the author.
877
878\typefile{mfun-800}
879
880Given that \CONTEXT\ is present on your system, you can process this file with:
881
882\starttyping
883context mfun-800
884\stoptyping
885
886You can define many graphics in one file. Later you can include individual pages
887from the resulting \PDF\ file in your document:
888
889\startbuffer
890\placefigure
891  {A silly figure, demonstrating that stand||alone||graphics
892   can be made.}
893  {\typesetfile[mfun-800.tex][page=1]}
894\stopbuffer
895
896\typebuffer
897
898In this case the \type {page=1} specification is not really needed. You can scale
899and manipulate the figure in any way supported by the macro package that you use.
900
901\getbuffer
902
903\stopsection
904
905\startsection[title={Managing resources}]
906
907A graphic consists of curves, either or not filled with a given color. A graphic
908can also include text, which means that fonts are used. Finally a graphic can
909have special effects, like a shaded fill. Colors, fonts and special effects go
910under the name resources, since they may demand special care or support from the
911viewing or printing device.
912
913% When fonts are used, a \METAPOST\ file is not self contained. This means that the
914% postprocessing program has to deal with the fonts. In \CONTEXT, the special
915% driver |<|and \PDFTEX\ support is considered as such|>| takes care of this.
916
917Special effects, like shading, are supported by dedicated \METAPOST\ modules.
918These are included in the \CONTEXT\ distribution and will be discussed later in
919\in {chapter} [sec:effects].
920
921Since \METAPOST\ supports color, an embedded graphic can be rather colorful.
922However, when color support is disabled or set up to convert colors to gray
923scales, \CONTEXT\ will convert the colors in the graphics to gray scales.
924
925\startbuffer[circle]
926  colorcircle(4cm,red,green,blue) ;
927\stopbuffer
928
929\startbuffer
930\startcombination[3*1]
931  {\setupcolors[state=start]\processMPbuffer[circle]}          {full color}
932  {\setupcolors[state=stop]\processMPbuffer[circle]}           {weighted gray}
933  {\setupcolors[state=stop,factor=no]\processMPbuffer[circle]} {linear gray}
934\stopcombination
935\stopbuffer
936
937You may wonder what the advantage is of weighted gray conversion. \in {Figure}
938[fig:color circles] shows the difference between natural colors, weighted gray
939scales and straightforward, non||weighted, gray scales.
940
941\placefigure
942  [here][fig:color circles]
943  {The advantage of weighted gray over linear gray.}
944  {\getbuffer\setupcolors[state=start,factor=yes]} % just to be sure
945
946When we convert color to gray, we use the following formula. This kind of
947conversion also takes place in black and white televisions.
948
949\placeformula [-]
950  \startformula
951    G = .30r + .59g + .11b
952  \stopformula
953
954\in {Section} [sec:conversion] introduces the \type {grayed} operation that you
955can use to convert a colored picture into a gray one. This macro uses the same
956conversion method as mentioned here.
957
958\stopsection
959
960\startsection[title={Instances}]
961
962There are a few instances predefined and if you want to isolate your own
963graphics from whatever \CONTEXT\ itself cooks up, you can define more as the
964extra overhead can be neglected.
965
966\starttabulate[|T|T|T|T|T|]
967\BC name        \BC format  \BC extensions \BC initializations \BC method  \NC \NR
968\NC metafun     \NC metafun \NC yes        \NC yes             \NC         \NC \NR
969\NC extrafun    \NC metafun \NC yes        \NC yes             \NC         \NC \NR
970\NC lessfun     \NC metafun \NC            \NC                 \NC         \NC \NR
971\NC doublefun   \NC metafun \NC yes        \NC yes             \NC double  \NC \NR
972\NC binaryfun   \NC metafun \NC yes        \NC yes             \NC binary  \NC \NR
973\NC decimalfun  \NC metafun \NC yes        \NC yes             \NC decimal \NC \NR
974\stoptabulate
975
976According to this the \type {doublefun} instance is defined as:
977
978\starttyping
979\defineMPinstance
980  [doublefun]
981  [format=metafun,
982   extensions=yes,
983   initializations=yes,
984   method=double]
985\stoptyping
986
987The \type {extensions} key relates to:
988
989\starttyping
990\startMPextensions
991    % some code
992\stopMPextensions
993\stoptyping
994
995that are used to pass (common) extensions to the instance. The \type
996{initializations} key relates to:
997
998\starttyping
999\startMPinitializations
1000    % some code
1001\stopMPinitializations
1002\stoptyping
1003
1004that are used to communicate \TEX\ properties to the instance (they are
1005expanded each graphic). Instance bound definitions can be set with:
1006
1007\starttyping
1008\startMPdefinitions{doublefun}
1009    % some code
1010\stopMPdefinitions
1011\stoptyping
1012
1013We do have more instances, for instance for the chemical subsystem. If you load
1014the \type {graph} module you get a double precision \type {graph} instance. We might
1015use more private ones in the future.
1016
1017When you make graphic pages, you can do this:
1018
1019\starttyping
1020\startMPpage[instance=doublefun]
1021    % some code
1022\stopMPpage
1023\stoptyping
1024
1025When you use the other commands you can optionally specify an instance:
1026
1027\startbuffer[metafun]
1028\startMPcode{metafun}
1029    draw textext(decimal pi) scaled 2 withcolor .625red ;
1030    draw boundingbox currentpicture enlarged 2pt ;
1031\stopMPcode
1032\stopbuffer
1033
1034\startbuffer[extrafun]
1035\startMPcode{extrafun}
1036    draw textext(decimal pi) scaled 2 withcolor .625green ;
1037    draw boundingbox currentpicture enlarged 2pt  ;
1038\stopMPcode
1039\stopbuffer
1040
1041\startbuffer[doublefun]
1042\startMPcode{doublefun}
1043    draw textext(decimal pi) scaled 2 withcolor .625blue ;
1044    draw boundingbox currentpicture enlarged 2pt  ;
1045\stopMPcode
1046\stopbuffer
1047
1048\startbuffer[binaryfun]
1049\startMPcode{binaryfun}
1050    draw textext(decimal pi) scaled 2 withcolor .625yellow ;
1051    draw boundingbox currentpicture enlarged 2pt  ;
1052\stopMPcode
1053\stopbuffer
1054
1055\startbuffer[decimalfun]
1056\startMPcode{decimalfun}
1057    draw textext(decimal pi) scaled 2 withcolor .375white ;
1058    draw boundingbox currentpicture enlarged 2pt  ;
1059\stopMPcode
1060\stopbuffer
1061
1062\typebuffer[metafun,extrafun,doublefun,binaryfun,decimalfun]
1063
1064The result is shown in \in {figure} [fig:instances] and as expected there
1065is a different value for $\pi$ reported.
1066
1067\startplacefigure[reference=fig:instances,title={Instances can use different number systems.}]
1068    \startcombination[1*5]
1069        {\getbuffer[metafun]}    {metafun}
1070        {\getbuffer[extrafun]}   {extrafun}
1071        {\getbuffer[doublefun]}  {doublefun}
1072        {\getbuffer[binaryfun]}  {binaryfun}
1073        {\getbuffer[decimalfun]} {decimalfun}
1074    \stopcombination
1075\stopplacefigure
1076
1077You need to be aware of the fact that the results of a (for instance) double
1078instance can differ from a scaled (the default) one. As long as graphics can be
1079processed in both models (which is the case as long as the dimensions stay below
10804096 base points) the outcome is probably not that different. However, we've seen
1081that the accuracy of for instance $\pi$ (just a variable) differs. I like to use
1082random values and the random generators are definitely different: each of the
1083number libraries has its own implementation. Let's look at that. We define two
1084random graphic generators:
1085
1086\startbuffer
1087\startuseMPgraphic{normaldeviate}
1088    randomseed := 100 ;
1089    draw fullsquare
1090        withpen pencircle scaled 1/200
1091        withcolor .5white ;
1092    for i=1 upto 500 :
1093        draw (normaldeviate,normaldeviate)
1094            scaled 1/3
1095            withpen pencircle scaled 1/30
1096            withtransparency (1,.5) ;
1097    endfor ;
1098    setbounds currentpicture to
1099        boundingbox fullcircle
1100        enlarged 1/2 ;
1101    currentpicture :=
1102        currentpicture
1103        xsized (2TextWidth/5) ;
1104\stopuseMPgraphic
1105\stopbuffer
1106
1107\typebuffer \getbuffer
1108
1109And:
1110
1111\startbuffer
1112\startuseMPgraphic{uniformdeviate}
1113    randomseed := 100 ;
1114    draw fullsquare
1115        withpen pencircle scaled 1/200
1116        withcolor .5white ;
1117    for i=1 upto 500 :
1118        draw (-1/2 + uniformdeviate 1,-1/2 + uniformdeviate 1)
1119            withpen pencircle scaled 1/30
1120            withtransparency (1,.5) ;
1121    endfor ;
1122    setbounds currentpicture to
1123        boundingbox fullcircle
1124        enlarged 1/2 ;
1125    currentpicture :=
1126        currentpicture
1127        xsized (2TextWidth/5) ;
1128\stopuseMPgraphic
1129\stopbuffer
1130
1131\typebuffer \getbuffer
1132
1133We show the results for a normaldeviate in \in {figure} [fig:random:1] \in {upto}
1134[fig:random:4] you see the randomizers per number system. In \in {figure}
1135[fig:random:compared] we demonstrate that the scaled version has its own variant.
1136
1137\unexpanded\def\TestRandomFun#1#2#3%
1138  {\startMPcode{#1}
1139      draw image(\includeMPgraphic{#2})
1140          withcolor #3 ;
1141   \stopMPcode}
1142
1143\startplacefigure[reference=fig:random:1,title={The scaled randomizers.}]
1144    \pushrandomseed
1145        \startcombination
1146            {\TestRandomFun{metafun}   {normaldeviate} {darkred}}    {normaldeviate}
1147            {\TestRandomFun{metafun}   {uniformdeviate}{darkred}}    {uniformdeviate}
1148        \stopcombination
1149    \poprandomseed
1150\stopplacefigure
1151
1152\startplacefigure[reference=fig:random:2,title={The double randomizers.}]
1153    \pushrandomseed
1154        \startcombination
1155            {\TestRandomFun{doublefun} {normaldeviate} {darkgreen}}  {normaldeviate}
1156            {\TestRandomFun{doublefun} {uniformdeviate}{darkgreen}}  {uniformdeviate}
1157        \stopcombination
1158    \poprandomseed
1159\stopplacefigure
1160
1161\startplacefigure[reference=fig:random:3,title={The decimal randomizers.}]
1162    \pushrandomseed
1163        \startcombination
1164            {\TestRandomFun{decimalfun}{normaldeviate} {darkblue}}   {normaldeviate}
1165            {\TestRandomFun{decimalfun}{uniformdeviate}{darkblue}}   {uniformdeviate}
1166        \stopcombination
1167    \poprandomseed
1168\stopplacefigure
1169
1170\startplacefigure[reference=fig:random:4,title={The binary randomizers.}]
1171    \pushrandomseed
1172        \startcombination
1173            {\TestRandomFun{binaryfun} {normaldeviate} {darkyellow}} {normaldeviate}
1174            {\TestRandomFun{binaryfun} {uniformdeviate}{darkyellow}} {uniformdeviate}
1175        \stopcombination
1176    \poprandomseed
1177\stopplacefigure
1178
1179\startplacefigure[reference=fig:random:compared,title={Normaldeviate and uniformdeviate overlayed.}]
1180    \pushrandomseed
1181        \startcombination[2*1]
1182            \bgroup
1183                \startoverlay
1184                    {\TestRandomFun{metafun}   {normaldeviate} {darkred}}
1185                    {\TestRandomFun{doublefun} {normaldeviate} {darkgreen}}
1186                    {\TestRandomFun{decimalfun}{normaldeviate} {darkblue}}
1187                    {\TestRandomFun{binaryfun} {normaldeviate} {darkyellow}}
1188                \stopoverlay
1189            \egroup {normaldeviate}
1190            \bgroup
1191                \startoverlay
1192                    {\TestRandomFun{metafun}   {uniformdeviate}{darkred}}
1193                    {\TestRandomFun{doublefun} {uniformdeviate}{darkgreen}}
1194                    {\TestRandomFun{decimalfun}{uniformdeviate}{darkblue}}
1195                    {\TestRandomFun{binaryfun} {uniformdeviate}{darkyellow}}
1196                \stopoverlay
1197            \egroup {uniformdeviate}
1198        \stopcombination
1199    \poprandomseed
1200\stopplacefigure
1201
1202\stopsection
1203
1204\stopchapter
1205
1206\stopcomponent
1207