hint.go 43.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
// Copyright 2012 The Freetype-Go Authors. All rights reserved.
// Use of this source code is governed by your choice of either the
// FreeType License or the GNU General Public License version 2 (or
// any later version), both of which can be found in the LICENSE file.

package truetype

// This file implements a Truetype bytecode interpreter.
// The opcodes are described at https://developer.apple.com/fonts/TTRefMan/RM05/Chap5.html

import (
	"errors"
13
	"math"
14 15

	"golang.org/x/image/math/fixed"
16 17
)

18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
const (
	twilightZone = 0
	glyphZone    = 1
	numZone      = 2
)

type pointType uint32

const (
	current      pointType = 0
	unhinted     pointType = 1
	inFontUnits  pointType = 2
	numPointType           = 3
)

33 34 35 36 37 38 39
// callStackEntry is a bytecode call stack entry.
type callStackEntry struct {
	program   []byte
	pc        int
	loopCount int32
}

40 41 42
// hinter implements bytecode hinting. A hinter can be re-used to hint a series
// of glyphs from a Font.
type hinter struct {
43
	stack, store []int32
44

45 46 47
	// functions is a map from function number to bytecode.
	functions map[int32][]byte

48
	// font and scale are the font and scale last used for this hinter.
49 50
	// Changing the font will require running the new font's fpgm bytecode.
	// Changing either will require running the font's prep bytecode.
51
	font  *Font
52
	scale fixed.Int26_6
53

54 55 56 57
	// gs and defaultGS are the current and default graphics state. The
	// default graphics state is the global default graphics state after
	// the font's fpgm and prep programs have been run.
	gs, defaultGS graphicsState
58

59 60 61 62
	// points and ends are the twilight zone's points, glyph's points
	// and glyph's contour boundaries.
	points [numZone][numPointType][]Point
	ends   []int
63 64 65

	// scaledCVT is the lazily initialized scaled Control Value Table.
	scaledCVTInitialized bool
66
	scaledCVT            []fixed.Int26_6
67
}
68

69 70
// graphicsState is described at https://developer.apple.com/fonts/TTRefMan/RM04/Chap4.html
type graphicsState struct {
71 72
	// Projection vector, freedom vector and dual projection vector.
	pv, fv, dv [2]f2dot14
73 74 75
	// Reference points and zone pointers.
	rp, zp [3]int32
	// Control Value / Single Width Cut-In.
76
	controlValueCutIn, singleWidthCutIn, singleWidth fixed.Int26_6
77 78
	// Delta base / shift.
	deltaBase, deltaShift int32
79
	// Minimum distance.
80
	minDist fixed.Int26_6
81 82 83
	// Loop count.
	loop int32
	// Rounding policy.
84
	roundPeriod, roundPhase, roundThreshold fixed.Int26_6
85
	roundSuper45                            bool
86 87 88 89 90 91 92 93 94
	// Auto-flip.
	autoFlip bool
}

var globalDefaultGS = graphicsState{
	pv:                [2]f2dot14{0x4000, 0}, // Unit vector along the X axis.
	fv:                [2]f2dot14{0x4000, 0},
	dv:                [2]f2dot14{0x4000, 0},
	zp:                [3]int32{1, 1, 1},
95
	controlValueCutIn: (17 << 6) / 16, // 17/16 as a fixed.Int26_6.
96 97
	deltaBase:         9,
	deltaShift:        3,
98
	minDist:           1 << 6, // 1 as a fixed.Int26_6.
99
	loop:              1,
100 101
	roundPeriod:       1 << 6, // 1 as a fixed.Int26_6.
	roundThreshold:    1 << 5, // 1/2 as a fixed.Int26_6.
102
	roundSuper45:      false,
103
	autoFlip:          true,
104 105
}

106
func resetTwilightPoints(f *Font, p []Point) []Point {
107
	if n := int(f.maxTwilightPoints) + 4; n <= cap(p) {
108 109 110 111 112 113 114 115 116 117
		p = p[:n]
		for i := range p {
			p[i] = Point{}
		}
	} else {
		p = make([]Point, n)
	}
	return p
}

118
func (h *hinter) init(f *Font, scale fixed.Int26_6) error {
119 120 121
	h.points[twilightZone][0] = resetTwilightPoints(f, h.points[twilightZone][0])
	h.points[twilightZone][1] = resetTwilightPoints(f, h.points[twilightZone][1])
	h.points[twilightZone][2] = resetTwilightPoints(f, h.points[twilightZone][2])
122

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
	rescale := h.scale != scale
	if h.font != f {
		h.font, rescale = f, true
		if h.functions == nil {
			h.functions = make(map[int32][]byte)
		} else {
			for k := range h.functions {
				delete(h.functions, k)
			}
		}

		if x := int(f.maxStackElements); x > len(h.stack) {
			x += 255
			x &^= 255
			h.stack = make([]int32, x)
		}
		if x := int(f.maxStorage); x > len(h.store) {
			x += 15
			x &^= 15
			h.store = make([]int32, x)
		}
		if len(f.fpgm) != 0 {
145
			if err := h.run(f.fpgm, nil, nil, nil, nil); err != nil {
146 147 148
				return err
			}
		}
149
	}
150 151 152

	if rescale {
		h.scale = scale
153
		h.scaledCVTInitialized = false
154 155 156

		h.defaultGS = globalDefaultGS

157
		if len(f.prep) != 0 {
158
			if err := h.run(f.prep, nil, nil, nil, nil); err != nil {
159 160
				return err
			}
161 162 163 164 165 166 167 168 169
			h.defaultGS = h.gs
			// The MS rasterizer doesn't allow the following graphics state
			// variables to be modified by the CVT program.
			h.defaultGS.pv = globalDefaultGS.pv
			h.defaultGS.fv = globalDefaultGS.fv
			h.defaultGS.dv = globalDefaultGS.dv
			h.defaultGS.rp = globalDefaultGS.rp
			h.defaultGS.zp = globalDefaultGS.zp
			h.defaultGS.loop = globalDefaultGS.loop
170
		}
171
	}
172
	return nil
173 174
}

