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