]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/race.qc
Merge remote-tracking branch 'origin/morosophos/enhance-demo-record-markers' into...
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / race.qc
1 #include "race.qh"
2
3 #include <common/deathtypes/all.qh>
4 #include <common/gamemodes/_mod.qh>
5 #include <common/gamemodes/rules.qh>
6 #include <common/mapobjects/subs.qh>
7 #include <common/mapobjects/triggers.qh>
8 #include <common/mutators/mutator/waypoints/waypointsprites.qh>
9 #include <common/net_linked.qh>
10 #include <common/notifications/all.qh>
11 #include <common/state.qh>
12 #include <common/stats.qh>
13 #include <common/vehicles/sv_vehicles.qh>
14 #include <common/weapons/_all.qh>
15 #include <common/weapons/weapon/porto.qh>
16 #include <lib/warpzone/common.qh>
17 #include <lib/warpzone/util_server.qh>
18 #include <server/bot/api.qh>
19 #include <server/cheats.qh>
20 #include <server/client.qh>
21 #include <server/command/getreplies.qh>
22 #include <server/damage.qh>
23 #include <server/gamelog.qh>
24 #include <server/intermission.qh>
25 #include <server/main.qh>
26 #include <server/mutators/_mod.qh>
27 #include <server/portals.qh>
28 #include <server/scores.qh>
29 #include <server/spawnpoints.qh>
30 #include <server/weapons/common.qh>
31 #include <server/world.qh>
32
33 .string stored_netname; // TODO: store this information independently of race-based gamemodes
34
35 string uid2name(string myuid)
36 {
37         string s = db_get(ServerProgsDB, strcat("/uid2name/", myuid));
38
39         // FIXME remove this later after 0.6 release
40         // convert old style broken records to correct style
41         if(s == "")
42         {
43                 s = db_get(ServerProgsDB, strcat("uid2name", myuid));
44                 if(s != "")
45                 {
46                         db_put(ServerProgsDB, strcat("/uid2name/", myuid), s);
47                         db_remove(ServerProgsDB, strcat("uid2name", myuid));
48                 }
49         }
50
51         if(s == "")
52                 s = "^1Unregistered Player";
53         return s;
54 }
55
56 void write_recordmarker(entity pl, float newpos, float tstart, float dt)
57 {
58     GameLogEcho(strcat(":recordset:", ftos(newpos), ":", ftos(pl.playerid), ":", ftos(etof(pl)), ":", ftos(dt)));
59
60     // also write a marker into demo files for demotc-race-record-extractor to find
61     if (pl.crypto_idfp != "") {
62       stuffcmd(pl,
63                strcat(
64                    strcat("//", strconv(2, 0, 0, GetGametype()), " RECORD SET ", TIME_ENCODED_TOSTRING(TIME_ENCODE(dt))),
65                    strcat(" ", ftos(tstart), " ", ftos(dt), " ", ftos(newpos), " "),
66                    strcat(pl.crypto_idfp, "\n")));
67     } else {
68       stuffcmd(pl,
69                strcat(
70                    strcat("//", strconv(2, 0, 0, GetGametype()), " RECORD SET ", TIME_ENCODED_TOSTRING(TIME_ENCODE(dt))),
71                    strcat(" ", ftos(tstart), " ", ftos(dt), " ", ftos(newpos), " ANONYMOUS")));
72     }
73 }
74
75 IntrusiveList g_race_targets;
76 IntrusiveList g_racecheckpoints;
77
78 void race_InitSpectator()
79 {
80         if(g_race_qualifying)
81                 if(msg_entity.enemy.race_laptime)
82                         race_SendNextCheckpoint(msg_entity.enemy, 1);
83 }
84
85 float race_readTime(string map, float pos)
86 {
87         return stof(db_get(ServerProgsDB, strcat(map, record_type, "time", ftos(pos))));
88 }
89
90 string race_readUID(string map, float pos)
91 {
92         return db_get(ServerProgsDB, strcat(map, record_type, "crypto_idfp", ftos(pos)));
93 }
94
95 float race_readPos(string map, float t)
96 {
97         for(int i = 1; i <= RANKINGS_CNT; ++i)
98         {
99                 int mytime = race_readTime(map, i);
100                 if(!mytime || mytime > t)
101                         return i;
102         }
103
104         return 0; // pos is zero if unranked
105 }
106
107 void race_writeTime(string map, float t, string myuid)
108 {
109         float newpos;
110         newpos = race_readPos(map, t);
111
112         float i, prevpos = 0;
113         for(i = 1; i <= RANKINGS_CNT; ++i)
114         {
115                 if(race_readUID(map, i) == myuid)
116                         prevpos = i;
117         }
118         if (prevpos)
119         {
120                 // player improved his existing record, only have to iterate on ranks between new and old recs
121                 for (i = prevpos; i > newpos; --i)
122                 {
123                         db_put(ServerProgsDB, strcat(map, record_type, "time", ftos(i)), ftos(race_readTime(map, i - 1)));
124                         db_put(ServerProgsDB, strcat(map, record_type, "crypto_idfp", ftos(i)), race_readUID(map, i - 1));
125                 }
126         }
127         else
128         {
129                 // player has no ranked record yet
130                 for (i = RANKINGS_CNT; i > newpos; --i)
131                 {
132                         float other_time = race_readTime(map, i - 1);
133                         if (other_time) {
134                                 db_put(ServerProgsDB, strcat(map, record_type, "time", ftos(i)), ftos(other_time));
135                                 db_put(ServerProgsDB, strcat(map, record_type, "crypto_idfp", ftos(i)), race_readUID(map, i - 1));
136                         }
137                 }
138         }
139
140         // store new time itself
141         db_put(ServerProgsDB, strcat(map, record_type, "time", ftos(newpos)), ftos(t));
142         db_put(ServerProgsDB, strcat(map, record_type, "crypto_idfp", ftos(newpos)), myuid);
143 }
144
145 string race_readName(string map, float pos)
146 {
147         return uid2name(db_get(ServerProgsDB, strcat(map, record_type, "crypto_idfp", ftos(pos))));
148 }
149
150 void race_checkAndWriteName(entity player)
151 {
152         if(CS_CVAR(player).cvar_cl_allow_uidtracking == 1 && CS_CVAR(player).cvar_cl_allow_uid2name == 1)
153         {
154                 if (!player.stored_netname)
155                         player.stored_netname = strzone(uid2name(player.crypto_idfp));
156                 if(player.stored_netname != player.netname)
157                 {
158                         db_put(ServerProgsDB, strcat("/uid2name/", player.crypto_idfp), player.netname);
159                         strcpy(player.stored_netname, player.netname);
160                 }
161         }
162 }
163
164
165 const float MAX_CHECKPOINTS = 255;
166
167 .float race_penalty;
168 .float race_penalty_accumulator;
169 .string race_penalty_reason;
170 .float race_checkpoint; // player: next checkpoint that has to be reached
171 .entity race_lastpenalty;
172
173 .entity sprite;
174
175 float race_checkpoint_records[MAX_CHECKPOINTS];
176 string race_checkpoint_recordholders[MAX_CHECKPOINTS];
177 float race_checkpoint_lasttimes[MAX_CHECKPOINTS];
178 float race_checkpoint_lastlaps[MAX_CHECKPOINTS];
179 entity race_checkpoint_lastplayers[MAX_CHECKPOINTS];
180
181 .float race_checkpoint_record[MAX_CHECKPOINTS];
182
183 float race_highest_checkpoint;
184 float race_timed_checkpoint;
185
186 float defrag_ents;
187 float defragcpexists;
188
189 float race_NextCheckpoint(float f)
190 {
191         if(f >= race_highest_checkpoint)
192                 return 0;
193         else
194                 return f + 1;
195 }
196
197 float race_PreviousCheckpoint(float f)
198 {
199         if(f == -1)
200                 return 0;
201         else if(f == 0)
202                 return race_highest_checkpoint;
203         else
204                 return f - 1;
205 }
206
207 // encode as:
208 //   0 = common start/finish
209 // 254 = start
210 // 255 = finish
211 float race_CheckpointNetworkID(float f)
212 {
213         if(race_timed_checkpoint)
214         {
215                 if(f == 0)
216                         return 254; // start
217                 else if(f == race_timed_checkpoint)
218                         return 255; // finish
219         }
220         return f;
221 }
222
223 void race_SendNextCheckpoint(entity e, float spec) // qualifying only
224 {
225         if(!e.race_laptime)
226                 return;
227
228         int cp = e.race_checkpoint;
229         float myrecordtime = e.race_checkpoint_record[cp];
230         float recordtime;
231         string recordholder;
232         if (autocvar_g_cts_cptimes_onlyself && (race_CheckpointNetworkID(cp) < 254)) {  // cp 254 - start line, cp 255 - finish line
233           recordtime = myrecordtime;
234           recordholder = "";
235         } else {
236           recordtime = race_checkpoint_records[cp];
237
238           recordholder = race_checkpoint_recordholders[cp];
239           if(recordholder == e.netname)
240                 recordholder = "";
241         }
242
243         if(!IS_REAL_CLIENT(e))
244                 return;
245
246         if(!spec)
247                 msg_entity = e;
248         WRITESPECTATABLE_MSG_ONE(msg_entity, {
249                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
250                 if(spec)
251                 {
252                         WriteByte(MSG_ONE, RACE_NET_CHECKPOINT_NEXT_SPEC_QUALIFYING);
253                         //WriteCoord(MSG_ONE, e.race_laptime - e.race_penalty_accumulator);
254                         WriteCoord(MSG_ONE, time - e.race_movetime - e.race_penalty_accumulator);
255                 }
256                 else
257                         WriteByte(MSG_ONE, RACE_NET_CHECKPOINT_NEXT_QUALIFYING);
258                 WriteByte(MSG_ONE, race_CheckpointNetworkID(cp)); // checkpoint the player will be at next
259                 WriteInt24_t(MSG_ONE, recordtime);
260                 if(!spec)
261                         WriteInt24_t(MSG_ONE, myrecordtime);
262                 WriteString(MSG_ONE, recordholder);
263         });
264 }
265
266 void race_send_recordtime(float msg)
267 {
268         // send the server best time
269         WriteHeader(msg, TE_CSQC_RACE);
270         WriteByte(msg, RACE_NET_SERVER_RECORD);
271         WriteInt24_t(msg, race_readTime(GetMapname(), 1));
272 }
273
274 void race_send_speedaward(float msg)
275 {
276         // send the best speed of the round
277         WriteHeader(msg, TE_CSQC_RACE);
278         WriteByte(msg, RACE_NET_SPEED_AWARD);
279         WriteInt24_t(msg, floor(speedaward_speed+0.5));
280         WriteString(msg, speedaward_holder);
281 }
282
283 void race_send_speedaward_alltimebest(float msg)
284 {
285         // send the best speed
286         WriteHeader(msg, TE_CSQC_RACE);
287         WriteByte(msg, RACE_NET_SPEED_AWARD_BEST);
288         WriteInt24_t(msg, floor(speedaward_alltimebest+0.5));
289         WriteString(msg, speedaward_alltimebest_holder);
290 }
291
292 void race_send_rankings_cnt(float msg)
293 {
294         WriteHeader(msg, TE_CSQC_RACE);
295         WriteByte(msg, RACE_NET_RANKINGS_CNT);
296         int m = min(RANKINGS_CNT, autocvar_g_cts_send_rankings_cnt);
297         WriteByte(msg, m);
298 }
299
300 void race_SendRanking(float pos, float prevpos, float del, float msg)
301 {
302         WriteHeader(msg, TE_CSQC_RACE);
303         WriteByte(msg, RACE_NET_SERVER_RANKINGS);
304         WriteShort(msg, pos);
305         WriteShort(msg, prevpos);
306         WriteShort(msg, del);
307         WriteString(msg, race_readName(GetMapname(), pos));
308         WriteInt24_t(msg, race_readTime(GetMapname(), pos));
309 }
310
311 void race_SpeedAwardFrame(entity player)
312 {
313         if (IS_OBSERVER(player))
314                 return;
315
316         if(vdist(player.velocity - player.velocity_z * '0 0 1', >, speedaward_speed))
317         {
318                 speedaward_speed = vlen(player.velocity - player.velocity_z * '0 0 1');
319                 speedaward_holder = player.netname;
320                 speedaward_uid = player.crypto_idfp;
321                 speedaward_lastupdate = time;
322         }
323         if (speedaward_speed > speedaward_lastsent && (time - speedaward_lastupdate > 1 || intermission_running))
324         {
325                 race_send_speedaward(MSG_ALL);
326                 speedaward_lastsent = speedaward_speed;
327                 if (speedaward_speed > speedaward_alltimebest && speedaward_uid != "")
328                 {
329                         speedaward_alltimebest = speedaward_speed;
330                         speedaward_alltimebest_holder = speedaward_holder;
331                         speedaward_alltimebest_uid = speedaward_uid;
332                         db_put(ServerProgsDB, strcat(GetMapname(), record_type, "speed/speed"), ftos(speedaward_alltimebest));
333                         db_put(ServerProgsDB, strcat(GetMapname(), record_type, "speed/crypto_idfp"), speedaward_alltimebest_uid);
334                         race_send_speedaward_alltimebest(MSG_ALL);
335                 }
336         }
337 }
338
339 void race_SendAll(entity player, bool only_rankings)
340 {
341         if(!IS_REAL_CLIENT(player))
342                 return;
343
344         msg_entity = player;
345         if (!only_rankings)
346         {
347                 race_send_recordtime(MSG_ONE);
348                 race_send_speedaward(MSG_ONE);
349
350                 speedaward_alltimebest = stof(db_get(ServerProgsDB, strcat(GetMapname(), record_type, "speed/speed")));
351                 speedaward_alltimebest_holder = uid2name(db_get(ServerProgsDB, strcat(GetMapname(), record_type, "speed/crypto_idfp")));
352                 race_send_speedaward_alltimebest(MSG_ONE);
353         }
354
355         int m = min(RANKINGS_CNT, autocvar_g_cts_send_rankings_cnt);
356         race_send_rankings_cnt(MSG_ONE);
357         for (int i = 1; i <= m; ++i)
358                 race_SendRanking(i, 0, 0, MSG_ONE);
359 }
360
361 void race_SendStatus(float id, entity e)
362 {
363         if(!IS_REAL_CLIENT(e))
364                 return;
365
366         float msg;
367         if (id == 0)
368                 msg = MSG_ONE;
369         else
370                 msg = MSG_ALL;
371         msg_entity = e;
372         WRITESPECTATABLE_MSG_ONE(msg_entity, {
373                 WriteHeader(msg, TE_CSQC_RACE);
374                 WriteByte(msg, RACE_NET_SERVER_STATUS);
375                 WriteShort(msg, id);
376                 WriteString(msg, e.netname);
377         });
378 }
379
380 void race_setTime(string map, float t, string myuid, string mynetname, entity e, bool showmessage)
381 {
382         // netname only used TEMPORARILY for printing
383         int newpos = race_readPos(map, t);
384
385         int player_prevpos = 0;
386         for(int i = 1; i <= RANKINGS_CNT; ++i)
387         {
388                 if(race_readUID(map, i) == myuid)
389                         player_prevpos = i;
390         }
391
392         float oldrec;
393         string oldrec_holder;
394         if (player_prevpos && (player_prevpos < newpos || !newpos))
395         {
396                 oldrec = race_readTime(GetMapname(), player_prevpos);
397                 race_SendStatus(0, e); // "fail"
398                 if(showmessage)
399                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_FAIL_RANKED, mynetname, player_prevpos, t, oldrec);
400                 return;
401         }
402         else if (!newpos)
403         {
404                 // no ranking, time worse than the worst ranked
405                 oldrec = race_readTime(GetMapname(), RANKINGS_CNT);
406                 race_SendStatus(0, e); // "fail"
407                 if(showmessage)
408                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_FAIL_UNRANKED, mynetname, RANKINGS_CNT, t, oldrec);
409                 return;
410         }
411
412         write_recordmarker(e, newpos, time - TIME_DECODE(t), TIME_DECODE(t));
413
414         // if we didn't hit a return yet, we have a new record!
415
416         // if the player does not have a UID we can unfortunately not store the record, as the rankings system relies on UIDs
417         if(myuid == "")
418         {
419                 if(showmessage)
420                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_NEW_MISSING_UID, mynetname, t);
421                 return;
422         }
423
424         if(uid2name(myuid) == "^1Unregistered Player")
425         {
426                 if(showmessage)
427                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_NEW_MISSING_NAME, mynetname, t);
428                 return;
429         }
430
431         oldrec = race_readTime(GetMapname(), newpos);
432         oldrec_holder = race_readName(GetMapname(), newpos);
433
434         // store new ranking
435         race_writeTime(GetMapname(), t, myuid);
436
437         if (showmessage)
438         {
439                 race_send_recordtime(MSG_ALL);
440         }
441
442         race_SendRanking(newpos, player_prevpos, 0, MSG_ALL);
443         strcpy(rankings_reply, getrankings());
444
445         if(newpos == player_prevpos)
446         {
447                 if(showmessage)
448                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_NEW_IMPROVED, mynetname, newpos, t, oldrec);
449                 if(newpos == 1) { race_SendStatus(3, e); } // "new server record"
450                 else { race_SendStatus(1, e); } // "new time"
451         }
452         else if(oldrec == 0)
453         {
454                 if(showmessage)
455                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_NEW_SET, mynetname, newpos, t);
456                 if(newpos == 1) { race_SendStatus(3, e); } // "new server record"
457                 else { race_SendStatus(2, e); } // "new rank"
458         }
459         else
460         {
461                 if(showmessage)
462                         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_NEW_BROKEN, mynetname, oldrec_holder, newpos, t, oldrec);
463                 if(newpos == 1) { race_SendStatus(3, e); } // "new server record"
464                 else { race_SendStatus(2, e); } // "new rank"
465         }
466 }
467
468 void race_deleteTime(string map, float pos)
469 {
470         for(int i = pos; i <= RANKINGS_CNT; ++i)
471         {
472                 string therank = ftos(i);
473                 if (i == RANKINGS_CNT)
474                 {
475                         db_remove(ServerProgsDB, strcat(map, record_type, "time", therank));
476                         db_remove(ServerProgsDB, strcat(map, record_type, "crypto_idfp", therank));
477                 }
478                 else
479                 {
480                         db_put(ServerProgsDB, strcat(map, record_type, "time", therank), ftos(race_readTime(GetMapname(), i+1)));
481                         db_put(ServerProgsDB, strcat(map, record_type, "crypto_idfp", therank), race_readUID(GetMapname(), i+1));
482                 }
483         }
484
485         race_SendRanking(pos, 0, 1, MSG_ALL);
486         if(pos == 1)
487                 race_send_recordtime(MSG_ALL);
488
489         strcpy(rankings_reply, getrankings());
490 }
491
492 void race_SendTime(entity e, float cp, float t, float tvalid)
493 {
494         float snew, l;
495
496         if(g_race_qualifying)
497                 t += e.race_penalty_accumulator;
498
499         t = TIME_ENCODE(t); // make integer
500
501         if(tvalid)
502         if(cp == race_timed_checkpoint) // finish line
503         if (!CS(e).race_completed)
504         {
505                 float s;
506                 if(g_race_qualifying)
507                 {
508                         s = GameRules_scoring_add(e, RACE_FASTEST, 0);
509                         if(!s || t < s)
510                                 GameRules_scoring_add(e, RACE_FASTEST, t - s);
511                 }
512                 else
513                 {
514                         s = GameRules_scoring_add(e, RACE_FASTEST, 0);
515                         if(!s || t < s)
516                                 GameRules_scoring_add(e, RACE_FASTEST, t - s);
517
518                         s = GameRules_scoring_add(e, RACE_TIME, 0);
519                         snew = TIME_ENCODE(time - game_starttime);
520                         GameRules_scoring_add(e, RACE_TIME, snew - s);
521                         l = GameRules_scoring_add_team(e, RACE_LAPS, 1);
522
523                         if(autocvar_fraglimit)
524                                 if(l >= autocvar_fraglimit)
525                                         race_StartCompleting();
526
527                         if(race_completing)
528                         {
529                                 CS(e).race_completed = 1;
530                                 MAKE_INDEPENDENT_PLAYER(e);
531                                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_FINISHED, e.netname);
532                                 ClientData_Touch(e);
533                         }
534                 }
535         }
536
537         if(g_race_qualifying)
538         {
539                 float recordtime;
540                 string recordholder;
541
542                 if(tvalid)
543                 {
544                         float myrecordtime = e.race_checkpoint_record[cp];
545                         if (autocvar_g_cts_cptimes_onlyself && (race_CheckpointNetworkID(cp) < 254)) {  // cp 254 - start line, cp 255 - finish line
546                           recordtime = myrecordtime;
547                           recordholder = "";
548                         } else {
549                           recordtime = race_checkpoint_records[cp];
550                           recordholder = strcat1(race_checkpoint_recordholders[cp]); // make a tempstring copy, as we'll possibly strunzone it
551                           if(recordholder == e.netname)
552                                 recordholder = "";
553
554                         }
555                         if(t != 0)
556                         {
557                                 if(cp == race_timed_checkpoint)
558                                 {
559                                         race_setTime(GetMapname(), t, e.crypto_idfp, e.netname, e, true);
560                                         MUTATOR_CALLHOOK(Race_FinalCheckpoint, e);
561                                 }
562                                 if(t < myrecordtime || myrecordtime == 0)
563                                         e.race_checkpoint_record[cp] = t; // resending done below
564
565                                 if(t < recordtime || recordtime == 0)
566                                 {
567                                         race_checkpoint_records[cp] = t;
568                                         strcpy(race_checkpoint_recordholders[cp], e.netname);
569                                         if(g_race_qualifying)
570                                                 FOREACH_CLIENT(IS_PLAYER(it) && IS_REAL_CLIENT(it) && it.race_checkpoint == cp, { race_SendNextCheckpoint(it, 0); });
571                                 }
572
573                         }
574                 }
575                 else
576                 {
577                         // dummies
578                         t = 0;
579                         recordtime = 0;
580                         recordholder = "";
581                 }
582
583                 if(IS_REAL_CLIENT(e))
584                 {
585                         if(g_race_qualifying)
586                         {
587                                 FOREACH_CLIENT(IS_REAL_CLIENT(it),
588                                 {
589                                         if(it == e || (IS_SPEC(it) && it.enemy == e))
590                                         {
591                                                 msg_entity = it;
592                                                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
593                                                 WriteByte(MSG_ONE, RACE_NET_CHECKPOINT_HIT_QUALIFYING);
594                                                 WriteByte(MSG_ONE, race_CheckpointNetworkID(cp)); // checkpoint the player now is at
595                                                 WriteInt24_t(MSG_ONE, t); // time to that intermediate
596                                                 WriteInt24_t(MSG_ONE, recordtime); // previously best time
597                                                 WriteInt24_t(MSG_ONE, ((tvalid) ? it.race_checkpoint_record[cp] : 0)); // previously best time
598                                                 WriteString(MSG_ONE, recordholder); // record holder
599                                         }
600                                 });
601                         }
602                 }
603         }
604         else // RACE! Not Qualifying
605         {
606                 float mylaps, lother, othtime;
607                 entity oth = race_checkpoint_lastplayers[cp];
608                 if(oth)
609                 {
610                         mylaps = GameRules_scoring_add(e, RACE_LAPS, 0);
611                         lother = race_checkpoint_lastlaps[cp];
612                         othtime = race_checkpoint_lasttimes[cp];
613                 }
614                 else
615                         mylaps = lother = othtime = 0;
616
617                 if(IS_REAL_CLIENT(e))
618                 {
619                         msg_entity = e;
620                         WRITESPECTATABLE_MSG_ONE(msg_entity, {
621                                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
622                                 WriteByte(MSG_ONE, RACE_NET_CHECKPOINT_HIT_RACE);
623                                 WriteByte(MSG_ONE, race_CheckpointNetworkID(cp)); // checkpoint the player now is at
624                                 if(e == oth)
625                                 {
626                                         WriteInt24_t(MSG_ONE, 0);
627                                         WriteByte(MSG_ONE, 0);
628                                         WriteByte(MSG_ONE, 0);
629                                 }
630                                 else
631                                 {
632                                         WriteInt24_t(MSG_ONE, TIME_ENCODE(time - race_checkpoint_lasttimes[cp]));
633                                         WriteByte(MSG_ONE, mylaps - lother);
634                                         WriteByte(MSG_ONE, etof(oth)); // record holder
635                                 }
636                         });
637                 }
638
639                 race_checkpoint_lastplayers[cp] = e;
640                 race_checkpoint_lasttimes[cp] = time;
641                 race_checkpoint_lastlaps[cp] = mylaps;
642
643                 if(IS_REAL_CLIENT(oth))
644                 {
645                         msg_entity = oth;
646                         WRITESPECTATABLE_MSG_ONE(msg_entity, {
647                                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
648                                 WriteByte(MSG_ONE, RACE_NET_CHECKPOINT_HIT_RACE_BY_OPPONENT);
649                                 WriteByte(MSG_ONE, race_CheckpointNetworkID(cp)); // checkpoint the player now is at
650                                 if(e == oth)
651                                 {
652                                         WriteInt24_t(MSG_ONE, 0);
653                                         WriteByte(MSG_ONE, 0);
654                                         WriteByte(MSG_ONE, 0);
655                                 }
656                                 else
657                                 {
658                                         WriteInt24_t(MSG_ONE, TIME_ENCODE(time - othtime));
659                                         WriteByte(MSG_ONE, lother - mylaps);
660                                         WriteByte(MSG_ONE, etof(e) - 1); // record holder
661                                 }
662                         });
663                 }
664         }
665 }
666
667 void race_ClearTime(entity e)
668 {
669         e.race_checkpoint = 0;
670         e.race_laptime = 0;
671         e.race_movetime = e.race_movetime_frac = e.race_movetime_count = 0;
672         e.race_penalty_accumulator = 0;
673         e.race_lastpenalty = NULL;
674
675         if(!IS_REAL_CLIENT(e))
676                 return;
677
678         msg_entity = e;
679         WRITESPECTATABLE_MSG_ONE(msg_entity, {
680                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
681                 WriteByte(MSG_ONE, RACE_NET_CHECKPOINT_CLEAR); // next
682         });
683 }
684
685 void checkpoint_passed(entity this, entity player)
686 {
687         if(IS_VEHICLE(player) && player.owner)
688                 player = player.owner;
689
690         if(player.personal && autocvar_g_allow_checkpoints)
691                 return; // practice mode!
692
693         if(player.classname == "porto")
694         {
695                 // do not allow portalling through checkpoints
696                 trace_plane_normal = normalize(-1 * player.velocity);
697                 W_Porto_Fail(player, 0);
698                 return;
699         }
700
701         string oldmsg; // used twice
702
703         /*
704          * Trigger targets
705          */
706         if (!((this.spawnflags & 2) && (IS_PLAYER(player))))
707         {
708                 oldmsg = this.message;
709                 this.message = "";
710                 SUB_UseTargets(this, player, player);
711                 this.message = oldmsg;
712         }
713
714         if (!IS_PLAYER(player))
715                 return;
716
717         /*
718          * Remove unauthorized equipment
719          */
720         Portal_ClearAll(player);
721
722         player.porto_forbidden = 2; // decreased by 1 each StartFrame
723
724         if(defrag_ents)
725         {
726                 if(this.race_checkpoint == -2)
727                 {
728                         this.race_checkpoint = player.race_checkpoint;
729                 }
730
731                 int cp_amount = 0, largest_cp_id = 0;
732                 IL_EACH(g_race_targets, it.classname == "target_checkpoint",
733                 {
734                         cp_amount += 1;
735                         if(it.race_checkpoint > largest_cp_id) // update the finish id if someone hit a new checkpoint
736                         {
737                                 if(!largest_cp_id)
738                                 {
739                                         IL_EACH(g_race_targets, it.classname == "target_checkpoint",
740                                         {
741                                                 if(it.race_checkpoint == -2) // set defragcpexists to -1 so that the cp id file will be rewritten when someone finishes
742                                                         defragcpexists = -1;
743                                         });
744                                 }
745
746                                 largest_cp_id = it.race_checkpoint;
747                                 IL_EACH(g_race_targets, it.classname == "target_stopTimer",
748                                 {
749                                         it.race_checkpoint = largest_cp_id + 1; // finish line
750                                 });
751                                 race_highest_checkpoint = largest_cp_id + 1;
752                                 race_timed_checkpoint = largest_cp_id + 1;
753                         }
754                 });
755
756                 if(!cp_amount)
757                 {
758                         IL_EACH(g_race_targets, it.classname == "target_stopTimer",
759                         {
760                                 it.race_checkpoint = 1;
761                         });
762                         race_highest_checkpoint = 1;
763                         race_timed_checkpoint = 1;
764                 }
765         }
766
767         if((player.race_checkpoint == -1 && this.race_checkpoint == 0) || (player.race_checkpoint == this.race_checkpoint))
768         {
769                 if(this.race_penalty)
770                 {
771                         if(player.race_lastpenalty != this)
772                         {
773                                 player.race_lastpenalty = this;
774                                 race_ImposePenaltyTime(player, this.race_penalty, this.race_penalty_reason);
775                         }
776                 }
777
778                 if(player.race_penalty)
779                         return;
780
781                 /*
782                  * Trigger targets
783                  */
784                 if(this.spawnflags & 2)
785                 {
786                         oldmsg = this.message;
787                         this.message = "";
788                         SUB_UseTargets(this, player, player); // TODO: should we be using other for the trigger here?
789                         this.message = oldmsg;
790                 }
791
792                 if(player.race_respawn_checkpoint != this.race_checkpoint || !player.race_started)
793                         player.race_respawn_spotref = this; // this is not a spot but a CP, but spawnpoint selection will deal with that
794                 player.race_respawn_checkpoint = this.race_checkpoint;
795                 player.race_checkpoint = race_NextCheckpoint(this.race_checkpoint);
796                 player.race_started = 1;
797
798                 race_SendTime(player, this.race_checkpoint, player.race_movetime, boolean(player.race_laptime));
799
800                 if(!this.race_checkpoint) // start line
801                 {
802                         player.race_laptime = time;
803                         player.race_movetime = player.race_movetime_frac = player.race_movetime_count = 0;
804                         player.race_penalty_accumulator = 0;
805                         player.race_lastpenalty = NULL;
806                 }
807
808                 if(g_race_qualifying)
809                         race_SendNextCheckpoint(player, 0);
810
811                 if(defrag_ents && defragcpexists < 0 && this.classname == "target_stopTimer")
812                 {
813                         float fh;
814                         defragcpexists = fh = fopen(strcat("maps/", GetMapname(), ".defragcp"), FILE_WRITE);
815                         if(fh >= 0)
816                         {
817                                 IL_EACH(g_race_targets, it.classname == "target_checkpoint",
818                                 {
819                                         fputs(fh, strcat(it.targetname, " ", ftos(it.race_checkpoint), "\n"));
820                                 });
821                         }
822                         fclose(fh);
823                 }
824         }
825         else if(player.race_checkpoint == race_NextCheckpoint(this.race_checkpoint))
826         {
827                 // ignored
828         }
829         else
830         {
831                 if(this.spawnflags & 4)
832                         Damage (player, this, this, 10000, DEATH_HURTTRIGGER.m_id, DMG_NOWEP, player.origin, '0 0 0');
833         }
834 }
835
836 void checkpoint_touch(entity this, entity toucher)
837 {
838         EXACTTRIGGER_TOUCH(this, toucher);
839         checkpoint_passed(this, toucher);
840 }
841
842 void checkpoint_use(entity this, entity actor, entity trigger)
843 {
844         if(trigger.classname == "info_player_deathmatch") // a spawn, a spawn
845                 return;
846
847         checkpoint_passed(this, actor);
848 }
849
850 bool race_waypointsprite_visible_for_player(entity this, entity player, entity view)
851 {
852         entity own = this.owner;
853         if(this.realowner)
854                 own = this.realowner; // target support
855
856         if(view.race_checkpoint == -1 || own.race_checkpoint == -2)
857                 return true;
858         else if(view.race_checkpoint == own.race_checkpoint)
859                 return true;
860         else
861                 return false;
862 }
863
864 void defrag_waypointsprites(entity targeted, entity checkpoint)
865 {
866         // bones_was_here: spawn a waypoint for every entity with a bmodel
867         // that directly or indirectly targets this checkpoint
868         // (anything a player could touch or shoot to activate this cp)
869
870         entity s = WP_RaceCheckpoint;
871         if (checkpoint.classname == "target_startTimer")
872                 s = WP_RaceStart;
873         else if (checkpoint.classname == "target_stopTimer")
874                 s = WP_RaceFinish;
875
876         for (entity t = findchain(target, targeted.targetname); t; t = t.chain)
877         {
878                 if (t.modelindex)
879                 {
880                         WaypointSprite_SpawnFixed(s, (t.absmin + t.absmax) * 0.5, t, sprite, RADARICON_NONE);
881                         t.sprite.realowner = checkpoint;
882                         t.sprite.waypointsprite_visible_for_player = race_waypointsprite_visible_for_player;
883                 }
884
885                 if (t.targetname)
886                         defrag_waypointsprites(t, checkpoint);
887         }
888 }
889
890 void trigger_race_checkpoint_verify(entity this)
891 {
892         static bool have_verified;
893         if (have_verified) return;
894         have_verified = true;
895
896         bool qual = g_race_qualifying;
897
898         int pl_race_checkpoint = 0;
899         int pl_race_place = 0;
900
901         if (g_race) {
902                 for (int i = 0; i <= race_highest_checkpoint; ++i) {
903                         pl_race_checkpoint = race_NextCheckpoint(i);
904
905                         // race only (middle of the race)
906                         g_race_qualifying = false;
907                         pl_race_place = 0;
908                         if (!Spawn_FilterOutBadSpots(this, findchain(classname, "info_player_deathmatch"), 0, false, true)) {
909                                 error(strcat("Checkpoint ", ftos(i), " misses a spawnpoint with race_place==", ftos(pl_race_place), " (used for respawning in race) - bailing out"));
910                         }
911
912                         if (i == 0) {
913                                 // qualifying only
914                                 g_race_qualifying = 1;
915                                 pl_race_place = race_lowest_place_spawn;
916                                 if (!Spawn_FilterOutBadSpots(this, findchain(classname, "info_player_deathmatch"), 0, false, true)) {
917                                         error(strcat("Checkpoint ", ftos(i), " misses a spawnpoint with race_place==", ftos(pl_race_place), " (used for qualifying) - bailing out"));
918                                 }
919
920                                 // race only (initial spawn)
921                                 g_race_qualifying = 0;
922                                 for (int p = 1; p <= race_highest_place_spawn; ++p) {
923                                         pl_race_place = p;
924                                         if (!Spawn_FilterOutBadSpots(this, findchain(classname, "info_player_deathmatch"), 0, false, true)) {
925                                                 error(strcat("Checkpoint ", ftos(i), " misses a spawnpoint with race_place==", ftos(pl_race_place), " (used for initially spawning in race) - bailing out"));
926                                         }
927                                 }
928                         }
929                 }
930         } else if (!defrag_ents) {
931                 // qualifying only
932                 pl_race_checkpoint = race_NextCheckpoint(0);
933                 g_race_qualifying = 1;
934                 pl_race_place = race_lowest_place_spawn;
935                 if (!Spawn_FilterOutBadSpots(this, findchain(classname, "info_player_deathmatch"), 0, false, true)) {
936                         error(strcat("Checkpoint 0 misses a spawnpoint with race_place==", ftos(pl_race_place), " (used for qualifying) - bailing out"));
937                 }
938         } else {
939                 pl_race_checkpoint = race_NextCheckpoint(0);
940                 g_race_qualifying = 1;
941                 pl_race_place = 0; // there's only one spawn on defrag maps
942
943                 // check if a defragcp file already exists, then read it and apply the checkpoint order
944                 float fh;
945                 float len;
946                 string l;
947
948                 defragcpexists = fh = fopen(strcat("maps/", GetMapname(), ".defragcp"), FILE_READ);
949                 if (fh >= 0) {
950                         while ((l = fgets(fh))) {
951                                 len = tokenize_console(l);
952                                 if (len != 2) {
953                                         defragcpexists = -1; // something's wrong in the defrag cp file, set defragcpexists to -1 so that it will be rewritten when someone finishes
954                                         continue;
955                                 }
956                                 for (entity cp = NULL; (cp = find(cp, classname, "target_checkpoint"));) {
957                                         if (argv(0) == cp.targetname) {
958                                                 cp.race_checkpoint = stof(argv(1));
959                                         }
960                                 }
961                         }
962                         fclose(fh);
963                 }
964         }
965
966         g_race_qualifying = qual;
967
968         if (race_timed_checkpoint) {
969                 if (defrag_ents) {
970                         IL_EACH(g_race_targets, it.classname == "target_checkpoint" || it.classname == "target_startTimer" || it.classname == "target_stopTimer",
971                         {
972                                 defrag_waypointsprites(it, it);
973
974                                 if(it.classname == "target_checkpoint") {
975                                         if(it.race_checkpoint == -2)
976                                                 defragcpexists = -1; // something's wrong with the defrag cp file or it has not been written yet, set defragcpexists to -1 so that it will be rewritten when someone finishes
977                                 }
978                         });
979                         if (defragcpexists != -1) {
980                                 float largest_cp_id = 0;
981                                 for (entity cp = NULL; (cp = find(cp, classname, "target_checkpoint"));) {
982                                         if (cp.race_checkpoint > largest_cp_id) {
983                                                 largest_cp_id = cp.race_checkpoint;
984                                         }
985                                 }
986                                 for (entity cp = NULL; (cp = find(cp, classname, "target_stopTimer"));) {
987                                         cp.race_checkpoint = largest_cp_id + 1; // finish line
988                                 }
989                                 race_highest_checkpoint = largest_cp_id + 1;
990                                 race_timed_checkpoint = largest_cp_id + 1;
991                         } else {
992                                 for (entity cp = NULL; (cp = find(cp, classname, "target_stopTimer"));) {
993                                         cp.race_checkpoint = 255; // finish line
994                                 }
995                                 race_highest_checkpoint = 255;
996                                 race_timed_checkpoint = 255;
997                         }
998                 } else {
999                         IL_EACH(g_racecheckpoints, it.sprite,
1000                         {
1001                                 if (it.race_checkpoint == 0) {
1002                                         WaypointSprite_UpdateSprites(it.sprite, WP_RaceStart, WP_Null, WP_Null);
1003                                 } else if (it.race_checkpoint == race_timed_checkpoint) {
1004                                         WaypointSprite_UpdateSprites(it.sprite, WP_RaceFinish, WP_Null, WP_Null);
1005                                 }
1006                         });
1007                 }
1008         }
1009
1010         if (defrag_ents) { /* The following hack shall be removed when per-player trigger_multiple.wait is implemented for cts */
1011                 for (entity trigger = NULL; (trigger = find(trigger, classname, "trigger_multiple")); ) {
1012                         for (entity targ = NULL; (targ = find(targ, targetname, trigger.target)); ) {
1013                                 if (targ.classname == "target_checkpoint" || targ.classname == "target_startTimer" || targ.classname == "target_stopTimer") {
1014                                         trigger.wait = 0;
1015                                         trigger.delay = 0;
1016                                         targ.wait = 0;
1017                                         targ.delay = 0;
1018
1019                     // These just make the game crash on some maps with oddly shaped triggers.
1020                     // (on the other hand they used to fix the case when two players ran through a checkpoint at once,
1021                     // and often one of them just passed through without being registered. Hope it's fixed  in a better way now.
1022                     // (happened on item triggers too)
1023                     //
1024                                         //targ.wait = -2;
1025                                         //targ.delay = 0;
1026
1027                                         //setsize(targ, trigger.mins, trigger.maxs);
1028                                         //setorigin(targ, trigger.origin);
1029                                         //remove(trigger);
1030                                 }
1031             }
1032         }
1033         }
1034 }
1035
1036 vector trigger_race_checkpoint_spawn_evalfunc(entity this, entity player, entity spot, vector current)
1037 {
1038         if(g_race_qualifying)
1039         {
1040                 // spawn at first
1041                 if(this.race_checkpoint != 0)
1042                         return '-1 0 0';
1043                 if(spot.race_place != race_lowest_place_spawn)
1044                         return '-1 0 0';
1045         }
1046         else
1047         {
1048                 if(this.race_checkpoint != player.race_respawn_checkpoint)
1049                         return '-1 0 0';
1050                 // try reusing the previous spawn
1051                 if(this == player.race_respawn_spotref || spot == player.race_respawn_spotref)
1052                         current.x += SPAWN_PRIO_RACE_PREVIOUS_SPAWN;
1053                 if(this.race_checkpoint == 0)
1054                 {
1055                         int pl = player.race_place;
1056                         if(pl > race_highest_place_spawn)
1057                                 pl = 0;
1058                         if(pl == 0 && !player.race_started)
1059                                 pl = race_highest_place_spawn; // use last place if he has not even touched finish yet
1060                         if(spot.race_place != pl)
1061                                 return '-1 0 0';
1062                 }
1063         }
1064         return current;
1065 }
1066
1067 spawnfunc(trigger_race_checkpoint)
1068 {
1069         vector o;
1070         if(!g_race && !g_cts) { delete(this); return; }
1071
1072         EXACTTRIGGER_INIT;
1073
1074         this.use = checkpoint_use;
1075         if (!(this.spawnflags & 1))
1076                 settouch(this, checkpoint_touch);
1077
1078         o = (this.absmin + this.absmax) * 0.5;
1079         tracebox(o, PL_MIN_CONST, PL_MAX_CONST, o - '0 0 1' * (o.z - this.absmin.z), MOVE_NORMAL, this);
1080         waypoint_spawnforitem_force(this, trace_endpos);
1081         this.nearestwaypointtimeout = -1;
1082
1083         if(this.message == "")
1084                 this.message = "went backwards";
1085         if (this.message2 == "")
1086                 this.message2 = "was pushed backwards by";
1087         if (this.race_penalty_reason == "")
1088                 this.race_penalty_reason = "missing a checkpoint";
1089
1090         this.race_checkpoint = this.cnt;
1091
1092         if(this.race_checkpoint > race_highest_checkpoint)
1093         {
1094                 race_highest_checkpoint = this.race_checkpoint;
1095                 if(this.spawnflags & 8)
1096                         race_timed_checkpoint = this.race_checkpoint;
1097                 else
1098                         race_timed_checkpoint = 0;
1099         }
1100
1101         if(!this.race_penalty)
1102         {
1103                 if(this.race_checkpoint)
1104                         WaypointSprite_SpawnFixed(WP_RaceCheckpoint, o, this, sprite, RADARICON_NONE);
1105                 else
1106                         WaypointSprite_SpawnFixed(WP_RaceStartFinish, o, this, sprite, RADARICON_NONE);
1107         }
1108
1109         this.sprite.waypointsprite_visible_for_player = race_waypointsprite_visible_for_player;
1110         this.spawn_evalfunc = trigger_race_checkpoint_spawn_evalfunc;
1111
1112         if (!g_racecheckpoints)
1113                 g_racecheckpoints = IL_NEW();
1114         IL_PUSH(g_racecheckpoints, this);
1115
1116         // trigger_race_checkpoint_verify checks this list too
1117         if (!g_race_targets)
1118                 g_race_targets = IL_NEW();
1119
1120         InitializeEntity(this, trigger_race_checkpoint_verify, INITPRIO_FINDTARGET);
1121 }
1122
1123 void target_checkpoint_setup(entity this)
1124 {
1125         if(!g_race && !g_cts) { delete(this); return; }
1126         defrag_ents = 1;
1127
1128         // if this is targeted, then it probably isn't a trigger
1129         bool is_trigger = this.targetname == "";
1130
1131         if(is_trigger)
1132                 EXACTTRIGGER_INIT;
1133
1134         this.use = checkpoint_use;
1135         if (is_trigger && !(this.spawnflags & 1))
1136                 settouch(this, checkpoint_touch);
1137
1138         vector org = this.origin;
1139
1140         // bots should only pathfind to this if it is a valid touchable trigger
1141         if(is_trigger)
1142         {
1143                 org = (this.absmin + this.absmax) * 0.5;
1144                 tracebox(org, PL_MIN_CONST, PL_MAX_CONST, org - '0 0 1' * (org.z - this.absmin.z), MOVE_NORMAL, this);
1145                 waypoint_spawnforitem_force(this, trace_endpos);
1146                 this.nearestwaypointtimeout = -1;
1147         }
1148
1149         if(this.message == "")
1150                 this.message = "went backwards";
1151         if (this.message2 == "")
1152                 this.message2 = "was pushed backwards by";
1153         if (this.race_penalty_reason == "")
1154                 this.race_penalty_reason = "missing a checkpoint";
1155
1156         if(this.classname == "target_startTimer")
1157                 this.race_checkpoint = 0;
1158         else
1159                 this.race_checkpoint = -2;
1160
1161         race_timed_checkpoint = 1;
1162
1163         if (!g_race_targets)
1164                 g_race_targets = IL_NEW();
1165         IL_PUSH(g_race_targets, this);
1166
1167         // trigger_race_checkpoint_verify checks this list too
1168         if (!g_racecheckpoints)
1169                 g_racecheckpoints = IL_NEW();
1170
1171         InitializeEntity(this, trigger_race_checkpoint_verify, INITPRIO_FINDTARGET);
1172 }
1173
1174 spawnfunc(target_checkpoint)
1175 {
1176         // xonotic defrag entity
1177         target_checkpoint_setup(this);
1178 }
1179
1180 // compatibility entity names
1181 spawnfunc(target_startTimer) { target_checkpoint_setup(this); }
1182 spawnfunc(target_stopTimer) { target_checkpoint_setup(this); }
1183
1184 void race_AbandonRaceCheck(entity p)
1185 {
1186         if(race_completing && !CS(p).race_completed)
1187         {
1188                 CS(p).race_completed = 1;
1189                 MAKE_INDEPENDENT_PLAYER(p);
1190                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_ABANDONED, p.netname);
1191                 ClientData_Touch(p);
1192         }
1193 }
1194
1195 void race_StartCompleting()
1196 {
1197         race_completing = 1;
1198         FOREACH_CLIENT(IS_PLAYER(it) && IS_DEAD(it), { race_AbandonRaceCheck(it); });
1199 }
1200
1201 void race_PreparePlayer(entity this)
1202 {
1203         race_ClearTime(this);
1204         this.race_place = 0;
1205         this.race_started = 0;
1206         this.race_respawn_checkpoint = 0;
1207         this.race_respawn_spotref = NULL;
1208 }
1209
1210 void race_RetractPlayer(entity this)
1211 {
1212         if(!g_race && !g_cts)
1213                 return;
1214         if(this.race_respawn_checkpoint == 0 || this.race_respawn_checkpoint == race_timed_checkpoint)
1215                 race_ClearTime(this);
1216         this.race_checkpoint = this.race_respawn_checkpoint;
1217 }
1218
1219 spawnfunc(info_player_race)
1220 {
1221         if(!g_race && !g_cts) { delete(this); return; }
1222         ++race_spawns;
1223         spawnfunc_info_player_deathmatch(this);
1224
1225         if(this.race_place > race_highest_place_spawn)
1226                 race_highest_place_spawn = this.race_place;
1227         if(this.race_place < race_lowest_place_spawn)
1228                 race_lowest_place_spawn = this.race_place;
1229 }
1230
1231 void race_ClearRecords()
1232 {
1233         for(int j = 0; j < MAX_CHECKPOINTS; ++j)
1234         {
1235                 race_checkpoint_records[j] = 0;
1236                 strfree(race_checkpoint_recordholders[j]);
1237         }
1238
1239         FOREACH_CLIENT(true, {
1240                 float p = it.race_place;
1241                 race_PreparePlayer(it);
1242                 it.race_place = p;
1243         });
1244 }
1245
1246 void race_ImposePenaltyTime(entity pl, float penalty, string reason)
1247 {
1248         if(g_race_qualifying)
1249         {
1250                 pl.race_penalty_accumulator += penalty;
1251                 if(IS_REAL_CLIENT(pl))
1252                 {
1253                         msg_entity = pl;
1254                         WRITESPECTATABLE_MSG_ONE(msg_entity, {
1255                                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
1256                                 WriteByte(MSG_ONE, RACE_NET_PENALTY_QUALIFYING);
1257                                 WriteShort(MSG_ONE, TIME_ENCODE(penalty));
1258                                 WriteString(MSG_ONE, reason);
1259                         });
1260                 }
1261         }
1262         else
1263         {
1264                 pl.race_penalty = time + penalty;
1265                 if(IS_REAL_CLIENT(pl))
1266                 {
1267                         msg_entity = pl;
1268                         WRITESPECTATABLE_MSG_ONE(msg_entity, {
1269                                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
1270                                 WriteByte(MSG_ONE, RACE_NET_PENALTY_RACE);
1271                                 WriteShort(MSG_ONE, TIME_ENCODE(penalty));
1272                                 WriteString(MSG_ONE, reason);
1273                         });
1274                 }
1275         }
1276 }
1277
1278 void penalty_touch(entity this, entity toucher)
1279 {
1280         EXACTTRIGGER_TOUCH(this, toucher);
1281         if(toucher.race_lastpenalty != this)
1282         {
1283                 toucher.race_lastpenalty = this;
1284                 race_ImposePenaltyTime(toucher, this.race_penalty, this.race_penalty_reason);
1285         }
1286 }
1287
1288 void penalty_use(entity this, entity actor, entity trigger)
1289 {
1290         race_ImposePenaltyTime(actor, this.race_penalty, this.race_penalty_reason);
1291 }
1292
1293 spawnfunc(trigger_race_penalty)
1294 {
1295         // TODO: find out why this wasnt done:
1296         //if(!g_cts && !g_race) { remove(this); return; }
1297
1298         EXACTTRIGGER_INIT;
1299
1300         this.use = penalty_use;
1301         if (!(this.spawnflags & 1))
1302                 settouch(this, penalty_touch);
1303
1304         if (this.race_penalty_reason == "")
1305                 this.race_penalty_reason = "missing a checkpoint";
1306         if (!this.race_penalty)
1307                 this.race_penalty = 5;
1308 }
1309
1310 float race_GetFractionalLapCount(entity e)
1311 {
1312         // interesting metrics (idea by KrimZon) to maybe sort players in the
1313         // scoreboard, immediately updates when overtaking
1314         //
1315         // requires the track to be built so you never get farther away from the
1316         // next checkpoint, though, and current Xonotic race maps are not built that
1317         // way
1318         //
1319         // also, this code is slow and would need optimization (i.e. "next CP"
1320         // links on CP entities)
1321
1322         float l;
1323         l = GameRules_scoring_add(e, RACE_LAPS, 0);
1324         if(CS(e).race_completed)
1325                 return l; // not fractional
1326
1327         vector o0, o1;
1328         float bestfraction, fraction;
1329         entity lastcp;
1330         float nextcpindex, lastcpindex;
1331
1332         nextcpindex = max(e.race_checkpoint, 0);
1333         lastcpindex = e.race_respawn_checkpoint;
1334         lastcp = e.race_respawn_spotref;
1335
1336         if(nextcpindex == lastcpindex)
1337                 return l; // finish
1338
1339         bestfraction = 1;
1340         IL_EACH(g_racecheckpoints, true,
1341         {
1342                 if(it.race_checkpoint != lastcpindex)
1343                         continue;
1344                 if(lastcp)
1345                         if(it != lastcp)
1346                                 continue;
1347                 o0 = (it.absmin + it.absmax) * 0.5;
1348                 IL_EACH(g_racecheckpoints, true,
1349                 {
1350                         if(it.race_checkpoint != nextcpindex)
1351                                 continue;
1352                         o1 = (it.absmin + it.absmax) * 0.5;
1353                         if(o0 == o1)
1354                                 continue;
1355                         fraction = bound(0.0001, vlen(e.origin - o1) / vlen(o0 - o1), 1);
1356                         if(fraction < bestfraction)
1357                                 bestfraction = fraction;
1358                 });
1359         });
1360
1361         // we are at CP "nextcpindex - bestfraction"
1362         // race_timed_checkpoint == 4: then nextcp==4 means 0.9999x, nextcp==0 means 0.0000x
1363         // race_timed_checkpoint == 0: then nextcp==0 means 0.9999x
1364         float c, nc;
1365         nc = race_highest_checkpoint + 1;
1366         c = ((nextcpindex - race_timed_checkpoint + nc + nc - 1) % nc) + 1 - bestfraction;
1367
1368         return l + c / nc;
1369 }