gamnit: implement new `TextSprites` settings in `BMFont`
[nit.git] / lib / gamnit / bmfont.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
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 # Parse Angel Code BMFont format and draw text
16 #
17 # The BMFont format supports packed textures, varying advance per character and
18 # even kernings. It can be generated with a number of tools, inluding:
19 # * BMFont, free software Windows app, http://www.angelcode.com/products/bmfont/
20 # * Littera, a web app, http://kvazars.com/littera/
21 #
22 # Format reference: http://www.angelcode.com/products/bmfont/doc/file_format.html
23 module bmfont
24
25 private import dom
26
27 intrude import font
28
29 # BMFont description, parsed with `Text::parse_bmfont` or loaded as a `BMFontAsset`
30 #
31 # This class flattens all the `info` and `common` data.
32 class BMFont
33
34 # ---
35 # info part
36 #
37 # How the font was generated.
38
39 # Name of the source true type font
40 var face: Text
41
42 # Size of the source true type font
43 var size: Float
44
45 # Is the font bold?
46 var bold: Bool
47
48 # Is the font italic?
49 var italic: Bool
50
51 # Does the font uses the Unicode charset?
52 var unicode: Bool
53
54 # Padding for each character
55 #
56 # In the format `up,right,down,left`
57 var padding: String
58
59 # Spacing for each character
60 #
61 # In the format `horizontal,vertical`.
62 var spacing: String
63
64 # ---
65 # common part
66 #
67 # Information common to all characters
68
69 # Distance in pixels between each line of text
70 var line_height: Float
71
72 # Pixels from the top of the line to the base of the characters
73 var base: Float
74
75 # Width of the texture
76 var scale_w: Float
77
78 # Height of the texture
79 var scale_h: Float
80
81 # Textures
82 var pages = new Map[String, TextureAsset]
83
84 # Characters in the font
85 var chars = new Map[Char, BMFontChar]
86
87 # Distance between certain characters
88 var kernings = new HashMap2[Char, Char, Float]
89
90 # Additional distance between `prev_char` and `char`
91 fun kerning(prev_char: nullable Char, char: Char): Float
92 do
93 if prev_char == null then return 0.0
94 return kernings[prev_char, char] or else 0.0
95 end
96
97 redef fun to_s do return "<{class_name} {face} at {size} pt, "+
98 "{pages.length} pages, {chars.length} chars>"
99
100 # TODO
101 #
102 # # From info
103 # charset
104 # stretchH
105 # smooth
106 # aa
107 # outline
108 #
109 # # From common
110 # packed
111 # alphaChnl
112 # redChnl
113 # greenChnl
114 # blueChnl
115 end
116
117 # Description of a character in a `BMFont`
118 class BMFontChar
119
120 # Subtexture left coordinate
121 var x: Float
122
123 # Subtexture top coordinate
124 var y: Float
125
126 # Subtexture width
127 var width: Float
128
129 # Subtexture height
130 var height: Float
131
132 # Drawing offset on X
133 var xoffset: Float
134
135 # Drawing offset on Y
136 var yoffset: Float
137
138 # Cursor advance after drawing this character
139 var xadvance: Float
140
141 # Full texture contaning this character and others
142 var page: TextureAsset
143
144 # TODO Channel where the image is found
145 #var chnl: Int
146
147 # Subtexture with this character image only
148 var subtexture: Texture = page.subtexture(x, y, width, height) is lazy
149 end
150
151 redef class Text
152
153 # Parse `self` as an XML BMFont description file
154 #
155 # Reports only basic XML format errors, other errors may be ignored or
156 # cause a crash.
157 #
158 # ~~~
159 # var desc = """
160 # <font>
161 # <info face="arial" size="72" bold="0" italic="0" charset=""
162 # unicode="1" stretchH="100" smooth="1" aa="1" padding="2,2,2,2"
163 # spacing="0,0" outline="0"/>
164 # <common lineHeight="80" base="65" scaleW="4030" scaleH="231"
165 # pages="1" packed="0"/>
166 # <pages>
167 # <page id="0" file="arial.png"/>
168 # </pages>
169 # <chars count="3">
170 # <char id="65" x="2519" y="10" width="55" height="59" xoffset="0"
171 # yoffset="13" xadvance="48" page="0" chnl="15"/>
172 # <char id="66" x="2600" y="10" width="46" height="58" xoffset="5"
173 # yoffset="13" xadvance="48" page="0" chnl="15"/>
174 # <char id="67" x="2673" y="9" width="52" height="60" xoffset="4"
175 # yoffset="12" xadvance="52" page="0" chnl="15"/>
176 # </chars>
177 # <kernings count="1">
178 # <kerning first="65" second="67" amount="-1"/>
179 # </kernings>
180 # </font>
181 # """
182 #
183 # var fnt = desc.parse_bmfont("dir_in_assets").value
184 # assert fnt.to_s == "<BMFont arial at 72.0 pt, 1 pages, 3 chars>"
185 # assert fnt.line_height == 80.0
186 # assert fnt.kernings['A', 'C'] == -1.0
187 # assert fnt.chars['A'].page.path == "dir_in_assets/arial.png"
188 # ~~~
189 fun parse_bmfont(dir: String): MaybeError[BMFont, Error]
190 do
191 # Parse XML
192 var xml = to_xml
193 if xml isa XMLError then
194 var msg = "XML Parse Error: {xml.message}:{xml.location or else 0}"
195 return new MaybeError[BMFont, Error](maybe_error=new Error(msg))
196 end
197
198 # Basic sanity check
199 var roots = xml["font"]
200 if roots.is_empty then
201 var msg = "Error: the XML document doesn't declare the expected `font` root"
202 return new MaybeError[BMFont, Error](maybe_error=new Error(msg))
203 end
204
205 # Expect the rest of the document to be well formatted
206 var root = roots.first
207
208 var info = root["info"].first
209 assert info isa XMLAttrTag
210 var info_map = info.attributes_to_map
211
212 var common = root["common"].first
213 assert common isa XMLAttrTag
214 var common_map = common.attributes_to_map
215
216 var fnt = new BMFont(
217 info_map["face"],
218 info_map["size"].to_f,
219 info_map["bold"] == "1",
220 info_map["italic"] == "1",
221 info_map["unicode"] == "1",
222 info_map["padding"],
223 info_map["spacing"],
224 common_map["lineHeight"].to_f,
225 common_map["base"].to_f,
226 common_map["scaleW"].to_f,
227 common_map["scaleH"].to_f
228 )
229
230 # Pages / pixel data files
231 var xml_pages = root["pages"].first
232 for page in xml_pages["page"] do
233 if not page isa XMLAttrTag then continue
234
235 var attributes = page.attributes_to_map
236 var file = dir / attributes["file"]
237 fnt.pages[attributes["id"]] = new TextureAsset(file)
238 end
239
240 # Char description
241 for item in root["chars"].first["char"] do
242 if not item isa XMLAttrTag then continue
243
244 var attributes = item.attributes_to_map
245 var id = attributes["id"].to_i.code_point
246
247 var c = new BMFontChar(
248 attributes["x"].to_f, attributes["y"].to_f,
249 attributes["width"].to_f, attributes["height"].to_f,
250 attributes["xoffset"].to_f, attributes["yoffset"].to_f,
251 attributes["xadvance"].to_f,
252 fnt.pages[attributes["page"]])
253
254 fnt.chars[id] = c
255 end
256
257 # Kerning between two characters
258 var kernings = root["kernings"]
259 if kernings.not_empty then
260 for item in kernings.first["kerning"] do
261 if not item isa XMLAttrTag then continue
262
263 var attributes = item.attributes_to_map
264 var first = attributes["first"].to_i.code_point
265 var second = attributes["second"].to_i.code_point
266 var amount = attributes["amount"].to_f
267 fnt.kernings[first, second] = amount
268 end
269 end
270
271 return new MaybeError[BMFont, Error](fnt)
272 end
273 end
274
275 # BMFont from the assets folder
276 #
277 # ~~~
278 # redef class App
279 # var font = new BMFontAsset("arial.fnt")
280 # var ui_text = new TextSprites(font, ui_camera.top_left)
281 #
282 # redef fun on_create
283 # do
284 # super
285 #
286 # font.load
287 # assert font.error == null
288 #
289 # ui_text.text = "Hello world!"
290 # end
291 # end
292 # ~~~
293 class BMFontAsset
294 super Asset
295 super Font
296
297 # Font description
298 #
299 # Require: `error == null`
300 fun desc: BMFont
301 do
302 # Cached results
303 var cache = desc_cache
304 if cache != null then return cache
305 var error = error
306 assert error == null else print_error error
307
308 # Load on first access
309 load
310 error = self.error
311 assert error == null else print_error error
312
313 return desc_cache.as(not null)
314 end
315
316 private var desc_cache: nullable BMFont = null
317
318 # Error at loading
319 var error: nullable Error = null
320
321 # XML description in the assets folder
322 private var text_asset = new TextAsset(path) is lateinit
323
324 # Load font description and textures from the assets folder
325 #
326 # Sets `error` if an error occurred, otherwise
327 # the font description can be accessed via `desc`.
328 fun load
329 do
330 var text_asset = text_asset
331 text_asset.load
332 var error = text_asset.error
333 if error != null then
334 self.error = error
335 return
336 end
337
338 var desc = text_asset.to_s
339 var fnt_or_error = desc.parse_bmfont(path.dirname)
340 if fnt_or_error.is_error then
341 self.error = fnt_or_error.error
342 return
343 end
344
345 var fnt = fnt_or_error.value
346 self.desc_cache = fnt
347
348 # Load textures too
349 for page_name, texture in fnt.pages do
350 texture.load
351
352 # Move up any texture loading error.
353 # This algo keeps only the latest error,
354 # but this isn't a problem on single page fonts.
355 error = texture.error
356 if error != null then self.error = error
357 end
358 end
359
360 redef fun write_into(text_sprites, text)
361 do
362 var dx = 0.0
363 var dy = 0.0
364 var text_width = 0.0
365
366 var max_width = text_sprites.max_width
367 var max_height = text_sprites.max_height
368
369 var line_height = desc.line_height
370 var partial_line_skip = line_height * partial_line_mod.to_f
371 var line_sprites = new Array[Sprite]
372
373 var prev_char = null
374 var i = -1
375 while i < text.length - 1 do
376 i += 1
377 var c = text[i]
378
379 # Special characters
380 var word_break = false
381 if c == '\n' then
382 justify(line_sprites, text_sprites.align, dx)
383 dy -= line_height
384 if max_height != null and max_height < -dy + line_height then break
385 dx = 0.0
386 prev_char = null
387 continue
388 else if c == pld then
389 dy -= partial_line_skip
390 word_break = true
391 continue
392 else if c == plu then
393 dy += partial_line_skip
394 word_break = true
395 continue
396 else if c.is_whitespace then
397 var space_advance = if desc.chars.keys.has(' ') then
398 desc.chars[' '].xadvance
399 else if desc.chars.keys.has('f') then
400 desc.chars['f'].xadvance
401 else 16.0
402 dx += space_advance
403 word_break = true
404 end
405
406 # End of a word?
407 if word_break then
408 # If we care about line width, check for overflow
409 if max_width != null then
410 # Calculate the length of the next word
411 var prev_w = null
412 var word_len = 0.0
413 for wi in [i+1..text.length[ do
414 var w = text[wi]
415
416 if w == '\n' or w == pld or w == plu or w.is_whitespace then break
417 word_len += advance(prev_w, w)
418 prev_w = w
419 end
420
421 # Would the line be too long?
422 if dx + word_len > max_width then
423 if text_sprites.wrap then
424 # Wrap
425 justify(line_sprites, text_sprites.align, dx)
426 dy -= line_height
427 if max_height != null and max_height < -dy + line_height then break
428 dx = 0.0
429 else
430 # Cut short
431 justify(line_sprites, text_sprites.align, dx)
432 dy -= line_height
433 if max_height != null and max_height < -dy + line_height then break
434 dx = 0.0
435 while c != '\n' and i < text.length - 1 do
436 i += 1
437 c = text[i]
438 end
439 end
440 end
441 end
442
443 prev_char = null
444 continue
445 end
446
447 # Replace or skip unknown characters
448 if not desc.chars.keys.has(c) then
449 var rc = replacement_char
450 if rc == null then continue
451 c = rc
452 end
453
454 var char_info = desc.chars[c]
455 var advance = char_info.xadvance
456 var kerning = desc.kerning(prev_char, c)
457
458 var x = dx + char_info.width/2.0 + char_info.xoffset + kerning
459 var y = dy - char_info.height/2.0 - char_info.yoffset
460 var pos = text_sprites.anchor.offset(x, y, 0.0)
461 var s = new Sprite(char_info.subtexture, pos)
462 text_sprites.sprites.add s
463 line_sprites.add s
464
465 dx += advance + kerning
466 prev_char = c
467
468 text_width = text_width.max(dx)
469 end
470
471 justify(line_sprites, text_sprites.align, dx)
472
473 # valign
474 if text_sprites.valign != 0.0 then
475 var d = (-dy+line_height) * text_sprites.valign
476 for s in text_sprites.sprites do s.center.y += d
477 end
478
479 text_sprites.width = text_width.max(dx)
480 text_sprites.height = dy + line_height
481 end
482
483 # Character replacing other characters missing from the font
484 private var replacement_char: nullable Char is lazy do
485 for c in "�?".chars do
486 if desc.chars.keys.has(c) then return c
487 end
488 return null
489 end
490
491 private fun advance(prev_char: nullable Char, char: Char): Float
492 do
493 var char_info = desc.chars[char]
494 var kerning = desc.kerning(prev_char, char)
495 return char_info.xadvance + kerning
496 end
497
498 private fun justify(line_sprites: Array[Sprite], align: Float, line_width: Float)
499 do
500 var dx = -line_width*align
501 for s in line_sprites do s.center.x += dx
502 line_sprites.clear
503 end
504 end