-
Notifications
You must be signed in to change notification settings - Fork 0
/
defs-proposal.Rhtml
1594 lines (1592 loc) · 65.3 KB
/
defs-proposal.Rhtml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
@media print {
body { }
p.img { text-align: center; page-break-inside: avoid }
img.CC { display: inline }
}
@media screen {
body { max-width: 800px; margin: auto }
p.img { text-align: center }
img.CC { display: inline }
}
p.date {
font-size: smaller;
margin: 0;
}
p.versionHistory {
color: gray
}
p.versionHistory a {
color: gray
}
p.ref {
text-indent: -2em;
padding-left: 2em;
}
p.fig {
text-align: left;
}
p.fig img, img.plot {
box-shadow: 10px 10px 20px;
margin-top: 10px;
margin-bottom: 20px;
}
</style>
</head>
<body>
<h1>Graphical Definitions in R Graphics</h1>
<p>
<span style="font-style: italic">by Paul Murrell</span>
<a href="http://orcid.org">
<img alt="" src="https://www.stat.auckland.ac.nz/~paul/ORCID/ORCiD.png" style="width: 16px; height: 16px; vertical-align: middle">
</a>
<span style="font-family: mono; font-size: small">
<a href="http://orcid.org/0000-0002-3224-8858">http://orcid.org/0000-0002-3224-8858</a>
</span>
</p>
<p class="date">
Version 1: original publication
</p>
<!--begin.rcode init, echo=FALSE, message=FALSE, results="hide"
opts_chunk$set(comment=" ", tidy=FALSE, dpi=96)
options(width=100)
## For wonky desktop set up
options(bitmapType="cairo")
end.rcode-->
<!--begin.rcode echo=FALSE, message=FALSE
library(grid)
end.rcode-->
<hr>
<p><a rel="license" href="http://creativecommons.org/licenses/by/4.0/"><img class="CC" alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by/4.0/88x31.png"></a><br><span xmlns:dct="http://purl.org/dc/terms/" property="dct:title">This document</span>
by <span xmlns:cc="http://creativecommons.org/ns#" property="cc:attributionName">Paul
Murrell</span> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/4.0/">Creative
Commons Attribution 4.0 International License</a>.
</p>
<hr>
<p>
This document describes a plan to expand the R graphics engine
to support graphical definitions: graphical features like gradients,
patterns, masks, and clipping paths.
</p>
<p>
The code changes are being
tracked in a
subversion branch called <code>R-defs</code>.
</p>
<p>
This is a living document that will evolve as the code is developed.
</p>
<p>
The <a href="#features">Features</a> Section outlines the features that I
would like to target and the
<a href="#demos">Demonstrations</a> Section provides a glimpse of how some
new features are currently implemented at the user
level (in the <code>R-defs</code> branch).
</p>
<p>
The <a href="#internals">Internal details</a> Section has more on the internal design and
internal code changes
that have been made.
</p>
<p>
The <a href="#issues">Issues</a> Section contains some of the major design
issues that I have identified so far and
the <a href="#discussion">Discussion</a> Section contains some questions and
(some) answers that I have already thought a bit about,
including the changes that would be imposed
on graphics device maintainers.
</p>
<div>
<h2>Table of Contents:</h2>
<ul style="list-style: none">
<li>
<a href="#intro">1. Introduction</a>
</li>
<li>
<a href="#issues">2. Issues</a>
</li>
<li>
<a href="#features">3. Features</a>
</li>
<li>
<a href="#demos">4. Demonstrations</a>
</li>
<li>
<a href="#internals">5. Internal details</a>
</li>
<li>
<a href="#discussion">6. Discussion</a>
</li>
</ul>
</div>
<h2>
<a name="intro">1. Introduction</a>
</h2>
<p>
The R graphics engine only supports a limited set of graphical
features: basic shapes like lines, rectangles, and circles;
paths (including shapes with holes);
text; raster images; and rectangular clipping regions.
These features are sufficient to produce a wide range of statistical plots,
but there are many things that R graphics cannot do.
</p>
<p>
For example, the image below contains a set of filled contours within
a map of New Zealand. The natural way to achieve this result would
be to draw the filled contours and apply a clipping path to the
filled contours based on
the boundary of New Zealand. That is
not something that can
be achieved in R graphics (because R graphics only supports
rectangular clipping regions).<a href="#clippingpathworkaround"><sup>1</sup></a>
</p>
<p>
<img src="gore-nzoverlaypath.png" alt="contour lines clipped to a map">
</p>
<p>
The plan is to add new graphical
features to the R graphics engine, such as clipping paths,
in order to expand the range of graphical images that can be produced
with R.
</p>
<h2>
<a name="issues">2. Issues</a>
</h2>
<p>
There are a number of issues that need to be resolved
when adding a new graphics feature to the R graphics engine.
</p>
<dl>
<dt>
Device-independence:
</dt>
<dd>
<p>
Can we generate the same output on all R graphics devices?
</p>
<p>
This
horse has already bolted.
The output on different R graphics devices has never been identical
and there are already graphics features
that are not supported on all R graphics devices (e.g.,
translucent colours are not supported on the PostScript device).
The plan is to double-down on this approach and just allow
graphics devices to opt out of any or all of the new features.
</p>
<p>
This is partly because not all devices will be capable
of supporting the new features and partly because it makes it
easy to roll out the new features; graphics devices can
initially opt out of all new features and add support as
and when they are able.
</p>
</dd>
<dt>
<code>SEXP</code>s in graphics devices:
</dt>
<dd>
<p>
Can we avoid sending R's <code>SEXP</code> structures to
graphics devices ?
</p>
<p>
In the early days, there was an effort to avoid using R's internal
C structures within graphics devices (so that they only had to
include R's graphics-related header files and they did not have to
worry about complications like R's memory management).
</p>
<p>
This horse has also bolted. From R 2.13.2 (at least), when the
<code>cap</code> graphics device procedure was added (to allow
raster "screen shots" of current device state), devices have
been able to at least return R structures.
</p>
<p>
The plan is again to double-down. Some of the new features
will require sending relatively complex information to the graphics
device (e.g., gradient information and
pattern information), so rather than
define complex new C structures, it makes sense to make use
of R's existing flexible structures.
</p>
<p>
One problem is that an SEXP in C is basically an opaque pointer.
How does the device know about changes to the SEXP structure?
The proposal is to
write a C API for interacting with the SEXP structures
and encourage
devices to use that. An example has been developed for
gradient fills (see the
<a href="#demos">Demonstrations</a> Section).
</p>
</dd>
<dt>
The feature set:
</dt>
<dd>
<p>
How to decide which graphics features to support?
</p>
<p>
This is almost the inverse of the device-independence problem.
Do we shoot for the union of all features supported by all
possible graphics devices ? Or do we target the feature set
of one particular device or format (e.g., SVG) ?
</p>
<p>
The plan is to take ideas from everywhere.
There are features that will only be supported by some
formats (e.g., SVG has filters, but Cairo has only very
limited filter support, whereas Cairo has mesh patterns,
but SVG does not).
There are also subtleties between formats, like the
'gradientUnits' in SVG that are not
supported in Cairo, but we can hopefully make an interface
for these (at least in 'grid') even if the graphics engine
only goes as far as Cairo support.
</p>
<p>
The PDF feature set is probably the most sophisticated (?).
For example, most graphics formats have linear and radial gradients,
Cairo graphics has "mesh patterns" that SVG does not,
but PDF has seven types of "shaders"
(type 2=Linear gradients, 3=Radial gradients,
4&5=Gouraud-shaded triangle meshes,
6=Coons patch meshes, and 7=Tensor-product patch meshes)
including Function-based shaders (type 1) that define the
colour of every point in the image using a mathematical function.
Gradient meshes have been proposed for SVG, but it
<a href="http://libregraphicsworld.org/blog/entry/gradient-meshes-and-hatching-to-be-removed-from-svg-2-0">does
not look like they will make it into SVG 2.0</a>.
</p>
</dd>
<dt>
'grid' versus 'graphics'
</dt>
<dd>
<p>
Will the new features be implemented for 'graphics' or 'grid'
or both ?
</p>
<p>
The new features will be implemented within the graphics engine.
This means that, in theory, interfaces can be made for both
'graphics' and 'grid'.
</p>
<p>
The plan is to focus, initially at least, on 'grid'.
This is because
'grid' allows more flexible and interesting definitions,
for example, the use of units in locating gradient stops.
'grid' also allows for things like adding features
by post-editing because we are able to address graphical
objects by name.
</p>
<p>
It is also possible in the meantime
to apply the new features to 'graphics'
output via <code>gridGraphics::grid.echo</code>
and functions like <code>grid::grid.edit</code>.
</p>
</dd>
<dt>
Graphics devices
</dt>
<dd>
<p>
Which graphics devices should implement which features ?
</p>
<p>
Obviously, only some features can be added to some graphics devices
because of limitations in graphics formats and/or graphics
libraries. This issue relates more to <em>when</em> support
gets added to different graphics devices. The problem is that
implementing all possible features on all possible devices
is a big job (made more difficult by the development environment
on some platforms, like Windows).
</p>
<p>
The proposal is to be feature-greedy and just
focus initially on the Cairo graphics devices.
This gives a reasonable coverage (raster on Linux at least, PDF,
and SVG) from a single set of code changes.
The idea would be to introduce as many features as possible,
on the Cairo devices, for 4.0.0 and then fill in the gaps.
Once the Cairo changes are implemented, they will hopefully
provide a template so that others
could contribute with patches
for other devices.
</p>
<p>
A danger is that only implementing for Cairo may "bias" the
graphics engine implementation towards that device and cause
problems for implementations on other graphics devices.
Perhaps implementing for two devices (e.g., also the PDF device)
rather than one
would be more prudent.
</p>
<p>
Another issue is that the default, "graphapp", Windows
device is NOT going to be able to support these features
very easily (if at all). GraphApp does not support any
of these features (?) (even in the
<a href="http://enchantia.com/graphapp/doc/manual/">latest version</a>
and not even the underlying Windows GDI supports gradient fills
(though it looks like clipping paths are possible).
OTOH, implementing features on the Cairo device makes them
available on all platforms (?).
I am unsure about whether the RStudio plot pane (RStudioGD) will
be able to support these features (across platforms).
</p>
<p>
Third-party graphics devices can of course update as much as they
want when they want, though they will have to immediately
provide some minimal stubs for the changes to the graphics
device API (<code>GraphicsDevice.h</code>).
</p>
</dd>
</dl>
<h2>
<a name="features">3. Features</a>
</h2>
<p>
This section briefly describes
the set of graphical features that are currently
being considered.
</p>
<dl>
<dt>
Gradients
</dt>
<dd>
<p>
This includes linear gradients and radial gradients.
Gradients can be applied to both fills and strokes
(at least on some devices).
</p>
<p>
Gradient meshes are also supported on several devices
(Cairo and PDF).
</p>
</dd>
<dt>
Patterns
</dt>
<dd>
<p>
Pattern fills are similar to gradient fills in that they
define a "paint" for filling a region. The difference is
that a pattern fill is based on "tiling" a smaller image.
</p>
<p>
There are other sorts of pattern fills in some formats
(e.g., function-based shaders in PDF).
</p>
</dd>
<dt>
Clipping paths
</dt>
<dd>
<p>
Allow clipping to an arbitrary path rather than just a
rectangle. This relies on being able to specify a
"path" separate from drawing (stroking or filling) it.
</p>
</dd>
<dt>
Masks
</dt>
<dd>
<p>
Similar to clipping except that affect translucency of
rendered output (rather than just visible or not).
Again, relies on being able to describe paths without
drawing them.
</p>
</dd>
<dt>
Filters
</dt>
<dd>
<p>
These are essentially raster operations, but a format like
SVG allows them to be defined as part of a vector image
(they are applied as part of the rasterization of the
vector image, for example, when drawing to screen).
</p>
<p>
Implementing these in the graphics engine is probably too hard.
I don't think any of the standard graphics devices will
support them (including the Cairo svg device).
</p>
<p>
These may have to remain the domain of packages like
'gridSVG' (which provides full access to SVG features)
or 'magick' (which allows us to apply raster operations
to raster images), possibly in combination with
the 'rasterize' package.
</p>
<p>
It looks like Thomas Lin Pedersen has been thinking along similar lines
(to the latter) with a
<a href="https://github.com/thomasp85/ggfx">'ggfx'</a> package.
</p>
<!-- Only very limited support in Cairo? No support in PDF?
(see ../../Examples/Filters) -->
</dd>
</dl>
<h2>
<a name="demos">4. Demonstrations</a>
</h2>
<p>
A new <a href="https://svn.r-project.org/R/branches/R-defs/"><code>R-defs</code></a>
branch has been created for experimenting.
So far, that includes the addition of support for
linear and radial gradient fills, patterns, clipping paths, and masks
on both Cairo graphics devices and the <code>pdf</code> device
(except for patterns),
with a 'grid' interface. The following set of examples
show how the 'grid' interface has been implemented so far.
</p>
<p>
<strong>NOTE: support for graphics definitions has only been implemented
for Cairo-based graphics devices and the <code>pdf</code> device
so far. Other graphics devices
should run, but will not produce output from graphics definitions.
Third-party graphics devices will hopefully error out (if they make
use of <code>R_GE_checkVersionOrDie</code>), but otherwise they
are likely to segfault until they are updated.</strong>
</p>
<p>
On the positive side, Cairo devices and the <code>pdf</code> device
can be used on all major platforms,
so there is already an option for accessing these new features
on all major platforms.
</p>
<h3>Gradients</h3>
<p>
The <code>fill</code> gpar can now be a linear gradient
(as well as a normal R colour).
</p>
<!--begin.rcode dev="svg", fig.width=2, fig.height=2
library(grid)
grid.rect(gp=gpar(fill=linearGradient()))
end.rcode-->
<p>
A linear gradient is defined by a start point (default: bottom-left)
and an end point (default: top-right) and a series of "stops".
Each stop is defined by a position on the line from start point to
end point, plus a colour. If the first stop is not at the start
point, or the last stop is not at the end point, we can specify
how the gradient "extends" beyond the first and last stops.
</p>
<p>
The following code creates a linear gradient that starts one inch
off the bottom of the image, proceeds vertically to the top of the image,
and transitions from red to yellow then back to red.
</p>
<!-- produce PNG for this one because SVG does NOT have
spreadMethod="none" (so Cairo SVG just uses "pad") -->
<!--begin.rcode dev="png", fig.width=2, fig.height=2, dpi=96
grid.rect(gp=gpar(fill=linearGradient(c("red", "yellow", "red"),
c(0, .5, 1),
x1=.5, y1=unit(1, "in"),
x2=.5, y2=1,
extend="none")))
end.rcode-->
<p>
When the gradient fill is specified on a grob,
the start and end points are relative to the grob bounding box.
The following code fills a rectangle in the central quarter of the
image with the default linear gradient; the gradient
starts at the bottom-left of the rectangle and ends at the top-right
of the rectangle.
</p>
<!--begin.rcode dev="svg", fig.width=2, fig.height=2
grid.rect(width=.5, height=.5,
gp=gpar(fill=linearGradient()))
end.rcode-->
<p>
A gradient fill can also be specified on a viewport, in which case
the gradient is relative to the viewport and all subsequent
drawing makes use of that gradient (unless a new explicit fill is
specified).
</p>
<p>
In the code below, we push a viewport that fills the whole image
and specify the default linear gradient fill, so the gradient
is relative to the whole image.
We then draw a rectangle, with no explicit fill, so it
"inherits" the gradient from the viewport.
</p>
<!--begin.rcode vppattern, dev="svg", fig.width=2, fig.height=2
pushViewport(viewport(gp=gpar(fill=linearGradient())))
grid.rect()
end.rcode-->
<p>
In the next example, we have the same viewport, but we draw
the rectangle only in the central quarter of the image. This
shows that the gradient that the rectangle inherits is relative
to the viewport rather than being relative to the rectangle.
</p>
<!--begin.rcode dev="svg", fig.width=2, fig.height=2
pushViewport(viewport(gp=gpar(fill=linearGradient())))
grid.rect(width=.5, height=.5)
end.rcode-->
<p>
The next example shows another variation on inheritance of gpar
settings. This time a viewport is pushed with the default
linear gradient and we draw a rectangle in the left third of the
image that inherits that gradient (relative to the viewport).
Then we push another viewport with a green fill and draw a rectangle
within that viewport (in the centre of the image) and that rectangle
inherits the green fill. Finally, we pop the second viewport and
return to the first viewport and restore its linear gradient
so that when we draw
a rectangle in the right third of the image it again inherits
the linear gradient (relative to the viewport).
</p>
<!--begin.rcode dev="svg", fig.width=2, fig.height=2
pushViewport(viewport(gp=gpar(fill=linearGradient())))
grid.rect(x=.2, width=.2, height=.5)
pushViewport(viewport(gp=gpar(fill="green")))
grid.rect(x=.5, width=.2, height=.5)
popViewport()
grid.rect(x=.8, width=.2, height=.5)
end.rcode-->
<p>
The next example also demonstrates inheritance of gpar settings,
but this time it is inheritance between viewports.
We push a viewport with the default gradient, then push another
viewport in the central quarter of the image, then draw a rectangle.
The second viewport inherits the gradient from the first viewport and
then the rectangle inherits the gradient from the second viewport.
The important point is that the gradient is relative to the first
viewport, which is where it was defined.
</p>
<!--begin.rcode dev="svg", fig.width=2, fig.height=2
pushViewport(viewport(gp=gpar(fill=linearGradient())))
pushViewport(viewport(width=.5, height=.5))
grid.rect()
end.rcode-->
<p>
The next example just shows that gradients work with
translucent colours. We draw the text "Reveal" then over the
top draw a rect with a gradient fill that transitions from
(opaque) white to transparent.
</p>
<!--begin.rcode dev="svg", fig.width=2, fig.height=2
grid.text("Reveal", gp=gpar(fontface="bold", cex=3))
grid.rect(gp=gpar(fill=linearGradient(c("white", "transparent"),
x1=.2, x2=.8, y1=.5, y2=.5)))
end.rcode-->
<p>
The next example shows that radial gradients work via
the same interface. It is expected that fill patterns would
work the same way.
</p>
<!--begin.rcode dev="svg", fig.width=2, fig.height=2
grid.rect(gp=gpar(fill=radialGradient()))
end.rcode-->
<p>
As with linear gradients, we have control over the start and end
of the radial gradient, though in the radial case it is a start circle
and an end circle. In the code below, we make a gradient that starts
near the top right of the image (with white) and ends with a circle
that fills the image (black).
</p>
<!--begin.rcode dev="svg", fig.width=2, fig.height=2
grid.rect(gp=gpar(fill=radialGradient(c("white", "black"),
cx1=.8, cy1=.8)))
end.rcode-->
<p>
The next example shows that we can add a gradient to an
existing image, in this case a 'ggplot2' plot.
Here we edit the background of the plot panel to add
a grey-to-white gradient.
</p>
<!--begin.rcode dev="svg", fig.width=5, fig.height=5, fig.keep="last"
library(ggplot2)
ggplot(mtcars) +
geom_point(aes(x=disp, y=mpg)) +
theme_bw()
grid.force()
grid.edit("panel.background", grep=TRUE,
gp=gpar(fill=linearGradient(c("grey", "white"), x1=.5, x2=.5)))
end.rcode-->
<p>
The next example is similar, but demonstrates that, even with
gradients only implemented in 'grid', we can still add gradients
to 'graphics' plots if we first convert them using the
'gridGraphics' package.
</p>
<!--begin.rcode dev="svg", dev.args=list(bg='transparent'), fig.width=5, fig.height=5, fig.keep="last"
plot(mpg ~ disp, mtcars, pch=16)
library(gridGraphics)
grid.echo()
g <- grid.grab()
box <- grid.grep("box", g, grep=TRUE)
g <- editGrob(g, box$name,
gp=gpar(fill=linearGradient(c("grey", "white"), x1=.5, x2=.5)))
g <- reorderGrob(g, box$name)
grid.newpage()
grid.draw(g)
end.rcode-->
<h3>Patterns</h3>
<p>
The <code>fill</code> gpar can also be a general pattern that is based
on a 'grid' grob. The <code>pattern</code> function takes a grob
and draws it as the fill for another grob.
</p>
<!--begin.rcode dev="svg", dev.args=list(bg='transparent'), fig.width=2, fig.height=2
pat <- pattern(circleGrob(1:3/4, r=unit(5, "mm"),
gp=gpar(fill=c("red", "green", "blue"))))
grid.rect(gp=gpar(fill=pat))
end.rcode-->
<p>
Patterns on grobs are relative to the grob.
</p>
<!--begin.rcode dev="svg", dev.args=list(bg='transparent'), fig.width=2, fig.height=2
pat <- pattern(circleGrob(1:3/4, r=unit(5, "mm"),
gp=gpar(fill=c("red", "green", "blue"))))
grid.rect(width=.5, gp=gpar(fill=pat))
end.rcode-->
<p>
Patterns on viewports are relative to the viewport.
</p>
<!--begin.rcode dev="svg", dev.args=list(bg='transparent'), fig.width=2, fig.height=2
pat <- pattern(circleGrob(1:3/4, r=unit(5, "mm"),
gp=gpar(fill=c("red", "green", "blue"))))
pushViewport(viewport(gp=gpar(fill=pat)))
grid.rect(width=.5)
end.rcode-->
<p>
Patterns are full drawings so can have gradients and clipping (see
"Clipping paths" below).
</p>
<!--begin.rcode dev="svg", dev.args=list(bg='transparent'), fig.width=2, fig.height=2
pat <- circleGrob(1:3/4, r=unit(5, "mm"),
vp=viewport(clip=rectGrob(height=unit(5, "mm")),
gp=gpar(fill=linearGradient(y1=.5, y2=.5))))
grid.rect(gp=gpar(fill=pattern(pat)))
end.rcode-->
<p>
Patterns can "extend" like gradient fills; probably the most
typical use of a pattern will draw a simple shape and then
specify <code>extend="repeat"</code>
to fill a region.
To do this, we must specify a size for the pattern (this specifies
a "size" for the "tile" that gets repeated).
For example, the code below fills a rectangle with a polka-dot
pattern by specifying a circle as the pattern and specifying that
the pattern size is just a little bit larger than the circle
and specifying that the pattern repeats.
</p>
<!--begin.rcode dev="svg", dev.args=list(bg='transparent'), fig.width=2, fig.height=2
pat <- pattern(circleGrob(r=unit(3, "mm"),
gp=gpar(col=NA, fill="grey")),
width=unit(8, "mm"),
height=unit(8, "mm"),
extend="repeat")
pushViewport(viewport(gp=gpar(fill=pat)))
grid.rect(width=.5)
end.rcode-->
<h3>Clipping paths</h3>
<p>
The <code>clip</code> argument for the <code>viewport</code> function
can be a 'grid' grob (in addition to the existing
<code>"on"</code>, which only enforces a rectangular clipping region).
The grob defines a path that is used
to set the clipping region.
</p>
<p>
A simple example is clipping output (in this case text) to a circle.
The text and the circle are both drawn in grey and then the text
is drawn black with the circle used as a clipping path.
</p>
<!--begin.rcode dev="svg", dev.args=list(bg='transparent'), fig.width=2, fig.height=2
grid.text("testing", gp=gpar(cex=3, col="grey"))
cg <- circleGrob(r=.25, gp=gpar(col="grey"))
grid.draw(cg)
pushViewport(viewport(clip=cg))
grid.text("testing", gp=gpar(cex=3))
end.rcode-->
<p>
A slightly more dramatic example involves clipping text to several
circles at once. Note that this still only requires a single
grob to specify the clipping path.
</p>
<!--begin.rcode dev="svg", dev.args=list(bg='transparent'), fig.width=2, fig.height=2
grid.text("testing", gp=gpar(cex=3, col="grey"))
cg <- circleGrob(x=1:3/4, r=.1, gp=gpar(col="grey"))
grid.draw(cg)
pushViewport(viewport(clip=cg))
grid.text("testing", gp=gpar(cex=3))
end.rcode-->
<p>
The clipping path is relative to the viewport and
clipping paths are inherited like the existing <code>clip</code>
settings.
</p>
<p>
In the following code (after drawing everything in grey
without any clipping), we push a viewport with three circles as the
clipping path, then we draw the text "test one", which gets clipped
to the circles. Next, we push another viewport in the bottom third
of the image, which inherits the clipping path, and we draw the text
"test two", which also gets clipped to the circles. Finally,
we pop those two viewports and push a third viewport in the top
third of the image; now there is no clipping path in effect (because
we popped the viewport with a clipping path), so when we
draw the text "test three" the text is not clipped at all.
</p>
<!--begin.rcode dev="svg", dev.args=list(bg='transparent'), fig.width=2, fig.height=2
cg <- circleGrob(y=1:3/4, r=.1, gp=gpar(col="grey"))
grid.text("test one", gp=gpar(cex=3, col="grey"))
grid.draw(cg)
pushViewport(viewport(y=0, height=1/3, just="bottom"))
grid.text("test two", gp=gpar(cex=3, col="grey"))
popViewport()
pushViewport(viewport(clip=cg))
grid.text("test one", gp=gpar(cex=3))
pushViewport(viewport(y=0, height=1/3, just="bottom"))
grid.text("test two", gp=gpar(cex=3))
popViewport(2)
pushViewport(viewport(y=1, height=1/3, just="top"))
grid.text("test three", gp=gpar(cex=3))
end.rcode-->
<p>
Clipping paths are just paths (outlines of shapes), they do not
reflect, for example, stroke width or fill colours.
</p>
<!--begin.rcode dev="svg", dev.args=list(bg='transparent'), fig.width=2, fig.height=2
path <- circleGrob(r=.3, gp=gpar(lwd=30, col="grey", fill=NA))
grid.text("testing", gp=gpar(col="grey", cex=3))
pushViewport(viewport(clip=path))
grid.draw(path)
grid.circle(r=.3)
grid.text("testing", gp=gpar(cex=3))
end.rcode-->
<p>
Although a clipping path can be an arbitrary 'grid' grob,
clipping and masks (see below) are disallowed within a clipping path.
Any viewport that sets <code>clip=TRUE</code> or <code>clip=FALSE</code>
or sets <code>clip</code> to be a grob, or that sets <code>mask</code>
to be a grob, will generate a warning and the clipping setting
(or the mask) will be ignored for determining the clipping path.
</p>
<p>
This constraint has been applied for several reasons:
to make life easier for graphics devices;
because it is very difficult or impossible to achieve
some nested clipping effects on some devices;
formats like PDF and SVG enforce limits on what can go
in a clipping path; and fancy clipping shapes can be
achieved by using a mask instead.
</p>
<h3>Masks</h3>
<p>
A 'grid' viewport can now have a <code>mask</code> (in addition to
<code>clip</code>). This value should be either <code>"inherit"</code>
(the default), in which case the viewport inherits the mask from
its parent, <code>"none"</code>, in which case the viewport does not
mask its content, or a 'grid' grob that defines a new mask for the
viewport.
</p>
<p>
The following example defines a circle grob with a
radial gradient fill that
starts at black in the centre and gradually transitions to
transparent at the circumference.
A viewport is pushed with this circle grob as the mask, then
a rectangle is drawn half the width of the viewport and
filled with solid black.
The result is that only the parts of the rectangle where
the mask is non-transparent are drawn; the retangle is filtered
by the mask.
</p>
<!--begin.rcode dev="svg", dev.args=list(bg='transparent'), fig.width=2, fig.height=2
mask <- circleGrob(gp=gpar(col=NA,
fill=radialGradient(c("black", "transparent"))))
pushViewport(viewport(mask=mask))
grid.rect(width=.5, gp=gpar(fill="black"))
end.rcode-->
<p>
The following code blends two 'ggplot2' plots using a mask.
This time the mask is a linear gradient from black 30%
of the way up the page to transparent 70% of the way up the page.
First, we draw a plot with the default ggplot2 them,
then we draw a black-and-white themed version of the same
plot on top, using the mask, so from 30% up the page the
black-and-white plot transitions smoothly into the default themed plot.
</p>
<!--begin.rcode dev="svg", dev.args=list(bg='transparent'), fig.width=5, fig.height=5, fig.keep="last"
gg1 <- ggplot(mtcars) +
geom_point(aes(x=disp, y=mpg))
gg2 <- gg1 +
theme_bw()
grad <- linearGradient(c("black", "transparent"), x1=.5, x2=.5, y1=.3, y2=.7)
mask <- rectGrob(gp=gpar(col=NA, fill=grad))
print(gg1)
pushViewport(viewport(mask=mask))
print(gg2, newpage=FALSE)
end.rcode-->
<p>
Here is an example of a relatively complex mask that cannot be
achieved with clipping paths (in the current proposal) because
it would require nesting clipping paths.
The mask consists of two narrow rectangles, but the left
rectangle is drawn within a viewport with a clipping path.
The same effect could be achieved by replacing the clipping path
with a mask (nested masks are ok).
</p>
<!--begin.rcode dev="svg", dev.args=list(bg='transparent'), fig.width=2, fig.height=2, fig.keep="last"
mask <- gTree(children=gList(rectGrob(x=.25, width=.3, height=.8,
gp=gpar(fill="black"),
vp=viewport(clip=circleGrob(r=.4))),
rectGrob(x=.75, width=.3, height=.8,
gp=gpar(fill="black"))))
pushViewport(viewport(mask=mask))
grid.rect(gp=gpar(fill="grey"))
popViewport()
end.rcode-->
<h2>
<a name="internals">5. Internal details</a>
</h2>
<h3>Gradients</h3>
<p>
A <code>patternFill</code>
property has been added to the <code>R_GE_gcontext</code>
(graphical context)
in the graphics engine.
This property can be either <code>NULL</code>
(indicating no pattern fill) or an R object, which
represents a reference to one of the current pattern fills on
the graphics device.
</p>
<p>
This property is in addition to the existing <code>fill</code>
property. If <code>patternFill</code> is non-<code>NULL</code>
then it overrides <code>fill</code>. This makes it easy
for a graphics device to ignore <code>patternFill</code>
if it wants to.
</p>
<p>
A <code>grDevices::linearGradient</code> function has been added.
This is not meant to be called
directly by users; it is there for 'graphics' and 'grid' to use.
The idea is the 'graphics' and 'grid' have user-level
interfaces to define gradients and those are
converted to graphics engine versions of the gradients
for drawing. There is also a <code>grDevices::radialGradient</code>.
</p>
<p>
A <code>setPattern</code> device function has been added to
allow the graphics engine to ask a graphics device to create
a pattern. The function takes a <code>"Pattern"</code> object
(either a linear or radial gradient so far) and returns an R object
(a reference to be used in a <code>patternFill</code> call).
</p>
<p>
(A graphics device can just always return <code>NULL</code>
if it generates
a new pattern every time <code>setPattern</code> is called ?)
</p>
<p>
There is also a <code>releasePattern</code> device function
so that, e.g., 'grid' can release a pattern that is just set on
a grob (and release all patterns on new page). Specify
<code>NULL</code>
to release all patterns.
</p>
<p>
NOTE that the <code>"Pattern"</code> sent to
<code>setPattern</code> is an SEXP,
which means it is sort of an opaque pointer in C code,
so the graphics engine provides a C API for extracting
information from a <code>"Pattern"</code> object.
For example,
<code>R_GE_isPattern</code> can be called to check for a pattern fill,
<code>R_GE_patternType</code> can be called to get the pattern type, and
<code>R_GE_linearGradientNumStops</code> can be called
to get the number of stops from a <code>LinearGradient</code> SEXP.
</p>
<p>
The Cairo graphics device (<code>x11(type="cairo")</code>,
<code>png(type="cairo")</code>,
<code>cairo_pdf()</code>, and <code>svg()</code>)
has implemented <code>setPattern</code>
and <code>releasePattern</code> and maintains an array
of patterns. It observes the new
<code>R_GE_gcontext.gradientFill</code> setting
and uses the value
as an index into its array of patterns.
</p>
<p>
The 'grid' package provides its own <code>linearGradient</code>
function for defining a linear gradient in 'grid'.
One notable difference is that the start and end points for
the gradient can be defined using 'grid' units.
The <code>gpar</code> function now also allows
a <code>GridPattern</code> as the value for the
<code>fill</code> property.
</p>
<p>
When gpar settings are enforced during drawing a grob, a
pattern fill is resolved to a graphics engine
<code>Pattern</code> (for example, the start and end
points for a linear gradient are converted to locations on the graphics
device).
If the pattern fill is specified on a viewport, the pattern definition
is relative to that viewport; if the pattern fill is specified
on a grob, then the pattern definition is
relative to the bounding box of the grob.
</p>
<p>
'grid' calls <code>setPattern</code> to "resolve" a pattern
and generates a <code>GridResolvedPattern</code>, which contains
the reference from <code>setPattern</code>. This allows
'grid' to reuse the pattern reference, e.g., when drawing
multiple shapes from a single grob, or when revisiting a
viewport (so that it does not have to ask the graphics device
for a new pattern for every shape or for every visit to a viewport).
</p>
<p>
When drawing a grob, 'grid' resolves the pattern relative to the grob,
gets the pattern reference and uses that for every shape that is drawn
from this grob, then releases the pattern.
</p>
<p>
When pushing a viewport, 'grid' resolves
the pattern relative to the viewport
and stores the resolved pattern in the pushed viewport, so that
revisits to the viewport can reuse the resolved pattern.
The resolved pattern is only stored in the pushed viewport so
that replays of the grid display list (e.g., <code>grid.edit</code>)
or the graphics engine display list (e.g., device resize or
device copy) will always resolve the pattern again.
</p>
<p>
When starting a new page, 'grid' releases all patterns.
</p>
<h3>Patterns</h3>
<p>
Patterns use the same <code>R_GE_context</code> slot as gradients;
a drawing can have a gradient OR a pattern fill OR a normal fill.
Patterns are passed to graphics devices via the same
<code>setPattern</code> device function.
</p>
<p>
There is a <code>grDevices::tilingPattern</code> function for
'graphics' and 'grid' to use to create a pattern.
</p>
<p>
'grid' creates a <code>GridTilingPattern</code> object,
which is a list with a component, <code>f</code>,
that contains a function to draw the grob that defines the pattern,
plus the location, size, and extend rule for the pattern.
</p>
<p>
The Cairo graphics device creates a pattern by running the pattern
function within a <code>cairo_push_group</code> and
<code>cairo_pop_group</code>. This means that the pattern
is drawn on a temporary surface and that drawing is turned into
a Cairo pattern to use as the source for filling other drawing.
</p>
<p>