@@ -4,17 +4,17 @@ import com.mojang.blaze3d.systems.RenderSystem
44import net.minecraft.client.texture.NativeImage
55import org.lwjgl.BufferUtils
66import org.lwjgl.opengl.GL13C.*
7- import java.awt.Color
8- import java.awt.Font
9- import java.awt.RenderingHints
10- import java.awt.Transparency
7+ import java.awt.*
118import java.awt.image.BufferedImage
129import java.io.ByteArrayOutputStream
1310import javax.imageio.ImageIO
1411import kotlin.math.roundToInt
1512import kotlin.math.sqrt
1613
1714object TextureUtils {
15+ private val metricCache = mutableMapOf<Font , FontMetrics >()
16+
17+
1818 fun bindTexture (id : Int , slot : Int = 0) {
1919 RenderSystem .activeTexture(GL_TEXTURE0 + slot)
2020 RenderSystem .bindTexture(id)
@@ -85,24 +85,31 @@ object TextureUtils {
8585 return NativeImage .read(buffer).pointer
8686 }
8787
88- fun getCharImage (font : Font , char : Char ): BufferedImage ? {
89- if (! font.canDisplay(char)) return null
88+ fun getCharImage (font : Font , codePoint : Char ): BufferedImage ? {
89+ if (! font.canDisplay(codePoint)) return null
90+
91+ val fontMetrics = metricCache.getOrPut(font) {
92+ val image = BufferedImage (1 , 1 , BufferedImage .TYPE_INT_ARGB )
93+ val graphics2D = image.createGraphics()
9094
91- val tempGraphics2D = BufferedImage (1 , 1 , BufferedImage .TYPE_INT_ARGB ).createGraphics()
92- tempGraphics2D.font = font
93- val fontMetrics = tempGraphics2D.fontMetrics
94- tempGraphics2D.dispose()
95+ graphics2D.font = font
96+ graphics2D.dispose()
97+
98+ image.graphics.getFontMetrics(font)
99+ }
95100
96- val charWidth = if (fontMetrics.charWidth(char ) > 0 ) fontMetrics.charWidth(char ) else 8
101+ val charWidth = if (fontMetrics.charWidth(codePoint ) > 0 ) fontMetrics.charWidth(codePoint ) else 8
97102 val charHeight = if (fontMetrics.height > 0 ) fontMetrics.height else font.size
98103
99104 val charImage = BufferedImage (charWidth, charHeight, BufferedImage .TYPE_INT_ARGB )
100105 val graphics2D = charImage.createGraphics()
101106
102107 graphics2D.setRenderingHint(RenderingHints .KEY_ANTIALIASING , RenderingHints .VALUE_ANTIALIAS_ON )
108+ graphics2D.setRenderingHint(RenderingHints .KEY_RENDERING , RenderingHints .VALUE_RENDER_DEFAULT )
109+
103110 graphics2D.font = font
104111 graphics2D.color = Color .WHITE
105- graphics2D.drawString(char .toString(), 0 , fontMetrics.ascent)
112+ graphics2D.drawString(codePoint .toString(), 0 , fontMetrics.ascent)
106113 graphics2D.dispose()
107114
108115 return charImage
0 commit comments