]> de.git.xonotic.org Git - xonotic/xonstat.git/blob - xonstat/batch/badges/gen_badges.py
Fixed/improved some things in gen_badges.py (more colors, fixed playernick handling)
[xonotic/xonstat.git] / xonstat / batch / badges / gen_badges.py
1 #-*- coding: utf-8 -*-
2
3 import cairo as C
4 import sqlalchemy as sa
5 import sqlalchemy.sql.functions as func
6 from datetime import datetime
7 from mako.template import Template
8 from os import system
9 from pyramid.paster import bootstrap
10 from xonstat.models import *
11 from xonstat.views.player import player_info_data
12 from xonstat.util import qfont_decode
13 from colorsys import rgb_to_hls, hls_to_rgb
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 # parameters to affect the output, could be changed via URL
33 params = {
34     'width':        560,
35     'height':        70,
36     'bg':           1,                      # 0 - black, 1 - dark_wall
37     'font':         0,                      # 0 - xolonium, 1 - dejavu sans
38 }
39
40
41 # maximal number of query results (for testing, set to 0 to get all)
42 NUM_PLAYERS = 100
43
44
45 def get_data(player):
46     """Return player data as dict.
47     
48     This function is similar to the function in player.py but more optimized
49     for this purpose.
50     """
51
52     # total games
53     # wins/losses
54     # kills/deaths
55     # duel/dm/tdm/ctf elo + rank
56     
57     player_id = player.player_id
58     
59     total_stats = {}
60     
61     games_played = DBSession.query(
62             Game.game_type_cd, func.count(), func.sum(PlayerGameStat.alivetime)).\
63             filter(Game.game_id == PlayerGameStat.game_id).\
64             filter(PlayerGameStat.player_id == player_id).\
65             group_by(Game.game_type_cd).\
66             order_by(func.count().desc()).\
67             limit(3).all()  # limit to 3 gametypes!
68     
69     total_stats['games'] = 0
70     total_stats['games_breakdown'] = {}  # this is a dictionary inside a dictionary .. dictception?
71     total_stats['games_alivetime'] = {}
72     total_stats['gametypes'] = []
73     for (game_type_cd, games, alivetime) in games_played:
74         total_stats['games'] += games
75         total_stats['gametypes'].append(game_type_cd)
76         total_stats['games_breakdown'][game_type_cd] = games
77         total_stats['games_alivetime'][game_type_cd] = alivetime
78     
79     (total_stats['kills'], total_stats['deaths'], total_stats['suicides'],
80      total_stats['alivetime'],) = DBSession.query(
81             func.sum(PlayerGameStat.kills),
82             func.sum(PlayerGameStat.deaths),
83             func.sum(PlayerGameStat.suicides),
84             func.sum(PlayerGameStat.alivetime)).\
85             filter(PlayerGameStat.player_id == player_id).\
86             one()
87     
88     (total_stats['wins'],) = DBSession.query(
89             func.count("*")).\
90             filter(Game.game_id == PlayerGameStat.game_id).\
91             filter(PlayerGameStat.player_id == player_id).\
92             filter(Game.winner == PlayerGameStat.team or PlayerGameStat.rank == 1).\
93             one()
94     
95     ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
96             from_statement(
97                 "select pr.game_type_cd, pr.rank, overall.max_rank "
98                 "from player_ranks pr,  "
99                    "(select game_type_cd, max(rank) max_rank "
100                     "from player_ranks  "
101                     "group by game_type_cd) overall "
102                 "where pr.game_type_cd = overall.game_type_cd  "
103                 "and player_id = :player_id "
104                 "order by rank").\
105             params(player_id=player_id).all()
106     
107     ranks_dict = {}
108     for gtc,rank,max_rank in ranks:
109         ranks_dict[gtc] = (rank, max_rank)
110
111     elos = DBSession.query(PlayerElo).\
112             filter_by(player_id=player_id).\
113             order_by(PlayerElo.elo.desc()).\
114             all()
115     
116     elos_dict = {}
117     for elo in elos:
118         if elo.games > 32:
119             elos_dict[elo.game_type_cd] = elo.elo
120     
121     data = {
122             'player':player,
123             'total_stats':total_stats,
124             'ranks':ranks_dict,
125             'elos':elos_dict,
126         }
127         
128     #print data
129     return data
130
131
132 def render_image(data):
133     """Render an image from the given data fields."""
134     
135     width, height = params['width'], params['height']
136     output = "output/%s.png" % data['player'].player_id
137     
138     font = "Xolonium"
139     if params['font'] == 1:
140         font = "DejaVu Sans"
141
142     total_stats = data['total_stats']
143     total_games = total_stats['games']
144     elos = data["elos"]
145     ranks = data["ranks"]
146
147
148     ## create background
149
150     surf = C.ImageSurface(C.FORMAT_RGB24, width, height)
151     ctx = C.Context(surf)
152
153     # draw background (just plain fillcolor)
154     if params['bg'] == 0:
155         ctx.rectangle(0, 0, 1, 1);
156         ctx.set_source_rgba(0.2, 0.2, 0.2, 1.0);
157         ctx.fill();
158     
159     # draw background image (try to get correct tiling, too)
160     if params['bg'] > 0:
161         bg = None
162         if params['bg'] == 1:
163             bg = C.ImageSurface.create_from_png("img/dark_wall.png");
164         
165         if bg:
166             bg_w, bg_h = bg.get_width(), bg.get_height()
167             bg_xoff = 0
168             while bg_xoff < width:
169                 bg_yoff = 0
170                 while bg_yoff < height:
171                     ctx.set_source_surface(bg, bg_xoff, bg_yoff);
172                     ctx.paint()
173                     bg_yoff += bg_h
174                 bg_xoff += bg_w
175
176
177     ## draw player's nickname with fancy colors
178     
179     # fontsize is reduced if width gets too large - TODO: needs finetuning
180     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
181     ctx.set_font_size(18)
182     xoff, yoff, tw, th = ctx.text_extents(player.stripped_nick)[:4]
183     if tw > 340:
184         ctx.set_font_size(16)
185     xoff, yoff, tw, th = ctx.text_extents(player.stripped_nick)[:4]
186     if tw > 340:
187         ctx.set_font_size(14)
188     
189     # split up nick into colored segments and draw each of them
190     qstr = qfont_decode(player.nick).replace('^^', '^').replace('\x00', '')
191     txt_xoff = 0
192     txt_xpos, txt_ypos = 5,18
193     
194     # split nick into colored segments
195     parts = []
196     pos = 1
197     while True:
198         npos = qstr.find('^', pos)
199         if npos < 0:
200             parts.append(qstr[pos-1:])
201             break;
202         parts.append(qstr[pos-1:npos])
203         pos = npos+1
204     
205     for txt in parts:
206         r,g,b = _dec_colors[7]
207         try:
208             if txt.startswith('^'):
209                 txt = txt[1:]
210                 if txt.startswith('x'):
211                     r = int(txt[1] * 2, 16) / 255.0
212                     g = int(txt[2] * 2, 16) / 255.0
213                     b = int(txt[3] * 2, 16) / 255.0
214                     hue, light, satur = rgb_to_hls(r, g, b)
215                     if light < _contrast_threshold:
216                         light = _contrast_threshold
217                         r, g, b = hls_to_rgb(hue, light, satur)
218                     txt = txt[4:]
219                 else:
220                     r,g,b = _dec_colors[int(txt[0])]
221                     txt = txt[1:]
222         except:
223             r,g,b = _dec_colors[7]
224         
225         if len(txt) < 1:
226             # only colorcode and no real text, skip this
227             continue
228         
229         ctx.set_source_rgb(r, g, b)
230         ctx.move_to(txt_xpos + txt_xoff, txt_ypos)
231         ctx.show_text(txt)
232
233         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
234         if tw == 0:
235             # only whitespaces, use some extra space
236             tw += 5*len(txt)
237         
238         txt_xoff += tw + 1
239
240
241     ## print elos and ranks
242     
243     games_x, games_y = 60,35
244     games_w = 110       # width of each gametype field
245     
246     # show up to three gametypes the player has participated in
247     for gt in total_stats['gametypes'][:3]:
248         ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
249         ctx.set_font_size(10)
250         ctx.set_source_rgb(1.0, 1.0, 1.0)
251         txt = "[ %s ]" % gt.upper()
252         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
253         ctx.move_to(games_x-xoff-tw/2,games_y-yoff-th/2)
254         ctx.show_text(txt)
255         
256         ctx.set_line_width(1)
257         ctx.move_to(games_x-games_w/2+5, games_y+8);
258         ctx.line_to(games_x+games_w/2-5, games_y+8);
259         ctx.stroke()
260         ctx.move_to(games_x-games_w/2+5, games_y+32);
261         ctx.line_to(games_x+games_w/2-5, games_y+32);
262         ctx.stroke()
263         
264         if not elos.has_key(gt) or not ranks.has_key(gt):
265             ctx.select_font_face(font, C.FONT_SLANT_ITALIC, C.FONT_WEIGHT_NORMAL)
266             ctx.set_font_size(10)
267             ctx.set_source_rgb(0.6, 0.6, 0.6)
268             txt = "(no stats yet!)"
269             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
270             ctx.move_to(games_x-xoff-tw/2,games_y+22-yoff-th/2)
271             ctx.show_text(txt)
272         else:
273             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
274             ctx.set_font_size(10)
275             ctx.set_source_rgb(1.0, 1.0, 0.5)
276             txt = "Elo: %.0f" % round(elos[gt], 0)
277             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
278             ctx.move_to(games_x-xoff-tw/2,games_y+15-yoff-th/2)
279             ctx.show_text(txt)
280             
281             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
282             ctx.set_font_size(8)
283             ctx.set_source_rgb(0.8, 0.8, 0.8)
284             txt = "Rank %d of %d" % ranks[gt]
285             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
286             ctx.move_to(games_x-xoff-tw/2,games_y+25-yoff-th/2)
287             ctx.show_text(txt)
288         
289         games_x += games_w
290
291
292     # print win percentage
293     win_x, win_y = 500,18
294     
295     if total_games > 0 and total_stats['wins'] is not None:
296         ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
297         ctx.set_font_size(9)
298         ctx.set_source_rgb(0.8, 0.8, 0.8)
299         txt = "Win Percentage"
300         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
301         ctx.move_to(win_x-xoff-tw/2,win_y-yoff-th/2)
302         ctx.show_text(txt)
303         
304         ratio = float(total_stats['wins'])/total_games
305         ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
306         ctx.set_font_size(12)
307         if ratio >= 0.75:
308             ctx.set_source_rgb(0.5, 1.0, 1.0)
309         elif ratio >= 0.5:
310             ctx.set_source_rgb(0.6, 1.0, 0.8)
311         elif ratio >= 0.25:
312             ctx.set_source_rgb(0.8, 1.0, 0.6)
313         else:
314             ctx.set_source_rgb(1.0, 1.0, 0.5)
315         txt = "%.2f%%" % round(ratio * 100, 2)
316         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
317         ctx.move_to(win_x-xoff-tw/2,win_y+14-yoff-th/2)
318         ctx.show_text(txt)
319
320         ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
321         ctx.set_font_size(8)
322         ctx.set_source_rgb(0.6, 0.8, 0.6)
323         txt = "%d wins" % total_stats["wins"]
324         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
325         ctx.move_to(win_x-xoff-tw/2,win_y+28-yoff-th/2)
326         ctx.show_text(txt)
327         ctx.set_source_rgb(0.8, 0.6, 0.6)
328         txt = "%d losses" % (total_games-total_stats['wins'])
329         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
330         ctx.move_to(win_x-xoff-tw/2,win_y+38-yoff-th/2)
331         ctx.show_text(txt)
332
333     # print kill/death ratio
334     kill_x, kill_y = 400,18
335     if total_stats['kills'] > 0 and total_stats['deaths'] > 0:
336         ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
337         ctx.set_font_size(9)
338         ctx.set_source_rgb(0.8, 0.8, 0.8)
339         txt = "Kill Ratio"
340         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
341         ctx.move_to(kill_x-xoff-tw/2,kill_y-yoff-th/2)
342         ctx.show_text(txt)
343         
344         ratio = float(total_stats['kills'])/total_stats['deaths']
345         ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
346         ctx.set_font_size(12)
347         if ratio >= 2:
348             ctx.set_source_rgb(0.2, 1.0, 0.2)
349         elif ratio >= 1:
350             ctx.set_source_rgb(0.5, 1.0, 0.5)
351         elif ratio >= 0.5:
352             ctx.set_source_rgb(1.0, 0.5, 0.5)
353         else:
354             ctx.set_source_rgb(1.0, 0.2, 0.2)
355         txt = "%.3f" % round(ratio, 3)
356         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
357         ctx.move_to(kill_x-xoff-tw/2,kill_y+14-yoff-th/2)
358         ctx.show_text(txt)
359
360         ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
361         ctx.set_font_size(8)
362         ctx.set_source_rgb(0.6, 0.8, 0.6)
363         txt = "%d kills" % total_stats["kills"]
364         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
365         ctx.move_to(kill_x-xoff-tw/2,kill_y+28-yoff-th/2)
366         ctx.show_text(txt)
367         ctx.set_source_rgb(0.8, 0.6, 0.6)
368         txt = "%d deaths" % total_stats['deaths']
369         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
370         ctx.move_to(kill_x-xoff-tw/2,kill_y+38-yoff-th/2)
371         ctx.show_text(txt)
372
373     # save to PNG
374     surf.write_to_png(output)
375
376
377 # environment setup
378 env = bootstrap('../../../development.ini')
379 req = env['request']
380 req.matchdict = {'id':3}
381
382 print "Requesting player data from db ..."
383 start = datetime.now()
384 players = DBSession.query(Player).\
385         filter(Player.player_id == PlayerElo.player_id).\
386         filter(Player.nick != None).\
387         filter(Player.player_id > 2).\
388         filter(Player.active_ind == True).\
389         limit(NUM_PLAYERS).all()
390 stop = datetime.now()
391 print "Query took %.2f seconds" % (stop-start).total_seconds()
392
393 print "Creating badges for %d players ..." % len(players)
394 start = datetime.now()
395 data_time, render_time = 0,0
396 for player in players:
397     req.matchdict['id'] = player.player_id
398     
399     sstart = datetime.now()
400     #data = player_info_data(req)
401     data = get_data(player)
402     sstop = datetime.now()
403     data_time += (sstop-sstart).total_seconds()
404     
405     print "\t#%d (%s)" % (player.player_id, player.stripped_nick)
406
407     sstart = datetime.now()
408     render_image(data)
409     sstop = datetime.now()
410     render_time += (sstop-sstart).total_seconds()
411
412 stop = datetime.now()
413 print "Creating the badges took %.2f seconds (%.2f s per player)" % ((stop-start).total_seconds(), (stop-start).total_seconds()/float(len(players)))
414 print "Total time for getting data: %.2f s" % data_time
415 print "Total time for redering images: %.2f s" % render_time
416