]> git.rm.cloudns.org Git - xonotic/xonstat.git/commitdiff
Added rudimentary skin support to badges (also moved large parts of code outside...
authorJan D. Behrens <zykure@web.de>
Tue, 28 Aug 2012 12:41:22 +0000 (14:41 +0200)
committerJan D. Behrens <zykure@web.de>
Tue, 28 Aug 2012 12:41:22 +0000 (14:41 +0200)
- To select skin, run gen_badges.py with the skin name as argument (i.e. "classic" or "archer").

xonstat/batch/badges/gen_badges.py
xonstat/batch/badges/render.py [new file with mode: 0644]

index e2b75de46186d7a22a8d52185d257a3dfa2aa6ca..712f7adf28d58b02931645ed50d4e35c12644266 100644 (file)
 #-*- coding: utf-8 -*-
 
 import sys
-import re
-import cairo as C
 from datetime import datetime
 import sqlalchemy as sa
 import sqlalchemy.sql.functions as func
 from colorsys import rgb_to_hls, hls_to_rgb
-from os import system
 from pyramid.paster import bootstrap
 from xonstat.models import *
-from xonstat.util import qfont_decode, _all_colors
 
-
-# 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)
-            ]
+from render import Skin
 
 
 # maximal number of query results (for testing, set to 0 to get all)
 NUM_PLAYERS = 100
 
-# image dimensions (likely breaks layout if changed)
-WIDTH   = 560
-HEIGHT  = 70
-
-# output filename, parameter is player id
-OUTPUT = "output/%d.png"
-
-
-NICK_POS        = (5,18)
-NICK_MAXWIDTH   = 330
-
-GAMES_POS       = (60,35)
-GAMES_WIDTH     = 110
-
-WINLOSS_POS     = (508,6)
-WINLOSS_WIDTH   = 104
-
-KILLDEATH_POS   = (390,6)
-KILLDEATH_WIDTH = 104
 
-PLAYTIME_POS    = (452,64)
-PLAYTIME_WIDTH  = 218
+skin_classic = Skin()
 
-
-# parameters to affect the output, could be changed via URL
-params = {
-    'bg':           1,                      # -1 - none, 0 - black, 1 - dark_wall, ...
-    'overlay':      0,                      # 0 - none, 1 - default overlay, ...
-    'font':         0,                      # 0 - xolonium, 1 - dejavu sans
-}
+skin_archer = Skin(
+        bg="background_archer-v1",
+        overlay="",
+    )
 
 
 # parse cmdline parameters (for testing)
