Friday, April 9, 2010

Distance Field Based Rendering of AngelCode Fonts

This morning, we added support for distance field based font rendering to the BitSquid engine (from Valve's paper http://www.valvesoftware.com/publications/2007/SIGGRAPH2007_AlphaTestedMagnification.pdf). An example is shown below:


The top row shows the original font, below that is the original font rendered with alpha test. The third row is a distance field representation of the font and the final row shows the distance field representation rendered with alpha test. Note that the distance field version gives better quality in the diagonal lines.

(Note: The last row looks thicker than the second row, because it was generated from a large font size and scaled down, while the second row was generated from a small font size. Because of true type font hinting at small sizes, the result is different. The last row gives a truer representation of the "actual" thickness of the font.)

A quick Google search didn't show any good tools for generating distance field font maps, so I decided to write my own. We use the excellent AngelCode Bitmap Font Generator (http://www.angelcode.com/products/bmfont/) to generate our font maps, so I decided to make a tool that works with the files generated by AngelCode:


The tool takes a high resolution AngelCode .fnt file as input. It scales it down by the specified scale factor and converts it to a distance field. The spread specifies how many pixels the distance field should extend outside the character outline before it clamps to zero. (It is useful if you want to add things such as glow effects to the font rendering.) After the conversion, the tool outputs new scaled down .tga images of the fonts and a new .fnt file with all measurements converted to work with the scaled down textures.

So to use it, you first generate a font bitmap and .fnt file using AngelCode at 8 x the font size and 8 x the texture size you want in the final image. (Make sure to add 8 x spread pixels of padding around the characters or else the distance fields will bleed into each other.) Then you run the tool to convert it to a distance field texture.

The tool is a bit limited -- it only works with monochrome uncompressed .tga files. It only reads and writes the XML version of the AngelCode font format. The distance field generation isn't particularly clever or fast. But I thought I should share it anyway since I couldn't find any other tools for generating distance field based font maps. Modifying it to support more formats shouldn't be much work.

Grab a binary version here:


Or the C# project files here:


Feel free to do whatever you want with it!

50 comments:

  1. Here's some other source/papers/exe you might want to check on the font/AA images topic, it might interest you:
    http://contourtextures.wikidot.com/
    http://www.ogre3d.org/forums/viewtopic.php?f=1&t=50844

    ReplyDelete
  2. Thank you. The anti-aliased version is interesting. One drawback with the method I'm using here is that you loose true type font hinting when you scale up/scale down. As a result, some of the finer details in the font can get lost (like in the upper part of the r in the example above) because the sample points where we measure the distance do not get optimally placed to capture the features of the font. (At least I think that is what is happening.)

    Using the AA method on a correctly sized font texture (i.e. not an upscaled one) might give a better result since it respects hinting. Would be worth trying.

    ReplyDelete
  3. Hi Niklas, very nice !
    I was researching those techniques for some new effects and ended on your page, what a coincidence.
    We used a similar technique in God of War 3 for our font rendering. It's a nice way to avoid baking the texts in textures while maintaining a good quality.

    ReplyDelete
  4. Hi Cedric!

    What a coincidence indeed! The game engine world sometimes seems a lot smaller than you would think.

    ReplyDelete
  5. Hi Niklas,

    In you app you generate a fnt file that has width and height values with decimal values. Am I right to assume that you use the rounded values of these? Does the error inserted by this is noticeable?

    Thanks for this great tool :),
    Jorge

    ReplyDelete
  6. No, I actually use the decimal values.

    ReplyDelete
  7. Have you tried this with more complex signs like a hanzi/kanji? I can imagine you won’t be able to scale it down that much without losing important information.

    In a system supporting Chinese typing you would probably need about 2x 1024x32 textures to get a reasonable amount of details (and using any form of texture compression for the GPU is probably unthinkable). I fear that our alphabet is only a fraction of the required memory, and probably among the few signs that can greatly benefit from this technique? It would though be interesting to hear if you have done any experimentation with this.

    We are currently using 2x 1024x32 textures for supporting the full Unicode char set, and Chinese seam to by far be the biggest char set with in it. It works okay, but I am considering starting rasterizing whole paragraphs in software and save to temporary textures. Because just thinking about adding support for large fonts for HUD and headers hurts... would probably require at least double that memory even if the distance field method works reasonably for hanzi.

    Do you have any thoughts on the matter? I can guess software rasterizing and the extra memory associated with that would have a whole other impact on console than on PC. And I have yet to get any real experience with programming larger projects for a console.
    (You can always try to scale down this one; 簣)

    ReplyDelete
  8. No I haven't experimented that much with complex characters. But you need a certain minimum resolution for this to work. If your resolution is so low that the basic strokes of the characters "blur together", then the distance field approach can't "unblur" them. But as long as that doesn't happen you should be fine.

    A scaled up distance field font will never look as good as the "real font" rendered at a bigger font size though. (Just better than a scaled up bitmap font.) For maximum quality that is the way to go. Juggling all those temporary textures is annoying though.

    ReplyDelete
  9. Hi, I wanted to use this tool, but it isn't working for me. It is generating all-white tga files. Have you run into that problem before? I want a 36 pixel font ultimately, so I generated a 288-pixel angelcode font. I put 64 pixels of padding on all four sides because I want 8 pixels of spread. I used the xml fnt format, and get no errors. Any idea what I might be doing wrong?

    Also I am wondering why you need to generate so large a font initially? The original distance field article just used a bitmap the same size as the resulting distance field image, didn't it? It's no big deal since the BMFont output is temporary but I was just wondering.

    Thanks for any assistance!
    Bob

    ReplyDelete
  10. Hi Bob. No I haven't seen that error.

    I use big textures just to get better values for the distance field. (Since I estimate the distance to the glyph curve by counting pixels.)

    ReplyDelete
  11. Oh that is funny -- the files are fine, actually. They just show up as all white when you view them in Quicktime Picture Viewer. That's the only program on my Windows 7 machine apparently that can show .tif files. What do you use? I'm installing Gimp but that's a heavy program just to look at TIFs.

    Thanks
    Bob

    ReplyDelete
  12. BMFont doesn't seem to be able to generate 600px size fonts exported to 2048x2048 textures. I guess that's too large?

    I tried converting to distance field using the same scale -- I put '1' into the Scale Down By box, is that right or should it be 0?

    The fonts aren't rendering yet but displaying them with the old shader shows the new font to be smaller, and more closely packed together, than the original. Shouldn't it be exactly the same if the scale is the same? In fact shouldn't I be able to use the original .fnt file in that case? Or does the converter change things about the glyphs?

    Thanks
    Bob

    ReplyDelete
  13. Hello again,

    I made some modifications to your tool that might be of use to other people working with distance field fonts.

    The giant fonts exported from BMFont for use in your tool will usually consist of several pages of texture map images, especially if you are making the entire alphabet. But once they are shrunken down into DF fonts, there's no need for them to be spread across several images. It's more convenient if the smaller DF letterforms are placed on a single texture map.

    I modified your code to do this -- for example, a font exported at 480 x 480 pixels per character takes four 2048x2048 texture maps. Shrinking down by a factor of 8, the distance field font fits on a single 1024x256 map.

    I haven't tested it beyond what I needed for my single application, and I am not a C# programmer -- so there could be some bugs in there. But it worked for me. Here's the executable and source code for the modified version if anyone wants to try it:

    http://www.flatblackfilms.com/distance_field_exe.zip
    http://www.flatblackfilms.com/distance_field_source.zip


    Thanks,
    Bob

    ReplyDelete
  14. Replies
    1. The original links appear to be down, but you can try the links I posted in the comment just above yours -- I made a slight modification which you can read about.

      Delete
  15. Hi there! The smaller font under each word tells the actual name of the font. The "sparkling" one is called Sweet Pea font

    and the link is: http://www.dafont.com/sweet-pea.font
    The clickable links to all of them are right under the image!
    Thanks!

    ReplyDelete
  16. Dafont.com is a site where you can download a ton of free fonts. You can search for a specific typeface, or search by the type of lettering you want, whether it’s serif or sans serif, hand lettered or grunge style. You can also put in your own phrase to see how it looks in a particular font. A lot of these fonts are very decorative and many are handdrawn, so it’s not always the best place to search for body text fonts. Each selection also tells you whether your download is free for personal or commercial use. The download is easy – you get a zip file with the font file inside. Unzip, install, and you’re ready to go.

    ReplyDelete
  17. Office.com/Setup is a set of desktop applications, which is widely used products for the home as well as an office. Microsoft office gives the freedom of writing documents, blogs, letters and with the use of Microsoft office PowerPoint one can prepare a presentation also.
    howtominernewswatt
    Norton.com/Setup
    Office.com/Setup
    Office.com/Setup
    office Setup
    Daily Helps
    office.com/Setup

    ReplyDelete
  18. Office Setup is a software which is used by almost all company and business and even by individuals For all their office activities or for personal use. It has excels, word, and ppt as their constituent are most widely used apps. For any concern and help just visit website for office help and key activation. You can do it by yourself if you know how to install office setup on your PC or Mac or you can call third party companies as well who can do it on your behalf.
    office.com/Setup
    office.com/Setup
    Norton.com/Setup
    office.com/Setup
    office.com/Setup
    office.com/Setup
    Norton.com/Setup

    ReplyDelete
  19. Allassignmenthelp is your academic caretaker. Our online assignment assistance is one of the most sought after in the US and other countries and you should give us a chance to assist you. Write My Assignment

    ReplyDelete
  20. hello everyone. I like writing and posting something new can be a really enjoyable task. By the way, do you know where to buy resume paper? I decided to change my job and I need a well-written essay.

    ReplyDelete
  21. The designing and application of this decorative staff are discussed in terms of the high needs the people wants for decoration depending on whether their required design is graphical, architectural or a product.freelance writer for hire

    ReplyDelete
  22. The assignment help online given by our devoted authors are of premium and high caliber. If you need assignment help Australia, get in touch with ABC Assignment Help. The assignments prepared by our dedicated writers are of premium and high quality. Avail the assignment help and get the desired results even at the last moment.

    ReplyDelete
  23. Take Assignment help Ireland services to finish your work without any stress. If you have no one to ask your queries, use Assignment help services and get experts’ guidance for your concerns.
    Assignment help Saudi Arabia
    assignment help Hong Kong
    assignment help Kuwait
    assignment help United Arab Emirates

    ReplyDelete

  24. 'I'm highly impressed by the piece of thoughts you have shared on this portal. all the best
    connect us on Assignment Help can shed your burden of assignments with a return of qualitative assignments.
    Online Assignment Help
    Programming Assignment Help
    Management Assignment Help
    My Assignment Help

    ReplyDelete
  25. I totally agree with the opinion that response paper is challenging task for students. They have not enough skills for this. I want to buy a response paper online because I also need some bits of advice.

    ReplyDelete
  26. Use Assignment Help to connect with Australian academic writers in just a few minutes. Students can take online assignment writing services in Australia when they have no one to ask their queries and find it tough to write your academic papers.
    My Assignment Help
    Assignment Help Online
    Online Assignment Help

    ReplyDelete
  27. En este momento de la digitalización, la técnica habitual para hacer pagos a través del dinero ha envejecido. Sustituya sus viejas técnicas por otras más actuales utilizando las administraciones en línea para pagar directamente a través de sus saldos financieros. Lo valioso de la administración de cuotas versátil que utiliza un pequeño mensaje, que se ha desarrollado obviamente patria desde que surgieron los problemas de ingresos, es que no necesita obtener un teléfono celular, es suficiente tener lo que ellos llaman un "responsable". Los clientes deben seleccionar en la fase de estos bancos, de los cuales indicarán la cantidad y la cantidad de intercambios habilitados siguiendo los parámetros, para utilizar la instalación por SMS. Las personas que utilizan saldos en el Banco de Venezuela banco de venezuela En Linea obtienen y harán compromisos interbancarios. Como un enfoque para obtener ganancias por la función, es urgente estar asociado con el BDV En Linea, en el cual debe iniciar la entrega esencial. Para las personas que tienen un registro gratuito en el banco del tesoro En Linea, puede crear la instalación de SMS de hasta 1,000,000 de bolívares de manera consistente, para eso debe consolidar la función en la instalación telefónica de Tesoro en Tesoro en la web y enviar, retirar la separación bnc , un correo electrónico al 2383 con toda la palabra Pagar, y los principales ejemplos de las cuentas bancarias de objetivos, el número de teléfono del destinatario, el tipo de cliente (V, Correo electrónico o J), el número de tarjeta de personalidad del beneficiario, el número fue con una coma y además dos decimales y código por la tarjeta de clasificación que se elegirá. Banco Bicentenario Debe inscribirse a través de su aplicación banco bicentenario En Linea Payment para explotar el servicio. En ese momento, pagará enviando un SMS al número 7077 juntos utilizando todo el términoEl código QR del video modificado se puede utilizar para descargar videos en su teléfono inteligente. Este convertidor mp3 en línea gratuito permite cambiar sus grabaciones de YouTube a MP3, MP4, MP4 HD, AVI y AVI HD. La interfaz es básica donde simplemente necesita pegar la URL del video y elegir el diseño de rendimiento. El registro modificado se hará accesible en la interfaz para descargar. También está disponible un módulo de programa gratuito para descargar videos. Con este programa en línea, sus grabaciones de YouTube se De hecho, mis abuelos tenían correo electrónico ... durante los años 90.Inevitablemente, el custodio estaba harto de observar involuntariamente que mi correo electrónico llegara al registro de la escuela. Por fin me arrinconó y dijo: "¿Has intentado hotmail ?" Entonces lo miré. Además, en ese primer año, fui un individuo sancionador por el trastorno de correo electrónico gratuito basado en la web. whatsapp web needs no presentation. It is all around the most well known texting application and has the most number of clients., GIFs, recordings, reports, this element bodes well. It tends to be exceptionally dull to return and quest for recently shared media, consequently another propelled search include. whatsapp web beta

    ReplyDelete
  28. Today, more and more students are going after assignment writing services so as to get assignment writing help and to escape from their writing troubles. Obviously, assignment writing services can help the students to get away from the tensions, strain and worries of writing assignments. Most of the students will be worried and stressed when they get assignments to be written on varied topics and it is definitely a matter of concern because not every assignment service provider has qualified experts and a team that specialises in that particular subject.
    top assignment help australia
    top assignment writing website
    best assignment writing help australia
    best online assignment writing help
    best assignment writing help

    ReplyDelete
  29. Get best biology assignment help from ABC assignment help, which is a one-stop solution for all your academic worries or related problems. Our experts help students to achieve their desired result and triumph in career. Contact us now to hire best team for your work.

    ReplyDelete
  30. Kunjungi situs panduan CARA BERMAIN LIVE GAME IDN yang baik dan benar di situs ini,kalian akan mengetahui tata cara bermain yang dianjurkan agar meraih keuntungan yang banyak di live game IDN. kalian bisa melihat panduan cara bermain game
    - ROULETTE
    - 12D
    - 24D
    - 24Dspin
    - 3D Shio
    - 5D Ball
    - Baccarat
    - Billiards
    - Dice 6
    - Dragon Tiger
    - Fantan
    - Gong Ball
    - Head Tail
    - Monopoly
    - Race Ball
    - Sicbo[Dice]


    Semua bisa kalian pelajari di Cara Bermain Live Game IDN LIVE

    ReplyDelete
  31. Holmes institute has implemented Holmes Blackboard
     in order to impart all educational resources for its students. Holmes blackboard acts as virtual blackboard and contain all required information for the students. Blackboard holmes login can be found on college site and can be used through login and password provided by the college. Blackboard holmes is one of the most advanced e-learning system offered by colleges in Australia. Students make holmes blackboard login so as to take out all assignment information and study class slides. Holmes Institute blackboard contain all information on course such as unit outline, assignment details and marking criteria etc. Holmes college blackboard is also used by the students to make their submission of assignment as well. Holmes blackboard is quite similar to the RMIT blackboard or Swinburne blackboard provided in their college for information access. Holmes Blackboard sydney has been recently updated to include some of the latest features wherein blackboard ultra has been launched which allow faster access to users.

    blackboard holmes login
    Holmes blackboard
    blackboard holmes
    holmes blackboard login

    ReplyDelete
  32. My Assignment help is the most preferred place to get assignment help Australia services where we offer 100% plagiarism free and money back guarantee ensuring complete satisfaction of students with every order. Our subject-specific experts are available 24x7 to provide properly formatted and referenced solutions in any subject from any level in Australian universities.

    ReplyDelete
  33. You had me engaged by reading and you know what? I want to read more about that. That's what's used as an amusing post. At My Assignment Help Au, We Offer Pocket-Friendly Services And Write Tailored Assignments. Students Trust Our Assignment Help in Australia. To Get Authentic Assignments Within Deadlines, Hire Us Today!

    ReplyDelete
  34. The techniques that are implemented by the business organisations for promoting
    and selling their products and services are referred to as marketing. The marketing
    mix for any organisation comprises of four elements namely product, price,
    promotion and place.
    marketing assignment help
    marketing management assignment help
    Marketing assignment writing help

    ReplyDelete
  35. If you want to watch free TV shows and movies using streaming websites then there is no alternative as compared to putlocker. Also, we made a list of alternatives like Putlocker sites that you can use to stream movies and TV shows.

    Here is the official Putlocker website with a lot of trending and popular movies to watch.

    Hosting companies and law enforcement are always taking down free streaming sites, including long-time favorite Putlockers. So what are you supposed to do when your usual top pick for free streaming isn’t working anymore?

    Don’t put away that popcorn just yet! I tested 47 leading streaming sites for safety, usability, and speed. After careful review and ranking based on streaming catalog size, content, and quality, I’ve found offical proxy site of Putlockers.

    ReplyDelete
  36. *******
    MODAL TERJANGKAU, HASIL MEMUKAU ! Solusi Tepat Untuk Permainan Kartu Anda Dengan Tingkat Kemenangan DI UTAMAKAN ! Hanya di Situs
    Link Alternatif SITUS BOLA RESMI SBOBETyang bisa temanin ke bosanan kalian, karna dari diri kita sendiri yg bisa mencegah penyakit yg lagi heboh itu,semoga kita semua dilindungiNYA.

    ReplyDelete
  37. Great website! To watch free movies online you can use this website! All movies updated with subtitles, no sign up required. Just search and play the movie online in HD. The one and only free movies website online: official site xmovies8

    ReplyDelete
  38. Our business law essay assignment help team is one of our best academic writing teams. Our team members at business law essay assignment help services are expert in this area and have immense practical knowledge. We present Business Law term paper help and Business Law thesis help if you search Business Law courseworkAustralia. Leaving aside law, we even cater to nursing, management, programming and engineering.
    Business Law Assignment Help
    Business Law assignment
    Business Law help
    Business Law Homework
    Business Law term paper
    Business Law thesis
    Business Law coursework

    ReplyDelete
  39. Behavioral Assignment Help

    https://www.myassignmenthelp.net/behavioral-geography-assignment-help

    I've ordered assignments on my assignment help a few times. And always I got the best scores in my college. That is why I was able to pass my exams.
    Thanks

    ReplyDelete
  40. This is the way our writers convey unrivaled Company Law assignment writers They work in a bit by bit procedure to give you a flawlessly composed paper. They additionally realize that every one of these components, at last, add to your straight in class. They take advantage of each lucky break to serve you with the absolute best.
    Company Law Essay Assignment
    Company Law assignment help
    Company Law coursework help
    Company Law dissertation
    Company research paper
    Company Law assignment writers

    ReplyDelete
  41. In October 2018, the MPAA's report on Online Notorious Markets to the United States Trade Representative, said that the conclusion of 123movies, 123movieshub, gostream, and gomovies, by walking of a criminal examination in Vietnam in 2018, was "a significant turn of events" in combating illicit film theft administrations. In any case, the MPAA report additionally noticed that various copycat locales had risen in any event in eight different nations. In November 2018 TorrentFreak revealed locales associated or like 123Movies, for example, WatchAsap had additionally been closed somewhere around the FBI, yet were re-coordinating to other document sharing destinations.

    ReplyDelete
  42. I did everything right but the fonts are not connected. If you make a detailed video of this whole affair, not only me but many other people who are having trouble connecting to the font will all be grateful to you. Buy Essay Online UK

    ReplyDelete
  43. IndoxxiMovie adalah salah satu situs film lama yang paling populer di daftar ini. Film tersedia dalam 1080p dan streaming dengan sedikit atau tanpa iklan atau pop-up.

    Beranda situs ini sangat sederhana dengan hanya bilah pencarian dan opsi Kategori yang terdaftar. Setelah Anda memilih film, Anda mungkin perlu mengklik tombol putar lebih dari sekali untuk memulai, tetapi ini tidak selalu terjadi.

    Lihat panduan kami di bawah ini untuk cara menggunakan IndoxxiMovie dengan aman di semua perangkat streaming populer.
    Indoxxi

    ReplyDelete
  44. I ejoyed surfing your blog, our post is very great.I read this post. It's very helpful. I will definitely go ahead and take advantage of this. plus This article is mind rich, continue uploading us such content
    hvac SEO
    .

    ReplyDelete
  45. We help you to stay at the top of the class with assignment writing help. The reason we have been the go to place for dissertation help is our pool of finest writing experts for all academic assignments. Our assignment assistance has great writing skills and runs a comprehensive assignment check to provide you with a custom online assignment. Our writers are best academic experts.
    Assignment writing help
    Dissertation help
    Assignment assistance

    ReplyDelete