]> de.git.xonotic.org Git - xonotic/xonstat.git/commitdiff
Merge branch 'badges' into approved
authorJan D. Behrens <zykure@web.de>
Sat, 15 Sep 2012 16:45:51 +0000 (18:45 +0200)
committerJan D. Behrens <zykure@web.de>
Sat, 15 Sep 2012 16:45:51 +0000 (18:45 +0200)
Conflicts:
xonstat/batch/badges/gen_badges.py

1  2 
xonstat/batch/badges/gen_badges.py
xonstat/templates/base.mako
xonstat/templates/player_info.mako

index 7a092b2bd9ff9a22372b218ae046feaf17f65c81,1d3acf1a02c1ac49ba69a73f69129a420560aa0d..0aa3f6014f28ced6956835d349b909925e9e77e6
  #-*- coding: utf-8 -*-
  
- import cairo as C
+ import sys
+ from datetime import datetime
  import sqlalchemy as sa
  import sqlalchemy.sql.functions as func
- from datetime import datetime
- from mako.template import Template
- from os import system
+ from sqlalchemy import distinct
  from pyramid.paster import bootstrap
  from xonstat.models import *
- from xonstat.views.player import player_info_data
- from xonstat.util import qfont_decode
- from colorsys import rgb_to_hls, hls_to_rgb
- # similar to html_colors() from util.py
- _contrast_threshold = 0.5
- _dec_colors = [ (0.5,0.5,0.5),
-                 (1.0,0.0,0.0),
-                 (0.2,1.0,0.0),
-                 (1.0,1.0,0.0),
-                 (0.2,0.4,1.0),
-                 (0.2,1.0,1.0),
-                 (1.0,0.2,102),
-                 (1.0,1.0,1.0),
-                 (0.6,0.6,0.6),
-                 (0.5,0.5,0.5)
-             ]
- # parameters to affect the output, could be changed via URL
- params = {
-     'width':        560,
-     'height':        70,
-     'bg':           1,                      # 0 - black, 1 - dark_wall
-     'font':         0,                      # 0 - xolonium, 1 - dejavu sans
- }
- # maximal number of query results (for testing, set to 0 to get all)
- NUM_PLAYERS = 100
- def get_data(player):
-     """Return player data as dict.
-     
-     This function is similar to the function in player.py but more optimized
-     for this purpose.
-     """
-     # total games
-     # wins/losses
-     # kills/deaths
-     # duel/dm/tdm/ctf elo + rank
-     
-     player_id = player.player_id
-     
-     total_stats = {}
-     
-     games_played = DBSession.query(
-             Game.game_type_cd, func.count(), func.sum(PlayerGameStat.alivetime)).\
-             filter(Game.game_id == PlayerGameStat.game_id).\
-             filter(PlayerGameStat.player_id == player_id).\
-             group_by(Game.game_type_cd).\
-             order_by(func.count().desc()).\
-             limit(3).all()  # limit to 3 gametypes!
-     
-     total_stats['games'] = 0
-     total_stats['games_breakdown'] = {}  # this is a dictionary inside a dictionary .. dictception?
-     total_stats['games_alivetime'] = {}
-     total_stats['gametypes'] = []
-     for (game_type_cd, games, alivetime) in games_played:
-         total_stats['games'] += games
-         total_stats['gametypes'].append(game_type_cd)
-         total_stats['games_breakdown'][game_type_cd] = games
-         total_stats['games_alivetime'][game_type_cd] = alivetime
-     
-     (total_stats['kills'], total_stats['deaths'], total_stats['suicides'],
-      total_stats['alivetime'],) = DBSession.query(
-             func.sum(PlayerGameStat.kills),
-             func.sum(PlayerGameStat.deaths),
-             func.sum(PlayerGameStat.suicides),
-             func.sum(PlayerGameStat.alivetime)).\
-             filter(PlayerGameStat.player_id == player_id).\
-             one()
-     
-     (total_stats['wins'],) = DBSession.query(
-             func.count("*")).\
-             filter(Game.game_id == PlayerGameStat.game_id).\
-             filter(PlayerGameStat.player_id == player_id).\
-             filter(Game.winner == PlayerGameStat.team or PlayerGameStat.rank == 1).\
-             one()
-     
-     ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
-             from_statement(
-                 "select pr.game_type_cd, pr.rank, overall.max_rank "
-                 "from player_ranks pr,  "
-                    "(select game_type_cd, max(rank) max_rank "
-                     "from player_ranks  "
-                     "group by game_type_cd) overall "
-                 "where pr.game_type_cd = overall.game_type_cd  "
-                 "and player_id = :player_id "
-                 "order by rank").\
-             params(player_id=player_id).all()
-     
-     ranks_dict = {}
-     for gtc,rank,max_rank in ranks:
-         ranks_dict[gtc] = (rank, max_rank)
-     elos = DBSession.query(PlayerElo).\
-             filter_by(player_id=player_id).\
-             order_by(PlayerElo.elo.desc()).\
-             all()
-     
-     elos_dict = {}
-     for elo in elos:
-         if elo.games > 32:
-             elos_dict[elo.game_type_cd] = elo.elo
-     
-     data = {
-             'player':player,
-             'total_stats':total_stats,
-             'ranks':ranks_dict,
-             'elos':elos_dict,
-         }
-         
-     #print data
-     return data
- def render_image(data):
-     """Render an image from the given data fields."""
-     
-     width, height = params['width'], params['height']
-     output = "output/%s.png" % data['player'].player_id
-     
-     font = "Xolonium"
-     if params['font'] == 1:
-         font = "DejaVu Sans"
-     total_stats = data['total_stats']
-     total_games = total_stats['games']
-     elos = data["elos"]
-     ranks = data["ranks"]
-     ## create background
-     surf = C.ImageSurface(C.FORMAT_RGB24, width, height)
-     ctx = C.Context(surf)
-     ctx.set_antialias(C.ANTIALIAS_GRAY)
  
