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