]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/race.qc
Impulses: migration pathway
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / race.qc
1 #include "race.qh"
2
3 #include "cl_client.qh"
4 #include "portals.qh"
5 #include "scores.qh"
6 #include "spawnpoints.qh"
7 #include "bot/waypoints.qh"
8 #include "bot/navigation.qh"
9 #include "command/getreplies.qh"
10 #include "../common/deathtypes/all.qh"
11 #include "../common/notifications.qh"
12 #include "../common/mapinfo.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(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({
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_VARNAME(dummy3, {
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, world, 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, world, 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, world, 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, world, 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, world, 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, world, 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         entity p;
361
362         if(g_race_qualifying)
363                 t += e.race_penalty_accumulator;
364
365         t = TIME_ENCODE(t); // make integer
366         // adding just 0.4 so it rounds down in the .5 case (matching the timer display)
367
368         if(tvalid)
369         if(cp == race_timed_checkpoint) // finish line
370         if (!e.race_completed)
371         {
372                 float s;
373                 if(g_race_qualifying)
374                 {
375                         s = PlayerScore_Add(e, SP_RACE_FASTEST, 0);
376                         if(!s || t < s)
377                                 PlayerScore_Add(e, SP_RACE_FASTEST, t - s);
378                 }
379                 else
380                 {
381                         s = PlayerScore_Add(e, SP_RACE_FASTEST, 0);
382                         if(!s || t < s)
383                                 PlayerScore_Add(e, SP_RACE_FASTEST, t - s);
384
385                         s = PlayerScore_Add(e, SP_RACE_TIME, 0);
386                         snew = TIME_ENCODE(time - game_starttime);
387                         PlayerScore_Add(e, SP_RACE_TIME, snew - s);
388                         l = PlayerTeamScore_Add(e, SP_RACE_LAPS, ST_RACE_LAPS, 1);
389
390                         if(autocvar_fraglimit)
391                                 if(l >= autocvar_fraglimit)
392                                         race_StartCompleting();
393
394                         if(race_completing)
395                         {
396                                 e.race_completed = 1;
397                                 MAKE_INDEPENDENT_PLAYER(e);
398                                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_RACE_FINISHED, e.netname);
399                                 ClientData_Touch(e);
400                         }
401                 }
402         }
403
404         float recordtime;
405         string recordholder;
406         if(g_race_qualifying)
407         {
408                 if(tvalid)
409                 {
410                         recordtime = race_checkpoint_records[cp];
411                         recordholder = strcat1(race_checkpoint_recordholders[cp]); // make a tempstring copy, as we'll possibly strunzone it!
412                         if(recordholder == e.netname)
413                                 recordholder = "";
414
415                         if(t != 0)
416                         {
417                                 if(cp == race_timed_checkpoint)
418                                 {
419                                         race_setTime(GetMapname(), t, e.crypto_idfp, e.netname, e);
420                                         MUTATOR_CALLHOOK(Race_FinalCheckpoint, e);
421                                 }
422                                 if(t < recordtime || recordtime == 0)
423                                 {
424                                         race_checkpoint_records[cp] = t;
425                                         if(race_checkpoint_recordholders[cp])
426                                                 strunzone(race_checkpoint_recordholders[cp]);
427                                         race_checkpoint_recordholders[cp] = strzone(e.netname);
428                                         if(g_race_qualifying)
429                                         {
430                                                 FOR_EACH_REALPLAYER(p)
431                                                         if(p.race_checkpoint == cp)
432                                                                 race_SendNextCheckpoint(p, 0);
433                                         }
434                                 }
435                         }
436                 }
437                 else
438                 {
439                         // dummies
440                         t = 0;
441                         recordtime = 0;
442                         recordholder = "";
443                 }
444
445                 if(IS_REAL_CLIENT(e))
446                 {
447                         msg_entity = e;
448                         if(g_race_qualifying)
449                         {
450                                 WRITESPECTATABLE_MSG_ONE_VARNAME(dummy1, {
451                                         WriteHeader(MSG_ONE, TE_CSQC_RACE);
452                                         WriteByte(MSG_ONE, RACE_NET_CHECKPOINT_HIT_QUALIFYING);
453                                         WriteByte(MSG_ONE, race_CheckpointNetworkID(cp)); // checkpoint the player now is at
454                                         WriteInt24_t(MSG_ONE, t); // time to that intermediate
455                                         WriteInt24_t(MSG_ONE, recordtime); // previously best time
456                                         WriteString(MSG_ONE, recordholder); // record holder
457                                 });
458                         }
459                 }
460         }
461         else // RACE! Not Qualifying
462         {
463                 float lself, lother, othtime;
464                 entity oth;
465                 oth = race_checkpoint_lastplayers[cp];
466                 if(oth)
467                 {
468                         lself = PlayerScore_Add(e, SP_RACE_LAPS, 0);
469                         lother = race_checkpoint_lastlaps[cp];
470                         othtime = race_checkpoint_lasttimes[cp];
471                 }
472                 else
473                         lself = lother = othtime = 0;
474
475                 if(IS_REAL_CLIENT(e))
476                 {
477                         msg_entity = e;
478                         WRITESPECTATABLE_MSG_ONE_VARNAME(dummy2, {
479                                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
480                                 WriteByte(MSG_ONE, RACE_NET_CHECKPOINT_HIT_RACE);
481                                 WriteByte(MSG_ONE, race_CheckpointNetworkID(cp)); // checkpoint the player now is at
482                                 if(e == oth)
483                                 {
484                                         WriteInt24_t(MSG_ONE, 0);
485                                         WriteByte(MSG_ONE, 0);
486                                         WriteString(MSG_ONE, "");
487                                 }
488                                 else
489                                 {
490                                         WriteInt24_t(MSG_ONE, TIME_ENCODE(time - race_checkpoint_lasttimes[cp]));
491                                         WriteByte(MSG_ONE, lself - lother);
492                                         WriteString(MSG_ONE, oth.netname); // record holder
493                                 }
494                         });
495                 }
496
497                 race_checkpoint_lastplayers[cp] = e;
498                 race_checkpoint_lasttimes[cp] = time;
499                 race_checkpoint_lastlaps[cp] = lself;
500
501                 if(IS_REAL_CLIENT(oth))
502                 {
503                         msg_entity = oth;
504                         WRITESPECTATABLE_MSG_ONE_VARNAME(dummy3, {
505                                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
506                                 WriteByte(MSG_ONE, RACE_NET_CHECKPOINT_HIT_RACE_BY_OPPONENT);
507                                 WriteByte(MSG_ONE, race_CheckpointNetworkID(cp)); // checkpoint the player now is at
508                                 if(e == oth)
509                                 {
510                                         WriteInt24_t(MSG_ONE, 0);
511                                         WriteByte(MSG_ONE, 0);
512                                         WriteString(MSG_ONE, "");
513                                 }
514                                 else
515                                 {
516                                         WriteInt24_t(MSG_ONE, TIME_ENCODE(time - othtime));
517                                         WriteByte(MSG_ONE, lother - lself);
518                                         WriteString(MSG_ONE, e.netname); // record holder
519                                 }
520                         });
521                 }
522         }
523 }
524
525 void race_ClearTime(entity e)
526 {
527         e.race_checkpoint = 0;
528         e.race_laptime = 0;
529         e.race_movetime = e.race_movetime_frac = e.race_movetime_count = 0;
530         e.race_penalty_accumulator = 0;
531         e.race_lastpenalty = world;
532
533         if(!IS_REAL_CLIENT(e))
534                 return;
535
536         msg_entity = e;
537         WRITESPECTATABLE_MSG_ONE({
538                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
539                 WriteByte(MSG_ONE, RACE_NET_CHECKPOINT_CLEAR); // next
540         });
541 }
542
543 void dumpsurface(entity e)
544 {
545         float n, si, ni;
546         vector norm, vec;
547         LOG_INFO("Surfaces of ", etos(e), ":\n");
548
549         LOG_INFO("TEST = ", ftos(getsurfacenearpoint(e, '0 0 0')), "\n");
550
551         for(si = 0; ; ++si)
552         {
553                 n = getsurfacenumpoints(e, si);
554                 if(n <= 0)
555                         break;
556                 LOG_INFO("  Surface ", ftos(si), ":\n");
557                 norm = getsurfacenormal(e, si);
558                 LOG_INFO("    Normal = ", vtos(norm), "\n");
559                 for(ni = 0; ni < n; ++ni)
560                 {
561                         vec = getsurfacepoint(e, si, ni);
562                         LOG_INFO("    Point ", ftos(ni), " = ", vtos(vec), " (", ftos(norm * vec), ")\n");
563                 }
564         }
565 }
566
567 void checkpoint_passed()
568 {SELFPARAM();
569         string oldmsg;
570         entity cp;
571
572         if(other.classname == "porto")
573         {
574                 // do not allow portalling through checkpoints
575                 trace_plane_normal = normalize(-1 * other.velocity);
576                 setself(other);
577                 W_Porto_Fail(0);
578                 return;
579         }
580
581         /*
582          * Trigger targets
583          */
584         if (!((self.spawnflags & 2) && (IS_PLAYER(other))))
585         {
586                 activator = other;
587                 oldmsg = self.message;
588                 self.message = "";
589                 SUB_UseTargets();
590                 self.message = oldmsg;
591         }
592
593         if (!IS_PLAYER(other))
594                 return;
595
596         /*
597          * Remove unauthorized equipment
598          */
599         Portal_ClearAll(other);
600
601         other.porto_forbidden = 2; // decreased by 1 each StartFrame
602
603         if(defrag_ents)
604         {
605                 if(self.race_checkpoint == -2)
606                 {
607                         self.race_checkpoint = other.race_checkpoint;
608                 }
609
610                 float largest_cp_id = 0;
611                 float cp_amount = 0;
612                 for(cp = world; (cp = find(cp, classname, "target_checkpoint"));)
613                 {
614                         cp_amount += 1;
615                         if(cp.race_checkpoint > largest_cp_id) // update the finish id if someone hit a new checkpoint
616                         {
617                                 largest_cp_id = cp.race_checkpoint;
618                                 for(cp = world; (cp = find(cp, classname, "target_stopTimer"));)
619                                         cp.race_checkpoint = largest_cp_id + 1; // finish line
620                                 race_highest_checkpoint = largest_cp_id + 1;
621                                 race_timed_checkpoint = largest_cp_id + 1;
622
623                                 for(cp = world; (cp = find(cp, classname, "target_checkpoint"));)
624                                 {
625                                         if(cp.race_checkpoint == -2) // set defragcpexists to -1 so that the cp id file will be rewritten when someone finishes
626                                                 defragcpexists = -1;
627                                 }
628                         }
629                 }
630                 if(cp_amount == 0)
631                 {
632                         for(cp = world; (cp = find(cp, classname, "target_stopTimer"));)
633                                 cp.race_checkpoint = 1;
634                         race_highest_checkpoint = 1;
635                         race_timed_checkpoint = 1;
636                 }
637         }
638
639         if((other.race_checkpoint == -1 && self.race_checkpoint == 0) || (other.race_checkpoint == self.race_checkpoint))
640         {
641                 if(self.race_penalty)
642                 {
643                         if(other.race_lastpenalty != self)
644                         {
645                                 other.race_lastpenalty = self;
646                                 race_ImposePenaltyTime(other, self.race_penalty, self.race_penalty_reason);
647                         }
648                 }
649
650                 if(other.race_penalty)
651                         return;
652
653                 /*
654                  * Trigger targets
655                  */
656                 if(self.spawnflags & 2)
657                 {
658                         activator = other;
659                         oldmsg = self.message;
660                         self.message = "";
661                         SUB_UseTargets();
662                         self.message = oldmsg;
663                 }
664
665                 if(other.race_respawn_checkpoint != self.race_checkpoint || !other.race_started)
666                         other.race_respawn_spotref = self; // this is not a spot but a CP, but spawnpoint selection will deal with that
667                 other.race_respawn_checkpoint = self.race_checkpoint;
668                 other.race_checkpoint = race_NextCheckpoint(self.race_checkpoint);
669                 other.race_started = 1;
670
671                 race_SendTime(other, self.race_checkpoint, other.race_movetime, boolean(other.race_laptime));
672
673                 if(!self.race_checkpoint) // start line
674                 {
675                         other.race_laptime = time;
676                         other.race_movetime = other.race_movetime_frac = other.race_movetime_count = 0;
677                         other.race_penalty_accumulator = 0;
678                         other.race_lastpenalty = world;
679                 }
680
681                 if(g_race_qualifying)
682                         race_SendNextCheckpoint(other, 0);
683
684                 if(defrag_ents && defragcpexists < 0 && self.classname == "target_stopTimer")
685                 {
686                         float fh;
687                         defragcpexists = fh = fopen(strcat("maps/", GetMapname(), ".defragcp"), FILE_WRITE);
688                         if(fh >= 0)
689                         {
690                                 for(cp = world; (cp = find(cp, classname, "target_checkpoint"));)
691                                 fputs(fh, strcat(cp.targetname, " ", ftos(cp.race_checkpoint), "\n"));
692                         }
693                         fclose(fh);
694                 }
695         }
696         else if(other.race_checkpoint == race_NextCheckpoint(self.race_checkpoint))
697         {
698                 // ignored
699         }
700         else
701         {
702                 if(self.spawnflags & 4)
703                         Damage (other, self, self, 10000, DEATH_HURTTRIGGER.m_id, other.origin, '0 0 0');
704         }
705 }
706
707 void checkpoint_touch()
708 {
709         EXACTTRIGGER_TOUCH;
710         checkpoint_passed();
711 }
712
713 void checkpoint_use()
714 {
715         if(other.classname == "info_player_deathmatch") // a spawn, a spawn
716                 return;
717
718         other = activator;
719         checkpoint_passed();
720 }
721
722 float race_waypointsprite_visible_for_player(entity e)
723 {SELFPARAM();
724         if(e.race_checkpoint == -1 || self.owner.race_checkpoint == -2)
725                 return true;
726         else if(e.race_checkpoint == self.owner.race_checkpoint)
727                 return true;
728         else
729                 return false;
730 }
731
732 float have_verified;
733 void trigger_race_checkpoint_verify()
734 {SELFPARAM();
735         entity cp;
736         float i, p;
737         float qual;
738
739         if(have_verified)
740                 return;
741         have_verified = 1;
742
743         qual = g_race_qualifying;
744
745         setself(spawn());
746         self.classname = STR_PLAYER;
747
748         if(g_race)
749         {
750                 for(i = 0; i <= race_highest_checkpoint; ++i)
751                 {
752                         self.race_checkpoint = race_NextCheckpoint(i);
753
754                         // race only (middle of the race)
755                         g_race_qualifying = 0;
756                         self.race_place = 0;
757                         if(!Spawn_FilterOutBadSpots(findchain(classname, "info_player_deathmatch"), 0, false))
758                                 error(strcat("Checkpoint ", ftos(i), " misses a spawnpoint with race_place==", ftos(self.race_place), " (used for respawning in race) - bailing out"));
759
760                         if(i == 0)
761                         {
762                                 // qualifying only
763                                 g_race_qualifying = 1;
764                                 self.race_place = race_lowest_place_spawn;
765                                 if(!Spawn_FilterOutBadSpots(findchain(classname, "info_player_deathmatch"), 0, false))
766                                         error(strcat("Checkpoint ", ftos(i), " misses a spawnpoint with race_place==", ftos(self.race_place), " (used for qualifying) - bailing out"));
767
768                                 // race only (initial spawn)
769                                 g_race_qualifying = 0;
770                                 for(p = 1; p <= race_highest_place_spawn; ++p)
771                                 {
772                                         self.race_place = p;
773                                         if(!Spawn_FilterOutBadSpots(findchain(classname, "info_player_deathmatch"), 0, false))
774                                                 error(strcat("Checkpoint ", ftos(i), " misses a spawnpoint with race_place==", ftos(self.race_place), " (used for initially spawning in race) - bailing out"));
775                                 }
776                         }
777                 }
778         }
779         else if(!defrag_ents)
780         {
781                 // qualifying only
782                 self.race_checkpoint = race_NextCheckpoint(0);
783                 g_race_qualifying = 1;
784                 self.race_place = race_lowest_place_spawn;
785                 if(!Spawn_FilterOutBadSpots(findchain(classname, "info_player_deathmatch"), 0, false))
786                         error(strcat("Checkpoint 0 misses a spawnpoint with race_place==", ftos(self.race_place), " (used for qualifying) - bailing out"));
787         }
788         else
789         {
790                 self.race_checkpoint = race_NextCheckpoint(0);
791                 g_race_qualifying = 1;
792                 self.race_place = 0; // there's only one spawn on defrag maps
793
794                 // check if a defragcp file already exists, then read it and apply the checkpoint order
795                 float fh;
796                 float len;
797                 string l;
798
799                 defragcpexists = fh = fopen(strcat("maps/", GetMapname(), ".defragcp"), FILE_READ);
800                 if(fh >= 0)
801                 {
802                         while((l = fgets(fh)))
803                         {
804                                 len = tokenize_console(l);
805                                 if(len != 2)
806                                 {
807                                         defragcpexists = -1; // something's wrong in the defrag cp file, set defragcpexists to -1 so that it will be rewritten when someone finishes
808                                         continue;
809                                 }
810                                 for(cp = world; (cp = find(cp, classname, "target_checkpoint"));)
811                                         if(argv(0) == cp.targetname)
812                                                 cp.race_checkpoint = stof(argv(1));
813                         }
814                         fclose(fh);
815                 }
816         }
817
818         g_race_qualifying = qual;
819
820         if(race_timed_checkpoint)
821         {
822                 if(defrag_ents)
823                 {
824                         for(cp = world; (cp = find(cp, classname, "target_startTimer"));)
825                                 WaypointSprite_UpdateSprites(cp.sprite, WP_RaceStart, WP_Null, WP_Null);
826                         for(cp = world; (cp = find(cp, classname, "target_stopTimer"));)
827                                 WaypointSprite_UpdateSprites(cp.sprite, WP_RaceFinish, WP_Null, WP_Null);
828
829                         for(cp = world; (cp = find(cp, classname, "target_checkpoint"));)
830                         {
831                                 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
832                                         defragcpexists = -1;
833                         }
834
835                         if(defragcpexists != -1)
836                         {
837                                 float largest_cp_id = 0;
838                                 for(cp = world; (cp = find(cp, classname, "target_checkpoint"));)
839                                         if(cp.race_checkpoint > largest_cp_id)
840                                                 largest_cp_id = cp.race_checkpoint;
841                                 for(cp = world; (cp = find(cp, classname, "target_stopTimer"));)
842                                         cp.race_checkpoint = largest_cp_id + 1; // finish line
843                                 race_highest_checkpoint = largest_cp_id + 1;
844                                 race_timed_checkpoint = largest_cp_id + 1;
845                         }
846                         else
847                         {
848                                 for(cp = world; (cp = find(cp, classname, "target_stopTimer"));)
849                                         cp.race_checkpoint = 255; // finish line
850                                 race_highest_checkpoint = 255;
851                                 race_timed_checkpoint = 255;
852                         }
853                 }
854                 else
855                 {
856                         for(cp = world; (cp = find(cp, classname, "trigger_race_checkpoint")); )
857                                 if(cp.sprite)
858                                 {
859                                         if(cp.race_checkpoint == 0)
860                                                 WaypointSprite_UpdateSprites(cp.sprite, WP_RaceStart, WP_Null, WP_Null);
861                                         else if(cp.race_checkpoint == race_timed_checkpoint)
862                                                 WaypointSprite_UpdateSprites(cp.sprite, WP_RaceFinish, WP_Null, WP_Null);
863                                 }
864                 }
865         }
866
867         if(defrag_ents)
868         {
869                 entity trigger, targ;
870                 for(trigger = world; (trigger = find(trigger, classname, "trigger_multiple")); )
871                         for(targ = world; (targ = find(targ, targetname, trigger.target)); )
872                                 if (targ.classname == "target_checkpoint" || targ.classname == "target_startTimer" || targ.classname == "target_stopTimer")
873                                 {
874                                         trigger.wait = 0;
875                                         trigger.delay = 0;
876                                         targ.wait = 0;
877                                         targ.delay = 0;
878
879                     // These just make the game crash on some maps with oddly shaped triggers.
880                     // (on the other hand they used to fix the case when two players ran through a checkpoint at once,
881                     // and often one of them just passed through without being registered. Hope it's fixed  in a better way now.
882                     // (happened on item triggers too)
883                     //
884                                         //targ.wait = -2;
885                                         //targ.delay = 0;
886
887                                         //setsize(targ, trigger.mins, trigger.maxs);
888                                         //setorigin(targ, trigger.origin);
889                                         //remove(trigger);
890                                 }
891         }
892         remove(self);
893         setself(this);
894 }
895
896 vector trigger_race_checkpoint_spawn_evalfunc(entity player, entity spot, vector current)
897 {SELFPARAM();
898         if(g_race_qualifying)
899         {
900                 // spawn at first
901                 if(self.race_checkpoint != 0)
902                         return '-1 0 0';
903                 if(spot.race_place != race_lowest_place_spawn)
904                         return '-1 0 0';
905         }
906         else
907         {
908                 if(self.race_checkpoint != player.race_respawn_checkpoint)
909                         return '-1 0 0';
910                 // try reusing the previous spawn
911                 if(self == player.race_respawn_spotref || spot == player.race_respawn_spotref)
912                         current.x += SPAWN_PRIO_RACE_PREVIOUS_SPAWN;
913                 if(self.race_checkpoint == 0)
914                 {
915                         float pl;
916                         pl = player.race_place;
917                         if(pl > race_highest_place_spawn)
918                                 pl = 0;
919                         if(pl == 0 && !player.race_started)
920                                 pl = race_highest_place_spawn; // use last place if he has not even touched finish yet
921                         if(spot.race_place != pl)
922                                 return '-1 0 0';
923                 }
924         }
925         return current;
926 }
927
928 spawnfunc(trigger_race_checkpoint)
929 {
930         vector o;
931         if(!g_race && !g_cts) { remove(self); return; }
932
933         EXACTTRIGGER_INIT;
934
935         self.use = checkpoint_use;
936         if (!(self.spawnflags & 1))
937                 self.touch = checkpoint_touch;
938
939         o = (self.absmin + self.absmax) * 0.5;
940         tracebox(o, PL_MIN, PL_MAX, o - '0 0 1' * (o.z - self.absmin.z), MOVE_NORMAL, self);
941         waypoint_spawnforitem_force(self, trace_endpos);
942         self.nearestwaypointtimeout = time + 1000000000;
943
944         if(self.message == "")
945                 self.message = "went backwards";
946         if (self.message2 == "")
947                 self.message2 = "was pushed backwards by";
948         if (self.race_penalty_reason == "")
949                 self.race_penalty_reason = "missing a checkpoint";
950
951         self.race_checkpoint = self.cnt;
952
953         if(self.race_checkpoint > race_highest_checkpoint)
954         {
955                 race_highest_checkpoint = self.race_checkpoint;
956                 if(self.spawnflags & 8)
957                         race_timed_checkpoint = self.race_checkpoint;
958                 else
959                         race_timed_checkpoint = 0;
960         }
961
962         if(!self.race_penalty)
963         {
964                 if(self.race_checkpoint)
965                         WaypointSprite_SpawnFixed(WP_RaceCheckpoint, o, self, sprite, RADARICON_NONE);
966                 else
967                         WaypointSprite_SpawnFixed(WP_RaceStartFinish, o, self, sprite, RADARICON_NONE);
968         }
969
970         self.sprite.waypointsprite_visible_for_player = race_waypointsprite_visible_for_player;
971         self.spawn_evalfunc = trigger_race_checkpoint_spawn_evalfunc;
972
973         InitializeEntity(self, trigger_race_checkpoint_verify, INITPRIO_FINDTARGET);
974 }
975
976 spawnfunc(target_checkpoint) // defrag entity
977 {
978         vector o;
979         if(!g_race && !g_cts) { remove(self); return; }
980         defrag_ents = 1;
981
982         EXACTTRIGGER_INIT;
983
984         self.use = checkpoint_use;
985         if (!(self.spawnflags & 1))
986                 self.touch = checkpoint_touch;
987
988         o = (self.absmin + self.absmax) * 0.5;
989         tracebox(o, PL_MIN, PL_MAX, o - '0 0 1' * (o.z - self.absmin.z), MOVE_NORMAL, self);
990         waypoint_spawnforitem_force(self, trace_endpos);
991         self.nearestwaypointtimeout = time + 1000000000;
992
993         if(self.message == "")
994                 self.message = "went backwards";
995         if (self.message2 == "")
996                 self.message2 = "was pushed backwards by";
997         if (self.race_penalty_reason == "")
998                 self.race_penalty_reason = "missing a checkpoint";
999
1000         if(self.classname == "target_startTimer")
1001                 self.race_checkpoint = 0;
1002         else
1003                 self.race_checkpoint = -2;
1004
1005         race_timed_checkpoint = 1;
1006
1007         if(self.race_checkpoint == 0)
1008                 WaypointSprite_SpawnFixed(WP_RaceStart, o, self, sprite, RADARICON_NONE);
1009         else
1010                 WaypointSprite_SpawnFixed(WP_RaceCheckpoint, o, self, sprite, RADARICON_NONE);
1011
1012         self.sprite.waypointsprite_visible_for_player = race_waypointsprite_visible_for_player;
1013
1014         InitializeEntity(self, trigger_race_checkpoint_verify, INITPRIO_FINDTARGET);
1015 }
1016
1017 spawnfunc(target_startTimer) { spawnfunc_target_checkpoint(this); }
1018 spawnfunc(target_stopTimer) { spawnfunc_target_checkpoint(this); }
1019
1020 void race_AbandonRaceCheck(entity p)
1021 {
1022         if(race_completing && !p.race_completed)
1023         {
1024                 p.race_completed = 1;
1025                 MAKE_INDEPENDENT_PLAYER(p);
1026                 Send_Notification(NOTIF_ALL, world, MSG_INFO, INFO_RACE_ABANDONED, p.netname);
1027                 ClientData_Touch(p);
1028         }
1029 }
1030
1031 void race_StartCompleting()
1032 {
1033         entity p;
1034         race_completing = 1;
1035         FOR_EACH_PLAYER(p)
1036                 if(p.deadflag != DEAD_NO)
1037                         race_AbandonRaceCheck(p);
1038 }
1039
1040 void race_PreparePlayer()
1041 {SELFPARAM();
1042         race_ClearTime(self);
1043         self.race_place = 0;
1044         self.race_started = 0;
1045         self.race_respawn_checkpoint = 0;
1046         self.race_respawn_spotref = world;
1047 }
1048
1049 void race_RetractPlayer()
1050 {SELFPARAM();
1051         if(!g_race && !g_cts)
1052                 return;
1053         if(self.race_respawn_checkpoint == 0 || self.race_respawn_checkpoint == race_timed_checkpoint)
1054                 race_ClearTime(self);
1055         self.race_checkpoint = self.race_respawn_checkpoint;
1056 }
1057
1058 spawnfunc(info_player_race)
1059 {
1060         if(!g_race && !g_cts) { remove(self); return; }
1061         ++race_spawns;
1062         spawnfunc_info_player_deathmatch(this);
1063
1064         if(self.race_place > race_highest_place_spawn)
1065                 race_highest_place_spawn = self.race_place;
1066         if(self.race_place < race_lowest_place_spawn)
1067                 race_lowest_place_spawn = self.race_place;
1068 }
1069
1070 void race_ClearRecords()
1071 {SELFPARAM();
1072         float i;
1073
1074         for(i = 0; i < MAX_CHECKPOINTS; ++i)
1075         {
1076                 race_checkpoint_records[i] = 0;
1077                 if(race_checkpoint_recordholders[i])
1078                         strunzone(race_checkpoint_recordholders[i]);
1079                 race_checkpoint_recordholders[i] = string_null;
1080         }
1081
1082         entity e;
1083         FOR_EACH_CLIENT(e)
1084         {
1085                 float p = e.race_place;
1086                 WITH(entity, self, e, race_PreparePlayer());
1087                 e.race_place = p;
1088         }
1089 }
1090
1091 void race_ImposePenaltyTime(entity pl, float penalty, string reason)
1092 {
1093         if(g_race_qualifying)
1094         {
1095                 pl.race_penalty_accumulator += penalty;
1096                 if(IS_REAL_CLIENT(pl))
1097                 {
1098                         msg_entity = pl;
1099                         WRITESPECTATABLE_MSG_ONE({
1100                                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
1101                                 WriteByte(MSG_ONE, RACE_NET_PENALTY_QUALIFYING);
1102                                 WriteShort(MSG_ONE, TIME_ENCODE(penalty));
1103                                 WriteString(MSG_ONE, reason);
1104                         });
1105                 }
1106         }
1107         else
1108         {
1109                 pl.race_penalty = time + penalty;
1110                 if(IS_REAL_CLIENT(pl))
1111                 {
1112                         msg_entity = pl;
1113                         WRITESPECTATABLE_MSG_ONE_VARNAME(dummy, {
1114                                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
1115                                 WriteByte(MSG_ONE, RACE_NET_PENALTY_RACE);
1116                                 WriteShort(MSG_ONE, TIME_ENCODE(penalty));
1117                                 WriteString(MSG_ONE, reason);
1118                         });
1119                 }
1120         }
1121 }
1122
1123 void penalty_touch()
1124 {SELFPARAM();
1125         EXACTTRIGGER_TOUCH;
1126         if(other.race_lastpenalty != self)
1127         {
1128                 other.race_lastpenalty = self;
1129                 race_ImposePenaltyTime(other, self.race_penalty, self.race_penalty_reason);
1130         }
1131 }
1132
1133 void penalty_use()
1134 {SELFPARAM();
1135         race_ImposePenaltyTime(activator, self.race_penalty, self.race_penalty_reason);
1136 }
1137
1138 spawnfunc(trigger_race_penalty)
1139 {
1140         // TODO: find out why this wasnt done:
1141         //if(!g_cts && !g_race) { remove(self); return; }
1142
1143         EXACTTRIGGER_INIT;
1144
1145         self.use = penalty_use;
1146         if (!(self.spawnflags & 1))
1147                 self.touch = penalty_touch;
1148
1149         if (self.race_penalty_reason == "")
1150                 self.race_penalty_reason = "missing a checkpoint";
1151         if (!self.race_penalty)
1152                 self.race_penalty = 5;
1153 }
1154
1155 float race_GetFractionalLapCount(entity e)
1156 {
1157         // interesting metrics (idea by KrimZon) to maybe sort players in the
1158         // scoreboard, immediately updates when overtaking
1159         //
1160         // requires the track to be built so you never get farther away from the
1161         // next checkpoint, though, and current Xonotic race maps are not built that
1162         // way
1163         //
1164         // also, this code is slow and would need optimization (i.e. "next CP"
1165         // links on CP entities)
1166
1167         float l;
1168         l = PlayerScore_Add(e, SP_RACE_LAPS, 0);
1169         if(e.race_completed)
1170                 return l; // not fractional
1171
1172         vector o0, o1;
1173         float bestfraction, fraction;
1174         entity lastcp, cp0, cp1;
1175         float nextcpindex, lastcpindex;
1176
1177         nextcpindex = max(e.race_checkpoint, 0);
1178         lastcpindex = e.race_respawn_checkpoint;
1179         lastcp = e.race_respawn_spotref;
1180
1181         if(nextcpindex == lastcpindex)
1182                 return l; // finish
1183
1184         bestfraction = 1;
1185         for(cp0 = world; (cp0 = find(cp0, classname, "trigger_race_checkpoint")); )
1186         {
1187                 if(cp0.race_checkpoint != lastcpindex)
1188                         continue;
1189                 if(lastcp)
1190                         if(cp0 != lastcp)
1191                                 continue;
1192                 o0 = (cp0.absmin + cp0.absmax) * 0.5;
1193                 for(cp1 = world; (cp1 = find(cp1, classname, "trigger_race_checkpoint")); )
1194                 {
1195                         if(cp1.race_checkpoint != nextcpindex)
1196                                 continue;
1197                         o1 = (cp1.absmin + cp1.absmax) * 0.5;
1198                         if(o0 == o1)
1199                                 continue;
1200                         fraction = bound(0.0001, vlen(e.origin - o1) / vlen(o0 - o1), 1);
1201                         if(fraction < bestfraction)
1202                                 bestfraction = fraction;
1203                 }
1204         }
1205
1206         // we are at CP "nextcpindex - bestfraction"
1207         // race_timed_checkpoint == 4: then nextcp==4 means 0.9999x, nextcp==0 means 0.0000x
1208         // race_timed_checkpoint == 0: then nextcp==0 means 0.9999x
1209         float c, nc;
1210         nc = race_highest_checkpoint + 1;
1211         c = ((nextcpindex - race_timed_checkpoint + nc + nc - 1) % nc) + 1 - bestfraction;
1212
1213         return l + c / nc;
1214 }