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
11 from pyramid.paster import bootstrap
12 from xonstat.models import *
13 from xonstat.util import qfont_decode, _all_colors
16 # similar to html_colors() from util.py
17 _contrast_threshold = 0.5
19 _dec_colors = [ (0.5,0.5,0.5),
32 # maximal number of query results (for testing, set to 0 to get all)
35 # image dimensions (likely breaks layout if changed)
39 # output filename, parameter is player id
40 OUTPUT = "output/%d.png"
52 KILLDEATH_POS = (390,6)
55 PLAYTIME_POS = (452,64)
59 # parameters to affect the output, could be changed via URL
61 'bg': 1, # 0 - black, 1 - dark_wall, ...
62 'overlay': 0, # 0 - none, 1 - default overlay, ...
63 'font': 0, # 0 - xolonium, 1 - dejavu sans
67 # parse cmdline parameters (for testing)
68 for arg in sys.argv[1:]:
71 if params.has_key(k.lower()):
78 """Return player data as dict.
80 This function is similar to the function in player.py but more optimized
87 # duel/dm/tdm/ctf elo + rank
89 player_id = player.player_id
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!
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
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).\
118 # (total_stats['wins'],) = DBSession.query(
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).\
125 (total_stats['wins'],) = DBSession.\
126 query("total_wins").\
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()
135 ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
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 "
141 "group by game_type_cd) overall "
142 "where pr.game_type_cd = overall.game_type_cd "
143 "and player_id = :player_id "
145 params(player_id=player_id).all()
148 for gtc,rank,max_rank in ranks:
149 ranks_dict[gtc] = (rank, max_rank)
151 elos = DBSession.query(PlayerElo).\
152 filter_by(player_id=player_id).\
153 order_by(PlayerElo.elo.desc()).\
159 elos_dict[elo.game_type_cd] = elo.elo
163 'total_stats':total_stats,
172 def render_image(data):
173 """Render an image from the given data fields."""
175 if params['font'] == 1:
178 total_stats = data['total_stats']
179 total_games = total_stats['games']
181 ranks = data["ranks"]
186 surf = C.ImageSurface(C.FORMAT_RGB24, WIDTH, HEIGHT)
187 ctx = C.Context(surf)
188 ctx.set_antialias(C.ANTIALIAS_GRAY)
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
196 # draw background image (try to get correct tiling, too)
199 if params['bg'] == 1:
200 bg = C.ImageSurface.create_from_png("img/dark_wall.png")
201 elif params['bg'] == 2:
202 bg = C.ImageSurface.create_from_png("img/asfalt.png")
203 elif params['bg'] == 3:
204 bg = C.ImageSurface.create_from_png("img/broken_noise.png")
205 elif params['bg'] == 4:
206 bg = C.ImageSurface.create_from_png("img/burried.png")
207 elif params['bg'] == 5:
208 bg = C.ImageSurface.create_from_png("img/dark_leather.png")
209 elif params['bg'] == 6:
210 bg = C.ImageSurface.create_from_png("img/txture.png")
211 elif params['bg'] == 7:
212 bg = C.ImageSurface.create_from_png("img/black_linen_v2.png")
213 elif params['bg'] == 8:
214 bg = C.ImageSurface.create_from_png("img/background_archer-v1.png")
218 bg_w, bg_h = bg.get_width(), bg.get_height()
220 while bg_xoff < WIDTH:
222 while bg_yoff < HEIGHT:
223 ctx.set_source_surface(bg, bg_xoff, bg_yoff)
228 # draw overlay graphic
229 if params['overlay'] > 0:
231 if params['overlay'] == 1:
232 overlay = C.ImageSurface.create_from_png("img/overlay.png")
234 ctx.set_source_surface(overlay, 0, 0)
235 ctx.mask_surface(overlay)
239 ## draw player's nickname with fancy colors
241 # deocde nick, strip all weird-looking characters
242 qstr = qfont_decode(player.nick).replace('^^', '^').replace(u'\x00', '')
247 qstr = ''.join(chars)
248 stripped_nick = strip_colors(qstr)
250 # fontsize is reduced if width gets too large
251 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
252 ctx.set_font_size(20)
253 xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
254 if tw > NICK_MAXWIDTH:
255 ctx.set_font_size(18)
256 xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
257 if tw > NICK_MAXWIDTH:
258 ctx.set_font_size(16)
259 xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
260 if tw > NICK_MAXWIDTH:
261 ctx.set_font_size(14)
262 xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
263 if tw > NICK_MAXWIDTH:
264 ctx.set_font_size(12)
266 # split up nick into colored segments and draw each of them
268 # split nick into colored segments
270 _all_colors = re.compile(r'(\^\d|\^x[\dA-Fa-f]{3})')
271 #print qstr, _all_colors.findall(qstr), _all_colors.split(qstr)
273 parts = _all_colors.split(qstr)
274 while len(parts) > 0:
277 if _all_colors.match(txt):
278 tag = txt[1:] # strip leading '^'
285 if not txt or len(txt) == 0:
286 # only colorcode and no real text, skip this
289 r,g,b = _dec_colors[7]
291 if tag.startswith('x'):
292 r = int(tag[1] * 2, 16) / 255.0
293 g = int(tag[2] * 2, 16) / 255.0
294 b = int(tag[3] * 2, 16) / 255.0
295 hue, light, satur = rgb_to_hls(r, g, b)
296 if light < _contrast_threshold:
297 light = _contrast_threshold
298 r, g, b = hls_to_rgb(hue, light, satur)
300 r,g,b = _dec_colors[int(tag[0])]
302 r,g,b = _dec_colors[7]
304 ctx.set_source_rgb(r, g, b)
305 ctx.move_to(NICK_POS[0] + xoffset, NICK_POS[1])
308 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
309 tw += (len(txt)-len(txt.strip()))*3 # account for lost whitespaces
313 ## print elos and ranks
315 # show up to three gametypes the player has participated in
317 for gt in total_stats['gametypes'][:3]:
318 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
319 ctx.set_font_size(10)
320 ctx.set_source_rgb(1.0, 1.0, 1.0)
321 txt = "[ %s ]" % gt.upper()
322 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
323 ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]-yoff-4)
327 old_aa = ctx.get_antialias()
328 ctx.set_antialias(C.ANTIALIAS_NONE)
329 ctx.set_source_rgb(0.8, 0.8, 0.8)
330 ctx.set_line_width(1)
331 ctx.move_to(GAMES_POS[0]+xoffset-GAMES_WIDTH/2+5, GAMES_POS[1]+8)
332 ctx.line_to(GAMES_POS[0]+xoffset+GAMES_WIDTH/2-5, GAMES_POS[1]+8)
334 ctx.move_to(GAMES_POS[0]+xoffset-GAMES_WIDTH/2+5, GAMES_POS[1]+32)
335 ctx.line_to(GAMES_POS[0]+xoffset+GAMES_WIDTH/2-5, GAMES_POS[1]+32)
337 ctx.set_antialias(old_aa)
339 if not elos.has_key(gt) or not ranks.has_key(gt):
340 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
341 ctx.set_font_size(12)
342 ctx.set_source_rgb(0.8, 0.2, 0.2)
343 txt = "no stats yet!"
344 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
345 ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]+28-yoff-4)
347 ctx.rotate(math.radians(-10))
351 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
352 ctx.set_font_size(10)
353 ctx.set_source_rgb(1.0, 1.0, 0.5)
354 txt = "Elo: %.0f" % round(elos[gt], 0)
355 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
356 ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]+15-yoff-4)
359 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
361 ctx.set_source_rgb(0.8, 0.8, 1.0)
362 txt = "Rank %d of %d" % ranks[gt]
363 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
364 ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]+25-yoff-3)
367 xoffset += GAMES_WIDTH
370 # print win percentage
372 if params['overlay'] == 0:
373 ctx.rectangle(WINLOSS_POS[0]-WINLOSS_WIDTH/2, WINLOSS_POS[1]-7, WINLOSS_WIDTH, 15)
374 ctx.set_source_rgba(0.8, 0.8, 0.8, 0.1)
377 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
378 ctx.set_font_size(10)
379 ctx.set_source_rgb(0.8, 0.8, 0.8)
380 txt = "Win Percentage"
381 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
382 ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]-yoff-3)
385 wins, losses = total_stats["wins"], total_games-total_stats["wins"]
388 ratio = float(wins)/total_games
389 txt = "%.2f%%" % round(ratio * 100, 2)
392 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
393 ctx.set_font_size(12)
395 ctx.set_source_rgb(0.2, 1.0, 1.0)
397 ctx.set_source_rgb(0.5, 1.0, 1.0)
399 ctx.set_source_rgb(0.5, 1.0, 0.8)
401 ctx.set_source_rgb(0.8, 1.0, 0.5)
403 ctx.set_source_rgb(1.0, 1.0, 0.5)
404 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
405 ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]+18-yoff-4)
408 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
410 ctx.set_source_rgb(0.6, 0.8, 0.8)
411 txt = "%d win" % wins
414 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
415 ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]+30-yoff-3)
417 ctx.set_source_rgb(0.8, 0.8, 0.6)
418 txt = "%d loss" % losses
421 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
422 ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]+40-yoff-3)
426 # print kill/death ratio
428 if params['overlay'] == 0:
429 ctx.rectangle(KILLDEATH_POS[0]-KILLDEATH_WIDTH/2, KILLDEATH_POS[1]-7, KILLDEATH_WIDTH, 15)
430 ctx.set_source_rgba(0.8, 0.8, 0.8, 0.1)
433 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
434 ctx.set_font_size(10)
435 ctx.set_source_rgb(0.8, 0.8, 0.8)
437 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
438 ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]-yoff-3)
441 kills, deaths = total_stats['kills'] , total_stats['deaths']
444 ratio = float(kills)/deaths
445 txt = "%.3f" % round(ratio, 3)
449 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
450 ctx.set_font_size(12)
452 ctx.set_source_rgb(0.0, 1.0, 0.0)
454 ctx.set_source_rgb(0.2, 1.0, 0.2)
456 ctx.set_source_rgb(0.5, 1.0, 0.5)
458 ctx.set_source_rgb(1.0, 0.5, 0.5)
460 ctx.set_source_rgb(1.0, 0.2, 0.2)
461 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
462 ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]+18-yoff-4)
465 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
467 ctx.set_source_rgb(0.6, 0.8, 0.6)
468 txt = "%d kill" % kills
471 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
472 ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]+30-yoff-3)
474 ctx.set_source_rgb(0.8, 0.6, 0.6)
475 txt = "%d death" % deaths
478 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
479 ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]+40-yoff-3)
485 if params['overlay'] == 0:
486 ctx.rectangle( PLAYTIME_POS[0]-PLAYTIME_WIDTH/2, PLAYTIME_POS[1]-7, PLAYTIME_WIDTH, 14)
487 ctx.set_source_rgba(0.8, 0.8, 0.8, 0.6)
490 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
491 ctx.set_font_size(10)
492 ctx.set_source_rgb(0.1, 0.1, 0.1)
493 txt = "Playing time: %s" % str(total_stats['alivetime'])
494 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
495 ctx.move_to(PLAYTIME_POS[0]-xoff-tw/2, PLAYTIME_POS[1]-yoff-4)
500 surf.write_to_png(OUTPUT % data['player'].player_id)
504 env = bootstrap('../../../development.ini')
506 req.matchdict = {'id':3}
508 print "Requesting player data from db ..."
509 start = datetime.now()
510 players = DBSession.query(Player).\
511 filter(Player.player_id == PlayerElo.player_id).\
512 filter(Player.nick != None).\
513 filter(Player.player_id > 2).\
514 filter(Player.active_ind == True).\
517 stop = datetime.now()
519 total_seconds = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
520 print "Query took %.2f seconds" % (total_seconds)
522 print "Creating badges for %d players ..." % len(players)
523 start = datetime.now()
524 data_time, render_time = 0,0
525 for player in players:
526 req.matchdict['id'] = player.player_id
528 sstart = datetime.now()
529 data = get_data(player)
530 sstop = datetime.now()
532 total_seconds = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
533 data_time += total_seconds
535 sstart = datetime.now()
537 sstop = datetime.now()
539 total_seconds = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
540 render_time += total_seconds
542 stop = datetime.now()
544 total_seconds = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
545 print "Creating the badges took %.2f seconds (%.2f s per player)" % (total_seconds, total_seconds/float(len(players)))
546 print "Total time for redering images: %.2f s" % render_time
547 print "Total time for getting data: %.2f s" % data_time