Implement a simple priority system.
[ccbs] / bigscreen / groupscreen.cpp
1 #include <cstdio>
2 #include <algorithm>
3 #include <map>
4
5 #include "groupscreen.h"
6 #include "fetch_group.h"
7 #include "fetch_max_score_for_songs.h"
8 #include "fetch_max_score_for_players.h"
9 #include "fetch_needs_update.h"
10 #include "fetch_highscore.h"
11 #include "fonts.h"
12
13 GroupScreen::GroupScreen(pqxx::connection &conn, unsigned tournament, unsigned round, unsigned parallel, unsigned machine, unsigned num_machines)
14         : tournament(tournament), round(round), parallel(parallel), machine(machine), num_machines(num_machines), scores_changed(conn, "scores"), conn(conn), valid(false)
15 {
16 }
17
18 GroupScreen::~GroupScreen()
19 {
20 }
21
22 bool GroupScreen::check_invalidated()
23 {
24         if (!valid)
25                 return true;
26         if (!scores_changed.get_flag())
27                 return false;
28
29         bool needs_update;
30         conn.perform(FetchNeedsUpdate(last_updated, tournament, round, parallel, &needs_update));
31
32         if (!needs_update)
33                 scores_changed.reset_flag();
34         
35         return needs_update;
36 }
37
38 void GroupScreen::draw(unsigned char *buf)
39 {
40         std::vector<TextDefer> td;
41         
42         scores_changed.reset_flag();
43
44         /*
45          * We'll probably need some values from here later on (although not all), just fetch them
46          * all while we're at it.
47          */
48         std::map<unsigned, unsigned> song_scores, player_scores;
49         conn.perform(FetchMaxScoreForSongs(tournament, &song_scores));
50         conn.perform(FetchMaxScoreForPlayers(tournament, round, &player_scores));
51         
52         Group group;
53         conn.perform(FetchGroup(tournament, round, parallel, &group));
54         gettimeofday(&last_updated, NULL);
55
56         memset(buf, 0, 800 * 600 * 4);
57
58         // main heading
59         char heading[64];
60         if (num_machines == 1) {
61                 if (parallel == 0) {
62                         std::sprintf(heading, "Round %u", round);
63                 } else {
64                         std::sprintf(heading, "Round %u, Group %u", round, parallel);
65                 }
66         } else {
67                 if (parallel == 0) {
68                         std::sprintf(heading, "Round %u, Machine %u", round, machine + 1);
69                 } else {
70                         std::sprintf(heading, "Round %u, Group %u, Machine %u", round, parallel, machine + 1);
71                 }
72         }
73
74         {
75                 unsigned width = my_draw_text(heading, NULL, 40.0);
76                 my_draw_text_deferred(td, heading, 40.0, 800/2 - width/2, 60);
77         }
78         
79         // Find out how wide each column has to be. First try unlimited width (ie.
80         // long titles for everything); if that gets too long, try again with short
81         // titles for chosen songs.
82         unsigned width[16], num_scores;
83         unsigned max_num_width = my_draw_text("8888", NULL, 22.0);
84         unsigned sumwidth;
85         for (unsigned mode = 0; mode < 2; ++mode) {
86                 for (unsigned i = 0; i < 16; ++i)
87                         width[i] = 0;
88
89                 for (std::vector<Player>::const_iterator i = group.players.begin(); i != group.players.end(); ++i) {
90                         unsigned col = 1;
91                         width[0] = std::max(width[0], my_draw_text(i->nick, NULL, 18.0));
92
93                         for (std::vector<Score>::const_iterator j = i->scores.begin(); j != i->scores.end(); ++j, ++col) {
94                                 if (j->chosen) {
95                                         width[col] = std::max(width[col], my_draw_text((mode == 0) ? j->song.title : j->song.short_title, NULL, 12.0) + 
96                                                         max_num_width + 10);
97                                 } else {                
98                                         width[col] = std::max(width[col], my_draw_text(j->song.short_title, NULL, 12.0));
99                                         width[col] = std::max(width[col], max_num_width);
100                                 }
101                         }
102                 }
103
104                 num_scores = group.players[0].scores.size();
105
106                 width[num_scores + 1] = std::max(my_draw_text("Total", NULL, 12.0), max_num_width);
107                 width[num_scores + 2] = my_draw_text("Rank", NULL, 12.0);
108
109                 // if we're at long titles and that works, don't try the short ones
110                 sumwidth = 0;
111                         
112                 for (unsigned i = 0; i <= num_scores + 2; ++i)
113                         sumwidth += width[i] + 20;
114                         
115                 if (sumwidth < 780)
116                         break;
117         }
118
119         /* 
120          * If we have space to go, distribute as much as we can to the chosen song column, so we won't have
121          * total and rank jumping around.
122          */
123         if (sumwidth < 780) {
124                 int first_chosen_col = -1;
125                 unsigned col = 1;
126
127                 for (std::vector<Score>::const_iterator i = group.players[0].scores.begin(); i != group.players[0].scores.end(); ++i, ++col) {
128                         if (i->chosen) {
129                                 first_chosen_col = col;
130                                 break;
131                         }
132                 }
133
134                 if (first_chosen_col != -1) {
135                         width[first_chosen_col] += 780 - sumwidth;
136                 }
137         }
138
139         // make column headings from the first player's songs
140         unsigned col = 1;
141         unsigned x = 40 + width[0];
142         for (std::vector<Score>::const_iterator i = group.players[0].scores.begin(); i != group.players[0].scores.end(); ++i, ++col) {
143                 if (!i->chosen) {
144                         unsigned this_width = my_draw_text(i->song.short_title, NULL, 12.0);
145                         my_draw_text_deferred(td, i->song.short_title, 12.0, x + width[col] / 2 - this_width / 2, 100);
146                 }
147                 x += width[col] + 20;
148         }
149
150         my_draw_text_deferred(td, "Total", 12.0, x + width[num_scores + 1] / 2 - my_draw_text("Total", NULL, 12.0) / 2, 100);
151         x += width[num_scores + 1] + 20;
152         my_draw_text_deferred(td, "Rank", 12.0, x + width[num_scores + 2] / 2 - my_draw_text("Rank", NULL, 12.0) / 2, 100);
153         
154         // show all the players and the scores
155         unsigned num_players_this_machine = (group.players.size() + num_machines - machine - 1) / num_machines;
156         unsigned show_players = std::min(num_players_this_machine, 9U);
157         unsigned y = (show_players <= 7) ? 140 : (140 - (show_players - 7) * 5);
158         
159         unsigned row = 0, m = 0;
160         for (std::vector<Player>::const_iterator i = group.players.begin(); i != group.players.end() && row < 9; ++i) {
161                 if (m++ % num_machines != machine)
162                         continue;
163
164                 my_draw_text_deferred(td, i->nick, 18.0, 20, y);
165
166                 unsigned x = 40 + width[0];
167
168                 unsigned col = 1;
169                 for (std::vector<Score>::const_iterator j = i->scores.begin(); j != i->scores.end(); ++j, ++col) {
170                         char text[16] = "";
171                         if (j->score != -1) {
172                                 std::sprintf(text, "%u", j->score);
173                         }
174         
175                         unsigned this_width = my_draw_text(text, NULL, 22.0);
176                         if (j->chosen) {
177                                 my_draw_text_deferred(td, text, 22.0, x + max_num_width - this_width, y);
178
179                                 // draw the long name if we can, otherwise use the short one
180                                 if (my_draw_text(j->song.title, NULL, 12.0) > (width[col] - 10 - max_num_width)) {
181                                         my_draw_text_deferred(td, j->song.short_title, 12.0, x + max_num_width + 10, y);
182                                 } else {
183                                         my_draw_text_deferred(td, j->song.title, 12.0, x + max_num_width + 10, y);
184                                 }
185                         } else {
186                                 my_draw_text_deferred(td, text, 22.0, x + width[col] / 2 - this_width / 2, y);
187                         }
188                         x += width[col] + 20;
189                 }
190
191                 // draw total
192                 {
193                         char text[16];
194                         std::sprintf(text, "%u", i->total);
195                         
196                         unsigned this_width = my_draw_text(text, NULL, 22.0);
197                         my_draw_text_deferred(td, text, 22.0, x + width[num_scores + 1] / 2 - this_width / 2, y);
198                         x += width[num_scores + 1] + 20;
199                 }
200
201                 if (show_players > 7)
202                         y += 40 - (show_players - 7) * 4;
203                 else 
204                         y += 40;
205                 ++row;
206                 
207         }
208         
209         /*
210          * Approximate (but probably working quite well in practice) heuristic
211          * for finding the min and max rank of a player works as follows:
212          *
213          * First of all, find out, for each player in the group, what the
214          * maximum remaining score possibly can be (the minimum score is of
215          * course identical to the player's current total). For a random song,
216          * this is of course 1000 * (maximum feet rating) (but of course, that
217          * depends on whether we can play single or double! for now, assume
218          * double is okay, but this logic will be deferred to FetchMaxScore
219          * anyhow); for a random song, we simply pick the highest-ranking song
220          * we can find, EXCEPT those the player has chosen earlier AND the
221          * random songs this round, AND all random songs from elimination rounds
222          * (ie. rounds with only one group). (Phew!) This doesn't solve problems
223          * we'd face with more than one chosen song, but it should be good enough.
224          *
225          * After we've found the max and min scores for all players, it's a simple
226          * matter of sorting; the best attainable rank for player X is obtained if 
227          * X gets max score and all others get min score, the worst attainable rank
228          * is obtained if X gets min score and all others get max score.
229          */
230         std::vector<unsigned> max_score, min_score;
231         for (std::vector<Player>::const_iterator i = group.players.begin(); i != group.players.end(); ++i) {
232                 unsigned min_score_tp = 0, max_score_tp = 0;
233                 for (std::vector<Score>::const_iterator j = i->scores.begin(); j != i->scores.end(); ++j, ++col) {
234                         if (j->score != -1) {
235                                 // already given
236                                 min_score_tp += j->score;
237                                 max_score_tp += j->score;
238                         } else {
239                                 unsigned max_score_this_song;
240                                 if (j->song.id != -1) {
241                                         // random song, or we know what song the player picked
242                                         max_score_this_song = song_scores[j->song.id];
243                                 } else {
244                                         max_score_this_song = player_scores[i->id];
245                                 }
246                                 max_score_tp += max_score_this_song;
247                         }
248                 }
249                 max_score.push_back(max_score_tp);
250                 min_score.push_back(min_score_tp);
251         }
252
253         // now finally find min and max rank, and draw it all
254         y = (show_players <= 7) ? 140 : (140 - (show_players - 7) * 5);
255         for (unsigned i = 0; i < group.players.size() && (i/num_machines) < show_players; ++i) {
256                 unsigned best_rank = 1, worst_rank = 1;
257                 for (unsigned j = 0; j < group.players.size(); ++j) {
258                         if (i == j)
259                                 continue;
260
261                         if (max_score[i] < min_score[j])
262                                 ++best_rank;
263                         if (min_score[i] <= max_score[j])
264                                 ++worst_rank;
265                 }
266
267                 char text[16];
268                 if (best_rank == worst_rank)
269                         std::sprintf(text, "%u", best_rank);
270                 else
271                         std::sprintf(text, "%u-%u", best_rank, worst_rank);
272                 
273                 if (i % num_machines != machine)
274                         continue;
275                 
276                 unsigned this_width = my_draw_text(text, NULL, 22.0);
277                 my_draw_text_deferred(td, text, 22.0, x + width[num_scores + 2] / 2 - this_width / 2, y);
278
279                 if (show_players > 7)
280                         y += 40 - (show_players - 7) * 4;
281                 else 
282                         y += 40;
283         }
284                 
285         /*
286          * Next up (at the bottom) is "who's playing, what will he/she be playing, and
287          * optionally, how much to lead/win and how much to secure qualification" (the
288          * last one only in the final round). We assume playing is done in a modified
289          * zigzag; all the random songs are played first in zigzag/wrapping order (player
290          * 1 song 1, player 2 song 2, player 3 song 3, player 1 song 2, player 2 song 3,
291          * player 3 song 1, etc... assuming three songs and three players) and then all
292          * the chosen songs are played (we assume only one chosen song).
293          *
294          * The lines are as follows:
295          *
296          * <player>
297          * <song>
298          * High score: <hs> by <hsplayer> at <hsevent>
299          * Needs to lead: <leadscore>
300          * Needs to secure qualification: <qualscore>
301          * Needs to win group: <winscore>
302          */
303         
304         /* Find the first player with the fewest songs played and part of this machine. */
305         unsigned min_played_songs = 9999, num_random_songs = 0;
306         Player *next_player = NULL;
307         m = 0;
308         for (std::vector<Player>::iterator i = group.players.begin(); i != group.players.end(); ++i) {
309                 unsigned this_played = 0, this_random_songs = 0;
310                 for (std::vector<Score>::const_iterator j = i->scores.begin(); j != i->scores.end(); ++j, ++col) {
311                         if (j->score != -1)
312                                 ++this_played;
313                         if (!j->chosen)
314                                 ++this_random_songs;
315                 }
316
317                 if ((m++ % num_machines == machine) && this_played < min_played_songs) {
318                         min_played_songs = this_played;
319                         next_player = &(*i);
320                         num_random_songs = this_random_songs;  // should be equal for all
321                 }
322         }
323
324         /* Find out what song this player is supposed to play next; try random songs first */ 
325         Score *next_song = NULL;
326
327         for (unsigned i = 0; i < num_random_songs; ++i) {
328                 unsigned j = (i + next_player->position - 1) % num_random_songs;
329                 if (next_player->scores[j].score == -1) {
330                         next_song = &(next_player->scores[j]);
331                         break;
332                 }
333         }
334
335         // then all songs, if that didn't work out (slightly icky, but hey)
336         if (next_song == NULL) {
337                 for (unsigned i = 0; i < num_scores; ++i) {
338                         unsigned j = (i + next_player->position) % num_scores;
339                         if (next_player->scores[j].score == -1) {
340                                 next_song = &(next_player->scores[j]);
341                                 break;
342                         }
343                 }
344         }
345
346         if (next_song != NULL) {
347                 widestring text = widestring("Next player: ") + next_player->nick;
348                 unsigned this_width = my_draw_text(text, NULL, 24.0);
349                 my_draw_text(text, buf, 24.0, 400 - this_width/2, 420);
350
351                 if (next_song->song.id != -1) {
352                         this_width = my_draw_text(next_song->song.title, NULL, 20.0);
353                         my_draw_text(next_song->song.title, buf, 20.0, 400 - this_width/2, 457);
354
355                         Highscore hs;
356                         conn.perform(FetchHighscore(next_song->song.id, &hs));
357                         
358                         if (hs.score != -1) {
359                                 text = widestring("High score: ") + widestring(pqxx::to_string(hs.score)) +
360                                         widestring(", by ") + hs.nick + widestring(" in ") + hs.tournament_name;
361                                 this_width = my_draw_text(text, NULL, 16.0);
362                                 my_draw_text(text, buf, 16.0, 400 - this_width/2, 487);
363                         }
364                 }
365
366                 // only show lead/win/qualify for the last song
367                 if (min_played_songs == num_scores - 1) {
368                         /*
369                          * Find out how much we need to lead, how much we need to be guaranteed
370                          * to win the group, and how much we need to secure qualification. (FIXME:
371                          * do the last one :-) )
372                          */
373                         
374                         // find the best score we can get
375                         unsigned max_score_this_song;
376                         if (next_song->song.id != -1) {
377                                 // random song, or we know what song the player picked
378                                 max_score_this_song = song_scores[next_song->song.id];
379                         } else {
380                                 max_score_this_song = player_scores[next_player->id];
381                         }
382
383                         unsigned y = 520;
384                         
385                         // see what score this player must beat to lead
386                         unsigned lead_beat = 0, win_beat = 0;
387                         for (unsigned i = 0; i < group.players.size(); ++i) {
388                                 if (group.players[i].id == next_player->id)
389                                         continue;
390                                 
391                                 lead_beat = std::max(lead_beat, group.players[i].total);
392                         }
393
394                         // find the best max score among the others
395                         for (unsigned i = 0; i < group.players.size(); ++i) {
396                                 if (group.players[i].id == next_player->id)
397                                         continue;
398
399                                 win_beat = std::max(win_beat, max_score[i]);
400                         }
401
402                         /*
403                          * There's a somewhat subtle point here. Normally, what a player would be interested in
404                          * with regard to qualification would be a set of three values:
405                          *
406                          * 1. How much is the absolute minimum required to qualify, given that all others
407                          *    fail?
408                          * 2. How much will give a reasonable chance of qualifying, given the expected performance
409                          *    of all the others?
410                          * 3. How much will be enough to secure qualification, no matter what?
411                          *
412                          * Given perfect guessing, #2 would be "how much is needed to qualify"; however, it is
413                          * completely impossible to give an exact value for that, and we're not into the guessing
414                          * games. :-) #1 is often so low it's completely unrealistic (ie. far enough from #2 that
415                          * it's not interesting), but #3, the most conservative estimate, is often a good measure.
416                          * #3 is "how much is needed to _secure_ qualification", and that is usually what we
417                          * print out when it's possible.
418                          *
419                          * However, in a few situations, #1 and #3 will be the exact same value, from which it
420                          * follows (from the squeeze law, or just common sense :-) ) that #2 will be the same
421                          * value as #1 and #3. (This usually happens near or at the end of a group.) In that
422                          * case, we know the value we seek (ie. "how much is needed to qualify"), so we drop
423                          * the word "secure" and just print it as-is.
424                          *
425                          * To find #1 and #3, we sort and pick out the values we need to beat in the best and
426                          * the worst case.
427                          */
428                         int qualify_beat_worst_case = -1, qualify_beat_best_case = -1;
429
430                         if (group.num_qualifying > 0) {
431                                 std::vector<unsigned> tmp;
432                                 
433                                 for (unsigned i = 0; i < group.players.size(); ++i) {
434                                         if (group.players[i].id == next_player->id)
435                                                 continue;
436                                         tmp.push_back(max_score[i]);
437                                 }
438                                 std::sort(tmp.begin(), tmp.end());
439                                 qualify_beat_worst_case = tmp[tmp.size() - group.num_qualifying];
440                                 
441                                 std::vector<unsigned> tmp2;
442                                 for (unsigned i = 0; i < group.players.size(); ++i) {
443                                         if (group.players[i].id == next_player->id)
444                                                 continue;
445                                         tmp2.push_back(min_score[i]);
446                                 }
447
448                                 std::sort(tmp2.begin(), tmp2.end());
449                                 qualify_beat_best_case = tmp2[tmp2.size() - group.num_qualifying];
450                         }
451                         
452                         // print out the lines we can attain
453                         if (next_player->total + max_score_this_song > lead_beat && (lead_beat != win_beat)) {
454                                 int lead_need = std::max(lead_beat - next_player->total + 1, 0U);
455                         
456                                 if (lead_need > 0) {
457                                         text = widestring("Needs to lead: ") + widestring(pqxx::to_string(lead_need));
458                                         this_width = my_draw_text(text, NULL, 18.0);
459                                         my_draw_text(text, buf, 18.0, 400 - this_width/2, y);
460
461                                         y += 30;
462                                 }
463                         }
464                         
465                         if (next_player->total + max_score_this_song > win_beat) {
466                                 int win_need = std::max(win_beat - next_player->total + 1, 0U);
467                                 
468                                 if (win_need > 0) {
469                                         text = widestring("Needs to win: ") + widestring(pqxx::to_string(win_need));
470
471                                         this_width = my_draw_text(text, NULL, 18.0);
472                                         my_draw_text(text, buf, 18.0, 400 - this_width/2, y);
473
474                                         y += 30;
475                                 }
476                         }
477
478                         if (group.num_qualifying > 0 &&
479                             next_player->total + max_score_this_song > unsigned(qualify_beat_worst_case) &&
480                             (unsigned(qualify_beat_worst_case) != win_beat)) {
481                                 int qual_need = std::max(qualify_beat_worst_case - next_player->total + 1, 0U);
482                                 
483                                 if (qual_need > 0) {
484                                         if (qualify_beat_worst_case == qualify_beat_best_case) {
485                                                 text = widestring("Needs to qualify: ") + widestring(pqxx::to_string(qual_need));
486                                         } else {
487                                                 text = widestring("Needs to secure qualification: ") + widestring(pqxx::to_string(qual_need));
488                                         }
489                                         
490                                         this_width = my_draw_text(text, NULL, 18.0);
491                                         my_draw_text(text, buf, 18.0, 400 - this_width/2, y);
492                                 
493                                         y += 30;
494                                 }
495                         }
496                 }
497         }
498         
499         valid = true;
500         draw_all_deferred_text(buf, td, last_text);
501         last_text = td;
502 }
503
504 int GroupScreen::get_priority()
505 {
506         return 10;
507 }