/
sheet.go
313 lines (262 loc) · 6.4 KB
/
sheet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
package pck
import (
"image"
"image/draw"
"math"
"strconv"
"strings"
"github.com/jakubDoka/mlok/ggl"
"github.com/jakubDoka/mlok/ggl/txt"
"github.com/jakubDoka/mlok/mat"
"github.com/jakubDoka/gogen/dirs"
"github.com/jakubDoka/gogen/str"
)
/*imp(
github.com/jakubDoka/gogen/templates
)*/
/*gen(
templates.Data<PicData, Data>
)*/
// PicData is data related to picture
type PicData struct {
Name string
bounds mat.AABB
Img draw.Image
drawer *txt.Drawer
}
// NPicData creates Slice of PicData from texture paths, it flips the textures
// so they are not upside down
func (d *Data) AddImages(paths ...string) error {
data := *d
for _, v := range paths {
d := PicData{}
d.Name = v
img, err := ggl.LoadImage(v)
if err != nil {
return err
}
ggl.FlipNRGBA(img)
d.Img = img
data = append(data, d)
}
*d = data
return nil
}
// AddMarkdown adds markdown font textures into Data
func (v *Data) AddMarkdown(m *txt.Markdown) {
for _, font := range m.Fonts {
*v = append(*v, PicData{
Name: font.Name,
Img: font.Pic,
drawer: font,
})
}
}
// Sheet contains sprite sheet and Regions
type Sheet struct {
Data
Root string
Pic *image.NRGBA
Regions map[string]mat.AABB
}
// NSheet creates new sheet containing textures from given paths
func NSheet(root string, paths ...string) (sh *Sheet, err error) {
sh = &Sheet{
Root: root,
}
err = sh.AddImages(paths...)
if err != nil {
return
}
sh.Pack()
return sh, nil
}
// Pack takes all Data in sheet and translates it into one packed image
// and regions, regarding the current Root the names will be modified, for
// example if root is "root" then "something/root/anything.png" will be saved under
// kay with value "anything" into s.Regions
func (s *Sheet) Pack() {
if len(s.Data) == 0 {
return
}
if s.Regions == nil {
s.Regions = map[string]mat.AABB{}
}
// cleanup
for k := range s.Regions {
delete(s.Regions, k)
}
for i := range s.Data {
d := &s.Data[i]
d.bounds = mat.FromRect(d.Img.Bounds()).ToVec().ToAABB()
}
w, h := Pack(s.Data)
bounds := image.Rect(0, 0, w, h)
s.Pic = image.NewNRGBA(bounds)
for _, d := range s.Data {
r := d.bounds.ToImage()
draw.Draw(s.Pic, r, d.Img, d.Img.Bounds().Min, draw.Over)
name, w, h, ok := DetectSpritesheet(d.Name, s.Root)
if ok {
w := float64(w)
h := float64(h)
for y, n := d.bounds.Max.Y, 0; y > d.bounds.Min.Y; y -= h {
for x := d.bounds.Min.X; x < d.bounds.Max.X; x += w {
n++
s.Regions[name+strconv.Itoa(n)] = mat.A(x, y-h, x+w, y)
}
}
} else {
s.Regions[name] = d.bounds
if d.drawer != nil {
d.drawer.Region = d.bounds.Min
}
}
}
s.Regions["All"] = mat.A(0, 0, float64(w), float64(h))
return
}
// Sprite returns sprite for region of given name
func (s *Sheet) Sprite(name string) (ggl.Sprite, bool) {
reg, ok := s.Regions[name]
return ggl.NSprite(reg), ok
}
// Batch returns batch for this sheet that can be used with sprites
func (s *Sheet) Batch() ggl.Batch {
return ggl.Batch{
Texture: ggl.NTexture(s.Pic, false),
}
}
// Pack packs rectangles in reasonable way, it tries to achieve
// size efficiency not speed
func Pack(data Data) (width, height int) {
// to guarantee that rect that is first in the row is highest
data.Sort(func(a, b PicData) bool {
return a.bounds.H() > b.bounds.H()
})
count := len(data)
if count == 1 { // useless, bail
return int(data[0].bounds.W()), int(data[0].bounds.H())
}
var (
point = calcOptimalSide(data)
lowestRatio = math.MaxFloat64
best, breakpoints []int
)
o:
for point < count {
var length float64
for i := 0; i < point; i++ {
length += data[i].bounds.W()
}
// it would result to infinit loop if there is rectangle that is wider then length
// si increase length and try again
for i := point; i < count; i++ {
if data[i].bounds.W() > length {
point++
continue o
}
}
var current int
breakpoints = breakpoints[:0]
// finding breakpoints
for current < count {
var total float64
breakpoints = append(breakpoints, current)
for current < count {
total += data[current].bounds.W()
if total > length {
break
}
current++
}
}
// calculating height of final cube for ratio
var tollness float64
for _, v := range breakpoints {
tollness += data[v].bounds.H()
}
// idk, it just kinda works like this
ratio := length*tollness/300 + math.Abs(length-tollness)
// deciding if we should stop, as long as ratio is decreasing continue, when it goes up, stop
if ratio < lowestRatio {
lowestRatio = ratio
best = append(best[:0], breakpoints...)
width = int(length)
height = int(tollness)
} else if ratio > lowestRatio {
break
}
point++
}
// modifying pic data according to best breakpoints
best = append(best, count)
offset := mat.ZV
for i := 0; i < len(best)-1; i++ {
// best can look like [0, 3, 6, 9] if there are 2 breakpoints on 3 and 6
for j := best[i]; j < best[i+1]; j++ {
data[j].bounds = data[j].bounds.Moved(offset)
offset.X += data[j].bounds.W()
}
offset.Y += data[best[i]].bounds.H()
offset.X = 0.0
}
return width, height
}
// calcOptimalArea calculates the most optimal rectangle
// that could theoretically be build from given data, side
// will be exactly correct only if all inputted rectangles
// are of same size
func calcOptimalSide(data Data) int {
// calculate total area
var area float64
for _, p := range data {
area += p.bounds.Area()
}
// side of square
side := math.Sqrt(area)
// find the break point
for i, p := range data {
side -= p.bounds.W()
if side <= 0 {
return i
}
}
return 0
}
// DetectSpritesheet parses name of texture into spritesheet if name is in format:
//
// name_width_height.ext
//
// where width hight are parameters of one sheet cell
func DetectSpritesheet(path, root string) (name string, w, h int, ok bool) {
idx := strings.LastIndex(path, ".")
if idx != -1 {
path = path[:idx] // remove extencion
}
path = dirs.NormPath(path) // fix slashes
// remove unimportant part of path
if root != "" {
parts := str.RevSplit(path, "/"+root+"/", 2)
path = parts[len(parts)-1]
}
// split to name, width, height
parts := str.RevSplit(path, "_", 3)
name = path
// parse numbers
if len(parts) == 3 {
var err error
w, err = strconv.Atoi(parts[1])
if err != nil {
return
}
h, err = strconv.Atoi(parts[2])
if err != nil {
return
}
name = parts[0]
ok = true
return
}
return
}