]> de.git.xonotic.org Git - xonotic/xonstat.git/blob - xonstat/batch/badges/skin.py
More design work on the two badge themes; also improved skin support
[xonotic/xonstat.git] / xonstat / batch / badges / skin.py
1 import math
2 import re
3 import zlib, struct
4 import cairo as C
5 from colorsys import rgb_to_hls, hls_to_rgb
6 from xonstat.util import strip_colors, qfont_decode, _all_colors
7
8 # similar to html_colors() from util.py
9 _contrast_threshold = 0.5
10
11 # standard colorset (^0 ... ^9)
12 _dec_colors = [ (0.5,0.5,0.5),
13                 (1.0,0.0,0.0),
14                 (0.2,1.0,0.0),
15                 (1.0,1.0,0.0),
16                 (0.2,0.4,1.0),
17                 (0.2,1.0,1.0),
18                 (1.0,0.2,102),
19                 (1.0,1.0,1.0),
20                 (0.6,0.6,0.6),
21                 (0.5,0.5,0.5)
22             ]
23
24
25 # function to write compressed PNG (using zlib)
26 def write_png(filename, buf, width, height):
27     width_byte_4 = width * 4
28     # fix color ordering (BGRA -> RGBA)
29     for byte in xrange(width*height):
30         pos = byte * 4
31         buf[pos:pos+4] = buf[pos+2] + buf[pos+1] + buf[pos+0] + buf[pos+3]
32     raw_data = b"".join(b'\x00' + buf[span:span + width_byte_4] for span in range(0, (height-1) * width * 4 + 1, width_byte_4))
33     def png_pack(png_tag, data):
34         chunk_head = png_tag + data
35         return struct.pack("!I", len(data)) + chunk_head + struct.pack("!I", 0xFFFFFFFF & zlib.crc32(chunk_head))
36     data = b"".join([
37         b'\x89PNG\r\n\x1a\n',
38         png_pack(b'IHDR', struct.pack("!2I5B", width, height, 8, 6, 0, 0, 0)),
39         png_pack(b'IDAT', zlib.compress(raw_data, 9)),
40         png_pack(b'IEND', b'')])
41     f = open(filename, "wb")
42     try:
43         f.write(data)
44     finally:
45         f.close()
46
47
48 class Skin:
49
50     # skin parameters, can be overriden by init
51     params = {}
52
53     # skin name
54     name = ""
55
56     # render context
57     ctx = None
58
59     def __init__(self, name, **params):
60         # default parameters
61         self.name = name
62         self.params = {
63             'bg':               None,           # None - plain; otherwise use given texture
64             'bgcolor':          None,           # transparent bg when bgcolor==None
65             'overlay':          None,           # add overlay graphic on top of bg
66             'font':             "Xolonium",
67             'width':            560,
68             'height':           70,
69             'nick_fontsize':    20,
70             'nick_pos':         (56,18),
71             'nick_maxwidth':    280,
72             'gametype_fontsize':10,
73             'gametype_pos':     (101,33),
74             'gametype_width':   94,
75             'gametype_height':  0,
76             'gametype_color':   (0.9, 0.9, 0.9),
77             'gametype_text':    "%s",
78             'gametype_align':   0,
79             'num_gametypes':    3,
80             'nostats_fontsize': 12,
81             'nostats_pos':      (101,59),
82             'nostats_color':    (0.8, 0.2, 0.1),
83             'nostats_angle':    -10,
84             'nostats_text':     "no stats yet!",
85             'nostats_align':    0,
86             'elo_pos':          (101,47),
87             'elo_fontsize':     10,
88             'elo_color':        (1.0, 1.0, 0.5),
89             'elo_text':         "Elo %.0f",
90             'elo_align':        0,
91             'rank_fontsize':    8,
92             'rank_pos':         (101,58),
93             'rank_color':       (0.8, 0.8, 1.0),
94             'rank_text':        "Rank %d of %d",
95             'rank_align':       0,
96             'wintext_fontsize': 10,
97             'wintext_pos':      (508,3),
98             'wintext_color':    (0.8, 0.8, 0.8),
99             'wintext_text':     "Win Percentage",
100             'wintext_align':    0,
101             'winp_fontsize':    12,
102             'winp_pos':         (508,19),
103             'winp_colortop':    (0.2, 1.0, 1.0),
104             'winp_colormid':    (0.4, 0.8, 0.4),
105             'winp_colorbot':    (1.0, 1.0, 0.2),
106             'winp_align':       0,
107             'wins_fontsize':    8,
108             'wins_pos':         (508,33),
109             'wins_color':       (0.6, 0.8, 0.8),
110             'wins_align':       0,
111             'loss_fontsize':    8,
112             'loss_pos':         (508,43),
113             'loss_color':       (0.8, 0.8, 0.6),
114             'loss_align':       0,
115             'kdtext_fontsize':  10,
116             'kdtext_pos':       (390,3),
117             'kdtext_width':     102,
118             'kdtext_color':     (0.8, 0.8, 0.8),
119             'kdtext_bg':        (0.8, 0.8, 0.8, 0.1),
120             'kdtext_text':      "Kill Ratio",
121             'kdtext_align':     0,
122             'kdr_fontsize':     12,
123             'kdr_pos':          (392,19),
124             'kdr_colortop':     (0.2, 1.0, 0.2),
125             'kdr_colormid':     (0.8, 0.8, 0.4),
126             'kdr_colorbot':     (1.0, 0.2, 0.2),
127             'kdr_align':        0,
128             'kills_fontsize':   8,
129             'kills_pos':        (392,33),
130             'kills_color':      (0.6, 0.8, 0.6),
131             'kills_align':      0,
132             'deaths_fontsize':  8,
133             'deaths_pos':       (392,43),
134             'deaths_color':     (0.8, 0.6, 0.6),
135             'deaths_align':     0,
136             'ptime_fontsize':   10,
137             'ptime_pos':        (451,60),
138             'ptime_color':      (0.1, 0.1, 0.1),
139             'ptime_text':       "Playing Time: %s",
140             'ptime_align':      0,
141         }
142         
143         for k,v in params.items():
144             if self.params.has_key(k):
145                 self.params[k] = v
146
147     def __str__(self):
148         return self.name
149
150     def __getattr__(self, key):
151         if self.params.has_key(key):
152             return self.params[key]
153         return None
154
155     def show_text(self, txt, pos, align=0, angle=None, offset=(0,0)):
156         ctx = self.ctx
157
158         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
159         if align > 0:
160             ctx.move_to(pos[0]+offset[0]-xoff,      pos[1]+offset[1]-yoff)
161         elif align < 0:
162             ctx.move_to(pos[0]+offset[0]-xoff-tw,   pos[1]+offset[1]-yoff)
163         else:
164             ctx.move_to(pos[0]+offset[0]-xoff-tw/2, pos[1]+offset[1]-yoff)
165         ctx.save()
166         if angle:
167             ctx.rotate(math.radians(angle))
168         ctx.show_text(txt)
169         ctx.restore()
170
171     def set_font(self, fontsize, color, bold=False, italic=False):
172         ctx    = self.ctx
173         font   = self.font
174         slant  = C.FONT_SLANT_ITALIC if italic else C.FONT_SLANT_NORMAL
175         weight = C.FONT_WEIGHT_BOLD  if bold   else C.FONT_WEIGHT_NORMAL
176
177         ctx.select_font_face(font, slant, weight)
178         ctx.set_font_size(fontsize)
179         if len(color) == 1:
180             ctx.set_source_rgb(color[0], color[0], color[0])
181         elif len(color) == 3:
182             ctx.set_source_rgb(color[0], color[1], color[2])
183         elif len(color) == 4:
184             ctx.set_source_rgba(color[0], color[1], color[2], color[3])
185         else:
186             ctx.set_source_rgb(1, 1, 1)
187
188     def render_image(self, data, output_filename):
189         """Render an image for the given player id."""
190
191         # setup variables
192
193         player          = data.player
194         elos            = data.elos
195         ranks           = data.ranks
196         #games           = data.total_stats['games']
197         wins, losses    = data.total_stats['wins'], data.total_stats['losses']
198         games           = wins + losses
199         kills, deaths   = data.total_stats['kills'], data.total_stats['deaths']
200         alivetime       = data.total_stats['alivetime']
201
202
203         # build image
204
205         surf = C.ImageSurface(C.FORMAT_ARGB32, self.width, self.height)
206         ctx = C.Context(surf)
207         self.ctx = ctx
208         ctx.set_antialias(C.ANTIALIAS_GRAY)
209         
210         # draw background
211         if self.bg == None:
212             if self.bgcolor != None:
213                 # plain fillcolor, full transparency possible with (1,1,1,0)
214                 ctx.save()
215                 ctx.set_operator(C.OPERATOR_SOURCE)
216                 ctx.rectangle(0, 0, self.width, self.height)
217                 ctx.set_source_rgba(self.bgcolor[0], self.bgcolor[1], self.bgcolor[2], self.bgcolor[3])
218                 ctx.fill()
219                 ctx.restore()
220         else:
221             try:
222                 # background texture
223                 bg = C.ImageSurface.create_from_png("img/%s.png" % self.bg)
224                 
225                 # tile image
226                 if bg:
227                     bg_w, bg_h = bg.get_width(), bg.get_height()
228                     bg_xoff = 0
229                     while bg_xoff < self.width:
230                         bg_yoff = 0
231                         while bg_yoff < self.height:
232                             ctx.set_source_surface(bg, bg_xoff, bg_yoff)
233                             #ctx.mask_surface(bg)
234                             ctx.paint()
235                             bg_yoff += bg_h
236                         bg_xoff += bg_w
237             except:
238                 #print "Error: Can't load background texture: %s" % self.bg
239                 pass
240
241         # draw overlay graphic
242         if self.overlay != None:
243             try:
244                 overlay = C.ImageSurface.create_from_png("img/%s.png" % self.overlay)
245                 ctx.set_source_surface(overlay, 0, 0)
246                 #ctx.mask_surface(overlay)
247                 ctx.paint()
248             except:
249                 #print "Error: Can't load overlay texture: %s" % self.overlay
250                 pass
251
252
253         ## draw player's nickname with fancy colors
254         
255         # deocde nick, strip all weird-looking characters
256         qstr = qfont_decode(player.nick).replace('^^', '^').replace(u'\x00', '')
257         chars = []
258         for c in qstr:
259             # replace weird characters that make problems - TODO
260             if ord(c) < 128:
261                 chars.append(c)
262         qstr = ''.join(chars)
263         stripped_nick = strip_colors(qstr.replace(' ', '_'))
264         
265         # fontsize is reduced if width gets too large
266         ctx.select_font_face(self.font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
267         shrinknick = 0
268         while shrinknick < 10:
269             ctx.set_font_size(self.nick_fontsize - shrinknick)
270             xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
271             if tw > self.nick_maxwidth:
272                 shrinknick += 2
273                 continue
274             break
275
276         # determine width of single whitespace for later use
277         xoff, yoff, tw, th = ctx.text_extents("_")[:4]
278         space_w = tw
279
280         # split nick into colored segments
281         xoffset = 0
282         _all_colors = re.compile(r'(\^\d|\^x[\dA-Fa-f]{3})')
283         parts = _all_colors.split(qstr)
284         while len(parts) > 0:
285             tag = None
286             txt = parts[0]
287             if _all_colors.match(txt):
288                 tag = txt[1:]  # strip leading '^'
289                 if len(parts) < 2:
290                     break
291                 txt = parts[1]
292                 del parts[1]
293             del parts[0]
294                 
295             if not txt or len(txt) == 0:
296                 # only colorcode and no real text, skip this
297                 continue
298             
299             if tag:
300                 if tag.startswith('x'):
301                     r = int(tag[1] * 2, 16) / 255.0
302                     g = int(tag[2] * 2, 16) / 255.0
303                     b = int(tag[3] * 2, 16) / 255.0
304                     hue, light, satur = rgb_to_hls(r, g, b)
305                     if light < _contrast_threshold:
306                         light = _contrast_threshold
307                         r, g, b = hls_to_rgb(hue, light, satur)
308                 else:
309                     r,g,b = _dec_colors[int(tag[0])]
310             else:
311                 r,g,b = _dec_colors[7]
312             
313             ctx.set_source_rgb(r, g, b)
314             ctx.move_to(self.nick_pos[0] + xoffset, self.nick_pos[1])
315             ctx.show_text(txt)
316
317             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
318             tw += (len(txt)-len(txt.strip())) * space_w  # account for lost whitespaces
319             xoffset += tw + 2
320
321         ## print elos and ranks
322         
323         xoffset, yoffset = 0, 0
324         count = 0
325         for gt in data.total_stats['gametypes'][:self.num_gametypes]:
326             if not elos.has_key(gt) or not ranks.has_key(gt):
327                 continue
328             count += 1
329         
330         # re-align segments if less than max. gametypes are shown
331         if count > 0:
332             if count < self.num_gametypes:
333                 diff = self.num_gametypes - count
334                 if diff % 2 == 0:
335                     xoffset += (diff-1) * self.gametype_width
336                     yoffset += (diff-1) * self.gametype_height
337                 else:
338                     xoffset += 0.5 * diff * self.gametype_width
339                     yoffset += 0.5 * diff * self.gametype_height
340         
341             # show a number gametypes the player has participated in
342             for gt in data.total_stats['gametypes'][:self.num_gametypes]:
343                 if not elos.has_key(gt) or not ranks.has_key(gt):
344                     continue
345
346                 offset = (xoffset, yoffset)
347                 if self.gametype_pos:
348                     txt = self.gametype_text % gt.upper()
349                     self.set_font(self.gametype_fontsize, self.gametype_color, bold=True)
350                     self.show_text(txt, self.gametype_pos, self.gametype_align, offset=offset)
351
352                 if self.elo_pos:
353                     txt = self.elo_text % round(elos[gt], 0)
354                     self.set_font(self.elo_fontsize, self.elo_color)
355                     self.show_text(txt, self.elo_pos, self.elo_align, offset=offset)
356                 if  self.rank_pos:
357                     txt = self.rank_text % ranks[gt]
358                     self.set_font(self.rank_fontsize, self.rank_color)
359                     self.show_text(txt, self.rank_pos, self.rank_align, offset=offset)
360
361                 xoffset += self.gametype_width
362                 yoffset += self.gametype_height
363         else:
364             if self.nostats_pos:
365                 xoffset += (self.num_gametypes-2) * self.gametype_width
366                 yoffset += (self.num_gametypes-2) * self.gametype_height
367                 offset = (xoffset, yoffset)
368
369                 txt = self.nostats_text
370                 self.set_font(self.nostats_fontsize, self.nostats_color, bold=True)
371                 self.show_text(txt, self.nostats_pos, self.nostats_align, angle=self.nostats_angle, offset=offset)
372
373
374         # print win percentage
375
376         if self.wintext_pos:
377             txt = self.wintext_text
378             self.set_font(self.wintext_fontsize, self.wintext_color)
379             self.show_text(txt, self.wintext_pos, self.wintext_align)
380
381         txt = "???"
382         try:
383             ratio = float(wins)/games
384             txt = "%.2f%%" % round(ratio * 100, 2)
385         except:
386             ratio = 0
387         
388         if self.winp_pos:
389             if ratio >= 0.5:
390                 nr = 2*(ratio-0.5)
391                 r = nr*self.winp_colortop[0] + (1-nr)*self.winp_colormid[0]
392                 g = nr*self.winp_colortop[1] + (1-nr)*self.winp_colormid[1]
393                 b = nr*self.winp_colortop[2] + (1-nr)*self.winp_colormid[2]
394             else:
395                 nr = 2*ratio
396                 r = nr*self.winp_colormid[0] + (1-nr)*self.winp_colorbot[0]
397                 g = nr*self.winp_colormid[1] + (1-nr)*self.winp_colorbot[1]
398                 b = nr*self.winp_colormid[2] + (1-nr)*self.winp_colorbot[2]
399             self.set_font(self.winp_fontsize, (r,g,b), bold=True)
400             self.show_text(txt, self.winp_pos, self.winp_align)
401
402         if self.wins_pos:
403             txt = "%d win" % wins
404             if wins != 1:
405                 txt += "s"
406             self.set_font(self.wins_fontsize, self.wins_color)
407             self.show_text(txt, self.wins_pos, self.wins_align)
408
409         if self.loss_pos:
410             txt = "%d loss" % losses
411             if losses != 1:
412                 txt += "es"
413             self.set_font(self.loss_fontsize, self.loss_color)
414             self.show_text(txt, self.loss_pos, self.loss_align)
415
416
417         # print kill/death ratio
418
419         if self.kdtext_pos:
420             txt = self.kdtext_text
421             self.set_font(self.kdtext_fontsize, self.kdtext_color)
422             self.show_text(txt, self.kdtext_pos, self.kdtext_align)
423         
424         txt = "???"
425         try:
426             ratio = float(kills)/deaths
427             txt = "%.3f" % round(ratio, 3)
428         except:
429             ratio = 0
430
431         if self.kdr_pos:
432             if ratio >= 1.0:
433                 nr = ratio-1.0
434                 if nr > 1:
435                     nr = 1
436                 r = nr*self.kdr_colortop[0] + (1-nr)*self.kdr_colormid[0]
437                 g = nr*self.kdr_colortop[1] + (1-nr)*self.kdr_colormid[1]
438                 b = nr*self.kdr_colortop[2] + (1-nr)*self.kdr_colormid[2]
439             else:
440                 nr = ratio
441                 r = nr*self.kdr_colormid[0] + (1-nr)*self.kdr_colorbot[0]
442                 g = nr*self.kdr_colormid[1] + (1-nr)*self.kdr_colorbot[1]
443                 b = nr*self.kdr_colormid[2] + (1-nr)*self.kdr_colorbot[2]
444             self.set_font(self.kdr_fontsize, (r,g,b), bold=True)
445             self.show_text(txt, self.kdr_pos, self.kdr_align)
446
447         if self.kills_pos:
448             txt = "%d kill" % kills
449             if kills != 1:
450                 txt += "s"
451             self.set_font(self.kills_fontsize, self.kills_color)
452             self.show_text(txt, self.kills_pos, self.kills_align)
453
454         if self.deaths_pos:
455             txt = ""
456             if deaths is not None:
457                 txt = "%d death" % deaths
458                 if deaths != 1:
459                     txt += "s"
460             self.set_font(self.deaths_fontsize, self.deaths_color)
461             self.show_text(txt, self.deaths_pos, self.deaths_align)
462
463
464         # print playing time
465
466         if self.ptime_pos:
467             txt = self.ptime_text % str(alivetime)
468             self.set_font(self.ptime_fontsize, self.ptime_color)
469             self.show_text(txt, self.ptime_pos, self.ptime_align)
470
471
472         # save to PNG
473         #surf.write_to_png(output_filename)
474         surf.flush()
475         imgdata = surf.get_data()
476         write_png(output_filename, imgdata, self.width, self.height)
477