-for arg in sys.argv[1:]:
-    try:
-        k,v = arg.split("=")
-        if params.has_key(k.lower()):
-            params[k] = int(v)
-    except:
-        continue
-
-
-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['alivetime'],) = DBSession.query(
-            func.sum(PlayerGameStat.kills),
-            func.sum(PlayerGameStat.deaths),
-            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()
-
-    (total_stats['wins'],) = DBSession.\
-            query("total_wins").\
-            from_statement(
-                "select count(*) total_wins "
-                "from games g, player_game_stats pgs "
-                "where g.game_id = pgs.game_id "
-                "and player_id=:player_id "
-                "and (g.winner = pgs.team or pgs.rank = 1)"
-            ).params(player_id=player_id).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."""
-    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_ARGB32, 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_rgb(0.04, 0.04, 0.04)  # bgcolor of Xonotic forum
-        ctx.fill()
-    elif params['bg'] < 0:
-        ctx.save()
-        ctx.set_operator(C.OPERATOR_SOURCE)
-        ctx.set_source_rgba(1, 1, 1, 0)
-        ctx.paint()
-        ctx.restore()
-
-    # 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")
-        elif params['bg'] == 2:
-            bg = C.ImageSurface.create_from_png("img/asfalt.png")
-        elif params['bg'] == 3:
-            bg = C.ImageSurface.create_from_png("img/broken_noise.png")
-        elif params['bg'] == 4:
-            bg = C.ImageSurface.create_from_png("img/burried.png")
-        elif params['bg'] == 5:
-            bg = C.ImageSurface.create_from_png("img/dark_leather.png")
-        elif params['bg'] == 6:
-            bg = C.ImageSurface.create_from_png("img/txture.png")
-        elif params['bg'] == 7:
-            bg = C.ImageSurface.create_from_png("img/black_linen_v2.png")
-        elif params['bg'] == 8:
-            bg = C.ImageSurface.create_from_png("img/background_archer-v1.png")
-        
-        # tile image
-        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 overlay graphic
-    if params['overlay'] > 0:
-        overlay = None
-        if params['overlay'] == 1:
-            overlay = C.ImageSurface.create_from_png("img/overlay.png")
-        if overlay:
-            ctx.set_source_surface(overlay, 0, 0)
-            ctx.mask_surface(overlay)
-            ctx.paint()
-
-
-    ## draw player's nickname with fancy colors
-    
-    # deocde nick, strip all weird-looking characters
-    qstr = qfont_decode(player.nick).replace('^^', '^').replace(u'\x00', '')
-    chars = []
-    for c in qstr:
-        if ord(c) < 128:
-            chars.append(c)
-    qstr = ''.join(chars)
-    stripped_nick = strip_colors(qstr)
-    
-    # fontsize is reduced if width gets too large
-    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(stripped_nick)[:4]
-    if tw > NICK_MAXWIDTH:
-        ctx.set_font_size(18)
-        xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
-        if tw > NICK_MAXWIDTH:
-            ctx.set_font_size(16)
-            xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
-            if tw > NICK_MAXWIDTH:
-                ctx.set_font_size(14)
-                xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
-                if tw > NICK_MAXWIDTH:
-                    ctx.set_font_size(12)
-    xoff, yoff, tw, th = ctx.text_extents("_")[:4]
-    space_w = tw
-    
-    # split up nick into colored segments and draw each of them
-    
-    # split nick into colored segments
-    xoffset = 0
-    _all_colors = re.compile(r'(\^\d|\^x[\dA-Fa-f]{3})')
-    #print qstr, _all_colors.findall(qstr), _all_colors.split(qstr)
-    
-    parts = _all_colors.split(qstr)
-    while len(parts) > 0:
-        tag = None
-        txt = parts[0]
-        if _all_colors.match(txt):
-            tag = txt[1:]  # strip leading '^'
-            if len(parts) < 2:
-                break
-            txt = parts[1]
-            del parts[1]
-        del parts[0]
-            
-        if not txt or len(txt) == 0:
-            # only colorcode and no real text, skip this
-            continue
-            
-        r,g,b = _dec_colors[7]
-        try:
-            if tag.startswith('x'):
-                r = int(tag[1] * 2, 16) / 255.0
-                g = int(tag[2] * 2, 16) / 255.0
-                b = int(tag[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)
-            else:
-                r,g,b = _dec_colors[int(tag[0])]
-        except:
-            r,g,b = _dec_colors[7]
-        
-        ctx.set_source_rgb(r, g, b)
-        ctx.move_to(NICK_POS[0] + xoffset, NICK_POS[1])
-        ctx.show_text(txt)
-
-        xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
-        tw += (len(txt)-len(txt.strip())) * space_w  # account for lost whitespaces
-        xoffset += tw + 2
-
-
-    ## print elos and ranks
-    
-    # show up to three gametypes the player has participated in
-    xoffset = 0
-    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_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]-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_POS[0]+xoffset-GAMES_WIDTH/2+5, GAMES_POS[1]+8)
-        ctx.line_to(GAMES_POS[0]+xoffset+GAMES_WIDTH/2-5, GAMES_POS[1]+8)
-        ctx.stroke()
-        ctx.move_to(GAMES_POS[0]+xoffset-GAMES_WIDTH/2+5, GAMES_POS[1]+32)
-        ctx.line_to(GAMES_POS[0]+xoffset+GAMES_WIDTH/2-5, GAMES_POS[1]+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_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]+28-yoff-4)
-            ctx.save()
-            ctx.rotate(math.radians(-10))
-            ctx.show_text(txt)
-            ctx.restore()
-        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_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]+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, 1.0)
-            txt = "Rank %d of %d" % ranks[gt]
-            xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
-            ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]+25-yoff-3)
-            ctx.show_text(txt)
-        
-        xoffset += GAMES_WIDTH
-
-
-    # print win percentage
-
-    if params['overlay'] == 0:
-        ctx.rectangle(WINLOSS_POS[0]-WINLOSS_WIDTH/2, WINLOSS_POS[1]-7, WINLOSS_WIDTH, 15)
-        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(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]-yoff-3)
-    ctx.show_text(txt)
-    
-    wins, losses = total_stats["wins"], total_games-total_stats["wins"]
-    txt = "???"
-    try:
-        ratio = float(wins)/total_games
-        txt = "%.2f%%" % round(ratio * 100, 2)
-    except:
-        ratio = 0
-    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(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]+18-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.8)
-    txt = "%d win" % wins
-    if wins != 1:
-        txt += "s"
-    xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
-    ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]+30-yoff-3)
-    ctx.show_text(txt)
-    ctx.set_source_rgb(0.8, 0.8, 0.6)
-    txt = "%d loss" % losses
-    if losses != 1:
-        txt += "es"
-    xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
-    ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]+40-yoff-3)
-    ctx.show_text(txt)
-
-
-    # print kill/death ratio
-
-    if params['overlay'] == 0:
-        ctx.rectangle(KILLDEATH_POS[0]-KILLDEATH_WIDTH/2, KILLDEATH_POS[1]-7, KILLDEATH_WIDTH, 15)
-        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(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]-yoff-3)
-    ctx.show_text(txt)
-    
-    kills, deaths = total_stats['kills'] , total_stats['deaths'] 
-    txt = "???"
-    try:
-        ratio = float(kills)/deaths
-        txt = "%.3f" % round(ratio, 3)
-    except:
-        ratio = 0
-
-    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)
-    else:
-        ctx.set_source_rgb(1.0, 0.2, 0.2)
-    xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
-    ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]+18-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 kill" % kills
-    if kills != 1:
-        txt += "s"
-    xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
-    ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]+30-yoff-3)
-    ctx.show_text(txt)
-    ctx.set_source_rgb(0.8, 0.6, 0.6)
-    txt = "%d death" % deaths
-    if deaths != 1:
-        txt += "s"
-    xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
-    ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]+40-yoff-3)
-    ctx.show_text(txt)
-
-
-    # print playing time
-
-    if params['overlay'] == 0:
-        ctx.rectangle( PLAYTIME_POS[0]-PLAYTIME_WIDTH/2, PLAYTIME_POS[1]-7, PLAYTIME_WIDTH, 14)
-        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(PLAYTIME_POS[0]-xoff-tw/2, PLAYTIME_POS[1]-yoff-4)
-    ctx.show_text(txt)
-
-
-    # save to PNG
-    surf.write_to_png(OUTPUT % data['player'].player_id)
+skin = skin_classic
+if len(sys.argv) > 1:
+    arg = sys.argv[1].lower()
+    if arg == "classic":
+        skin = skin_classic
+    elif arg == "archer":
+        skin = skin_archer
 
 
 # environment setup
@@ -543,14 +68,14 @@ for player in players:
     req.matchdict['id'] = player.player_id
 
     sstart = datetime.now()
-    data = get_data(player)
+    skin.get_data(player)
     sstop = datetime.now()
     td = sstop-sstart
     total_seconds = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
     data_time += total_seconds
 
     sstart = datetime.now()
-    render_image(data)
+    skin.render_image("output/%d.png" % player.player_id)
     sstop = datetime.now()
     td = sstop-sstart
     total_seconds = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
@@ -559,7 +84,7 @@ for player in players:
 stop = datetime.now()
 td = stop-start
 total_seconds = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
-print "Creating the badges took %.2f seconds (%.2f s per player)" % (total_seconds, total_seconds/float(len(players)))
-print "Total time for redering images: %.2f s" % render_time
-print "Total time for getting data: %.2f s" % data_time
+print "Creating the badges took %.1f seconds (%.3f s per player)" % (total_seconds, total_seconds/float(len(players)))
+print "Total time for redering images: %.3f s" % render_time
+print "Total time for getting data: %.3f s" % data_time
 
diff --git a/xonstat/batch/badges/render.py b/xonstat/batch/badges/render.py
new file mode 100644 (file)
index 0000000..f788f94
--- /dev/null
@@ -0,0 +1,520 @@
+import re
+import cairo as C
+import sqlalchemy as sa
+import sqlalchemy.sql.functions as func
+from xonstat.models import *
+from xonstat.util import qfont_decode, _all_colors
+
+# 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)
+            ]
+
+
+class Skin:
+
+    # player data, will be filled by get_data()
+    data = {}
+
+    # skin parameters, can be overriden by init
+    params = {
+        'bg':               "dark_wall",    # None - plain; otherwise use given texture
+        'bgcolor':          None,           # transparent bg when bgcolor==None
+        'overlay':          None,           # add overlay graphic on top of bg
+        'font':             "Xolonium",
+        'width':            560,
+        'height':           70,
+        'nick_fontsize':    20,
+        'nick_pos':         (5,18),
+        'nick_maxwidth':    330,
+        'gametype_fontsize':12,
+        'gametype_pos':     (60,31),
+        'gametype_width':   110,
+        'gametype_height':  22,
+        'gametype_color':   (1.0, 1.0, 1.0),
+        'num_gametypes':    3,
+        'nostats_fontsize': 12,
+        'nostats_pos':      (60,59),
+        'nostats_color':    (0.8, 0.2, 0.2),
+        'nostats_angle':    -10,
+        'elo_pos':          (60,47),
+        'elo_fontsize':     10,
+        'elo_color':        (1.0, 1.0, 0.5),
+        'rank_fontsize':    8,
+        'rank_pos':         (60,57),
+        'rank_color':       (0.8, 0.8, 1.0),
+        'wintext_fontsize': 10,
+        'wintext_pos':      (508,3),
+        'wintext_width':    102,
+        'wintext_color':    (0.8, 0.8, 0.8),
+        'wintext_bg':       (0.8, 0.8, 0.8, 0.1),
+        'winp_fontsize':    12,
+        'winp_pos':         (508,19),
+        'winp_colortop':    (0.2, 1.0, 1.0),
+        'winp_colorbot':    (1.0, 1.0, 0.2),
+        'wins_fontsize':    8,
+        'wins_pos':         (508,33),
+        'wins_color':       (0.6, 0.8, 0.8),
+        'loss_fontsize':    8,
+        'loss_pos':         (508,43),
+        'loss_color':       (0.8, 0.8, 0.6),
+        'kdtext_fontsize':  10,
+        'kdtext_pos':       (390,3),
+        'kdtext_width':     102,
+        'kdtext_color':     (0.8, 0.8, 0.8),
+        'kdtext_bg':        (0.8, 0.8, 0.8, 0.1),
+        'kdr_fontsize':     12,
+        'kdr_pos':          (392,19),
+        'kdr_colortop':     (0.2, 1.0, 0.2),
+        'kdr_colorbot':     (1.0, 0.2, 0.2),
+        'kills_fontsize':   8,
+        'kills_pos':        (392,46),
+        'kills_color':      (0.6, 0.8, 0.6),
+        'deaths_fontsize':  8,
+        'deaths_pos':       (392,56),
+        'deaths_color':     (0.8, 0.6, 0.6),
+        'ptime_fontsize':   10,
+        'ptime_pos':        (451,60),
+        'ptime_width':      218,
+        'ptime_bg':         (0.8, 0.8, 0.8, 0.6),
+        'ptime_color':      (0.1, 0.1, 0.1),
+    }
+    
+    def __init__(self, **params):
+        for k,v in params.items():
+            if self.params.has_key(k):
+                self.params[k] = v
+
+    def __getattr__(self, key):
+        if self.params.has_key(key):
+            return self.params[key]
+        return None
+
+    def render_image(self, output_filename):
+        """Render an image for the given player id."""
+
+        # setup variables
+
+        player = self.data['player']
+        total_stats = self.data['total_stats']
+        total_games = total_stats['games']
+        elos  = self.data["elos"]
+        ranks = self.data["ranks"]
+
+        font = "Xolonium"
+        if self.font == 1:
+            font = "DejaVu Sans"
+
+
+        # build image
+
+        surf = C.ImageSurface(C.FORMAT_ARGB32, self.width, self.height)
+        ctx = C.Context(surf)
+        ctx.set_antialias(C.ANTIALIAS_GRAY)
+        
+        # draw background
+        if self.bg == None:
+            if self.bgcolor == None:
+                # transparent background
+                ctx.save()
+                ctx.set_operator(C.OPERATOR_SOURCE)
+                ctx.set_source_rgba(1, 1, 1, 0)
+                ctx.paint()
+                ctx.restore()
+            else:
+                # plain fillcolor
+                ctx.rectangle(0, 0, self.width, self.height)
+                ctx.set_source_rgb(self.bgcolor, self.bgcolor, self.bgcolor)
+                ctx.fill()
+        else:
+            try:
+                # background texture
+                bg = C.ImageSurface.create_from_png("img/%s.png" % self.bg)
+                
+                # tile image
+                if bg:
+                    bg_w, bg_h = bg.get_width(), bg.get_height()
+                    bg_xoff = 0
+                    while bg_xoff < self.width:
+                        bg_yoff = 0
+                        while bg_yoff < self.height:
+                            ctx.set_source_surface(bg, bg_xoff, bg_yoff)
+                            ctx.paint()
+                            bg_yoff += bg_h
+                        bg_xoff += bg_w
+            except:
+                #print "Error: Can't load background texture: %s" % self.bg
+                pass
+
+        # draw overlay graphic
+        if self.overlay:
+            overlay = None
+            try:
+                overlay = C.ImageSurface.create_from_png("img/%s.png" % self.overlay)
+                ctx.set_source_surface(overlay, 0, 0)
+                ctx.mask_surface(overlay)
+                ctx.paint()
+            except:
+                #print "Error: Can't load overlay texture: %s" % self.overlay
+                pass
+
+
+        ## draw player's nickname with fancy colors
+        
+        # deocde nick, strip all weird-looking characters
+        qstr = qfont_decode(player.nick).replace('^^', '^').replace(u'\x00', '')
+        chars = []
+        for c in qstr:
+            # replace weird characters that make problems - TODO
+            if ord(c) < 128:
+                chars.append(c)
+        qstr = ''.join(chars)
+        stripped_nick = strip_colors(qstr.replace(' ', '_'))
+        
+        # fontsize is reduced if width gets too large
+        ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
+        shrinknick = 0
+        while shrinknick < 10:
+            ctx.set_font_size(self.nick_fontsize - shrinknick)
+            xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
+            if tw > self.nick_maxwidth:
+                shrinknick += 2
+                continue
+            break
+
+        # determine width of single whitespace for later use
+        xoff, yoff, tw, th = ctx.text_extents("_")[:4]
+        space_w = tw
+
+        # split nick into colored segments
+        xoffset = 0
+        _all_colors = re.compile(r'(\^\d|\^x[\dA-Fa-f]{3})')
+        parts = _all_colors.split(qstr)
+        while len(parts) > 0:
+            tag = None
+            txt = parts[0]
+            if _all_colors.match(txt):
+                tag = txt[1:]  # strip leading '^'
+                if len(parts) < 2:
+                    break
+                txt = parts[1]
+                del parts[1]
+            del parts[0]
+                
+            if not txt or len(txt) == 0:
+                # only colorcode and no real text, skip this
+                continue
+                
+            r,g,b = _dec_colors[7]
+            try:
+                if tag.startswith('x'):
+                    r = int(tag[1] * 2, 16) / 255.0
+                    g = int(tag[2] * 2, 16) / 255.0
+                    b = int(tag[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)
+                else:
+                    r,g,b = _dec_colors[int(tag[0])]
+            except:
+                r,g,b = _dec_colors[7]
+            
+            ctx.set_source_rgb(r, g, b)
+            ctx.move_to(self.nick_pos[0] + xoffset, self.nick_pos[1])
+            ctx.show_text(txt)
+
+            xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
+            tw += (len(txt)-len(txt.strip())) * space_w  # account for lost whitespaces
+            xoffset += tw + 2
+
+        ## print elos and ranks
+        
+        # show up to three gametypes the player has participated in
+        xoffset = 0
+        for gt in total_stats['gametypes'][:self.num_gametypes]:
+            ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
+            ctx.set_font_size(self.gametype_fontsize)
+            ctx.set_source_rgb(self.gametype_color[0],self.gametype_color[1],self.gametype_color[2])
+            txt = "[ %s ]" % gt.upper()
+            xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
+            ctx.move_to(self.gametype_pos[0]+xoffset-xoff-tw/2, self.gametype_pos[1]-yoff)
+            ctx.show_text(txt)
+            
+
+            # draw lines - TODO put this in overlay graphic
+            if not self.overlay:
+                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(self.gametype_pos[0]+xoffset-self.gametype_width/2+5, self.gametype_pos[1]+14)
+                ctx.line_to(self.gametype_pos[0]+xoffset+self.gametype_width/2-5, self.gametype_pos[1]+14)
+                ctx.stroke()
+                ctx.move_to(self.gametype_pos[0]+xoffset-self.gametype_width/2+5, self.gametype_pos[1]+self.gametype_height+14)
+                ctx.line_to(self.gametype_pos[0]+xoffset+self.gametype_width/2-5, self.gametype_pos[1]+self.gametype_height+14)
+                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(self.nostats_fontsize)
+                ctx.set_source_rgb(self.nostats_color[0],self.nostats_color[1],self.nostats_color[2])
+                txt = "no stats yet!"
+                xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
+                ctx.move_to(self.nostats_pos[0]+xoffset-xoff-tw/2, self.nostats_pos[1]-yoff)
+                ctx.save()
+                ctx.rotate(math.radians(self.nostats_angle))
+                ctx.show_text(txt)
+                ctx.restore()
+            else:
+                ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
+                ctx.set_font_size(self.elo_fontsize)
+                ctx.set_source_rgb(self.elo_color[0], self.elo_color[1], self.elo_color[2])
+                txt = "Elo: %.0f" % round(elos[gt], 0)
+                xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
+                ctx.move_to(self.elo_pos[0]+xoffset-xoff-tw/2, self.elo_pos[1]-yoff)
+                ctx.show_text(txt)
+                
+                ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
+                ctx.set_font_size(self.rank_fontsize)
+                ctx.set_source_rgb(self.rank_color[0], self.rank_color[1], self.rank_color[2])
+                txt = "Rank %d of %d" % ranks[gt]
+                xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
+                ctx.move_to(self.rank_pos[0]+xoffset-xoff-tw/2, self.rank_pos[1]-yoff)
+                ctx.show_text(txt)
+            
+            xoffset += self.gametype_width
+
+
+        # print win percentage
+
+        if not self.overlay:
+            ctx.rectangle(self.wintext_pos[0]-self.wintext_width/2, self.wintext_pos[1]-self.wintext_fontsize/2+1,
+                    self.wintext_width, self.wintext_fontsize+4)
+            ctx.set_source_rgba(self.wintext_bg[0], self.wintext_bg[1], self.wintext_bg[2], self.wintext_bg[3])
+            ctx.fill()
+
+        ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
+        ctx.set_font_size(self.wintext_fontsize)
+        ctx.set_source_rgb(self.wintext_color[0], self.wintext_color[1], self.wintext_color[2])
+        txt = "Win Percentage"
+        xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
+        ctx.move_to(self.wintext_pos[0]-xoff-tw/2, self.wintext_pos[1]-yoff)
+        ctx.show_text(txt)
+        
+        wins, losses = total_stats["wins"], total_games-total_stats["wins"]
+        txt = "???"
+        try:
+            ratio = float(wins)/total_games
+            txt = "%.2f%%" % round(ratio * 100, 2)
+        except:
+            ratio = 0
+        ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
+        ctx.set_font_size(self.winp_fontsize)
+        r = ratio*self.winp_colortop[0] + (1-ratio)*self.winp_colorbot[0]
+        g = ratio*self.winp_colortop[1] + (1-ratio)*self.winp_colorbot[1]
+        b = ratio*self.winp_colortop[2] + (1-ratio)*self.winp_colorbot[2]
+        ctx.set_source_rgb(r, g, b)
+        xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
+        ctx.move_to(self.winp_pos[0]-xoff-tw/2, self.winp_pos[1]-yoff)
+        ctx.show_text(txt)
+
+        ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
+        ctx.set_font_size(self.wins_fontsize)
+        ctx.set_source_rgb(self.wins_color[0], self.wins_color[1], self.wins_color[2])
+        txt = "%d win" % wins
+        if wins != 1:
+            txt += "s"
+        xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
+        ctx.move_to(self.wins_pos[0]-xoff-tw/2, self.wins_pos[1]-yoff)
+        ctx.show_text(txt)
+
+        ctx.set_font_size(self.loss_fontsize)
+        ctx.set_source_rgb(self.loss_color[0], self.loss_color[1], self.loss_color[2])
+        txt = "%d loss" % losses
+        if losses != 1:
+            txt += "es"
+        xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
+        ctx.move_to(self.loss_pos[0]-xoff-tw/2, self.loss_pos[1]-yoff)
+        ctx.show_text(txt)
+
+
+        # print kill/death ratio
+
+        if not self.overlay:
+            ctx.rectangle(self.kdtext_pos[0]-self.kdtext_width/2, self.kdtext_pos[1]-self.kdtext_fontsize/2+1,
+                    self.kdtext_width, self.kdtext_fontsize+4)
+            ctx.set_source_rgba(self.kdtext_bg[0], self.kdtext_bg[1], self.kdtext_bg[2], self.kdtext_bg[3])
+            ctx.fill()
+
+        ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
+        ctx.set_font_size(self.kdtext_fontsize)
+        ctx.set_source_rgb(self.kdtext_color[0], self.kdtext_color[1], self.kdtext_color[2])
+        txt = "Kill Ratio"
+        xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
+        ctx.move_to(self.kdtext_pos[0]-xoff-tw/2, self.kdtext_pos[1]-yoff)
+        ctx.show_text(txt)
+        
+        kills, deaths = total_stats['kills'] , total_stats['deaths'] 
+        txt = "???"
+        try:
+            ratio = float(kills)/deaths
+            txt = "%.3f" % round(ratio, 3)
+        except:
+            ratio = 0
+
+        ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
+        ctx.set_font_size(self.kdr_fontsize)
+        nr = ratio / 2.0
+        if nr > 1:
+            nr = 1
+        r = nr*self.kdr_colortop[0] + (1-nr)*self.kdr_colorbot[0]
+        g = nr*self.kdr_colortop[1] + (1-nr)*self.kdr_colorbot[1]
+        b = nr*self.kdr_colortop[2] + (1-nr)*self.kdr_colorbot[2]
+        ctx.set_source_rgb(r, g, b)
+        xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
+        ctx.move_to(self.kdr_pos[0]-xoff-tw/2, self.kdr_pos[1]-yoff)
+        ctx.show_text(txt)
+
+        ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
+        ctx.set_font_size(self.kills_fontsize)
+        ctx.set_source_rgb(self.kills_color[0], self.kills_color[1], self.kills_color[2])
+        txt = "%d kill" % kills
+        if kills != 1:
+            txt += "s"
+        xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
+        ctx.move_to(self.kills_pos[0]-xoff-tw/2, self.kills_pos[1]+yoff)
+        ctx.show_text(txt)
+
+        ctx.set_font_size(self.deaths_fontsize)
+        ctx.set_source_rgb(self.deaths_color[0], self.deaths_color[1], self.deaths_color[2])
+        txt = "%d death" % deaths
+        if deaths != 1:
+            txt += "s"
+        xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
+        ctx.move_to(self.deaths_pos[0]-xoff-tw/2, self.deaths_pos[1]+yoff)
+        ctx.show_text(txt)
+
+
+        # print playing time
+
+        if not self.overlay:
+            ctx.rectangle( self.ptime_pos[0]-self.ptime_width/2, self.ptime_pos[1]-self.ptime_fontsize/2+1,
+                    self.ptime_width, self.ptime_fontsize+4)
+            ctx.set_source_rgba(self.ptime_bg[0], self.ptime_bg[1], self.ptime_bg[2], self.ptime_bg[2])
+            ctx.fill()
+
+        ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
+        ctx.set_font_size(self.ptime_fontsize)
+        ctx.set_source_rgb(self.ptime_color[0], self.ptime_color[1], self.ptime_color[2])
+        txt = "Playing time: %s" % str(total_stats['alivetime'])
+        xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
+        ctx.move_to(self.ptime_pos[0]-xoff-tw/2, self.ptime_pos[1]-yoff)
+        ctx.show_text(txt)
+
+
+        # save to PNG
+        surf.write_to_png(output_filename)
+
+
+    def get_data(self, 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
+
+        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 = {}
+        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['alivetime'],) = DBSession.query(
+                func.sum(PlayerGameStat.kills),
+                func.sum(PlayerGameStat.deaths),
+                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()
+
+        (total_stats['wins'],) = DBSession.\
+                query("total_wins").\
+                from_statement(
+                    "select count(*) total_wins "
+                    "from games g, player_game_stats pgs "
+                    "where g.game_id = pgs.game_id "
+                    "and player_id=:player_id "
+                    "and (g.winner = pgs.team or pgs.rank = 1)"
+                ).params(player_id=player_id).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
+
+        self.data = {
+                'player':player,
+                'total_stats':total_stats,
+                'ranks':ranks_dict,
+                'elos':elos_dict,
+            }
+