203

There are already a number of questions about text rendering in OpenGL, such as:

But mostly what is discussed is rendering textured quads using the fixed-function pipeline. Surely shaders must make a better way.

I'm not really concerned about internationalization, most of my strings will be plot tick labels (date and time or purely numeric). But the plots will be re-rendered at the screen refresh rate and there could be quite a bit of text (not more than a few thousand glyphs on-screen, but enough that hardware accelerated layout would be nice).

What is the recommended approach for text-rendering using modern OpenGL? (Citing existing software using the approach is good evidence that it works well)

  • Geometry shaders that accept e.g. position and orientation and a character sequence and emit textured quads
  • Geometry shaders that render vector fonts
  • As above, but using tessellation shaders instead
  • A compute shader to do font rasterization
Community
  • 1
  • 1
Ben Voigt
  • 260,885
  • 36
  • 380
  • 671
  • 10
    I'm not able to answer on state of the art, being primarily OpenGL ES oriented nowadays, but tessellating a TTF using the GLU tesselator and submitting it as geometry via the old fixed functionality pipeline with kerning calculated on CPU gave good visual results on anti-aliasing hardware and good performance across the board even almost a decade ago. So it's not just with shaders that you can find a 'better' way (depending on your criteria, of course). FreeType can spit out Bezier glyph boundaries and kerning information, so you can work live from a TTF at runtime. – Tommy Mar 10 '11 at 16:59
  • QML2 (of Qt5) does some interesting tricks with OpenGL and distance fields when rendering text: http://blog.qt.digia.com/blog/2012/08/08/native-looking-text-in-qml-2/ – mlvljr Nov 10 '13 at 12:47
  • 9
    this "off-topic" is the curse of stack overflow. seriously? – Nikolaos Giotis Sep 29 '14 at 20:38
  • 1
    a more naive "how to do it" version: http://stackoverflow.com/questions/8847899/opengl-how-to-draw-text-using-only-opengl-methods – Ciro Santilli新疆棉花TRUMP BAN BAD May 01 '16 at 08:56
  • @NikYotis I think this is too broad / tool rec: it is an actual research subject :-) But I won't close vote because it's useful. – Ciro Santilli新疆棉花TRUMP BAN BAD May 01 '16 at 08:57
  • @Peter: If you want a similar question covering versions past 4.1, ask as a new question containing a link back to this one (and it also needs to name a specific version number, because moving targets are bad) – Ben Voigt May 15 '17 at 22:43
  • @BenVoigt: Sorry if you didn't like my edit. Since some of the techniques in the accepted answer appear to be doable using any version of OpenGL that uses shaders ("modern" OpenGL or OpenGL version 3.2 and later), and especially since a particular version is not elsewhere mentioned in the question, I merely assumed that broadening the title by saying "modern OpenGL" instead of "OpenGL 4.1" would not seriously affect the scope of the question. (I have no intent on asking any questions on this topic.) – Peter O. May 19 '17 at 09:08
  • So I don't lose it again, here is a library that implements Valve's distance field method. https://code.google.com/p/glyphy/ I haven't tried it. Also maybe worth a look: https://code.google.com/p/signed-distance-field-font-generator/ – Timmmm Jul 24 '14 at 14:30

5 Answers5

208

Rendering outlines, unless you render only a dozen characters total, remains a "no go" due to the number of vertices needed per character to approximate curvature. Though there have been approaches to evaluate bezier curves in the pixel shader instead, these suffer from not being easily antialiased, which is trivial using a distance-map-textured quad, and evaluating curves in the shader is still computationally much more expensive than necessary.

The best trade-off between "fast" and "quality" are still textured quads with a signed distance field texture. It is very slightly slower than using a plain normal textured quad, but not so much. The quality on the other hand, is in an entirely different ballpark. The results are truly stunning, it is as fast as you can get, and effects such as glow are trivially easy to add, too. Also, the technique can be downgraded nicely to older hardware, if needed.

See the famous Valve paper for the technique.

The technique is conceptually similar to how implicit surfaces (metaballs and such) work, though it does not generate polygons. It runs entirely in the pixel shader and takes the distance sampled from the texture as a distance function. Everything above a chosen threshold (usually 0.5) is "in", everything else is "out". In the simplest case, on 10 year old non-shader-capable hardware, setting the alpha test threshold to 0.5 will do that exact thing (though without special effects and antialiasing).
If one wants to add a little more weight to the font (faux bold), a slightly smaller threshold will do the trick without modifying a single line of code (just change your "font_weight" uniform). For a glow effect, one simply considers everything above one threshold as "in" and everything above another (smaller) threshold as "out, but in glow", and LERPs between the two. Antialiasing works similarly.