-     # draw background (just plain fillcolor)
-     if params['bg'] == 0:
-         ctx.rectangle(0, 0, width, height)
-         ctx.set_source_rgba(0.2, 0.2, 0.2, 1.0)
-         ctx.fill()
-     
-     # draw background image (try to get correct tiling, too)
-     if params['bg'] > 0:
-         bg = None
-         if params['bg'] == 1:
-             bg = C.ImageSurface.create_from_png("img/dark_wall.png")
-         
-         if bg:
-             bg_w, bg_h = bg.get_width(), bg.get_height()
-             bg_xoff = 0
-             while bg_xoff < width:
-                 bg_yoff = 0
-                 while bg_yoff < height:
-                     ctx.set_source_surface(bg, bg_xoff, bg_yoff)
-                     ctx.paint()
-                     bg_yoff += bg_h
-                 bg_xoff += bg_w
-     ## draw player's nickname with fancy colors
-     
-     # fontsize is reduced if width gets too large
-     nick_xmax = 335
-     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
-     ctx.set_font_size(20)
-     xoff, yoff, tw, th = ctx.text_extents(player.stripped_nick)[:4]
-     if tw > nick_xmax:
-         ctx.set_font_size(18)
-         xoff, yoff, tw, th = ctx.text_extents(player.stripped_nick)[:4]
-         if tw > nick_xmax:
-             ctx.set_font_size(16)
-             xoff, yoff, tw, th = ctx.text_extents(player.stripped_nick)[:4]
-             if tw > nick_xmax:
-                 ctx.set_font_size(14)
-                 xoff, yoff, tw, th = ctx.text_extents(player.stripped_nick)[:4]
-                 if tw > nick_xmax:
-                     ctx.set_font_size(12)
-     
-     # split up nick into colored segments and draw each of them
-     qstr = qfont_decode(player.nick).replace('^^', '^').replace('\x00', ' ')
-     txt_xoff = 0
-     txt_xpos, txt_ypos = 5,18
-     
-     # split nick into colored segments
-     parts = []
-     pos = 1
-     while True:
-         npos = qstr.find('^', pos)
-         if npos < 0:
-             parts.append(qstr[pos-1:])
-             break;
-         parts.append(qstr[pos-1:npos])
-         pos = npos+1
-     
-     for txt in parts:
-         r,g,b = _dec_colors[7]
-         try:
-             if txt.startswith('^'):
-                 txt = txt[1:]
-                 if txt.startswith('x'):
-                     r = int(txt[1] * 2, 16) / 255.0
-                     g = int(txt[2] * 2, 16) / 255.0
-                     b = int(txt[3] * 2, 16) / 255.0
-                     hue, light, satur = rgb_to_hls(r, g, b)
-                     if light < _contrast_threshold:
-                         light = _contrast_threshold
-                         r, g, b = hls_to_rgb(hue, light, satur)
-                     txt = txt[4:]
-                 else:
-                     r,g,b = _dec_colors[int(txt[0])]
-                     txt = txt[1:]
-         except:
-             r,g,b = _dec_colors[7]
-         
-         if len(txt) < 1:
-             # only colorcode and no real text, skip this
-             continue
-         
-         ctx.set_source_rgb(r, g, b)
-         ctx.move_to(txt_xpos + txt_xoff, txt_ypos)
-         ctx.show_text(txt)
-         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
-         if tw == 0:
-             # only whitespaces, use some extra space
-             tw += 5*len(txt)
-         
-         txt_xoff += tw + 1
-     ## print elos and ranks
-     
-     games_x, games_y = 60,35
-     games_w = 110       # width of each gametype field
-     
-     # show up to three gametypes the player has participated in
-     for gt in total_stats['gametypes'][:3]:
-         ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
-         ctx.set_font_size(10)
-         ctx.set_source_rgb(1.0, 1.0, 1.0)
-         txt = "[ %s ]" % gt.upper()
-         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
-         ctx.move_to(games_x-xoff-tw/2,games_y-yoff-4)
-         ctx.show_text(txt)
-         
-         old_aa = ctx.get_antialias()
-         ctx.set_antialias(C.ANTIALIAS_NONE)
-         ctx.set_source_rgb(0.8, 0.8, 0.8)
-         ctx.set_line_width(1)
-         ctx.move_to(games_x-games_w/2+5, games_y+8)
-         ctx.line_to(games_x+games_w/2-5, games_y+8)
-         ctx.stroke()
-         ctx.move_to(games_x-games_w/2+5, games_y+32)
-         ctx.line_to(games_x+games_w/2-5, games_y+32)
-         ctx.stroke()
-         ctx.set_antialias(old_aa)
-         
-         if not elos.has_key(gt) or not ranks.has_key(gt):
-             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
-             ctx.set_font_size(12)
-             ctx.set_source_rgb(0.8, 0.2, 0.2)
-             txt = "no stats yet!"
-             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
-             ctx.move_to(games_x-xoff-tw/2,games_y+28-yoff-4)
-             ctx.save()
-             ctx.rotate(math.radians(-10))
-             ctx.show_text(txt)
-             ctx.restore()
+ from skin import Skin
+ from playerdata import PlayerData
+ # maximal number of query results (for testing, set to None to get all)
+ NUM_PLAYERS = None
+ # we look for players who have activity within the past DELTA hours
+ DELTA = 6
+ # classic skin WITHOUT NAME - writes PNGs into "output//###.png"
+ skin_classic = Skin( "",
+         bg              = "broken_noise",
+         overlay         = "overlay_classic",
+     )
+ # more fancy skin [** WIP **]- writes PNGs into "output/archer/###.png"
+ skin_archer = Skin( "archer",
+         bg              = "background_archer-v1",
+         overlay         = None,
+     )
+ # minimal skin - writes PNGs into "output/minimal/###.png"
+ skin_minimal = Skin( "minimal",
+         bg              = None,
+         bgcolor         = (0.04, 0.04, 0.04, 1.0),
+         overlay         = "overlay_minimal",
+         width           = 560,
+         height          = 40,
+         nick_fontsize   = 16,
+         nick_pos        = (36,16),
+         num_gametypes   = 3,
+         nick_maxwidth   = 300,
+         gametype_pos    = (70,30),
+         gametype_color  = (0.0, 0.0, 0.0),
+         gametype_text   = "%s:",
+         gametype_width  = 100,
+         gametype_fontsize = 10,
+         gametype_align  = -1,
+         gametype_upper  = False,
+         elo_pos         = (75,30),
+         elo_text        = "Elo %.0f",
+         elo_color       = (0.7, 0.7, 0.7),
+         elo_align       = 1,
+         rank_pos        = None,
+         nostats_pos     = None,
+         #nostats_pos     = (75,30),
+         #nostats_fontsize = 10,
+         #nostats_angle   = 0,
+         #nostats_text    = "no stats yet!",
+         #nostats_color   = (0.7, 0.4, 0.4),
+         kdr_pos         = (392,15),
+         kdr_fontsize    = 10,
+         kdr_colortop    = (0.6, 0.8, 0.6),
+         kdr_colormid    = (0.6, 0.6, 0.6),
+         kdr_colorbot    = (0.8, 0.6, 0.6),
+         kills_pos       = None,
+         deaths_pos      = None,
+         winp_pos        = (508,15),
+         winp_fontsize   = 10,
+         winp_colortop   = (0.6, 0.8, 0.8),
+         winp_colormid   = (0.6, 0.6, 0.6),
+         winp_colorbot   = (0.8, 0.8, 0.6),
+         wins_pos        = None,
+         loss_pos        = None,
+         ptime_pos       = (451,30),
+         ptime_color     = (0.7, 0.7, 0.7),
+     )
+ # parse cmdline parameters (for testing)
+ skins = []
+ for arg in sys.argv[1:]:
+     if arg.startswith("-"):
+         arg = arg[1:]
+         if arg == "force":
+             DELTA = 2**24   # large enough to enforce update, and doesn't result in errors
+         elif arg == "test":
+             NUM_PLAYERS = 100
          else:
