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