175
func (h *hinter) run(program []byte, pCurrent, pUnhinted, pInFontUnits []Point, ends []int) error {
176
	h.gs = h.defaultGS
177 178 179 180
	h.points[glyphZone][current] = pCurrent
	h.points[glyphZone][unhinted] = pUnhinted
	h.points[glyphZone][inFontUnits] = pInFontUnits
	h.ends = ends
N
Nigel Tao 已提交
181

N
Nigel Tao 已提交
182 183 184
	if len(program) > 50000 {
		return errors.New("truetype: hinting: too many instructions")
	}
185 186 187
	var (
		steps, pc, top int
		opcode         uint8
188 189 190

		callStack    [32]callStackEntry
		callStackTop int
191
	)
192

193
	for 0 <= pc && pc < len(program) {
194 195
		steps++
		if steps == 100000 {
N
Nigel Tao 已提交
196
			return errors.New("truetype: hinting: too many steps")
197 198 199 200 201 202 203
		}
		opcode = program[pc]
		if top < int(popCount[opcode]) {
			return errors.New("truetype: hinting: stack underflow")
		}
		switch opcode {

204
		case opSVTCA0:
205 206
			h.gs.pv = [2]f2dot14{0, 0x4000}
			h.gs.fv = [2]f2dot14{0, 0x4000}
207
			h.gs.dv = [2]f2dot14{0, 0x4000}
208 209

		case opSVTCA1:
210 211
			h.gs.pv = [2]f2dot14{0x4000, 0}
			h.gs.fv = [2]f2dot14{0x4000, 0}
212
			h.gs.dv = [2]f2dot14{0x4000, 0}
213 214

		case opSPVTCA0:
215
			h.gs.pv = [2]f2dot14{0, 0x4000}
216
			h.gs.dv = [2]f2dot14{0, 0x4000}
217 218

		case opSPVTCA1:
219
			h.gs.pv = [2]f2dot14{0x4000, 0}
220
			h.gs.dv = [2]f2dot14{0x4000, 0}
221 222

		case opSFVTCA0:
223
			h.gs.fv = [2]f2dot14{0, 0x4000}
224 225

		case opSFVTCA1:
226
			h.gs.fv = [2]f2dot14{0x4000, 0}
227

228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
		case opSPVTL0, opSPVTL1, opSFVTL0, opSFVTL1:
			top -= 2
			p1 := h.point(0, current, h.stack[top+0])
			p2 := h.point(0, current, h.stack[top+1])
			if p1 == nil || p2 == nil {
				return errors.New("truetype: hinting: point out of range")
			}
			dx := f2dot14(p1.X - p2.X)
			dy := f2dot14(p1.Y - p2.Y)
			if dx == 0 && dy == 0 {
				dx = 0x4000
			} else if opcode&1 != 0 {
				// Counter-clockwise rotation.
				dx, dy = -dy, dx
			}
			v := normalize(dx, dy)
			if opcode < opSFVTL0 {
				h.gs.pv = v
				h.gs.dv = v
			} else {
				h.gs.fv = v
			}

251 252
		case opSPVFS:
			top -= 2
253 254
			h.gs.pv = normalize(f2dot14(h.stack[top]), f2dot14(h.stack[top+1]))
			h.gs.dv = h.gs.pv
255 256 257

		case opSFVFS:
			top -= 2
258
			h.gs.fv = normalize(f2dot14(h.stack[top]), f2dot14(h.stack[top+1]))
259 260 261 262 263

		case opGPV:
			if top+1 >= len(h.stack) {
				return errors.New("truetype: hinting: stack overflow")
			}
264 265
			h.stack[top+0] = int32(h.gs.pv[0])
			h.stack[top+1] = int32(h.gs.pv[1])
266 267 268 269 270 271
			top += 2

		case opGFV:
			if top+1 >= len(h.stack) {
				return errors.New("truetype: hinting: stack overflow")
			}
272 273
			h.stack[top+0] = int32(h.gs.fv[0])
			h.stack[top+1] = int32(h.gs.fv[1])
274 275 276
			top += 2

		case opSFVTPV:
277 278
			h.gs.fv = h.gs.pv

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
		case opISECT:
			top -= 5
			p := h.point(2, current, h.stack[top+0])
			a0 := h.point(1, current, h.stack[top+1])
			a1 := h.point(1, current, h.stack[top+2])
			b0 := h.point(0, current, h.stack[top+3])
			b1 := h.point(0, current, h.stack[top+4])
			if p == nil || a0 == nil || a1 == nil || b0 == nil || b1 == nil {
				return errors.New("truetype: hinting: point out of range")
			}

			dbx := b1.X - b0.X
			dby := b1.Y - b0.Y
			dax := a1.X - a0.X
			day := a1.Y - a0.Y
			dx := b0.X - a0.X
			dy := b0.Y - a0.Y
			discriminant := mulDiv(int64(dax), int64(-dby), 0x40) +
				mulDiv(int64(day), int64(dbx), 0x40)
			dotProduct := mulDiv(int64(dax), int64(dbx), 0x40) +
				mulDiv(int64(day), int64(dby), 0x40)
			// The discriminant above is actually a cross product of vectors
			// da and db. Together with the dot product, they can be used as
			// surrogates for sine and cosine of the angle between the vectors.
			// Indeed,
			//       dotproduct   = |da||db|cos(angle)
			//       discriminant = |da||db|sin(angle)
			// We use these equations to reject grazing intersections by
			// thresholding abs(tan(angle)) at 1/19, corresponding to 3 degrees.
			absDisc, absDotP := discriminant, dotProduct
			if absDisc < 0 {
				absDisc = -absDisc
			}
			if absDotP < 0 {
				absDotP = -absDotP
			}
			if 19*absDisc > absDotP {
				val := mulDiv(int64(dx), int64(-dby), 0x40) +
					mulDiv(int64(dy), int64(dbx), 0x40)
				rx := mulDiv(val, int64(dax), discriminant)
				ry := mulDiv(val, int64(day), discriminant)
320 321
				p.X = a0.X + fixed.Int26_6(rx)
				p.Y = a0.Y + fixed.Int26_6(ry)
322 323 324 325 326 327
			} else {
				p.X = (a0.X + a1.X + b0.X + b1.X) / 4
				p.Y = (a0.Y + a1.Y + b0.Y + b1.Y) / 4
			}
			p.Flags |= flagTouchedX | flagTouchedY

328 329 330 331 332 333 334 335 336 337 338 339 340
		case opSRP0, opSRP1, opSRP2:
			top--
			h.gs.rp[opcode-opSRP0] = h.stack[top]

		case opSZP0, opSZP1, opSZP2:
			top--
			h.gs.zp[opcode-opSZP0] = h.stack[top]

		case opSZPS:
			top--
			h.gs.zp[0] = h.stack[top]
			h.gs.zp[1] = h.stack[top]
			h.gs.zp[2] = h.stack[top]
341 342 343

		case opSLOOP:
			top--
344 345 346 347 348 349 350 351
			// https://developer.apple.com/fonts/TrueType-Reference-Manual/RM05/Chap5.html#SLOOP
			// says that "Setting the loop variable to zero is an error". In
			// theory, the inequality on the next line should be "<=" instead
			// of "<". In practice, some font files' bytecode, such as the '2'
			// glyph in the DejaVuSansMono.ttf that comes with Ubuntu 14.04,
			// issue SLOOP with a zero on top of the stack. Just like the C
			// Freetype code, we allow the zero.
			if h.stack[top] < 0 {
352 353
				return errors.New("truetype: hinting: invalid data")
			}
354
			h.gs.loop = h.stack[top]
355

N
Nigel Tao 已提交
356
		case opRTG:
357 358 359
			h.gs.roundPeriod = 1 << 6
			h.gs.roundPhase = 0
			h.gs.roundThreshold = 1 << 5
360
			h.gs.roundSuper45 = false
N
Nigel Tao 已提交
361 362

		case opRTHG:
363 364 365
			h.gs.roundPeriod = 1 << 6
			h.gs.roundPhase = 1 << 5
			h.gs.roundThreshold = 1 << 5
366
			h.gs.roundSuper45 = false
N
Nigel Tao 已提交
367

368 369
		case opSMD:
			top--
370
			h.gs.minDist = fixed.Int26_6(h.stack[top])
371

N
Nigel Tao 已提交
372 373 374 375
		case opELSE:
			opcode = 1
			goto ifelse

N
Nigel Tao 已提交
376 377 378 379 380
		case opJMPR:
			top--
			pc += int(h.stack[top])
			continue

381 382
		case opSCVTCI:
			top--
383
			h.gs.controlValueCutIn = fixed.Int26_6(h.stack[top])
384 385 386

		case opSSWCI:
			top--
387
			h.gs.singleWidthCutIn = fixed.Int26_6(h.stack[top])
388 389 390

		case opSSW:
			top--
391
			h.gs.singleWidth = h.font.scale(h.scale * fixed.Int26_6(h.stack[top]))
392

393
		case opDUP:
394
			if top >= len(h.stack) {
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
				return errors.New("truetype: hinting: stack overflow")
			}
			h.stack[top] = h.stack[top-1]
			top++

		case opPOP:
			top--

		case opCLEAR:
			top = 0

		case opSWAP:
			h.stack[top-1], h.stack[top-2] = h.stack[top-2], h.stack[top-1]

		case opDEPTH:
410
			if top >= len(h.stack) {
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
				return errors.New("truetype: hinting: stack overflow")
			}
			h.stack[top] = int32(top)
			top++

		case opCINDEX, opMINDEX:
			x := int(h.stack[top-1])
			if x <= 0 || x >= top {
				return errors.New("truetype: hinting: invalid data")
			}
			h.stack[top-1] = h.stack[top-1-x]
			if opcode == opMINDEX {
				copy(h.stack[top-1-x:top-1], h.stack[top-x:top])
				top--
			}

427 428 429 430 431 432 433
		case opALIGNPTS:
			top -= 2
			p := h.point(1, current, h.stack[top])
			q := h.point(0, current, h.stack[top+1])
			if p == nil || q == nil {
				return errors.New("truetype: hinting: point out of range")
			}
434
			d := dotProduct(fixed.Int26_6(q.X-p.X), fixed.Int26_6(q.Y-p.Y), h.gs.pv) / 2
435 436 437 438 439 440 441 442 443 444 445
			h.move(p, +d, true)
			h.move(q, -d, true)

		case opUTP:
			top--
			p := h.point(0, current, h.stack[top])
			if p == nil {
				return errors.New("truetype: hinting: point out of range")
			}
			p.Flags &^= flagTouchedX | flagTouchedY

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
		case opLOOPCALL, opCALL:
			if callStackTop >= len(callStack) {
				return errors.New("truetype: hinting: call stack overflow")
			}
			top--
			f, ok := h.functions[h.stack[top]]
			if !ok {
				return errors.New("truetype: hinting: undefined function")
			}
			callStack[callStackTop] = callStackEntry{program, pc, 1}
			if opcode == opLOOPCALL {
				top--
				if h.stack[top] == 0 {
					break
				}
				callStack[callStackTop].loopCount = h.stack[top]
			}
			callStackTop++
			program, pc = f, 0
			continue

		case opFDEF:
			// Save all bytecode up until the next ENDF.
			startPC := pc + 1
		fdefloop:
			for {
				pc++
				if pc >= len(program) {
					return errors.New("truetype: hinting: unbalanced FDEF")
				}
				switch program[pc] {
				case opFDEF:
					return errors.New("truetype: hinting: nested FDEF")
				case opENDF:
					top--
					h.functions[h.stack[top]] = program[startPC : pc+1]
					break fdefloop
				default:
					var ok bool
					pc, ok = skipInstructionPayload(program, pc)
					if !ok {
						return errors.New("truetype: hinting: unbalanced FDEF")
					}
				}
			}

		case opENDF:
			if callStackTop == 0 {
				return errors.New("truetype: hinting: call stack underflow")
			}
			callStackTop--
			callStack[callStackTop].loopCount--
			if callStack[callStackTop].loopCount != 0 {
				callStackTop++
				pc = 0
				continue
			}
			program, pc = callStack[callStackTop].program, callStack[callStackTop].pc

505 506
		case opMDAP0, opMDAP1:
			top--
507 508 509
			i := h.stack[top]
			p := h.point(0, current, i)
			if p == nil {
510 511
				return errors.New("truetype: hinting: point out of range")
			}
512
			distance := fixed.Int26_6(0)
513
			if opcode == opMDAP1 {
514
				distance = dotProduct(p.X, p.Y, h.gs.pv)
515 516 517
				// TODO: metrics compensation.
				distance = h.round(distance) - distance
			}
518
			h.move(p, distance, true)
519 520 521 522
			h.gs.rp[0] = i
			h.gs.rp[1] = i

		case opIUP0, opIUP1:
523 524 525 526 527
			iupY, mask := opcode == opIUP0, uint32(flagTouchedX)
			if iupY {
				mask = flagTouchedY
			}
			prevEnd := 0
528
			for _, end := range h.ends {
529
				for i := prevEnd; i < end; i++ {
530
					for i < end && h.points[glyphZone][current][i].Flags&mask == 0 {
531 532 533 534 535 536 537 538
						i++
					}
					if i == end {
						break
					}
					firstTouched, curTouched := i, i
					i++
					for ; i < end; i++ {
539
						if h.points[glyphZone][current][i].Flags&mask != 0 {
540 541 542 543 544 545 546 547 548 549 550 551
							h.iupInterp(iupY, curTouched+1, i-1, curTouched, i)
							curTouched = i
						}
					}
					if curTouched == firstTouched {
						h.iupShift(iupY, prevEnd, end, curTouched)
					} else {
						h.iupInterp(iupY, curTouched+1, end-1, curTouched, firstTouched)
						if firstTouched > 0 {
							h.iupInterp(iupY, prevEnd, firstTouched-1, curTouched, firstTouched)
						}
					}
552
				}
553
				prevEnd = end
554 555
			}

556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
		case opSHP0, opSHP1:
			if top < int(h.gs.loop) {
				return errors.New("truetype: hinting: stack underflow")
			}
			_, _, d, ok := h.displacement(opcode&1 == 0)
			if !ok {
				return errors.New("truetype: hinting: point out of range")
			}
			for ; h.gs.loop != 0; h.gs.loop-- {
				top--
				p := h.point(2, current, h.stack[top])
				if p == nil {
					return errors.New("truetype: hinting: point out of range")
				}
				h.move(p, d, true)
			}
			h.gs.loop = 1

574 575
		case opSHC0, opSHC1:
			top--
576
			zonePointer, i, d, ok := h.displacement(opcode&1 == 0)
577 578 579 580 581 582 583 584 585 586 587
			if !ok {
				return errors.New("truetype: hinting: point out of range")
			}
			if h.gs.zp[2] == 0 {
				// TODO: implement this when we have a glyph that does this.
				return errors.New("hinting: unimplemented SHC instruction")
			}
			contour := h.stack[top]
			if contour < 0 || len(ends) <= int(contour) {
				return errors.New("truetype: hinting: contour out of range")
			}
588
			j0, j1 := int32(0), int32(h.ends[contour])
589
			if contour > 0 {
590
				j0 = int32(h.ends[contour-1])
591
			}
592
			move := h.gs.zp[zonePointer] != h.gs.zp[2]
593
			for j := j0; j < j1; j++ {
594
				if move || j != i {
N
Nigel Tao 已提交
595
					h.move(h.point(2, current, j), d, true)
596
				}
597 598
			}

599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
		case opSHZ0, opSHZ1:
			top--
			zonePointer, i, d, ok := h.displacement(opcode&1 == 0)
			if !ok {
				return errors.New("truetype: hinting: point out of range")
			}

			// As per C Freetype, SHZ doesn't move the phantom points, or mark
			// the points as touched.
			limit := int32(len(h.points[h.gs.zp[2]][current]))
			if h.gs.zp[2] == glyphZone {
				limit -= 4
			}
			for j := int32(0); j < limit; j++ {
				if i != j || h.gs.zp[zonePointer] != h.gs.zp[2] {
					h.move(h.point(2, current, j), d, false)
				}
			}

		case opSHPIX:
			top--
620
			d := fixed.Int26_6(h.stack[top])
621 622 623 624 625 626 627 628 629 630 631 632 633
			if top < int(h.gs.loop) {
				return errors.New("truetype: hinting: stack underflow")
			}
			for ; h.gs.loop != 0; h.gs.loop-- {
				top--
				p := h.point(2, current, h.stack[top])
				if p == nil {
					return errors.New("truetype: hinting: point out of range")
				}
				h.move(p, d, true)
			}
			h.gs.loop = 1

634 635 636 637 638 639 640 641 642 643 644
		case opIP:
			if top < int(h.gs.loop) {
				return errors.New("truetype: hinting: stack underflow")
			}
			pointType := inFontUnits
			twilight := h.gs.zp[0] == 0 || h.gs.zp[1] == 0 || h.gs.zp[2] == 0
			if twilight {
				pointType = unhinted
			}
			p := h.point(1, pointType, h.gs.rp[2])
			oldP := h.point(0, pointType, h.gs.rp[1])
645
			oldRange := dotProduct(p.X-oldP.X, p.Y-oldP.Y, h.gs.dv)
646 647 648

			p = h.point(1, current, h.gs.rp[2])
			curP := h.point(0, current, h.gs.rp[1])
649
			curRange := dotProduct(p.X-curP.X, p.Y-curP.Y, h.gs.pv)
650 651 652 653
			for ; h.gs.loop != 0; h.gs.loop-- {
				top--
				i := h.stack[top]
				p = h.point(2, pointType, i)
654
				oldDist := dotProduct(p.X-oldP.X, p.Y-oldP.Y, h.gs.dv)
655
				p = h.point(2, current, i)
656 657
				curDist := dotProduct(p.X-curP.X, p.Y-curP.Y, h.gs.pv)
				newDist := fixed.Int26_6(0)
658 659
				if oldDist != 0 {
					if oldRange != 0 {
660
						newDist = fixed.Int26_6(mulDiv(int64(oldDist), int64(curRange), int64(oldRange)))
661 662 663 664
					} else {
						newDist = -oldDist
					}
				}
665
				h.move(p, newDist-curDist, true)
666 667
			}
			h.gs.loop = 1
668

669 670 671
		case opMSIRP0, opMSIRP1:
			top -= 2
			i := h.stack[top]
672
			distance := fixed.Int26_6(h.stack[top+1])
673 674 675 676 677 678 679

			// TODO: special case h.gs.zp[1] == 0 in C Freetype.
			ref := h.point(0, current, h.gs.rp[0])
			p := h.point(1, current, i)
			if ref == nil || p == nil {
				return errors.New("truetype: hinting: point out of range")
			}
680
			curDist := dotProduct(p.X-ref.X, p.Y-ref.Y, h.gs.pv)
681 682 683 684 685 686 687 688 689 690 691

			// Set-RP0 bit.
			if opcode == opMSIRP1 {
				h.gs.rp[0] = i
			}
			h.gs.rp[1] = h.gs.rp[0]
			h.gs.rp[2] = i

			// Move the point.
			h.move(p, distance-curDist, true)

692 693 694 695
		case opALIGNRP:
			if top < int(h.gs.loop) {
				return errors.New("truetype: hinting: stack underflow")
			}
696
			ref := h.point(0, current, h.gs.rp[0])
697
			if ref == nil {
698 699 700 701
				return errors.New("truetype: hinting: point out of range")
			}
			for ; h.gs.loop != 0; h.gs.loop-- {
				top--
702 703
				p := h.point(1, current, h.stack[top])
				if p == nil {
704 705
					return errors.New("truetype: hinting: point out of range")
				}
706
				h.move(p, -dotProduct(p.X-ref.X, p.Y-ref.Y, h.gs.pv), true)
707 708 709
			}
			h.gs.loop = 1

N
Nigel Tao 已提交
710
		case opRTDG:
711 712 713
			h.gs.roundPeriod = 1 << 5
			h.gs.roundPhase = 0
			h.gs.roundThreshold = 1 << 4
714
			h.gs.roundSuper45 = false
N
Nigel Tao 已提交
715

716 717 718
		case opMIAP0, opMIAP1:
			top -= 2
			i := h.stack[top]
719
			distance := h.getScaledCVT(h.stack[top+1])
720 721 722
			if h.gs.zp[0] == 0 {
				p := h.point(0, unhinted, i)
				q := h.point(0, current, i)
723 724
				p.X = fixed.Int26_6((int64(distance) * int64(h.gs.fv[0])) >> 14)
				p.Y = fixed.Int26_6((int64(distance) * int64(h.gs.fv[1])) >> 14)
725 726 727
				*q = *p
			}
			p := h.point(0, current, i)
728
			oldDist := dotProduct(p.X, p.Y, h.gs.pv)
729
			if opcode == opMIAP1 {
730
				if fabs(distance-oldDist) > h.gs.controlValueCutIn {
731 732 733 734 735
					distance = oldDist
				}
				// TODO: metrics compensation.
				distance = h.round(distance)
			}
736
			h.move(p, distance-oldDist, true)
737 738 739
			h.gs.rp[0] = i
			h.gs.rp[1] = i

740 741 742 743 744 745 746 747
		case opNPUSHB:
			opcode = 0
			goto push

		case opNPUSHW:
			opcode = 0x80
			goto push

748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
		case opWS:
			top -= 2
			i := int(h.stack[top])
			if i < 0 || len(h.store) <= i {
				return errors.New("truetype: hinting: invalid data")
			}
			h.store[i] = h.stack[top+1]

		case opRS:
			i := int(h.stack[top-1])
			if i < 0 || len(h.store) <= i {
				return errors.New("truetype: hinting: invalid data")
			}
			h.stack[top-1] = h.store[i]

763 764
		case opWCVTP:
			top -= 2
765
			h.setScaledCVT(h.stack[top], fixed.Int26_6(h.stack[top+1]))
766 767 768 769

		case opRCVT:
			h.stack[top-1] = int32(h.getScaledCVT(h.stack[top-1]))

770 771 772 773
		case opGC0, opGC1:
			i := h.stack[top-1]
			if opcode == opGC0 {
				p := h.point(2, current, i)
774
				h.stack[top-1] = int32(dotProduct(p.X, p.Y, h.gs.pv))
775 776 777
			} else {
				p := h.point(2, unhinted, i)
				// Using dv as per C Freetype.
778
				h.stack[top-1] = int32(dotProduct(p.X, p.Y, h.gs.dv))
779 780
			}

781 782 783 784 785 786 787
		case opSCFS:
			top -= 2
			i := h.stack[top]
			p := h.point(2, current, i)
			if p == nil {
				return errors.New("truetype: hinting: point out of range")
			}
788 789
			c := dotProduct(p.X, p.Y, h.gs.pv)
			h.move(p, fixed.Int26_6(h.stack[top+1])-c, true)
790 791 792 793 794 795 796 797 798 799
			if h.gs.zp[2] != 0 {
				break
			}
			q := h.point(2, unhinted, i)
			if q == nil {
				return errors.New("truetype: hinting: point out of range")
			}
			q.X = p.X
			q.Y = p.Y

800 801
		case opMD0, opMD1:
			top--
802 803 804 805 806 807 808
			pt, v, scale := pointType(0), [2]f2dot14{}, false
			if opcode == opMD0 {
				pt = current
				v = h.gs.pv
			} else if h.gs.zp[0] == 0 || h.gs.zp[1] == 0 {
				pt = unhinted
				v = h.gs.dv
809
			} else {
810 811 812 813 814 815 816 817 818
				pt = inFontUnits
				v = h.gs.dv
				scale = true
			}
			p := h.point(0, pt, h.stack[top-1])
			q := h.point(1, pt, h.stack[top])
			if p == nil || q == nil {
				return errors.New("truetype: hinting: point out of range")
			}
819
			d := int32(dotProduct(p.X-q.X, p.Y-q.Y, v))
820
			if scale {
821
				d = int32(int64(d*int32(h.scale)) / int64(h.font.fUnitsPerEm))
822
			}
823
			h.stack[top-1] = d
824

825 826 827 828 829
		case opMPPEM, opMPS:
			if top >= len(h.stack) {
				return errors.New("truetype: hinting: stack overflow")
			}
			// For MPS, point size should be irrelevant; we return the PPEM.
830
			h.stack[top] = int32(h.scale) >> 6
831 832 833 834 835
			top++

		case opFLIPON, opFLIPOFF:
			h.gs.autoFlip = opcode == opFLIPON

N
Nigel Tao 已提交
836 837 838
		case opDEBUG:
			// No-op.

839 840
		case opLT:
			top--
N
Nigel Tao 已提交
841
			h.stack[top-1] = bool2int32(h.stack[top-1] < h.stack[top])
842 843 844

		case opLTEQ:
			top--
N
Nigel Tao 已提交
845
			h.stack[top-1] = bool2int32(h.stack[top-1] <= h.stack[top])
846 847 848

		case opGT:
			top--
N
Nigel Tao 已提交
849
			h.stack[top-1] = bool2int32(h.stack[top-1] > h.stack[top])
850 851 852

		case opGTEQ:
			top--
N
Nigel Tao 已提交
853
			h.stack[top-1] = bool2int32(h.stack[top-1] >= h.stack[top])
854 855 856

		case opEQ:
			top--
N
Nigel Tao 已提交
857
			h.stack[top-1] = bool2int32(h.stack[top-1] == h.stack[top])
858 859 860

		case opNEQ:
			top--
N
Nigel Tao 已提交
861
			h.stack[top-1] = bool2int32(h.stack[top-1] != h.stack[top])
862

N
Nigel Tao 已提交
863
		case opODD, opEVEN:
864
			i := h.round(fixed.Int26_6(h.stack[top-1])) >> 6
N
Nigel Tao 已提交
865
			h.stack[top-1] = int32(i&1) ^ int32(opcode-opODD)
866

N
Nigel Tao 已提交
867 868 869 870 871 872 873 874 875 876
		case opIF:
			top--
			if h.stack[top] == 0 {
				opcode = 0
				goto ifelse
			}

		case opEIF:
			// No-op.

N
Nigel Tao 已提交
877 878 879 880 881 882 883 884 885 886 887
		case opAND:
			top--
			h.stack[top-1] = bool2int32(h.stack[top-1] != 0 && h.stack[top] != 0)

		case opOR:
			top--
			h.stack[top-1] = bool2int32(h.stack[top-1]|h.stack[top] != 0)

		case opNOT:
			h.stack[top-1] = bool2int32(h.stack[top-1] == 0)

888
		case opDELTAP1:
889
			goto delta
890

891 892 893 894 895 896 897 898
		case opSDB:
			top--
			h.gs.deltaBase = h.stack[top]

		case opSDS:
			top--
			h.gs.deltaShift = h.stack[top]

899 900
		case opADD:
			top--
N
Nigel Tao 已提交
901
			h.stack[top-1] += h.stack[top]
902 903 904

		case opSUB:
			top--
N
Nigel Tao 已提交
905
			h.stack[top-1] -= h.stack[top]
906 907

		case opDIV:
N
Nigel Tao 已提交
908 909
			top--
			if h.stack[top] == 0 {
910 911
				return errors.New("truetype: hinting: division by zero")
			}
912
			h.stack[top-1] = int32(fdiv(fixed.Int26_6(h.stack[top-1]), fixed.Int26_6(h.stack[top])))
913 914 915

		case opMUL:
			top--
916
			h.stack[top-1] = int32(fmul(fixed.Int26_6(h.stack[top-1]), fixed.Int26_6(h.stack[top])))
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932

		case opABS:
			if h.stack[top-1] < 0 {
				h.stack[top-1] = -h.stack[top-1]
			}

		case opNEG:
			h.stack[top-1] = -h.stack[top-1]

		case opFLOOR:
			h.stack[top-1] &^= 63

		case opCEILING:
			h.stack[top-1] += 63
			h.stack[top-1] &^= 63

N
Nigel Tao 已提交
933 934 935
		case opROUND00, opROUND01, opROUND10, opROUND11:
			// The four flavors of opROUND are equivalent. See the comment below on
			// opNROUND for the rationale.
936
			h.stack[top-1] = int32(h.round(fixed.Int26_6(h.stack[top-1])))
N
Nigel Tao 已提交
937 938 939 940 941 942 943 944

		case opNROUND00, opNROUND01, opNROUND10, opNROUND11:
			// No-op. The spec says to add one of four "compensations for the engine
			// characteristics", to cater for things like "different dot-size printers".
			// https://developer.apple.com/fonts/TTRefMan/RM02/Chap2.html#engine_compensation
			// This code does not implement engine compensation, as we don't expect to
			// be used to output on dot-matrix printers.

945 946
		case opWCVTF:
			top -= 2
947
			h.setScaledCVT(h.stack[top], h.font.scale(h.scale*fixed.Int26_6(h.stack[top+1])))
948

949 950
		case opDELTAP2, opDELTAP3, opDELTAC1, opDELTAC2, opDELTAC3:
			goto delta
951

N
Nigel Tao 已提交
952 953 954 955
		case opSROUND, opS45ROUND:
			top--
			switch (h.stack[top] >> 6) & 0x03 {
			case 0:
956
				h.gs.roundPeriod = 1 << 5
N
Nigel Tao 已提交
957
			case 1, 3:
958
				h.gs.roundPeriod = 1 << 6
N
Nigel Tao 已提交
959
			case 2:
960
				h.gs.roundPeriod = 1 << 7
N
Nigel Tao 已提交
961
			}
962 963
			h.gs.roundSuper45 = opcode == opS45ROUND
			if h.gs.roundSuper45 {
N
Nigel Tao 已提交
964 965
				// The spec says to multiply by √2, but the C Freetype code says 1/√2.
				// We go with 1/√2.
966 967
				h.gs.roundPeriod *= 46341
				h.gs.roundPeriod /= 65536
N
Nigel Tao 已提交
968
			}
969
			h.gs.roundPhase = h.gs.roundPeriod * fixed.Int26_6((h.stack[top]>>4)&0x03) / 4
N
Nigel Tao 已提交
970
			if x := h.stack[top] & 0x0f; x != 0 {
971
				h.gs.roundThreshold = h.gs.roundPeriod * fixed.Int26_6(x-4) / 8
N
Nigel Tao 已提交
972
			} else {
973
				h.gs.roundThreshold = h.gs.roundPeriod - 1
N
Nigel Tao 已提交
974 975
			}

N
Nigel Tao 已提交
976 977 978 979 980 981 982 983 984 985 986 987 988 989
		case opJROT:
			top -= 2
			if h.stack[top+1] != 0 {
				pc += int(h.stack[top])
				continue
			}

		case opJROF:
			top -= 2
			if h.stack[top+1] == 0 {
				pc += int(h.stack[top])
				continue
			}

N
Nigel Tao 已提交
990
		case opROFF:
991 992 993
			h.gs.roundPeriod = 0
			h.gs.roundPhase = 0
			h.gs.roundThreshold = 0
994
			h.gs.roundSuper45 = false
N
Nigel Tao 已提交
995 996

		case opRUTG:
997 998 999
			h.gs.roundPeriod = 1 << 6
			h.gs.roundPhase = 0
			h.gs.roundThreshold = 1<<6 - 1
1000
			h.gs.roundSuper45 = false
N
Nigel Tao 已提交
1001 1002

		case opRDTG:
1003 1004 1005
			h.gs.roundPeriod = 1 << 6
			h.gs.roundPhase = 0
			h.gs.roundThreshold = 0
1006
			h.gs.roundSuper45 = false
N
Nigel Tao 已提交
1007

1008 1009 1010 1011
		case opSANGW, opAA:
			// These ops are "anachronistic" and no longer used.
			top--

1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
		case opFLIPPT:
			if top < int(h.gs.loop) {
				return errors.New("truetype: hinting: stack underflow")
			}
			points := h.points[glyphZone][current]
			for ; h.gs.loop != 0; h.gs.loop-- {
				top--
				i := h.stack[top]
				if i < 0 || len(points) <= int(i) {
					return errors.New("truetype: hinting: point out of range")
				}
				points[i].Flags ^= flagOnCurve
			}
			h.gs.loop = 1

		case opFLIPRGON, opFLIPRGOFF:
			top -= 2
			i, j, points := h.stack[top], h.stack[top+1], h.points[glyphZone][current]
			if i < 0 || len(points) <= int(i) || j < 0 || len(points) <= int(j) {
				return errors.New("truetype: hinting: point out of range")
			}
			for ; i <= j; i++ {
				if opcode == opFLIPRGON {
					points[i].Flags |= flagOnCurve
				} else {
					points[i].Flags &^= flagOnCurve
				}
			}

1041 1042 1043 1044
		case opSCANCTRL:
			// We do not support dropout control, as we always rasterize grayscale glyphs.
			top--

1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
		case opSDPVTL0, opSDPVTL1:
			top -= 2
			for i := 0; i < 2; i++ {
				pt := unhinted
				if i != 0 {
					pt = current
				}
				p := h.point(1, pt, h.stack[top])
				q := h.point(2, pt, h.stack[top+1])
				if p == nil || q == nil {
					return errors.New("truetype: hinting: point out of range")
				}
				dx := f2dot14(p.X - q.X)
				dy := f2dot14(p.Y - q.Y)
				if dx == 0 && dy == 0 {
					dx = 0x4000
				} else if opcode&1 != 0 {
					// Counter-clockwise rotation.
					dx, dy = -dy, dx
				}
				if i == 0 {
					h.gs.dv = normalize(dx, dy)
				} else {
					h.gs.pv = normalize(dx, dy)
				}
			}

1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
		case opGETINFO:
			res := int32(0)
			if h.stack[top-1]&(1<<0) != 0 {
				// Set the engine version. We hard-code this to 35, the same as
				// the C freetype code, which says that "Version~35 corresponds
				// to MS rasterizer v.1.7 as used e.g. in Windows~98".
				res |= 35
			}
			if h.stack[top-1]&(1<<5) != 0 {
				// Set that we support grayscale.
				res |= 1 << 12
			}
			// We set no other bits, as we do not support rotated or stretched glyphs.
			h.stack[top-1] = res

1087 1088 1089 1090 1091
		case opIDEF:
			// IDEF is for ancient versions of the bytecode interpreter, and is no longer used.
			return errors.New("truetype: hinting: unsupported IDEF instruction")

		case opROLL:
1092 1093
			h.stack[top-1], h.stack[top-3], h.stack[top-2] =
				h.stack[top-3], h.stack[top-2], h.stack[top-1]
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106

		case opMAX:
			top--
			if h.stack[top-1] < h.stack[top] {
				h.stack[top-1] = h.stack[top]
			}

		case opMIN:
			top--
			if h.stack[top-1] > h.stack[top] {
				h.stack[top-1] = h.stack[top]
			}

1107 1108 1109 1110
		case opSCANTYPE:
			// We do not support dropout control, as we always rasterize grayscale glyphs.
			top--

1111 1112 1113 1114 1115 1116 1117 1118 1119
		case opINSTCTRL:
			// TODO: support instruction execution control? It seems rare, and even when
			// nominally used (e.g. Source Sans Pro), it seems conditional on extreme or
			// unusual rasterization conditions. For example, the code snippet at
			// https://developer.apple.com/fonts/TTRefMan/RM05/Chap5.html#INSTCTRL
			// uses INSTCTRL when grid-fitting a rotated or stretched glyph, but
			// freetype-go does not support rotated or stretched glyphs.
			top -= 2

1120 1121 1122
		default:
			if opcode < opPUSHB000 {
				return errors.New("truetype: hinting: unrecognized instruction")
1123 1124
			}

1125 1126
			if opcode < opMDRP00000 {
				// PUSHxxxx opcode.
1127

1128 1129
				if opcode < opPUSHW000 {
					opcode -= opPUSHB000 - 1
1130
				} else {
1131
					opcode -= opPUSHW000 - 1 - 0x80
1132
				}
1133
				goto push
1134 1135
			}

1136 1137
			if opcode < opMIRP00000 {
				// MDRPxxxxx opcode.
1138

1139 1140 1141 1142 1143 1144 1145 1146
				top--
				i := h.stack[top]
				ref := h.point(0, current, h.gs.rp[0])
				p := h.point(1, current, i)
				if ref == nil || p == nil {
					return errors.New("truetype: hinting: point out of range")
				}

1147
				oldDist := fixed.Int26_6(0)
1148 1149 1150
				if h.gs.zp[0] == 0 || h.gs.zp[1] == 0 {
					p0 := h.point(1, unhinted, i)
					p1 := h.point(0, unhinted, h.gs.rp[0])
1151
					oldDist = dotProduct(p0.X-p1.X, p0.Y-p1.Y, h.gs.dv)
1152
				} else {
1153 1154
					p0 := h.point(1, inFontUnits, i)
					p1 := h.point(0, inFontUnits, h.gs.rp[0])
1155 1156
					oldDist = dotProduct(p0.X-p1.X, p0.Y-p1.Y, h.gs.dv)
					oldDist = h.font.scale(h.scale * oldDist)
1157 1158
				}

1159
				// Single-width cut-in test.
1160
				if x := fabs(oldDist - h.gs.singleWidth); x < h.gs.singleWidthCutIn {
1161 1162 1163 1164 1165 1166
					if oldDist >= 0 {
						oldDist = +h.gs.singleWidth
					} else {
						oldDist = -h.gs.singleWidth
					}
				}
1167

1168 1169 1170 1171 1172 1173
				// Rounding bit.
				// TODO: metrics compensation.
				distance := oldDist
				if opcode&0x04 != 0 {
					distance = h.round(oldDist)
				}
1174

1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
				// Minimum distance bit.
				if opcode&0x08 != 0 {
					if oldDist >= 0 {
						if distance < h.gs.minDist {
							distance = h.gs.minDist
						}
					} else {
						if distance > -h.gs.minDist {
							distance = -h.gs.minDist
						}
					}
				}
1187

1188 1189 1190 1191 1192
				// Set-RP0 bit.
				h.gs.rp[1] = h.gs.rp[0]
				h.gs.rp[2] = i
				if opcode&0x10 != 0 {
					h.gs.rp[0] = i
1193 1194
				}

1195
				// Move the point.
1196
				oldDist = dotProduct(p.X-ref.X, p.Y-ref.Y, h.gs.pv)
1197
				h.move(p, distance-oldDist, true)
1198

1199 1200
			} else {
				// MIRPxxxxx opcode.
1201

1202 1203 1204
				top -= 2
				i := h.stack[top]
				cvtDist := h.getScaledCVT(h.stack[top+1])
1205
				if fabs(cvtDist-h.gs.singleWidth) < h.gs.singleWidthCutIn {
1206 1207 1208 1209 1210 1211
					if cvtDist >= 0 {
						cvtDist = +h.gs.singleWidth
					} else {
						cvtDist = -h.gs.singleWidth
					}
				}
1212

1213 1214 1215 1216 1217
				if h.gs.zp[1] == 0 {
					// TODO: implement once we have a .ttf file that triggers
					// this, so that we can step through C's freetype.
					return errors.New("truetype: hinting: unimplemented twilight point adjustment")
				}
1218

1219 1220 1221 1222 1223
				ref := h.point(0, unhinted, h.gs.rp[0])
				p := h.point(1, unhinted, i)
				if ref == nil || p == nil {
					return errors.New("truetype: hinting: point out of range")
				}
1224
				oldDist := dotProduct(p.X-ref.X, p.Y-ref.Y, h.gs.dv)
1225

1226 1227 1228 1229
				ref = h.point(0, current, h.gs.rp[0])
				p = h.point(1, current, i)
				if ref == nil || p == nil {
					return errors.New("truetype: hinting: point out of range")
1230
				}
1231
				curDist := dotProduct(p.X-ref.X, p.Y-ref.Y, h.gs.pv)
1232

1233 1234 1235 1236 1237 1238 1239 1240 1241 1242
				if h.gs.autoFlip && oldDist^cvtDist < 0 {
					cvtDist = -cvtDist
				}

				// Rounding bit.
				// TODO: metrics compensation.
				distance := cvtDist
				if opcode&0x04 != 0 {
					// The CVT value is only used if close enough to oldDist.
					if (h.gs.zp[0] == h.gs.zp[1]) &&
1243
						(fabs(cvtDist-oldDist) > h.gs.controlValueCutIn) {
1244 1245

						distance = oldDist
1246
					}
1247
					distance = h.round(distance)
1248 1249
				}

1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
				// Minimum distance bit.
				if opcode&0x08 != 0 {
					if oldDist >= 0 {
						if distance < h.gs.minDist {
							distance = h.gs.minDist
						}
					} else {
						if distance > -h.gs.minDist {
							distance = -h.gs.minDist
						}
					}
				}
1262

1263 1264 1265 1266 1267 1268
				// Set-RP0 bit.
				h.gs.rp[1] = h.gs.rp[0]
				h.gs.rp[2] = i
				if opcode&0x10 != 0 {
					h.gs.rp[0] = i
				}
1269

1270 1271 1272
				// Move the point.
				h.move(p, distance-curDist, true)
			}
1273 1274 1275 1276
		}
		pc++
		continue

N
Nigel Tao 已提交
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
	ifelse:
		// Skip past bytecode until the next ELSE (if opcode == 0) or the
		// next EIF (for all opcodes). Opcode == 0 means that we have come
		// from an IF. Opcode == 1 means that we have come from an ELSE.
		{
		ifelseloop:
			for depth := 0; ; {
				pc++
				if pc >= len(program) {
					return errors.New("truetype: hinting: unbalanced IF or ELSE")
				}
				switch program[pc] {
				case opIF:
					depth++
				case opELSE:
					if depth == 0 && opcode == 0 {
						break ifelseloop
					}
				case opEIF:
					depth--
					if depth < 0 {
						break ifelseloop
					}
1300 1301 1302 1303
				default:
					var ok bool
					pc, ok = skipInstructionPayload(program, pc)
					if !ok {
N
Nigel Tao 已提交
1304 1305 1306 1307 1308 1309 1310 1311
						return errors.New("truetype: hinting: unbalanced IF or ELSE")
					}
				}
			}
			pc++
			continue
		}

1312
	push:
N
Nigel Tao 已提交
1313
		// Push n elements from the program to the stack, where n is the low 7 bits of
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
		// opcode. If the low 7 bits are zero, then n is the next byte from the program.
		// The high bit being 0 means that the elements are zero-extended bytes.
		// The high bit being 1 means that the elements are sign-extended words.
		{
			width := 1
			if opcode&0x80 != 0 {
				opcode &^= 0x80
				width = 2
			}
			if opcode == 0 {
				pc++
1325
				if pc >= len(program) {
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
					return errors.New("truetype: hinting: insufficient data")
				}
				opcode = program[pc]
			}
			pc++
			if top+int(opcode) > len(h.stack) {
				return errors.New("truetype: hinting: stack overflow")
			}
			if pc+width*int(opcode) > len(program) {
				return errors.New("truetype: hinting: insufficient data")
			}
			for ; opcode > 0; opcode-- {
				if width == 1 {
					h.stack[top] = int32(program[pc])
				} else {
					h.stack[top] = int32(int8(program[pc]))<<8 | int32(program[pc+1])
				}
				top++
				pc += width
			}
			continue
		}
1348

1349
	delta:
1350
		{
1351
			if opcode >= opDELTAC1 && !h.scaledCVTInitialized {
1352
				h.initializeScaledCVT()
1353
			}
1354
			top--
1355 1356
			n := h.stack[top]
			if int32(top) < 2*n {
1357
				return errors.New("truetype: hinting: stack underflow")
1358
			}
1359 1360 1361 1362 1363
			for ; n > 0; n-- {
				top -= 2
				b := h.stack[top]
				c := (b & 0xf0) >> 4
				switch opcode {
1364
				case opDELTAP2, opDELTAC2:
1365
					c += 16
1366
				case opDELTAP3, opDELTAC3:
1367 1368 1369
					c += 32
				}
				c += h.gs.deltaBase
1370
				if ppem := (int32(h.scale) + 1<<5) >> 6; ppem != c {
1371 1372 1373 1374 1375 1376 1377
					continue
				}
				b = (b & 0x0f) - 8
				if b >= 0 {
					b++
				}
				b = b * 64 / (1 << uint32(h.gs.deltaShift))
1378 1379 1380 1381 1382
				if opcode >= opDELTAC1 {
					a := h.stack[top+1]
					if a < 0 || len(h.scaledCVT) <= int(a) {
						return errors.New("truetype: hinting: index out of range")
					}
1383
					h.scaledCVT[a] += fixed.Int26_6(b)
1384 1385 1386 1387 1388
				} else {
					p := h.point(0, current, h.stack[top+1])
					if p == nil {
						return errors.New("truetype: hinting: point out of range")
					}
1389
					h.move(p, fixed.Int26_6(b), true)
1390 1391 1392 1393
				}
			}
			pc++
			continue
1394
		}
1395 1396 1397 1398
	}
	return nil
}