By using an 8-bit signed distance value rather than a single bit, this technique increases the effective resolution of your texture map 16-fold in each dimension (instead of black and white, all possible shades are used, thus we have 256 times the information using the same storage). But even if you magnify far beyond 16x, the result still looks quite acceptable. Long straight lines will eventually become a bit wiggly, but there will be no typical "blocky" sampling artefacts.

You can use a geometry shader for generating the quads out of points (reduce bus bandwidth), but honestly the gains are rather marginal. The same is true for instanced character rendering as described in GPG8. The overhead of instancing is only amortized if you have a lot of text to draw. The gains are, in my opinion, in no relation to the added complexity and non-downgradeability. Plus, you are either limited by the amount of constant registers, or you have to read from a texture buffer object, which is non-optimal for cache coherence (and the intent was to optimize to begin with!).
A simple, plain old vertex buffer is just as fast (possibly faster) if you schedule the upload a bit ahead in time and will run on every hardware built during the last 15 years. And, it is not limited to any particular number of characters in your font, nor to a particular number of characters to render.

If you are sure that you do not have more than 256 characters in your font, texture arrays may be worth a consideration to strip off bus bandwidth in a similar manner as generating quads from points in the geometry shader. When using an array texture, the texture coordinates of all quads have identical, constant s and t coordinates and only differ in the r coordinate, which is equal to the character index to render.
But like with the other techniques, the expected gains are marginal at the cost of being incompatible with previous generation hardware.

There is a handy tool by Jonathan Dummer for generating distance textures: description page

Update:
As more recently pointed out in Programmable Vertex Pulling (D. Rákos, "OpenGL Insights", pp. 239), there is no significant extra latency or overhead associated with pulling vertex data programmatically from the shader on the newest generations of GPUs, as compared to doing the same using the standard fixed function.
Also, the latest generations of GPUs have more and more reasonably sized general-purpose L2 caches (e.g. 1536kiB on nvidia Kepler), so one may expect the incoherent access problem when pulling random offsets for the quad corners from a buffer texture being less of a problem.

This makes the idea of pulling constant data (such as quad sizes) from a buffer texture more attractive. A hypothetical implementation could thus reduce PCIe and memory transfers, as well as GPU memory, to a minimum with an approach like this:

  • Only upload a character index (one per character to be displayed) as the only input to a vertex shader that passes on this index and gl_VertexID, and amplify that to 4 points in the geometry shader, still having the character index and the vertex id (this will be "gl_primitiveID made available in the vertex shader") as the sole attributes, and capture this via transform feedback.
  • This will be fast, because there are only two output attributes (main bottleneck in GS), and it is close to "no-op" otherwise in both stages.
  • Bind a buffer texture which contains, for each character in the font, the textured quad's vertex positions relative to the base point (these are basically the "font metrics"). This data can be compressed to 4 numbers per quad by storing only the offset of the bottom left vertex, and encoding the width and height of the axis-aligned box (assuming half floats, this will be 8 bytes of constant buffer per character -- a typical 256 character font could fit completely into 2kiB of L1 cache).
  • Set an uniform for the baseline
  • Bind a buffer texture with horizontal offsets. These could probably even be calculated on the GPU, but it is much easier and more efficient to that kind of thing on the CPU, as it is a strictly sequential operation and not at all trivial (think of kerning). Also, it would need another feedback pass, which would be another sync point.
  • Render the previously generated data from the feedback buffer, the vertex shader pulls the horizontal offset of the base point and the offsets of the corner vertices from buffer objects (using the primitive id and the character index). The original vertex ID of the submitted vertices is now our "primitive ID" (remember the GS turned the vertices into quads).

Like this, one could ideally reduce the required vertex bandwith by 75% (amortized), though it would only be able to render a single line. If one wanted to be able to render several lines in one draw call, one would need to add the baseline to the buffer texture, rather than using an uniform (making the bandwidth gains smaller).

However, even assuming a 75% reduction -- since the vertex data to display "reasonable" amounts of text is only somewhere around 50-100kiB (which is practically zero to a GPU or a PCIe bus) -- I still doubt that the added complexity and losing backwards-compatibility is really worth the trouble. Reducing zero by 75% is still only zero. I have admittedly not tried the above approach, and more research would be needed to make a truly qualified statement. But still, unless someone can demonstrate a truly stunning performance difference (using "normal" amounts of text, not billions of characters!), my point of view remains that for the vertex data, a simple, plain old vertex buffer is justifiably good enough to be considered part of a "state of the art solution". It's simple and straightforward, it works, and it works well.

