]> de.git.xonotic.org Git - xonotic/xonstat.git/blob - xonstat/batch/badges/gen_badges.py
Added support for transparent background in badges (bg=-1)
[xonotic/xonstat.git] / xonstat / batch / badges / gen_badges.py
1 #-*- coding: utf-8 -*-
2
3 import sys
4 import re
5 import cairo as C
6 from datetime import datetime
7 import sqlalchemy as sa
8 import sqlalchemy.sql.functions as func
9 from colorsys import rgb_to_hls, hls_to_rgb
10 from os import system
11 from pyramid.paster import bootstrap
12 from xonstat.models import *
13 from xonstat.util import qfont_decode, _all_colors
14
15
16 # similar to html_colors() from util.py
17 _contrast_threshold = 0.5
18
19 _dec_colors = [ (0.5,0.5,0.5),
20                 (1.0,0.0,0.0),
21                 (0.2,1.0,0.0),
22                 (1.0,1.0,0.0),
23                 (0.2,0.4,1.0),
24                 (0.2,1.0,1.0),
25                 (1.0,0.2,102),
26                 (1.0,1.0,1.0),
27                 (0.6,0.6,0.6),
28                 (0.5,0.5,0.5)
29             ]
30
31
32 # maximal number of query results (for testing, set to 0 to get all)
33 NUM_PLAYERS = 100
34
35 # image dimensions (likely breaks layout if changed)
36 WIDTH   = 560
37 HEIGHT  = 70
38
39 # output filename, parameter is player id
40 OUTPUT = "output/%d.png"
41
42
43 NICK_POS        = (5,18)
44 NICK_MAXWIDTH   = 330
45
46 GAMES_POS       = (60,35)
47 GAMES_WIDTH     = 110
48
49 WINLOSS_POS     = (508,6)
50 WINLOSS_WIDTH   = 104
51
52 KILLDEATH_POS   = (390,6)
53 KILLDEATH_WIDTH = 104
54
55 PLAYTIME_POS    = (452,64)
56 PLAYTIME_WIDTH  = 218
57
58
59 # parameters to affect the output, could be changed via URL
60 params = {
61     'bg':           1,                      # -1 - none, 0 - black, 1 - dark_wall, ...
62     'overlay':      0,                      # 0 - none, 1 - default overlay, ...
63     'font':         0,                      # 0 - xolonium, 1 - dejavu sans
64 }
65
66
67 # parse cmdline parameters (for testing)
68 for arg in sys.argv[1:]:
69     try:
70         k,v = arg.split("=")
71         if params.has_key(k.lower()):
72             params[k] = int(v)
73     except:
74         continue
75
76
77 def get_data(player):
78     """Return player data as dict.
79
80     This function is similar to the function in player.py but more optimized
81     for this purpose.
82     """
83
84     # total games
85     # wins/losses
86     # kills/deaths
87     # duel/dm/tdm/ctf elo + rank
88
89     player_id = player.player_id
90
91     total_stats = {}
92
93     games_played = DBSession.query(
94             Game.game_type_cd, func.count(), func.sum(PlayerGameStat.alivetime)).\
95             filter(Game.game_id == PlayerGameStat.game_id).\
96             filter(PlayerGameStat.player_id == player_id).\
97             group_by(Game.game_type_cd).\
98             order_by(func.count().desc()).\
99             limit(3).all()  # limit to 3 gametypes!
100
101     total_stats['games'] = 0
102     total_stats['games_breakdown'] = {}  # this is a dictionary inside a dictionary .. dictception?
103     total_stats['games_alivetime'] = {}
104     total_stats['gametypes'] = []
105     for (game_type_cd, games, alivetime) in games_played:
106         total_stats['games'] += games
107         total_stats['gametypes'].append(game_type_cd)
108         total_stats['games_breakdown'][game_type_cd] = games
109         total_stats['games_alivetime'][game_type_cd] = alivetime
110
111     (total_stats['kills'], total_stats['deaths'], total_stats['alivetime'],) = DBSession.query(
112             func.sum(PlayerGameStat.kills),
113             func.sum(PlayerGameStat.deaths),
114             func.sum(PlayerGameStat.alivetime)).\
115             filter(PlayerGameStat.player_id == player_id).\
116             one()
117
118 #    (total_stats['wins'],) = DBSession.query(
119 #            func.count("*")).\
120 #            filter(Game.game_id == PlayerGameStat.game_id).\
121 #            filter(PlayerGameStat.player_id == player_id).\
122 #            filter(Game.winner == PlayerGameStat.team or PlayerGameStat.rank == 1).\
123 #            one()
124
125     (total_stats['wins'],) = DBSession.\
126             query("total_wins").\
127             from_statement(
128                 "select count(*) total_wins "
129                 "from games g, player_game_stats pgs "
130                 "where g.game_id = pgs.game_id "
131                 "and player_id=:player_id "
132                 "and (g.winner = pgs.team or pgs.rank = 1)"
133             ).params(player_id=player_id).one()
134
135     ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
136             from_statement(
137                 "select pr.game_type_cd, pr.rank, overall.max_rank "
138                 "from player_ranks pr,  "
139                    "(select game_type_cd, max(rank) max_rank "
140                     "from player_ranks  "
141                     "group by game_type_cd) overall "
142                 "where pr.game_type_cd = overall.game_type_cd  "
143                 "and player_id = :player_id "
144                 "order by rank").\
145             params(player_id=player_id).all()
146
147     ranks_dict = {}
148     for gtc,rank,max_rank in ranks:
149         ranks_dict[gtc] = (rank, max_rank)
150
151     elos = DBSession.query(PlayerElo).\
152             filter_by(player_id=player_id).\
153             order_by(PlayerElo.elo.desc()).\
154             all()
155
156     elos_dict = {}
157     for elo in elos:
158         if elo.games > 32:
159             elos_dict[elo.game_type_cd] = elo.elo
160
161     data = {
162             'player':player,
163             'total_stats':total_stats,
164             'ranks':ranks_dict,
165             'elos':elos_dict,
166         }
167
168     #print data
169     return data
170
171
172 def render_image(data):
173     """Render an image from the given data fields."""
174     font = "Xolonium"
175     if params['font'] == 1:
176         font = "DejaVu Sans"
177
178     total_stats = data['total_stats']
179     total_games = total_stats['games']
180     elos = data["elos"]
181     ranks = data["ranks"]
182
183
184     ## create background
185
186     surf = C.ImageSurface(C.FORMAT_ARGB32, WIDTH, HEIGHT)
187     ctx = C.Context(surf)
188     ctx.set_antialias(C.ANTIALIAS_GRAY)
189
190     # draw background (just plain fillcolor)
191     if params['bg'] == 0:
192         ctx.rectangle(0, 0, WIDTH, HEIGHT)
193         ctx.set_source_rgb(0.04, 0.04, 0.04)  # bgcolor of Xonotic forum
194         ctx.fill()
195     elif params['bg'] < 0:
196         ctx.save()
197         ctx.set_operator(C.OPERATOR_SOURCE)
198         ctx.set_source_rgba(1, 1, 1, 0)
199         ctx.paint()
200         ctx.restore()
201
202     # draw background image (try to get correct tiling, too)
203     if params['bg'] > 0:
204         bg = None
205         if params['bg'] == 1:
206             bg = C.ImageSurface.create_from_png("img/dark_wall.png")
207         elif params['bg'] == 2:
208             bg = C.ImageSurface.create_from_png("img/asfalt.png")
209         elif params['bg'] == 3:
210             bg = C.ImageSurface.create_from_png("img/broken_noise.png")
211         elif params['bg'] == 4:
212             bg = C.ImageSurface.create_from_png("img/burried.png")
213         elif params['bg'] == 5:
214             bg = C.ImageSurface.create_from_png("img/dark_leather.png")
215         elif params['bg'] == 6:
216             bg = C.ImageSurface.create_from_png("img/txture.png")
217         elif params['bg'] == 7:
218             bg = C.ImageSurface.create_from_png("img/black_linen_v2.png")
219         elif params['bg'] == 8:
220             bg = C.ImageSurface.create_from_png("img/background_archer-v1.png")
221         
222         # tile image
223         if bg:
224             bg_w, bg_h = bg.get_width(), bg.get_height()
225             bg_xoff = 0
226             while bg_xoff < WIDTH:
227                 bg_yoff = 0
228                 while bg_yoff < HEIGHT:
229                     ctx.set_source_surface(bg, bg_xoff, bg_yoff)
230                     ctx.paint()
231                     bg_yoff += bg_h
232                 bg_xoff += bg_w
233
234     # draw overlay graphic
235     if params['overlay'] > 0:
236         overlay = None
237         if params['overlay'] == 1:
238             overlay = C.ImageSurface.create_from_png("img/overlay.png")
239         if overlay:
240             ctx.set_source_surface(overlay, 0, 0)
241             ctx.mask_surface(overlay)
242             ctx.paint()
243
244
245     ## draw player's nickname with fancy colors
246     
247     # deocde nick, strip all weird-looking characters
248     qstr = qfont_decode(player.nick).replace('^^', '^').replace(u'\x00', '')
249     chars = []
250     for c in qstr:
251         if ord(c) < 128:
252             chars.append(c)
253     qstr = ''.join(chars)
254     stripped_nick = strip_colors(qstr)
255     
256     # fontsize is reduced if width gets too large
257     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
258     ctx.set_font_size(20)
259     xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
260     if tw > NICK_MAXWIDTH:
261         ctx.set_font_size(18)
262         xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
263         if tw > NICK_MAXWIDTH:
264             ctx.set_font_size(16)
265             xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
266             if tw > NICK_MAXWIDTH:
267                 ctx.set_font_size(14)
268                 xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
269                 if tw > NICK_MAXWIDTH:
270                     ctx.set_font_size(12)
271     xoff, yoff, tw, th = ctx.text_extents("_")[:4]
272     space_w = tw
273     
274     # split up nick into colored segments and draw each of them
275     
276     # split nick into colored segments
277     xoffset = 0
278     _all_colors = re.compile(r'(\^\d|\^x[\dA-Fa-f]{3})')
279     #print qstr, _all_colors.findall(qstr), _all_colors.split(qstr)
280     
281     parts = _all_colors.split(qstr)
282     while len(parts) > 0:
283         tag = None
284         txt = parts[0]
285         if _all_colors.match(txt):
286             tag = txt[1:]  # strip leading '^'
287             if len(parts) < 2:
288                 break
289             txt = parts[1]
290             del parts[1]
291         del parts[0]
292             
293         if not txt or len(txt) == 0:
294             # only colorcode and no real text, skip this
295             continue
296             
297         r,g,b = _dec_colors[7]
298         try:
299             if tag.startswith('x'):
300                 r = int(tag[1] * 2, 16) / 255.0
301                 g = int(tag[2] * 2, 16) / 255.0
302                 b = int(tag[3] * 2, 16) / 255.0
303                 hue, light, satur = rgb_to_hls(r, g, b)
304                 if light < _contrast_threshold:
305                     light = _contrast_threshold
306                     r, g, b = hls_to_rgb(hue, light, satur)
307             else:
308                 r,g,b = _dec_colors[int(tag[0])]
309         except:
310             r,g,b = _dec_colors[7]
311         
312         ctx.set_source_rgb(r, g, b)
313         ctx.move_to(NICK_POS[0] + xoffset, NICK_POS[1])
314         ctx.show_text(txt)
315
316         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
317         tw += (len(txt)-len(txt.strip())) * space_w  # account for lost whitespaces
318         xoffset += tw + 2
319
320
321     ## print elos and ranks
322     
323     # show up to three gametypes the player has participated in
324     xoffset = 0
325     for gt in total_stats['gametypes'][:3]:
326         ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
327         ctx.set_font_size(10)
328         ctx.set_source_rgb(1.0, 1.0, 1.0)
329         txt = "[ %s ]" % gt.upper()
330         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
331         ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]-yoff-4)
332         ctx.show_text(txt)
333         
334
335         old_aa = ctx.get_antialias()
336         ctx.set_antialias(C.ANTIALIAS_NONE)
337         ctx.set_source_rgb(0.8, 0.8, 0.8)
338         ctx.set_line_width(1)
339         ctx.move_to(GAMES_POS[0]+xoffset-GAMES_WIDTH/2+5, GAMES_POS[1]+8)
340         ctx.line_to(GAMES_POS[0]+xoffset+GAMES_WIDTH/2-5, GAMES_POS[1]+8)
341         ctx.stroke()
342         ctx.move_to(GAMES_POS[0]+xoffset-GAMES_WIDTH/2+5, GAMES_POS[1]+32)
343         ctx.line_to(GAMES_POS[0]+xoffset+GAMES_WIDTH/2-5, GAMES_POS[1]+32)
344         ctx.stroke()
345         ctx.set_antialias(old_aa)
346
347         if not elos.has_key(gt) or not ranks.has_key(gt):
348             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
349             ctx.set_font_size(12)
350             ctx.set_source_rgb(0.8, 0.2, 0.2)
351             txt = "no stats yet!"
352             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
353             ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]+28-yoff-4)
354             ctx.save()
355             ctx.rotate(math.radians(-10))
356             ctx.show_text(txt)
357             ctx.restore()
358         else:
359             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
360             ctx.set_font_size(10)
361             ctx.set_source_rgb(1.0, 1.0, 0.5)
362             txt = "Elo: %.0f" % round(elos[gt], 0)
363             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
364             ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]+15-yoff-4)
365             ctx.show_text(txt)
366             
367             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
368             ctx.set_font_size(8)
369             ctx.set_source_rgb(0.8, 0.8, 1.0)
370             txt = "Rank %d of %d" % ranks[gt]
371             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
372             ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]+25-yoff-3)
373             ctx.show_text(txt)
374         
375         xoffset += GAMES_WIDTH
376
377
378     # print win percentage
379
380     if params['overlay'] == 0:
381         ctx.rectangle(WINLOSS_POS[0]-WINLOSS_WIDTH/2, WINLOSS_POS[1]-7, WINLOSS_WIDTH, 15)
382         ctx.set_source_rgba(0.8, 0.8, 0.8, 0.1)
383         ctx.fill();
384
385     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
386     ctx.set_font_size(10)
387     ctx.set_source_rgb(0.8, 0.8, 0.8)
388     txt = "Win Percentage"
389     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
390     ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]-yoff-3)
391     ctx.show_text(txt)
392     
393     wins, losses = total_stats["wins"], total_games-total_stats["wins"]
394     txt = "???"
395     try:
396         ratio = float(wins)/total_games
397         txt = "%.2f%%" % round(ratio * 100, 2)
398     except:
399         ratio = 0
400     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
401     ctx.set_font_size(12)
402     if ratio >= 0.90:
403         ctx.set_source_rgb(0.2, 1.0, 1.0)
404     elif ratio >= 0.75:
405         ctx.set_source_rgb(0.5, 1.0, 1.0)
406     elif ratio >= 0.5:
407         ctx.set_source_rgb(0.5, 1.0, 0.8)
408     elif ratio >= 0.25:
409         ctx.set_source_rgb(0.8, 1.0, 0.5)
410     else:
411         ctx.set_source_rgb(1.0, 1.0, 0.5)
412     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
413     ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]+18-yoff-4)
414     ctx.show_text(txt)
415     
416     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
417     ctx.set_font_size(8)
418     ctx.set_source_rgb(0.6, 0.8, 0.8)
419     txt = "%d win" % wins
420     if wins != 1:
421         txt += "s"
422     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
423     ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]+30-yoff-3)
424     ctx.show_text(txt)
425     ctx.set_source_rgb(0.8, 0.8, 0.6)
426     txt = "%d loss" % losses
427     if losses != 1:
428         txt += "es"
429     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
430     ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]+40-yoff-3)
431     ctx.show_text(txt)
432
433
434     # print kill/death ratio
435
436     if params['overlay'] == 0:
437         ctx.rectangle(KILLDEATH_POS[0]-KILLDEATH_WIDTH/2, KILLDEATH_POS[1]-7, KILLDEATH_WIDTH, 15)
438         ctx.set_source_rgba(0.8, 0.8, 0.8, 0.1)
439         ctx.fill()
440
441     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
442     ctx.set_font_size(10)
443     ctx.set_source_rgb(0.8, 0.8, 0.8)
444     txt = "Kill Ratio"
445     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
446     ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]-yoff-3)
447     ctx.show_text(txt)
448     
449     kills, deaths = total_stats['kills'] , total_stats['deaths'] 
450     txt = "???"
451     try:
452         ratio = float(kills)/deaths
453         txt = "%.3f" % round(ratio, 3)
454     except:
455         ratio = 0
456
457     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
458     ctx.set_font_size(12)
459     if ratio >= 3:
460         ctx.set_source_rgb(0.0, 1.0, 0.0)
461     elif ratio >= 2:
462         ctx.set_source_rgb(0.2, 1.0, 0.2)
463     elif ratio >= 1:
464         ctx.set_source_rgb(0.5, 1.0, 0.5)
465     elif ratio >= 0.5:
466         ctx.set_source_rgb(1.0, 0.5, 0.5)
467     else:
468         ctx.set_source_rgb(1.0, 0.2, 0.2)
469     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
470     ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]+18-yoff-4)
471     ctx.show_text(txt)
472
473     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
474     ctx.set_font_size(8)
475     ctx.set_source_rgb(0.6, 0.8, 0.6)
476     txt = "%d kill" % kills
477     if kills != 1:
478         txt += "s"
479     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
480     ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]+30-yoff-3)
481     ctx.show_text(txt)
482     ctx.set_source_rgb(0.8, 0.6, 0.6)
483     txt = "%d death" % deaths
484     if deaths != 1:
485         txt += "s"
486     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
487     ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]+40-yoff-3)
488     ctx.show_text(txt)
489
490
491     # print playing time
492
493     if params['overlay'] == 0:
494         ctx.rectangle( PLAYTIME_POS[0]-PLAYTIME_WIDTH/2, PLAYTIME_POS[1]-7, PLAYTIME_WIDTH, 14)
495         ctx.set_source_rgba(0.8, 0.8, 0.8, 0.6)
496         ctx.fill();
497
498     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
499     ctx.set_font_size(10)
500     ctx.set_source_rgb(0.1, 0.1, 0.1)
501     txt = "Playing time: %s" % str(total_stats['alivetime'])
502     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
503     ctx.move_to(PLAYTIME_POS[0]-xoff-tw/2, PLAYTIME_POS[1]-yoff-4)
504     ctx.show_text(txt)
505
506
507     # save to PNG
508     surf.write_to_png(OUTPUT % data['player'].player_id)
509
510
511 # environment setup
512 env = bootstrap('../../../development.ini')
513 req = env['request']
514 req.matchdict = {'id':3}
515
516 print "Requesting player data from db ..."
517 start = datetime.now()
518 players = []
519 if NUM_PLAYERS:
520     players = DBSession.query(Player).\
521             filter(Player.player_id == PlayerElo.player_id).\
522             filter(Player.nick != None).\
523             filter(Player.player_id > 2).\
524             filter(Player.active_ind == True).\
525             limit(NUM_PLAYERS).all()
526 else:
527     players = DBSession.query(Player).\
528             filter(Player.player_id == PlayerElo.player_id).\
529             filter(Player.nick != None).\
530             filter(Player.player_id > 2).\
531             filter(Player.active_ind == True).\
532             all()
533
534 stop = datetime.now()
535 td = stop-start
536 total_seconds = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
537 print "Query took %.2f seconds" % (total_seconds)
538
539 print "Creating badges for %d players ..." % len(players)
540 start = datetime.now()
541 data_time, render_time = 0,0
542 for player in players:
543     req.matchdict['id'] = player.player_id
544
545     sstart = datetime.now()
546     data = get_data(player)
547     sstop = datetime.now()
548     td = sstop-sstart
549     total_seconds = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
550     data_time += total_seconds
551
552     sstart = datetime.now()
553     render_image(data)
554     sstop = datetime.now()
555     td = sstop-sstart
556     total_seconds = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
557     render_time += total_seconds
558
559 stop = datetime.now()
560 td = stop-start
561 total_seconds = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
562 print "Creating the badges took %.2f seconds (%.2f s per player)" % (total_seconds, total_seconds/float(len(players)))
563 print "Total time for redering images: %.2f s" % render_time
564 print "Total time for getting data: %.2f s" % data_time
565