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
10 # similar to html_colors() from util.py
11 _contrast_threshold = 0.5
13 _dec_colors = [ (0.5,0.5,0.5),
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):
31 buf[pos:pos+4] = buf[pos+2] + buf[pos+1] + buf[pos+0] + buf[pos+3]
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))
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")
52 # player data, will be filled by get_data()
55 # skin parameters, can be overriden by init
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
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 ]",
73 'nostats_fontsize': 12,
74 'nostats_pos': (60,59),
75 'nostats_color': (0.8, 0.2, 0.2),
77 'nostats_text': "no stats yet!",
80 'elo_color': (1.0, 1.0, 0.5),
81 'elo_text': "Elo %.0f",
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),
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",
94 'winp_colortop': (0.2, 1.0, 1.0),
95 'winp_colorbot': (1.0, 1.0, 0.2),
98 'wins_color': (0.6, 0.8, 0.8),
100 'loss_pos': (508,43),
101 'loss_color': (0.8, 0.8, 0.6),
102 'kdtext_fontsize': 10,
103 'kdtext_pos': (390,3),
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",
110 'kdr_colortop': (0.2, 1.0, 0.2),
111 'kdr_colorbot': (1.0, 0.2, 0.2),
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),
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",
126 def __init__(self, **params):
127 for k,v in params.items():
128 if self.params.has_key(k):
131 def __getattr__(self, key):
132 if self.params.has_key(key):
133 return self.params[key]
136 def render_image(self, output_filename):
137 """Render an image for the given player id."""
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"]
154 surf = C.ImageSurface(C.FORMAT_ARGB32, self.width, self.height)
155 ctx = C.Context(surf)
156 ctx.set_antialias(C.ANTIALIAS_GRAY)
160 ctx.set_operator(C.OPERATOR_SOURCE)
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])
170 bg = C.ImageSurface.create_from_png("img/%s.png" % self.bg)
174 bg_w, bg_h = bg.get_width(), bg.get_height()
176 while bg_xoff < self.width:
178 while bg_yoff < self.height:
179 ctx.set_source_surface(bg, bg_xoff, bg_yoff)
180 #ctx.mask_surface(bg)
186 #print "Error: Can't load background texture: %s" % self.bg
190 # draw overlay graphic
191 if self.overlay != None:
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)
198 #print "Error: Can't load overlay texture: %s" % self.overlay
202 ## draw player's nickname with fancy colors
204 # deocde nick, strip all weird-looking characters
205 qstr = qfont_decode(player.nick).replace('^^', '^').replace(u'\x00', '')
208 # replace weird characters that make problems - TODO
211 qstr = ''.join(chars)
212 stripped_nick = strip_colors(qstr.replace(' ', '_'))
214 # fontsize is reduced if width gets too large
215 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
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:
225 # determine width of single whitespace for later use
226 xoff, yoff, tw, th = ctx.text_extents("_")[:4]
229 # split nick into colored segments
231 _all_colors = re.compile(r'(\^\d|\^x[\dA-Fa-f]{3})')
232 parts = _all_colors.split(qstr)
233 while len(parts) > 0:
236 if _all_colors.match(txt):
237 tag = txt[1:] # strip leading '^'
244 if not txt or len(txt) == 0:
245 # only colorcode and no real text, skip this
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)
258 r,g,b = _dec_colors[int(tag[0])]
260 r,g,b = _dec_colors[7]
262 ctx.set_source_rgb(r, g, b)
263 ctx.move_to(self.nick_pos[0] + xoffset, self.nick_pos[1])
266 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
267 tw += (len(txt)-len(txt.strip())) * space_w # account for lost whitespaces
270 ## print elos and ranks
272 # show up to three gametypes the player has participated in
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)
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)
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)
296 ctx.set_antialias(old_aa)
298 if not elos.has_key(gt) or not ranks.has_key(gt):
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)
307 ctx.rotate(math.radians(self.nostats_angle))
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)
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)
328 xoffset += self.gametype_width
331 # print win percentage
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])
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)
348 wins, losses = total_stats["wins"], total_games-total_stats["wins"]
351 ratio = float(wins)/total_games
352 txt = "%.2f%%" % round(ratio * 100, 2)
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)
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
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)
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
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)
389 # print kill/death ratio
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])
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)
406 kills, deaths = total_stats['kills'] , total_stats['deaths']
409 ratio = float(kills)/deaths
410 txt = "%.3f" % round(ratio, 3)
415 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
416 ctx.set_font_size(self.kdr_fontsize)
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)
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
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)
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
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)
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])
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)
470 #surf.write_to_png(output_filename)
472 imgdata = surf.get_data()
473 writepng(output_filename, imgdata, self.width, self.height)
476 def get_data(self, player):
477 """Return player data as dict.
479 This function is similar to the function in player.py but more optimized
486 # duel/dm/tdm/ctf elo + rank
488 player_id = player.player_id
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!
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
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).\
516 # (total_stats['wins'],) = DBSession.query(
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).\
523 (total_stats['wins'],) = DBSession.\
524 query("total_wins").\
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()
533 ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
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 "
539 "group by game_type_cd) overall "
540 "where pr.game_type_cd = overall.game_type_cd "
541 "and player_id = :player_id "
543 params(player_id=player_id).all()
546 for gtc,rank,max_rank in ranks:
547 ranks_dict[gtc] = (rank, max_rank)
549 elos = DBSession.query(PlayerElo).\
550 filter_by(player_id=player_id).\
551 order_by(PlayerElo.elo.desc()).\
557 elos_dict[elo.game_type_cd] = elo.elo
561 'total_stats':total_stats,