1399
func (h *hinter) initializeScaledCVT() {
1400 1401 1402 1403 1404 1405 1406
	h.scaledCVTInitialized = true
	if n := len(h.font.cvt) / 2; n <= cap(h.scaledCVT) {
		h.scaledCVT = h.scaledCVT[:n]
	} else {
		if n < 32 {
			n = 32
		}
1407
		h.scaledCVT = make([]fixed.Int26_6, len(h.font.cvt)/2, n)
1408 1409 1410
	}
	for i := range h.scaledCVT {
		unscaled := uint16(h.font.cvt[2*i])<<8 | uint16(h.font.cvt[2*i+1])
1411
		h.scaledCVT[i] = h.font.scale(h.scale * fixed.Int26_6(int16(unscaled)))
1412 1413 1414 1415
	}
}

// getScaledCVT returns the scaled value from the font's Control Value Table.
1416
func (h *hinter) getScaledCVT(i int32) fixed.Int26_6 {
1417 1418 1419 1420
	if !h.scaledCVTInitialized {
		h.initializeScaledCVT()
	}
	if i < 0 || len(h.scaledCVT) <= int(i) {
1421 1422
		return 0
	}
1423 1424 1425 1426
	return h.scaledCVT[i]
}

// setScaledCVT overrides the scaled value from the font's Control Value Table.
1427
func (h *hinter) setScaledCVT(i int32, v fixed.Int26_6) {
1428 1429 1430 1431 1432 1433 1434
	if !h.scaledCVTInitialized {
		h.initializeScaledCVT()
	}
	if i < 0 || len(h.scaledCVT) <= int(i) {
		return
	}
	h.scaledCVT[i] = v
1435 1436
}