-             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
-             ctx.set_font_size(10)
-             ctx.set_source_rgb(1.0, 1.0, 0.5)
-             txt = "Elo: %.0f" % round(elos[gt], 0)
-             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
-             ctx.move_to(games_x-xoff-tw/2,games_y+15-yoff-4)
-             ctx.show_text(txt)
-             
-             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
-             ctx.set_font_size(8)
-             ctx.set_source_rgb(0.8, 0.8, 0.8)
-             txt = "Rank %d of %d" % ranks[gt]
-             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
-             ctx.move_to(games_x-xoff-tw/2,games_y+25-yoff-3)
-             ctx.show_text(txt)
-         
-         games_x += games_w
-     # print win percentage
-     win_x, win_y = 505,11
-     win_w, win_h = 100,14
-     
-     ctx.rectangle(win_x-win_w/2,win_y-win_h/2,win_w,win_h)
-     ctx.set_source_rgba(0.8, 0.8, 0.8, 0.1)
-     ctx.fill();
-     
-     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
-     ctx.set_font_size(10)
-     ctx.set_source_rgb(0.8, 0.8, 0.8)
-     txt = "Win Percentage"
-     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
-     ctx.move_to(win_x-xoff-tw/2,win_y-yoff-3)
-     ctx.show_text(txt)
-     
-     txt = "???"
-     if total_games > 0 and total_stats['wins'] is not None:
-         ratio = float(total_stats['wins'])/total_games
-         txt = "%.2f%%" % round(ratio * 100, 2)
-     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
-     ctx.set_font_size(12)
-     if ratio >= 0.90:
-         ctx.set_source_rgb(0.2, 1.0, 1.0)
-     elif ratio >= 0.75:
-         ctx.set_source_rgb(0.5, 1.0, 1.0)
-     elif ratio >= 0.5:
-         ctx.set_source_rgb(0.5, 1.0, 0.8)
-     elif ratio >= 0.25:
-         ctx.set_source_rgb(0.8, 1.0, 0.5)
-     else:
-         ctx.set_source_rgb(1.0, 1.0, 0.5)
-     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
-     ctx.move_to(win_x-xoff-tw/2,win_y+16-yoff-4)
-     ctx.show_text(txt)
-     
-     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
-     ctx.set_font_size(8)
-     ctx.set_source_rgb(0.6, 0.8, 0.6)
-     txt = "%d wins" % total_stats["wins"]
-     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
-     ctx.move_to(win_x-xoff-tw/2,win_y+28-yoff-3)
-     ctx.show_text(txt)
-     ctx.set_source_rgb(0.8, 0.6, 0.6)
-     txt = "%d losses" % (total_games-total_stats['wins'])
-     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
-     ctx.move_to(win_x-xoff-tw/2,win_y+38-yoff-3)
-     ctx.show_text(txt)
-     # print kill/death ratio
-     kill_x, kill_y = 395,11
-     kill_w, kill_h = 100,14
-     
-     ctx.rectangle(kill_x-kill_w/2,kill_y-kill_h/2,kill_w,kill_h)
-     ctx.set_source_rgba(0.8, 0.8, 0.8, 0.1)
-     ctx.fill()
-     
-     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
-     ctx.set_font_size(10)
-     ctx.set_source_rgb(0.8, 0.8, 0.8)
-     txt = "Kill Ratio"
-     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
-     ctx.move_to(kill_x-xoff-tw/2,kill_y-yoff-3)
-     ctx.show_text(txt)
-     
-     txt = "???"
-     if total_stats['deaths'] > 0 and total_stats['kills'] is not None:
-         ratio = float(total_stats['kills'])/total_stats['deaths']
-         txt = "%.3f" % round(ratio, 3)
-     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
-     ctx.set_font_size(12)
-     if ratio >= 3:
-         ctx.set_source_rgb(0.0, 1.0, 0.0)
-     elif ratio >= 2:
-         ctx.set_source_rgb(0.2, 1.0, 0.2)
-     elif ratio >= 1:
-         ctx.set_source_rgb(0.5, 1.0, 0.5)
-     elif ratio >= 0.5:
-         ctx.set_source_rgb(1.0, 0.5, 0.5)
+             print """Usage:  gen_badges.py [options] [skin list]
+     Options:
+         -force      Force updating all badges (delta = 2^24)
+         -test       Limit number of players to 100 (for testing)
+         -help       Show this help text
+     Skin list:
+         Space-separated list of skins to use when creating badges.
+         Available skins:  classic, minimal, archer
+         If no skins are given, classic and minmal will be used by default.
+         NOTE: Output directories must exists before running the program!
+ """
+             sys.exit(-1)
      else:
-         ctx.set_source_rgb(1.0, 0.2, 0.2)
-     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
-     ctx.move_to(kill_x-xoff-tw/2,kill_y+16-yoff-4)
-     ctx.show_text(txt)
-     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
-     ctx.set_font_size(8)
-     ctx.set_source_rgb(0.6, 0.8, 0.6)
-     txt = "%d kills" % total_stats["kills"]
-     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
-     ctx.move_to(kill_x-xoff-tw/2,kill_y+28-yoff-3)
-     ctx.show_text(txt)
-     ctx.set_source_rgb(0.8, 0.6, 0.6)
-     txt = "%d deaths" % total_stats['deaths']
-     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
-     ctx.move_to(kill_x-xoff-tw/2,kill_y+38-yoff-3)
-     ctx.show_text(txt)
-     # print playing time
-     time_x, time_y = 450,64
-     time_w, time_h = 210,10
-     
-     ctx.rectangle(time_x-time_w/2,time_y-time_h/2-1,time_w,time_y+time_h/2-1)
-     ctx.set_source_rgba(0.8, 0.8, 0.8, 0.6)
-     ctx.fill();
-     
-     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
-     ctx.set_font_size(10)
-     ctx.set_source_rgb(0.1, 0.1, 0.1)
-     txt = "Playing time: %s" % str(total_stats['alivetime'])
-     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
-     ctx.move_to(time_x-xoff-tw/2,time_y-yoff-4)
-     ctx.show_text(txt)
-     # save to PNG
-     surf.write_to_png(output)
+         if arg == "classic":
+             skins.append(skin_classic)
+         elif arg == "minimal":
+             skins.append(skin_minimal)
+         elif arg == "archer":
+             skins.append(skin_archer)
  
+ if len(skins) == 0:
+     skins = [ skin_classic, skin_minimal ]
  
 -
  # environment setup
  env = bootstrap('../../../development.ini')
  req = env['request']
  req.matchdict = {'id':3}
  
  print "Requesting player data from db ..."
+ cutoff_dt = datetime.utcnow() - timedelta(hours=DELTA)
  start = datetime.now()
- players = DBSession.query(Player).\
-         filter(Player.player_id == PlayerElo.player_id).\
-         filter(Player.nick != None).\
-         filter(Player.player_id > 2).\
-         filter(Player.active_ind == True).\
-         limit(NUM_PLAYERS).all()
- stop = datetime.now()
- print "Query took %.2f seconds" % (stop-start).total_seconds()
- print "Creating badges for %d players ..." % len(players)
- start = datetime.now()
- data_time, render_time = 0,0
- for player in players:
-     req.matchdict['id'] = player.player_id
-     
-     sstart = datetime.now()
-     #data = player_info_data(req)
-     data = get_data(player)
-     sstop = datetime.now()
-     data_time += (sstop-sstart).total_seconds()
-     
-     print "\t#%d (%s)" % (player.player_id, player.stripped_nick)
-     sstart = datetime.now()
-     render_image(data)
-     sstop = datetime.now()
-     render_time += (sstop-sstart).total_seconds()
+ players = []
+ if NUM_PLAYERS:
+     players = DBSession.query(distinct(Player.player_id)).\
+             filter(Player.player_id == PlayerElo.player_id).\
+             filter(Player.player_id == PlayerGameStat.player_id).\
+             filter(PlayerGameStat.create_dt > cutoff_dt).\
+             filter(Player.nick != None).\
+             filter(Player.player_id > 2).\
+             filter(Player.active_ind == True).\
+             limit(NUM_PLAYERS).all()
+ else:
+     players = DBSession.query(distinct(Player.player_id)).\
+             filter(Player.player_id == PlayerElo.player_id).\
+             filter(Player.player_id == PlayerGameStat.player_id).\
+             filter(PlayerGameStat.create_dt > cutoff_dt).\
+             filter(Player.nick != None).\
+             filter(Player.player_id > 2).\
+             filter(Player.active_ind == True).\
+             all()
  
