Lua logo

Preface

This is the reference manual of MoonFreeType, which is a Lua binding library for the FreeType Library. [1]

It is assumed that the reader is familiar with both FreeType and the Lua programming language.

For convenience of reference, this document contains external (deep) links to the Lua Reference Manual and to the FreeType Documentation.

Getting and installing

For installation intructions, refer to the README file in the MoonFreeType official repository on GitHub.

Module organization

The MoonFreeType module is loaded using Lua’s require() and returns a table containing the functions it provides (as usual with Lua modules). This manual assumes that such table is named ft, i.e. that it is loaded with:

 ft = require("moonfreetype")

but nothing forbids the use of a different name.

Examples

A few examples can be found in the examples/ directory of the release package.

License

MoonFreeType is released under the MIT/X11 license (same as Lua, and with the same only requirement to give proper credits to the original author). The copyright notice is in the LICENSE file in the base directory of the official repository on GitHub.

Introduction

MoonFreeType is meant to be used similarly to FreeType (apart, of course, from programming in Lua instead of C). The following example shows its basic usage: you create an instance of the library, load faces from font files, retrieve glyphs from faces, and use them for whatever your purpose is.

Basic usage example
ft = require("moonfreetype")

-- Create an instance of the library:
lib = ft.init_freetype()

-- Load a font face from file, and rescale it:
face = ft.new_face(lib, "myfavouritefont.ttf")
face:set_pixel_sizes(0, 48)

-- Load the glyph for the character 'X' in the glyph slot:
face:load_char('X')
-- Get the glyph's data and print some of the fields:
glyph = face:glyph()
print("format", glyph.format)
print("metrics.width", glyph.metrics.width)
print("metrics.height", glyph.metrics.height)
-- ...

-- Delete the library
lib:done() -- short for ft.done_freetype(lib)

In MoonFreeType, FreeType functions are bound to by Lua functions which are members of the ft table. Each such function has a name which is usually a snake case version of the original (e.g. ft.init_freetype( ) for FT_Init_FreeType( ), ft.new_face( ) for FT_New_Face( ), and so on).

Some of the FreeType data types - for example libraries and faces - are represented in MoonFreeType as Lua objects (userdata with methods), while some other are represented as simple Lua tables with fields that reflect the underlying C structs.

Functions that are related to objects are also available as methods, for example face:set_pixel_sizes(…​) is the same as ft.set_pixel_sizes(face,…​). Methods are also provided to access the properties of objects, e.g. face:num_glyphs( ), face:family_name( ), etc.

All these function and methods, together with some additional utilities, are described in the sections that follow (that purposedly reflect the structure of the FreeType API Reference).

Core API

The library object

  • library = init_freetype( )
    Creates a new library instance.
    Rfr: FT_Init_FreeType.

  • done_freetype(library)
    Deletes the given library and all its children (faces, etc.)
    Also available as library:done( ) method.
    Rfr: FT_Done_FreeType.

  • major, minor, patch = library_version(library)
    Returns the library version.
    Also available as library:version( ) method.
    Rfr: FT_Library_Version.

The face object

  • face = new_face(library, filename [, index, instance])
    Creates a new face.
    filename: the path to the font file (a string).
    index: the index of the face in the font file (0-based, defaults to 0).
    instance: named instance index (defaults to 0)
    Also available as library:new_face( ) method.
    Rfr: FT_New_Face.

  • done_face(face)
    Deletes the given face.
    Also available as face:done( ) method.
    Rfr: FT_Done_Face.

Note
All MoonFreeType functions having a face object as first parameter are also available as face object methods. For example, the function set_pixel_sizes(face, width, height) is also available as face:set_pixel_sizes(width, height).