1437
func (h *hinter) point(zonePointer uint32, pt pointType, i int32) *Point {
1438
	points := h.points[h.gs.zp[zonePointer]][pt]
1439 1440 1441 1442 1443 1444
	if i < 0 || len(points) <= int(i) {
		return nil
	}
	return &points[i]
}

1445
func (h *hinter) move(p *Point, distance fixed.Int26_6, touch bool) {
1446 1447 1448
	fvx := int64(h.gs.fv[0])
	pvx := int64(h.gs.pv[0])
	if fvx == 0x4000 && pvx == 0x4000 {
1449
		p.X += fixed.Int26_6(distance)
1450 1451 1452
		if touch {
			p.Flags |= flagTouchedX
		}
1453 1454
		return
	}
1455

1456 1457
	fvy := int64(h.gs.fv[1])
	pvy := int64(h.gs.pv[1])
1458
	if fvy == 0x4000 && pvy == 0x4000 {
1459
		p.Y += fixed.Int26_6(distance)
1460 1461 1462 1463 1464 1465
		if touch {
			p.Flags |= flagTouchedY
		}
		return
	}

1466
	fvDotPv := (fvx*pvx + fvy*pvy) >> 14
1467 1468

	if fvx != 0 {
1469
		p.X += fixed.Int26_6(mulDiv(fvx, int64(distance), fvDotPv))
1470 1471 1472 1473 1474 1475
		if touch {
			p.Flags |= flagTouchedX
		}
	}

	if fvy != 0 {
1476
		p.Y += fixed.Int26_6(mulDiv(fvy, int64(distance), fvDotPv))
1477 1478 1479 1480
		if touch {
			p.Flags |= flagTouchedY
		}
	}
1481 1482
}

