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