The following methods can be used to access the properties of a face object, that is, the fields of the underlying FT_FaceRec struct.

  • n = face:num_faces( )

  • index, instance = face:face_index( )
    Returns the index of the face in the font file (0-based) and the named instance index.

  • boolean = face:has_horizontal( )
    boolean = face:has_vertical( )
    boolean = face:has_kerning( )
    boolean = face:is_scalable( )
    boolean = face:is_sfnt( )
    boolean = face:is_fixed_width( )
    boolean = face:has_fixed_sizes( )
    boolean = face:has_fast_glyphs( )
    boolean = face:has_glyph_names( )
    boolean = face:has_multiple_masters( )
    boolean = face:is_cid_keyed( )
    boolean = face:is_tricky( )
    boolean = face:has_color( )
    Rfr: FT_FACE_FLAG_XXX.

  • boolean = face:is_italic( )
    boolean = face:is_bold( )
    Rfr: FT_STYLE_FLAG_XXX.

  • n = face:num_glyphs( )

  • string = face:family_name( )
    string = face:style_name( )
    May return nil (these fields are optional).

  • n = face:num_fixed_sizes( )
    {bitmapsize} = face:available_sizes( )
    Returns nil if num_fixed_sizes is 0, otherwise returns a table with num_fixed_sizes elements.

  • n = face:num_charmaps( )
    Returns nil if num__charmaps is 0, otherwise returns a table with num_charmaps elements.

  • bbox = face:bbox( )
    n = face:units_per_em( )
    n = face:ascender( )
    n = face:descender( )
    n = face:height( )
    n = face:max_advance_width( )
    n = face:max_advance_height( )
    n = face:underline_position( )
    n = face:underline_thickness( )
    These are relevant only to scalable outlines (see FT_FaceRec).

  • glyphdata = face:glyph( )
    Returns the data for the current glyph, i.e. the last loaded in the face’s glyph slot with a load_char( ) or load_glyph( ) call.

  • bitmap, left, top = face:glyph_bitmap( )
    Returns an handle to the bitmap object and the left and top bearing for the current glyph.
    Returns nil if the glyph format is not 'bitmap'.

  • outline = face:glyph_outline( )
    Returns an handle to the outline object for the current glyph.
    Returns nil if the glyph format is not 'outline'.

  • sizemetrics = face:size( )
    Returns the metrics for the current active size for this face.

  • charmap = face:charmap( )
    Returns the current active charmap for this face.

Base interface

  • load_char(face, charcode [, loadflags])
    charcode: character code (integer) or ascii character (string).
    Rfr: FT_Load_Char.

  • load_glyph(face, glyphindex [, loadflags])
    Rfr: FT_Load_Glyph.

  • glyphindex = get_char_index(face, charcode)
    charcode: character code (integer) or ascii character (string).
    Returns nil if the character code is not defined.
    Rfr: FT_Get_Char_Index.

  • glyphindex = get_name_index(face, glyphname)
    Returns nil if there is no glyph with such name.
    Rfr: FT_Get_Name_Index.

  • glyphname = get_glyph_name(face, glyphindex)
    Rfr: FT_Get_Glyph_Name.

  • name = get_postscript_name(face)
    Rfr: FT_Get_Postscript_Name.

  • charcode, glyphindex = get_first_char(face)
    charcode, glyphindex = get_next_char(face, charcode)
    charcode: character code (integer) or ascii character (string). Returned as integer.
    Both return nil if there is no first or next character.
    Rfr: FT_Get_First_Char, FT_Get_Next_Char.

  • set_transform(face [, matrix [, delta]])
    matrix: the 2x2 transformation matrix (nil for identity matrix).
    delta: the translation vector (nil for null vector).
    Rfr: FT_Set_Transform.

  • render_glyph(face, rendermode)
    Convert the current glyph image to a bitmap.
    Rfr: FT_Render_Glyph.

  • fstypeflags = get_fstype_flags(face)
    Rfr: FT_Get_FSType_Flags.

  • vector = get_kerning(face, leftglyph, rightglyph, kerningmode)
    leftglyph, rightglyph: integers (glyph indices, 1-based).
    Rfr: FT_Get_Kerning.

  • kerning = get_track_kerning(face, pointsize, degree)
    Rfr: FT_Get_Track_Kerning.

Glyph variants

