Magnum::TextureTools::DistanceField class

Create a signed distance field.

Converts a binary black/white image (stored in the red channel of input) to a signed distance field (stored in the red channel of output rectangle). The purpose of this function is to convert a high-resolution binary image (such as vector artwork or font glyphs) to a low-resolution grayscale image. The image will then occupy much less memory and can be scaled without aliasing issues. Additionally it provides foundation for features like outlining, glow or drop shadow essentially for free.

You can also use the magnum-distancefieldconverter utility to do distance field conversion on command-line. This functionality is also used inside the magnum-fontconverter utility.

The algorithm

For each pixel inside the output sub-rectangle the algorithm looks at corresponding pixel in the input and tries to find nearest pixel of opposite color in an area defined radius. Signed distance between the points is then saved as value of given pixel in output. Value of 1.0 means that the pixel was originally colored white and nearest black pixel is farther than radius, value of 0.0 means that the pixel was originally black and nearest white pixel is farther than radius. Values around 0.5 are around edges.

The resulting texture can be used with bilinear filtering. It can be converted back to binary form in shader using e.g. GLSL smoothstep() function with step around 0.5 to create antialiased edges. Or you can exploit the distance field features to create many other effects. See also Shaders::DistanceFieldVector.

Based on: Chris Green - Improved Alpha-Tested Magnification for Vector Textures and Special Effects, SIGGRAPH 2007, http://www.valvesoftware.com/publications/2007/SIGGRAPH2007_AlphaTestedMagnification.pdf

Constructors, destructors, conversion operators

DistanceField(UnsignedInt radius) explicit
Constructor.

Public functions

auto radius() const -> UnsignedInt
Max lookup radius.
void operator()(GL::Texture2D& input, GL::Texture2D& output, const Range2Di& rectangle, const Vector2i& imageSize = {})
Calculate the distance field.

Function documentation

Magnum::TextureTools::DistanceField::DistanceField(UnsignedInt radius) explicit

Constructor.

Parameters
radius Max lookup radius in the input texture

Prepares the shader and other internal state for given radius.

void Magnum::TextureTools::DistanceField::operator()(GL::Texture2D& input, GL::Texture2D& output, const Range2Di& rectangle, const Vector2i& imageSize = {})

Calculate the distance field.

Parameters
input Input texture
output Output texture
rectangle Rectangle in output texture where to render
imageSize Input texture size. Needed only for OpenGL ES, on desktop GL the information is gathered automatically using GL::Texture2D::imageSize().