From f298b9541b4a883d57deca601bdca6a2c1b858ba Mon Sep 17 00:00:00 2001 From: Hajime Hoshi Date: Wed, 8 Mar 2023 16:27:36 +0900 Subject: [PATCH] internal/restorable: use a cache for pixels at readPixelsFromGPU Updates #2375 --- internal/restorable/image.go | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/internal/restorable/image.go b/internal/restorable/image.go index 5d01b791e..6c03628ca 100644 --- a/internal/restorable/image.go +++ b/internal/restorable/image.go @@ -124,12 +124,11 @@ type Image struct { // staleRegions is not used when AlwaysReadPixelsFromGPU() returns true. staleRegions []image.Rectangle - // pixelsForRestore is cached byte slices for pixels. - // pixelsForRestore is just a cache to avoid allocations (#2375). - // pixelsForRestore is used only at restore. + // pixelsCache is cached byte slices for pixels. + // pixelsCache is just a cache to avoid allocations (#2375). // // A key is the region and a value is a byte slice for the region. - pixelsForRestore map[image.Rectangle][]byte + pixelsCache map[image.Rectangle][]byte // regionsForRestore is cached regions. // regionsForRestore is just a cache to avoid allocations (#2375). @@ -485,7 +484,15 @@ func (i *Image) readPixelsFromGPU(graphicsDriver graphicsdriver.Graphics) error continue } - pix := make([]byte, 4*r.Dx()*r.Dy()) + if i.pixelsCache == nil { + i.pixelsCache = map[image.Rectangle][]byte{} + } + + pix, ok := i.pixelsCache[r] + if !ok { + pix = make([]byte, 4*r.Dx()*r.Dy()) + i.pixelsCache[r] = pix + } if err := i.image.ReadPixels(graphicsDriver, pix, r.Min.X, r.Min.Y, r.Dx(), r.Dy()); err != nil { return err } @@ -612,14 +619,14 @@ func (i *Image) restore(graphicsDriver graphicsdriver.Graphics) error { continue } - if i.pixelsForRestore == nil { - i.pixelsForRestore = map[image.Rectangle][]byte{} + if i.pixelsCache == nil { + i.pixelsCache = map[image.Rectangle][]byte{} } - pix, ok := i.pixelsForRestore[r] + pix, ok := i.pixelsCache[r] if !ok { pix = make([]byte, 4*r.Dx()*r.Dy()) - i.pixelsForRestore[r] = pix + i.pixelsCache[r] = pix } if err := gimg.ReadPixels(graphicsDriver, pix, r.Min.X, r.Min.Y, r.Dx(), r.Dy()); err != nil { return err @@ -645,7 +652,7 @@ func (i *Image) Dispose() { i.image.Dispose() i.image = nil i.basePixels = Pixels{} - i.pixelsForRestore = nil + i.pixelsCache = nil i.clearDrawTrianglesHistory() i.stale = false i.staleRegions = i.staleRegions[:0]