Glyph Management

  • glyph = get_glyph(face)
    Creates a glyph object. The glyph image is extracted from the current glyph slot of the given face.
    Also available as face:get_glyph( ) method.
    Rfr: FT_Get_Glyph.

  • newglyph = glyph_copy(glyph)
    Creates a glyph object copying it from another one.
    Also available as glyph:copy( ) method.
    Rfr: FT_Glyph_Copy.

  • done_glyph(glyph)
    Also available as glyph:done( ) method.
    Rfr: FT_Done_Glyph.

  • cbox = glyph_get_cbox(glyph, bboxmode)
    Also available as glyph:get_cbox( ) method.
    Rfr: FT_Glyph_Get_CBox.

  • glyph_to_bitmap(glyph, rendermode [, origin [, destroy]])
    The origin parameter is a vector and defaults to nil (null vector, no translation).
    The destroy parameter is a boolean and defaults to true.
    Also available as glyph:to_bitmap( ) method.
    Rfr: FT_Glyph_To_Bitmap.

  • glyph_transform(glyph, matrix, delta)
    Also available as glyph:transform( ) method.
    The matrix and delta parameters are a matrix and vector, respectively.
    Rfr: FT_Glyph_Transform.


The following methods are available in order to access the contents of the glyph object (see FT_Glyph):

Size Management

  • size = new_size(face)
    Also available as face:new_size( ) method.
    Rfr: FT_New_Size.

  • done_size(size)
    Also available as size:done( ) method.
    Rfr: FT_Done_Size.

  • activate_size(size)
    Also available as size:activate( ) method.
    Rfr: FT_Activate_Size.

Format-Specific API

Font Formats

Support API

Computations

Rfr: Computations.

  • result = muldiv(a, b, c)
    result = mulfix(a, b)
    result = divfix(a, b)
    result = roundfix(a)
    result = ceilfix(a)
    result = floorfix(a)

  • result = sin(angle)
    result = cos(angle)
    result = tan(angle)
    angle = atan2(x, y)
    angle = angle_diff(angle1, angle2)

  • vector = vector_unit(angle)
    vector = vector_rotate(vector, unit_angle_)
    length = vector_length(vector)
    length, angle = vector_polarize(vector)
    vector = vector_from_polar(length, angle)

  • vector = vector_transform(vector, matrix)
    matrix = matrix_invert(matrix)
    matrix = matrix_multiply(matrix1, matrix2)

The constants ANGLE_PI, ANGLE_PI4, ANGLE_2PI, ANGLE_PI2 are also available as members of the ft table.

Outline processing

  • outline = outline_new(library, maxpoints, maxcontours)
    Returns an handle to a new outline object.
    Also available as library:outline_new( ) method.
    Rfr: FT_Outline_New.

  • outline_done(outline)
    Also available as outline:done( ) method.
    Rfr: FT_Outline_Done.

  • outline_copy(srcoutline, dstoutline)
    Source and destination outline must belong to the same library.
    Also available as outline:copy( ) method.
    Rfr: FT_Outline_Copy.

  • boolean, errmsg = outline_check(outline)
    Returns true on success, or false followed by an error message on failure.
    Also available as outline:check( ) method.
    Rfr: FT_Outline_Check.

  • outline_translate(outline, xoffset, yoffset)
    Also available as outline:translate( ) method.
    Rfr: FT_Outline_Translate.

  • outline_transform(outline, matrix)
    Also available as outline:transform( ) method.
    Rfr: FT_Outline_Transform.

  • outline_embolden(outline, strength)
    Also available as outline:embolden( ) method.
    Rfr: FT_Outline_Embolden.

  • outline_emboldenxy(outline, xstrength, ystrength)
    Also available as outline:emboldenxy( ) method.
    Rfr: FT_Outline_EmboldenXY.

  • outline_reverse(outline)
    Also available as outline:reverse( ) method.
    Rfr: FT_Outline_Reverse.

  • bbox = outline_get_bbox(outline)
    Also available as outline:get_bbox( ) method.
    Rfr: FT_Outline_Get_BBox.

  • cbox = outline_get_cbox(outline)
    Also available as outline:get_cbox( ) method.
    Rfr: FT_Outline_Get_CBox.

  • outline_get_bitmap(outline, dstbitmap)
    The destination bitmap must belong to the same library as the outline.
    Also available as outline:get_bitmap( ) method.
    Rfr: FT_Outline_Get_Bitmap.

  • orientation = outline_get_orientation(outline)
    Also available as outline:get_orientation( ) method.
    Rfr: FT_Outline_Get_Orientation.

  • border = outline_getinsideborder(outline)
    Also available as outline:getinsideborder( ) method.
    Rfr: FT_Outline_GetInsideBorder.

  • border = outline_getoutsideborder(outline)
    Also available as outline:getoutsideborder( ) method.
    Rfr: FT_Outline_GetOutsideBorder.

