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