Debian Codegraph @

shiny/iconvg/rasterizer.go

raw symbols SCIP
1 // Copyright 2016 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package iconvg
6
7 import (
8 "image"
9 "image/color"
10 "image/draw"
11 "math"
12
13 "golang.org/x/exp/shiny/iconvg/internal/gradient"
14 "golang.org/x/image/math/f64"
15 "golang.org/x/image/vector"
16 )
17
18 const (
19 smoothTypeNone = iota
20 smoothTypeQuad
21 smoothTypeCube
22 )
23
24 // Rasterizer is a Destination that draws an IconVG graphic onto a raster
25 // image.
26 //
27 // The zero value is usable, in that it has no raster image to draw onto, so
28 // that calling Decode with this Destination is a no-op (other than checking
29 // the encoded form for errors in the byte code). Call SetDstImage to change
30 // the raster image, before calling Decode or between calls to Decode.
31 type Rasterizer struct {
32 z vector.Rasterizer
33
34 dst draw.Image
35 r image.Rectangle
36 drawOp draw.Op
37
38 // scale and bias transforms the metadata.ViewBox rectangle to the (0, 0) -
39 // (r.Dx(), r.Dy()) rectangle.
40 scaleX float32
41 biasX float32
42 scaleY float32
43 biasY float32
44
45 metadata Metadata
46
47 lod0 float32
48 lod1 float32
49 cSel uint8
50 nSel uint8
51
52 disabled bool
53
54 firstStartPath bool
55 prevSmoothType uint8
56 prevSmoothPointX float32
57 prevSmoothPointY float32
58
59 fill image.Image
60 flatColor color.RGBA
61 flatImage image.Uniform
62 gradient gradient.Gradient
63
64 cReg [64]color.RGBA
65 nReg [64]float32
66 stops [64]gradient.Stop
67 }
68
69 // SetDstImage sets the Rasterizer to draw onto a destination image, given by
70 // dst and r, with the given compositing operator.
71 //
72 // The IconVG graphic (which does not have a fixed size in pixels) will be
73 // scaled in the X and Y dimensions to fit the rectangle r. The scaling factors
74 // may differ in the two dimensions.
75 func (z *Rasterizer) SetDstImage(dst draw.Image, r image.Rectangle, drawOp draw.Op) {
76 z.dst = dst
77 if r.Empty() {
78 r = image.Rectangle{}
79 }
80 z.r = r
81 z.drawOp = drawOp
82 z.recalcTransform()
83 }
84
85 // Reset resets the Rasterizer for the given Metadata.
86 func (z *Rasterizer) Reset(m Metadata) {
87 z.metadata = m
88 z.lod0 = 0
89 z.lod1 = positiveInfinity
90 z.cSel = 0
91 z.nSel = 0
92 z.firstStartPath = true
93 z.prevSmoothType = smoothTypeNone
94 z.prevSmoothPointX = 0
95 z.prevSmoothPointY = 0
96 z.cReg = m.Palette
97 z.nReg = [64]float32{}
98 z.recalcTransform()
99 }
100
101 func (z *Rasterizer) recalcTransform() {
102 z.scaleX = float32(z.r.Dx()) / (z.metadata.ViewBox.Max[0] - z.metadata.ViewBox.Min[0])
103 z.biasX = -z.metadata.ViewBox.Min[0]
104 z.scaleY = float32(z.r.Dy()) / (z.metadata.ViewBox.Max[1] - z.metadata.ViewBox.Min[1])
105 z.biasY = -z.metadata.ViewBox.Min[1]
106 }
107
108 func (z *Rasterizer) SetCSel(cSel uint8) { z.cSel = cSel & 0x3f }
109 func (z *Rasterizer) SetNSel(nSel uint8) { z.nSel = nSel & 0x3f }
110
111 func (z *Rasterizer) SetCReg(adj uint8, incr bool, c Color) {
112 z.cReg[(z.cSel-adj)&0x3f] = c.Resolve(&z.metadata.Palette, &z.cReg)
113 if incr {
114 z.cSel++
115 }
116 }
117
118 func (z *Rasterizer) SetNReg(adj uint8, incr bool, f float32) {
119 z.nReg[(z.nSel-adj)&0x3f] = f
120 if incr {
121 z.nSel++
122 }
123 }
124
125 func (z *Rasterizer) SetLOD(lod0, lod1 float32) {
126 z.lod0, z.lod1 = lod0, lod1
127 }
128
129 func (z *Rasterizer) unabsX(x float32) float32 { return x/z.scaleX - z.biasX }
130 func (z *Rasterizer) unabsY(y float32) float32 { return y/z.scaleY - z.biasY }
131
132 func (z *Rasterizer) absX(x float32) float32 { return z.scaleX * (x + z.biasX) }
133 func (z *Rasterizer) absY(y float32) float32 { return z.scaleY * (y + z.biasY) }
134 func (z *Rasterizer) relX(x float32) float32 { return z.scaleX * x }
135 func (z *Rasterizer) relY(y float32) float32 { return z.scaleY * y }
136
137 func (z *Rasterizer) absVec2(x, y float32) (zx, zy float32) {
138 return z.absX(x), z.absY(y)
139 }
140
141 func (z *Rasterizer) relVec2(x, y float32) (zx, zy float32) {
142 px, py := z.z.Pen()
143 return px + z.relX(x), py + z.relY(y)
144 }
145
146 // implicitSmoothPoint returns the implicit control point for smooth-quadratic
147 // and smooth-cubic Bézier curves.
148 //
149 // https://www.w3.org/TR/SVG/paths.html#PathDataCurveCommands says, "The first
150 // control point is assumed to be the reflection of the second control point on
151 // the previous command relative to the current point. (If there is no previous
152 // command or if the previous command was not [a quadratic or cubic command],
153 // assume the first control point is coincident with the current point.)"
154 func (z *Rasterizer) implicitSmoothPoint(thisSmoothType uint8) (zx, zy float32) {
155 px, py := z.z.Pen()
156 if z.prevSmoothType != thisSmoothType {
157 return px, py
158 }
159 return 2*px - z.prevSmoothPointX, 2*py - z.prevSmoothPointY
160 }
161
162 func (z *Rasterizer) initGradient(rgba color.RGBA) (ok bool) {
163 nStops := int(rgba.R & 0x3f)
164 cBase := int(rgba.G & 0x3f)
165 nBase := int(rgba.B & 0x3f)
166 prevN := negativeInfinity
167 for i := 0; i < nStops; i++ {
168 c := z.cReg[(cBase+i)&0x3f]
169 if !validAlphaPremulColor(c) {
170 return false
171 }
172 n := z.nReg[(nBase+i)&0x3f]
173 if !(0 <= n && n <= 1) || !(n > prevN) {
174 return false
175 }
176 prevN = n
177 z.stops[i] = gradient.Stop{
178 Offset: float64(n),
179 RGBA64: color.RGBA64{
180 R: uint16(c.R) * 0x101,
181 G: uint16(c.G) * 0x101,
182 B: uint16(c.B) * 0x101,
183 A: uint16(c.A) * 0x101,
184 },
185 }
186 }
187
188 // The affine transformation matrix in the IconVG graphic, stored in 6
189 // contiguous NREG registers, goes from graphic coordinate space (i.e. the
190 // metadata viewBox) to the gradient coordinate space. We need it to start
191 // in pixel space, not graphic coordinate space.
192
193 invZSX := 1 / float64(z.scaleX)
194 invZSY := 1 / float64(z.scaleY)
195 zBX := float64(z.biasX)
196 zBY := float64(z.biasY)
197
198 a := float64(z.nReg[(nBase-6)&0x3f])
199 b := float64(z.nReg[(nBase-5)&0x3f])
200 c := float64(z.nReg[(nBase-4)&0x3f])
201 d := float64(z.nReg[(nBase-3)&0x3f])
202 e := float64(z.nReg[(nBase-2)&0x3f])
203 f := float64(z.nReg[(nBase-1)&0x3f])
204
205 pix2Grad := f64.Aff3{
206 a * invZSX,
207 b * invZSY,
208 c - a*zBX - b*zBY,
209 d * invZSX,
210 e * invZSY,
211 f - d*zBX - e*zBY,
212 }
213
214 shape := gradient.ShapeLinear
215 if (rgba.B>>6)&0x01 != 0 {
216 shape = gradient.ShapeRadial
217 }
218 z.gradient.Init(
219 shape,
220 gradient.Spread(rgba.G>>6),
221 pix2Grad,
222 z.stops[:nStops],
223 )
224
225 return true
226 }
227
228 func (z *Rasterizer) StartPath(adj uint8, x, y float32) {
229 z.flatColor = z.cReg[(z.cSel-adj)&0x3f]
230 if validAlphaPremulColor(z.flatColor) {
231 z.flatImage.C = &z.flatColor
232 z.fill = &z.flatImage
233 z.disabled = z.flatColor.A == 0
234 } else if z.flatColor.A == 0x00 && z.flatColor.B&0x80 != 0 {
235 z.fill = &z.gradient
236 z.disabled = !z.initGradient(z.flatColor)
237 } else {
238 z.fill = nil
239 z.disabled = true
240 }
241
242 width, height := z.r.Dx(), z.r.Dy()
243 h := float32(height)
244 z.disabled = z.disabled || !(z.lod0 <= h && h < z.lod1)
245 if z.disabled {
246 return
247 }
248
249 z.z.Reset(width, height)
250 if z.firstStartPath {
251 z.firstStartPath = false
252 z.z.DrawOp = z.drawOp
253 }
254 z.prevSmoothType = smoothTypeNone
255 z.z.MoveTo(z.absVec2(x, y))
256 }
257
258 func (z *Rasterizer) ClosePathEndPath() {
259 if z.disabled {
260 return
261 }
262 z.z.ClosePath()
263 if z.dst == nil {
264 return
265 }
266 z.z.Draw(z.dst, z.r, z.fill, image.Point{})
267 }
268
269 func (z *Rasterizer) ClosePathAbsMoveTo(x, y float32) {
270 if z.disabled {
271 return
272 }
273 z.prevSmoothType = smoothTypeNone
274 z.z.ClosePath()
275 z.z.MoveTo(z.absVec2(x, y))
276 }
277
278 func (z *Rasterizer) ClosePathRelMoveTo(x, y float32) {
279 if z.disabled {
280 return
281 }
282 z.prevSmoothType = smoothTypeNone
283 z.z.ClosePath()
284 z.z.MoveTo(z.relVec2(x, y))
285 }
286
287 func (z *Rasterizer) AbsHLineTo(x float32) {
288 if z.disabled {
289 return
290 }
291 _, py := z.z.Pen()
292 z.prevSmoothType = smoothTypeNone
293 z.z.LineTo(z.absX(x), py)
294 }
295
296 func (z *Rasterizer) RelHLineTo(x float32) {
297 if z.disabled {
298 return
299 }
300 px, py := z.z.Pen()
301 z.prevSmoothType = smoothTypeNone
302 z.z.LineTo(px+z.relX(x), py)
303 }
304
305 func (z *Rasterizer) AbsVLineTo(y float32) {
306 if z.disabled {
307 return
308 }
309 px, _ := z.z.Pen()
310 z.prevSmoothType = smoothTypeNone
311 z.z.LineTo(px, z.absY(y))
312 }
313
314 func (z *Rasterizer) RelVLineTo(y float32) {
315 if z.disabled {
316 return
317 }
318 px, py := z.z.Pen()
319 z.prevSmoothType = smoothTypeNone
320 z.z.LineTo(px, py+z.relY(y))
321 }
322
323 func (z *Rasterizer) AbsLineTo(x, y float32) {
324 if z.disabled {
325 return
326 }
327 z.prevSmoothType = smoothTypeNone
328 z.z.LineTo(z.absVec2(x, y))
329 }
330
331 func (z *Rasterizer) RelLineTo(x, y float32) {
332 if z.disabled {
333 return
334 }
335 z.prevSmoothType = smoothTypeNone
336 z.z.LineTo(z.relVec2(x, y))
337 }
338
339 func (z *Rasterizer) AbsSmoothQuadTo(x, y float32) {
340 if z.disabled {
341 return
342 }
343 x1, y1 := z.implicitSmoothPoint(smoothTypeQuad)
344 x, y = z.absVec2(x, y)
345 z.prevSmoothType = smoothTypeQuad
346 z.prevSmoothPointX, z.prevSmoothPointY = x1, y1
347 z.z.QuadTo(x1, y1, x, y)
348 }
349
350 func (z *Rasterizer) RelSmoothQuadTo(x, y float32) {
351 if z.disabled {
352 return
353 }
354 x1, y1 := z.implicitSmoothPoint(smoothTypeQuad)
355 x, y = z.relVec2(x, y)
356 z.prevSmoothType = smoothTypeQuad
357 z.prevSmoothPointX, z.prevSmoothPointY = x1, y1
358 z.z.QuadTo(x1, y1, x, y)
359 }
360
361 func (z *Rasterizer) AbsQuadTo(x1, y1, x, y float32) {
362 if z.disabled {
363 return
364 }
365 x1, y1 = z.absVec2(x1, y1)
366 x, y = z.absVec2(x, y)
367 z.prevSmoothType = smoothTypeQuad
368 z.prevSmoothPointX, z.prevSmoothPointY = x1, y1
369 z.z.QuadTo(x1, y1, x, y)
370 }
371
372 func (z *Rasterizer) RelQuadTo(x1, y1, x, y float32) {
373 if z.disabled {
374 return
375 }
376 x1, y1 = z.relVec2(x1, y1)
377 x, y = z.relVec2(x, y)
378 z.prevSmoothType = smoothTypeQuad
379 z.prevSmoothPointX, z.prevSmoothPointY = x1, y1
380 z.z.QuadTo(x1, y1, x, y)
381 }
382
383 func (z *Rasterizer) AbsSmoothCubeTo(x2, y2, x, y float32) {
384 if z.disabled {
385 return
386 }
387 x1, y1 := z.implicitSmoothPoint(smoothTypeCube)
388 x2, y2 = z.absVec2(x2, y2)
389 x, y = z.absVec2(x, y)
390 z.prevSmoothType = smoothTypeCube
391 z.prevSmoothPointX, z.prevSmoothPointY = x2, y2
392 z.z.CubeTo(x1, y1, x2, y2, x, y)
393 }
394
395 func (z *Rasterizer) RelSmoothCubeTo(x2, y2, x, y float32) {
396 if z.disabled {
397 return
398 }
399 x1, y1 := z.implicitSmoothPoint(smoothTypeCube)
400 x2, y2 = z.relVec2(x2, y2)
401 x, y = z.relVec2(x, y)
402 z.prevSmoothType = smoothTypeCube
403 z.prevSmoothPointX, z.prevSmoothPointY = x2, y2
404 z.z.CubeTo(x1, y1, x2, y2, x, y)
405 }
406
407 func (z *Rasterizer) AbsCubeTo(x1, y1, x2, y2, x, y float32) {
408 if z.disabled {
409 return
410 }
411 x1, y1 = z.absVec2(x1, y1)
412 x2, y2 = z.absVec2(x2, y2)
413 x, y = z.absVec2(x, y)
414 z.prevSmoothType = smoothTypeCube
415 z.prevSmoothPointX, z.prevSmoothPointY = x2, y2
416 z.z.CubeTo(x1, y1, x2, y2, x, y)
417 }
418
419 func (z *Rasterizer) RelCubeTo(x1, y1, x2, y2, x, y float32) {
420 if z.disabled {
421 return
422 }
423 x1, y1 = z.relVec2(x1, y1)
424 x2, y2 = z.relVec2(x2, y2)
425 x, y = z.relVec2(x, y)
426 z.prevSmoothType = smoothTypeCube
427 z.prevSmoothPointX, z.prevSmoothPointY = x2, y2
428 z.z.CubeTo(x1, y1, x2, y2, x, y)
429 }
430
431 func (z *Rasterizer) AbsArcTo(rx, ry, xAxisRotation float32, largeArc, sweep bool, x, y float32) {
432 if z.disabled {
433 return
434 }
435 z.prevSmoothType = smoothTypeNone
436
437 // We follow the "Conversion from endpoint to center parameterization"
438 // algorithm as per
439 // https://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter
440
441 // There seems to be a bug in the spec's "implementation notes".
442 //
443 // Actual implementations, such as
444 // - https://git.gnome.org/browse/librsvg/tree/rsvg-path.c
445 // - http://svn.apache.org/repos/asf/xmlgraphics/batik/branches/svg11/sources/org/apache/batik/ext/awt/geom/ExtendedGeneralPath.java
446 // - https://java.net/projects/svgsalamander/sources/svn/content/trunk/svg-core/src/main/java/com/kitfox/svg/pathcmd/Arc.java
447 // - https://github.com/millermedeiros/SVGParser/blob/master/com/millermedeiros/geom/SVGArc.as
448 // do something slightly different (marked with a †).
449
450 // (†) The Abs isn't part of the spec. Neither is checking that Rx and Ry
451 // are non-zero (and non-NaN).
452 Rx := math.Abs(float64(rx))
453 Ry := math.Abs(float64(ry))
454 if !(Rx > 0 && Ry > 0) {
455 z.z.LineTo(x, y)
456 return
457 }
458
459 // We work in IconVG coordinates (e.g. from -32 to +32 by default), rather
460 // than destination image coordinates (e.g. the width of the dst image),
461 // since the rx and ry radii also need to be scaled, but their scaling
462 // factors can be different, and aren't trivial to calculate due to
463 // xAxisRotation.
464 //
465 // We convert back to destination image coordinates via absX and absY calls
466 // later, during arcSegmentTo.
467 penX, penY := z.z.Pen()
468 x1 := float64(z.unabsX(penX))
469 y1 := float64(z.unabsY(penY))
470 x2 := float64(x)
471 y2 := float64(y)
472
473 phi := 2 * math.Pi * float64(xAxisRotation)
474
475 // Step 1: Compute (x1′, y1′)
476 halfDx := (x1 - x2) / 2
477 halfDy := (y1 - y2) / 2
478 cosPhi := math.Cos(phi)
479 sinPhi := math.Sin(phi)
480 x1Prime := +cosPhi*halfDx + sinPhi*halfDy
481 y1Prime := -sinPhi*halfDx + cosPhi*halfDy
482
483 // Step 2: Compute (cx′, cy′)
484 rxSq := Rx * Rx
485 rySq := Ry * Ry
486 x1PrimeSq := x1Prime * x1Prime
487 y1PrimeSq := y1Prime * y1Prime
488
489 // (†) Check that the radii are large enough.
490 radiiCheck := x1PrimeSq/rxSq + y1PrimeSq/rySq
491 if radiiCheck > 1 {
492 c := math.Sqrt(radiiCheck)
493 Rx *= c
494 Ry *= c
495 rxSq = Rx * Rx
496 rySq = Ry * Ry
497 }
498
499 denom := rxSq*y1PrimeSq + rySq*x1PrimeSq
500 step2 := 0.0
501 if a := rxSq*rySq/denom - 1; a > 0 {
502 step2 = math.Sqrt(a)
503 }
504 if largeArc == sweep {
505 step2 = -step2
506 }
507 cxPrime := +step2 * Rx * y1Prime / Ry
508 cyPrime := -step2 * Ry * x1Prime / Rx
509
510 // Step 3: Compute (cx, cy) from (cx′, cy′)
511 cx := +cosPhi*cxPrime - sinPhi*cyPrime + (x1+x2)/2
512 cy := +sinPhi*cxPrime + cosPhi*cyPrime + (y1+y2)/2
513
514 // Step 4: Compute θ1 and Δθ
515 ax := (+x1Prime - cxPrime) / Rx
516 ay := (+y1Prime - cyPrime) / Ry
517 bx := (-x1Prime - cxPrime) / Rx
518 by := (-y1Prime - cyPrime) / Ry
519 theta1 := angle(1, 0, ax, ay)
520 deltaTheta := angle(ax, ay, bx, by)
521 if sweep {
522 if deltaTheta < 0 {
523 deltaTheta += 2 * math.Pi
524 }
525 } else {
526 if deltaTheta > 0 {
527 deltaTheta -= 2 * math.Pi
528 }
529 }
530
531 // This ends the
532 // https://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter
533 // algorithm. What follows below is specific to this implementation.
534
535 // We approximate an arc by one or more cubic Bézier curves.
536 n := int(math.Ceil(math.Abs(deltaTheta) / (math.Pi/2 + 0.001)))
537 for i := 0; i < n; i++ {
538 z.arcSegmentTo(cx, cy,
539 theta1+deltaTheta*float64(i+0)/float64(n),
540 theta1+deltaTheta*float64(i+1)/float64(n),
541 Rx, Ry, cosPhi, sinPhi,
542 )
543 }
544 }
545
546 // arcSegmentTo approximates an arc by a cubic Bézier curve. The mathematical
547 // formulae for the control points are the same as that used by librsvg.
548 func (z *Rasterizer) arcSegmentTo(cx, cy, theta1, theta2, rx, ry, cosPhi, sinPhi float64) {
549 halfDeltaTheta := (theta2 - theta1) * 0.5
550 q := math.Sin(halfDeltaTheta * 0.5)
551 t := (8 * q * q) / (3 * math.Sin(halfDeltaTheta))
552 cos1 := math.Cos(theta1)
553 sin1 := math.Sin(theta1)
554 cos2 := math.Cos(theta2)
555 sin2 := math.Sin(theta2)
556 x1 := rx * (+cos1 - t*sin1)
557 y1 := ry * (+sin1 + t*cos1)
558 x2 := rx * (+cos2 + t*sin2)
559 y2 := ry * (+sin2 - t*cos2)
560 x3 := rx * (+cos2)
561 y3 := ry * (+sin2)
562 z.z.CubeTo(
563 z.absX(float32(cx+cosPhi*x1-sinPhi*y1)),
564 z.absY(float32(cy+sinPhi*x1+cosPhi*y1)),
565 z.absX(float32(cx+cosPhi*x2-sinPhi*y2)),
566 z.absY(float32(cy+sinPhi*x2+cosPhi*y2)),
567 z.absX(float32(cx+cosPhi*x3-sinPhi*y3)),
568 z.absY(float32(cy+sinPhi*x3+cosPhi*y3)),
569 )
570 }
571
572 func (z *Rasterizer) RelArcTo(rx, ry, xAxisRotation float32, largeArc, sweep bool, x, y float32) {
573 ax, ay := z.relVec2(x, y)
574 z.AbsArcTo(rx, ry, xAxisRotation, largeArc, sweep, z.unabsX(ax), z.unabsY(ay))
575 }
576
577 // angle returns the angle between the u and v vectors.
578 func angle(ux, uy, vx, vy float64) float64 {
579 uNorm := math.Sqrt(ux*ux + uy*uy)
580 vNorm := math.Sqrt(vx*vx + vy*vy)
581 norm := uNorm * vNorm
582 cos := (ux*vx + uy*vy) / norm
583 ret := 0.0
584 if cos <= -1 {
585 ret = math.Pi
586 } else if cos >= +1 {
587 ret = 0
588 } else {
589 ret = math.Acos(cos)
590 }
591 if ux*vy < uy*vx {
592 return -ret
593 }
594 return +ret
595 }