1483
func (h *hinter) iupInterp(interpY bool, p1, p2, ref1, ref2 int) {
1484 1485 1486
	if p1 > p2 {
		return
	}
1487 1488
	if ref1 >= len(h.points[glyphZone][current]) ||
		ref2 >= len(h.points[glyphZone][current]) {
1489 1490 1491
		return
	}

1492
	var ifu1, ifu2 fixed.Int26_6
1493
	if interpY {
1494 1495
		ifu1 = h.points[glyphZone][inFontUnits][ref1].Y
		ifu2 = h.points[glyphZone][inFontUnits][ref2].Y
1496
	} else {
1497 1498
		ifu1 = h.points[glyphZone][inFontUnits][ref1].X
		ifu2 = h.points[glyphZone][inFontUnits][ref2].X
1499 1500 1501 1502 1503 1504
	}
	if ifu1 > ifu2 {
		ifu1, ifu2 = ifu2, ifu1
		ref1, ref2 = ref2, ref1
	}

1505
	var unh1, unh2, delta1, delta2 fixed.Int26_6
1506
	if interpY {
1507 1508 1509 1510
		unh1 = h.points[glyphZone][unhinted][ref1].Y
		unh2 = h.points[glyphZone][unhinted][ref2].Y
		delta1 = h.points[glyphZone][current][ref1].Y - unh1
		delta2 = h.points[glyphZone][current][ref2].Y - unh2
1511
	} else {
1512 1513 1514 1515
		unh1 = h.points[glyphZone][unhinted][ref1].X
		unh2 = h.points[glyphZone][unhinted][ref2].X
		delta1 = h.points[glyphZone][current][ref1].X - unh1
		delta2 = h.points[glyphZone][current][ref2].X - unh2
1516 1517
	}

1518
	var xy, ifuXY fixed.Int26_6
1519 1520 1521
	if ifu1 == ifu2 {
		for i := p1; i <= p2; i++ {
			if interpY {
1522
				xy = h.points[glyphZone][unhinted][i].Y
1523
			} else {
1524
				xy = h.points[glyphZone][unhinted][i].X
1525 1526 1527 1528 1529 1530 1531 1532 1533
			}

			if xy <= unh1 {
				xy += delta1
			} else {
				xy += delta2
			}

			if interpY {
1534
				h.points[glyphZone][current][i].Y = xy
1535
			} else {
1536
				h.points[glyphZone][current][i].X = xy
1537 1538
			}
		}
1539 1540
		return
	}
1541

1542 1543 1544 1545 1546 1547 1548 1549 1550
	scale, scaleOK := int64(0), false
	for i := p1; i <= p2; i++ {
		if interpY {
			xy = h.points[glyphZone][unhinted][i].Y
			ifuXY = h.points[glyphZone][inFontUnits][i].Y
		} else {
			xy = h.points[glyphZone][unhinted][i].X
			ifuXY = h.points[glyphZone][inFontUnits][i].X
		}
1551

1552 1553 1554 1555 1556 1557 1558
		if xy <= unh1 {
			xy += delta1
		} else if xy >= unh2 {
			xy += delta2
		} else {
			if !scaleOK {
				scaleOK = true
1559
				scale = mulDiv(int64(unh2+delta2-unh1-delta1), 0x10000, int64(ifu2-ifu1))
1560
			}
1561 1562 1563
			numer := int64(ifuXY-ifu1) * scale
			if numer >= 0 {
				numer += 0x8000
1564
			} else {
1565
				numer -= 0x8000
1566
			}
1567
			xy = unh1 + delta1 + fixed.Int26_6(numer/0x10000)
1568 1569 1570 1571 1572 1573
		}

		if interpY {
			h.points[glyphZone][current][i].Y = xy
		} else {
			h.points[glyphZone][current][i].X = xy
1574 1575 1576 1577
		}
	}
}

