SDF combining distance fields

submited by
Style Pass
2024-09-28 14:00:04

Learning about font rendering, I was looking at text closely last time, and I noticed another issue. The shadows of each letter overlap the previous letter. That’s because I’m drawing one letter at a time. So for example in the fl, I draw the f’s letter, outline, and shadow, then I draw l’s letter, outline, and shadow. So l’s shadow is drawn on top of f’s letter.

The first thing I considered was to draw all the shadows first and then draw all the letters. But a second problem here, harder to see, is that shadows are drawn on top of the adjacent letter’s shadows, and that causes them to be darker than they should be. The distance fields for adjacent letters always overlap:

To solve both problems, I can generate a new distance field which is the min() of the distance fields for each character. The min() of signed distance fields is the union of the shapes. I used the blendEquation()[1] function with MAX_EXT instead of the default FUNC_ADD (it’s max instead of min because msdfgen’s encoding is inverted). The MAX_EXT extension seems to have 100% support[2] in WebGL 1, and is always included with WebGL 2.

The output texture holds a combined distance field. I then use the distance field shader to draw that combined distance field to the map.

Leave a Comment