3 import sqlalchemy as sa
4 import sqlalchemy.sql.functions as func
5 from xonstat.models import *
6 from xonstat.util import qfont_decode, _all_colors
8 # similar to html_colors() from util.py
9 _contrast_threshold = 0.5
11 _dec_colors = [ (0.5,0.5,0.5),
26 # player data, will be filled by get_data()
29 # skin parameters, can be overriden by init
31 'bg': "dark_wall", # None - plain; otherwise use given texture
32 'bgcolor': None, # transparent bg when bgcolor==None
33 'overlay': None, # add overlay graphic on top of bg
40 'gametype_fontsize':12,
41 'gametype_pos': (60,31),
42 'gametype_width': 110,
43 'gametype_height': 22,
44 'gametype_color': (1.0, 1.0, 1.0),
46 'nostats_fontsize': 12,
47 'nostats_pos': (60,59),
48 'nostats_color': (0.8, 0.2, 0.2),
52 'elo_color': (1.0, 1.0, 0.5),
55 'rank_color': (0.8, 0.8, 1.0),
56 'wintext_fontsize': 10,
57 'wintext_pos': (508,3),
59 'wintext_color': (0.8, 0.8, 0.8),
60 'wintext_bg': (0.8, 0.8, 0.8, 0.1),
63 'winp_colortop': (0.2, 1.0, 1.0),
64 'winp_colorbot': (1.0, 1.0, 0.2),
67 'wins_color': (0.6, 0.8, 0.8),
70 'loss_color': (0.8, 0.8, 0.6),
71 'kdtext_fontsize': 10,
72 'kdtext_pos': (390,3),
74 'kdtext_color': (0.8, 0.8, 0.8),
75 'kdtext_bg': (0.8, 0.8, 0.8, 0.1),
78 'kdr_colortop': (0.2, 1.0, 0.2),
79 'kdr_colorbot': (1.0, 0.2, 0.2),
81 'kills_pos': (392,46),
82 'kills_color': (0.6, 0.8, 0.6),
84 'deaths_pos': (392,56),
85 'deaths_color': (0.8, 0.6, 0.6),
87 'ptime_pos': (451,60),
89 'ptime_bg': (0.8, 0.8, 0.8, 0.6),
90 'ptime_color': (0.1, 0.1, 0.1),
93 def __init__(self, **params):
94 for k,v in params.items():
95 if self.params.has_key(k):
98 def __getattr__(self, key):
99 if self.params.has_key(key):
100 return self.params[key]
103 def render_image(self, output_filename):
104 """Render an image for the given player id."""
108 player = self.data['player']
109 total_stats = self.data['total_stats']
110 total_games = total_stats['games']
111 elos = self.data["elos"]
112 ranks = self.data["ranks"]
121 surf = C.ImageSurface(C.FORMAT_ARGB32, self.width, self.height)
122 ctx = C.Context(surf)
123 ctx.set_antialias(C.ANTIALIAS_GRAY)
127 if self.bgcolor == None:
128 # transparent background
130 ctx.set_operator(C.OPERATOR_SOURCE)
131 ctx.set_source_rgba(1, 1, 1, 0)
136 ctx.rectangle(0, 0, self.width, self.height)
137 ctx.set_source_rgb(self.bgcolor, self.bgcolor, self.bgcolor)
142 bg = C.ImageSurface.create_from_png("img/%s.png" % self.bg)
146 bg_w, bg_h = bg.get_width(), bg.get_height()
148 while bg_xoff < self.width:
150 while bg_yoff < self.height:
151 ctx.set_source_surface(bg, bg_xoff, bg_yoff)
156 #print "Error: Can't load background texture: %s" % self.bg
159 # draw overlay graphic
163 overlay = C.ImageSurface.create_from_png("img/%s.png" % self.overlay)
164 ctx.set_source_surface(overlay, 0, 0)
165 ctx.mask_surface(overlay)
168 #print "Error: Can't load overlay texture: %s" % self.overlay
172 ## draw player's nickname with fancy colors
174 # deocde nick, strip all weird-looking characters
175 qstr = qfont_decode(player.nick).replace('^^', '^').replace(u'\x00', '')
178 # replace weird characters that make problems - TODO
181 qstr = ''.join(chars)
182 stripped_nick = strip_colors(qstr.replace(' ', '_'))
184 # fontsize is reduced if width gets too large
185 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
187 while shrinknick < 10:
188 ctx.set_font_size(self.nick_fontsize - shrinknick)
189 xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
190 if tw > self.nick_maxwidth:
195 # determine width of single whitespace for later use
196 xoff, yoff, tw, th = ctx.text_extents("_")[:4]
199 # split nick into colored segments
201 _all_colors = re.compile(r'(\^\d|\^x[\dA-Fa-f]{3})')
202 parts = _all_colors.split(qstr)
203 while len(parts) > 0:
206 if _all_colors.match(txt):
207 tag = txt[1:] # strip leading '^'
214 if not txt or len(txt) == 0:
215 # only colorcode and no real text, skip this
218 r,g,b = _dec_colors[7]
220 if tag.startswith('x'):
221 r = int(tag[1] * 2, 16) / 255.0
222 g = int(tag[2] * 2, 16) / 255.0
223 b = int(tag[3] * 2, 16) / 255.0
224 hue, light, satur = rgb_to_hls(r, g, b)
225 if light < _contrast_threshold:
226 light = _contrast_threshold
227 r, g, b = hls_to_rgb(hue, light, satur)
229 r,g,b = _dec_colors[int(tag[0])]
231 r,g,b = _dec_colors[7]
233 ctx.set_source_rgb(r, g, b)
234 ctx.move_to(self.nick_pos[0] + xoffset, self.nick_pos[1])
237 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
238 tw += (len(txt)-len(txt.strip())) * space_w # account for lost whitespaces
241 ## print elos and ranks
243 # show up to three gametypes the player has participated in
245 for gt in total_stats['gametypes'][:self.num_gametypes]:
246 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
247 ctx.set_font_size(self.gametype_fontsize)
248 ctx.set_source_rgb(self.gametype_color[0],self.gametype_color[1],self.gametype_color[2])
249 txt = "[ %s ]" % gt.upper()
250 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
251 ctx.move_to(self.gametype_pos[0]+xoffset-xoff-tw/2, self.gametype_pos[1]-yoff)
255 # draw lines - TODO put this in overlay graphic
257 old_aa = ctx.get_antialias()
258 ctx.set_antialias(C.ANTIALIAS_NONE)
259 ctx.set_source_rgb(0.8, 0.8, 0.8)
260 ctx.set_line_width(1)
261 ctx.move_to(self.gametype_pos[0]+xoffset-self.gametype_width/2+5, self.gametype_pos[1]+14)
262 ctx.line_to(self.gametype_pos[0]+xoffset+self.gametype_width/2-5, self.gametype_pos[1]+14)
264 ctx.move_to(self.gametype_pos[0]+xoffset-self.gametype_width/2+5, self.gametype_pos[1]+self.gametype_height+14)
265 ctx.line_to(self.gametype_pos[0]+xoffset+self.gametype_width/2-5, self.gametype_pos[1]+self.gametype_height+14)
267 ctx.set_antialias(old_aa)
269 if not elos.has_key(gt) or not ranks.has_key(gt):
270 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
271 ctx.set_font_size(self.nostats_fontsize)
272 ctx.set_source_rgb(self.nostats_color[0],self.nostats_color[1],self.nostats_color[2])
273 txt = "no stats yet!"
274 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
275 ctx.move_to(self.nostats_pos[0]+xoffset-xoff-tw/2, self.nostats_pos[1]-yoff)
277 ctx.rotate(math.radians(self.nostats_angle))
281 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
282 ctx.set_font_size(self.elo_fontsize)
283 ctx.set_source_rgb(self.elo_color[0], self.elo_color[1], self.elo_color[2])
284 txt = "Elo: %.0f" % round(elos[gt], 0)
285 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
286 ctx.move_to(self.elo_pos[0]+xoffset-xoff-tw/2, self.elo_pos[1]-yoff)
289 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
290 ctx.set_font_size(self.rank_fontsize)
291 ctx.set_source_rgb(self.rank_color[0], self.rank_color[1], self.rank_color[2])
292 txt = "Rank %d of %d" % ranks[gt]
293 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
294 ctx.move_to(self.rank_pos[0]+xoffset-xoff-tw/2, self.rank_pos[1]-yoff)
297 xoffset += self.gametype_width
300 # print win percentage
303 ctx.rectangle(self.wintext_pos[0]-self.wintext_width/2, self.wintext_pos[1]-self.wintext_fontsize/2+1,
304 self.wintext_width, self.wintext_fontsize+4)
305 ctx.set_source_rgba(self.wintext_bg[0], self.wintext_bg[1], self.wintext_bg[2], self.wintext_bg[3])
308 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
309 ctx.set_font_size(self.wintext_fontsize)
310 ctx.set_source_rgb(self.wintext_color[0], self.wintext_color[1], self.wintext_color[2])
311 txt = "Win Percentage"
312 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
313 ctx.move_to(self.wintext_pos[0]-xoff-tw/2, self.wintext_pos[1]-yoff)
316 wins, losses = total_stats["wins"], total_games-total_stats["wins"]
319 ratio = float(wins)/total_games
320 txt = "%.2f%%" % round(ratio * 100, 2)
323 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
324 ctx.set_font_size(self.winp_fontsize)
325 r = ratio*self.winp_colortop[0] + (1-ratio)*self.winp_colorbot[0]
326 g = ratio*self.winp_colortop[1] + (1-ratio)*self.winp_colorbot[1]
327 b = ratio*self.winp_colortop[2] + (1-ratio)*self.winp_colorbot[2]
328 ctx.set_source_rgb(r, g, b)
329 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
330 ctx.move_to(self.winp_pos[0]-xoff-tw/2, self.winp_pos[1]-yoff)
333 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
334 ctx.set_font_size(self.wins_fontsize)
335 ctx.set_source_rgb(self.wins_color[0], self.wins_color[1], self.wins_color[2])
336 txt = "%d win" % wins
339 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
340 ctx.move_to(self.wins_pos[0]-xoff-tw/2, self.wins_pos[1]-yoff)
343 ctx.set_font_size(self.loss_fontsize)
344 ctx.set_source_rgb(self.loss_color[0], self.loss_color[1], self.loss_color[2])
345 txt = "%d loss" % losses
348 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
349 ctx.move_to(self.loss_pos[0]-xoff-tw/2, self.loss_pos[1]-yoff)
353 # print kill/death ratio
356 ctx.rectangle(self.kdtext_pos[0]-self.kdtext_width/2, self.kdtext_pos[1]-self.kdtext_fontsize/2+1,
357 self.kdtext_width, self.kdtext_fontsize+4)
358 ctx.set_source_rgba(self.kdtext_bg[0], self.kdtext_bg[1], self.kdtext_bg[2], self.kdtext_bg[3])
361 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
362 ctx.set_font_size(self.kdtext_fontsize)
363 ctx.set_source_rgb(self.kdtext_color[0], self.kdtext_color[1], self.kdtext_color[2])
365 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
366 ctx.move_to(self.kdtext_pos[0]-xoff-tw/2, self.kdtext_pos[1]-yoff)
369 kills, deaths = total_stats['kills'] , total_stats['deaths']
372 ratio = float(kills)/deaths
373 txt = "%.3f" % round(ratio, 3)
377 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
378 ctx.set_font_size(self.kdr_fontsize)
382 r = nr*self.kdr_colortop[0] + (1-nr)*self.kdr_colorbot[0]
383 g = nr*self.kdr_colortop[1] + (1-nr)*self.kdr_colorbot[1]
384 b = nr*self.kdr_colortop[2] + (1-nr)*self.kdr_colorbot[2]
385 ctx.set_source_rgb(r, g, b)
386 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
387 ctx.move_to(self.kdr_pos[0]-xoff-tw/2, self.kdr_pos[1]-yoff)
390 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
391 ctx.set_font_size(self.kills_fontsize)
392 ctx.set_source_rgb(self.kills_color[0], self.kills_color[1], self.kills_color[2])
393 txt = "%d kill" % kills
396 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
397 ctx.move_to(self.kills_pos[0]-xoff-tw/2, self.kills_pos[1]+yoff)
400 ctx.set_font_size(self.deaths_fontsize)
401 ctx.set_source_rgb(self.deaths_color[0], self.deaths_color[1], self.deaths_color[2])
402 txt = "%d death" % deaths
405 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
406 ctx.move_to(self.deaths_pos[0]-xoff-tw/2, self.deaths_pos[1]+yoff)
413 ctx.rectangle( self.ptime_pos[0]-self.ptime_width/2, self.ptime_pos[1]-self.ptime_fontsize/2+1,
414 self.ptime_width, self.ptime_fontsize+4)
415 ctx.set_source_rgba(self.ptime_bg[0], self.ptime_bg[1], self.ptime_bg[2], self.ptime_bg[2])
418 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
419 ctx.set_font_size(self.ptime_fontsize)
420 ctx.set_source_rgb(self.ptime_color[0], self.ptime_color[1], self.ptime_color[2])
421 txt = "Playing time: %s" % str(total_stats['alivetime'])
422 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
423 ctx.move_to(self.ptime_pos[0]-xoff-tw/2, self.ptime_pos[1]-yoff)
428 surf.write_to_png(output_filename)
431 def get_data(self, player):
432 """Return player data as dict.
434 This function is similar to the function in player.py but more optimized
441 # duel/dm/tdm/ctf elo + rank
443 player_id = player.player_id
445 games_played = DBSession.query(
446 Game.game_type_cd, func.count(), func.sum(PlayerGameStat.alivetime)).\
447 filter(Game.game_id == PlayerGameStat.game_id).\
448 filter(PlayerGameStat.player_id == player_id).\
449 group_by(Game.game_type_cd).\
450 order_by(func.count().desc()).\
451 limit(3).all() # limit to 3 gametypes!
454 total_stats['games'] = 0
455 total_stats['games_breakdown'] = {} # this is a dictionary inside a dictionary .. dictception?
456 total_stats['games_alivetime'] = {}
457 total_stats['gametypes'] = []
458 for (game_type_cd, games, alivetime) in games_played:
459 total_stats['games'] += games
460 total_stats['gametypes'].append(game_type_cd)
461 total_stats['games_breakdown'][game_type_cd] = games
462 total_stats['games_alivetime'][game_type_cd] = alivetime
464 (total_stats['kills'], total_stats['deaths'], total_stats['alivetime'],) = DBSession.query(
465 func.sum(PlayerGameStat.kills),
466 func.sum(PlayerGameStat.deaths),
467 func.sum(PlayerGameStat.alivetime)).\
468 filter(PlayerGameStat.player_id == player_id).\
471 # (total_stats['wins'],) = DBSession.query(
473 # filter(Game.game_id == PlayerGameStat.game_id).\
474 # filter(PlayerGameStat.player_id == player_id).\
475 # filter(Game.winner == PlayerGameStat.team or PlayerGameStat.rank == 1).\
478 (total_stats['wins'],) = DBSession.\
479 query("total_wins").\
481 "select count(*) total_wins "
482 "from games g, player_game_stats pgs "
483 "where g.game_id = pgs.game_id "
484 "and player_id=:player_id "
485 "and (g.winner = pgs.team or pgs.rank = 1)"
486 ).params(player_id=player_id).one()
488 ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
490 "select pr.game_type_cd, pr.rank, overall.max_rank "
491 "from player_ranks pr, "
492 "(select game_type_cd, max(rank) max_rank "
494 "group by game_type_cd) overall "
495 "where pr.game_type_cd = overall.game_type_cd "
496 "and player_id = :player_id "
498 params(player_id=player_id).all()
501 for gtc,rank,max_rank in ranks:
502 ranks_dict[gtc] = (rank, max_rank)
504 elos = DBSession.query(PlayerElo).\
505 filter_by(player_id=player_id).\
506 order_by(PlayerElo.elo.desc()).\
512 elos_dict[elo.game_type_cd] = elo.elo
516 'total_stats':total_stats,