# instancer

Partially instantiate a variable font.

The module exports an instantiateVariableFont function and CLI that allow to create full instances (i.e. static fonts) from variable fonts, as well as “partial” variable fonts that only contain a subset of the original variation space.

For example, if you wish to pin the width axis to a given location while also restricting the weight axis to 400..700 range, you can do:

    $ fonttools varLib.instancer ./NotoSans-VF.ttf wdth=85 wght=400:700

See fonttools varLib.instancer –help for more info on the CLI options.

The module’s entry point is the instantiateVariableFont function, which takes a TTFont object and a dict specifying either axis coodinates or (min, max) ranges, and returns a new TTFont representing either a partial VF, or full instance if all the VF axes were given an explicit coordinate.

E.g. here’s how to pin the wght axis at a given location in a wght+wdth variable font, keeping only the deltas associated with the wdth axis:

    | >>> from fontTools import ttLib
    | >>> from fontTools.varLib import instancer
    | >>> varfont = ttLib.TTFont("path/to/MyVariableFont.ttf")
    | >>> [a.axisTag for a in varfont["fvar"].axes]  # the varfont's current axes
    | ['wght', 'wdth']
    | >>> partial = instancer.instantiateVariableFont(varfont, {"wght": 300})
    | >>> [a.axisTag for a in partial["fvar"].axes]  # axes left after pinning 'wght'
    | ['wdth']

If the input location specifies all the axes, the resulting instance is no longer ‘variable’ (same as using fontools varLib.mutator):

>>> instance = instancer.instantiateVariableFont(
… varfont, {“wght”: 700, “wdth”: 67.5}
… )
>>> “fvar” not in instance
True

If one just want to drop an axis at the default location, without knowing in advance what the default value for that axis is, one can pass a None value:

>>> instance = instancer.instantiateVariableFont(varfont, {“wght”: None})
>>> len(varfont[“fvar”].axes)
1

From the console script, this is equivalent to passing wght=drop as input.

This module is similar to fontTools.varLib.mutator, which it’s intended to supersede. Note that, unlike varLib.mutator, when an axis is not mentioned in the input location, the varLib.instancer will keep the axis and the corresponding deltas, whereas mutator implicitly drops the axis at its default coordinate.

The module currently supports only the first three “levels” of partial instancing, with the rest planned to be implemented in the future, namely:

L1

  dropping one or more axes while leaving the default tables unmodified;

L2

  dropping one or more axes while pinning them at non-default locations;

L3

  restricting the range of variation of one or more axes, by setting either a new minimum or maximum, potentially – though not necessarily – dropping entire regions of variations that fall completely outside this new range.

L4

  moving the default location of an axis.

Currently only TrueType-flavored variable fonts (i.e. containing ‘glyf’ table) are supported, but support for CFF2 variable fonts will be added soon.

The discussion and implementation of these features are tracked at https://github.com/fonttools/fonttools/issues/1537

class fontTools.varLib.instancer.AxisRange(*args, **kwargs)
  count(value, /)

    Return number of occurrences of value.

  index(value, start=0, stop=9223372036854775807, /)

    Return first index of value.

    Raises ValueError if the value is not present.

  maximum

    Alias for field number 1

  minimum

    Alias for field number 0

class fontTools.varLib.instancer.NormalizedAxisRange(*args, **kwargs)
  count(value, /)

    Return number of occurrences of value.

  index(value, start=0, stop=9223372036854775807, /)

    Return first index of value.

    Raises ValueError if the value is not present.

  maximum

    Alias for field number 1

  minimum

    Alias for field number 0

