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