diff --git a/text/v2/glyph.go b/text/v2/glyph.go index cdf03df26..96053a033 100644 --- a/text/v2/glyph.go +++ b/text/v2/glyph.go @@ -43,12 +43,14 @@ type glyphImageCacheEntry struct { } type glyphImageCache[Key comparable] struct { - cache map[Key]*glyphImageCacheEntry - atime int64 - m sync.Mutex + cache map[Key]*glyphImageCacheEntry + atime int64 + glyphVariationCount int + + m sync.Mutex } -func (g *glyphImageCache[Key]) getOrCreate(face Face, key Key, create func() *ebiten.Image) *ebiten.Image { +func (g *glyphImageCache[Key]) getOrCreate(key Key, create func() *ebiten.Image) *ebiten.Image { g.m.Lock() defer g.m.Unlock() @@ -83,7 +85,7 @@ func (g *glyphImageCache[Key]) getOrCreate(face Face, key Key, create func() *eb // If the number of glyphs exceeds this soft limits, old glyphs are removed. // Even after cleaning up the cache, the number of glyphs might still exceed the soft limit, but // this is fine. - cacheSoftLimit := 128 * glyphVariationCount(face) + cacheSoftLimit := 128 * g.glyphVariationCount if len(g.cache) > cacheSoftLimit { for key, e := range g.cache { // 60 is an arbitrary number. diff --git a/text/v2/gotextfacesource.go b/text/v2/gotextfacesource.go index 91ce2ed09..ddfbd7ead 100644 --- a/text/v2/gotextfacesource.go +++ b/text/v2/gotextfacesource.go @@ -287,9 +287,11 @@ func (g *GoTextFaceSource) getOrCreateGlyphImage(goTextFace *GoTextFace, key goT g.glyphImageCache = map[float64]*glyphImageCache[goTextGlyphImageCacheKey]{} } if _, ok := g.glyphImageCache[goTextFace.Size]; !ok { - g.glyphImageCache[goTextFace.Size] = &glyphImageCache[goTextGlyphImageCacheKey]{} + g.glyphImageCache[goTextFace.Size] = &glyphImageCache[goTextGlyphImageCacheKey]{ + glyphVariationCount: glyphVariationCount(goTextFace), + } } - return g.glyphImageCache[goTextFace.Size].getOrCreate(goTextFace, key, create) + return g.glyphImageCache[goTextFace.Size].getOrCreate(key, create) } type singleFontmap struct { diff --git a/text/v2/gox.go b/text/v2/gox.go index e12a8ff5b..571b21779 100644 --- a/text/v2/gox.go +++ b/text/v2/gox.go @@ -43,7 +43,7 @@ type goXFaceGlyphImageCacheKey struct { type GoXFace struct { f *faceWithCache - glyphImageCache glyphImageCache[goXFaceGlyphImageCacheKey] + glyphImageCache *glyphImageCache[goXFaceGlyphImageCacheKey] cachedMetrics Metrics @@ -57,7 +57,11 @@ func NewGoXFace(face font.Face) *GoXFace { f: face, }, } + // Set addr as early as possible. This is necessary for glyphVariationCount. s.addr = s + s.glyphImageCache = &glyphImageCache[goXFaceGlyphImageCacheKey]{ + glyphVariationCount: glyphVariationCount(s), + } return s } @@ -170,7 +174,7 @@ func (s *GoXFace) glyphImage(r rune, origin fixed.Point26_6) (*ebiten.Image, int rune: r, xoffset: subpixelOffset.X, } - img := s.glyphImageCache.getOrCreate(s, key, func() *ebiten.Image { + img := s.glyphImageCache.getOrCreate(key, func() *ebiten.Image { return s.glyphImageImpl(r, subpixelOffset, b) }) imgX := (origin.X + b.Min.X).Floor()