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