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