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