]> git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/scores.qc
Change server's player sorting algorithm to work as the scoreboard's one, so it doesn...
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / scores.qc
1 #include "scores.qh"
2
3 #include <common/mapinfo.qh>
4 #include <common/mutators/base.qh>
5 #include <common/net_linked.qh>
6 #include <common/playerstats.qh>
7 #include <common/scores.qh>
8 #include <common/state.qh>
9 #include <common/stats.qh>
10 #include <common/teams.qh>
11 #include <common/weapons/_all.qh>
12 #include <server/client.qh>
13 #include <server/command/common.qh>
14 #include <server/intermission.qh>
15 #include <server/mutators/_mod.qh>
16 #include <server/round_handler.qh>
17 #include <server/world.qh>
18
19 .entity scorekeeper;
20 entity teamscorekeepers[16];
21 float teamscores_entities_count;
22 var .float scores_primary;
23 var .float teamscores_primary;
24 float scores_flags_primary;
25 float teamscores_flags_primary;
26 var .float scores_secondary;
27 float scores_flags_secondary;
28
29 vector ScoreField_Compare(entity t1, entity t2, .float field, float fieldflags, vector previous, bool strict) // returns: cmp value, best prio
30 {
31         if(fieldflags & SFL_NOT_SORTABLE) // column does not sort
32                 return previous;
33         if(!strict && !(fieldflags & SFL_SORT_PRIO_MASK)) // column does not sort
34                 return previous;
35         if((fieldflags & SFL_SORT_PRIO_MASK) < previous.y)
36                 return previous;
37         if (t1.(field) == t2.(field))
38                 return previous;
39
40         previous.y = fieldflags & SFL_SORT_PRIO_MASK;
41
42         if(fieldflags & SFL_ZERO_IS_WORST)
43         {
44                 if (t1.(field) == 0)
45                 {
46                         previous.x = -1;
47                         return previous;
48                 }
49                 else if (t2.(field) == 0)
50                 {
51                         previous.x = +1;
52                         return previous;
53                 }
54         }
55
56         if (fieldflags & SFL_LOWER_IS_BETTER)
57                 previous.x = (t2.(field) - t1.(field));
58         else
59                 previous.x = (t1.(field) - t2.(field));
60
61         return previous;
62 }
63
64 /*
65  * teamscore entities
66  */
67
68 bool TeamScore_SendEntity(entity this, entity to, float sendflags)
69 {
70         float i, longflags;
71
72         WriteHeader(MSG_ENTITY, ENT_CLIENT_TEAMSCORES);
73         int t = this.team - 1;
74         assert(t, eprint(this));
75         WriteByte(MSG_ENTITY, t);
76
77         longflags = 0;
78         for(i = 0; i < MAX_TEAMSCORE; ++i)
79                 if(this.(teamscores(i)) > 127 || this.(teamscores(i)) <= -128)
80                         longflags |= BIT(i);
81
82 #if MAX_TEAMSCORE <= 8
83         WriteByte(MSG_ENTITY, sendflags);
84         WriteByte(MSG_ENTITY, longflags);
85 #else
86         WriteShort(MSG_ENTITY, sendflags);
87         WriteShort(MSG_ENTITY, longflags);
88 #endif
89         for(i = 0; i < MAX_TEAMSCORE; ++i)
90                 if(sendflags & BIT(i))
91                 {
92                         if(longflags & BIT(i))
93                                 WriteInt24_t(MSG_ENTITY, this.(teamscores(i)));
94                         else
95                                 WriteChar(MSG_ENTITY, this.(teamscores(i)));
96                 }
97
98         return true;
99 }
100
101 void TeamScore_Spawn(float t, string name)
102 {
103         entity ts = new_pure(csqc_score_team);
104         ts.netname = name; // not used yet, FIXME
105         ts.team = t;
106         Net_LinkEntity(ts, false, 0, TeamScore_SendEntity);
107         teamscorekeepers[t - 1] = ts;
108         ++teamscores_entities_count;
109         PlayerStats_GameReport_AddTeam(t);
110 }
111
112 float TeamScore_AddToTeam(int t, float scorefield, float score)
113 {
114         entity s;
115
116         if(game_stopped)
117         {
118                 score = 0;
119         }
120
121         if(!scores_initialized) return 0; // FIXME remove this when everything uses this system
122         if(t <= 0 || t >= 16)
123         {
124                 if(game_stopped)
125                         return 0;
126                 error("Adding score to invalid team!");
127         }
128         s = teamscorekeepers[t - 1];
129         if(!s)
130         {
131                 if(game_stopped)
132                         return 0;
133                 error("Adding score to unknown team!");
134         }
135         if(score)
136                 if(teamscores_label(scorefield) != "")
137                         s.SendFlags |= BIT(scorefield);
138         return (s.(teamscores(scorefield)) += score);
139 }
140
141 float TeamScore_Add(entity player, float scorefield, float score)
142 {
143         return TeamScore_AddToTeam(player.team, scorefield, score);
144 }
145
146 float TeamScore_Compare(entity t1, entity t2, bool strict)
147 {
148         if(!t1 || !t2) return (!t2) - !t1;
149
150         // supporting MAX_TEAMSCORE > 2 requires keeping track of primary and secondary teamscore
151         if (MAX_TEAMSCORE > 2)
152                 error("MAX_TEAMSCORE > 2 not supported");
153
154         // first compare primary, then others (don't check secondary flag since there are only 2 teamscores)
155         vector result = '0 0 0';
156         int i = boolean(teamscores_primary && teamscores_primary == teamscores(1));
157         result = ScoreField_Compare(t1, t2, teamscores(i), teamscores_flags(i), result, strict);
158         if (result.x == 0)
159         {
160                 i = (i + 1) % MAX_TEAMSCORE;
161                 result = ScoreField_Compare(t1, t2, teamscores(i), teamscores_flags(i), result, strict);
162         }
163
164         if (result.x == 0 && strict)
165                 result.x = t1.team - t2.team;
166
167         return result.x;
168 }
169
170 /*
171  * the scoreinfo entity
172  */
173
174 void ScoreInfo_SetLabel_PlayerScore(PlayerScoreField i, string label, float scoreflags)
175 {
176         scores_label(i) = label;
177         scores_flags(i) = scoreflags;
178         if((scoreflags & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_PRIMARY)
179         {
180                 scores_primary = scores(i);
181                 scores_flags_primary = scoreflags;
182         }
183         else if((scoreflags & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_SECONDARY)
184         {
185                 scores_secondary = scores(i);
186                 scores_flags_secondary = scoreflags;
187         }
188         if(label != "")
189         {
190                 PlayerStats_GameReport_AddEvent(strcat(PLAYERSTATS_TOTAL, label));
191                 PlayerStats_GameReport_AddEvent(strcat(PLAYERSTATS_SCOREBOARD, label));
192         }
193 }
194
195 void ScoreInfo_SetLabel_TeamScore(float i, string label, float scoreflags)
196 {
197         teamscores_label(i) = label;
198         teamscores_flags(i) = scoreflags;
199         if((scoreflags & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_PRIMARY)
200         {
201                 teamscores_primary = teamscores(i);
202                 teamscores_flags_primary = scoreflags;
203         }
204         if(label != "")
205         {
206                 PlayerStats_GameReport_AddEvent(strcat(PLAYERSTATS_TOTAL, label));
207                 PlayerStats_GameReport_AddEvent(strcat(PLAYERSTATS_SCOREBOARD, label));
208         }
209 }
210
211 bool ScoreInfo_SendEntity(entity this, entity to, int sf)
212 {
213         float i;
214         WriteHeader(MSG_ENTITY, ENT_CLIENT_SCORES_INFO);
215         WriteRegistered(Gametypes, MSG_ENTITY, MapInfo_LoadedGametype);
216         FOREACH(Scores, true, {
217                 WriteString(MSG_ENTITY, scores_label(it));
218                 WriteByte(MSG_ENTITY, scores_flags(it));
219         });
220         for(i = 0; i < MAX_TEAMSCORE; ++i)
221         {
222                 WriteString(MSG_ENTITY, teamscores_label(i));
223                 WriteByte(MSG_ENTITY, teamscores_flags(i));
224         }
225         // prevent sending the welcome message again when score types are sent again because the scoring system has changed
226         // it can happen in some game modes like Race when the qualyfing session ends and the race starts
227         bool welcome_msg_too = (!CS(to) || time < CS(to).jointime + 5);
228         WriteByte(MSG_ENTITY, welcome_msg_too);
229         // welcome message is sent here because it needs to know the gametype
230         if (welcome_msg_too)
231                 SendWelcomemessage_msg_type(to, false, MSG_ENTITY);
232         return true;
233 }
234
235 void ScoreInfo_Init(int teams)
236 {
237         if(scores_initialized)
238         {
239                 scores_initialized.SendFlags |= 1; // force a resend
240         }
241         else
242         {
243                 scores_initialized = new_pure(ent_client_scoreinfo);
244                 Net_LinkEntity(scores_initialized, false, 0, ScoreInfo_SendEntity);
245         }
246         if(teams & BIT(0))
247                 TeamScore_Spawn(NUM_TEAM_1, "Red");
248         if(teams & BIT(1))
249                 TeamScore_Spawn(NUM_TEAM_2, "Blue");
250         if(teams & BIT(2))
251                 TeamScore_Spawn(NUM_TEAM_3, "Yellow");
252         if(teams & BIT(3))
253                 TeamScore_Spawn(NUM_TEAM_4, "Pink");
254 }
255
256 /*
257  * per-player score entities
258  */
259
260 bool PlayerScore_SendEntity(entity this, entity to, float sendflags)
261 {
262         WriteHeader(MSG_ENTITY, ENT_CLIENT_SCORES);
263         WriteByte(MSG_ENTITY, etof(this.owner));
264
265         int longflags = 0;
266         FOREACH(Scores, true, {
267             int p = 1 << (i % 16);
268                 if (this.(scores(it)) > 127 || this.(scores(it)) <= -128)
269                         longflags |= p;
270     });
271
272         WriteShort(MSG_ENTITY, sendflags);
273         WriteShort(MSG_ENTITY, longflags);
274         FOREACH(Scores, true, {
275             int p = 1 << (i % 16);
276                 if (sendflags & p)
277                 {
278                         if(longflags & p)
279                                 WriteInt24_t(MSG_ENTITY, this.(scores(it)));
280                         else
281                                 WriteChar(MSG_ENTITY, this.(scores(it)));
282                 }
283     });
284
285         return true;
286 }
287
288 float PlayerScore_Clear(entity player)
289 {
290         entity sk;
291
292         if(teamscores_entities_count)
293                 return 0;
294
295         if(MUTATOR_CALLHOOK(ForbidPlayerScore_Clear)) return 0;
296
297         sk = CS(player).scorekeeper;
298         FOREACH(Scores, true, {
299                 if(sk.(scores(it)) != 0)
300                         if(scores_label(it) != "")
301                                 sk.SendFlags |= BIT(i % 16);
302                 if(i != SP_ELO.m_id)
303                         sk.(scores(it)) = 0;
304         });
305
306         return 1;
307 }
308
309 void Score_ClearAll()
310 {
311         entity sk;
312         float t;
313         FOREACH_CLIENTSLOT(true, {
314                 sk = CS(it).scorekeeper;
315                 if (!sk) continue;
316                 FOREACH(Scores, true, {
317                         if(sk.(scores(it)) != 0)
318                                 if(scores_label(it) != "")
319                                         sk.SendFlags |= BIT(i % 16);
320                         if(i != SP_ELO.m_id)
321                                 sk.(scores(it)) = 0;
322                 });
323         });
324         for(t = 0; t < 16; ++t)
325         {
326                 sk = teamscorekeepers[t];
327                 if(!sk)
328                         continue;
329                 for(int j = 0; j < MAX_TEAMSCORE; ++j)
330                 {
331                         if(sk.(teamscores(j)) != 0)
332                                 if(teamscores_label(j) != "")
333                                         sk.SendFlags |= BIT(j);
334                         sk.(teamscores(j)) = 0;
335                 }
336         }
337 }
338
339 void PlayerScore_Attach(entity player)
340 {
341         if(CS(player).scorekeeper)
342                 error("player already has a scorekeeper");
343         entity sk = new_pure(scorekeeper);
344         sk.owner = player;
345         Net_LinkEntity(sk, false, 0, PlayerScore_SendEntity);
346         CS(player).scorekeeper = sk;
347 }
348
349 void PlayerScore_Detach(entity player)
350 {
351         if(!CS(player).scorekeeper)
352                 error("player has no scorekeeper");
353         delete(CS(player).scorekeeper);
354         CS(player).scorekeeper = NULL;
355 }
356
357 float PlayerScore_Add(entity player, PlayerScoreField scorefield, float score)
358 {
359         bool mutator_returnvalue = MUTATOR_CALLHOOK(AddPlayerScore, scorefield, score, player);
360         score = M_ARGV(1, float);
361
362         if(!mutator_returnvalue && game_stopped)
363         {
364                 score = 0;
365         }
366
367         if(!scores_initialized) return 0; // FIXME remove this when everything uses this system
368         entity s = CS(player).scorekeeper;
369         if(!s)
370         {
371                 if(game_stopped)
372                         return 0;
373                 LOG_WARN("Adding score to unknown player!");
374                 return 0;
375         }
376         if(!score)
377         {
378                 return s.(scores(scorefield));
379         }
380         if(scores_label(scorefield) != "")
381                 s.SendFlags |= BIT(scorefield.m_id % 16);
382         if(!warmup_stage)
383                 PlayerStats_GameReport_Event_Player(s.owner, strcat(PLAYERSTATS_TOTAL, scores_label(scorefield)), score);
384         s.(scores(scorefield)) += score;
385         MUTATOR_CALLHOOK(AddedPlayerScore, scorefield, score, player);
386         return s.(scores(scorefield));
387 }
388
389 float PlayerScore_Set(entity player, PlayerScoreField scorefield, float score)
390 {
391         if(!scores_initialized) return 0; // FIXME remove this when everything uses this system
392         entity s = CS(player).scorekeeper;
393         if(!s)
394         {
395                 if(game_stopped)
396                         return 0;
397                 LOG_WARN("Setting score of unknown player!");
398                 return 0;
399         }
400
401         float oldscore = s.(scores(scorefield));
402         if(oldscore == score)
403                 return oldscore;
404
405         if(scores_label(scorefield) != "")
406                 s.SendFlags |= BIT(scorefield.m_id % 16);
407         s.(scores(scorefield)) = score;
408         return s.(scores(scorefield));
409 }
410
411 float PlayerTeamScore_Add(entity player, PlayerScoreField pscorefield, float tscorefield, float score)
412 {
413         float r;
414         r = PlayerScore_Add(player, pscorefield, score);
415         if(teamscores_entities_count) // only for teamplay
416                 r = TeamScore_Add(player, tscorefield, score);
417         return r;
418 }
419
420 float PlayerScore_Compare(entity t1, entity t2, bool strict)
421 {
422         if(!t1 || !t2) return (!t2) - !t1;
423
424         vector result = '0 0 0';
425
426         result = ScoreField_Compare(t1, t2, scores_primary, scores_flags_primary, result, strict);
427         // NOTE: if (scores_secondary) doesn't work because it's a field pointer
428         if (result.x == 0 && scores_flags_secondary)
429                 result = ScoreField_Compare(t1, t2, scores_secondary, scores_flags_secondary, result, strict);
430
431         if (result.x == 0)
432                 FOREACH(Scores, true, {
433                         if (scores_flags(it) & SFL_SORT_PRIO_MASK)
434                                 continue;
435                         if (scores_label(it) == "")
436                                 continue;
437                         var .float f = scores(it);
438                         result = ScoreField_Compare(t1, t2, f, scores_flags(it), result, strict);
439                         if (result.x) break;
440                 });
441
442         if (result.x == 0 && strict)
443                 result.x = t1.owner.playerid - t2.owner.playerid;
444
445         return result.x;
446 }
447
448 void WinningConditionHelper(entity this)
449 {
450         float c;
451         string s;
452         float fullstatus;
453         entity winnerscorekeeper;
454         entity secondscorekeeper;
455         entity sk;
456
457         // format:
458         // gametype:P<pure>:S<slots>::plabel,plabel:tlabel,tlabel:teamid:tscore,tscore:teamid:tscore,tscore
459         // score labels always start with a symbol or with lower case
460         // so to match pure, match for :P0:
461         // to match full, match for :S0:
462
463         fullstatus = autocvar_g_full_getstatus_responses;
464
465         s = GetGametype();
466         s = strcat(s, ":", autocvar_g_xonoticversion);
467         s = strcat(s, ":P", ftos(cvar_purechanges_count));
468         s = strcat(s, ":S", ftos(nJoinAllowed(this, NULL)));
469         s = strcat(s, ":F", ftos(serverflags));
470         s = strcat(s, ":T", sv_termsofservice_url_escaped);
471         s = strcat(s, ":M", modname);
472         s = strcat(s, "::", GetPlayerScoreString(NULL, (fullstatus ? 1 : 2)));
473
474         if(teamscores_entities_count)
475         {
476                 float t;
477
478                 s = strcat(s, ":", GetTeamScoreString(0, 1));
479                 for(t = 0; t < 16; ++t)
480                         if(teamscorekeepers[t])
481                                 s = strcat(s, ":", ftos(t+1), ":", GetTeamScoreString(t+1, 1));
482
483                 WinningConditionHelper_winnerteam = -1;
484                 WinningConditionHelper_secondteam = -1;
485                 winnerscorekeeper = NULL;
486                 secondscorekeeper = NULL;
487                 for(t = 0; t < 16; ++t)
488                 {
489                         sk = teamscorekeepers[t];
490                         c = TeamScore_Compare(winnerscorekeeper, sk, 1);
491                         if(c < 0)
492                         {
493                                 WinningConditionHelper_secondteam = WinningConditionHelper_winnerteam;
494                                 WinningConditionHelper_winnerteam = t + 1;
495                                 secondscorekeeper = winnerscorekeeper;
496                                 winnerscorekeeper = sk;
497                         }
498                         else
499                         {
500                                 c = TeamScore_Compare(secondscorekeeper, sk, 1);
501                                 if(c < 0)
502                                 {
503                                         WinningConditionHelper_secondteam = t + 1;
504                                         secondscorekeeper = sk;
505                                 }
506                         }
507                 }
508
509                 WinningConditionHelper_equality = (TeamScore_Compare(winnerscorekeeper, secondscorekeeper, 0) == 0);
510                 if(WinningConditionHelper_equality)
511                         WinningConditionHelper_winnerteam = WinningConditionHelper_secondteam = -1;
512
513                 WinningConditionHelper_topscore = winnerscorekeeper.teamscores_primary;
514                 WinningConditionHelper_secondscore = secondscorekeeper.teamscores_primary;
515                 WinningConditionHelper_lowerisbetter = (teamscores_flags_primary & SFL_LOWER_IS_BETTER);
516                 WinningConditionHelper_zeroisworst = (teamscores_flags_primary & SFL_ZERO_IS_WORST);
517
518                 WinningConditionHelper_winner = NULL; // not supported in teamplay
519                 WinningConditionHelper_second = NULL; // not supported in teamplay
520         }
521         else
522         {
523                 WinningConditionHelper_winner = NULL;
524                 WinningConditionHelper_second = NULL;
525                 winnerscorekeeper = NULL;
526                 secondscorekeeper = NULL;
527                 FOREACH_CLIENT(IS_PLAYER(it), {
528                         sk = CS(it).scorekeeper;
529                         c = PlayerScore_Compare(winnerscorekeeper, sk, true);
530                         if(c < 0)
531                         {
532                                 WinningConditionHelper_second = WinningConditionHelper_winner;
533                                 WinningConditionHelper_winner = it;
534                                 secondscorekeeper = winnerscorekeeper;
535                                 winnerscorekeeper = sk;
536                         }
537                         else
538                         {
539                                 c = PlayerScore_Compare(secondscorekeeper, sk, true);
540                                 if(c < 0)
541                                 {
542                                         WinningConditionHelper_second = it;
543                                         secondscorekeeper = sk;
544                                 }
545                         }
546                 });
547
548                 WinningConditionHelper_equality = (PlayerScore_Compare(winnerscorekeeper, secondscorekeeper, false) == 0);
549                 if(WinningConditionHelper_equality)
550                         WinningConditionHelper_winner = WinningConditionHelper_second = NULL;
551
552                 WinningConditionHelper_topscore = winnerscorekeeper.scores_primary;
553                 WinningConditionHelper_secondscore = secondscorekeeper.scores_primary;
554                 WinningConditionHelper_lowerisbetter = (scores_flags_primary & SFL_LOWER_IS_BETTER);
555                 WinningConditionHelper_zeroisworst = (scores_flags_primary & SFL_ZERO_IS_WORST);
556
557                 WinningConditionHelper_winnerteam = -1; // no teamplay
558                 WinningConditionHelper_secondteam = -1; // no teamplay
559         }
560
561         if(WinningConditionHelper_topscore == 0)
562         {
563                 if(scores_flags_primary & SFL_ZERO_IS_WORST)
564                 {
565                         if(WinningConditionHelper_lowerisbetter)
566                                 WinningConditionHelper_topscore = 999999999;
567                         else
568                                 WinningConditionHelper_topscore = -999999999;
569                 }
570                 if(player_count == 0) // special case: empty servers DO end the match at a 0:0 tie
571                         WinningConditionHelper_equality = 0;
572         }
573
574         if(WinningConditionHelper_secondscore == 0)
575         {
576                 if(scores_flags_primary & SFL_ZERO_IS_WORST)
577                 {
578                         if(WinningConditionHelper_lowerisbetter)
579                                 WinningConditionHelper_secondscore = 999999999;
580                         else
581                                 WinningConditionHelper_secondscore = -999999999;
582                 }
583         }
584
585         strcpy(worldstatus, s);
586
587         FOREACH_CLIENT(true, {
588                 string s = "";
589                 if(fullstatus)
590                 {
591                         s = GetPlayerScoreString(it, 1);
592                         s = strcat(s, IS_REAL_CLIENT(it) ? ":human" : ":bot");
593                         if(!(IS_PLAYER(it) || INGAME_JOINED(it)))
594                                 s = strcat(s, ":spectator");
595                 }
596                 else
597                 {
598                         if (IS_PLAYER(it) || INGAME_JOINED(it))
599                                 s = GetPlayerScoreString(it, 2);
600                         else
601                                 s = "-666";
602                 }
603
604                 strcpy(it.clientstatus, s);
605         });
606 }
607
608 string GetScoreLogLabel(string label, float fl)
609 {
610         if(fl & SFL_LOWER_IS_BETTER)
611                 label = strcat(label, "<");
612         if((fl & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_PRIMARY)
613                 label = strcat(label, "!!");
614         else if((fl & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_SECONDARY)
615                 label = strcat(label, "!");
616         return label;
617 }
618
619 string GetPlayerScoreString(entity pl, float shortString)
620 {
621         string out;
622         entity sk;
623         float f;
624         string l;
625
626         out = "";
627         if(!pl)
628         {
629                 // label
630                 FOREACH(Scores, true, {
631                         if ((scores_flags(it) & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_PRIMARY)
632                         {
633                                 f = scores_flags(it);
634                                 l = scores_label(it);
635                                 out = strcat(out, GetScoreLogLabel(l, f), ",");
636                         }
637         });
638                 if(shortString < 2)
639                 FOREACH(Scores, true, {
640                         if((scores_flags(it) & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_SECONDARY)
641                         {
642                                 f = scores_flags(it);
643                                 l = scores_label(it);
644                                 out = strcat(out, GetScoreLogLabel(l, f), ",");
645                         }
646         });
647                 if(shortString < 1)
648                 FOREACH(Scores, true, {
649                         if((scores_flags(it) & SFL_SORT_PRIO_MASK) != SFL_SORT_PRIO_PRIMARY)
650                         if((scores_flags(it) & SFL_SORT_PRIO_MASK) != SFL_SORT_PRIO_SECONDARY)
651                         {
652                                 f = scores_flags(it);
653                                 l = scores_label(it);
654                                 out = strcat(out, GetScoreLogLabel(l, f), ",");
655                         }
656         });
657                 out = substring(out, 0, strlen(out) - 1);
658         }
659         else if((sk = CS(pl).scorekeeper))
660         {
661                 FOREACH(Scores, true, {
662                         if ((scores_flags(it) & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_PRIMARY)
663                                 out = strcat(out, ftos(sk.(scores(it))), ",");
664         });
665                 if(shortString < 2)
666                 FOREACH(Scores, true, {
667                         if ((scores_flags(it) & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_SECONDARY)
668                                 out = strcat(out, ftos(sk.(scores(it))), ",");
669         });
670                 if(shortString < 1)
671                 FOREACH(Scores, true, {
672                         if((scores_flags(it) & SFL_SORT_PRIO_MASK) != SFL_SORT_PRIO_PRIMARY)
673                         if((scores_flags(it) & SFL_SORT_PRIO_MASK) != SFL_SORT_PRIO_SECONDARY)
674                                 out = strcat(out, ftos(sk.(scores(it))), ",");
675         });
676                 out = substring(out, 0, strlen(out) - 1);
677         }
678         return out;
679 }
680
681 string GetTeamScoreString(float tm, float shortString)
682 {
683         string out;
684         entity sk;
685         float i, f;
686         string l;
687
688         out = "";
689         if(tm == 0)
690         {
691                 // label
692                 for(i = 0; i < MAX_TEAMSCORE; ++i)
693                         if((teamscores_flags(i) & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_PRIMARY)
694                         {
695                                 f = teamscores_flags(i);
696                                 l = teamscores_label(i);
697                                 out = strcat(out, GetScoreLogLabel(l, f), ",");
698                         }
699                 if(shortString < 2)
700                 for(i = 0; i < MAX_TEAMSCORE; ++i)
701                         if((teamscores_flags(i) & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_SECONDARY)
702                         {
703                                 f = teamscores_flags(i);
704                                 l = teamscores_label(i);
705                                 out = strcat(out, GetScoreLogLabel(l, f), ",");
706                         }
707                 if(shortString < 1)
708                 for(i = 0; i < MAX_TEAMSCORE; ++i)
709                         if((teamscores_flags(i) & SFL_SORT_PRIO_MASK) != SFL_SORT_PRIO_PRIMARY)
710                         if((teamscores_flags(i) & SFL_SORT_PRIO_MASK) != SFL_SORT_PRIO_SECONDARY)
711                         {
712                                 f = teamscores_flags(i);
713                                 l = teamscores_label(i);
714                                 out = strcat(out, GetScoreLogLabel(l, f), ",");
715                         }
716                 out = substring(out, 0, strlen(out) - 1);
717         }
718         else if((sk = teamscorekeepers[tm - 1]))
719         {
720                 for(i = 0; i < MAX_TEAMSCORE; ++i)
721                         if((teamscores_flags(i) & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_PRIMARY)
722                                 out = strcat(out, ftos(sk.(teamscores(i))), ",");
723                 if(shortString < 2)
724                 for(i = 0; i < MAX_TEAMSCORE; ++i)
725                         if((teamscores_flags(i) & SFL_SORT_PRIO_MASK) == SFL_SORT_PRIO_SECONDARY)
726                                 out = strcat(out, ftos(sk.(teamscores(i))), ",");
727                 if(shortString < 1)
728                 for(i = 0; i < MAX_TEAMSCORE; ++i)
729                         if((teamscores_flags(i) & SFL_SORT_PRIO_MASK) != SFL_SORT_PRIO_PRIMARY)
730                         if((teamscores_flags(i) & SFL_SORT_PRIO_MASK) != SFL_SORT_PRIO_SECONDARY)
731                                 out = strcat(out, ftos(sk.(teamscores(i))), ",");
732                 out = substring(out, 0, strlen(out) - 1);
733         }
734         return out;
735 }
736
737 float PlayerTeamScore_Compare(entity p1, entity p2, float teams, bool strict)
738 {
739         if(teams && teamscores_entities_count)
740         {
741                 if(p1.team != p2.team)
742                 {
743                         entity t1, t2;
744                         float r;
745                         t1 = teamscorekeepers[p1.team - 1];
746                         t2 = teamscorekeepers[p2.team - 1];
747                         r = TeamScore_Compare(t1, t2, ((teams >= 0) ? 1 : strict));
748                         return r;
749                 }
750                 if(teams < 0)
751                         return 0;
752         }
753
754         return PlayerScore_Compare(CS(p1).scorekeeper, CS(p2).scorekeeper, strict);
755 }
756
757 entity PlayerScore_Sort(.float field, int teams, bool strict, bool nospectators)
758 {
759         entity p, plist, pprev, pbest, pbestprev, pfirst, plast;
760         float i, j;
761
762         plist = NULL;
763
764         FOREACH_CLIENT(true, { it.(field) = 0; });
765
766         FOREACH_CLIENT(CS(it).scorekeeper,
767         {
768                 if(nospectators)
769                         if(it.frags == FRAGS_SPECTATOR)
770                                 continue;
771
772                 it.chain = plist;
773                 plist = it;
774         });
775         // Now plist points to the whole list.
776
777         pfirst = plast = NULL;
778
779         i = j = 0;
780         while(plist)
781         {
782                 pprev = pbestprev = NULL;
783                 pbest = plist;
784                 for(p = plist; (pprev = p), (p = p.chain); )
785                 {
786                         if(PlayerTeamScore_Compare(p, pbest, teams, strict) > 0)
787                         {
788                                 pbest = p;
789                                 pbestprev = pprev;
790                         }
791                 }
792
793                 // remove pbest out of the chain
794                 if(pbestprev == NULL)
795                         plist = pbest.chain;
796                 else
797                         pbestprev.chain = pbest.chain;
798                 pbest.chain = NULL;
799
800                 ++i;
801                 if(!plast || PlayerTeamScore_Compare(plast, pbest, teams, strict))
802                         j = i;
803
804                 pbest.(field) = j;
805
806                 if (!pfirst)
807                         pfirst = pbest;
808                 if(plast)
809                         plast.chain = pbest;
810                 plast = pbest;
811         }
812
813         return pfirst;
814 }
815
816 float TeamScore_GetCompareValue(float t)
817 {
818         float s;
819         entity sk;
820
821         if(t <= 0 || t >= 16)
822         {
823                 if(game_stopped)
824                         return 0;
825                 error("Reading score of invalid team!");
826         }
827
828         sk = teamscorekeepers[t - 1];
829         if (!sk)
830                 return -999999999;
831         s = sk.teamscores_primary;
832         if(teamscores_flags_primary & SFL_ZERO_IS_WORST)
833                 if(!s)
834                         return -999999999;
835         if(teamscores_flags_primary & SFL_LOWER_IS_BETTER)
836                 s = -s;
837         return s;
838 }
839
840 const float NAMEWIDTH = 22;
841 const float SCORESWIDTH = 58;
842 // TODO put this somewhere in common?
843 string Score_NicePrint_ItemColor(float vflags)
844 {
845         if(vflags & SFL_SORT_PRIO_PRIMARY)
846                 return "^3";
847         else if(vflags & SFL_SORT_PRIO_SECONDARY)
848                 return "^5";
849         else
850                 return "^7";
851 }
852
853 void Score_NicePrint_Team(entity to, float t, float w)
854 {
855         string s, s2;
856         float i;
857         entity sk;
858         float fl, sc;
859         s = "";
860
861         sk = teamscorekeepers[t - 1];
862         if(sk)
863         {
864                 s = strcat(s, Team_ColoredFullName(t));
865                 for(i = 0; i < MAX_TEAMSCORE; ++i)
866                         if(teamscores_label(i) != "")
867                         {
868                                 fl = teamscores_flags(i);
869                                 sc = sk.(teamscores(i));
870                                 s = strcat(s, " ", Score_NicePrint_ItemColor(fl), ScoreString(fl, sc));
871                         }
872         }
873         else
874                 s = "Scores:";
875
876         s = strcat(s, strpad(max(0, NAMEWIDTH - strlennocol(s)), ""));
877
878         FOREACH(Scores, true, {
879                 if(scores_label(it) != "")
880                 {
881                         fl = scores_flags(it);
882                         s2 = scores_label(it);
883                         s = strcat(s, " ", Score_NicePrint_ItemColor(fl), strpad(-w, substring(s2, 0, w)));
884                 }
885     });
886
887         print_to(to, s);
888 }
889
890 void Score_NicePrint_Player(entity to, entity p, float w)
891 {
892         string s;
893         float i;
894         entity sk;
895         float fl, sc;
896         s = "  ";
897
898         sk = CS(p).scorekeeper;
899
900         s = strcat(s, playername(p.netname, p.team, false));
901         for (;;)
902         {
903                 i = strlennocol(s) - NAMEWIDTH;
904                 if(i > 0)
905                         s = substring(s, 0, strlen(s) - i);
906                 else
907                 {
908                         s = strcat(s, strpad(i, ""));
909                         break;
910                 }
911         }
912
913         FOREACH(Scores, true, {
914                 if(scores_label(it) != "")
915                 {
916                         fl = scores_flags(it);
917                         sc = sk.(scores(it));
918                         s = strcat(s, " ", Score_NicePrint_ItemColor(fl), strpad(-w, ScoreString(fl, sc)));
919                 }
920     });
921
922         print_to(to, s);
923 }
924
925 void Score_NicePrint_Spectators(entity to)
926 {
927         print_to(to, "Spectators:");
928 }
929
930 void Score_NicePrint_Spectator(entity to, entity p)
931 {
932         print_to(to, strcat("  ", playername(p.netname, p.team, false)));
933 }
934
935 .float score_dummyfield;
936 void Score_NicePrint(entity to)
937 {
938         entity p;
939         float w;
940
941         int t = 0;
942         FOREACH(Scores, true, {
943                 if(scores_label(it) != "")
944                         ++t;
945     });
946         w = bound(6, floor(SCORESWIDTH / t - 1), 9);
947
948         p = PlayerScore_Sort(score_dummyfield, 1, true, false);
949         t = -1;
950
951         if(!teamscores_entities_count)
952                 Score_NicePrint_Team(to, t, w);
953         while(p)
954         {
955                 if(teamscores_entities_count)
956                         if(t != p.team)
957                                 Score_NicePrint_Team(to, p.team, w);
958                 Score_NicePrint_Player(to, p, w);
959                 t = p.team;
960                 p = p.chain;
961         }
962
963         t = 0;
964         FOREACH_CLIENT(!IS_PLAYER(it), {
965                 if (!t)
966                         Score_NicePrint_Spectators(to);
967                 Score_NicePrint_Spectator(to, it);
968                 t = 1;
969         });
970 }
971
972 void PlayerScore_PlayerStats(entity p)
973 {
974         entity s = CS(p).scorekeeper;
975         FOREACH(Scores, true, {
976                 if(s.(scores(it)) != 0 && scores_label(it) != "")
977                         PlayerStats_GameReport_Event_Player(s.owner,
978                                 strcat(PLAYERSTATS_SCOREBOARD, scores_label(it)), s.(scores(it)));
979         });
980 }
981
982 void PlayerScore_TeamStats()
983 {
984         entity sk;
985         float t, i;
986         for(t = 0; t < 16; ++t)
987         {
988                 sk = teamscorekeepers[t];
989                 if(!sk)
990                         continue;
991                 for(i = 0; i < MAX_TEAMSCORE; ++i)
992                         if(sk.(teamscores(i)) != 0 && teamscores_label(i) != "")
993                                 // the +1 is important here!
994                                 PlayerStats_GameReport_Event_Team(t+1,
995                                         strcat(PLAYERSTATS_SCOREBOARD, teamscores_label(i)), sk.(teamscores(i)));
996         }
997 }