removeOverlaps.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. """ Simplify TrueType glyphs by merging overlapping contours/components.
  2. Requires https://github.com/fonttools/skia-pathops
  3. """
  4. import itertools
  5. import logging
  6. from typing import Callable, Iterable, Optional, Mapping
  7. from fontTools.misc.roundTools import otRound
  8. from fontTools.ttLib import ttFont
  9. from fontTools.ttLib.tables import _g_l_y_f
  10. from fontTools.ttLib.tables import _h_m_t_x
  11. from fontTools.pens.ttGlyphPen import TTGlyphPen
  12. import pathops
  13. __all__ = ["removeOverlaps"]
  14. class RemoveOverlapsError(Exception):
  15. pass
  16. log = logging.getLogger("fontTools.ttLib.removeOverlaps")
  17. _TTGlyphMapping = Mapping[str, ttFont._TTGlyph]
  18. def skPathFromGlyph(glyphName: str, glyphSet: _TTGlyphMapping) -> pathops.Path:
  19. path = pathops.Path()
  20. pathPen = path.getPen(glyphSet=glyphSet)
  21. glyphSet[glyphName].draw(pathPen)
  22. return path
  23. def skPathFromGlyphComponent(
  24. component: _g_l_y_f.GlyphComponent, glyphSet: _TTGlyphMapping
  25. ):
  26. baseGlyphName, transformation = component.getComponentInfo()
  27. path = skPathFromGlyph(baseGlyphName, glyphSet)
  28. return path.transform(*transformation)
  29. def componentsOverlap(glyph: _g_l_y_f.Glyph, glyphSet: _TTGlyphMapping) -> bool:
  30. if not glyph.isComposite():
  31. raise ValueError("This method only works with TrueType composite glyphs")
  32. if len(glyph.components) < 2:
  33. return False # single component, no overlaps
  34. component_paths = {}
  35. def _get_nth_component_path(index: int) -> pathops.Path:
  36. if index not in component_paths:
  37. component_paths[index] = skPathFromGlyphComponent(
  38. glyph.components[index], glyphSet
  39. )
  40. return component_paths[index]
  41. return any(
  42. pathops.op(
  43. _get_nth_component_path(i),
  44. _get_nth_component_path(j),
  45. pathops.PathOp.INTERSECTION,
  46. fix_winding=False,
  47. keep_starting_points=False,
  48. )
  49. for i, j in itertools.combinations(range(len(glyph.components)), 2)
  50. )
  51. def ttfGlyphFromSkPath(path: pathops.Path) -> _g_l_y_f.Glyph:
  52. # Skia paths have no 'components', no need for glyphSet
  53. ttPen = TTGlyphPen(glyphSet=None)
  54. path.draw(ttPen)
  55. glyph = ttPen.glyph()
  56. assert not glyph.isComposite()
  57. # compute glyph.xMin (glyfTable parameter unused for non composites)
  58. glyph.recalcBounds(glyfTable=None)
  59. return glyph
  60. def _round_path(
  61. path: pathops.Path, round: Callable[[float], float] = otRound
  62. ) -> pathops.Path:
  63. rounded_path = pathops.Path()
  64. for verb, points in path:
  65. rounded_path.add(verb, *((round(p[0]), round(p[1])) for p in points))
  66. return rounded_path
  67. def _simplify(path: pathops.Path, debugGlyphName: str) -> pathops.Path:
  68. # skia-pathops has a bug where it sometimes fails to simplify paths when there
  69. # are float coordinates and control points are very close to one another.
  70. # Rounding coordinates to integers works around the bug.
  71. # Since we are going to round glyf coordinates later on anyway, here it is
  72. # ok(-ish) to also round before simplify. Better than failing the whole process
  73. # for the entire font.
  74. # https://bugs.chromium.org/p/skia/issues/detail?id=11958
  75. # https://github.com/google/fonts/issues/3365
  76. # TODO(anthrotype): remove once this Skia bug is fixed
  77. try:
  78. return pathops.simplify(path, clockwise=path.clockwise)
  79. except pathops.PathOpsError:
  80. pass
  81. path = _round_path(path)
  82. try:
  83. path = pathops.simplify(path, clockwise=path.clockwise)
  84. log.debug(
  85. "skia-pathops failed to simplify '%s' with float coordinates, "
  86. "but succeded using rounded integer coordinates",
  87. debugGlyphName,
  88. )
  89. return path
  90. except pathops.PathOpsError as e:
  91. if log.isEnabledFor(logging.DEBUG):
  92. path.dump()
  93. raise RemoveOverlapsError(
  94. f"Failed to remove overlaps from glyph {debugGlyphName!r}"
  95. ) from e
  96. raise AssertionError("Unreachable")
  97. def removeTTGlyphOverlaps(
  98. glyphName: str,
  99. glyphSet: _TTGlyphMapping,
  100. glyfTable: _g_l_y_f.table__g_l_y_f,
  101. hmtxTable: _h_m_t_x.table__h_m_t_x,
  102. removeHinting: bool = True,
  103. ) -> bool:
  104. glyph = glyfTable[glyphName]
  105. # decompose composite glyphs only if components overlap each other
  106. if (
  107. glyph.numberOfContours > 0
  108. or glyph.isComposite()
  109. and componentsOverlap(glyph, glyphSet)
  110. ):
  111. path = skPathFromGlyph(glyphName, glyphSet)
  112. # remove overlaps
  113. path2 = _simplify(path, glyphName)
  114. # replace TTGlyph if simplified path is different (ignoring contour order)
  115. if {tuple(c) for c in path.contours} != {tuple(c) for c in path2.contours}:
  116. glyfTable[glyphName] = glyph = ttfGlyphFromSkPath(path2)
  117. # simplified glyph is always unhinted
  118. assert not glyph.program
  119. # also ensure hmtx LSB == glyph.xMin so glyph origin is at x=0
  120. width, lsb = hmtxTable[glyphName]
  121. if lsb != glyph.xMin:
  122. hmtxTable[glyphName] = (width, glyph.xMin)
  123. return True
  124. if removeHinting:
  125. glyph.removeHinting()
  126. return False
  127. def removeOverlaps(
  128. font: ttFont.TTFont,
  129. glyphNames: Optional[Iterable[str]] = None,
  130. removeHinting: bool = True,
  131. ignoreErrors=False,
  132. ) -> None:
  133. """Simplify glyphs in TTFont by merging overlapping contours.
  134. Overlapping components are first decomposed to simple contours, then merged.
  135. Currently this only works with TrueType fonts with 'glyf' table.
  136. Raises NotImplementedError if 'glyf' table is absent.
  137. Note that removing overlaps invalidates the hinting. By default we drop hinting
  138. from all glyphs whether or not overlaps are removed from a given one, as it would
  139. look weird if only some glyphs are left (un)hinted.
  140. Args:
  141. font: input TTFont object, modified in place.
  142. glyphNames: optional iterable of glyph names (str) to remove overlaps from.
  143. By default, all glyphs in the font are processed.
  144. removeHinting (bool): set to False to keep hinting for unmodified glyphs.
  145. ignoreErrors (bool): set to True to ignore errors while removing overlaps,
  146. thus keeping the tricky glyphs unchanged (fonttools/fonttools#2363).
  147. """
  148. try:
  149. glyfTable = font["glyf"]
  150. except KeyError:
  151. raise NotImplementedError("removeOverlaps currently only works with TTFs")
  152. hmtxTable = font["hmtx"]
  153. # wraps the underlying glyf Glyphs, takes care of interfacing with drawing pens
  154. glyphSet = font.getGlyphSet()
  155. if glyphNames is None:
  156. glyphNames = font.getGlyphOrder()
  157. # process all simple glyphs first, then composites with increasing component depth,
  158. # so that by the time we test for component intersections the respective base glyphs
  159. # have already been simplified
  160. glyphNames = sorted(
  161. glyphNames,
  162. key=lambda name: (
  163. glyfTable[name].getCompositeMaxpValues(glyfTable).maxComponentDepth
  164. if glyfTable[name].isComposite()
  165. else 0,
  166. name,
  167. ),
  168. )
  169. modified = set()
  170. for glyphName in glyphNames:
  171. try:
  172. if removeTTGlyphOverlaps(
  173. glyphName, glyphSet, glyfTable, hmtxTable, removeHinting
  174. ):
  175. modified.add(glyphName)
  176. except RemoveOverlapsError:
  177. if not ignoreErrors:
  178. raise
  179. log.error("Failed to remove overlaps for '%s'", glyphName)
  180. log.debug("Removed overlaps for %s glyphs:\n%s", len(modified), " ".join(modified))
  181. def main(args=None):
  182. import sys
  183. if args is None:
  184. args = sys.argv[1:]
  185. if len(args) < 2:
  186. print(
  187. f"usage: fonttools ttLib.removeOverlaps INPUT.ttf OUTPUT.ttf [GLYPHS ...]"
  188. )
  189. sys.exit(1)
  190. src = args[0]
  191. dst = args[1]
  192. glyphNames = args[2:] or None
  193. with ttFont.TTFont(src) as f:
  194. removeOverlaps(f, glyphNames)
  195. f.save(dst)
  196. if __name__ == "__main__":
  197. main()