Having already referenced "OpenGL Insights" above, it is worth to also point out the chapter "2D Shape Rendering by Distance Fields" by Stefan Gustavson which explains distance field rendering in great detail.

Update 2016:

Meanwhile, there exist several additional techniques which aim to remove the corner rounding artefacts which become disturbing at extreme magnifications.

One approach simply uses pseudo-distance fields instead of distance fields (the difference being that the distance is the shortest distance not to the actual outline, but to the outline or an imaginary line protruding over the edge). This is somewhat better, and runs at the same speed (identical shader), using the same amount of texture memory.

Another approach uses the median-of-three in a three-channel texture details and implementation available at github. This aims to be an improvement over the and-or hacks used previously to address the issue. Good quality, slightly, almost not noticeably, slower, but uses three times as much texture memory. Also, extra effects (e.g. glow) are harder to get right.

Lastly, storing the actual bezier curves making up characters, and evaluating them in a fragment shader has become practical, with slightly inferior performance (but not so much that it's a problem) and stunning results even at highest magnifications.
WebGL demo rendering a large PDF with this technique in real time available here.

mr5
  • 3,015
  • 3
  • 39
  • 54
Damon
  • 61,669
  • 16
  • 122
  • 172
  • Intersting - good stuff. How do these techniques work for making small fonts look as good as "soft" font specific rendering of antialiased fonts for document viewing in the 10 to 30 pixel high range? – peterk Feb 09 '12 at 23:51
  • 1
    They look quite good (even with naive filtering and in absence of mipmapping, since you have very small textures and the data nicely interpolates). Personally I think they even look _better_ than the "real" thing in many cases, because there are no oddities as hinting, which often produce things that I perceive as "weird". For example, smaller text doesn't suddenly get bold for no obvious reason, nor pop to pixel boundaries - effects you often see with "real" fonts. There may be historic reasons for that (1985 b/w displays), but today, it's beyond my comprehension why it has to be like that. – Damon Feb 10 '12 at 12:23
  • 2
    Works & looks great, thanks for sharing! For those who want HLSL frag shader source see [here](http://bytewrangler.blogspot.co.uk/2011/10/signed-distance-fields.html). You can adapt this for GLSL by replacing the `clip(...)` line with `if (text.a < 0.5) {discard;}` (or `text.a < threshold`). HTH. – Engineer Oct 07 '12 at 14:05
  • 1
    Thanks for the update. I wish I could upvote again. – Ben Voigt Mar 21 '13 at 17:02
  • @Damon: What are "on the newest generations of GPUs"? If you're going to quote something, be complete about it. – Nicol Bolas Mar 28 '13 at 00:32
  • Also, I don't see the point of your proposed method, thanks to this: "*Bind a buffer texture with horizontal offsets.*" That requires a full GPU/CPU sync, which is certainly not worth the effort compared to adding a few shorts to a buffer. You still have to use buffer streaming techniques either way; do you really think that two rendering passes and a GPU/CPU sync are going to be faster than the obvious method? – Nicol Bolas Mar 28 '13 at 00:37
  • 2
    @NicolBolas: You seem to not have read very carefully. Both questions are explained in the answer. Kepler is given as a "latest gen" example, there is no second pass (and it's explained why), and I state that I do _not_ believe that the hypotetical bandwidth-saving technique is noticeably faster or worth the trouble at all. However, belief means nothing -- one would have to try to know (I haven't since I don't consider drawing "normal" amounts of text a bottleneck either way). It _could_ nevertheless be worthwhile in a when one is desperate about bandwidth and has "abnormal" amounts of text. – Damon Mar 28 '13 at 15:49
  • @Damon: "*Kepler is given as a "latest gen" example*" I saw that, but that's not an answer (and if it didn't, you're *really* misleading people by suggesting that it's testing was comprehensive). Presumably, the book did testing on non-Kepler hardware. If you're going to cite the book and give some of it's information, you should give a *complete* rundown of the hardware it tested this on and which hardware could do it reasonably. Not a cryptic "on the newest generations of GPUs". – Nicol Bolas Mar 28 '13 at 23:03
  • @Damon: "*there is no second pass (and it's explained why)*" Really? "*Render the **previously generated data** from the feedback buffer*" That sounds an awful lot like a second pass to me. I did misread about the GPU/CPU sync, though. As for "'abnormal' amounts of text", CivIV has more text than most games. Versions of FireFox attempt to accelerate glyph rendering through OpenGL. And neither of them use this technique. In order for this minor bandwidth savings to matter, you would have to either be rendering a lot of overlapping text, or you'd be rendering at mega-resolutions. – Nicol Bolas Mar 28 '13 at 23:13
  • 3
    @NicolBolas: You're right about that sentence, sorry. It is indeed a bit misleading. In the previous paragraph, I wrote _"One could probably even generate this on the GPU, but that would require feedback and... isnogud."_ -- but then errornously continued with _"the generated data from the feedback buffer"_. I'll correct this. Actually, I'll rewrite the complete thing on the weekend, so it's less ambiguous. – Damon Mar 29 '13 at 15:00
  • The demo of WebGL does not look good on the latest Android Webview. Fonts are jagged and rendered incorrectly. – mr5 May 16 '17 at 23:24
  • 1
    "The best trade-off between "fast" and "quality" are still textured quads with a signed distance field texture." I disagreed with this generalisation, this is only true for middle to large font sizes, but not at all for small ones. For small ones you are better off with using Freetype etc and rendering the glyphs directly without SDF. I am talking about font glyph sizes below ~16 pixels height here. Unfortunately, such sizes are still quite common in game GUIs, especially if you have a complex GUI like in most strategy games / Diablo-like ARPGs etc., not so much in 1st/3rd person shooters ;) – Ident Jul 25 '17 at 18:54
15

http://code.google.com/p/glyphy/

The main difference between GLyphy and other SDF-based OpenGL renderers is that most other projects sample the SDF into a texture. This has all the usual problems that sampling has. Ie. it distorts the outline and is low quality. GLyphy instead represents the SDF using actual vectors submitted to the GPU. This results in very high quality rendering.

The downside is that the code is for iOS with OpenGL ES. I'm probably going to make a Windows/Linux OpenGL 4.x port (hopefully the author will add some real documentation, though).

Display Name
  • 1,940
  • 1
  • 21
  • 40
  • 3
    Anyone interested in GLyphy should probably watch the author's talk at Linux.conf.au 2014: https://www.youtube.com/watch?v=KdNxR5V7prk – Fizz Aug 07 '14 at 15:09
14

The most widespread technique is still textured quads. However in 2005 LORIA developed something called vector textures, i.e. rendering vector graphics as textures on primitives. If one uses this to convert TrueType or OpenType fonts into a vector texture you get this:

http://alice.loria.fr/index.php/publications.html?Paper=VTM@2005

datenwolf
  • 149,702
  • 12
  • 167
  • 273
  • 2
    Do you know of any implementations using this technique? – luke Aug 14 '13 at 12:44
  • 2
    No (as in production-grade), but Kilgard's paper (see my answer below for link) has a brief critique, which I summarize as: not yet practical. There has been more research in the area; more recent work cited by Kilgard includes http://research.microsoft.com/en-us/um/people/hoppe/ravg.pdf and https://uwspace.uwaterloo.ca/handle/10012/4262 – Fizz Aug 08 '14 at 19:55
9

I'm surprised Mark Kilgard's baby, NV_path_rendering (NVpr), was not mentioned by any of the above. Although its goals are more general than font rendering, it can also render text from fonts and with kerning. It doesn't even require OpenGL 4.1, but it is a vendor/Nvidia-only extension at the moment. It basically turns fonts into paths using glPathGlyphsNV which depends on the freetype2 library to get the metrics, etc. Then you can also access the kerning info with glGetPathSpacingNV and use NVpr's general path rendering mechanism to display text from using the path-"converted" fonts. (I put that in quotes, because there's no real conversion, the curves are used as is.)

The recorded demo for NVpr's font capabilities is unfortunately not particularly impressive. (Maybe someone should make one along the lines of the much snazzier SDF demo one can find on the intertubes...)

The 2011 NVpr API presentation talk for the fonts part starts here and continues in the next part; it is a bit unfortunate how that presentation is split.

More general materials on NVpr:

  • Nvidia NVpr hub, but some material on the landing page is not the most up-to-date
  • Siggraph 2012 paper for the brains of the path-rendering method, called "stencil, then cover" (StC); the paper also explains briefly how competing tech like Direct2D works. The font-related bits have been relegated to an annex of the paper. There are also some extras like videos/demos.
  • GTC 2014 presentation for an update status; in a nutshell: it's now supported by Google's Skia (Nvidia contributed the code in late 2013 and 2014), which in turn is used in Google Chrome and [independently of Skia, I think] in a beta of Adobe Illustrator CC 2014
  • the official documentation in the OpenGL extension registry
  • USPTO has granted at least four patents to Kilgard/Nvidia in connection with NVpr, of which you should probably be aware of, in case you want to implement StC by yourself: US8698837, US8698808, US8704830 and US8730253. Note that there are something like 17 more USPTO documents connected to this as "also published as", most of which are patent applications, so it's entirely possible more patents may be granted from those.

And since the word "stencil" did not produce any hits on this page before my answer, it appears the subset of the SO community that participated on this page insofar, despite being pretty numerous, was unaware of tessellation-free, stencil-buffer-based methods for path/font rendering in general. Kilgard has a FAQ-like post at on the opengl forum which may illuminate how the tessellation-free path rendering methods differ from bog standard 3D graphics, even though they're still using a [GP]GPU. (NVpr needs a CUDA-capable chip.)

For historical perspective, Kilgard is also the author of the classic "A Simple OpenGL-based API for Texture Mapped Text", SGI, 1997, which should not be confused with the stencil-based NVpr that debuted in 2011.


Most if not all the recent methods discussed on this page, including stencil-based methods like NVpr or SDF-based methods like GLyphy (which I'm not discussing here any further because other answers already cover it) have however one limitation: they are suitable for large text display on conventional (~100 DPI) monitors without jaggies at any level of scaling, and they also look nice, even at small size, on high-DPI, retina-like displays. They don't fully provide what Microsoft's Direct2D+DirectWrite gives you however, namely hinting of small glyphs on mainstream displays. (For a visual survey of hinting in general see this typotheque page for instance. A more in-depth resource is on antigrain.com.)

I'm not aware of any open & productized OpenGL-based stuff that can do what Microsoft can with hinting at the moment. (I admit ignorance to Apple's OS X GL/Quartz internals, because to the best of my knowledge Apple hasn't published how they do GL-based font/path rendering stuff. It seems that OS X, unlike MacOS 9, doesn't do hinting at all, which annoys some people.) Anyway, there is one 2013 research paper that addresses hinting via OpenGL shaders written by INRIA's Nicolas P. Rougier; it is probably worth reading if you need to do hinting from OpenGL. While it may seem that a library like freetype already does all the work when it comes to hinting, that's not actually so for the following reason, which I'm quoting from the paper:

The FreeType library can rasterize a glyph using sub-pixel anti-aliasing in RGB mode. However, this is only half of the problem, since we also want to achieve sub-pixel positioning for accurate placement of the glyphs. Displaying the textured quad at fractional pixel coordinates does not solve the problem, since it only results in texture interpolation at the whole-pixel level. Instead, we want to achieve a precise shift (between 0 and 1) in the subpixel domain. This can be done in a fragment shader [...].

The solution is not exactly trivial, so I'm not going to try to explain it here. (The paper is open-access.)


One other thing I've learned from Rougier's paper (and which Kilgard doesn't seem to have considered) is that the font powers that be (Microsoft+Adobe) have created not one but two kerning specification methods. The old one is based on a so-called kern table and it is supported by freetype. The new one is called GPOS and it is only supported by newer font libraries like HarfBuzz or pango in the free software world. Since NVpr doesn't seem to support either of those libraries, kerning might not work out of the box with NVpr for some new fonts; there are some of those apparently in the wild, according to this forum discussion.

Finally, if you need to do complex text layout (CTL) you seem to be currently out of luck with OpenGL as no OpenGL-based library appears to exist for that. (DirectWrite on the other hand can handle CTL.) There are open-sourced libraries like HarfBuzz which can render CTL, but I don't know how you'd get them to work well (as in using the stencil-based methods) via OpenGL. You'd probably have to write the glue code to extract the re-shaped outlines and feed them into NVpr or SDF-based solutions as paths.

Community
  • 1
  • 1
Fizz
  • 3,927
  • 20
  • 45
  • 4
    I didn't mention NV_path_rendering because it's an extension, a vendor proprietary to make matters worse. I normally try to give answers only for techniques that are universally applicable. – datenwolf Aug 08 '14 at 20:26
  • 1
    Well, I can agree to that to some extent. The method itself ("stencil, then cover") is not actually difficult to implement directly in OpenGL, but it will have high command overhead if done naively that way, as prior stencil-based attempts ended up. Skia [via Ganesh] tried a stencil-based solution at on point, but gave up on it, according to Kilgrad. The way it's implemented by Nvidia, a layer below, using CUDA capabilities, makes it perform. You could try to "Mantle" StC yourself using a whole bunch of EXT/ARB extensions. But beware that Kilgard/Nvidia have two patent applications on NVpr. – Fizz Aug 09 '14 at 07:40
3

I think your best bet would be to look into cairo graphics with OpenGL backend.

The only problem I had when developing a prototype with 3.3 core was deprecated function usage in OpenGL backend. It was 1-2 years ago so situation might have improved...

Anyway, I hope in the future desktop opengl graphics drivers will implement OpenVG.

Orhun
  • 324
  • 2
  • 6