Debian Codegraph @

shiny/iconvg/upgrade.go

raw symbols SCIP
1 // Copyright 2021 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 "bytes"
9 "errors"
10 "image/color"
11 "math"
12 )
13
14 // UpgradeToFileFormatVersion1Options are the options to the
15 // UpgradeToFileFormatVersion1 function.
16 type UpgradeToFileFormatVersion1Options struct {
17 // ArcsExpandWithHighResolutionCoordinates is like the
18 // Encoder.HighResolutionCoordinates field. It controls whether to favor
19 // file size (false) or precision (true) when replacing File Format Version
20 // 0's arcs with cubic Bézier curves.
21 ArcsExpandWithHighResolutionCoordinates bool
22 }
23
24 // UpgradeToFileFormatVersion1 upgrades IconVG data from the 2016 experimental
25 // "File Format Version 0" to the 2021 "File Format Version 1".
26 //
27 // This package (golang.org/x/exp/shiny/iconvg) holds a decoder for FFV0,
28 // including this function to convert from FFV0 to FFV1. Different packages
29 // (github.com/google/iconvg/src/go/*) decode FFV1.
30 //
31 // Amongst some new features and other clean-ups, FFV1 sets up the capability
32 // for animated vector graphics, therefore removing some FFV0 features (such as
33 // arc segments) that can be hard to animate smoothly. The IconvG FFV1 format
34 // and its design decisions are discussed at
35 // https://github.com/google/iconvg/issues/4#issuecomment-874105547
36 func UpgradeToFileFormatVersion1(v0 []byte, opts *UpgradeToFileFormatVersion1Options) (v1 []byte, retErr error) {
37 u := &upgrader{}
38 if opts != nil {
39 u.opts = *opts
40 }
41 for i := range u.creg {
42 u.creg[i] = upgradeColor{
43 typ: ColorTypePaletteIndex,
44 paletteIndex: uint8(i),
45 }
46 }
47
48 if !bytes.HasPrefix(v0, magicBytes) {
49 return nil, errInvalidMagicIdentifier
50 }
51 v1 = append(v1, "\x8AIVG"...)
52 v0 = v0[4:]
53
54 v1, v0, retErr = u.upgradeMetadata(v1, v0)
55 if retErr != nil {
56 return nil, retErr
57 }
58
59 v1, _, retErr = u.upgradeBytecode(v1, v0)
60 if retErr != nil {
61 return nil, retErr
62 }
63
64 return v1, nil
65 }
66
67 const (
68 upgradeVerbMoveTo = 0
69 upgradeVerbLineTo = 1
70 upgradeVerbQuadTo = 2
71 upgradeVerbCubeTo = 3
72 )
73
74 type upgrader struct {
75 opts UpgradeToFileFormatVersion1Options
76
77 // These fields hold the current path's geometry.
78 verbs []uint8
79 args [][2]float32
80
81 // These fields track most of the FFV0 virtual machine register state. The
82 // FFV1 register model is different enough that we don't just translate
83 // each FFV0 register-related opcode individually.
84 creg [64]upgradeColor
85 nreg [64]float32
86 csel uint32
87 nsel uint32
88 fill uint32
89
90 // These fields track the most recent color written to FFV1 register
91 // REGS[SEL+7] (and SEL is kept at 56). As a file size optimization, we
92 // don't have to emit the first half of "Set REGS[SEL+7] = etc; Use
93 // REGS[SEL+7]" if the register already holds the "etc" value.
94 regsSel7 color.RGBA
95 hasRegsSel7 bool
96
97 // calculatingJumpLOD is whether the upgrader.upgradeBytecode method is
98 // being called recursively. FFV0 sets a Level-Of-Detail filter that
99 // applies implicitly until the next SetLOD opcode (if any). FFV1 instead
100 // explicitly gives the number of opcodes to skip if outside the LOD range.
101 calculatingJumpLOD bool
102 }
103
104 func (u *upgrader) upgradeMetadata(v1 buffer, v0 buffer) (newV1 buffer, newV0 buffer, retErr error) {
105 nMetadataChunks, n := v0.decodeNatural()
106 if n == 0 {
107 return nil, nil, errInvalidNumberOfMetadataChunks
108 }
109 v1.encodeNaturalFFV1(nMetadataChunks)
110 v0 = v0[n:]
111
112 for ; nMetadataChunks > 0; nMetadataChunks-- {
113 length, n := v0.decodeNatural()
114 if n == 0 {
115 return nil, nil, errInvalidMetadataChunkLength
116 }
117 v0 = v0[n:]
118 if uint64(length) > uint64(len(v0)) {
119 return nil, nil, errInvalidMetadataChunkLength
120 }
121 upgrade, err := u.upgradeMetadataChunk(v0[:length])
122 if err != nil {
123 return nil, nil, err
124 }
125 v1.encodeNaturalFFV1(uint32(len(upgrade)))
126 v1 = append(v1, upgrade...)
127 v0 = v0[length:]
128 }
129 return v1, v0, nil
130 }
131
132 func (u *upgrader) upgradeMetadataChunk(v0 buffer) (v1 buffer, retErr error) {
133 mid, n := v0.decodeNatural()
134 if n == 0 {
135 return nil, errInvalidMetadataIdentifier
136 }
137 switch mid {
138 case midViewBox:
139 mid = ffv1MIDViewBox
140 case midSuggestedPalette:
141 mid = ffv1MIDSuggestedPalette
142 default:
143 return nil, errInvalidMetadataIdentifier
144 }
145 v1.encodeNaturalFFV1(mid)
146 v0 = v0[n:]
147
148 switch mid {
149 case ffv1MIDViewBox:
150 for i := 0; i < 4; i++ {
151 x, n := v0.decodeNatural()
152 if n == 0 {
153 return nil, errInvalidViewBox
154 }
155 v1.encodeNaturalFFV1(x)
156 v0 = v0[n:]
157 }
158 if len(v0) != 0 {
159 return nil, errInvalidViewBox
160 }
161
162 case ffv1MIDSuggestedPalette:
163 if len(v0) == 0 {
164 return nil, errInvalidSuggestedPalette
165 }
166 numColors := 1 + int(v0[0]&0x3f)
167 colorLength := 1 + int(v0[0]>>6)
168 v1 = append(v1, uint8(numColors-1))
169 v0 = v0[1:]
170 for i := 0; i < numColors; i++ {
171 c, n := Color{}, 0
172 switch colorLength {
173 case 1:
174 c, n = v0.decodeColor1()
175 case 2:
176 c, n = v0.decodeColor2()
177 case 3:
178 c, n = v0.decodeColor3Direct()
179 case 4:
180 c, n = v0.decodeColor4()
181 }
182 if n == 0 {
183 return nil, errInvalidSuggestedPalette
184 } else if (c.typ == ColorTypeRGBA) && validAlphaPremulColor(c.data) {
185 v1 = append(v1, c.data.R, c.data.G, c.data.B, c.data.A)
186 } else {
187 v1 = append(v1, 0x00, 0x00, 0x00, 0xff)
188 }
189 v0 = v0[n:]
190 }
191 if len(v0) != 0 {
192 return nil, errInvalidSuggestedPalette
193 }
194 }
195 return v1, nil
196 }
197
198 func (u *upgrader) upgradeBytecode(v1 buffer, v0 buffer) (newV1 buffer, newV0 buffer, retErr error) {
199 uf := upgradeFunc(upgradeStyling)
200 for len(v0) > 0 {
201 uf, v1, v0, retErr = uf(u, v1, v0)
202 if retErr != nil {
203 if retErr == errCalculatingJumpLOD {
204 return v1, v0, nil
205 }
206 return nil, nil, retErr
207 }
208 }
209 return v1, v0, nil
210 }
211
212 var errCalculatingJumpLOD = errors.New("iconvg: calculating JumpLOD")
213
214 type upgradeFunc func(*upgrader, buffer, buffer) (upgradeFunc, buffer, buffer, error)
215
216 func upgradeStyling(u *upgrader, v1 buffer, v0 buffer) (uf upgradeFunc, newV1 buffer, newV0 buffer, retErr error) {
217 for len(v0) > 0 {
218 switch opcode := v0[0]; {
219 case opcode < 0x80: // "Set CSEL/NSEL"
220 if opcode < 0x40 {
221 u.csel = uint32(opcode & 63)
222 } else {
223 u.nsel = uint32(opcode & 63)
224 }
225 v0 = v0[1:]
226
227 case opcode < 0xa8: // "Set CREG[etc] to an etc color"
228 adj := uint32(opcode & 7)
229 if adj == 7 {
230 adj = 0
231 }
232 index := (u.csel - adj) & 63
233
234 v0 = v0[1:]
235 c, n := Color{}, 0
236 switch (opcode - 0x80) >> 3 {
237 case 0:
238 c, n = v0.decodeColor1()
239 case 1:
240 c, n = v0.decodeColor2()
241 case 2:
242 c, n = v0.decodeColor3Direct()
243 case 3:
244 c, n = v0.decodeColor4()
245 case 4:
246 c, n = v0.decodeColor3Indirect()
247 }
248 if n == 0 {
249 return nil, nil, nil, errInvalidColor
250 }
251 u.creg[index], retErr = u.resolve(c, false)
252 if retErr != nil {
253 return nil, nil, nil, retErr
254 }
255 v0 = v0[n:]
256
257 if (opcode & 7) == 7 {
258 u.csel = (u.csel + 1) & 63
259 }
260
261 case opcode < 0xc0: // "Set NREG[etc] to a real number"
262 adj := uint32(opcode & 7)
263 if adj == 7 {
264 adj = 0
265 }
266 index := (u.nsel - adj) & 63
267
268 v0 = v0[1:]
269 f, n := float32(0), 0
270 switch (opcode - 0x80) >> 3 {
271 case 5:
272 f, n = v0.decodeReal()
273 case 6:
274 f, n = v0.decodeCoordinate()
275 case 7:
276 f, n = v0.decodeZeroToOne()
277 }
278 if n == 0 {
279 return nil, nil, nil, errInvalidNumber
280 }
281 u.nreg[index] = f
282 v0 = v0[n:]
283
284 if (opcode & 7) == 7 {
285 u.nsel = (u.nsel + 1) & 63
286 }
287
288 case opcode < 0xc7: // Start path.
289 adj := uint32(opcode & 7)
290 u.fill = (u.csel - adj) & 63
291 v1 = append(v1, 0x35) // FFV1 MoveTo.
292 v0 = v0[1:]
293 return upgradeDrawing, v1, v0, nil
294
295 case opcode == 0xc7: // "Set LOD"
296 if u.calculatingJumpLOD {
297 u.calculatingJumpLOD = false
298 return nil, v1, v0, errCalculatingJumpLOD
299 }
300
301 v0 = v0[1:]
302 lod := [2]float32{}
303 for i := range lod {
304 f, n := v0.decodeReal()
305 if n == 0 {
306 return nil, nil, nil, errInvalidNumber
307 }
308 lod[i] = f
309 v0 = v0[n:]
310 }
311 if (lod[0] == 0) && math.IsInf(float64(lod[1]), +1) {
312 break
313 }
314
315 u.calculatingJumpLOD = true
316 ifTrue := []byte(nil)
317 if ifTrue, v0, retErr = u.upgradeBytecode(nil, v0); retErr != nil {
318 return nil, nil, nil, retErr
319 }
320 nInstructions := countFFV1Instructions(ifTrue)
321 if nInstructions >= (1 << 30) {
322 return nil, nil, nil, errUnsupportedUpgrade
323 }
324 v1 = append(v1, 0x3a) // FFV1 JumpLOD.
325 v1.encodeNaturalFFV1(uint32(nInstructions))
326 v1.encodeCoordinateFFV1(lod[0])
327 v1.encodeCoordinateFFV1(lod[1])
328 v1 = append(v1, ifTrue...)
329
330 default:
331 return nil, nil, nil, errUnsupportedStylingOpcode
332 }
333 }
334 return upgradeStyling, v1, v0, nil
335 }
336
337 func upgradeDrawing(u *upgrader, v1 buffer, v0 buffer) (uf upgradeFunc, newV1 buffer, newV0 buffer, retErr error) {
338 u.verbs = u.verbs[:0]
339 u.args = u.args[:0]
340
341 coords := [3][2]float32{}
342 pen := [2]float32{}
343 prevSmoothType := smoothTypeNone
344 prevSmoothPoint := [2]float32{}
345
346 // Handle the implicit M after a "Start path" styling op.
347 v0, retErr = decodeCoordinates(pen[:2], nil, v0)
348 if retErr != nil {
349 return nil, nil, nil, retErr
350 }
351 u.verbs = append(u.verbs, upgradeVerbMoveTo)
352 u.args = append(u.args, pen)
353 startingPoint := pen
354
355 for len(v0) > 0 {
356 switch opcode := v0[0]; {
357 case opcode < 0xc0: // LineTo, QuadTo, CubeTo.
358 nCoordPairs, nReps, relative, smoothType := 0, 1+int(opcode&0x0f), false, smoothTypeNone
359 switch opcode >> 4 {
360 case 0x00, 0x01: // "L (absolute lineTo)"
361 nCoordPairs = 1
362 nReps = 1 + int(opcode&0x1f)
363 case 0x02, 0x03: // "l (relative lineTo)"
364 nCoordPairs = 1
365 nReps = 1 + int(opcode&0x1f)
366 relative = true
367 case 0x04: // "T (absolute smooth quadTo)"
368 nCoordPairs = 1
369 smoothType = smoothTypeQuad
370 case 0x05: // "t (relative smooth quadTo)"
371 nCoordPairs = 1
372 relative = true
373 smoothType = smoothTypeQuad
374 case 0x06: // "Q (absolute quadTo)"
375 nCoordPairs = 2
376 case 0x07: // "q (relative quadTo)"
377 nCoordPairs = 2
378 relative = true
379 case 0x08: // "S (absolute smooth cubeTo)"
380 nCoordPairs = 2
381 smoothType = smoothTypeCube
382 case 0x09: // "s (relative smooth cubeTo)"
383 nCoordPairs = 2
384 relative = true
385 smoothType = smoothTypeCube
386 case 0x0a: // "C (absolute cubeTo)"
387 nCoordPairs = 3
388 case 0x0b: // "c (relative cubeTo)"
389 nCoordPairs = 3
390 relative = true
391 }
392 v0 = v0[1:]
393
394 for i := 0; i < nReps; i++ {
395 smoothIndex := 0
396 if smoothType != smoothTypeNone {
397 smoothIndex = 1
398 if smoothType != prevSmoothType {
399 coords[0][0] = pen[0]
400 coords[0][1] = pen[1]
401 } else {
402 coords[0][0] = (2 * pen[0]) - prevSmoothPoint[0]
403 coords[0][1] = (2 * pen[1]) - prevSmoothPoint[1]
404 }
405 }
406 allCoords := coords[:smoothIndex+nCoordPairs]
407 explicitCoords := allCoords[smoothIndex:]
408
409 v0, retErr = decodeCoordinatePairs(explicitCoords, nil, v0)
410 if retErr != nil {
411 return nil, nil, nil, retErr
412 }
413 if relative {
414 for c := range explicitCoords {
415 explicitCoords[c][0] += pen[0]
416 explicitCoords[c][1] += pen[1]
417 }
418 }
419
420 u.verbs = append(u.verbs, uint8(len(allCoords)))
421 u.args = append(u.args, allCoords...)
422
423 pen = allCoords[len(allCoords)-1]
424 if len(allCoords) == 2 {
425 prevSmoothPoint = allCoords[0]
426 prevSmoothType = smoothTypeQuad
427 } else if len(allCoords) == 3 {
428 prevSmoothPoint = allCoords[1]
429 prevSmoothType = smoothTypeCube
430 } else {
431 prevSmoothType = smoothTypeNone
432 }
433 }
434
435 case opcode < 0xe0: // ArcTo.
436 v1, v0, retErr = u.upgradeArcs(&pen, v1, v0)
437 if retErr != nil {
438 return nil, nil, nil, retErr
439 }
440 prevSmoothType = smoothTypeNone
441
442 default: // Other drawing opcodes.
443 v0 = v0[1:]
444 switch opcode {
445 case 0xe1: // "z (closePath); end path"
446 goto endPath
447
448 case 0xe2, 0xe3: // "z (closePath); M (absolute/relative moveTo)"
449 v0, retErr = decodeCoordinatePairs(coords[:1], nil, v0)
450 if retErr != nil {
451 return nil, nil, nil, retErr
452 }
453 if opcode == 0xe2 {
454 pen[0] = coords[0][0]
455 pen[1] = coords[0][1]
456 } else {
457 pen[0] += coords[0][0]
458 pen[1] += coords[0][1]
459 }
460 u.verbs = append(u.verbs, upgradeVerbMoveTo)
461 u.args = append(u.args, pen)
462
463 default:
464 tmp := [1]float32{}
465 v0, retErr = decodeCoordinates(tmp[:1], nil, v0)
466 if retErr != nil {
467 return nil, nil, nil, retErr
468 }
469 switch opcode {
470 case 0xe6: // "H (absolute horizontal lineTo)"
471 pen[0] = tmp[0]
472 case 0xe7: // "h (relative horizontal lineTo)"
473 pen[0] += tmp[0]
474 case 0xe8: // "V (absolute vertical lineTo)"
475 pen[1] = tmp[0]
476 case 0xe9: // "v (relative vertical lineTo)"
477 pen[1] += tmp[0]
478 default:
479 return nil, nil, nil, errUnsupportedDrawingOpcode
480 }
481 u.verbs = append(u.verbs, upgradeVerbLineTo)
482 u.args = append(u.args, pen)
483 }
484 prevSmoothType = smoothTypeNone
485 }
486 }
487
488 endPath:
489 v1, retErr = u.finishDrawing(v1, startingPoint)
490 return upgradeStyling, v1, v0, retErr
491 }
492
493 func (u *upgrader) finishDrawing(v1 buffer, startingPoint [2]float32) (newV1 buffer, retErr error) {
494 v1.encodeCoordinatePairFFV1(u.args[0])
495
496 for i, j := 1, 1; i < len(u.verbs); {
497 curr := u.args[j-1]
498 runLength := u.computeRunLength(u.verbs[i:])
499 verb := u.verbs[i]
500
501 if verb == upgradeVerbMoveTo {
502 v1 = append(v1, 0x35) // FFV1 MoveTo.
503 v1.encodeCoordinatePairFFV1(u.args[j])
504 i += 1
505 j += 1
506 continue
507 }
508
509 switch verb {
510 case upgradeVerbLineTo:
511 if ((runLength == 3) && ((j + 3) == len(u.args)) && u.looksLikeParallelogram3(&curr, u.args[j:], &startingPoint)) ||
512 ((runLength == 4) && u.looksLikeParallelogram4(&curr, u.args[j:j+4])) {
513 v1 = append(v1, 0x34) // FFV1 Parallelogram.
514 v1.encodeCoordinatePairFFV1(u.args[j+0])
515 v1.encodeCoordinatePairFFV1(u.args[j+1])
516 i += 4
517 j += 4 * 1
518 continue
519 }
520 case upgradeVerbCubeTo:
521 if (runLength == 4) && u.looksLikeEllipse(&curr, u.args[j:j+(4*3)]) {
522 v1 = append(v1, 0x33) // FFV1 Ellipse (4 quarters).
523 v1.encodeCoordinatePairFFV1(u.args[j+2])
524 v1.encodeCoordinatePairFFV1(u.args[j+5])
525 i += 4
526 j += 4 * 3
527 continue
528 }
529 }
530
531 opcodeBase := 0x10 * (verb - 1) // FFV1 LineTo / QuadTo / CubeTo.
532 if runLength < 16 {
533 v1 = append(v1, opcodeBase|uint8(runLength))
534 } else {
535 v1 = append(v1, opcodeBase)
536 v1.encodeNaturalFFV1(uint32(runLength) - 16)
537 }
538 args := u.args[j : j+(runLength*int(verb))]
539 for _, arg := range args {
540 v1.encodeCoordinatePairFFV1(arg)
541 }
542 i += runLength
543 j += len(args)
544 }
545
546 return u.emitFill(v1)
547 }
548
549 func (u *upgrader) emitFill(v1 buffer) (newV1 buffer, retErr error) {
550 switch c := u.creg[u.fill]; c.typ {
551 case ColorTypeRGBA:
552 if validAlphaPremulColor(c.rgba) {
553 if !u.hasRegsSel7 || (u.regsSel7 != c.rgba) {
554 u.hasRegsSel7, u.regsSel7 = true, c.rgba
555 v1 = append(v1, 0x57, // FFV1 Set REGS[SEL+7].hi32.
556 c.rgba.R, c.rgba.G, c.rgba.B, c.rgba.A)
557 }
558 v1 = append(v1, 0x87) // FFV1 Fill (flat color) with REGS[SEL+7].
559
560 } else if (c.rgba.A == 0) && (c.rgba.B&0x80 != 0) {
561 nStops := int(c.rgba.R & 63)
562 cBase := int(c.rgba.G & 63)
563 nBase := int(c.rgba.B & 63)
564 if nStops < 2 {
565 return nil, errInvalidColor
566 } else if nStops > 17 {
567 return nil, errUnsupportedUpgrade
568 }
569
570 v1 = append(v1, 0x70|uint8(nStops-2)) // FFV1 SEL -= N; Set REGS[SEL+1 .. SEL+1+N].
571 for i := 0; i < nStops; i++ {
572 if stopOffset := u.nreg[(nBase+i)&63]; stopOffset <= 0 {
573 v1 = append(v1, 0x00, 0x00, 0x00, 0x00)
574 } else if stopOffset < 1 {
575 u := uint32(stopOffset * 0x10000)
576 v1 = append(v1, uint8(u>>0), uint8(u>>8), uint8(u>>16), uint8(u>>24))
577 } else {
578 v1 = append(v1, 0x00, 0x00, 0x01, 0x00)
579 }
580
581 if stopColor := u.creg[(cBase+i)&63]; stopColor.typ != ColorTypeRGBA {
582 return nil, errUnsupportedUpgrade
583 } else {
584 v1 = append(v1,
585 stopColor.rgba.R,
586 stopColor.rgba.G,
587 stopColor.rgba.B,
588 stopColor.rgba.A,
589 )
590 }
591 }
592
593 nMatrixElements := 0
594 if c.rgba.B&0x40 == 0 {
595 v1 = append(v1, 0x91, // FFV1 Fill (linear gradient) with REGS[SEL+1 .. SEL+1+N].
596 (c.rgba.G&0xc0)|uint8(nStops-2))
597 nMatrixElements = 3
598 } else {
599 v1 = append(v1, 0xa1, // FFV1 Fill (radial gradient) with REGS[SEL+1 .. SEL+1+N].
600 (c.rgba.G&0xc0)|uint8(nStops-2))
601 nMatrixElements = 6
602 }
603 for i := 0; i < nMatrixElements; i++ {
604 u := math.Float32bits(u.nreg[(nBase+i-6)&63])
605 v1 = append(v1, uint8(u>>0), uint8(u>>8), uint8(u>>16), uint8(u>>24))
606 }
607
608 v1 = append(v1, 0x36, // FFV1 SEL += N.
609 uint8(nStops))
610 } else {
611 return nil, errInvalidColor
612 }
613
614 case ColorTypePaletteIndex:
615 if c.paletteIndex < 7 {
616 v1 = append(v1, 0x88+c.paletteIndex) // FFV1 Fill (flat color) with REGS[SEL+8+N].
617 } else {
618 v1 = append(v1, 0x56, // FFV1 Set REGS[SEL+6].hi32.
619 0x80|c.paletteIndex, 0, 0, 0,
620 0x86) // FFV1 Fill (flat color) with REGS[SEL+6].
621 }
622
623 case ColorTypeBlend:
624 if c.color0.typ == ColorTypeRGBA {
625 v1 = append(v1, 0x53, // FFV1 Set REGS[SEL+3].hi32.
626 c.color0.rgba.R, c.color0.rgba.G, c.color0.rgba.B, c.color0.rgba.A)
627 }
628 if c.color1.typ == ColorTypeRGBA {
629 v1 = append(v1, 0x54, // FFV1 Set REGS[SEL+4].hi32.
630 c.color1.rgba.R, c.color1.rgba.G, c.color1.rgba.B, c.color1.rgba.A)
631 }
632 v1 = append(v1, 0x55, // FFV1 Set REGS[SEL+5].hi32.
633 c.blend)
634 if c.color0.typ == ColorTypeRGBA {
635 v1 = append(v1, 0xfe)
636 } else {
637 v1 = append(v1, 0x80|c.color0.paletteIndex)
638 }
639 if c.color1.typ == ColorTypeRGBA {
640 v1 = append(v1, 0xff)
641 } else {
642 v1 = append(v1, 0x80|c.color1.paletteIndex)
643 }
644 v1 = append(v1, 0, 0x85) // FFV1 Fill (flat color) with REGS[SEL+5].
645 }
646
647 return v1, nil
648 }
649
650 func (u *upgrader) computeRunLength(verbs []uint8) int {
651 firstVerb := verbs[0]
652 if firstVerb == 0 {
653 return 1
654 }
655 n := 1
656 for ; (n < len(verbs)) && (verbs[n] == firstVerb); n++ {
657 }
658 return n
659 }
660
661 // looksLikeParallelogram3 is like looksLikeParallelogram4 but the final point
662 // (implied by the ClosePath op) is separate from the middle 3 args.
663 func (u *upgrader) looksLikeParallelogram3(curr *[2]float32, args [][2]float32, final *[2]float32) bool {
664 if len(args) != 3 {
665 panic("unreachable")
666 }
667 return (*curr == *final) &&
668 (curr[0] == (args[0][0] - args[1][0] + args[2][0])) &&
669 (curr[1] == (args[0][1] - args[1][1] + args[2][1]))
670 }
671
672 // looksLikeParallelogram4 returns whether the 5 coordinate pairs (A, B, C, D,
673 // E) form a parallelogram:
674 //
675 // E=A B
676 //
677 // o---------o
678 // \ \
679 // \ \
680 // \ \
681 // o---------o
682 // D C
683 //
684 // Specifically, it checks that (A == E) and ((A - B) == (D - C)). That last
685 // equation can be rearranged as (A == (B - C + D)).
686 //
687 // The motivation is that, if looksLikeParallelogram4 is true, then the 5 input
688 // coordinate pairs can then be compressed to 3: A, B and C. Or, if the current
689 // point A is implied by context then 4 input pairs can be compressed to 2.
690 func (u *upgrader) looksLikeParallelogram4(curr *[2]float32, args [][2]float32) bool {
691 if len(args) != 4 {
692 panic("unreachable")
693 }
694 return (*curr == args[3]) &&
695 (curr[0] == (args[0][0] - args[1][0] + args[2][0])) &&
696 (curr[1] == (args[0][1] - args[1][1] + args[2][1]))
697 }
698
699 // looksLikeEllipse returns whether the 13 coordinate pairs (A, A+, B-, B, B+,
700 // C- C, C+, D-, D, D+, A-, E) form a cubic Bézier approximation to an ellipse.
701 // Let A± denote the two tangent vectors (A+ - A) and (A - A-) and likewise for
702 // B±, C± and D±.
703 //
704 // A+ B-
705 //
706 // E=A o o B
707 // A- o---------o B+
708 //
709 // o \ \ o
710 // \ X \
711 // o \ \ o
712 // D+ o---------o C-
713 // D o o C
714 // D- C+
715 //
716 // See https://nigeltao.github.io/blog/2021/three-points-define-ellipse.html
717 // for a better version of that ASCII art.
718 //
719 // Specifically, it checks that (A, B, C, D, E), also known as (*curr, args[2],
720 // args[5], args[8] and args[11]), forms a parallelogram. If so, let X be the
721 // parallelogram center and define two axis vectors: r = B-X and s = C-X.
722 //
723 // These axes define the parallelogram's or ellipse's shape but they are not
724 // necessarily orthogonal and hence not necessarily the ellipse's major
725 // (longest) and minor (shortest) axes. If s is a 90 degree rotation of r then
726 // the parallelogram is a square and the ellipse is a circle.
727 //
728 // This function further checks that the A±, B± C± and D± tangents are
729 // approximately equal to +λ×r, +λ×s, -λ×r and -λ×s, where λ = ((math.Sqrt2 -
730 // 1) × 4 / 3) comes from the cubic Bézier approximation to a quarter-circle.
731 //
732 // The motivation is that, if looksLikeEllipse is true, then the 13 input
733 // coordinate pairs can then be compressed to 3: A, B and C. Or, if the current
734 // point A is implied by context then 12 input pairs can be compressed to 2.
735 func (u *upgrader) looksLikeEllipse(curr *[2]float32, args [][2]float32) bool {
736 if len(args) != 12 {
737 panic("unreachable")
738 }
739 if (*curr != args[11]) ||
740 (curr[0] != (args[2][0] - args[5][0] + args[8][0])) ||
741 (curr[1] != (args[2][1] - args[5][1] + args[8][1])) {
742 return false
743 }
744 center := [2]float32{
745 (args[2][0] + args[8][0]) / 2,
746 (args[2][1] + args[8][1]) / 2,
747 }
748
749 // 0.5522847498307933984022516322796 ≈ ((math.Sqrt2 - 1) × 4 / 3), the
750 // tangent lengths (as a fraction of the radius) for a commonly used cubic
751 // Bézier approximation to a circle. Multiplying that by 0.98 and 1.02
752 // checks that we're within 2% of that fraction.
753 //
754 // This also covers the slightly different 0.551784777779014 constant,
755 // recommended by https://pomax.github.io/bezierinfo/#circles_cubic
756 const λMin = 0.98 * 0.5522847498307933984022516322796
757 const λMax = 1.02 * 0.5522847498307933984022516322796
758
759 // Check the first axis.
760 r := [2]float32{
761 args[2][0] - center[0],
762 args[2][1] - center[1],
763 }
764 rMin := [2]float32{r[0] * λMin, r[1] * λMin}
765 rMax := [2]float32{r[0] * λMax, r[1] * λMax}
766 if rMin[0] > rMax[0] {
767 rMin[0], rMax[0] = rMax[0], rMin[0]
768 }
769 if rMin[1] > rMax[1] {
770 rMin[1], rMax[1] = rMax[1], rMin[1]
771 }
772 if !within(args[0][0]-curr[0], args[0][1]-curr[1], rMin, rMax) ||
773 !within(args[4][0]-args[5][0], args[4][1]-args[5][1], rMin, rMax) ||
774 !within(args[5][0]-args[6][0], args[5][1]-args[6][1], rMin, rMax) ||
775 !within(args[11][0]-args[10][0], args[11][1]-args[10][1], rMin, rMax) {
776 return false
777 }
778
779 // Check the second axis.
780 s := [2]float32{
781 args[5][0] - center[0],
782 args[5][1] - center[1],
783 }
784 sMin := [2]float32{s[0] * λMin, s[1] * λMin}
785 sMax := [2]float32{s[0] * λMax, s[1] * λMax}
786 if sMin[0] > sMax[0] {
787 sMin[0], sMax[0] = sMax[0], sMin[0]
788 }
789 if sMin[1] > sMax[1] {
790 sMin[1], sMax[1] = sMax[1], sMin[1]
791 }
792 if !within(args[2][0]-args[1][0], args[2][1]-args[1][1], sMin, sMax) ||
793 !within(args[3][0]-args[2][0], args[3][1]-args[2][1], sMin, sMax) ||
794 !within(args[7][0]-args[8][0], args[7][1]-args[8][1], sMin, sMax) ||
795 !within(args[8][0]-args[9][0], args[8][1]-args[9][1], sMin, sMax) {
796 return false
797 }
798
799 return true
800 }
801
802 func within(v0 float32, v1 float32, min [2]float32, max [2]float32) bool {
803 return (min[0] <= v0) && (v0 <= max[0]) && (min[1] <= v1) && (v1 <= max[1])
804 }
805
806 func (u *upgrader) upgradeArcs(pen *[2]float32, v1 buffer, v0 buffer) (newV1 buffer, newV0 buffer, retErr error) {
807 coords := [6]float32{}
808 largeArc, sweep := false, false
809 opcode := v0[0]
810 v0 = v0[1:]
811 nReps := 1 + int(opcode&0x0f)
812 for i := 0; i < nReps; i++ {
813 v0, retErr = decodeCoordinates(coords[:2], nil, v0)
814 if retErr != nil {
815 return nil, nil, retErr
816 }
817 coords[2], v0, retErr = decodeAngle(nil, v0)
818 if retErr != nil {
819 return nil, nil, retErr
820 }
821 largeArc, sweep, v0, retErr = decodeArcToFlags(nil, v0)
822 if retErr != nil {
823 return nil, nil, retErr
824 }
825 v0, retErr = decodeCoordinates(coords[4:6], nil, v0)
826 if retErr != nil {
827 return nil, nil, retErr
828 }
829 if (opcode >> 4) == 0x0d {
830 coords[4] += pen[0]
831 coords[5] += pen[1]
832 }
833 u.upgradeArc(pen, coords[0], coords[1], coords[2], largeArc, sweep, coords[4], coords[5])
834 pen[0] = coords[4]
835 pen[1] = coords[5]
836 }
837 return v1, v0, nil
838 }
839
840 func (u *upgrader) upgradeArc(pen *[2]float32, rx, ry, xAxisRotation float32, largeArc, sweep bool, finalX, finalY float32) {
841 // We follow the "Conversion from endpoint to center parameterization"
842 // algorithm as per
843 // https://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter
844
845 // There seems to be a bug in the spec's "implementation notes".
846 //
847 // Actual implementations, such as
848 // - https://git.gnome.org/browse/librsvg/tree/rsvg-path.c
849 // - http://svn.apache.org/repos/asf/xmlgraphics/batik/branches/svg11/sources/org/apache/batik/ext/awt/geom/ExtendedGeneralPath.java
850 // - https://java.net/projects/svgsalamander/sources/svn/content/trunk/svg-core/src/main/java/com/kitfox/svg/pathcmd/Arc.java
851 // - https://github.com/millermedeiros/SVGParser/blob/master/com/millermedeiros/geom/SVGArc.as
852 // do something slightly different (marked with a †).
853
854 // (†) The Abs isn't part of the spec. Neither is checking that Rx and Ry
855 // are non-zero (and non-NaN).
856 Rx := math.Abs(float64(rx))
857 Ry := math.Abs(float64(ry))
858 if !(Rx > 0 && Ry > 0) {
859 u.verbs = append(u.verbs, upgradeVerbLineTo)
860 u.args = append(u.args, [2]float32{finalX, finalY})
861 return
862 }
863
864 x1 := float64(pen[0])
865 y1 := float64(pen[1])
866 x2 := float64(finalX)
867 y2 := float64(finalY)
868
869 phi := 2 * math.Pi * float64(xAxisRotation)
870
871 // Step 1: Compute (x1′, y1′)
872 halfDx := (x1 - x2) / 2
873 halfDy := (y1 - y2) / 2
874 cosPhi := math.Cos(phi)
875 sinPhi := math.Sin(phi)
876 x1Prime := +cosPhi*halfDx + sinPhi*halfDy
877 y1Prime := -sinPhi*halfDx + cosPhi*halfDy
878
879 // Step 2: Compute (cx′, cy′)
880 rxSq := Rx * Rx
881 rySq := Ry * Ry
882 x1PrimeSq := x1Prime * x1Prime
883 y1PrimeSq := y1Prime * y1Prime
884
885 // (†) Check that the radii are large enough.
886 radiiCheck := x1PrimeSq/rxSq + y1PrimeSq/rySq
887 if radiiCheck > 1 {
888 c := math.Sqrt(radiiCheck)
889 Rx *= c
890 Ry *= c
891 rxSq = Rx * Rx
892 rySq = Ry * Ry
893 }
894
895 denom := rxSq*y1PrimeSq + rySq*x1PrimeSq
896 step2 := 0.0
897 if a := rxSq*rySq/denom - 1; a > 0 {
898 step2 = math.Sqrt(a)
899 }
900 if largeArc == sweep {
901 step2 = -step2
902 }
903 cxPrime := +step2 * Rx * y1Prime / Ry
904 cyPrime := -step2 * Ry * x1Prime / Rx
905
906 // Step 3: Compute (cx, cy) from (cx′, cy′)
907 cx := +cosPhi*cxPrime - sinPhi*cyPrime + (x1+x2)/2
908 cy := +sinPhi*cxPrime + cosPhi*cyPrime + (y1+y2)/2
909
910 // Step 4: Compute θ1 and Δθ
911 ax := (+x1Prime - cxPrime) / Rx
912 ay := (+y1Prime - cyPrime) / Ry
913 bx := (-x1Prime - cxPrime) / Rx
914 by := (-y1Prime - cyPrime) / Ry
915 theta1 := angle(1, 0, ax, ay)
916 deltaTheta := angle(ax, ay, bx, by)
917 if sweep {
918 if deltaTheta < 0 {
919 deltaTheta += 2 * math.Pi
920 }
921 } else {
922 if deltaTheta > 0 {
923 deltaTheta -= 2 * math.Pi
924 }
925 }
926
927 // This ends the
928 // https://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter
929 // algorithm. What follows below is specific to this implementation.
930
931 // We approximate an arc by one or more cubic Bézier curves.
932 n := int(math.Ceil(math.Abs(deltaTheta) / (math.Pi/2 + 0.001)))
933 for i := 0; i < n; i++ {
934 u.arcSegmentTo(cx, cy,
935 theta1+deltaTheta*float64(i+0)/float64(n),
936 theta1+deltaTheta*float64(i+1)/float64(n),
937 Rx, Ry, cosPhi, sinPhi,
938 )
939 }
940 }
941
942 // arcSegmentTo approximates an arc by a cubic Bézier curve. The mathematical
943 // formulae for the control points are the same as that used by librsvg.
944 func (u *upgrader) arcSegmentTo(cx, cy, theta1, theta2, rx, ry, cosPhi, sinPhi float64) {
945 halfDeltaTheta := (theta2 - theta1) * 0.5
946 q := math.Sin(halfDeltaTheta * 0.5)
947 t := (8 * q * q) / (3 * math.Sin(halfDeltaTheta))
948 cos1 := math.Cos(theta1)
949 sin1 := math.Sin(theta1)
950 cos2 := math.Cos(theta2)
951 sin2 := math.Sin(theta2)
952 x1 := rx * (+cos1 - t*sin1)
953 y1 := ry * (+sin1 + t*cos1)
954 x2 := rx * (+cos2 + t*sin2)
955 y2 := ry * (+sin2 - t*cos2)
956 x3 := rx * (+cos2)
957 y3 := ry * (+sin2)
958 highResolutionCoordinates := u.opts.ArcsExpandWithHighResolutionCoordinates
959 u.verbs = append(u.verbs, upgradeVerbCubeTo)
960 u.args = append(u.args,
961 [2]float32{
962 quantize(float32(cx+cosPhi*x1-sinPhi*y1), highResolutionCoordinates),
963 quantize(float32(cy+sinPhi*x1+cosPhi*y1), highResolutionCoordinates),
964 },
965 [2]float32{
966 quantize(float32(cx+cosPhi*x2-sinPhi*y2), highResolutionCoordinates),
967 quantize(float32(cy+sinPhi*x2+cosPhi*y2), highResolutionCoordinates),
968 },
969 [2]float32{
970 quantize(float32(cx+cosPhi*x3-sinPhi*y3), highResolutionCoordinates),
971 quantize(float32(cy+sinPhi*x3+cosPhi*y3), highResolutionCoordinates),
972 },
973 )
974 }
975
976 func countFFV1Instructions(src buffer) (ret uint64) {
977 for len(src) > 0 {
978 ret++
979 opcode := src[0]
980 src = src[1:]
981
982 switch {
983 case opcode < 0x40:
984 switch {
985 case opcode < 0x30:
986 nReps := uint32(opcode & 15)
987 if nReps == 0 {
988 n := 0
989 nReps, n = src.decodeNaturalFFV1()
990 src = src[n:]
991 nReps += 16
992 }
993 nCoords := 2 * (1 + int(opcode>>4))
994 for ; nReps > 0; nReps-- {
995 for i := 0; i < nCoords; i++ {
996 _, n := src.decodeNaturalFFV1()
997 src = src[n:]
998 }
999 }
1000 case opcode < 0x35:
1001 for i := 0; i < 4; i++ {
1002 _, n := src.decodeNaturalFFV1()
1003 src = src[n:]
1004 }
1005 case opcode == 0x35:
1006 for i := 0; i < 2; i++ {
1007 _, n := src.decodeNaturalFFV1()
1008 src = src[n:]
1009 }
1010 case opcode == 0x36:
1011 src = src[1:]
1012 case opcode == 0x37:
1013 // No-op.
1014 default:
1015 // upgradeBytecode (with calculatingJumpLOD set) will not emit
1016 // jump or call instructions.
1017 panic("unexpected FFV1 instruction")
1018 }
1019
1020 case opcode < 0x80:
1021 switch (opcode >> 4) & 3 {
1022 case 0, 1:
1023 src = src[4:]
1024 case 2:
1025 src = src[8:]
1026 default:
1027 src = src[8*(2+int(opcode&15)):]
1028 }
1029
1030 case opcode < 0xc0:
1031 switch (opcode >> 4) & 3 {
1032 case 0:
1033 // No-op.
1034 case 1:
1035 src = src[13:]
1036 case 2:
1037 src = src[25:]
1038 default:
1039 // upgradeBytecode (with calculatingJumpLOD set) will not emit
1040 // reserved instructions.
1041 panic("unexpected FFV1 instruction")
1042 }
1043
1044 default:
1045 // upgradeBytecode (with calculatingJumpLOD set) will not emit
1046 // reserved instructions.
1047 panic("unexpected FFV1 instruction")
1048 }
1049 }
1050 return ret
1051 }
1052
1053 type upgradeColor struct {
1054 typ ColorType
1055 paletteIndex uint8
1056 blend uint8
1057 rgba color.RGBA
1058 color0 *upgradeColor
1059 color1 *upgradeColor
1060 }
1061
1062 func (u *upgrader) resolve(c Color, denyBlend bool) (upgradeColor, error) {
1063 switch c.typ {
1064 case ColorTypeRGBA:
1065 return upgradeColor{
1066 typ: ColorTypeRGBA,
1067 rgba: c.data,
1068 }, nil
1069 case ColorTypePaletteIndex:
1070 return upgradeColor{
1071 typ: ColorTypePaletteIndex,
1072 paletteIndex: c.paletteIndex(),
1073 }, nil
1074 case ColorTypeCReg:
1075 upgrade := u.creg[c.cReg()]
1076 if denyBlend && (upgrade.typ == ColorTypeBlend) {
1077 return upgradeColor{}, errUnsupportedUpgrade
1078 }
1079 return upgrade, nil
1080 }
1081
1082 if denyBlend {
1083 return upgradeColor{}, errUnsupportedUpgrade
1084 }
1085 t, c0, c1 := c.blend()
1086 color0, err := u.resolve(decodeColor1(c0), true)
1087 if err != nil {
1088 return upgradeColor{}, err
1089 }
1090 color1, err := u.resolve(decodeColor1(c1), true)
1091 if err != nil {
1092 return upgradeColor{}, err
1093 }
1094 return upgradeColor{
1095 typ: ColorTypeBlend,
1096 blend: t,
1097 color0: &color0,
1098 color1: &color1,
1099 }, nil
1100 }