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