Quick retrieval of advance values

Bitmap handling

  • bitmap = new_bitmap(library)
    Returns an handle to a new bitmap object.
    Also available as library:new_bitmap( ) method.
    Rfr: FT_Bitmap_Init.

  • done_bitmap(bitmap)
    Also available as bitmap:done( ) method.
    Rfr: FT_Bitmap_Done.

  • bitmap_copy(srcbitmap, dstbitmap)
    Source and destination bitmap must belong to the same library.
    Also available as srcbitmap:copy( ) method.
    Rfr: FT_Bitmap_Copy.

  • bitmap_convert(srcbitmap, dstbitmap, alignment)
    Source and destination bitmap must belong to the same library.
    Also available as srcbitmap:convert( ) method.
    Rfr: FT_Bitmap_Convert.

  • bitmap_embolden(bitmap, xstrength, ystrength)
    Also available as bitmap:embolden( ) method.
    Rfr: FT_Bitmap_Embolden.

  • bitmapdata = bitmap:data([left , top])
    Use this to retrieve the bitmap contents.
    The 'left' and 'top' parameters are used only to initialize the respective fields of the returned bitmapdata table (both default to 0).

Glyph Stroker

  • stroker = stroker_new(library)
    Returns an handle to a new strokerobject.
    Also available as library:stroker_new( ) method.
    Rfr: FT_Stroker_New.

  • stroker_done(stroker)
    Also available as stroker:done( ) method.
    Rfr: FT_Stroker_Done.

  • stroker_beginsubpath(stroker, to, open)
    The to parameter is a vector and the open parameter is a boolean.
    Also available as stroker:beginsubpath( ) method.
    Rfr: FT_Stroker_BeginSubPath.

  • stroker_endsubpath(stroker)
    Also available as stroker:endsubpath( ) method.
    Rfr: FT_Stroker_EndSubPath.

  • stroker_rewind(stroker)
    Also available as stroker:rewind( ) method.
    Rfr: FT_Stroker_Rewind.

  • stroker_set(stroker, radius, linecap, linejoin, miterlimit)
    Also available as stroker:set( ) method.
    Rfr: FT_Stroker_Set.

  • stroker_conicto(stroker, control, to)
    The control and to parameters are vectors.
    Also available as stroker:conicto( ) method.
    Rfr: FT_Stroker_ConicTo.

  • stroker_cubicto(stroker, control1, control2, to)
    The control1, control2, and to parameters are vectors.
    Also available as stroker:cubicto( ) method.
    Rfr: FT_Stroker_CubicTo.

  • stroker_lineto(stroker, to)
    The to parameter is a vector.
    Also available as stroker:lineto( ) method.
    Rfr: FT_Stroker_LineTo.

  • numpoints, numcontours = stroker_getcounts(stroker)
    Also available as stroker:getcounts( ) method.
    Rfr: FT_Stroker_GetCounts.

  • numpoints, numcontours = stroker_getbordercounts(stroker, border)
    Also available as stroker:getbordercounts( ) method.
    Rfr: FT_Stroker_GetBorderCounts.

  • stroker_parseoutline(stroker, outline, opened)
    The opened parameter is a boolean.
    Stroker and outline must belong to the same library.
    Also available as stroker:parseoutline( ) method.
    Rfr: FT_Stroker_ParseOutline.

  • stroker_export(stroker, outline)
    Stroker and outline must belong to the same library.
    Also available as stroker:export( ) method.
    Rfr: FT_Stroker_Export.

  • stroker_exportborder(stroker, border, outline)
    Stroker and outline must belong to the same library.
    Also available as stroker:exportborder( ) method.
    Rfr: FT_Stroker_ExportBorder.

Error Codes

Error codes are not exposed directly. MoonFreeTypes automatically performs error checking whenever it calls a FreeType function, and if an error occurs, it raises a Lua error( ) passing it the text version of the FreeType error code as the message parameter.

