image.go 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369
  1. // Copyright 2014 Hajime Hoshi
  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. package ebiten
  15. import (
  16. "fmt"
  17. "image"
  18. "image/color"
  19. "math"
  20. "unsafe"
  21. "github.com/hajimehoshi/ebiten/v2/internal/affine"
  22. "github.com/hajimehoshi/ebiten/v2/internal/atlas"
  23. "github.com/hajimehoshi/ebiten/v2/internal/builtinshader"
  24. "github.com/hajimehoshi/ebiten/v2/internal/graphics"
  25. "github.com/hajimehoshi/ebiten/v2/internal/graphicscommand"
  26. "github.com/hajimehoshi/ebiten/v2/internal/graphicsdriver"
  27. "github.com/hajimehoshi/ebiten/v2/internal/restorable"
  28. "github.com/hajimehoshi/ebiten/v2/internal/shaderir"
  29. "github.com/hajimehoshi/ebiten/v2/internal/ui"
  30. )
  31. // Image represents a rectangle set of pixels.
  32. // The pixel format is alpha-premultiplied RGBA.
  33. // Image implements the standard image.Image and draw.Image interfaces.
  34. type Image struct {
  35. // addr holds self to check copying.
  36. // See strings.Builder for similar examples.
  37. addr *Image
  38. image *ui.Image
  39. original *Image
  40. bounds image.Rectangle
  41. // tmpVertices must not be reused until ui.Image.Draw* is called.
  42. tmpVertices []float32
  43. // tmpIndices must not be reused until ui.Image.Draw* is called.
  44. tmpIndices []uint32
  45. // tmpUniforms must not be reused until ui.Image.Draw* is called.
  46. tmpUniforms []uint32
  47. // Do not add a 'buffering' member that are resolved lazily.
  48. // This tends to forget resolving the buffer easily (#2362).
  49. }
  50. func (i *Image) copyCheck() {
  51. if i.addr != i {
  52. panic("ebiten: illegal use of non-zero Image copied by value")
  53. }
  54. }
  55. // Size returns the size of the image.
  56. //
  57. // Deprecated: as of v2.5. Use Bounds().Dx() and Bounds().Dy() or Bounds().Size() instead.
  58. func (i *Image) Size() (width, height int) {
  59. s := i.Bounds().Size()
  60. return s.X, s.Y
  61. }
  62. func (i *Image) isDisposed() bool {
  63. return i.image == nil
  64. }
  65. func (i *Image) isSubImage() bool {
  66. return i.original != nil
  67. }
  68. // Clear resets the pixels of the image into 0.
  69. //
  70. // When the image is disposed, Clear does nothing.
  71. func (i *Image) Clear() {
  72. i.Fill(color.Transparent)
  73. }
  74. // Fill fills the image with a solid color.
  75. //
  76. // When the image is disposed, Fill does nothing.
  77. func (i *Image) Fill(clr color.Color) {
  78. i.copyCheck()
  79. if i.isDisposed() {
  80. return
  81. }
  82. var crf, cgf, cbf, caf float32
  83. cr, cg, cb, ca := clr.RGBA()
  84. crf = float32(cr) / 0xffff
  85. cgf = float32(cg) / 0xffff
  86. cbf = float32(cb) / 0xffff
  87. caf = float32(ca) / 0xffff
  88. i.image.Fill(crf, cgf, cbf, caf, i.adjustedBounds())
  89. }
  90. func canSkipMipmap(det float32, filter builtinshader.Filter) bool {
  91. if filter != builtinshader.FilterLinear {
  92. return true
  93. }
  94. return math.Abs(float64(det)) >= 0.999
  95. }
  96. // DrawImageOptions represents options for DrawImage.
  97. type DrawImageOptions struct {
  98. // GeoM is a geometry matrix to draw.
  99. // The default (zero) value is identity, which draws the image at (0, 0).
  100. GeoM GeoM
  101. // ColorScale is a scale of color.
  102. //
  103. // ColorScale is slightly different from colorm.ColorM's Scale in terms of alphas.
  104. // ColorScale is applied to premultiplied-alpha colors, while colorm.ColorM is applied to straight-alpha colors.
  105. // Thus, ColorM.Scale(r, g, b, a) equals to ColorScale.Scale(r*a, g*a, b*a, a).
  106. //
  107. // The default (zero) value is identity, which is (1, 1, 1, 1).
  108. ColorScale ColorScale
  109. // ColorM is a color matrix to draw.
  110. // The default (zero) value is identity, which doesn't change any color.
  111. //
  112. // Deprecated: as of v2.5. Use ColorScale or the package colorm instead.
  113. ColorM ColorM
  114. // CompositeMode is a composite mode to draw.
  115. // The default (zero) value is CompositeModeCustom (Blend is used).
  116. //
  117. // Deprecated: as of v2.5. Use Blend instead.
  118. CompositeMode CompositeMode
  119. // Blend is a blending way of the source color and the destination color.
  120. // Blend is used only when CompositeMode is CompositeModeCustom.
  121. // The default (zero) value is the regular alpha blending.
  122. Blend Blend
  123. // Filter is a type of texture filter.
  124. // The default (zero) value is FilterNearest.
  125. Filter Filter
  126. // DisableMipmaps disables mipmaps.
  127. // When Filter is FilterLinear and GeoM shrinks the image, mipmaps are used by default.
  128. // Mipmap is useful to render a shrunk image with high quality.
  129. // However, mipmaps can be expensive, especially on mobiles.
  130. // When DisableMipmaps is true, mipmap is not used.
  131. // When Filter is not FilterLinear, DisableMipmaps is ignored.
  132. //
  133. // The default (zero) value is false.
  134. DisableMipmaps bool
  135. }
  136. // adjustPosition converts the position in the *ebiten.Image coordinate to the *ui.Image coordinate.
  137. func (i *Image) adjustPosition(x, y int) (int, int) {
  138. if i.isSubImage() {
  139. or := i.original.Bounds()
  140. x -= or.Min.X
  141. y -= or.Min.Y
  142. return x, y
  143. }
  144. r := i.Bounds()
  145. x -= r.Min.X
  146. y -= r.Min.Y
  147. return x, y
  148. }
  149. // adjustPositionF32 converts the position in the *ebiten.Image coordinate to the *ui.Image coordinate.
  150. func (i *Image) adjustPositionF32(x, y float32) (float32, float32) {
  151. if i.isSubImage() {
  152. or := i.original.Bounds()
  153. x -= float32(or.Min.X)
  154. y -= float32(or.Min.Y)
  155. return x, y
  156. }
  157. r := i.Bounds()
  158. x -= float32(r.Min.X)
  159. y -= float32(r.Min.Y)
  160. return x, y
  161. }
  162. func (i *Image) adjustedBounds() image.Rectangle {
  163. b := i.Bounds()
  164. x, y := i.adjustPosition(b.Min.X, b.Min.Y)
  165. return image.Rect(x, y, x+b.Dx(), y+b.Dy())
  166. }
  167. // DrawImage draws the given image on the image i.
  168. //
  169. // DrawImage accepts the options. For details, see the document of
  170. // DrawImageOptions.
  171. //
  172. // For drawing, the pixels of the argument image at the time of this call is
  173. // adopted. Even if the argument image is mutated after this call, the drawing
  174. // result is never affected.
  175. //
  176. // When the image i is disposed, DrawImage does nothing.
  177. // When the given image img is disposed, DrawImage panics.
  178. //
  179. // When the given image is as same as i, DrawImage panics.
  180. //
  181. // DrawImage works more efficiently as batches
  182. // when the successive calls of DrawImages satisfy the below conditions:
  183. //
  184. // - All render targets are the same (A in A.DrawImage(B, op))
  185. // - All Blend values are the same
  186. // - All Filter values are the same
  187. //
  188. // A whole image and its sub-image are considered to be the same, but some
  189. // environments like browsers might not work efficiently (#2471).
  190. //
  191. // Even when all the above conditions are satisfied, multiple draw commands can
  192. // be used in really rare cases. Ebitengine images usually share an internal
  193. // automatic texture atlas, but when you consume the atlas, or you create a huge
  194. // image, those images cannot be on the same texture atlas. In this case, draw
  195. // commands are separated.
  196. // Another case is when you use an offscreen as a render source. An offscreen
  197. // doesn't share the texture atlas with high probability.
  198. //
  199. // For more performance tips, see https://ebitengine.org/en/documents/performancetips.html
  200. func (i *Image) DrawImage(img *Image, options *DrawImageOptions) {
  201. i.copyCheck()
  202. if img.isDisposed() {
  203. panic("ebiten: the given image to DrawImage must not be disposed")
  204. }
  205. if i.isDisposed() {
  206. return
  207. }
  208. if options == nil {
  209. options = &DrawImageOptions{}
  210. }
  211. var blend graphicsdriver.Blend
  212. if options.CompositeMode == CompositeModeCustom {
  213. blend = options.Blend.internalBlend()
  214. } else {
  215. blend = options.CompositeMode.blend().internalBlend()
  216. }
  217. filter := builtinshader.Filter(options.Filter)
  218. geoM := options.GeoM
  219. if offsetX, offsetY := i.adjustPosition(0, 0); offsetX != 0 || offsetY != 0 {
  220. geoM.Translate(float64(offsetX), float64(offsetY))
  221. }
  222. a, b, c, d, tx, ty := geoM.elements32()
  223. det := a*d - b*c
  224. if det == 0 {
  225. return
  226. }
  227. bounds := img.Bounds()
  228. sx0, sy0 := img.adjustPosition(bounds.Min.X, bounds.Min.Y)
  229. sx1, sy1 := img.adjustPosition(bounds.Max.X, bounds.Max.Y)
  230. colorm, cr, cg, cb, ca := colorMToScale(options.ColorM.affineColorM())
  231. cr, cg, cb, ca = options.ColorScale.apply(cr, cg, cb, ca)
  232. vs := i.ensureTmpVertices(4 * graphics.VertexFloatCount)
  233. graphics.QuadVerticesFromSrcAndMatrix(vs, float32(sx0), float32(sy0), float32(sx1), float32(sy1), a, b, c, d, tx, ty, cr, cg, cb, ca)
  234. is := graphics.QuadIndices()
  235. srcs := [graphics.ShaderSrcImageCount]*ui.Image{img.image}
  236. useColorM := !colorm.IsIdentity()
  237. shader := builtinShader(filter, builtinshader.AddressUnsafe, useColorM)
  238. i.tmpUniforms = i.tmpUniforms[:0]
  239. if useColorM {
  240. var body [16]float32
  241. var translation [4]float32
  242. colorm.Elements(body[:], translation[:])
  243. i.tmpUniforms = shader.appendUniforms(i.tmpUniforms, map[string]any{
  244. builtinshader.UniformColorMBody: body[:],
  245. builtinshader.UniformColorMTranslation: translation[:],
  246. })
  247. }
  248. dr := i.adjustedBounds()
  249. hint := restorable.HintNone
  250. if overwritesDstRegion(options.Blend, dr, geoM, sx0, sy0, sx1, sy1) {
  251. hint = restorable.HintOverwriteDstRegion
  252. }
  253. skipMipmap := options.DisableMipmaps
  254. if !skipMipmap {
  255. skipMipmap = canSkipMipmap(det, filter)
  256. }
  257. i.image.DrawTriangles(srcs, vs, is, blend, dr, [graphics.ShaderSrcImageCount]image.Rectangle{img.adjustedBounds()}, shader.shader, i.tmpUniforms, graphicsdriver.FillRuleFillAll, skipMipmap, false, hint)
  258. }
  259. // overwritesDstRegion reports whether the given parameters overwrite the destination region completely.
  260. func overwritesDstRegion(blend Blend, dstRegion image.Rectangle, geoM GeoM, sx0, sy0, sx1, sy1 int) bool {
  261. // TODO: More precisely, BlendFactorDestinationRGB, BlendFactorDestinationAlpha, and operations should be checked.
  262. if blend != BlendCopy && blend != BlendClear {
  263. return false
  264. }
  265. // Check the result vertices is not a rotated rectangle.
  266. if geoM.b != 0 || geoM.c != 0 {
  267. return false
  268. }
  269. // Check the result vertices completely covers dstRegion.
  270. x0, y0 := geoM.Apply(float64(sx0), float64(sy0))
  271. x1, y1 := geoM.Apply(float64(sx1), float64(sy1))
  272. if float64(dstRegion.Min.X) < x0 || float64(dstRegion.Min.Y) < y0 || float64(dstRegion.Max.X) > x1 || float64(dstRegion.Max.Y) > y1 {
  273. return false
  274. }
  275. return true
  276. }
  277. // Vertex represents a vertex passed to DrawTriangles.
  278. type Vertex struct {
  279. // DstX and DstY represents a point on a destination image.
  280. DstX float32
  281. DstY float32
  282. // SrcX and SrcY represents a point on a source image.
  283. // Be careful that SrcX/SrcY coordinates are on the image's bounds.
  284. // This means that an upper-left point of a sub-image might not be (0, 0).
  285. SrcX float32
  286. SrcY float32
  287. // ColorR/ColorG/ColorB/ColorA represents color scaling values.
  288. // Their interpretation depends on the concrete draw call used:
  289. // - DrawTriangles: straight-alpha or premultiplied-alpha encoded color multiplier.
  290. // The format is determined by ColorScaleMode in DrawTrianglesOptions.
  291. // If ColorA is 0, the vertex is fully transparent and color is ignored.
  292. // If ColorA is 1, the vertex has the color (ColorR, ColorG, ColorB).
  293. // Vertex colors are converted to premultiplied-alpha internally and
  294. // interpolated linearly respecting alpha.
  295. // - DrawTrianglesShader: arbitrary floating point values sent to the shader.
  296. // These are interpolated linearly and independently of each other.
  297. ColorR float32
  298. ColorG float32
  299. ColorB float32
  300. ColorA float32
  301. // Custom0/Custom1/Custom2/Custom3 represents general-purpose values passed to the shader.
  302. // In order to use them, Fragment must have an additional vec4 argument.
  303. //
  304. // These values are valid only when DrawTrianglesShader is used.
  305. // In other cases, these values are ignored.
  306. Custom0 float32
  307. Custom1 float32
  308. Custom2 float32
  309. Custom3 float32
  310. }
  311. var _ [0]byte = [unsafe.Sizeof(Vertex{}) - unsafe.Sizeof(float32(0))*graphics.VertexFloatCount]byte{}
  312. // Address represents a sampler address mode.
  313. type Address int
  314. const (
  315. // AddressUnsafe means there is no guarantee when the texture coordinates are out of range.
  316. AddressUnsafe Address = Address(builtinshader.AddressUnsafe)
  317. // AddressClampToZero means that out-of-range texture coordinates return 0 (transparent).
  318. AddressClampToZero Address = Address(builtinshader.AddressClampToZero)
  319. // AddressRepeat means that texture coordinates wrap to the other side of the texture.
  320. AddressRepeat Address = Address(builtinshader.AddressRepeat)
  321. )
  322. // FillRule is the rule whether an overlapped region is rendered with DrawTriangles(Shader).
  323. type FillRule int
  324. const (
  325. // FillRuleFillAll indicates all the triangles are rendered regardless of overlaps.
  326. FillRuleFillAll FillRule = FillRule(graphicsdriver.FillRuleFillAll)
  327. // FillRuleNonZero means that triangles are rendered based on the non-zero rule.
  328. // If and only if the number of overlaps is not 0, the region is rendered.
  329. FillRuleNonZero FillRule = FillRule(graphicsdriver.FillRuleNonZero)
  330. // FillRuleEvenOdd means that triangles are rendered based on the even-odd rule.
  331. // If and only if the number of overlaps is odd, the region is rendered.
  332. FillRuleEvenOdd FillRule = FillRule(graphicsdriver.FillRuleEvenOdd)
  333. )
  334. const (
  335. // FillAll indicates all the triangles are rendered regardless of overlaps.
  336. //
  337. // Deprecated: as of v2.8. Use FillRuleFillAll instead.
  338. FillAll = FillRuleFillAll
  339. // NonZero means that triangles are rendered based on the non-zero rule.
  340. // If and only if the number of overlaps is not 0, the region is rendered.
  341. //
  342. // Deprecated: as of v2.8. Use FillRuleNonZero instead.
  343. NonZero = FillRuleNonZero
  344. // EvenOdd means that triangles are rendered based on the even-odd rule.
  345. // If and only if the number of overlaps is odd, the region is rendered.
  346. //
  347. // Deprecated: as of v2.8. Use FillRuleEvenOdd instead.
  348. EvenOdd = FillRuleEvenOdd
  349. )
  350. // ColorScaleMode is the mode of color scales in vertices.
  351. type ColorScaleMode int
  352. const (
  353. // ColorScaleModeStraightAlpha indicates color scales in vertices are
  354. // straight-alpha encoded color multiplier.
  355. ColorScaleModeStraightAlpha ColorScaleMode = iota
  356. // ColorScaleModePremultipliedAlpha indicates color scales in vertices are
  357. // premultiplied-alpha encoded color multiplier.
  358. ColorScaleModePremultipliedAlpha
  359. )
  360. // DrawTrianglesOptions represents options for DrawTriangles.
  361. type DrawTrianglesOptions struct {
  362. // ColorM is a color matrix to draw.
  363. // The default (zero) value is identity, which doesn't change any color.
  364. // ColorM is applied before vertex color scale is applied.
  365. //
  366. // Deprecated: as of v2.5. Use the package colorm instead.
  367. ColorM ColorM
  368. // ColorScaleMode is the mode of color scales in vertices.
  369. // ColorScaleMode affects the color calculation with vertex colors, but doesn't affect with a color matrix.
  370. // The default (zero) value is ColorScaleModeStraightAlpha.
  371. ColorScaleMode ColorScaleMode
  372. // CompositeMode is a composite mode to draw.
  373. // The default (zero) value is CompositeModeCustom (Blend is used).
  374. //
  375. // Deprecated: as of v2.5. Use Blend instead.
  376. CompositeMode CompositeMode
  377. // Blend is a blending way of the source color and the destination color.
  378. // Blend is used only when CompositeMode is CompositeModeCustom.
  379. // The default (zero) value is the regular alpha blending.
  380. Blend Blend
  381. // Filter is a type of texture filter.
  382. // The default (zero) value is FilterNearest.
  383. Filter Filter
  384. // Address is a sampler address mode.
  385. // The default (zero) value is AddressUnsafe.
  386. Address Address
  387. // FillRule indicates the rule how an overlapped region is rendered.
  388. //
  389. // The rules FillRuleNonZero and FillRuleEvenOdd are useful when you want to render a complex polygon.
  390. // A complex polygon is a non-convex polygon like a concave polygon, a polygon with holes, or a self-intersecting polygon.
  391. // See examples/vector for actual usages.
  392. //
  393. // The default (zero) value is FillRuleFillAll.
  394. FillRule FillRule
  395. // AntiAlias indicates whether the rendering uses anti-alias or not.
  396. // AntiAlias is useful especially when you pass vertices from the vector package.
  397. //
  398. // AntiAlias increases internal draw calls and might affect performance.
  399. // Use the build tag `ebitenginedebug` to check the number of draw calls if you care.
  400. //
  401. // The default (zero) value is false.
  402. AntiAlias bool
  403. // DisableMipmaps disables mipmaps.
  404. // When Filter is FilterLinear and GeoM shrinks the image, mipmaps are used by default.
  405. // Mipmap is useful to render a shrunk image with high quality.
  406. // However, mipmaps can be expensive, especially on mobiles.
  407. // When DisableMipmaps is true, mipmap is not used.
  408. // When Filter is not FilterLinear, DisableMipmaps is ignored.
  409. //
  410. // The default (zero) value is false.
  411. DisableMipmaps bool
  412. }
  413. // MaxIndicesCount is the maximum number of indices for DrawTriangles and DrawTrianglesShader.
  414. //
  415. // Deprecated: as of v2.6. This constant is no longer used.
  416. const MaxIndicesCount = (1 << 16) / 3 * 3
  417. // MaxIndicesNum is the maximum number of indices for DrawTriangles and DrawTrianglesShader.
  418. //
  419. // Deprecated: as of v2.4. This constant is no longer used.
  420. const MaxIndicesNum = MaxIndicesCount
  421. // MaxVerticesCount is the maximum number of vertices for DrawTriangles and DrawTrianglesShader.
  422. //
  423. // Deprecated: as of v2.7. Use MaxVertexCount instead.
  424. const MaxVerticesCount = graphicscommand.MaxVertexCount
  425. // MaxVertexCount is the maximum number of vertices for DrawTriangles and DrawTrianglesShader.
  426. const MaxVertexCount = graphicscommand.MaxVertexCount
  427. // DrawTriangles draws triangles with the specified vertices and their indices.
  428. //
  429. // img is used as a source image. img cannot be nil.
  430. // If you want to draw triangles with a solid color, use a small white image
  431. // and adjust the color elements in the vertices. For an actual implementation,
  432. // see the example 'vector'.
  433. //
  434. // Vertex contains color values, which are interpreted as straight-alpha colors by default.
  435. // This depends on the option's ColorScaleMode.
  436. //
  437. // If len(vertices) is more than MaxVertexCount, the exceeding part is ignored.
  438. //
  439. // If len(indices) is not multiple of 3, DrawTriangles panics.
  440. //
  441. // If a value in indices is out of range of vertices, or not less than MaxVertexCount, DrawTriangles panics.
  442. //
  443. // The rule in which DrawTriangles works effectively is same as DrawImage's.
  444. //
  445. // When the given image is disposed, DrawTriangles panics.
  446. //
  447. // When the image i is disposed, DrawTriangles does nothing.
  448. func (i *Image) DrawTriangles(vertices []Vertex, indices []uint16, img *Image, options *DrawTrianglesOptions) {
  449. i.copyCheck()
  450. if img != nil && img.isDisposed() {
  451. panic("ebiten: the given image to DrawTriangles must not be disposed")
  452. }
  453. if i.isDisposed() {
  454. return
  455. }
  456. if len(vertices) > graphicscommand.MaxVertexCount {
  457. // The last part cannot be specified by indices. Just omit them.
  458. vertices = vertices[:graphicscommand.MaxVertexCount]
  459. }
  460. if len(indices)%3 != 0 {
  461. panic("ebiten: len(indices) % 3 must be 0")
  462. }
  463. for i, idx := range indices {
  464. if int(idx) >= len(vertices) {
  465. panic(fmt.Sprintf("ebiten: indices[%d] must be less than len(vertices) (%d) but was %d", i, len(vertices), idx))
  466. }
  467. }
  468. if options == nil {
  469. options = &DrawTrianglesOptions{}
  470. }
  471. var blend graphicsdriver.Blend
  472. if options.CompositeMode == CompositeModeCustom {
  473. blend = options.Blend.internalBlend()
  474. } else {
  475. blend = options.CompositeMode.blend().internalBlend()
  476. }
  477. address := builtinshader.Address(options.Address)
  478. filter := builtinshader.Filter(options.Filter)
  479. colorm, cr, cg, cb, ca := colorMToScale(options.ColorM.affineColorM())
  480. vs := i.ensureTmpVertices(len(vertices) * graphics.VertexFloatCount)
  481. dst := i
  482. if options.ColorScaleMode == ColorScaleModeStraightAlpha {
  483. // Avoid using `for i, v := range vertices` as adding `v` creates a copy from `vertices` unnecessarily on each loop (#3103).
  484. for i := range vertices {
  485. dx, dy := dst.adjustPositionF32(vertices[i].DstX, vertices[i].DstY)
  486. vs[i*graphics.VertexFloatCount] = dx
  487. vs[i*graphics.VertexFloatCount+1] = dy
  488. sx, sy := img.adjustPositionF32(vertices[i].SrcX, vertices[i].SrcY)
  489. vs[i*graphics.VertexFloatCount+2] = sx
  490. vs[i*graphics.VertexFloatCount+3] = sy
  491. vs[i*graphics.VertexFloatCount+4] = vertices[i].ColorR * vertices[i].ColorA * cr
  492. vs[i*graphics.VertexFloatCount+5] = vertices[i].ColorG * vertices[i].ColorA * cg
  493. vs[i*graphics.VertexFloatCount+6] = vertices[i].ColorB * vertices[i].ColorA * cb
  494. vs[i*graphics.VertexFloatCount+7] = vertices[i].ColorA * ca
  495. }
  496. } else {
  497. // See comment above (#3103).
  498. for i := range vertices {
  499. dx, dy := dst.adjustPositionF32(vertices[i].DstX, vertices[i].DstY)
  500. vs[i*graphics.VertexFloatCount] = dx
  501. vs[i*graphics.VertexFloatCount+1] = dy
  502. sx, sy := img.adjustPositionF32(vertices[i].SrcX, vertices[i].SrcY)
  503. vs[i*graphics.VertexFloatCount+2] = sx
  504. vs[i*graphics.VertexFloatCount+3] = sy
  505. vs[i*graphics.VertexFloatCount+4] = vertices[i].ColorR * cr
  506. vs[i*graphics.VertexFloatCount+5] = vertices[i].ColorG * cg
  507. vs[i*graphics.VertexFloatCount+6] = vertices[i].ColorB * cb
  508. vs[i*graphics.VertexFloatCount+7] = vertices[i].ColorA * ca
  509. }
  510. }
  511. is := i.ensureTmpIndices(len(indices))
  512. for i := range is {
  513. is[i] = uint32(indices[i])
  514. }
  515. srcs := [graphics.ShaderSrcImageCount]*ui.Image{img.image}
  516. useColorM := !colorm.IsIdentity()
  517. shader := builtinShader(filter, address, useColorM)
  518. i.tmpUniforms = i.tmpUniforms[:0]
  519. if useColorM {
  520. var body [16]float32
  521. var translation [4]float32
  522. colorm.Elements(body[:], translation[:])
  523. i.tmpUniforms = shader.appendUniforms(i.tmpUniforms, map[string]any{
  524. builtinshader.UniformColorMBody: body[:],
  525. builtinshader.UniformColorMTranslation: translation[:],
  526. })
  527. }
  528. skipMipmap := options.DisableMipmaps
  529. if !skipMipmap {
  530. skipMipmap = filter != builtinshader.FilterLinear
  531. }
  532. i.image.DrawTriangles(srcs, vs, is, blend, i.adjustedBounds(), [graphics.ShaderSrcImageCount]image.Rectangle{img.adjustedBounds()}, shader.shader, i.tmpUniforms, graphicsdriver.FillRule(options.FillRule), skipMipmap, options.AntiAlias, restorable.HintNone)
  533. }
  534. // DrawTrianglesShaderOptions represents options for DrawTrianglesShader.
  535. type DrawTrianglesShaderOptions struct {
  536. // CompositeMode is a composite mode to draw.
  537. // The default (zero) value is CompositeModeCustom (Blend is used).
  538. //
  539. // Deprecated: as of v2.5. Use Blend instead.
  540. CompositeMode CompositeMode
  541. // Blend is a blending way of the source color and the destination color.
  542. // Blend is used only when CompositeMode is CompositeModeCustom.
  543. // The default (zero) value is the regular alpha blending.
  544. Blend Blend
  545. // Uniforms is a set of uniform variables for the shader.
  546. // The keys are the names of the uniform variables.
  547. // The values must be a numeric type, or a slice or an array of a numeric type.
  548. // If the uniform variable type is an array, a vector or a matrix,
  549. // you have to specify linearly flattened values as a slice or an array.
  550. // For example, if the uniform variable type is [4]vec4, the length will be 16.
  551. //
  552. // If a uniform variable's name doesn't exist in Uniforms, this is treated as if zero values are specified.
  553. Uniforms map[string]any
  554. // Images is a set of the source images.
  555. // All the images' sizes must be the same.
  556. Images [4]*Image
  557. // FillRule indicates the rule how an overlapped region is rendered.
  558. //
  559. // The rules FillRuleNonZero and FillRuleEvenOdd are useful when you want to render a complex polygon.
  560. // A complex polygon is a non-convex polygon like a concave polygon, a polygon with holes, or a self-intersecting polygon.
  561. // See examples/vector for actual usages.
  562. //
  563. // The default (zero) value is FillRuleFillAll.
  564. FillRule FillRule
  565. // AntiAlias indicates whether the rendering uses anti-alias or not.
  566. // AntiAlias is useful especially when you pass vertices from the vector package.
  567. //
  568. // AntiAlias increases internal draw calls and might affect performance.
  569. // Use the build tag `ebitenginedebug` to check the number of draw calls if you care.
  570. //
  571. // The default (zero) value is false.
  572. AntiAlias bool
  573. }
  574. // Check the number of images.
  575. var _ [len(DrawTrianglesShaderOptions{}.Images) - graphics.ShaderSrcImageCount]struct{} = [0]struct{}{}
  576. // DrawTrianglesShader draws triangles with the specified vertices and their indices with the specified shader.
  577. //
  578. // Vertex contains color values, which can be interpreted for any purpose by the shader.
  579. //
  580. // For the details about the shader, see https://ebitengine.org/en/documents/shader.html.
  581. //
  582. // If the shader unit is texels, one of the specified image is non-nil and its size is different from (width, height),
  583. // DrawTrianglesShader panics.
  584. // If one of the specified image is non-nil and is disposed, DrawTrianglesShader panics.
  585. //
  586. // If len(vertices) is more than MaxVertexCount, the exceeding part is ignored.
  587. //
  588. // If len(indices) is not multiple of 3, DrawTrianglesShader panics.
  589. //
  590. // If a value in indices is out of range of vertices, or not less than MaxVertexCount, DrawTrianglesShader panics.
  591. //
  592. // When a specified image is non-nil and is disposed, DrawTrianglesShader panics.
  593. //
  594. // If a specified uniform variable's length or type doesn't match with an expected one, DrawTrianglesShader panics.
  595. //
  596. // Even if a result is an invalid color as a premultiplied-alpha color, i.e. an alpha value exceeds other color values,
  597. // the value is kept and is not clamped.
  598. //
  599. // When the image i is disposed, DrawTrianglesShader does nothing.
  600. func (i *Image) DrawTrianglesShader(vertices []Vertex, indices []uint16, shader *Shader, options *DrawTrianglesShaderOptions) {
  601. i.copyCheck()
  602. if i.isDisposed() {
  603. return
  604. }
  605. if shader.isDisposed() {
  606. panic("ebiten: the given shader to DrawTrianglesShader must not be disposed")
  607. }
  608. if len(vertices) > graphicscommand.MaxVertexCount {
  609. // The last part cannot be specified by indices. Just omit them.
  610. vertices = vertices[:graphicscommand.MaxVertexCount]
  611. }
  612. if len(indices)%3 != 0 {
  613. panic("ebiten: len(indices) % 3 must be 0")
  614. }
  615. for i, idx := range indices {
  616. if int(idx) >= len(vertices) {
  617. panic(fmt.Sprintf("ebiten: indices[%d] must be less than len(vertices) (%d) but was %d", i, len(vertices), idx))
  618. }
  619. }
  620. if options == nil {
  621. options = &DrawTrianglesShaderOptions{}
  622. }
  623. var blend graphicsdriver.Blend
  624. if options.CompositeMode == CompositeModeCustom {
  625. blend = options.Blend.internalBlend()
  626. } else {
  627. blend = options.CompositeMode.blend().internalBlend()
  628. }
  629. vs := i.ensureTmpVertices(len(vertices) * graphics.VertexFloatCount)
  630. dst := i
  631. src := options.Images[0]
  632. // Avoid using `for i, v := range vertices` as adding `v` creates a copy from `vertices` unnecessarily on each loop (#3103).
  633. for i := range vertices {
  634. dx, dy := dst.adjustPositionF32(vertices[i].DstX, vertices[i].DstY)
  635. vs[i*graphics.VertexFloatCount] = dx
  636. vs[i*graphics.VertexFloatCount+1] = dy
  637. sx, sy := vertices[i].SrcX, vertices[i].SrcY
  638. if src != nil {
  639. sx, sy = src.adjustPositionF32(sx, sy)
  640. }
  641. vs[i*graphics.VertexFloatCount+2] = sx
  642. vs[i*graphics.VertexFloatCount+3] = sy
  643. vs[i*graphics.VertexFloatCount+4] = vertices[i].ColorR
  644. vs[i*graphics.VertexFloatCount+5] = vertices[i].ColorG
  645. vs[i*graphics.VertexFloatCount+6] = vertices[i].ColorB
  646. vs[i*graphics.VertexFloatCount+7] = vertices[i].ColorA
  647. vs[i*graphics.VertexFloatCount+8] = vertices[i].Custom0
  648. vs[i*graphics.VertexFloatCount+9] = vertices[i].Custom1
  649. vs[i*graphics.VertexFloatCount+10] = vertices[i].Custom2
  650. vs[i*graphics.VertexFloatCount+11] = vertices[i].Custom3
  651. }
  652. is := i.ensureTmpIndices(len(indices))
  653. for i := range is {
  654. is[i] = uint32(indices[i])
  655. }
  656. var imgs [graphics.ShaderSrcImageCount]*ui.Image
  657. var imgSize image.Point
  658. for i, img := range options.Images {
  659. if img == nil {
  660. continue
  661. }
  662. if img.isDisposed() {
  663. panic("ebiten: the given image to DrawTrianglesShader must not be disposed")
  664. }
  665. if shader.unit == shaderir.Texels {
  666. if i == 0 {
  667. imgSize = img.Bounds().Size()
  668. } else {
  669. // TODO: Check imgw > 0 && imgh > 0
  670. if img.Bounds().Size() != imgSize {
  671. panic("ebiten: all the source images must be the same size with the rectangle")
  672. }
  673. }
  674. }
  675. imgs[i] = img.image
  676. }
  677. var srcRegions [graphics.ShaderSrcImageCount]image.Rectangle
  678. for i, img := range options.Images {
  679. if img == nil {
  680. continue
  681. }
  682. srcRegions[i] = img.adjustedBounds()
  683. }
  684. i.tmpUniforms = i.tmpUniforms[:0]
  685. i.tmpUniforms = shader.appendUniforms(i.tmpUniforms, options.Uniforms)
  686. i.image.DrawTriangles(imgs, vs, is, blend, i.adjustedBounds(), srcRegions, shader.shader, i.tmpUniforms, graphicsdriver.FillRule(options.FillRule), true, options.AntiAlias, restorable.HintNone)
  687. }
  688. // DrawRectShaderOptions represents options for DrawRectShader.
  689. type DrawRectShaderOptions struct {
  690. // GeoM is a geometry matrix to draw.
  691. // The default (zero) value is identity, which draws the rectangle at (0, 0).
  692. GeoM GeoM
  693. // ColorScale is a scale of color.
  694. // This scaling values are passed to the `color vec4` argument of the Fragment function in a Kage program.
  695. // The default (zero) value is identity, which is (1, 1, 1, 1).
  696. ColorScale ColorScale
  697. // CompositeMode is a composite mode to draw.
  698. // The default (zero) value is CompositeModeCustom (Blend is used).
  699. //
  700. // Deprecated: as of v2.5. Use Blend instead.
  701. CompositeMode CompositeMode
  702. // Blend is a blending way of the source color and the destination color.
  703. // Blend is used only when CompositeMode is CompositeModeCustom.
  704. // The default (zero) value is the regular alpha blending.
  705. Blend Blend
  706. // Uniforms is a set of uniform variables for the shader.
  707. // The keys are the names of the uniform variables.
  708. // The values must be a numeric type, or a slice or an array of a numeric type.
  709. // If the uniform variable type is an array, a vector or a matrix,
  710. // you have to specify linearly flattened values as a slice or an array.
  711. // For example, if the uniform variable type is [4]vec4, the length will be 16.
  712. //
  713. // If a uniform variable's name doesn't exist in Uniforms, this is treated as if zero values are specified.
  714. Uniforms map[string]any
  715. // Images is a set of the source images.
  716. // All the images' sizes must be the same.
  717. Images [4]*Image
  718. }
  719. // Check the number of images.
  720. var _ [len(DrawRectShaderOptions{}.Images)]struct{} = [graphics.ShaderSrcImageCount]struct{}{}
  721. // DrawRectShader draws a rectangle with the specified width and height with the specified shader.
  722. //
  723. // For the details about the shader, see https://ebitengine.org/en/documents/shader.html.
  724. //
  725. // When one of the specified image is non-nil and its size is different from (width, height), DrawRectShader panics.
  726. // When one of the specified image is non-nil and is disposed, DrawRectShader panics.
  727. //
  728. // If a specified uniform variable's length or type doesn't match with an expected one, DrawRectShader panics.
  729. //
  730. // In a shader, srcPos in Fragment represents a position in a source image.
  731. // If no source images are specified, srcPos represents the position from (0, 0) to (width, height) in pixels.
  732. // If the unit is pixels by a compiler directive `//kage:unit pixelss`, srcPos values are valid.
  733. // If the unit is texels (default), srcPos values still take from (0, 0) to (width, height),
  734. // but these are invalid since srcPos is expected to be in texels in the texel-unit mode.
  735. // This behavior is preserved for backward compatibility. It is recommended to use the pixel-unit mode to avoid confusion.
  736. //
  737. // If no source images are specified, imageSrc0Size returns a valid size only when the unit is pixels,
  738. // but always returns 0 when the unit is texels (default).
  739. //
  740. // Even if a result is an invalid color as a premultiplied-alpha color, i.e. an alpha value exceeds other color values,
  741. // the value is kept and is not clamped.
  742. //
  743. // When the image i is disposed, DrawRectShader does nothing.
  744. func (i *Image) DrawRectShader(width, height int, shader *Shader, options *DrawRectShaderOptions) {
  745. i.copyCheck()
  746. if i.isDisposed() {
  747. return
  748. }
  749. if shader.isDisposed() {
  750. panic("ebiten: the given shader to DrawRectShader must not be disposed")
  751. }
  752. if options == nil {
  753. options = &DrawRectShaderOptions{}
  754. }
  755. var blend graphicsdriver.Blend
  756. if options.CompositeMode == CompositeModeCustom {
  757. blend = options.Blend.internalBlend()
  758. } else {
  759. blend = options.CompositeMode.blend().internalBlend()
  760. }
  761. var imgs [graphics.ShaderSrcImageCount]*ui.Image
  762. for i, img := range options.Images {
  763. if img == nil {
  764. continue
  765. }
  766. if img.isDisposed() {
  767. panic("ebiten: the given image to DrawRectShader must not be disposed")
  768. }
  769. if img.Bounds().Size() != image.Pt(width, height) {
  770. panic("ebiten: all the source images must be the same size with the rectangle")
  771. }
  772. imgs[i] = img.image
  773. }
  774. var srcRegions [graphics.ShaderSrcImageCount]image.Rectangle
  775. for i, img := range options.Images {
  776. if img == nil {
  777. if shader.unit == shaderir.Pixels && i == 0 {
  778. // Give the source size as pixels only when the unit is pixels so that users can get the source size via imageSrc0Size (#2166).
  779. // With the texel mode, the imageSrc0Origin and imageSrc0Size values should be in texels so the source position in pixels would not match.
  780. srcRegions[i] = image.Rect(0, 0, width, height)
  781. }
  782. continue
  783. }
  784. srcRegions[i] = img.adjustedBounds()
  785. }
  786. geoM := options.GeoM
  787. if offsetX, offsetY := i.adjustPosition(0, 0); offsetX != 0 || offsetY != 0 {
  788. geoM.Translate(float64(offsetX), float64(offsetY))
  789. }
  790. a, b, c, d, tx, ty := geoM.elements32()
  791. if det := a*d - b*c; det == 0 {
  792. return
  793. }
  794. cr, cg, cb, ca := options.ColorScale.elements()
  795. vs := i.ensureTmpVertices(4 * graphics.VertexFloatCount)
  796. // Do not use srcRegions[0].Dx() and srcRegions[0].Dy() as these might be empty.
  797. graphics.QuadVerticesFromSrcAndMatrix(vs,
  798. float32(srcRegions[0].Min.X), float32(srcRegions[0].Min.Y),
  799. float32(srcRegions[0].Min.X+width), float32(srcRegions[0].Min.Y+height),
  800. a, b, c, d, tx, ty, cr, cg, cb, ca)
  801. is := graphics.QuadIndices()
  802. i.tmpUniforms = i.tmpUniforms[:0]
  803. i.tmpUniforms = shader.appendUniforms(i.tmpUniforms, options.Uniforms)
  804. dr := i.adjustedBounds()
  805. hint := restorable.HintNone
  806. // Do not use srcRegions[0].Dx() and srcRegions[0].Dy() as these might be empty.
  807. if overwritesDstRegion(options.Blend, dr, geoM, srcRegions[0].Min.X, srcRegions[0].Min.Y, srcRegions[0].Min.X+width, srcRegions[0].Min.Y+height) {
  808. hint = restorable.HintOverwriteDstRegion
  809. }
  810. i.image.DrawTriangles(imgs, vs, is, blend, dr, srcRegions, shader.shader, i.tmpUniforms, graphicsdriver.FillRuleFillAll, true, false, hint)
  811. }
  812. // SubImage returns an image representing the portion of the image p visible through r.
  813. // The returned value shares pixels with the original image.
  814. //
  815. // The returned value is always *ebiten.Image.
  816. //
  817. // If the image is disposed, SubImage returns nil.
  818. //
  819. // A sub-image returned by SubImage can be used as a rendering source and a rendering destination.
  820. // If a sub-image is used as a rendering source, the image is used as if it is a small image.
  821. // If a sub-image is used as a rendering destination, the region being rendered is clipped.
  822. //
  823. // Successive uses of multiple various regions as rendering destination is still efficient
  824. // when all the underlying images are the same, but some platforms like browsers might not work efficiently.
  825. func (i *Image) SubImage(r image.Rectangle) image.Image {
  826. i.copyCheck()
  827. if i.isDisposed() {
  828. return nil
  829. }
  830. r = r.Intersect(i.Bounds())
  831. // Need to check Empty explicitly. See the standard image package implementations.
  832. if r.Empty() {
  833. r = image.ZR
  834. }
  835. var orig = i
  836. if i.isSubImage() {
  837. orig = i.original
  838. }
  839. img := &Image{
  840. image: i.image,
  841. bounds: r,
  842. original: orig,
  843. }
  844. img.addr = img
  845. return img
  846. }
  847. // Bounds returns the bounds of the image.
  848. //
  849. // Bounds implements the standard image.Image's Bounds.
  850. func (i *Image) Bounds() image.Rectangle {
  851. if i.isDisposed() {
  852. panic("ebiten: the image is already disposed")
  853. }
  854. return i.bounds
  855. }
  856. // ColorModel returns the color model of the image.
  857. //
  858. // ColorModel implements the standard image.Image's ColorModel.
  859. func (i *Image) ColorModel() color.Model {
  860. return color.RGBAModel
  861. }
  862. // ReadPixels reads the image's pixels from the image.
  863. //
  864. // The given pixels represent RGBA pre-multiplied alpha values.
  865. //
  866. // ReadPixels loads pixels from GPU to system memory if necessary, which means that ReadPixels can be slow.
  867. //
  868. // ReadPixels always sets a transparent color if the image is disposed.
  869. //
  870. // len(pixels) must be 4 * (bounds width) * (bounds height).
  871. // If len(pixels) is not correct, ReadPixels panics.
  872. //
  873. // ReadPixels also works on a sub-image.
  874. //
  875. // Note that an important logic should not rely on values returned by ReadPixels, since
  876. // the returned values can include very slight differences between some machines.
  877. //
  878. // ReadPixels can't be called outside the main loop (ebiten.Run's updating function) starts.
  879. func (i *Image) ReadPixels(pixels []byte) {
  880. b := i.Bounds()
  881. if got, want := len(pixels), 4*b.Dx()*b.Dy(); got != want {
  882. panic(fmt.Sprintf("ebiten: len(pixels) must be %d but %d at ReadPixels", want, got))
  883. }
  884. if i.isDisposed() {
  885. for i := range pixels {
  886. pixels[i] = 0
  887. }
  888. return
  889. }
  890. i.image.ReadPixels(pixels, i.adjustedBounds())
  891. }
  892. // At returns the color of the image at (x, y).
  893. //
  894. // At implements the standard image.Image's At.
  895. //
  896. // At loads pixels from GPU to system memory if necessary, which means that At can be slow.
  897. //
  898. // At always returns a transparent color if the image is disposed.
  899. //
  900. // Note that an important logic should not rely on values returned by At, since
  901. // the returned values can include very slight differences between some machines.
  902. //
  903. // At can't be called outside the main loop (ebiten.Run's updating function) starts.
  904. func (i *Image) At(x, y int) color.Color {
  905. r, g, b, a := i.at(x, y)
  906. return color.RGBA{R: r, G: g, B: b, A: a}
  907. }
  908. // RGBA64At implements the standard image.RGBA64Image's RGBA64At.
  909. //
  910. // RGBA64At loads pixels from GPU to system memory if necessary, which means
  911. // that RGBA64At can be slow.
  912. //
  913. // RGBA64At always returns a transparent color if the image is disposed.
  914. //
  915. // Note that an important logic should not rely on values returned by RGBA64At,
  916. // since the returned values can include very slight differences between some machines.
  917. //
  918. // RGBA64At can't be called outside the main loop (ebiten.Run's updating function) starts.
  919. func (i *Image) RGBA64At(x, y int) color.RGBA64 {
  920. r, g, b, a := i.at(x, y)
  921. return color.RGBA64{R: uint16(r) * 0x101, G: uint16(g) * 0x101, B: uint16(b) * 0x101, A: uint16(a) * 0x101}
  922. }
  923. func (i *Image) at(x, y int) (r, g, b, a byte) {
  924. if i.isDisposed() {
  925. return 0, 0, 0, 0
  926. }
  927. if !image.Pt(x, y).In(i.Bounds()) {
  928. return 0, 0, 0, 0
  929. }
  930. x, y = i.adjustPosition(x, y)
  931. var pix [4]byte
  932. i.image.ReadPixels(pix[:], image.Rect(x, y, x+1, y+1))
  933. return pix[0], pix[1], pix[2], pix[3]
  934. }
  935. // Set sets the color at (x, y).
  936. //
  937. // Set implements the standard draw.Image's Set.
  938. //
  939. // Even if a result is an invalid color as a premultiplied-alpha color, i.e. an alpha value exceeds other color values,
  940. // the value is kept and is not clamped.
  941. //
  942. // If the image is disposed, Set does nothing.
  943. func (i *Image) Set(x, y int, clr color.Color) {
  944. i.copyCheck()
  945. if i.isDisposed() {
  946. return
  947. }
  948. if !image.Pt(x, y).In(i.Bounds()) {
  949. return
  950. }
  951. if i.isSubImage() {
  952. i = i.original
  953. }
  954. dx, dy := i.adjustPosition(x, y)
  955. cr, cg, cb, ca := clr.RGBA()
  956. i.image.WritePixels([]byte{byte(cr >> 8), byte(cg >> 8), byte(cb >> 8), byte(ca >> 8)}, image.Rect(dx, dy, dx+1, dy+1))
  957. }
  958. // Dispose disposes the image data.
  959. // After disposing, most of the image functions do nothing and returns meaningless values.
  960. //
  961. // Calling Dispose is not mandatory. GC automatically collects internal resources that no objects refer to.
  962. // However, calling Dispose explicitly is helpful if memory usage matters.
  963. //
  964. // If the image is a sub-image, Dispose does nothing.
  965. //
  966. // If the image is disposed, Dispose does nothing.
  967. //
  968. // Deprecated: as of v2.7. Use Deallocate instead.
  969. func (i *Image) Dispose() {
  970. i.copyCheck()
  971. if i.isDisposed() {
  972. return
  973. }
  974. if i.isSubImage() {
  975. return
  976. }
  977. i.image.Deallocate()
  978. i.image = nil
  979. }
  980. // Deallocate clears the image and deallocates the internal state of the image.
  981. // Even after Deallocate is called, the image is still available.
  982. // In this case, the image's internal state is allocated again.
  983. //
  984. // Usually, you don't have to call Deallocate since the internal state is automatically released by GC.
  985. // However, if you are sure that the image is no longer used but not sure how this image object is referred,
  986. // you can call Deallocate to make sure that the internal state is deallocated.
  987. //
  988. // If the image is a sub-image, Deallocate does nothing.
  989. //
  990. // If the image is disposed, Deallocate does nothing.
  991. func (i *Image) Deallocate() {
  992. i.copyCheck()
  993. if i.isDisposed() {
  994. return
  995. }
  996. if i.isSubImage() {
  997. return
  998. }
  999. i.image.Deallocate()
  1000. }
  1001. // WritePixels replaces the pixels of the image.
  1002. //
  1003. // The given pixels are treated as RGBA pre-multiplied alpha values.
  1004. //
  1005. // len(pix) must be 4 * (bounds width) * (bounds height).
  1006. // If len(pix) is not correct, WritePixels panics.
  1007. //
  1008. // WritePixels also works on a sub-image.
  1009. //
  1010. // Even if a result is an invalid color as a premultiplied-alpha color, i.e. an alpha value exceeds other color values,
  1011. // the value is kept and is not clamped.
  1012. //
  1013. // When the image is disposed, WritePixels does nothing.
  1014. func (i *Image) WritePixels(pixels []byte) {
  1015. i.copyCheck()
  1016. if i.isDisposed() {
  1017. return
  1018. }
  1019. // Do not need to copy pixels here.
  1020. // * In internal/mipmap, pixels are copied when necessary.
  1021. // * In internal/atlas, pixels are copied to make its paddings.
  1022. i.image.WritePixels(pixels, i.adjustedBounds())
  1023. }
  1024. // ReplacePixels replaces the pixels of the image.
  1025. //
  1026. // Deprecated: as of v2.4. Use WritePixels instead.
  1027. func (i *Image) ReplacePixels(pixels []byte) {
  1028. i.WritePixels(pixels)
  1029. }
  1030. // NewImage returns an empty image.
  1031. //
  1032. // If width or height is less than 1 or more than device-dependent maximum size, NewImage panics.
  1033. //
  1034. // NewImage should be called only when necessary.
  1035. // For example, you should avoid to call NewImage every Update or Draw call.
  1036. // Reusing the same image by Clear is much more efficient than creating a new image.
  1037. //
  1038. // NewImage panics if RunGame already finishes.
  1039. func NewImage(width, height int) *Image {
  1040. return newImage(image.Rect(0, 0, width, height), atlas.ImageTypeRegular)
  1041. }
  1042. // NewImageOptions represents options for NewImage.
  1043. type NewImageOptions struct {
  1044. // Unmanaged represents whether the image is unmanaged or not.
  1045. // The default (zero) value is false, that means the image is managed.
  1046. //
  1047. // An unmanaged image is never on an internal automatic texture atlas.
  1048. // A regular image is a part of an internal texture atlas, and locating them is done automatically in Ebitengine.
  1049. // Unmanaged is useful when you want finer controls over the image for performance and memory reasons.
  1050. Unmanaged bool
  1051. }
  1052. // NewImageWithOptions returns an empty image with the given bounds and the options.
  1053. //
  1054. // If width or height is less than 1 or more than device-dependent maximum size, NewImageWithOptions panics.
  1055. //
  1056. // The rendering origin position is (0, 0) of the given bounds.
  1057. // If DrawImage is called on a new image created by NewImageOptions,
  1058. // for example, the center of scaling and rotating is (0, 0), that might not be an upper-left position.
  1059. //
  1060. // If options is nil, the default setting is used.
  1061. //
  1062. // NewImageWithOptions should be called only when necessary.
  1063. // For example, you should avoid to call NewImageWithOptions every Update or Draw call.
  1064. // Reusing the same image by Clear is much more efficient than creating a new image.
  1065. //
  1066. // NewImageWithOptions panics if RunGame already finishes.
  1067. func NewImageWithOptions(bounds image.Rectangle, options *NewImageOptions) *Image {
  1068. imageType := atlas.ImageTypeRegular
  1069. if options != nil && options.Unmanaged {
  1070. imageType = atlas.ImageTypeUnmanaged
  1071. }
  1072. return newImage(bounds, imageType)
  1073. }
  1074. func newImage(bounds image.Rectangle, imageType atlas.ImageType) *Image {
  1075. if isRunGameEnded() {
  1076. panic(fmt.Sprintf("ebiten: NewImage cannot be called after RunGame finishes"))
  1077. }
  1078. width, height := bounds.Dx(), bounds.Dy()
  1079. if width <= 0 {
  1080. panic(fmt.Sprintf("ebiten: width at NewImage must be positive but %d", width))
  1081. }
  1082. if height <= 0 {
  1083. panic(fmt.Sprintf("ebiten: height at NewImage must be positive but %d", height))
  1084. }
  1085. i := &Image{
  1086. image: ui.Get().NewImage(width, height, imageType),
  1087. bounds: bounds,
  1088. }
  1089. i.addr = i
  1090. return i
  1091. }
  1092. // NewImageFromImage creates a new image with the given image (source).
  1093. //
  1094. // If source's width or height is less than 1 or more than device-dependent maximum size, NewImageFromImage panics.
  1095. //
  1096. // NewImageFromImage should be called only when necessary.
  1097. // For example, you should avoid to call NewImageFromImage every Update or Draw call.
  1098. // Reusing the same image by Clear and WritePixels is much more efficient than creating a new image.
  1099. //
  1100. // NewImageFromImage panics if RunGame already finishes.
  1101. //
  1102. // The returned image's upper-left position is always (0, 0). The source's bounds are not respected.
  1103. func NewImageFromImage(source image.Image) *Image {
  1104. return NewImageFromImageWithOptions(source, nil)
  1105. }
  1106. // NewImageFromImageOptions represents options for NewImageFromImage.
  1107. type NewImageFromImageOptions struct {
  1108. // Unmanaged represents whether the image is unmanaged or not.
  1109. // The default (zero) value is false, that means the image is managed.
  1110. //
  1111. // An unmanaged image is never on an internal automatic texture atlas.
  1112. // A regular image is a part of an internal texture atlas, and locating them is done automatically in Ebitengine.
  1113. // Unmanaged is useful when you want finer controls over the image for performance and memory reasons.
  1114. Unmanaged bool
  1115. // PreserveBounds represents whether the new image's bounds are the same as the given image.
  1116. // The default (zero) value is false, that means the new image's upper-left position is adjusted to (0, 0).
  1117. PreserveBounds bool
  1118. }
  1119. // NewImageFromImageWithOptions creates a new image with the given image (source) with the given options.
  1120. //
  1121. // If source's width or height is less than 1 or more than device-dependent maximum size, NewImageFromImageWithOptions panics.
  1122. //
  1123. // If options is nil, the default setting is used.
  1124. //
  1125. // NewImageFromImageWithOptions should be called only when necessary.
  1126. // For example, you should avoid to call NewImageFromImageWithOptions every Update or Draw call.
  1127. // Reusing the same image by Clear and WritePixels is much more efficient than creating a new image.
  1128. //
  1129. // NewImageFromImageWithOptions panics if RunGame already finishes.
  1130. func NewImageFromImageWithOptions(source image.Image, options *NewImageFromImageOptions) *Image {
  1131. if options == nil {
  1132. options = &NewImageFromImageOptions{}
  1133. }
  1134. var r image.Rectangle
  1135. if options.PreserveBounds {
  1136. r = source.Bounds()
  1137. } else {
  1138. size := source.Bounds().Size()
  1139. r = image.Rect(0, 0, size.X, size.Y)
  1140. }
  1141. i := NewImageWithOptions(r, &NewImageOptions{
  1142. Unmanaged: options.Unmanaged,
  1143. })
  1144. // If the given image is an Ebitengine image, use DrawImage instead of reading pixels from the source.
  1145. // This works even before the game loop runs.
  1146. if source, ok := source.(*Image); ok {
  1147. op := &DrawImageOptions{}
  1148. if options.PreserveBounds {
  1149. b := source.Bounds()
  1150. op.GeoM.Translate(float64(b.Min.X), float64(b.Min.Y))
  1151. }
  1152. i.DrawImage(source, op)
  1153. return i
  1154. }
  1155. i.WritePixels(imageToBytes(source))
  1156. return i
  1157. }
  1158. // colorMToScale returns a new color matrix and color scales that equal to the given matrix in terms of the effect.
  1159. //
  1160. // If the given matrix is merely a scaling matrix, colorMToScale returns
  1161. // an identity matrix and its scaling factors in premultiplied-alpha format.
  1162. // This is useful to optimize the rendering speed by avoiding the use of the
  1163. // color matrix and instead multiplying all vertex colors by the scale.
  1164. func colorMToScale(colorm affine.ColorM) (newColorM affine.ColorM, r, g, b, a float32) {
  1165. if colorm.IsIdentity() {
  1166. return colorm, 1, 1, 1, 1
  1167. }
  1168. if !colorm.ScaleOnly() {
  1169. return colorm, 1, 1, 1, 1
  1170. }
  1171. r = colorm.At(0, 0)
  1172. g = colorm.At(1, 1)
  1173. b = colorm.At(2, 2)
  1174. a = colorm.At(3, 3)
  1175. // Color matrices work on non-premultiplied colors.
  1176. // This color matrix can only make colors darker or equal,
  1177. // and thus can never invoke color clamping.
  1178. // Thus the simpler vertex color scale based shader can be used.
  1179. //
  1180. // Negative color values can become positive and out-of-range
  1181. // after applying to vertex colors below, which can make the min() in the shader kick in.
  1182. //
  1183. // Alpha values smaller than 0, combined with negative vertex colors,
  1184. // can also make the min() kick in, so that shall be ruled out too.
  1185. if r < 0 || g < 0 || b < 0 || a < 0 || r > 1 || g > 1 || b > 1 {
  1186. return colorm, 1, 1, 1, 1
  1187. }
  1188. return affine.ColorMIdentity{}, r * a, g * a, b * a, a
  1189. }
  1190. func (i *Image) ensureTmpVertices(n int) []float32 {
  1191. if cap(i.tmpVertices) < n {
  1192. i.tmpVertices = make([]float32, n)
  1193. }
  1194. return i.tmpVertices[:n]
  1195. }
  1196. func (i *Image) ensureTmpIndices(n int) []uint32 {
  1197. if cap(i.tmpIndices) < n {
  1198. i.tmpIndices = make([]uint32, n)
  1199. }
  1200. return i.tmpIndices[:n]
  1201. }
  1202. // private implements FinalScreen.
  1203. func (*Image) private() {
  1204. }