class fontTools.varLib.instancer.OverlapMode(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
  KEEP_AND_DONT_SET_FLAGS = 0
  KEEP_AND_SET_FLAGS = 1
  REMOVE = 2
  REMOVE_AND_IGNORE_ERRORS = 3
  as_integer_ratio()

    Return integer ratio.

    Return a pair of integers, whose ratio is exactly equal to the original int and with a positive denominator.

        >>> (10).as_integer_ratio()
        (10, 1)
        >>> (-10).as_integer_ratio()
        (-10, 1)
        >>> (0).as_integer_ratio()
        (0, 1)

  bit_count()

    Number of ones in the binary representation of the absolute value of self.

    Also known as the population count.

        >>> bin(13)
        '0b1101'
        >>> (13).bit_count()
        3

  bit_length()

    Number of bits necessary to represent self in binary.

        >>> bin(37)
        '0b100101'
        >>> (37).bit_length()
        6

  conjugate()

    Returns self, the complex conjugate of any int.

  denominator

    the denominator of a rational number in lowest terms

  from_bytes(byteorder='big', *, signed=False)

    Return the integer represented by the given array of bytes.

    bytes

      Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.

    byteorder

      The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value. Default is to use ‘big’.

    signed

      Indicates whether two’s complement is used to represent the integer.

  imag

    the imaginary part of a complex number

  numerator

    the numerator of a rational number in lowest terms

  real

    the real part of a complex number

  to_bytes(length=1, byteorder='big', *, signed=False)

    Return an array of bytes representing an integer.

    length

      Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes. Default is length 1.

    byteorder

      The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value. Default is to use ‘big’.

    signed

      Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.

fontTools.varLib.instancer.axisValuesFromAxisLimits(stat, axisLimits)

fontTools.varLib.instancer.instantiateAvar(varfont, axisLimits)

fontTools.varLib.instancer.instantiateCvar(varfont, axisLimits)

fontTools.varLib.instancer.instantiateFeatureVariations(varfont, axisLimits)

fontTools.varLib.instancer.instantiateFvar(varfont, axisLimits)

fontTools.varLib.instancer.instantiateGvar(varfont, axisLimits, optimize=True)

fontTools.varLib.instancer.instantiateGvarGlyph(varfont, glyphname, axisLimits, optimize=True)

  Remove? https://github.com/fonttools/fonttools/pull/2266

fontTools.varLib.instancer.instantiateHVAR(varfont, axisLimits)

fontTools.varLib.instancer.instantiateItemVariationStore(itemVarStore, fvarAxes, axisLimits)

  Compute deltas at partial location, and update varStore in-place.

  Remove regions in which all axes were instanced, or fall outside the new axis limits. Scale the deltas of the remaining regions where only some of the axes were instanced.

  The number of VarData subtables, and the number of items within each, are not modified, in order to keep the existing VariationIndex valid. One may call VarStore.optimize() method after this to further optimize those.

  Parameters

    - varStore – An otTables.VarStore object (Item Variation Store)

    - fvarAxes – list of fvar’s Axis objects

    - axisLimits – Dict[str, float] mapping axis tags to normalized axis coordinates (float) or ranges for restricting an axis’ min/max (NormalizedAxisRange). May not specify coordinates/ranges for all the fvar axes.

  Returns

    to be added to the default instance, of type dict of floats

      keyed by VariationIndex compound values: i.e. (outer << 16) + inner.

  Return type

    defaultDeltas

fontTools.varLib.instancer.instantiateMVAR(varfont, axisLimits)

fontTools.varLib.instancer.instantiateOTL(varfont, axisLimits)

fontTools.varLib.instancer.instantiateSTAT(varfont, axisLimits)

fontTools.varLib.instancer.instantiateTupleVariationStore(variations, axisLimits, origCoords=None, endPts=None)

  Instantiate TupleVariation list at the given location, or limit axes’ min/max.

  The ‘variations’ list of TupleVariation objects is modified in-place. The ‘axisLimits’ (dict) maps axis tags (str) to either a single coordinate along the axis (float), or to minimum/maximum coordinates (NormalizedAxisRange).

  A ‘full’ instance (i.e. static font) is produced when all the axes are pinned to single coordinates; a ‘partial’ instance (i.e. a less variable font) is produced when some of the axes are omitted, or restricted with a new range.

  Tuples that do not participate are kept as they are. Those that have 0 influence at the given location are removed from the variation store. Those that are fully instantiated (i.e. all their axes are being pinned) are also removed from the variation store, their scaled deltas accummulated and returned, so that they can be added by the caller to the default instance’s coordinates. Tuples that are only partially instantiated (i.e. not all the axes that they participate in are being pinned) are kept in the store, and their deltas multiplied by the scalar support of the axes to be pinned at the desired location.

  Parameters

    - variations – List[TupleVariation] from either ‘gvar’ or ‘cvar’.

    - axisLimits – Dict[str, Union[float, NormalizedAxisRange]]: axes’ coordinates for the full or partial instance, or ranges for restricting an axis’ min/max.

    - origCoords – GlyphCoordinates: default instance’s coordinates for computing ‘gvar’ inferred points (cf. table__g_l_y_f._getCoordinatesAndControls).

    - endPts – List[int]: indices of contour end points, for inferring ‘gvar’ deltas.

  Returns

    the overall delta adjustment after applicable deltas were summed.

  Return type

    List[float]

fontTools.varLib.instancer.instantiateVVAR(varfont, axisLimits)

fontTools.varLib.instancer.instantiateVariableFont(varfont, axisLimits, inplace=False, optimize=True, overlap=OverlapMode.KEEP_AND_SET_FLAGS, updateFontNames=False)

  Instantiate variable font, either fully or partially.

  Depending on whether the axisLimits dictionary references all or some of the input varfont’s axes, the output font will either be a full instance (static font) or a variable font with possibly less variation data.

  Parameters

    - varfont – a TTFont instance, which must contain at least an ‘fvar’ table. Note that variable fonts with ‘CFF2’ table are not supported yet.

    - axisLimits – a dict keyed by axis tags (str) containing the coordinates (float) along one or more axes where the desired instance will be located. If the value is None, the default coordinate as per ‘fvar’ table for that axis is used. The limit values can also be (min, max) tuples for restricting an axis’s variation range. The default axis value must be included in the new range.

    - inplace (bool) – whether to modify input TTFont object in-place instead of returning a distinct object.

    - optimize (bool) – if False, do not perform IUP-delta optimization on the remaining ‘gvar’ table’s deltas. Possibly faster, and might work around rendering issues in some buggy environments, at the cost of a slightly larger file size.

    - overlap (OverlapMode) – variable fonts usually contain overlapping contours, and some font rendering engines on Apple platforms require that the OVERLAP_SIMPLE and OVERLAP_COMPOUND flags in the ‘glyf’ table be set to force rendering using a non-zero fill rule. Thus we always set these flags on all glyphs to maximise cross-compatibility of the generated instance. You can disable this by passing OverlapMode.KEEP_AND_DONT_SET_FLAGS. If you want to remove the overlaps altogether and merge overlapping contours and components, you can pass OverlapMode.REMOVE (or REMOVE_AND_IGNORE_ERRORS to not hard-fail on tricky glyphs). Note that this requires the skia-pathops package (available to pip install). The overlap parameter only has effect when generating full static instances.

    - updateFontNames (bool) – if True, update the instantiated font’s name table using the Axis Value Tables from the STAT table. The name table and the style bits in the head and OS/2 table will be updated so they conform to the R/I/B/BI model. If the STAT table is missing or an Axis Value table is missing for a given axis coordinate, a ValueError will be raised.

fontTools.varLib.instancer.isInstanceWithinAxisRanges(location, axisRanges)

fontTools.varLib.instancer.limitTupleVariationAxisRange(var, axisTag, axisRange)

fontTools.varLib.instancer.limitTupleVariationAxisRanges(variations, axisRanges)

fontTools.varLib.instancer.main(args=None)

  Partially instantiate a variable font

fontTools.varLib.instancer.normalize(value, triple, avarMapping)

fontTools.varLib.instancer.normalizeAxisLimits(varfont, axisLimits, usingAvar=True)

fontTools.varLib.instancer.parseArgs(args)

  Parse argv.

  Returns

    3-tuple (infile, axisLimits, options) axisLimits is either a Dict[str, Optional[float]], for pinning variation axes to specific coordinates along those axes (with None as a placeholder for an axis’ default value); or a Dict[str, Tuple(float, float)], meaning limit this axis to min/max range. Axes locations are in user-space coordinates, as defined in the “fvar” table.

fontTools.varLib.instancer.parseLimits(limits)

fontTools.varLib.instancer.pinTupleVariationAxes(variations, location)

fontTools.varLib.instancer.populateAxisDefaults(varfont, axisLimits)

fontTools.varLib.instancer.sanityCheckVariableTables(varfont)

fontTools.varLib.instancer.setCvarDeltas(cvt, deltas)

fontTools.varLib.instancer.setMacOverlapFlags(glyfTable)

fontTools.varLib.instancer.setMvarDeltas(varfont, deltas)

fontTools.varLib.instancer.setRibbiBits(font)

  Set the head.macStyle and OS/2.fsSelection style bits appropriately.

fontTools.varLib.instancer.splitAxisLocationAndRanges(axisLimits, rangeType=<class 'fontTools.varLib.instancer.AxisRange'>)