4 import sqlalchemy as sa
5 import sqlalchemy.sql.functions as func
6 from datetime import datetime
7 from mako.template import Template
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
16 # similar to html_colors() from util.py
17 _contrast_threshold = 0.5
19 _dec_colors = [ (0.5,0.5,0.5),
32 # parameters to affect the output, could be changed via URL
36 'bg': 1, # 0 - black, 1 - dark_wall
37 'font': 0, # 0 - xolonium, 1 - dejavu sans
38 'gametypes': ['duel','dm','ctf'], # up to three gametypes to show
42 # maximal number of query results (for testing, set to 0 to get all)
47 """Return player data as dict.
49 This function is similar to the function in player.py but more optimized
56 # duel/dm/tdm/ctf elo + rank
58 player_id = player.player_id
62 games_played = DBSession.query(
63 Game.game_type_cd, func.count(), func.sum(PlayerGameStat.alivetime)).\
64 filter(Game.game_id == PlayerGameStat.game_id).\
65 filter(PlayerGameStat.player_id == player_id).\
66 group_by(Game.game_type_cd).\
67 order_by(func.count().desc()).\
70 total_stats['games'] = 0
71 total_stats['games_breakdown'] = {} # this is a dictionary inside a dictionary .. dictception?
72 total_stats['games_alivetime'] = {}
73 for (game_type_cd, games, alivetime) in games_played:
74 total_stats['games'] += games
75 total_stats['games_breakdown'][game_type_cd] = games
76 total_stats['games_alivetime'][game_type_cd] = alivetime
78 (total_stats['kills'], total_stats['deaths'], total_stats['suicides'],
79 total_stats['alivetime'],) = DBSession.query(
80 func.sum(PlayerGameStat.kills),
81 func.sum(PlayerGameStat.deaths),
82 func.sum(PlayerGameStat.suicides),
83 func.sum(PlayerGameStat.alivetime)).\
84 filter(PlayerGameStat.player_id == player_id).\
87 (total_stats['wins'],) = DBSession.query(
89 filter(Game.game_id == PlayerGameStat.game_id).\
90 filter(PlayerGameStat.player_id == player_id).\
91 filter(Game.winner == PlayerGameStat.team or PlayerGameStat.rank == 1).\
94 ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
96 "select pr.game_type_cd, pr.rank, overall.max_rank "
97 "from player_ranks pr, "
98 "(select game_type_cd, max(rank) max_rank "
100 "group by game_type_cd) overall "
101 "where pr.game_type_cd = overall.game_type_cd "
102 "and player_id = :player_id "
104 params(player_id=player_id).all()
107 for gtc,rank,max_rank in ranks:
108 ranks_dict[gtc] = (rank, max_rank)
110 elos = DBSession.query(PlayerElo).\
111 filter_by(player_id=player_id).\
112 order_by(PlayerElo.elo.desc()).\
118 elos_dict[elo.game_type_cd] = elo.elo
122 'total_stats':total_stats,
131 def render_image(data):
132 """Render an image from the given data fields."""
134 width, height = params['width'], params['height']
135 output = "output/%s.png" % data['player'].player_id
138 if params['font'] == 1:
144 surf = C.ImageSurface(C.FORMAT_RGB24, width, height)
145 ctx = C.Context(surf)
147 # draw background (just plain fillcolor)
148 if params['bg'] == 0:
149 ctx.rectangle(0, 0, 1, 1);
150 ctx.set_source_rgba(0.2, 0.2, 0.2, 1.0);
153 # draw background image (try to get correct tiling, too)
156 if params['bg'] == 1:
157 bg = C.ImageSurface.create_from_png("img/dark_wall.png");
160 bg_w, bg_h = bg.get_width(), bg.get_height()
162 while bg_xoff < width:
164 while bg_yoff < height:
165 ctx.set_source_surface(bg, bg_xoff, bg_yoff);
171 ## draw player's nickname with fancy colors
173 # fontsize is reduced if width gets too large - TODO: needs finetuning
174 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
175 ctx.set_font_size(18)
176 xoff, yoff, tw, th = ctx.text_extents(player.stripped_nick)[:4]
178 ctx.set_font_size(16)
179 xoff, yoff, tw, th = ctx.text_extents(player.stripped_nick)[:4]
181 ctx.set_font_size(14)
183 # split up nick into colored segments and draw each of them
184 qstr = qfont_decode(player.nick).replace('^^', '^')
186 txt_xpos, txt_ypos = 5,18
187 for txt in qstr.split('^'):
189 if txt.startswith('x'):
190 r = int(txt[1] * 2, 16) / 255.0
191 g = int(txt[2] * 2, 16) / 255.0
192 b = int(txt[3] * 2, 16) / 255.0
193 hue, light, satur = rgb_to_hls(r, g, b)
194 if light < _contrast_threshold:
195 light = _contrast_threshold
196 r, g, b = hls_to_rgb(hue, light, satur)
199 r,g,b = _dec_colors[int(txt[0])]
202 r,g,b = _dec_colors[7]
205 # only colorcode and no real text, skip this
208 ctx.set_source_rgb(r, g, b)
209 ctx.move_to(txt_xpos + txt_xoff, txt_ypos)
212 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
214 # only whitespaces, use some extra space
219 ## print elos and ranks
222 ranks = data["ranks"]
223 games_x, games_y = 60,35
224 games_w = 110 # width of each gametype field
226 for gt in params['gametypes']:
227 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
228 ctx.set_font_size(10)
229 ctx.set_source_rgb(1.0, 1.0, 1.0)
230 txt = "[ %s ]" % gt.upper()
231 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
232 ctx.move_to(games_x-xoff-tw/2,games_y-yoff-th/2)
235 ctx.set_line_width(1)
236 ctx.move_to(games_x-games_w/2+5, games_y+8);
237 ctx.line_to(games_x+games_w/2-5, games_y+8);
239 ctx.move_to(games_x-games_w/2+5, games_y+32);
240 ctx.line_to(games_x+games_w/2-5, games_y+32);
243 if not elos.has_key(gt) or not ranks.has_key(gt):
244 ctx.select_font_face(font, C.FONT_SLANT_ITALIC, C.FONT_WEIGHT_NORMAL)
245 ctx.set_font_size(10)
246 ctx.set_source_rgb(0.7, 0.7, 0.7)
247 txt = "(no stats yet!)"
248 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
249 ctx.move_to(games_x-xoff-tw/2,games_y+22-yoff-th/2)
252 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
253 ctx.set_font_size(10)
254 ctx.set_source_rgb(1.0, 1.0, 1.0)
255 txt = "Elo: %.0f" % round(elos[gt], 0)
256 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
257 ctx.move_to(games_x-xoff-tw/2,games_y+15-yoff-th/2)
260 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
262 ctx.set_source_rgb(0.7, 0.7, 0.7)
263 txt = "Rank %d of %d" % ranks[gt]
264 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
265 ctx.move_to(games_x-xoff-tw/2,games_y+25-yoff-th/2)
271 # print win percentage
272 total_stats = data['total_stats']
273 total_games = total_stats['games']
274 win_x, win_y = 500,18
276 if total_games > 0 and total_stats['wins'] is not None:
277 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
279 ctx.set_source_rgb(0.5, 0.5, 0.5)
280 txt = "Win Percentage"
281 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
282 ctx.move_to(win_x-xoff-tw/2,win_y-yoff-th/2)
285 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
286 ctx.set_font_size(12)
287 ctx.set_source_rgb(1.0, 1.0, 1.0)
288 txt = "%.2f%%" % round(float(total_stats['wins'])/total_games * 100, 2)
289 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
290 ctx.move_to(win_x-xoff-tw/2,win_y+14-yoff-th/2)
293 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
295 ctx.set_source_rgb(0.8, 0.8, 0.8)
296 txt = "%d wins" % total_stats["wins"]
297 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
298 ctx.move_to(win_x-xoff-tw/2,win_y+28-yoff-th/2)
300 txt = "%d losses" % (total_games-total_stats['wins'])
301 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
302 ctx.move_to(win_x-xoff-tw/2,win_y+38-yoff-th/2)
305 # print kill/death ratio
306 kill_x, kill_y = 400,18
307 if total_stats['kills'] > 0 and total_stats['deaths'] > 0:
308 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
310 ctx.set_source_rgb(0.5, 0.5, 0.5)
312 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
313 ctx.move_to(kill_x-xoff-tw/2,kill_y-yoff-th/2)
316 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
317 ctx.set_font_size(12)
318 ctx.set_source_rgb(1.0, 1.0, 1.0)
319 txt = "%.3f" % round(float(total_stats['kills'])/total_stats['deaths'], 3)
320 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
321 ctx.move_to(kill_x-xoff-tw/2,kill_y+14-yoff-th/2)
324 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
326 ctx.set_source_rgb(0.8, 0.8, 0.8)
327 txt = "%d kills" % total_stats["kills"]
328 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
329 ctx.move_to(kill_x-xoff-tw/2,kill_y+28-yoff-th/2)
331 txt = "%d deaths" % total_stats['deaths']
332 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
333 ctx.move_to(kill_x-xoff-tw/2,kill_y+38-yoff-th/2)
337 surf.write_to_png(output)
341 env = bootstrap('../../../development.ini')
343 req.matchdict = {'id':3}
345 print "Requesting player data from db ..."
346 start = datetime.now()
347 players = DBSession.query(Player).\
348 filter(Player.player_id == PlayerElo.player_id).\
349 filter(Player.nick != None).\
350 filter(Player.player_id > 2).\
351 filter(Player.active_ind == True).\
352 limit(NUM_PLAYERS).all()
353 stop = datetime.now()
354 print "Query took %.2f seconds" % (stop-start).total_seconds()
356 print "Creating badges for %d players ..." % len(players)
357 start = datetime.now()
358 data_time, render_time = 0,0
359 for player in players:
360 req.matchdict['id'] = player.player_id
362 sstart = datetime.now()
363 #data = player_info_data(req)
364 data = get_data(player)
365 sstop = datetime.now()
366 data_time += (sstop-sstart).total_seconds()
368 print "\t#%d (%s)" % (player.player_id, player.stripped_nick)
370 sstart = datetime.now()
372 sstop = datetime.now()
373 render_time += (sstop-sstart).total_seconds()
375 stop = datetime.now()
376 print "Creating the badges took %.2f seconds (%.2f s per player)" % ((stop-start).total_seconds(), (stop-start).total_seconds()/float(len(players)))
377 print "Total time for getting data: %.2f s" % data_time
378 print "Total time for redering images: %.2f s" % render_time