1578
func (h *hinter) iupShift(interpY bool, p1, p2, p int) {
1579
	var delta fixed.Int26_6
1580
	if interpY {
1581
		delta = h.points[glyphZone][current][p].Y - h.points[glyphZone][unhinted][p].Y
1582
	} else {
1583
		delta = h.points[glyphZone][current][p].X - h.points[glyphZone][unhinted][p].X
1584 1585 1586 1587 1588 1589 1590 1591 1592
	}
	if delta == 0 {
		return
	}
	for i := p1; i < p2; i++ {
		if i == p {
			continue
		}
		if interpY {
1593
			h.points[glyphZone][current][i].Y += delta
1594
		} else {
1595
			h.points[glyphZone][current][i].X += delta
1596 1597 1598 1599
		}
	}
}

1600
func (h *hinter) displacement(useZP1 bool) (zonePointer uint32, i int32, d fixed.Int26_6, ok bool) {
1601 1602 1603 1604 1605 1606 1607 1608 1609
	zonePointer, i = uint32(0), h.gs.rp[1]
	if useZP1 {
		zonePointer, i = 1, h.gs.rp[2]
	}
	p := h.point(zonePointer, current, i)
	q := h.point(zonePointer, unhinted, i)
	if p == nil || q == nil {
		return 0, 0, 0, false
	}
1610
	d = dotProduct(p.X-q.X, p.Y-q.Y, h.gs.pv)
1611 1612 1613
	return zonePointer, i, d, true
}

