forked from gonum/plot
/
canvas.go
329 lines (292 loc) · 7.88 KB
/
canvas.go
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
// Copyright ©2016 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package vgtex provides a vg.Canvas implementation for LaTeX, targeted at
// the TikZ/PGF LaTeX package: https://sourceforge.net/projects/pgf
//
// vgtex generates PGF instructions that will be interpreted and rendered by LaTeX.
// vgtex allows to put any valid LaTeX notation inside plot's strings.
package vgtex // import "github.com/emptywe/plot/vg/vgtex"
import (
"bufio"
"bytes"
"fmt"
"image"
"image/color"
"image/png"
"io"
"math"
"os"
"strings"
"time"
"github.com/emptywe/plot/font"
"github.com/emptywe/plot/vg"
"github.com/emptywe/plot/vg/draw"
)
const degPerRadian = 180 / math.Pi
const (
defaultHeader = `%%%%%% generated by gonum/plot %%%%%%
\documentclass{standalone}
\usepackage{pgf}
\begin{document}
`
defaultFooter = "\\end{document}\n"
)
func init() {
draw.RegisterFormat("tex", func(w, h vg.Length) vg.CanvasWriterTo {
return NewDocument(w, h)
})
}
// Canvas implements the vg.Canvas interface, translating drawing
// primitives from gonum/plot to PGF.
type Canvas struct {
buf *bytes.Buffer
w, h vg.Length
stack []context
// If document is true, Canvas.WriteTo will generate a standalone
// .tex file that can be fed to, e.g., pdflatex.
document bool
id int64 // id is a unique identifier for this canvas
}
type context struct {
color color.Color
dashArray []vg.Length
dashOffset vg.Length
linew vg.Length
}
// New returns a new LaTeX canvas.
func New(w, h vg.Length) *Canvas {
return newCanvas(w, h, false)
}
// NewDocument returns a new LaTeX canvas that can be readily
// compiled into a standalone document.
func NewDocument(w, h vg.Length) *Canvas {
return newCanvas(w, h, true)
}
func newCanvas(w, h vg.Length, document bool) *Canvas {
c := &Canvas{
buf: new(bytes.Buffer),
w: w,
h: h,
document: document,
id: time.Now().UnixNano(),
}
if !document {
c.wtex(`%%%% gonum/plot created for LaTeX/pgf`)
c.wtex(`%%%% you need to add:`)
c.wtex(`%%%% \usepackage{pgf}`)
c.wtex(`%%%% to your LaTeX document`)
}
c.wtex("")
c.wtex(`\begin{pgfpicture}`)
c.stack = make([]context, 1)
vg.Initialize(c)
return c
}
func (c *Canvas) context() *context {
return &c.stack[len(c.stack)-1]
}
// Size returns the width and height of the canvas.
func (c *Canvas) Size() (w, h vg.Length) {
return c.w, c.h
}
// SetLineWidth implements the vg.Canvas.SetLineWidth method.
func (c *Canvas) SetLineWidth(w vg.Length) {
c.context().linew = w
}
// SetLineDash implements the vg.Canvas.SetLineDash method.
func (c *Canvas) SetLineDash(pattern []vg.Length, offset vg.Length) {
c.context().dashArray = pattern
c.context().dashOffset = offset
}
// SetColor implements the vg.Canvas.SetColor method.
func (c *Canvas) SetColor(clr color.Color) {
c.context().color = clr
}
// Rotate implements the vg.Canvas.Rotate method.
func (c *Canvas) Rotate(rad float64) {
c.wtex(`\pgftransformrotate{%g}`, rad*degPerRadian)
}
// Translate implements the vg.Canvas.Translate method.
func (c *Canvas) Translate(pt vg.Point) {
c.wtex(`\pgftransformshift{\pgfpoint{%gpt}{%gpt}}`, pt.X, pt.Y)
}
// Scale implements the vg.Canvas.Scale method.
func (c *Canvas) Scale(x, y float64) {
c.wtex(`\pgftransformxscale{%g}`, x)
c.wtex(`\pgftransformyscale{%g}`, y)
}
// Push implements the vg.Canvas.Push method.
func (c *Canvas) Push() {
c.wtex(`\begin{pgfscope}`)
c.stack = append(c.stack, *c.context())
}
// Pop implements the vg.Canvas.Pop method.
func (c *Canvas) Pop() {
c.stack = c.stack[:len(c.stack)-1]
c.wtex(`\end{pgfscope}`)
c.wtex("")
}
// Stroke implements the vg.Canvas.Stroke method.
func (c *Canvas) Stroke(p vg.Path) {
if c.context().linew <= 0 {
return
}
c.Push()
c.wstyle()
c.wpath(p)
c.wtex(`\pgfusepath{stroke}`)
c.Pop()
}
// Fill implements the vg.Canvas.Fill method.
func (c *Canvas) Fill(p vg.Path) {
c.Push()
c.wstyle()
c.wpath(p)
c.wtex(`\pgfusepath{fill}`)
c.Pop()
}
// FillString implements the vg.Canvas.FillString method.
func (c *Canvas) FillString(f font.Face, pt vg.Point, text string) {
c.Push()
c.wcolor()
pt.X += 0.5 * f.Width(text)
c.wtex(`\pgftext[base,at={\pgfpoint{%gpt}{%gpt}}]{{\fontsize{%gpt}{%gpt}\selectfont %s}}`, pt.X, pt.Y, f.Font.Size, f.Font.Size, text)
c.Pop()
}
// DrawImage implements the vg.Canvas.DrawImage method.
// DrawImage will first save the image inside a PNG file and have the
// generated LaTeX reference that file.
// The file name will be "gonum-pgf-image-<canvas-id>-<time.Now()>.png
func (c *Canvas) DrawImage(rect vg.Rectangle, img image.Image) {
fname := fmt.Sprintf("gonum-pgf-image-%v-%v.png", c.id, time.Now().UnixNano())
f, err := os.Create(fname)
if err != nil {
panic(err)
}
defer f.Close()
err = png.Encode(f, img)
if err != nil {
panic(fmt.Errorf("vgtex: error encoding image to PNG: %v", err))
}
var (
xmin = rect.Min.X
ymin = rect.Min.Y
width = rect.Size().X
height = rect.Size().Y
)
c.wtex(`\pgftext[base,left,at=\pgfpoint{%gpt}{%gpt}]{\pgfimage[height=%gpt,width=%gpt]{%s}}`, xmin, ymin, height, width, fname)
}
func (c *Canvas) indent(s string) string {
return strings.Repeat(s, len(c.stack))
}
func (c *Canvas) wtex(s string, args ...interface{}) {
fmt.Fprintf(c.buf, c.indent(" ")+s+"\n", args...)
}
func (c *Canvas) wstyle() {
c.wdash()
c.wlineWidth()
c.wcolor()
}
func (c *Canvas) wdash() {
if len(c.context().dashArray) == 0 {
c.wtex(`\pgfsetdash{}{0pt}`)
return
}
str := `\pgfsetdash{`
for _, d := range c.context().dashArray {
str += fmt.Sprintf("{%gpt}", d)
}
str += fmt.Sprintf("}{%gpt}", c.context().dashOffset)
c.wtex(str)
}
func (c *Canvas) wlineWidth() {
c.wtex(`\pgfsetlinewidth{%gpt}`, c.context().linew)
}
func (c *Canvas) wcolor() {
col := c.context().color
if col == nil {
col = color.Black
}
r, g, b, a := col.RGBA()
// FIXME(sbinet) \color will last until the end of the current TeX group
// use \pgfsetcolor and \pgfsetstrokecolor instead.
// it needs a named color: define it on the fly (storing it at the beginning
// of the document.)
c.wtex(
`\color[rgb]{%g,%g,%g}`,
float64(r)/math.MaxUint16,
float64(g)/math.MaxUint16,
float64(b)/math.MaxUint16,
)
opacity := float64(a) / math.MaxUint16
c.wtex(`\pgfsetstrokeopacity{%g}`, opacity)
c.wtex(`\pgfsetfillopacity{%g}`, opacity)
}
func (c *Canvas) wpath(p vg.Path) {
for _, comp := range p {
switch comp.Type {
case vg.MoveComp:
c.wtex(`\pgfpathmoveto{\pgfpoint{%gpt}{%gpt}}`, comp.Pos.X, comp.Pos.Y)
case vg.LineComp:
c.wtex(`\pgflineto{\pgfpoint{%gpt}{%gpt}}`, comp.Pos.X, comp.Pos.Y)
case vg.ArcComp:
start := comp.Start * degPerRadian
angle := comp.Angle * degPerRadian
r := comp.Radius
c.wtex(`\pgfpatharc{%g}{%g}{%gpt}`, start, angle, r)
case vg.CurveComp:
var a, b vg.Point
switch len(comp.Control) {
case 1:
a = comp.Control[0]
b = a
case 2:
a = comp.Control[0]
b = comp.Control[1]
default:
panic("vgtex: invalid number of control points")
}
c.wtex(`\pgfcurveto{\pgfpoint{%gpt}{%gpt}}{\pgfpoint{%gpt}{%gpt}}{\pgfpoint{%gpt}{%gpt}}`,
a.X, a.Y, b.X, b.Y, comp.Pos.X, comp.Pos.Y)
case vg.CloseComp:
c.wtex("%% path-close")
default:
panic(fmt.Errorf("vgtex: unknown path component type: %v", comp.Type))
}
}
}
// WriteTo implements the io.WriterTo interface, writing a LaTeX/pgf plot.
func (c *Canvas) WriteTo(w io.Writer) (int64, error) {
var (
n int64
nn int
err error
)
b := bufio.NewWriter(w)
if c.document {
nn, err = b.Write([]byte(defaultHeader))
n += int64(nn)
if err != nil {
return n, err
}
}
m, err := c.buf.WriteTo(b)
n += m
if err != nil {
return n, err
}
nn, err = fmt.Fprintf(b, "\\end{pgfpicture}\n")
n += int64(nn)
if err != nil {
return n, err
}
if c.document {
nn, err = b.Write([]byte(defaultFooter))
n += int64(nn)
if err != nil {
return n, err
}
}
return n, b.Flush()
}