This behaviour can be overridden by using pcall( ).

Structs

Most FreeType structs are represented in MoonFreeType as Lua tables, which are described in this section.

There is an (almost) one-to-one correspondence between the table fields and the fields of the underlying C structs. Refer to the FreeType documentation for their meanings.

  • bbox = {
    xmin, ymin: integer,
    xmax, ymax: integer,
    } (rfr: FT_BBox)

  • bitmapdata = {
    rows, width, pitch, left, top: integer,
    pixel_mode: pixelmode,
    num_grays: integer (for 'gray' pixel mode only),
    buffer: binary string (#buffer = rows * abs(pitch)),
    } (rfr: FT_Bitmap)

  • bitmapsize = {
    height, width: integer,
    size: integer,
    x_ppem, y_ppem: integer,
    } (rfr: FT_Bitmap_Size)

  • charmap = {
    encoding: encoding,
    platform_id, encoding_id: integer,
    platform_name, encoding_name: string (text version of id, may be nil),
    } (rfr: FT_CharMapRec)

  • glyphdata = {
    metrics: glyphmetrics,
    linear_hori_advance: integer,
    linear_vert_advance: integer,
    advance: matrix,
    format: glyphformat,
    bitmap: bitmapdata (for 'bitmap' format only),
    outline: outlinedata (for 'outline' and 'plotter' formats only),
    subglyphs: {subglyph} (for 'composite' format only),
    control_data: binary string (optional),
    lsb_delta, rsb_delta: integer,
    } (rfr: FT_GlyphSlot)
    Note: The fields bitmap_left, and bitmap_top are moved in the bitmapdata table (as bitmap.left and bitmap.top, respectively).

  • glyphmetrics = {
    width, height: integer,
    hori_bearing_x, hori_bearing_y, hori_advance: integer,
    vert_bearing_x, vert_bearing_y, vert_advance: integer,
    } (rfr: FT_Glyph_Metrics)

  • matrix = {
    xx, xy: integer,
    yx, yy: integer,
    } (rfr: FT_Matrix)

  • outlinedata = {
    points: {vector},
    tags: {integer} (#tags = #points),
    type: {pointtype} (#type = #points),
    scanmode: {scanmode} (#scanmode = #points),
    contours: {integer} (indices in points array, 1-based),
    flags: outlineflags (integer code),
    } (rfr: FT_Outline)

  • sizemetrics = {
    x_ppem, y_ppem: integer,
    y_scale, y_scale: integer,
    ascender, descender: integer,
    height: integer,
    max_advance: integer,
    } (rfr: FT_Size_Metrics)

  • subglyph = {
    index: integer (glyph index, 1-based),
    flags: subglyphflags (integer code),
    arg1, arg2: integer,
    transform: matrix,
    } (rfr: FT_Get_SubGlyph_Info)

  • vector = {
    x, y: integer,
    } (rfr: FT_Vector)

Enums

FreeType enums are mapped in MoonFreeType to sets of string literals (as is customary in Lua). Admitted literals are available in the ft table (e.g. *ft.ENCODING_XXX for FT_ENCODING_XXX), and can also be inferred from the corresponding C enum names. For example, given the ft.ENCODING_XXX hint for the encoding enum type, the literals it admits are obtained by lowercasing the XXX part of the name and replacing any underscore with a space.

If needed, the following function can be used to obtain the list of literals admitted by a particular enum type.

  • {literal} = ft.enum(enumtype)
    Returns a table listing the literals admitted by enumtype (given as a string, e.g. 'ms symbol', 'unicode', etc).

bboxmode: ft.GLYPH_BBOX_XXX
Values: 'unscaled', 'gridfit', 'truncate', 'pixels'.
Rfr: FT_Glyph_BBox_Mode.

encoding: ft.ENCODING_XXX
Values: 'none', 'ms symbol', 'unicode', 'sjis', 'gb2312', 'big5', 'wansung', 'johab', 'adobe standard', 'adobe expert', 'adobe custom', 'adobe latin 1', 'apple roman'.
Rfr: FT_Encoding.

glyphformat: ft.GLYPH_FORMAT_XXX
Values: 'none', 'composite', 'bitmap', 'outline', 'plotter'.
Rfr: FT_Glyph_Format.

kerningmode: ft.KERNING_XXX
Values: 'default', 'unfitted', 'unscaled'.
Rfr: FT_Kerning_Mode.

orientation: ft.ORIENTATION_XXX
Values: 'fill right' (truetype), 'fill left' (postscript).
Rfr: FT_Orientation.

pixelmode: ft.PIXEL_MODE_XXX
Values: 'none', 'mono', 'gray', 'gray2', 'gray4', 'lcd', 'lcd v', 'bgra'.
Rfr: FT_Pixel_Mode.

pointtype: -
Values: 'on', 'cubic', or 'conic'.
Rfr: FT_Outline tags.

rendermode: ft.RENDER_MODE_XXX
Values: 'normal', 'light', 'mono', 'lcd', 'lcd v'.
Rfr: FT_Render_Mode.

scanmode: -
Values: 'none', 'touch x', 'touch y', or 'touch both'.
Rfr: FT_Outline tags.

sizerequesttype: ft.SIZE_REQUEST_XXX
Values: 'bbox', 'cell', 'nominal', 'real dim', 'scales'.
Rfr: FT_Size_Request_Type.

strokerborder: ft.STROKER_BORDER_XXX
Values: 'left', 'right'.
Rfr: FT_StrokerBorder.

strokerlinecap: ft.STROKER_LINECAP_XXX
Values: 'butt', 'round', 'square'.
Rfr: FT_Stroker_LineCap.

strokerlinejoin: ft.STROKER_LINEJOIN_XXX
Values: 'round', 'bevel', 'miter variable', 'miter fixed'.
Rfr: FT_Stroker_LineJoin.

truetypeenginetype: ft.TRUETYPE_ENGINE_TYPE_XXX
Values: 'none', 'patented', 'unpatented'
Rfr: FT_TrueTypeEngineType.

Flags

Flags in MoonFreeType functions and structs are always represented as plain integers, and encoded in the same way as the corresponding flags in the FreeType API.

The ft table contains the FT_XXX values, renamed as ft.XXX (e.g. ft.LOAD_RENDER, ft.LOAD_NO_SCALE, etc.).

For each flags type (see the list below), a utility function is also available to map an integer code to a list of string literals, each corresponding to an individual bit set in the code, and viceversa to encode an integer value from the individual bits given as a list of string literals. The generic definition of such functions is the following, where xxxflags stands for fstypeflags, loadflags, etc:

  • code = xxxflags(s1, s2, …​)
    s1, s2, …​ = xxxflags(code)
    Maps the integer code to/from the list of string values s1, s2, …​.

fstypeflags: ft.FSTYPE_XXX
Values: 'installable embedding' (0), 'restricted license embedding', 'preview and print embedding', 'editable embedding', 'no subsetting', 'bitmap embedding only'.
Rfr: FT_FSTYPE_XXX.

loadflags: ft.LOAD_XXX
Values: 'default' (0), 'no scale', 'no hinting', 'render', 'no bitmap', 'vertical layout', 'force autohint', 'crop bitmap', 'pedantic', 'ignore global advance width', 'no recurse', 'ignore transform', 'monochrome', 'linear design', 'no autohint', 'color', 'compute metrics', 'fast only', 'target normal' (0), 'target light', 'target mono', 'target lcd', 'target lcd v'.
Note: only one target flag can be included.
Rfr: FT_LOAD_XXX.

outlineflags: ft.OUTLINE_XXX
Values: 'none', 'owner', 'even odd fill', 'reverse fill', 'ignore dropouts', 'smart dropouts', 'include stubs', 'high precision', 'single pass'.
Rfr: FT_OUTLINE_XXX.

subglyphflags: ft.SUBGLYPH_FLAG_XXX
Values: 'none' (0), 'args are words', 'args are xy values', 'round xy to grid', 'scale', 'xy scale', '2x2', 'use my metrics' .
Rfr: FT_SUBGLYPH_FLAG_XXX.

Implementation notes


1. This manual is written in AsciiDoc, rendered with AsciiDoctor and a CSS from the AsciiDoctor Stylesheet Factory. The PDF version is produced with AsciiDoctor-Pdf.