1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
// skipInstructionPayload increments pc by the extra data that follows a
// variable length PUSHB or PUSHW instruction.
func skipInstructionPayload(program []byte, pc int) (newPC int, ok bool) {
	switch program[pc] {
	case opNPUSHB:
		pc++
		if pc >= len(program) {
			return 0, false
		}
		pc += int(program[pc])
	case opNPUSHW:
		pc++
		if pc >= len(program) {
			return 0, false
		}
		pc += 2 * int(program[pc])
	case opPUSHB000, opPUSHB001, opPUSHB010, opPUSHB011,
		opPUSHB100, opPUSHB101, opPUSHB110, opPUSHB111:
		pc += int(program[pc] - (opPUSHB000 - 1))
	case opPUSHW000, opPUSHW001, opPUSHW010, opPUSHW011,
		opPUSHW100, opPUSHW101, opPUSHW110, opPUSHW111:
		pc += 2 * int(program[pc]-(opPUSHW000-1))
	}
	return pc, true
}

1640 1641 1642
// f2dot14 is a 2.14 fixed point number.
type f2dot14 int16

1643 1644
func normalize(x, y f2dot14) [2]f2dot14 {
	fx, fy := float64(x), float64(y)
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656
	l := 0x4000 / math.Hypot(fx, fy)
	fx *= l
	if fx >= 0 {
		fx += 0.5
	} else {
		fx -= 0.5
	}
	fy *= l
	if fy >= 0 {
		fy += 0.5
	} else {
		fy -= 0.5
1657
	}
1658
	return [2]f2dot14{f2dot14(fx), f2dot14(fy)}
1659 1660
}

