rect.go (2618B)
1 // Copyright 2019 The Ebiten Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package restorable 16 17 import ( 18 "fmt" 19 "image" 20 21 "github.com/hajimehoshi/ebiten/v2/internal/graphicscommand" 22 ) 23 24 type rectToPixels struct { 25 m map[image.Rectangle][]byte 26 27 lastR image.Rectangle 28 lastPix []byte 29 } 30 31 func (rtp *rectToPixels) addOrReplace(pixels []byte, x, y, width, height int) { 32 if len(pixels) != 4*width*height { 33 msg := fmt.Sprintf("restorable: len(pixels) must be 4*%d*%d = %d but %d", width, height, 4*width*height, len(pixels)) 34 if pixels == nil { 35 msg += " (nil)" 36 } 37 panic(msg) 38 } 39 40 if rtp.m == nil { 41 rtp.m = map[image.Rectangle][]byte{} 42 } 43 44 newr := image.Rect(x, y, x+width, y+height) 45 for r := range rtp.m { 46 if r == newr { 47 // Replace the region. 48 rtp.m[r] = pixels 49 if r == rtp.lastR { 50 rtp.lastPix = pixels 51 } 52 return 53 } 54 if r.Overlaps(newr) { 55 panic(fmt.Sprintf("restorable: region (%#v) conflicted with the other region (%#v)", newr, r)) 56 } 57 } 58 59 // Add the region. 60 rtp.m[newr] = pixels 61 if newr == rtp.lastR { 62 rtp.lastPix = pixels 63 } 64 } 65 66 func (rtp *rectToPixels) remove(x, y, width, height int) { 67 if rtp.m == nil { 68 return 69 } 70 71 newr := image.Rect(x, y, x+width, y+height) 72 for r := range rtp.m { 73 if r == newr { 74 delete(rtp.m, r) 75 return 76 } 77 } 78 } 79 80 func (rtp *rectToPixels) at(i, j int) (byte, byte, byte, byte, bool) { 81 if rtp.m == nil { 82 return 0, 0, 0, 0, false 83 } 84 85 var pix []byte 86 87 var r image.Rectangle 88 var found bool 89 if pt := image.Pt(i, j); pt.In(rtp.lastR) { 90 r = rtp.lastR 91 found = true 92 pix = rtp.lastPix 93 } else { 94 for rr := range rtp.m { 95 if pt.In(rr) { 96 r = rr 97 found = true 98 rtp.lastR = rr 99 pix = rtp.m[rr] 100 rtp.lastPix = pix 101 break 102 } 103 } 104 } 105 106 if !found { 107 return 0, 0, 0, 0, false 108 } 109 110 idx := 4 * ((j-r.Min.Y)*r.Dx() + (i - r.Min.X)) 111 return pix[idx], pix[idx+1], pix[idx+2], pix[idx+3], true 112 } 113 114 func (rtp *rectToPixels) apply(img *graphicscommand.Image) { 115 // TODO: Isn't this too heavy? Can we merge the operations? 116 for r, pix := range rtp.m { 117 img.ReplacePixels(pix, r.Min.X, r.Min.Y, r.Dx(), r.Dy()) 118 } 119 }