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