- stop = datetime.now()
- print "Creating the badges took %.2f seconds (%.2f s per player)" % ((stop-start).total_seconds(), (stop-start).total_seconds()/float(len(players)))
- print "Total time for getting data: %.2f s" % data_time
- print "Total time for redering images: %.2f s" % render_time
+ playerdata = PlayerData()
+ if len(players) > 0:
+     stop = datetime.now()
+     td = stop-start
+     total_seconds = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
+     print "Query took %.2f seconds" % (total_seconds)
+     print "Creating badges for %d players ..." % len(players)
+     start = datetime.now()
+     data_time, render_time = 0,0
+     for player_id in players:
+         req.matchdict['id'] = player_id
+         sstart = datetime.now()
+         playerdata.get_data(player_id)
+         sstop = datetime.now()
+         td = sstop-sstart
+         total_seconds = float(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
+         data_time += total_seconds
+         sstart = datetime.now()
+         for sk in skins:
+             sk.render_image(playerdata, "output/%s/%d.png" % (str(sk), player_id[0]))
+         sstop = datetime.now()
+         td = sstop-sstart
+         total_seconds = float(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
+         render_time += total_seconds
+     stop = datetime.now()
+     td = stop-start
+     total_seconds = float(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
+     print "Creating the badges took %.1f seconds (%.3f s per player)" % (total_seconds, total_seconds/float(len(players)))
+     print "Total time for rendering images: %.3f s" % render_time
+     print "Total time for getting data: %.3f s" % data_time
+ else:
+     print "No active players found!"
  
index 53526091cafe7ac0c7ef3494e5a8e3189d66a217,3d6af2dc01da957f4c0e2e10f4465ea2ca49bd4a..3947174e39183162305ea6e070d6377563167c99
@@@ -23,8 -23,6 +23,8 @@@
      <link href="/static/css/style.css" rel="stylesheet">
      <link type="images/vnd.microsoft.icon" rel="shortcut icon" href="/static/favicon.ico">
      </%block>
 +    
 +    <script src="/static/js/jquery-1.7.1.min.js"></script>
    </head>
  
    <body>
@@@ -39,7 -37,7 +39,7 @@@
  
        <div class="row">
          <div class="span12" id="xonborder">
-           <div id="title"><%block name="title"></%block></div>
+           <div id="title"><%block name="title"></%block>&nbsp;</div>
              ${self.body()}
          </div> <!-- /xonborder -->
        </div> <!-- /main row -->
        </%block>
  
        <%block name="js">
+       <script src="/static/js/jquery-1.7.1.min.js"></script>
        </%block>
  
+       <!-- RELATIVE TIME CONVERSION -->
+       <script type="text/javascript">
+       $('.abstime').each(function(i,e){
+         var epoch = e.getAttribute('data-epoch');
+         var d = new Date(0);
+         d.setUTCSeconds(epoch);
+         e.setAttribute('title', d.toDateString() + ' ' + d.toTimeString());  
+       });
+       </script>
+       <!-- GOOGLE ANALYTICS -->
        <script type="text/javascript">
        var _gaq = _gaq || [];
        _gaq.push(['_setAccount', 'UA-30391685-1']);
index e7b04058691832d2ddf84c352f3b0d8eb635ae33,3149228e486c7b5c168efd5d4f43486818ba715f..c88c96c27c924cf3511fbc72ec9b5a7fc6abd033
@@@ -8,14 -8,11 +8,14 @@@ ${nav.nav('players')
  
  <%block name="js">
      % if player is not None:
 -      <script src="/static/js/jquery-1.7.1.min.js"></script>
        <script src="/static/js/jquery.flot.min.js"></script>
 +      <script src="/static/js/bootstrap-tabs.js"></script>
        <script type="text/javascript">
 -      $(function () {
 +      jQuery(document).ready(function ($) {
 +          $(".tabs").tabs();
 +      });      
  
 +      $(function () {
            // plot the accuracy graph
            function plot_acc_graph(data) {
                var games = new Array();
            }
  
            var previousPoint = null;
 +          var previousLabel = null;
            $('#acc-graph').bind("plothover", function (event, pos, item) {
                if (item) {
 -                  if (previousPoint != item.dataIndex) {
 +                  if ((previousLabel != item.series.label) || (previousPoint != item.dataIndex)) {
                      previousPoint = item.dataIndex;
 +                    previousLabel = item.series.label;
  
                      $("#tooltip").remove();
                      var x = item.datapoint[0].toFixed(2),
                else {
                    $("#tooltip").remove();
                    previousPoint = null;
 +                  previousLabel = null;
                }
            });
  
            $('#dmg-graph').bind("plothover", function (event, pos, item) {
                if (item) {
 -                  if (previousPoint != item.dataIndex) {
 +                  if ((previousLabel != item.series.label) || (previousPoint != item.dataIndex)) {
                      previousPoint = item.dataIndex;
 +                    previousLabel = item.series.label;
  
                      $("#tooltip").remove();
                      var x = item.datapoint[0].toFixed(2),
                else {
                    $("#tooltip").remove();
                    previousPoint = null;
 +                  previousLabel = null;
                }
            });
  
            });
        })
        </script>
 +      <script src="/static/js/bootstrap-tabs.min.js"></script>
      % endif
  </%block>
  
@@@ -191,57 -182,35 +191,57 @@@ Player Informatio
      <p>
        Member Since: <small>${player.create_dt.strftime('%m/%d/%Y at %I:%M %p')} </small><br />
  
-       Last Seen: <small>${recent_games[0][1].fuzzy_date()} </small><br />
+       Last Seen: <small><span class="abstime" data-epoch="${recent_games[0][1].epoch()}" title="${recent_games[0][1].create_dt.strftime('%a, %d %b %Y %H:%M:%S UTC')}">${recent_games[0][1].fuzzy_date()}</span> </small><br />
  
 -      Playing Time: <small>${total_stats['alivetime']} </small><br />
 -
 -      <% games_breakdown_str = ', '.join(["{0} {1}".format(ng, gt) for (gt, ng) in games_breakdown]) %>
 -      Games Played: <small>${total_games} (${games_breakdown_str})</small><br />
 -
 -      % if fav_map is not None:
 -      Favorite Map: <small><a href="${request.route_url('map_info', id=fav_map['id'])}" title="view map info">${fav_map['name']}</a></small><br />
 +      Playing Time: <small>${total_stats['alivetime']}
 +      % if total_stats['alivetime_month'] and total_stats['alivetime'] > total_stats['alivetime_month']:
 +          % if total_stats['alivetime_week'] and total_stats['alivetime_month'] > total_stats['alivetime_week']:
 +              <br />(${total_stats['alivetime_month']} this month; ${total_stats['alivetime_week']} this week)
 +          % else:
 +              <br />(${total_stats['alivetime_month']} this month)
 +          % endif
        % endif
 +      </small><br />
 +
 +      <% games_breakdown_str = ', '.join(["{0} {1}".format(ng, gt) for (gt, ng) in total_stats['games_breakdown'].items()]) %>
 +      Games Played: <small>${total_stats['games']}<br />(${games_breakdown_str})</small><br />
      </p>
    </div>
    <div class="span6">
      <p>
 -       % if total_games > 0 and total_stats['wins'] is not None:
 -       Win Percentage: <small>${round(float(total_stats['wins'])/total_games * 100, 2)}% (${total_stats['wins']} wins, ${total_games - total_stats['wins']} losses) </small><br />
 -       % endif
 +      % if fav_server is not None:
 +      Favorite Server: <small><a href="${request.route_url('server_info', id=fav_server[0]['id'])}" title="view server info">${fav_server[0]['name']}</a></small><br />
 +      % endif
 +
 +      % if fav_map is not None:
 +      Favorite Map: <small><a href="${request.route_url('map_info', id=fav_map[0]['id'])}" title="view map info">${fav_map[0]['name']}</a></small><br />
 +      % endif
 +
 +      % if fav_weapon is not None:
 +      Favorite Weapon: <small>${fav_weapon[0]['name']}</small><br />
 +      % endif
 +
 +      % if total_stats['games'] > 0 and total_stats['wins'] is not None:
 +      Win Percentage: <small>${round(float(total_stats['wins'])/total_stats['games'] * 100, 2)}% (${total_stats['wins']} wins, ${total_stats['games'] - total_stats['wins']} losses) </small><br />
 +      % endif
  
 -       % if total_stats['kills'] > 0 and total_stats['deaths'] > 0:
 -       Kill Ratio: <small>${round(float(total_stats['kills'])/total_stats['deaths'], 3)} (${total_stats['kills']} kills, ${total_stats['deaths']} deaths) </small><br />
 -       % endif
 +      % if total_stats['kills'] > 0 and total_stats['deaths'] > 0:
 +      Kill Ratio: <small>${round(float(total_stats['kills'])/total_stats['deaths'], 3)} (${total_stats['kills']} kills, ${total_stats['deaths']} deaths, ${total_stats['suicides']} suicides) </small><br />
 +      % endif
 +    </p>
 +  </div>
 +</div>
  
 +<div class="row">
 +  <div class="span12">
 +    <p>
         % if elos_display is not None and len(elos_display) > 0:
         Elo:
 -          <small>${', '.join(elos_display)} </small>
 -          <br />
 -          %if '*' in ', '.join(elos_display):
 -              <small><i>*preliminary Elo</i></small><br />
 +          <small>${elos_display} </small>
 +          %if '*' in elos_display:
 +              <small><i>*preliminary Elo</i></small>
            %endif
 +          <br />
        % endif
  
        % if ranks_display != '':
    </div>
  </div>
  
 -
  % if 'nex' in recent_weapons or 'rifle' in recent_weapons or 'minstanex' in recent_weapons or 'uzi' in recent_weapons or 'shotgun' in recent_weapons:
  <div class="row">
    <div class="span10">
            <div class="acc-weap weapon-active">
              <img src="${request.static_url("xonstat:static/images/nex.png")}" />
              <p><small>Nex</small></p>
 -            <a href="${request.route_url('player_accuracy', id=player.player_id, _query={'weapon':'nex'})}" title="Show nex accuracy"></a>
 +            <a href="${request.route_url('player_accuracy', id=player.player_id, _query=[('weapon','nex')])}" title="Show nex accuracy"></a>
            </div>
          </li>
          % endif
            <div class="acc-weap">
              <img src="${request.static_url("xonstat:static/images/rifle.png")}" />
              <p><small>Rifle</small></p>
 -            <a href="${request.route_url('player_accuracy', id=player.player_id, _query={'weapon':'rifle'})}" title="Show rifle accuracy"></a>
 +            <a href="${request.route_url('player_accuracy', id=player.player_id, _query=[('weapon','rifle')])}" title="Show rifle accuracy"></a>
            </div>
          </li>
          % endif
            <div class="acc-weap">
              <img src="${request.static_url("xonstat:static/images/minstanex.png")}" />
              <p><small>Minstanex</small></p>
 -            <a href="${request.route_url('player_accuracy', id=player.player_id, _query={'weapon':'minstanex'})}" title="Show minstanex accuracy"></a>
 +            <a href="${request.route_url('player_accuracy', id=player.player_id, _query=[('weapon','minstanex')])}" title="Show minstanex accuracy"></a>
            </div>
          </li>
          % endif
            <div class="acc-weap">
              <img src="${request.static_url("xonstat:static/images/uzi.png")}" />
              <p><small>Uzi</small></p>
 -            <a href="${request.route_url('player_accuracy', id=player.player_id, _query={'weapon':'uzi'})}" title="Show uzi accuracy"></a>
 +            <a href="${request.route_url('player_accuracy', id=player.player_id, _query=[('weapon','uzi')])}" title="Show uzi accuracy"></a>
            </div>
          </li>
          % endif
            <div class="acc-weap">
              <img src="${request.static_url("xonstat:static/images/shotgun.png")}" />
              <p><small>Shotgun</small></p>
 -            <a href="${request.route_url('player_accuracy', id=player.player_id, _query={'weapon':'shotgun'})}" title="Show shotgun accuracy"></a>
 +            <a href="${request.route_url('player_accuracy', id=player.player_id, _query=[('weapon','shotgun')])}" title="Show shotgun accuracy"></a>
            </div>
          </li>
          % endif
            <div class="dmg-weap weapon-active">
              <img src="${request.static_url("xonstat:static/images/rocketlauncher.png")}" />
              <p><small>Rocket</small></p>
 -            <a href="${request.route_url('player_damage', id=player.player_id, _query={'weapon':'rocketlauncher'})}" title="Show rocket launcher efficiency"></a>
 +            <a href="${request.route_url('player_damage', id=player.player_id, _query=[('weapon','rocketlauncher')])}" title="Show rocket launcher efficiency"></a>
            </div>
          </li>
          % endif
            <div class="dmg-weap">
              <img src="${request.static_url("xonstat:static/images/grenadelauncher.png")}" />
              <p><small>Mortar</small></p>
 -            <a href="${request.route_url('player_damage', id=player.player_id, _query={'weapon':'grenadelauncher'})}" title="Show mortar damage efficiency"></a>
 +            <a href="${request.route_url('player_damage', id=player.player_id, _query=[('weapon','grenadelauncher')])}" title="Show mortar damage efficiency"></a>
            </div>
          </li>
          % endif
            <div class="dmg-weap">
              <img src="${request.static_url("xonstat:static/images/electro.png")}" />
              <p><small>Electro</small></p>
 -            <a href="${request.route_url('player_damage', id=player.player_id, _query={'weapon':'electro'})}" title="Show electro damage efficiency"></a>
 +            <a href="${request.route_url('player_damage', id=player.player_id, _query=[('weapon','electro')])}" title="Show electro damage efficiency"></a>
            </div>
          </li>
          % endif
            <div class="dmg-weap">
              <img src="${request.static_url("xonstat:static/images/crylink.png")}" />
              <p><small>Crylink</small></p>
 -            <a href="${request.route_url('player_damage', id=player.player_id, _query={'weapon':'crylink'})}" title="Show crylink damage efficiency"></a>
 +            <a href="${request.route_url('player_damage', id=player.player_id, _query=[('weapon','crylink')])}" title="Show crylink damage efficiency"></a>
            </div>
          </li>
          % endif
            <div class="dmg-weap">
              <img src="${request.static_url("xonstat:static/images/hagar.png")}" />
              <p><small>Hagar</small></p>
 -            <a href="${request.route_url('player_damage', id=player.player_id, _query={'weapon':'hagar'})}" title="Show hagar damage efficiency"></a>
 +            <a href="${request.route_url('player_damage', id=player.player_id, _query=[('weapon','hagar')])}" title="Show hagar damage efficiency"></a>
            </div>
          </li>
          % endif
            <div class="dmg-weap">
              <img src="${request.static_url("xonstat:static/images/laser.png")}" />
              <p><small>Laser</small></p>
 -            <a href="${request.route_url('player_damage', id=player.player_id, _query={'weapon':'laser'})}" title="Show laser damage efficiency"></a>
 +            <a href="${request.route_url('player_damage', id=player.player_id, _query=[('weapon','laser')])}" title="Show laser damage efficiency"></a>
            </div>
          </li>
          % endif
  </div>
  % endif
  
 +<div class="row">
 +  <div class="span8 tabbable">
 +    <h3>Game Breakdown</h3>
 +    <ul class="tabs nav nav-pills" data-tabs="tabs">
 +    <% gametypes = ['Overall', 'Duel', 'DM', 'TDM', 'CTF'] %>
 +    % for gtc in gametypes:
 +      % if gtc.lower() == 'overall' or total_stats['games_breakdown'].has_key(gtc.lower()):
 +        % if gtc.lower() == 'overall':
 +      <li class="active">
 +        % else:
 +      <li>
 +        % endif
 +        <a href="#breakdown-${gtc.lower()}" data-toggle="tabs">${gtc}</a>
 +      </li>
 +      % endif
 +    % endfor
 +    </ul>
 +    <div class="tab-content">
 +    % for gtc in gametypes:
 +      <% gtc_key = gtc.lower() %>
 +      % if gtc_key == "overall":
 +        <% total     = total_stats['games'] %>
 +        <% alivetime = total_stats['alivetime'] %>
 +        <% wins      = total_stats['wins'] %>
 +        <% losses    = total - wins %>
 +        <% kills     = total_stats['kills'] %>
 +        <% deaths    = total_stats['deaths'] %>
 +        <% suicides  = total_stats['suicides'] %>
 +      % elif total_stats['games_breakdown'].has_key(gtc_key):
 +        <% total     = total_stats['games_breakdown'][gtc_key] %>
 +        <% alivetime = total_stats['games_alivetime'][gtc_key] %>
 +        <% wins      = total_stats[gtc_key+'_wins'] %>
 +        <% losses    = total - wins %>
 +        % if gtc_key == "ctf":
 +          <% caps      = total_stats[gtc_key+'_caps'] %>
 +          <% pickups   = total_stats[gtc_key+'_pickups'] %>
 +          <% returns   = total_stats[gtc_key+'_returns'] %>
 +          <% drops     = total_stats[gtc_key+'_drops'] %>
 +          <% fckills   = total_stats[gtc_key+'_fckills'] %>
 +        % else:
 +          <% kills     = total_stats[gtc_key+'_kills'] %>
 +          <% deaths    = total_stats[gtc_key+'_deaths'] %>
 +          <% suicides  = total_stats[gtc_key+'_suicides'] %>
 +        % endif
 +      % endif
 +      % if gtc_key == 'overall' or total_stats['games_breakdown'].has_key(gtc_key):
 +        % if gtc_key == 'overall':
 +      <div class="tab-pane active" id="breakdown-${gtc_key}">
 +        % else:
 +      <div class="tab-pane" id="breakdown-${gtc_key}">
 +        % endif
 +        <div style="margin:15px;float:left;"><img title="${gtc}" src="/static/images/icons/48x48/${gtc_key}.png" alt="${gtc}" /></div>
 +        <table class="table table-bordered table-condensed">
 +          <thead>
 +          </thead>
 +          <tbody>
 +            <tr>
 +              <td><b>Games Played:</b></td>
 +              <td>${total}</td>
 +              % if gtc_key == 'overall':
 +              <td></td>
 +              % else:
 +              <td>${round(float(total)/total_stats['games'] * 100, 2)}% of all games</td>
 +              % endif
 +            </tr>
 +            <tr>
 +              <td><b>Playing Time:</b></td>
 +              <td>${alivetime} hours</td>
 +              % if gtc_key == 'overall':
 +              <td></td>
 +              % else:
 +              <td>${round(float(alivetime.total_seconds())/total_stats['alivetime'].total_seconds() * 100, 2)}% of total playing time</td>
 +              % endif
 +            </tr>
 +            <tr>
 +              <td width="30%"><b>Win Percentage:</b></td>
 +              <td width="30%">${round(float(wins)/total * 100, 2)}%</td>
 +              <td width="40%">${wins} wins, ${losses} losses</td>
 +            </tr>
 +            % if gtc_key == 'ctf':
 +            <tr>
 +              <td><b>Caps:</b></td>
 +              <td>${round(float(caps)/total, 2)} per game</td>
 +              <td>${caps} total</td>
 +            </tr>
 +            <tr>
 +              <td><b>Pickups:</b></td>
 +              <td>${round(float(pickups)/total, 2)} per game</td>
 +              <td>${pickups} total</td>
 +            </tr>
 +            <tr>
 +              <td><b>Drops:</b></td>
 +              <td>${round(float(drops)/total, 2)} per game</td>
 +              <td>${drops} total</td>
 +            </tr>
 +            <tr>
 +              <td><b>Returns:</b></td>
 +              <td>${round(float(returns)/total, 2)} per game</td>
 +              <td>${returns} total</td>
 +            </tr>
 +            <tr>
 +              <td><b>FC Kills:</b></td>
 +              <td>${round(float(fckills)/total, 2)} per game</td>
 +              <td>${fckills} total</td>
 +            </tr>
 +            <tr>
 +              <td><b>Cap Ratio:</b></td>
 +              <td>${round(float(caps)/pickups, 3)}</td>
 +              <td></td>
 +            </tr>
 +            <tr>
 +              <td><b>Drop Ratio:</b></td>
 +              <td>${round(float(drops)/pickups, 3)}</td>
 +              <td></td>
 +            </tr>
 +            <tr>
 +              <td><b>Return Ratio:</b></td>
 +              <td>${round(float(returns)/fckills, 3)}</td>
 +              <td></td>
 +            </tr>
 +            % else:
 +            <tr>
 +              <td><b>Kills:</b></td>
 +              <td>${round(float(kills)/total, 2)} per game</td>
 +              <td>${kills} total</td>
 +            </tr>
 +            <tr>
 +              <td><b>Deaths:</b></td>
 +              <td>${round(float(deaths)/total, 2)} per game</td>
 +              <td>${deaths} total</td>
 +            </tr>
 +            <tr>
 +              <td><b>Suicides:</b></td>
 +              <td>${round(float(suicides)/total, 2)} per game</td>
 +              <td>${suicides} total</td>
 +            </tr>
 +            <tr>
 +              <td><b>Kill Ratio:</b></td>
 +              <td>${round(float(kills)/deaths, 3)}</td>
 +              <td></td>
 +            </tr>
 +            <tr>
 +              <td><b>Suicide Ratio:</b></td>
 +              <td>${round(float(suicides)/deaths, 3)}</td>
 +              <td></td>
 +            </tr>
 +            % endif
 +          </tbody>
 +        </table>
 +      </div>
 +      % endif
 +    % endfor
 +    </div>
 +  </div>
 +</div>
 +
  
  ##### RECENT GAMES (v2) ####
  % if recent_games:
 +<br />
  <div class="row">
    <div class="span12">
      <h3>Recent Games</h3>
              % endif
            % endif
             </td>
-            <td>${game.fuzzy_date()}</td>
+            <td><span class="abstime" data-epoch="${game.epoch()}" title="${game.create_dt.strftime('%a, %d %b %Y %H:%M:%S UTC')}">${game.fuzzy_date()}</span></td>
          </tr>
        % endfor
        </tbody>