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