View Javadoc
1   
2   package org.newdawn.slick;
3   
4   import java.awt.Font;
5   import java.awt.FontFormatException;
6   import java.awt.FontMetrics;
7   import java.awt.Rectangle;
8   import java.awt.font.GlyphVector;
9   import java.awt.font.TextAttribute;
10  import java.io.IOException;
11  import java.lang.reflect.Field;
12  import java.util.ArrayList;
13  import java.util.Collections;
14  import java.util.Comparator;
15  import java.util.Iterator;
16  import java.util.LinkedHashMap;
17  import java.util.List;
18  import java.util.Map;
19  import java.util.Map.Entry;
20  
21  import org.newdawn.slick.font.Glyph;
22  import org.newdawn.slick.font.GlyphPage;
23  import org.newdawn.slick.font.HieroSettings;
24  import org.newdawn.slick.font.effects.Effect;
25  import org.newdawn.slick.opengl.Texture;
26  import org.newdawn.slick.opengl.TextureImpl;
27  import org.newdawn.slick.opengl.renderer.Renderer;
28  import org.newdawn.slick.opengl.renderer.SGL;
29  import org.newdawn.slick.util.ResourceLoader;
30  
31  import javax.annotation.Nonnull;
32  import javax.annotation.Nullable;
33  
34  /**
35   * A Slick bitmap font that can display unicode glyphs from a TrueTypeFont.
36   * 
37   * For efficiency, glyphs are packed on to textures. Glyphs can be loaded to the textures on the fly, when they are first needed
38   * for display. However, it is best to load the glyphs that are known to be needed at startup.
39   * @author Nathan Sweet <misc@n4te.com>
40   */
41  public class UnicodeFont implements org.newdawn.slick.Font {
42      /** The number of display lists that will be cached for strings from this font */
43      private static final int DISPLAY_LIST_CACHE_SIZE = 200;
44      /** The highest glyph code allowed */
45      static private final int MAX_GLYPH_CODE = 0x10FFFF;
46      /** The number of glyphs on a page */
47      private static final int PAGE_SIZE = 512;
48      /** The number of pages */
49      private static final int PAGES = MAX_GLYPH_CODE / PAGE_SIZE;
50      /** Interface to OpenGL */
51      private static final SGL GL = Renderer.get();
52      /** A dummy display list used as a place holder */
53      private static final DisplayList EMPTY_DISPLAY_LIST = new DisplayList();
54  
55      /**
56       * Utility to create a Java font for a TTF file reference
57       *
58       * @param ttfFileRef The file system or classpath location of the TrueTypeFont file.
59       * @return The font created
60       * @throws SlickException Indicates a failure to locate or load the font into Java's font
61       * system.
62       */
63      private static Font createFont (String ttfFileRef) throws SlickException {
64          try {
65              return Font.createFont(Font.TRUETYPE_FONT, ResourceLoader.getResourceAsStream(ttfFileRef));
66          } catch (FontFormatException ex) {
67              throw new SlickException("Invalid font: " + ttfFileRef, ex);
68          } catch (IOException ex) {
69              throw new SlickException("Error reading font: " + ttfFileRef, ex);
70          }
71      }
72  
73      /**
74       * Sorts glyphs by height, tallest first.
75       */
76      private static final Comparator<Glyph> heightComparator = (o1, o2) -> o1.getHeight() - o2.getHeight();
77  
78      /** The AWT font that is being rendered */
79      private Font font;
80      /** The reference to the True Type Font file that has kerning information */
81      private String ttfFileRef;
82      /** The ascent of the font */
83      private int ascent;
84      /** The decent of the font */
85      private int descent;
86      /** The leading edge of the font */
87      private int leading;
88      /** The width of a space for the font */
89      private int spaceWidth;
90      /** The glyphs that are available in this font */
91      private final Glyph[][] glyphs = new Glyph[PAGES][];
92      /** The pages that have been loaded for this font */
93      private final List<GlyphPage> glyphPages = new ArrayList<>();
94      /** The glyphs queued up to be rendered */
95      private final List<Glyph> queuedGlyphs = new ArrayList<>(256);
96      /** The effects that need to be applied to the font */
97      private final List<Effect> effects = new ArrayList<>();
98  
99      /** The padding applied in pixels to the top of the glyph rendered area */
100     private int paddingTop;
101     /** The padding applied in pixels to the left of the glyph rendered area */
102     private int paddingLeft;
103     /** The padding applied in pixels to the bottom of the glyph rendered area */
104     private int paddingBottom;
105     /** The padding applied in pixels to the right of the glyph rendered area */
106     private int paddingRight;
107     /** The padding applied in pixels to horizontal advance for each glyph */
108     private int paddingAdvanceX;
109     /** The padding applied in pixels to vertical advance for each glyph */
110     private int paddingAdvanceY;
111     /** The glyph to display for missing glyphs in code points */
112     @Nullable
113     private Glyph missingGlyph;
114 
115     /** The width of the glyph page generated */
116     private int glyphPageWidth = 512;
117     /** The height of the glyph page generated */
118     private int glyphPageHeight = 512;
119 
120     /** True if display list caching is turned on */
121     private boolean displayListCaching = true;
122     /** The based display list ID */
123     private int baseDisplayListID = -1;
124     /** The ID of the display list that has been around the longest time */
125     private int eldestDisplayListID;
126     /** The map fo the display list generated and cached - modified to allow removal of the oldest entry */
127     @Nullable
128     private final Map<CharSequence, DisplayList> displayLists = new LinkedHashMap<CharSequence, DisplayList>(DISPLAY_LIST_CACHE_SIZE, 1, true) {
129         /**
130          * 
131          */
132         private static final long serialVersionUID = 1L;
133 
134         protected boolean removeEldestEntry (@Nonnull Entry<CharSequence, DisplayList> eldest) {
135             DisplayList displayList = eldest.getValue();
136             if (displayList != null) eldestDisplayListID = displayList.id;
137             return size() > DISPLAY_LIST_CACHE_SIZE;
138         }
139     };
140 
141     /**
142      * Create a new unicode font based on a TTF file
143      *
144      * @param ttfFileRef The file system or classpath location of the TrueTypeFont file.
145      * @param hieroFileRef The file system or classpath location of the Hiero settings file.
146      * @throws SlickException if the UnicodeFont could not be initialized.
147      */
148     public UnicodeFont (String ttfFileRef, String hieroFileRef) throws SlickException {
149         this(ttfFileRef, new HieroSettings(hieroFileRef));
150     }
151 
152     /**
153      * Create a new unicode font based on a TTF file and a set of heiro configuration
154      *
155      * @param ttfFileRef The file system or classpath location of the TrueTypeFont file.
156      * @param settings The settings configured via the Hiero tool
157      * @throws SlickException if the UnicodeFont could not be initialized.
158      */
159     private UnicodeFont(String ttfFileRef, @Nonnull HieroSettings settings) throws SlickException {
160         this.ttfFileRef = ttfFileRef;
161         Font font = createFont(ttfFileRef);
162         initializeFont(font, settings.getFontSize(), settings.isBold(), settings.isItalic());
163         loadSettings(settings);
164     }
165 
166     /**
167      * Create a new unicode font based on a TTF file alone
168      *
169      * @param ttfFileRef The file system or classpath location of the TrueTypeFont file.
170      * @param size The point size of the font to generated
171      * @param bold True if the font should be rendered in bold typeface
172      * @param italic True if the font should be rendered in bold typeface
173      * @throws SlickException if the UnicodeFont could not be initialized.
174      */
175     public UnicodeFont (String ttfFileRef, int size, boolean bold, boolean italic) throws SlickException {
176         this.ttfFileRef = ttfFileRef;
177         initializeFont(createFont(ttfFileRef), size, bold, italic);
178     }
179 
180     /**
181      * Creates a new UnicodeFont.
182      *
183      * @param font The AWT font to render
184      * @param hieroFileRef The file system or classpath location of the Hiero settings file.
185      * @throws SlickException if the UnicodeFont could not be initialized.
186      */
187     public UnicodeFont (@Nonnull Font font, String hieroFileRef) throws SlickException {
188         this(font, new HieroSettings(hieroFileRef));
189     }
190 
191     /**
192      * Creates a new UnicodeFont.
193      *
194      * @param font The AWT font to render
195      * @param settings The settings configured via the Hiero tool
196      */
197     private UnicodeFont(@Nonnull Font font, @Nonnull HieroSettings settings) {
198         initializeFont(font, settings.getFontSize(), settings.isBold(), settings.isItalic());
199         loadSettings(settings);
200     }
201 
202     /**
203      * Creates a new UnicodeFont.
204      *
205      * @param font The AWT font to render
206      */
207     public UnicodeFont (@Nonnull Font font) {
208         initializeFont(font, font.getSize(), font.isBold(), font.isItalic());
209     }
210 
211     /**
212      * Creates a new UnicodeFont.
213      *
214      * @param font The AWT font to render
215      * @param size The point size of the font to generated
216      * @param bold True if the font should be rendered in bold typeface
217      * @param italic True if the font should be rendered in bold typeface
218      */
219     public UnicodeFont (@Nonnull Font font, int size, boolean bold, boolean italic) {
220         initializeFont(font, size, bold, italic);
221     }
222 
223     /**
224      * Initialise the font to be used based on configuration
225      *
226      * @param baseFont The AWT font to render
227      * @param size The point size of the font to generated
228      * @param bold True if the font should be rendered in bold typeface
229      * @param italic True if the font should be rendered in bold typeface
230      */
231     @SuppressWarnings({"unchecked","rawtypes"})
232     private void initializeFont(@Nonnull Font baseFont, int size, boolean bold, boolean italic) {
233         Map attributes = baseFont.getAttributes();
234         attributes.put(TextAttribute.SIZE, (float) size);
235         attributes.put(TextAttribute.WEIGHT, bold ? TextAttribute.WEIGHT_BOLD : TextAttribute.WEIGHT_REGULAR);
236         attributes.put(TextAttribute.POSTURE, italic ? TextAttribute.POSTURE_OBLIQUE : TextAttribute.POSTURE_REGULAR);
237         try {
238             attributes.put(TextAttribute.class.getDeclaredField("KERNING").get(null), TextAttribute.class.getDeclaredField(
239                 "KERNING_ON").get(null));
240         } catch (Exception ignored) {
241         }
242         font = baseFont.deriveFont(attributes);
243 
244         FontMetrics metrics = GlyphPage.getScratchGraphics().getFontMetrics(font);
245 
246         ascent = metrics.getAscent();
247         descent = metrics.getDescent();
248         leading = metrics.getLeading();
249 
250         // Determine width of space glyph (getGlyphPixelBounds gives a width of zero).
251         char[] chars = " ".toCharArray();
252         GlyphVector vector = font.layoutGlyphVector(GlyphPage.renderContext, chars, 0, chars.length, Font.LAYOUT_LEFT_TO_RIGHT);
253         spaceWidth = vector.getGlyphLogicalBounds(0).getBounds().width;
254     }
255 
256     /**
257      * Load the hiero setting and configure the unicode font's rendering
258      *
259      * @param settings The settings to be applied
260      */
261     private void loadSettings(@Nonnull HieroSettings settings) {
262         paddingTop = settings.getPaddingTop();
263         paddingLeft = settings.getPaddingLeft();
264         paddingBottom = settings.getPaddingBottom();
265         paddingRight = settings.getPaddingRight();
266         paddingAdvanceX = settings.getPaddingAdvanceX();
267         paddingAdvanceY = settings.getPaddingAdvanceY();
268         glyphPageWidth = settings.getGlyphPageWidth();
269         glyphPageHeight = settings.getGlyphPageHeight();
270         effects.addAll(settings.getEffects());
271     }
272 
273     /**
274      * Queues the glyphs in the specified codepoint range (inclusive) to be loaded. Note that the glyphs are not actually loaded
275      * until {@link #loadGlyphs()} is called.
276      *
277      * Some characters like combining marks and non-spacing marks can only be rendered with the context of other glyphs. In this
278      * case, use {@link #addGlyphs(String)}.
279      *
280      * @param startCodePoint The code point of the first glyph to add
281      * @param endCodePoint The code point of the last glyph to add
282      */
283     void addGlyphs(int startCodePoint, int endCodePoint) {
284         for (int codePoint = startCodePoint; codePoint <= endCodePoint; codePoint++)
285             addGlyphs(new String(Character.toChars(codePoint)));
286     }
287 
288     /**
289      * Queues the glyphs in the specified text to be loaded. Note that the glyphs are not actually loaded until
290      * {@link #loadGlyphs()} is called.
291      *
292      * @param text The text containing the glyphs to be added
293      */
294     void addGlyphs(@Nullable String text) {
295         if (text == null) throw new IllegalArgumentException("text cannot be null.");
296 
297         char[] chars = text.toCharArray();
298         GlyphVector vector = font.layoutGlyphVector(GlyphPage.renderContext, chars, 0, chars.length, Font.LAYOUT_LEFT_TO_RIGHT);
299         for (int i = 0, n = vector.getNumGlyphs(); i < n; i++) {
300             int codePoint = text.codePointAt(vector.getGlyphCharIndex(i));
301             Rectangle bounds = getGlyphBounds(vector, i, codePoint);
302             getGlyph(vector.getGlyphCode(i), codePoint, bounds, vector, i);
303         }
304     }
305 
306     /**
307      * Queues the glyphs in the ASCII character set (codepoints 32 through 127) to be loaded. Note that the glyphs are not actually
308      * loaded until {@link #loadGlyphs()} is called.
309      */
310     public void addAsciiGlyphs () {
311         addGlyphs(32, 127);
312     }
313 
314     /**
315      * Queues the glyphs in the NEHE character set (codepoints 32 through 128) to be loaded. Note that the glyphs are not actually
316      * loaded until {@link #loadGlyphs()} is called.
317      *
318      * @deprecated Use addAsciiGlyphs() (codepoints 32-127) or addGlyphs(int, int) for something more specific
319      */
320     @Deprecated
321     public void addNeheGlyphs () {
322         addGlyphs(32, 32 + 96);
323     }
324 
325     /**
326      * Loads all queued glyphs to the backing textures. Glyphs that are typically displayed together should be added and loaded at
327      * the same time so that they are stored on the same backing texture. This reduces the number of backing texture binds required
328      * to draw glyphs.
329      *
330      * @return True if the glyphs were loaded entirely
331      * @throws SlickException if the glyphs could not be loaded.
332      */
333     public boolean loadGlyphs () {
334         return loadGlyphs(-1);
335     }
336 
337     /**
338      * Loads up to the specified number of queued glyphs to the backing textures. This is typically called from the game loop to
339      * load glyphs on the fly that were requested for display but have not yet been loaded.
340      *
341      * @param maxGlyphsToLoad The maximum number of glyphs to be loaded this time
342      * @return True if the glyphs were loaded entirely
343      * @throws SlickException if the glyphs could not be loaded.
344      */
345     boolean loadGlyphs(int maxGlyphsToLoad) {
346         if (queuedGlyphs.isEmpty()) return false;
347 
348         if (effects.isEmpty())
349             throw new IllegalStateException("The UnicodeFont must have at least one effect before any glyphs can be loaded.");
350 
351         for (Iterator<Glyph> iter = queuedGlyphs.iterator(); iter.hasNext();) {
352             Glyph glyph = iter.next();
353             int codePoint = glyph.getCodePoint();
354 
355             // Don't load an image for a glyph with nothing to display.
356             if (glyph.getWidth() == 0 || codePoint == ' ') {
357                 iter.remove();
358                 continue;
359             }
360 
361             // Only load the first missing glyph.
362             if (glyph.isMissing()) {
363                 if (missingGlyph != null) {
364                     if (glyph != missingGlyph) iter.remove();
365                     continue;
366                 }
367                 missingGlyph = glyph;
368             }
369         }
370 
371         Collections.sort(queuedGlyphs, heightComparator);
372 
373         // Add to existing pages.
374         for (GlyphPage glyphPage : glyphPages) {
375             maxGlyphsToLoad -= glyphPage.loadGlyphs(queuedGlyphs, maxGlyphsToLoad);
376             if (maxGlyphsToLoad == 0 || queuedGlyphs.isEmpty())
377                 return true;
378         }
379 
380         // Add to new pages.
381         while (!queuedGlyphs.isEmpty()) {
382             GlyphPage glyphPage = new GlyphPage(this, glyphPageWidth, glyphPageHeight);
383             glyphPages.add(glyphPage);
384             maxGlyphsToLoad -= glyphPage.loadGlyphs(queuedGlyphs, maxGlyphsToLoad);
385             if (maxGlyphsToLoad == 0) return true;
386         }
387         System.out.println("glyphs loaded");
388         return true;
389     }
390 
391     /**
392      * Clears all loaded and queued glyphs.
393      */
394     void clearGlyphs() {
395         for (int i = 0; i < PAGES; i++)
396             glyphs[i] = null;
397 
398         for (GlyphPage page : glyphPages) {
399             page.getImage().destroy();
400         }
401         glyphPages.clear();
402 
403         if (baseDisplayListID != -1) {
404             GL.glDeleteLists(baseDisplayListID, displayLists.size());
405             baseDisplayListID = -1;
406         }
407 
408         queuedGlyphs.clear();
409         missingGlyph = null;
410     }
411 
412     /**
413      * Releases all resources used by this UnicodeFont. This method should be called when this UnicodeFont instance is no longer
414      * needed.
415      */
416     public void destroy () {
417         // The destroy() method is just to provide a consistent API for releasing resources.
418         clearGlyphs();
419     }
420 
421     /**
422      * Identical to {@link #drawString(float, float, CharSequence, Color, int, int)} but returns a
423      * DisplayList which provides access to the width and height of the text drawn.
424      *
425      * @param text The text to render
426      * @param x The horizontal location to render at
427      * @param y The vertical location to render at
428      * @param color The colour to apply as a filter on the text
429      * @param startIndex The start index into the string to start rendering at
430      * @param endIndex The end index into the string to render to
431      * @return The reference to the display list that was drawn and potentiall ygenerated
432      */
433     @Nullable
434     DisplayList drawDisplayList(float x, float y, @Nullable CharSequence text, @Nullable Color color, int startIndex, int endIndex) {
435         if (text == null) throw new IllegalArgumentException("text cannot be null.");
436         if (text.length() == 0) return EMPTY_DISPLAY_LIST;
437         if (color == null) throw new IllegalArgumentException("color cannot be null.");
438 
439         x -= paddingLeft;
440         y -= paddingTop;
441 
442         CharSequence displayListKey = text.subSequence(startIndex, endIndex);
443 
444         color.bind();
445         TextureImpl.bindNone();
446 
447         DisplayList displayList = null;
448         if (displayListCaching && queuedGlyphs.isEmpty()) {
449             if (baseDisplayListID == -1) {
450                 baseDisplayListID = GL.glGenLists(DISPLAY_LIST_CACHE_SIZE);
451                 if (baseDisplayListID == 0) {
452                     baseDisplayListID = -1;
453                     displayListCaching = false;
454                     return new DisplayList();
455                 }
456             }
457             // Try to use a display list compiled for this text.
458             displayList = displayLists.get(displayListKey);
459             if (displayList != null) {
460                 if (displayList.invalid)
461                     displayList.invalid = false;
462                 else {
463                     GL.glTranslatef(x, y, 0);
464                     GL.glCallList(displayList.id);
465                     GL.glTranslatef(-x, -y, 0);
466                     return displayList;
467                 }
468             } else if (displayList == null) {
469                 // Compile a new display list.
470                 displayList = new DisplayList();
471                 int displayListCount = displayLists.size();
472                 displayLists.put(displayListKey, displayList);
473                 if (displayListCount < DISPLAY_LIST_CACHE_SIZE)
474                     displayList.id = baseDisplayListID + displayListCount;
475                 else
476                     displayList.id = eldestDisplayListID;
477             }
478             displayLists.put(displayListKey, displayList);
479         }
480 
481         GL.glTranslatef(x, y, 0);
482 
483         if (displayList != null) GL.glNewList(displayList.id, SGL.GL_COMPILE_AND_EXECUTE);
484 
485         char[] chars = toCharArray(text, 0, endIndex);
486         GlyphVector vector = font.layoutGlyphVector(GlyphPage.renderContext, chars, 0, chars.length, Font.LAYOUT_LEFT_TO_RIGHT);
487 
488         int maxWidth = 0, totalHeight = 0, lines = 0;
489         int extraX = 0, extraY = ascent;
490         boolean startNewLine = false;
491         Texture lastBind = null;
492         for (int glyphIndex = 0, n = vector.getNumGlyphs(); glyphIndex < n; glyphIndex++) {
493             int charIndex = vector.getGlyphCharIndex(glyphIndex);
494             if (charIndex < startIndex) continue;
495             if (charIndex > endIndex) break;
496 
497             int codePoint = Character.codePointAt(text, charIndex);
498 
499             Rectangle bounds = getGlyphBounds(vector, glyphIndex, codePoint);
500             Glyph glyph = getGlyph(vector.getGlyphCode(glyphIndex), codePoint, bounds, vector, glyphIndex);
501 
502             if (startNewLine && codePoint != '\n') {
503                 extraX = -bounds.x;
504                 startNewLine = false;
505             }
506 
507             Image image = glyph.getImage();
508             if (image == null && missingGlyph != null && glyph.isMissing()) image = missingGlyph.getImage();
509             if (image != null) {
510                 // Draw glyph, only binding a new glyph page texture when necessary.
511                 Texture texture = image.getTexture();
512                 if (lastBind != null && lastBind != texture) {
513                     GL.glEnd();
514                     lastBind = null;
515                 }
516                 if (lastBind == null) {
517                     texture.bind();
518                     GL.glBegin(SGL.GL_QUADS);
519                     lastBind = texture;
520                 }
521                 image.drawEmbedded(bounds.x + extraX, bounds.y + extraY, image.getWidth(), image.getHeight());
522             }
523 
524             if (glyphIndex >= 0) extraX += paddingRight + paddingLeft + paddingAdvanceX;
525             maxWidth = Math.max(maxWidth, bounds.x + extraX + bounds.width);
526             totalHeight = Math.max(totalHeight, ascent + bounds.y + bounds.height);
527 
528             if (codePoint == '\n') {
529                 startNewLine = true; // Mac gives -1 for bounds.x of '\n', so use the bounds.x of the next glyph.
530                 extraY += getLineHeight();
531                 lines++;
532                 totalHeight = 0;
533             }
534         }
535         if (lastBind != null) GL.glEnd();
536 
537         if (displayList != null) {
538             GL.glEndList();
539             // Invalidate the display list if it had glyphs that need to be loaded.
540             if (!queuedGlyphs.isEmpty()) displayList.invalid = true;
541         }
542 
543         GL.glTranslatef(-x, -y, 0);
544 
545         if (displayList == null) displayList = new DisplayList();
546         displayList.width = (short)maxWidth;
547         displayList.height = (short)(lines * getLineHeight() + totalHeight);
548         return displayList;
549     }
550 
551     public void drawString (float x, float y, CharSequence text, Color color, int startIndex, int endIndex) {
552         drawDisplayList(x, y, text, color, startIndex, endIndex);
553     }
554 
555     public void drawString (float x, float y, @Nonnull CharSequence text) {
556         drawString(x, y, text, Color.white);
557     }
558 
559     public void drawString (float x, float y, @Nonnull CharSequence text, Color col) {
560         drawString(x, y, text, col, 0, text.length());
561     }
562 
563     /**
564      * Returns the glyph for the specified codePoint. If the glyph does not exist yet,
565      * it is created and queued to be loaded.
566      *
567      * @param glyphCode The code of the glyph to locate
568      * @param codePoint The code point associated with the glyph
569      * @param bounds The bounds of the glyph on the page
570      * @param vector The vector the glyph is part of
571      * @param index The index of the glyph within the vector
572      * @return The glyph requested
573      */
574     private Glyph getGlyph (int glyphCode, int codePoint, @Nonnull Rectangle bounds, @Nonnull GlyphVector vector, int index) {
575         if (glyphCode < 0 || glyphCode >= MAX_GLYPH_CODE) {
576             // GlyphVector#getGlyphCode sometimes returns negative numbers on OS X.
577             return new Glyph(codePoint, bounds, vector, index, this) {
578                 public boolean isMissing () {
579                     return true;
580                 }
581             };
582         }
583         int pageIndex = glyphCode / PAGE_SIZE;
584         int glyphIndex = glyphCode & (PAGE_SIZE - 1);
585         Glyph glyph;
586         Glyph[] page = glyphs[pageIndex];
587         if (page != null) {
588             glyph = page[glyphIndex];
589             if (glyph != null) return glyph;
590         } else
591             page = glyphs[pageIndex] = new Glyph[PAGE_SIZE];
592         // Add glyph so size information is available and queue it so its image can be loaded later.
593         glyph = page[glyphIndex] = new Glyph(codePoint, bounds, vector, index, this);
594         queuedGlyphs.add(glyph);
595         return glyph;
596     }
597 
598     /**
599      * Returns the bounds of the specified glyph.\
600      *
601      * @param vector The vector the glyph is part of
602      * @param index The index of the glyph within the vector
603      * @param codePoint The code point associated with the glyph
604      */
605     private Rectangle getGlyphBounds (@Nonnull GlyphVector vector, int index, int codePoint) {
606         Rectangle bounds = vector.getGlyphPixelBounds(index, GlyphPage.renderContext, 0, 0);
607         if (codePoint == ' ') bounds.width = spaceWidth;
608         return bounds;
609     }
610 
611     /**
612      * Returns the width of the space character.
613      */
614     public int getSpaceWidth () {
615         return spaceWidth;
616     }
617 
618     /**
619      * @see org.newdawn.slick.Font#getWidth(CharSequence)
620      */
621     public int getWidth (@Nullable CharSequence text) {
622         if (text == null) throw new IllegalArgumentException("text cannot be null.");
623         if (text.length() == 0) return 0;
624 
625         if (displayListCaching) {
626             DisplayList displayList = displayLists.get(text);
627             if (displayList != null) return displayList.width;
628         }
629 
630         char[] chars = toCharArray(text, 0, text.length());
631         GlyphVector vector = font.layoutGlyphVector(GlyphPage.renderContext, chars, 0, chars.length, Font.LAYOUT_LEFT_TO_RIGHT);
632 
633         int width = 0;
634         int extraX = 0;
635         boolean startNewLine = false;
636         for (int glyphIndex = 0, n = vector.getNumGlyphs(); glyphIndex < n; glyphIndex++) {
637             int charIndex = vector.getGlyphCharIndex(glyphIndex);
638             int codePoint = Character.codePointAt(text, charIndex);
639             Rectangle bounds = getGlyphBounds(vector, glyphIndex, codePoint);
640 
641             if (startNewLine && codePoint != '\n') extraX = -bounds.x;
642 
643             if (glyphIndex > 0) extraX += paddingLeft + paddingRight + paddingAdvanceX;
644             width = Math.max(width, bounds.x + extraX + bounds.width);
645 
646             if (codePoint == '\n') startNewLine = true;
647         }
648 
649         return width;
650     }
651 
652     private static int indexOf(@Nonnull CharSequence cs, char chr) {
653         for (int i=0; i<cs.length(); i++) {
654             if (cs.charAt(i)==chr)
655                 return i;
656         }
657         return -1;
658     }
659 
660     //instead of subSequence().toString().toCharArray()
661     @Nonnull
662     private static char[] toCharArray(@Nonnull CharSequence cs, int startIndex, int endIndex) {
663         if (startIndex==0 && endIndex==cs.length() && cs instanceof String)
664             return ((String)cs).toCharArray();
665         int s = endIndex-startIndex;
666         char[] ar = new char[s];
667         for (int x=0, i=startIndex; i<s; x++, i++)
668             ar[x] = cs.charAt(i);
669         return ar;
670     }
671 
672 
673     /**
674      * @see org.newdawn.slick.Font#getHeight(CharSequence)
675      */
676     public int getHeight (@Nullable CharSequence text) {
677         if (text == null) throw new IllegalArgumentException("text cannot be null.");
678         if (text.length() == 0) return 0;
679 
680         if (displayListCaching) {
681             DisplayList displayList = displayLists.get(text);
682             if (displayList != null) return displayList.height;
683         }
684 
685         char[] chars = toCharArray(text, 0, text.length());
686         GlyphVector vector = font.layoutGlyphVector(GlyphPage.renderContext, chars, 0, chars.length, Font.LAYOUT_LEFT_TO_RIGHT);
687 
688         int lines = 0, height = 0;
689         for (int i = 0, n = vector.getNumGlyphs(); i < n; i++) {
690             int charIndex = vector.getGlyphCharIndex(i);
691             int codePoint = Character.codePointAt(text, charIndex);
692             if (codePoint == ' ') continue;
693             Rectangle bounds = getGlyphBounds(vector, i, codePoint);
694 
695             height = Math.max(height, ascent + bounds.y + bounds.height);
696 
697             if (codePoint == '\n') {
698                 lines++;
699                 height = 0;
700             }
701         }
702         return lines * getLineHeight() + height;
703     }
704 
705     /**
706      * Returns the distance from the y drawing location to the top most pixel of the
707      * specified text.
708      *
709      * @param text The text to analyse
710      * @return The distance fro the y drawing location ot the top most pixel of the specified text
711      */
712     public int getYOffset (@Nullable CharSequence text) {
713         if (text == null) throw new IllegalArgumentException("text cannot be null.");
714 
715         DisplayList displayList = null;
716         if (displayListCaching) {
717             displayList = displayLists.get(text);
718             if (displayList != null && displayList.yOffset != null) return displayList.yOffset.intValue();
719         }
720 
721 
722 
723         int end = indexOf(text, '\n');
724         if (end==-1)
725             end = text.length();
726         char[] chars = toCharArray(text, 0, end);
727         GlyphVector vector = font.layoutGlyphVector(GlyphPage.renderContext, chars, 0, chars.length, Font.LAYOUT_LEFT_TO_RIGHT);
728         int yOffset = ascent + vector.getPixelBounds(null, 0, 0).y;
729 
730         if (displayList != null) displayList.yOffset = (short) yOffset;
731 
732         return yOffset;
733     }
734 
735     /**
736      * Returns the TrueTypeFont for this UnicodeFont.
737      *
738      * @return The AWT Font being rendered
739      */
740     public Font getFont() {
741         return font;
742     }
743 
744     /**
745      * Returns the padding above a glyph on the GlyphPage to allow for effects to be drawn.
746      *
747      * @return The padding at the top of the glyphs when drawn
748      */
749     public int getPaddingTop() {
750         return paddingTop;
751     }
752 
753     /**
754      * Sets the padding above a glyph on the GlyphPage to allow for effects to be drawn.
755      *
756      * @param paddingTop The padding at the top of the glyphs when drawn
757      */
758     public void setPaddingTop(int paddingTop) {
759         this.paddingTop = paddingTop;
760     }
761 
762     /**
763      * Returns the padding to the left of a glyph on the GlyphPage to allow for effects to be drawn.
764      *
765      * @return The padding at the left of the glyphs when drawn
766      */
767     public int getPaddingLeft() {
768         return paddingLeft;
769     }
770 
771     /**
772      * Sets the padding to the left of a glyph on the GlyphPage to allow for effects to be drawn.
773      *
774      * @param paddingLeft The padding at the left of the glyphs when drawn
775      */
776     public void setPaddingLeft(int paddingLeft) {
777         this.paddingLeft = paddingLeft;
778     }
779 
780     /**
781      * Returns the padding below a glyph on the GlyphPage to allow for effects to be drawn.
782      *
783      * @return The padding at the bottom of the glyphs when drawn
784      */
785     public int getPaddingBottom() {
786         return paddingBottom;
787     }
788 
789     /**
790      * Sets the padding below a glyph on the GlyphPage to allow for effects to be drawn.
791      *
792      * @param paddingBottom The padding at the bottom of the glyphs when drawn
793      */
794     public void setPaddingBottom(int paddingBottom) {
795         this.paddingBottom = paddingBottom;
796     }
797 
798     /**
799      * Returns the padding to the right of a glyph on the GlyphPage to allow for effects to be drawn.
800      *
801      * @return The padding at the right of the glyphs when drawn
802      */
803     public int getPaddingRight () {
804         return paddingRight;
805     }
806 
807     /**
808      * Sets the padding to the right of a glyph on the GlyphPage to allow for effects to be drawn.
809      *
810      * @param paddingRight The padding at the right of the glyphs when drawn
811      */
812     public void setPaddingRight (int paddingRight) {
813         this.paddingRight = paddingRight;
814     }
815 
816     /**
817      * Gets the additional amount to offset glyphs on the x axis.
818      *
819      * @return The padding applied for each horizontal advance (i.e. when a glyph is rendered)
820      */
821     public int getPaddingAdvanceX() {
822         return paddingAdvanceX;
823     }
824 
825     /**
826      * Sets the additional amount to offset glyphs on the x axis. This is typically set to a negative number when left or right
827      * padding is used so that glyphs are not spaced too far apart.
828      *
829      * @param paddingAdvanceX The padding applied for each horizontal advance (i.e. when a glyph is rendered)
830      */
831     public void setPaddingAdvanceX (int paddingAdvanceX) {
832         this.paddingAdvanceX = paddingAdvanceX;
833     }
834 
835     /**
836      * Gets the additional amount to offset a line of text on the y axis.
837      *
838      * @return The padding applied for each vertical advance (i.e. when a glyph is rendered)
839      */
840     public int getPaddingAdvanceY () {
841         return paddingAdvanceY;
842     }
843 
844     /**
845      * Sets the additional amount to offset a line of text on the y axis. This is typically set to a negative number when top or
846      * bottom padding is used so that lines of text are not spaced too far apart.
847      *
848      * @param paddingAdvanceY The padding applied for each vertical advance (i.e. when a glyph is rendered)
849      */
850     public void setPaddingAdvanceY (int paddingAdvanceY) {
851         this.paddingAdvanceY = paddingAdvanceY;
852     }
853 
854     /**
855      * Returns the distance from one line of text to the next. This is the sum of the descent, ascent, leading, padding top,
856      * padding bottom, and padding advance y. To change the line height, use {@link #setPaddingAdvanceY(int)}.
857      */
858     public int getLineHeight() {
859         return descent + ascent + leading + paddingTop + paddingBottom + paddingAdvanceY;
860     }
861 
862     /**
863      * Gets the distance from the baseline to the y drawing location.
864      *
865      * @return The ascent of this font
866      */
867     public int getAscent() {
868         return ascent;
869     }
870 
871     /**
872      * Gets the distance from the baseline to the bottom of most alphanumeric characters
873      * with descenders.
874      *
875      * @return The distance from the baseline to the bottom of the font
876      */
877     public int getDescent () {
878         return descent;
879     }
880 
881     /**
882      * Gets the extra distance between the descent of one line of text to the ascent of the next.
883      *
884      * @return The leading edge of the font
885      */
886     public int getLeading () {
887         return leading;
888     }
889 
890     /**
891      * Returns the width of the backing textures.
892      *
893      * @return The width of the glyph pages in this font
894      */
895     public int getGlyphPageWidth () {
896         return glyphPageWidth;
897     }
898 
899     /**
900      * Sets the width of the backing textures. Default is 512.
901      *
902      * @param glyphPageWidth The width of the glyph pages in this font
903      */
904     public void setGlyphPageWidth(int glyphPageWidth) {
905         this.glyphPageWidth = glyphPageWidth;
906     }
907 
908     /**
909      * Returns the height of the backing textures.
910      *
911      * @return The height of the glyph pages in this font
912      */
913     public int getGlyphPageHeight() {
914         return glyphPageHeight;
915     }
916 
917     /**
918      * Sets the height of the backing textures. Default is 512.
919      *
920      * @param glyphPageHeight The width of the glyph pages in this font
921      */
922     public void setGlyphPageHeight(int glyphPageHeight) {
923         this.glyphPageHeight = glyphPageHeight;
924     }
925 
926     /**
927      * Returns the GlyphPages for this UnicodeFont.
928      *
929      * @return The glyph pages that have been loaded into this font
930      */
931     @Nonnull
932     public List<GlyphPage> getGlyphPages () {
933         return glyphPages;
934     }
935 
936     /**
937      * Returns a list of {@link org.newdawn.slick.font.effects.Effect}s that will be applied
938      * to the glyphs.
939      *
940      * @return The list of effects to be applied to the font
941      */
942     @Nonnull
943     public List<Effect> getEffects () {
944         return effects;
945     }
946 
947     /**
948      * Returns true if this UnicodeFont caches the glyph drawing instructions to
949      * improve performance.
950      *
951      * @return True if caching is turned on
952      */
953     public boolean isCaching () {
954         return displayListCaching;
955     }
956 
957     /**
958      * Sets if this UnicodeFont caches the glyph drawing instructions to improve performance.
959      * Default is true. Text rendering is very slow without display list caching.
960      *
961      * @param displayListCaching True if caching should be turned on
962      */
963     public void setDisplayListCaching (boolean displayListCaching) {
964         this.displayListCaching = displayListCaching;
965     }
966 
967     /**
968      * Returns the path to the TTF file for this UnicodeFont, or null. If this UnicodeFont was created without specifying the TTF
969      * file, it will try to determine the path using Sun classes. If this fails, null is returned.
970      *
971      * @return The reference to the font file that the kerning was loaded from
972      */
973     @Nullable
974     public String getFontFile () {
975         if (ttfFileRef == null || ttfFileRef.length()==0) {
976             // Worst case if this UnicodeFont was loaded without a ttfFileRef, try to get the font file from Sun's classes.
977             try {
978                 Object font2D = Class.forName("sun.font.FontManager").getDeclaredMethod("getFont2D", new Class[] {Font.class})
979                     .invoke(null, font);
980                 Field platNameField = Class.forName("sun.font.PhysicalFont").getDeclaredField("platName");
981                 platNameField.setAccessible(true);
982                 ttfFileRef = (String)platNameField.get(font2D);
983             } catch (Throwable ignored) {
984                 //System.out.println(ignored.getMessage());
985             }
986             if (ttfFileRef == null) ttfFileRef = "";
987         }
988         if (ttfFileRef.length() == 0) return null;
989         return ttfFileRef;
990     }
991 
992     /**
993      * A simple descriptor for display lists cached within this font
994      */
995     public static class DisplayList {
996         /** True if this display list has been invalidated */
997         boolean invalid;
998         /** The ID of the display list this descriptor represents */
999         int id;
1000         /** The vertical offset to the top of this display list */
1001         Short yOffset;
1002 
1003         /** The width of rendered text in the list */
1004         public short width;
1005         /** The height of the rendered text in the list */
1006         public short height;
1007         /** Application data stored in the list */
1008         public Object userData;
1009 
1010         DisplayList () {
1011         }
1012     }
1013 }