]> git.xonotic.org Git - xonotic/xonstat.git/blob - xonstat/batch/badges/render.py
3ee9c572f4743998e29026be07d00af1aa23ea7e
[xonotic/xonstat.git] / xonstat / batch / badges / render.py
1 import re
2 import zlib, struct
3 import cairo as C
4 from colorsys import rgb_to_hls, hls_to_rgb
5 import sqlalchemy as sa
6 import sqlalchemy.sql.functions as func
7 from xonstat.models import *
8 from xonstat.util import qfont_decode, _all_colors
9
10 # similar to html_colors() from util.py
11 _contrast_threshold = 0.5
12
13 _dec_colors = [ (0.5,0.5,0.5),
14                 (1.0,0.0,0.0),
15                 (0.2,1.0,0.0),
16                 (1.0,1.0,0.0),
17                 (0.2,0.4,1.0),
18                 (0.2,1.0,1.0),
19                 (1.0,0.2,102),
20                 (1.0,1.0,1.0),
21                 (0.6,0.6,0.6),
22                 (0.5,0.5,0.5)
23             ]
24
25
26 def writepng(filename, buf, width, height):
27     width_byte_4 = width * 4
28     # fix color ordering (BGR -> RGB)
29     for byte in xrange(width*height):
30         pos = byte * 4
31         buf[pos:pos+4] = buf[pos+2] + buf[pos+1] + buf[pos+0] + buf[pos+3]
32     # merge lines
33     #raw_data = b"".join(b'\x00' + buf[span:span + width_byte_4] for span in xrange((height - 1) * width * 4, -1, - width_byte_4))
34     raw_data = b"".join(b'\x00' + buf[span:span + width_byte_4] for span in range(0, (height-1) * width * 4 + 1, width_byte_4))
35     def png_pack(png_tag, data):
36         chunk_head = png_tag + data
37         return struct.pack("!I", len(data)) + chunk_head + struct.pack("!I", 0xFFFFFFFF & zlib.crc32(chunk_head))
38     data = b"".join([
39         b'\x89PNG\r\n\x1a\n',
40         png_pack(b'IHDR', struct.pack("!2I5B", width, height, 8, 6, 0, 0, 0)),
41         png_pack(b'IDAT', zlib.compress(raw_data, 9)),
42         png_pack(b'IEND', b'')])
43     f = open(filename, "wb")
44     try:
45         f.write(data)
46     finally:
47         f.close()
48
49
50 class Skin:
51
52     # player data, will be filled by get_data()
53     data = {}
54
55     # skin parameters, can be overriden by init
56     params = {
57         'bg':               "dark_wall",    # None - plain; otherwise use given texture
58         'bgcolor':          None,           # transparent bg when bgcolor==None
59         'overlay':          None,           # add overlay graphic on top of bg
60         'font':             "Xolonium",
61         'width':            560,
62         'height':           70,
63         'nick_fontsize':    20,
64         'nick_pos':         (5,18),
65         'nick_maxwidth':    330,
66         'gametype_fontsize':12,
67         'gametype_pos':     (60,31),
68         'gametype_width':   110,
69         'gametype_height':  22,
70         'gametype_color':   (1.0, 1.0, 1.0),
71         'gametype_text':    "[ %s ]",
72         'num_gametypes':    3,
73         'nostats_fontsize': 12,
74         'nostats_pos':      (60,59),
75         'nostats_color':    (0.8, 0.2, 0.2),
76         'nostats_angle':    -10,
77         'nostats_text':     "no stats yet!",
78         'elo_pos':          (60,47),
79         'elo_fontsize':     10,
80         'elo_color':        (1.0, 1.0, 0.5),
81         'elo_text':         "Elo %.0f",
82         'rank_fontsize':    8,
83         'rank_pos':         (60,57),
84         'rank_color':       (0.8, 0.8, 1.0),
85         'rank_text':        "Rank %d of %d",
86         'wintext_fontsize': 10,
87         'wintext_pos':      (508,3),
88         'wintext_width':    102,
89         'wintext_color':    (0.8, 0.8, 0.8),
90         'wintext_bg':       (0.8, 0.8, 0.8, 0.1),
91         'wintext_text':     "Win Percentage",
92         'winp_fontsize':    12,
93         'winp_pos':         (508,19),
94         'winp_colortop':    (0.2, 1.0, 1.0),
95         'winp_colorbot':    (1.0, 1.0, 0.2),
96         'wins_fontsize':    8,
97         'wins_pos':         (508,33),
98         'wins_color':       (0.6, 0.8, 0.8),
99         'loss_fontsize':    8,
100         'loss_pos':         (508,43),
101         'loss_color':       (0.8, 0.8, 0.6),
102         'kdtext_fontsize':  10,
103         'kdtext_pos':       (390,3),
104         'kdtext_width':     102,
105         'kdtext_color':     (0.8, 0.8, 0.8),
106         'kdtext_bg':        (0.8, 0.8, 0.8, 0.1),
107         'kdtext_text':      "Kill Ratio",
108         'kdr_fontsize':     12,
109         'kdr_pos':          (392,19),
110         'kdr_colortop':     (0.2, 1.0, 0.2),
111         'kdr_colorbot':     (1.0, 0.2, 0.2),
112         'kills_fontsize':   8,
113         'kills_pos':        (392,46),
114         'kills_color':      (0.6, 0.8, 0.6),
115         'deaths_fontsize':  8,
116         'deaths_pos':       (392,56),
117         'deaths_color':     (0.8, 0.6, 0.6),
118         'ptime_fontsize':   10,
119         'ptime_pos':        (451,60),
120         'ptime_width':      222,
121         'ptime_bg':         (0.8, 0.8, 0.8, 0.5),
122         'ptime_color':      (0.1, 0.1, 0.1),
123         'ptime_text':       "Playing Time: %s",
124     }
125     
126     def __init__(self, **params):
127         for k,v in params.items():
128             if self.params.has_key(k):
129                 self.params[k] = v
130
131     def __getattr__(self, key):
132         if self.params.has_key(key):
133             return self.params[key]
134         return None
135
136     def render_image(self, output_filename):
137         """Render an image for the given player id."""
138
139         # setup variables
140
141         player = self.data['player']
142         total_stats = self.data['total_stats']
143         total_games = total_stats['games']
144         elos  = self.data["elos"]
145         ranks = self.data["ranks"]
146
147         font = "Xolonium"
148         if self.font == 1:
149             font = "DejaVu Sans"
150
151
152         # build image
153
154         surf = C.ImageSurface(C.FORMAT_ARGB32, self.width, self.height)
155         ctx = C.Context(surf)
156         ctx.set_antialias(C.ANTIALIAS_GRAY)
157         
158         # draw background
159         ctx.save()
160         ctx.set_operator(C.OPERATOR_SOURCE)
161         if self.bg == None:
162             if self.bgcolor != None:
163                 # plain fillcolor, full transparency possible with (1,1,1,0)
164                 ctx.rectangle(0, 0, self.width, self.height)
165                 ctx.set_source_rgba(self.bgcolor[0], self.bgcolor[1], self.bgcolor[2], self.bgcolor[3])
166                 ctx.fill()
167         else:
168             try:
169                 # background texture
170                 bg = C.ImageSurface.create_from_png("img/%s.png" % self.bg)
171                 
172                 # tile image
173                 if bg:
174                     bg_w, bg_h = bg.get_width(), bg.get_height()
175                     bg_xoff = 0
176                     while bg_xoff < self.width:
177                         bg_yoff = 0
178                         while bg_yoff < self.height:
179                             ctx.set_source_surface(bg, bg_xoff, bg_yoff)
180                             #ctx.mask_surface(bg)
181                             ctx.paint()
182                             bg_yoff += bg_h
183                         bg_xoff += bg_w
184
185             except:
186                 #print "Error: Can't load background texture: %s" % self.bg
187                 pass
188         ctx.restore()
189
190         # draw overlay graphic
191         if self.overlay != None:
192             try:
193                 overlay = C.ImageSurface.create_from_png("img/%s.png" % self.overlay)
194                 ctx.set_source_surface(overlay, 0, 0)
195                 #ctx.mask_surface(overlay)
196                 ctx.paint()
197             except:
198                 #print "Error: Can't load overlay texture: %s" % self.overlay
199                 pass
200
201
202         ## draw player's nickname with fancy colors
203         
204         # deocde nick, strip all weird-looking characters
205         qstr = qfont_decode(player.nick).replace('^^', '^').replace(u'\x00', '')
206         chars = []
207         for c in qstr:
208             # replace weird characters that make problems - TODO
209             if ord(c) < 128:
210                 chars.append(c)
211         qstr = ''.join(chars)
212         stripped_nick = strip_colors(qstr.replace(' ', '_'))
213         
214         # fontsize is reduced if width gets too large
215         ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
216         shrinknick = 0
217         while shrinknick < 10:
218             ctx.set_font_size(self.nick_fontsize - shrinknick)
219             xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
220             if tw > self.nick_maxwidth:
221                 shrinknick += 2
222                 continue
223             break
224
225         # determine width of single whitespace for later use
226         xoff, yoff, tw, th = ctx.text_extents("_")[:4]
227         space_w = tw
228
229         # split nick into colored segments
230         xoffset = 0
231         _all_colors = re.compile(r'(\^\d|\^x[\dA-Fa-f]{3})')
232         parts = _all_colors.split(qstr)
233         while len(parts) > 0:
234             tag = None
235             txt = parts[0]
236             if _all_colors.match(txt):
237                 tag = txt[1:]  # strip leading '^'
238                 if len(parts) < 2:
239                     break
240                 txt = parts[1]
241                 del parts[1]
242             del parts[0]
243                 
244             if not txt or len(txt) == 0:
245                 # only colorcode and no real text, skip this
246                 continue
247             
248             if tag:
249                 if tag.startswith('x'):
250                     r = int(tag[1] * 2, 16) / 255.0
251                     g = int(tag[2] * 2, 16) / 255.0
252                     b = int(tag[3] * 2, 16) / 255.0
253                     hue, light, satur = rgb_to_hls(r, g, b)
254                     if light < _contrast_threshold:
255                         light = _contrast_threshold
256                         r, g, b = hls_to_rgb(hue, light, satur)
257                 else:
258                     r,g,b = _dec_colors[int(tag[0])]
259             else:
260                 r,g,b = _dec_colors[7]
261             
262             ctx.set_source_rgb(r, g, b)
263             ctx.move_to(self.nick_pos[0] + xoffset, self.nick_pos[1])
264             ctx.show_text(txt)
265
266             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
267             tw += (len(txt)-len(txt.strip())) * space_w  # account for lost whitespaces
268             xoffset += tw + 2
269
270         ## print elos and ranks
271         
272         # show up to three gametypes the player has participated in
273         xoffset = 0
274         for gt in total_stats['gametypes'][:self.num_gametypes]:
275             if self.gametype_pos:
276                 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
277                 ctx.set_font_size(self.gametype_fontsize)
278                 ctx.set_source_rgb(self.gametype_color[0],self.gametype_color[1],self.gametype_color[2])
279                 txt = self.gametype_text % gt.upper()
280                 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
281                 ctx.move_to(self.gametype_pos[0]+xoffset-xoff-tw/2, self.gametype_pos[1]-yoff)
282                 ctx.show_text(txt)
283
284                 # draw lines - TODO put this in overlay graphic
285                 if self.overlay == None:
286                     old_aa = ctx.get_antialias()
287                     ctx.set_antialias(C.ANTIALIAS_NONE)
288                     ctx.set_source_rgb(0.8, 0.8, 0.8)
289                     ctx.set_line_width(1)
290                     ctx.move_to(self.gametype_pos[0]+xoffset-self.gametype_width/2+5, self.gametype_pos[1]+14)
291                     ctx.line_to(self.gametype_pos[0]+xoffset+self.gametype_width/2-5, self.gametype_pos[1]+14)
292                     ctx.stroke()
293                     ctx.move_to(self.gametype_pos[0]+xoffset-self.gametype_width/2+5, self.gametype_pos[1]+self.gametype_height+14)
294                     ctx.line_to(self.gametype_pos[0]+xoffset+self.gametype_width/2-5, self.gametype_pos[1]+self.gametype_height+14)
295                     ctx.stroke()
296                     ctx.set_antialias(old_aa)
297
298             if not elos.has_key(gt) or not ranks.has_key(gt):
299                 if self.nostats_pos:
300                     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
301                     ctx.set_font_size(self.nostats_fontsize)
302                     ctx.set_source_rgb(self.nostats_color[0],self.nostats_color[1],self.nostats_color[2])
303                     txt = self.nostats_text
304                     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
305                     ctx.move_to(self.nostats_pos[0]+xoffset-xoff-tw/2, self.nostats_pos[1]-yoff)
306                     ctx.save()
307                     ctx.rotate(math.radians(self.nostats_angle))
308                     ctx.show_text(txt)
309                     ctx.restore()
310             else:
311                 if self.elo_pos:
312                     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
313                     ctx.set_font_size(self.elo_fontsize)
314                     ctx.set_source_rgb(self.elo_color[0], self.elo_color[1], self.elo_color[2])
315                     txt = self.elo_text % round(elos[gt], 0)
316                     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
317                     ctx.move_to(self.elo_pos[0]+xoffset-xoff-tw/2, self.elo_pos[1]-yoff)
318                     ctx.show_text(txt)
319                 if  self.rank_pos:
320                     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
321                     ctx.set_font_size(self.rank_fontsize)
322                     ctx.set_source_rgb(self.rank_color[0], self.rank_color[1], self.rank_color[2])
323                     txt = self.rank_text % ranks[gt]
324                     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
325                     ctx.move_to(self.rank_pos[0]+xoffset-xoff-tw/2, self.rank_pos[1]-yoff)
326                     ctx.show_text(txt)
327             
328             xoffset += self.gametype_width
329
330
331         # print win percentage
332
333         if self.wintext_pos:
334             if self.overlay == None:
335                 ctx.rectangle(self.wintext_pos[0]-self.wintext_width/2, self.wintext_pos[1]-self.wintext_fontsize/2+1,
336                         self.wintext_width, self.wintext_fontsize+4)
337                 ctx.set_source_rgba(self.wintext_bg[0], self.wintext_bg[1], self.wintext_bg[2], self.wintext_bg[3])
338                 ctx.fill()
339
340             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
341             ctx.set_font_size(self.wintext_fontsize)
342             ctx.set_source_rgb(self.wintext_color[0], self.wintext_color[1], self.wintext_color[2])
343             txt = self.wintext_text
344             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
345             ctx.move_to(self.wintext_pos[0]-xoff-tw/2, self.wintext_pos[1]-yoff)
346             ctx.show_text(txt)
347
348         wins, losses = total_stats["wins"], total_games-total_stats["wins"]
349         txt = "???"
350         try:
351             ratio = float(wins)/total_games
352             txt = "%.2f%%" % round(ratio * 100, 2)
353         except:
354             ratio = 0
355         
356         if self.winp_pos:
357             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
358             ctx.set_font_size(self.winp_fontsize)
359             r = ratio*self.winp_colortop[0] + (1-ratio)*self.winp_colorbot[0]
360             g = ratio*self.winp_colortop[1] + (1-ratio)*self.winp_colorbot[1]
361             b = ratio*self.winp_colortop[2] + (1-ratio)*self.winp_colorbot[2]
362             ctx.set_source_rgb(r, g, b)
363             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
364             ctx.move_to(self.winp_pos[0]-xoff-tw/2, self.winp_pos[1]-yoff)
365             ctx.show_text(txt)
366
367         if self.wins_pos:
368             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
369             ctx.set_font_size(self.wins_fontsize)
370             ctx.set_source_rgb(self.wins_color[0], self.wins_color[1], self.wins_color[2])
371             txt = "%d win" % wins
372             if wins != 1:
373                 txt += "s"
374             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
375             ctx.move_to(self.wins_pos[0]-xoff-tw/2, self.wins_pos[1]-yoff)
376             ctx.show_text(txt)
377
378         if self.loss_pos:
379             ctx.set_font_size(self.loss_fontsize)
380             ctx.set_source_rgb(self.loss_color[0], self.loss_color[1], self.loss_color[2])
381             txt = "%d loss" % losses
382             if losses != 1:
383                 txt += "es"
384             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
385             ctx.move_to(self.loss_pos[0]-xoff-tw/2, self.loss_pos[1]-yoff)
386             ctx.show_text(txt)
387
388
389         # print kill/death ratio
390
391         if self.kdtext_pos:
392             if self.overlay == None:
393                 ctx.rectangle(self.kdtext_pos[0]-self.kdtext_width/2, self.kdtext_pos[1]-self.kdtext_fontsize/2+1,
394                         self.kdtext_width, self.kdtext_fontsize+4)
395                 ctx.set_source_rgba(self.kdtext_bg[0], self.kdtext_bg[1], self.kdtext_bg[2], self.kdtext_bg[3])
396                 ctx.fill()
397
398             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
399             ctx.set_font_size(self.kdtext_fontsize)
400             ctx.set_source_rgb(self.kdtext_color[0], self.kdtext_color[1], self.kdtext_color[2])
401             txt = self.kdtext_text
402             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
403             ctx.move_to(self.kdtext_pos[0]-xoff-tw/2, self.kdtext_pos[1]-yoff)
404             ctx.show_text(txt)
405         
406         kills, deaths = total_stats['kills'] , total_stats['deaths'] 
407         txt = "???"
408         try:
409             ratio = float(kills)/deaths
410             txt = "%.3f" % round(ratio, 3)
411         except:
412             ratio = 0
413
414         if self.kdr_pos:
415             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
416             ctx.set_font_size(self.kdr_fontsize)
417             nr = ratio / 2.0
418             if nr > 1:
419                 nr = 1
420             r = nr*self.kdr_colortop[0] + (1-nr)*self.kdr_colorbot[0]
421             g = nr*self.kdr_colortop[1] + (1-nr)*self.kdr_colorbot[1]
422             b = nr*self.kdr_colortop[2] + (1-nr)*self.kdr_colorbot[2]
423             ctx.set_source_rgb(r, g, b)
424             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
425             ctx.move_to(self.kdr_pos[0]-xoff-tw/2, self.kdr_pos[1]-yoff)
426             ctx.show_text(txt)
427
428         if self.kills_pos:
429             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
430             ctx.set_font_size(self.kills_fontsize)
431             ctx.set_source_rgb(self.kills_color[0], self.kills_color[1], self.kills_color[2])
432             txt = "%d kill" % kills
433             if kills != 1:
434                 txt += "s"
435             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
436             ctx.move_to(self.kills_pos[0]-xoff-tw/2, self.kills_pos[1]+yoff)
437             ctx.show_text(txt)
438
439         if self.deaths_pos:
440             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
441             ctx.set_font_size(self.deaths_fontsize)
442             ctx.set_source_rgb(self.deaths_color[0], self.deaths_color[1], self.deaths_color[2])
443             txt = "%d death" % deaths
444             if deaths != 1:
445                 txt += "s"
446             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
447             ctx.move_to(self.deaths_pos[0]-xoff-tw/2, self.deaths_pos[1]+yoff)
448             ctx.show_text(txt)
449
450
451         # print playing time
452
453         if self.ptime_pos:
454             if self.overlay == None:
455                 ctx.rectangle( self.ptime_pos[0]-self.ptime_width/2, self.ptime_pos[1]-self.ptime_fontsize/2+1,
456                         self.ptime_width, self.ptime_fontsize+4)
457                 ctx.set_source_rgba(self.ptime_bg[0], self.ptime_bg[1], self.ptime_bg[2], self.ptime_bg[2])
458                 ctx.fill()
459
460             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
461             ctx.set_font_size(self.ptime_fontsize)
462             ctx.set_source_rgb(self.ptime_color[0], self.ptime_color[1], self.ptime_color[2])
463             txt = self.ptime_text % str(total_stats['alivetime'])
464             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
465             ctx.move_to(self.ptime_pos[0]-xoff-tw/2, self.ptime_pos[1]-yoff)
466             ctx.show_text(txt)
467
468
469         # save to PNG
470         #surf.write_to_png(output_filename)
471         surf.flush()
472         imgdata = surf.get_data()
473         writepng(output_filename, imgdata, self.width, self.height)
474
475
476     def get_data(self, player):
477         """Return player data as dict.
478
479         This function is similar to the function in player.py but more optimized
480         for this purpose.
481         """
482
483         # total games
484         # wins/losses
485         # kills/deaths
486         # duel/dm/tdm/ctf elo + rank
487
488         player_id = player.player_id
489
490         games_played = DBSession.query(
491                 Game.game_type_cd, func.count(), func.sum(PlayerGameStat.alivetime)).\
492                 filter(Game.game_id == PlayerGameStat.game_id).\
493                 filter(PlayerGameStat.player_id == player_id).\
494                 group_by(Game.game_type_cd).\
495                 order_by(func.count().desc()).\
496                 limit(3).all()  # limit to 3 gametypes!
497
498         total_stats = {}
499         total_stats['games'] = 0
500         total_stats['games_breakdown'] = {}  # this is a dictionary inside a dictionary .. dictception?
501         total_stats['games_alivetime'] = {}
502         total_stats['gametypes'] = []
503         for (game_type_cd, games, alivetime) in games_played:
504             total_stats['games'] += games
505             total_stats['gametypes'].append(game_type_cd)
506             total_stats['games_breakdown'][game_type_cd] = games
507             total_stats['games_alivetime'][game_type_cd] = alivetime
508
509         (total_stats['kills'], total_stats['deaths'], total_stats['alivetime'],) = DBSession.query(
510                 func.sum(PlayerGameStat.kills),
511                 func.sum(PlayerGameStat.deaths),
512                 func.sum(PlayerGameStat.alivetime)).\
513                 filter(PlayerGameStat.player_id == player_id).\
514                 one()
515
516     #    (total_stats['wins'],) = DBSession.query(
517     #            func.count("*")).\
518     #            filter(Game.game_id == PlayerGameStat.game_id).\
519     #            filter(PlayerGameStat.player_id == player_id).\
520     #            filter(Game.winner == PlayerGameStat.team or PlayerGameStat.rank == 1).\
521     #            one()
522
523         (total_stats['wins'],) = DBSession.\
524                 query("total_wins").\
525                 from_statement(
526                     "select count(*) total_wins "
527                     "from games g, player_game_stats pgs "
528                     "where g.game_id = pgs.game_id "
529                     "and player_id=:player_id "
530                     "and (g.winner = pgs.team or pgs.rank = 1)"
531                 ).params(player_id=player_id).one()
532
533         ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
534                 from_statement(
535                     "select pr.game_type_cd, pr.rank, overall.max_rank "
536                     "from player_ranks pr,  "
537                        "(select game_type_cd, max(rank) max_rank "
538                         "from player_ranks  "
539                         "group by game_type_cd) overall "
540                     "where pr.game_type_cd = overall.game_type_cd  "
541                     "and player_id = :player_id "
542                     "order by rank").\
543                 params(player_id=player_id).all()
544
545         ranks_dict = {}
546         for gtc,rank,max_rank in ranks:
547             ranks_dict[gtc] = (rank, max_rank)
548
549         elos = DBSession.query(PlayerElo).\
550                 filter_by(player_id=player_id).\
551                 order_by(PlayerElo.elo.desc()).\
552                 all()
553
554         elos_dict = {}
555         for elo in elos:
556             if elo.games > 32:
557                 elos_dict[elo.game_type_cd] = elo.elo
558
559         self.data = {
560                 'player':player,
561                 'total_stats':total_stats,
562                 'ranks':ranks_dict,
563                 'elos':elos_dict,
564             }
565