/
text.go
289 lines (248 loc) · 7.67 KB
/
text.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
// Copyright 2017 The Ebiten Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package text offers functions to draw texts on an Ebiten's image.
//
// For the example using a TTF font, see font package in the examples.
package text
import (
"image"
"image/color"
"math"
"sync"
"golang.org/x/image/font"
"golang.org/x/image/math/fixed"
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/internal/hooks"
)
var (
monotonicClock int64
)
func now() int64 {
return monotonicClock
}
func init() {
hooks.AppendHookOnBeforeUpdate(func() error {
monotonicClock++
return nil
})
}
func fixed26_6ToFloat64(x fixed.Int26_6) float64 {
return float64(x>>6) + float64(x&((1<<6)-1))/float64(1<<6)
}
func drawGlyph(dst *ebiten.Image, face font.Face, r rune, img *ebiten.Image, x, y fixed.Int26_6, clr ebiten.ColorM) {
if img == nil {
return
}
b := getGlyphBounds(face, r)
op := &ebiten.DrawImageOptions{}
op.GeoM.Translate(float64((x+b.Min.X)>>6), float64((y+b.Min.Y)>>6))
op.ColorM = clr
dst.DrawImage(img, op)
}
var (
glyphBoundsCache = map[font.Face]map[rune]fixed.Rectangle26_6{}
)
func getGlyphBounds(face font.Face, r rune) fixed.Rectangle26_6 {
if _, ok := glyphBoundsCache[face]; !ok {
glyphBoundsCache[face] = map[rune]fixed.Rectangle26_6{}
}
if b, ok := glyphBoundsCache[face][r]; ok {
return b
}
b, _, _ := face.GlyphBounds(r)
glyphBoundsCache[face][r] = b
return b
}
type glyphImageCacheEntry struct {
image *ebiten.Image
atime int64
}
var (
glyphImageCache = map[font.Face]map[rune]*glyphImageCacheEntry{}
)
func getGlyphImage(face font.Face, r rune) *ebiten.Image {
if _, ok := glyphImageCache[face]; !ok {
glyphImageCache[face] = map[rune]*glyphImageCacheEntry{}
}
if e, ok := glyphImageCache[face][r]; ok {
e.atime = now()
return e.image
}
b := getGlyphBounds(face, r)
w, h := (b.Max.X - b.Min.X).Ceil(), (b.Max.Y - b.Min.Y).Ceil()
if w == 0 || h == 0 {
glyphImageCache[face][r] = &glyphImageCacheEntry{
image: nil,
atime: now(),
}
return nil
}
if b.Min.X&((1<<6)-1) != 0 {
w++
}
if b.Min.Y&((1<<6)-1) != 0 {
h++
}
rgba := image.NewRGBA(image.Rect(0, 0, w, h))
d := font.Drawer{
Dst: rgba,
Src: image.White,
Face: face,
}
x, y := -b.Min.X, -b.Min.Y
x, y = fixed.I(x.Ceil()), fixed.I(y.Ceil())
d.Dot = fixed.Point26_6{X: x, Y: y}
d.DrawString(string(r))
img := ebiten.NewImageFromImage(rgba)
if _, ok := glyphImageCache[face][r]; !ok {
glyphImageCache[face][r] = &glyphImageCacheEntry{
image: img,
atime: now(),
}
}
return img
}
var textM sync.Mutex
// Draw draws a given text on a given destination image dst.
//
// face is the font for text rendering.
// (x, y) represents a 'dot' (period) position.
// This means that if the given text consisted of a single character ".",
// it would be positioned at the given position (x, y).
// Be careful that this doesn't represent left-upper corner position.
//
// clr is the color for text rendering.
//
// If you want to adjust the position of the text, these functions are useful:
//
// * text.BoundString: the rendered bounds of the given text.
// * golang.org/x/image/font.Face.Metrics: the metrics of the face.
//
// The '\n' newline character puts the following text on the next line.
// Line height is based on Metrics().Height of the font.
//
// Glyphs used for rendering are cached in least-recently-used way.
// It is OK to call Draw with a same text and a same face at every frame in terms of performance.
//
// Be careful that the passed font face is held by this package and is never released.
// This is a known issue (#498).
//
// Draw is concurrent-safe.
func Draw(dst *ebiten.Image, text string, face font.Face, x, y int, clr color.Color) {
textM.Lock()
defer textM.Unlock()
cr, cg, cb, ca := clr.RGBA()
if ca == 0 {
return
}
var colorm ebiten.ColorM
colorm.Scale(float64(cr)/float64(ca), float64(cg)/float64(ca), float64(cb)/float64(ca), float64(ca)/0xffff)
fx, fy := fixed.I(x), fixed.I(y)
prevR := rune(-1)
faceHeight := face.Metrics().Height
for _, r := range text {
if prevR >= 0 {
fx += face.Kern(prevR, r)
}
if r == '\n' {
fx = fixed.I(x)
fy += faceHeight
prevR = rune(-1)
continue
}
img := getGlyphImage(face, r)
drawGlyph(dst, face, r, img, fx, fy, colorm)
fx += glyphAdvance(face, r)
prevR = r
}
// cacheSoftLimit indicates the soft limit of the number of glyphs in the cache.
// If the number of glyphs exceeds this soft limits, old glyphs are removed.
// Even after clearning up the cache, the number of glyphs might still exceeds the soft limit, but
// this is fine.
const cacheSoftLimit = 512
// Clean up the cache.
if len(glyphImageCache[face]) > cacheSoftLimit {
for r, e := range glyphImageCache[face] {
// 60 is an arbitrary number.
if e.atime < now()-60 {
delete(glyphImageCache[face], r)
}
}
}
}
// BoundString returns the measured size of a given string using a given font.
// This method will return the exact size in pixels that a string drawn by Draw will be.
// The bound's origin point indicates the dot (period) position.
// This means that if the text consists of one character '.', this dot is rendered at (0, 0).
//
// This is very similar to golang.org/x/image/font's BoundString,
// but this BoundString calculates the actual rendered area considering multiple lines and space characters.
//
// face is the font for text rendering.
// text is the string that's being measured.
//
// Be careful that the passed font face is held by this package and is never released.
// This is a known issue (#498).
//
// BoundString is concurrent-safe.
func BoundString(face font.Face, text string) image.Rectangle {
textM.Lock()
defer textM.Unlock()
m := face.Metrics()
faceHeight := m.Height
fx, fy := fixed.I(0), fixed.I(0)
prevR := rune(-1)
var bounds fixed.Rectangle26_6
for _, r := range text {
if prevR >= 0 {
fx += face.Kern(prevR, r)
}
if r == '\n' {
fx = fixed.I(0)
fy += faceHeight
prevR = rune(-1)
continue
}
b := getGlyphBounds(face, r)
b.Min.X += fx
b.Max.X += fx
b.Min.Y += fy
b.Max.Y += fy
bounds = bounds.Union(b)
fx += glyphAdvance(face, r)
prevR = r
}
return image.Rect(
int(math.Floor(fixed26_6ToFloat64(bounds.Min.X))),
int(math.Floor(fixed26_6ToFloat64(bounds.Min.Y))),
int(math.Ceil(fixed26_6ToFloat64(bounds.Max.X))),
int(math.Ceil(fixed26_6ToFloat64(bounds.Max.Y))),
)
}
// CacheGlyphs precaches the glyphs for the given text and the given font face into the cache.
//
// Draw automatically creates and caches necessary glyphs, so usually you don't have to call CacheGlyphs
// explicitly. However, for example, when you call Draw for each rune of one big text, Draw tries to create the glyph
// cache and render it for each rune. This is very inefficient because creating a glyph image and rendering it are
// different operations and can never be merged as one draw call. CacheGlyphs creates necessary glyphs without
// rendering them so that these operations are likely merged into one draw call.
//
// If a rune's glyph is already cached, CacheGlyphs does nothing for the rune.
func CacheGlyphs(face font.Face, text string) {
textM.Lock()
defer textM.Unlock()
for _, r := range text {
getGlyphImage(face, r)
}
}