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