1661
// fabs returns abs(x) in 26.6 fixed point arithmetic.
1662
func fabs(x fixed.Int26_6) fixed.Int26_6 {
1663 1664 1665 1666 1667 1668
	if x < 0 {
		return -x
	}
	return x
}

1669
// fdiv returns x/y in 26.6 fixed point arithmetic.
1670 1671
func fdiv(x, y fixed.Int26_6) fixed.Int26_6 {
	return fixed.Int26_6((int64(x) << 6) / int64(y))
N
Nigel Tao 已提交
1672 1673
}

1674
// fmul returns x*y in 26.6 fixed point arithmetic.
1675 1676
func fmul(x, y fixed.Int26_6) fixed.Int26_6 {
	return fixed.Int26_6((int64(x)*int64(y) + 1<<5) >> 6)
N
Nigel Tao 已提交
1677 1678
}

1679 1680 1681 1682 1683
// dotProduct returns the dot product of [x, y] and q. It is almost the same as
//	px := int64(x)
//	py := int64(y)
//	qx := int64(q[0])
//	qy := int64(q[1])
1684
//	return fixed.Int26_6((px*qx + py*qy + 1<<13) >> 14)
1685 1686
// except that the computation is done with 32-bit integers to produce exactly
// the same rounding behavior as C Freetype.
1687
func dotProduct(x, y fixed.Int26_6, q [2]f2dot14) fixed.Int26_6 {
1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714
	// Compute x*q[0] as 64-bit value.
	l := uint32((int32(x) & 0xFFFF) * int32(q[0]))
	m := (int32(x) >> 16) * int32(q[0])

	lo1 := l + (uint32(m) << 16)
	hi1 := (m >> 16) + (int32(l) >> 31) + bool2int32(lo1 < l)

	// Compute y*q[1] as 64-bit value.
	l = uint32((int32(y) & 0xFFFF) * int32(q[1]))
	m = (int32(y) >> 16) * int32(q[1])

	lo2 := l + (uint32(m) << 16)
	hi2 := (m >> 16) + (int32(l) >> 31) + bool2int32(lo2 < l)

	// Add them.
	lo := lo1 + lo2
	hi := hi1 + hi2 + bool2int32(lo < lo1)

	// Divide the result by 2^14 with rounding.
	s := hi >> 31
	l = lo + uint32(s)
	hi += s + bool2int32(l < lo)
	lo = l

	l = lo + 0x2000
	hi += bool2int32(l < lo)

1715
	return fixed.Int26_6((uint32(hi) << 18) | (l >> 14))
1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
}

// mulDiv returns x*y/z, rounded to the nearest integer.
func mulDiv(x, y, z int64) int64 {
	xy := x * y
	if z < 0 {
		xy, z = -xy, -z
	}
	if xy >= 0 {
		xy += z / 2
	} else {
		xy -= z / 2
	}
	return xy / z
1730 1731
}

N
Nigel Tao 已提交
1732 1733
// round rounds the given number. The rounding algorithm is described at
// https://developer.apple.com/fonts/TTRefMan/RM02/Chap2.html#rounding
1734
func (h *hinter) round(x fixed.Int26_6) fixed.Int26_6 {
1735
	if h.gs.roundPeriod == 0 {
1736
		// Rounding is off.
N
Nigel Tao 已提交
1737 1738 1739
		return x
	}
	if x >= 0 {
1740 1741 1742 1743 1744 1745 1746
		ret := x - h.gs.roundPhase + h.gs.roundThreshold
		if h.gs.roundSuper45 {
			ret /= h.gs.roundPeriod
			ret *= h.gs.roundPeriod
		} else {
			ret &= -h.gs.roundPeriod
		}
1747 1748
		if x != 0 && ret < 0 {
			ret = 0
N
Nigel Tao 已提交
1749
		}
1750
		return ret + h.gs.roundPhase
N
Nigel Tao 已提交
1751
	}
1752 1753 1754 1755 1756 1757 1758 1759
	ret := -x - h.gs.roundPhase + h.gs.roundThreshold
	if h.gs.roundSuper45 {
		ret /= h.gs.roundPeriod
		ret *= h.gs.roundPeriod
	} else {
		ret &= -h.gs.roundPeriod
	}
	if ret < 0 {
1760 1761
		ret = 0
	}
1762
	return -ret - h.gs.roundPhase
N
Nigel Tao 已提交
1763 1764
}

1765 1766 1767 1768 1769 1770
func bool2int32(b bool) int32 {
	if b {
		return 1
	}
	return 0
}