Debian Codegraph @

vendor/github.com/xyproto/gfx/tiles.go

raw
1 package gfx
2
3 import "image"
4
5 // Tiles is a slice of paletted images.
6 type Tiles []PalettedImage
7
8 // Tileset is a paletted tileset.
9 type Tileset struct {
10 Palette Palette // Palette of the tileset.
11 Size image.Point // Size is the size of each tile.
12 Tiles Tiles // Images contains all of the images in the tileset.
13 }
14
15 // TilesetData is the raw data in a tileset
16 type TilesetData [][]uint8
17
18 // NewTileset creates a new paletted tileset.
19 func NewTileset(p Palette, s image.Point, td TilesetData) *Tileset {
20 ts := &Tileset{Palette: p, Size: s}
21
22 for i := 0; i < len(td); i++ {
23 ts.Tiles = append(ts.Tiles, NewTile(p, s.X, td[i]))
24 }
25
26 return ts
27 }
28
29 // NewTilesetFromImage creates a new paletted tileset based on the provided palette, tile size and image.
30 func NewTilesetFromImage(p Palette, tileSize image.Point, src image.Image) *Tileset {
31 cols := src.Bounds().Dx() / tileSize.X
32 rows := src.Bounds().Dy() / tileSize.Y
33
34 tiles := make(Tiles, cols*rows)
35
36 for row := 0; row < rows; row++ {
37 for col := 0; col < cols; col++ {
38 t := NewPaletted(tileSize.X, tileSize.Y, p)
39
40 DrawSrc(t, t.Bounds(), src, Pt(col*tileSize.X, row*tileSize.Y))
41
42 i := (row * cols) + col
43
44 tiles[i] = t
45 }
46 }
47
48 return &Tileset{Palette: p, Size: tileSize, Tiles: tiles}
49 }
50
51 // NewTile returns a new paletted image with the given pix, stride and palette.
52 func NewTile(p Palette, cols int, pix []uint8) *Paletted {
53 return &Paletted{
54 Palette: p,
55 Stride: cols,
56 Pix: pix,
57 Rect: calcRect(cols, pix),
58 }
59 }
60
61 func calcRect(cols int, pix []uint8) image.Rectangle {
62 s := calcSize(cols, pix)
63
64 return IR(0, 0, s.X, s.Y)
65 }
66
67 func calcSize(cols int, pix []uint8) image.Point {
68 l := len(pix)
69
70 if l < cols {
71 return Pt(cols, 1)
72 }
73
74 rows := l / cols
75
76 if rows*cols == l {
77 return Pt(cols, rows)
78 }
79
80 if rows%cols > 0 {
81 rows++
82 }
83
84 return Pt(cols, rows)
85 }