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