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