]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/race.qc
Merge branch 'martin-t/units' into '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, LAMBDA(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, true,
816         {
817                 entity cpt = it;
818                 FOREACH_ENTITY_STRING(target, cpt.targetname,
819                 {
820                         vector org = (it.absmin + it.absmax) * 0.5;
821                         if(cpt.race_checkpoint == 0)
822                                 WaypointSprite_SpawnFixed(WP_RaceStart, org, it, sprite, RADARICON_NONE);
823                         else
824                                 WaypointSprite_SpawnFixed(WP_RaceCheckpoint, org, it, sprite, RADARICON_NONE);
825
826                         it.sprite.realowner = cpt;
827                         it.sprite.waypointsprite_visible_for_player = race_waypointsprite_visible_for_player;
828                 });
829         });
830
831         if (race_timed_checkpoint) {
832                 if (defrag_ents) {
833                         IL_EACH(g_race_targets, true,
834                         {
835                                 entity cpt = it;
836                                 if(it.classname == "target_startTimer" || it.classname == "target_stopTimer") {
837                                         FOREACH_ENTITY_STRING(target, cpt.targetname, {
838                                                 WaypointSprite_UpdateSprites(it.sprite, ((cpt.classname == "target_startTimer") ? WP_RaceStart : WP_RaceFinish), WP_Null, WP_Null);
839                                         });
840                                 }
841                                 if(it.classname == "target_checkpoint") {
842                                         if(it.race_checkpoint == -2)
843                                                 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
844                                 }
845                         });
846                         if (defragcpexists != -1) {
847                                 float largest_cp_id = 0;
848                                 for (entity cp = NULL; (cp = find(cp, classname, "target_checkpoint"));) {
849                                         if (cp.race_checkpoint > largest_cp_id) {
850                                                 largest_cp_id = cp.race_checkpoint;
851                     }
852                 }
853                                 for (entity cp = NULL; (cp = find(cp, classname, "target_stopTimer"));) {
854                                         cp.race_checkpoint = largest_cp_id + 1; // finish line
855                 }
856                                 race_highest_checkpoint = largest_cp_id + 1;
857                                 race_timed_checkpoint = largest_cp_id + 1;
858                         } else {
859                                 for (entity cp = NULL; (cp = find(cp, classname, "target_stopTimer"));) {
860                                         cp.race_checkpoint = 255; // finish line
861                 }
862                                 race_highest_checkpoint = 255;
863                                 race_timed_checkpoint = 255;
864                         }
865                 } else {
866                         IL_EACH(g_racecheckpoints, it.sprite,
867                         {
868                                 if (it.race_checkpoint == 0) {
869                                         WaypointSprite_UpdateSprites(it.sprite, WP_RaceStart, WP_Null, WP_Null);
870                 } else if (it.race_checkpoint == race_timed_checkpoint) {
871                                         WaypointSprite_UpdateSprites(it.sprite, WP_RaceFinish, WP_Null, WP_Null);
872                                 }
873             });
874                 }
875         }
876
877         if (defrag_ents) {
878                 for (entity trigger = NULL; (trigger = find(trigger, classname, "trigger_multiple")); ) {
879                         for (entity targ = NULL; (targ = find(targ, targetname, trigger.target)); ) {
880                                 if (targ.classname == "target_checkpoint" || targ.classname == "target_startTimer" || targ.classname == "target_stopTimer") {
881                                         trigger.wait = 0;
882                                         trigger.delay = 0;
883                                         targ.wait = 0;
884                                         targ.delay = 0;
885
886                     // These just make the game crash on some maps with oddly shaped triggers.
887                     // (on the other hand they used to fix the case when two players ran through a checkpoint at once,
888                     // and often one of them just passed through without being registered. Hope it's fixed  in a better way now.
889                     // (happened on item triggers too)
890                     //
891                                         //targ.wait = -2;
892                                         //targ.delay = 0;
893
894                                         //setsize(targ, trigger.mins, trigger.maxs);
895                                         //setorigin(targ, trigger.origin);
896                                         //remove(trigger);
897                                 }
898             }
899         }
900         }
901 }
902
903 vector trigger_race_checkpoint_spawn_evalfunc(entity this, entity player, entity spot, vector current)
904 {
905         if(g_race_qualifying)
906         {
907                 // spawn at first
908                 if(this.race_checkpoint != 0)
909                         return '-1 0 0';
910                 if(spot.race_place != race_lowest_place_spawn)
911                         return '-1 0 0';
912         }
913         else
914         {
915                 if(this.race_checkpoint != player.race_respawn_checkpoint)
916                         return '-1 0 0';
917                 // try reusing the previous spawn
918                 if(this == player.race_respawn_spotref || spot == player.race_respawn_spotref)
919                         current.x += SPAWN_PRIO_RACE_PREVIOUS_SPAWN;
920                 if(this.race_checkpoint == 0)
921                 {
922                         int pl = player.race_place;
923                         if(pl > race_highest_place_spawn)
924                                 pl = 0;
925                         if(pl == 0 && !player.race_started)
926                                 pl = race_highest_place_spawn; // use last place if he has not even touched finish yet
927                         if(spot.race_place != pl)
928                                 return '-1 0 0';
929                 }
930         }
931         return current;
932 }
933
934 spawnfunc(trigger_race_checkpoint)
935 {
936         vector o;
937         if(!g_race && !g_cts) { delete(this); return; }
938
939         EXACTTRIGGER_INIT;
940
941         this.use = checkpoint_use;
942         if (!(this.spawnflags & 1))
943                 settouch(this, checkpoint_touch);
944
945         o = (this.absmin + this.absmax) * 0.5;
946         tracebox(o, PL_MIN_CONST, PL_MAX_CONST, o - '0 0 1' * (o.z - this.absmin.z), MOVE_NORMAL, this);
947         waypoint_spawnforitem_force(this, trace_endpos);
948         this.nearestwaypointtimeout = -1;
949
950         if(this.message == "")
951                 this.message = "went backwards";
952         if (this.message2 == "")
953                 this.message2 = "was pushed backwards by";
954         if (this.race_penalty_reason == "")
955                 this.race_penalty_reason = "missing a checkpoint";
956
957         this.race_checkpoint = this.cnt;
958
959         if(this.race_checkpoint > race_highest_checkpoint)
960         {
961                 race_highest_checkpoint = this.race_checkpoint;
962                 if(this.spawnflags & 8)
963                         race_timed_checkpoint = this.race_checkpoint;
964                 else
965                         race_timed_checkpoint = 0;
966         }
967
968         if(!this.race_penalty)
969         {
970                 if(this.race_checkpoint)
971                         WaypointSprite_SpawnFixed(WP_RaceCheckpoint, o, this, sprite, RADARICON_NONE);
972                 else
973                         WaypointSprite_SpawnFixed(WP_RaceStartFinish, o, this, sprite, RADARICON_NONE);
974         }
975
976         this.sprite.waypointsprite_visible_for_player = race_waypointsprite_visible_for_player;
977         this.spawn_evalfunc = trigger_race_checkpoint_spawn_evalfunc;
978
979         IL_PUSH(g_racecheckpoints, this);
980
981         InitializeEntity(this, trigger_race_checkpoint_verify, INITPRIO_FINDTARGET);
982 }
983
984 spawnfunc(target_checkpoint) // defrag entity
985 {
986         if(!g_race && !g_cts) { delete(this); return; }
987         defrag_ents = 1;
988
989         // if this is targeted, then it probably isn't a trigger
990         bool is_trigger = !boolean(!this.nottargeted && this.targetname != "");
991
992         if(is_trigger)
993                 EXACTTRIGGER_INIT;
994
995         this.use = checkpoint_use;
996         if (is_trigger && !(this.spawnflags & 1))
997                 settouch(this, checkpoint_touch);
998
999         vector org = this.origin;
1000
1001         // bots should only pathfind to this if it is a valid touchable trigger
1002         if(is_trigger)
1003         {
1004                 org = (this.absmin + this.absmax) * 0.5;
1005                 tracebox(org, PL_MIN_CONST, PL_MAX_CONST, org - '0 0 1' * (org.z - this.absmin.z), MOVE_NORMAL, this);
1006                 waypoint_spawnforitem_force(this, trace_endpos);
1007                 this.nearestwaypointtimeout = -1;
1008         }
1009
1010         if(this.message == "")
1011                 this.message = "went backwards";
1012         if (this.message2 == "")
1013                 this.message2 = "was pushed backwards by";
1014         if (this.race_penalty_reason == "")
1015                 this.race_penalty_reason = "missing a checkpoint";
1016
1017         if(this.classname == "target_startTimer")
1018                 this.race_checkpoint = 0;
1019         else
1020                 this.race_checkpoint = -2;
1021
1022         race_timed_checkpoint = 1;
1023
1024         IL_PUSH(g_race_targets, this);
1025
1026         InitializeEntity(this, trigger_race_checkpoint_verify, INITPRIO_FINDTARGET);
1027 }
1028
1029 spawnfunc(target_startTimer) { spawnfunc_target_checkpoint(this); }
1030 spawnfunc(target_stopTimer) { spawnfunc_target_checkpoint(this); }
1031
1032 void race_AbandonRaceCheck(entity p)
1033 {
1034         if(race_completing && !CS(p).race_completed)
1035         {
1036                 CS(p).race_completed = 1;
1037                 MAKE_INDEPENDENT_PLAYER(p);
1038                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_RACE_ABANDONED, p.netname);
1039                 ClientData_Touch(p);
1040         }
1041 }
1042
1043 void race_StartCompleting()
1044 {
1045         race_completing = 1;
1046         FOREACH_CLIENT(IS_PLAYER(it) && IS_DEAD(it), LAMBDA(race_AbandonRaceCheck(it)));
1047 }
1048
1049 void race_PreparePlayer(entity this)
1050 {
1051         race_ClearTime(this);
1052         this.race_place = 0;
1053         this.race_started = 0;
1054         this.race_respawn_checkpoint = 0;
1055         this.race_respawn_spotref = NULL;
1056 }
1057
1058 void race_RetractPlayer(entity this)
1059 {
1060         if(!g_race && !g_cts)
1061                 return;
1062         if(this.race_respawn_checkpoint == 0 || this.race_respawn_checkpoint == race_timed_checkpoint)
1063                 race_ClearTime(this);
1064         this.race_checkpoint = this.race_respawn_checkpoint;
1065 }
1066
1067 spawnfunc(info_player_race)
1068 {
1069         if(!g_race && !g_cts) { delete(this); return; }
1070         ++race_spawns;
1071         spawnfunc_info_player_deathmatch(this);
1072
1073         if(this.race_place > race_highest_place_spawn)
1074                 race_highest_place_spawn = this.race_place;
1075         if(this.race_place < race_lowest_place_spawn)
1076                 race_lowest_place_spawn = this.race_place;
1077 }
1078
1079 void race_ClearRecords()
1080 {
1081         for(int j = 0; j < MAX_CHECKPOINTS; ++j)
1082         {
1083                 race_checkpoint_records[j] = 0;
1084                 if(race_checkpoint_recordholders[j])
1085                         strunzone(race_checkpoint_recordholders[j]);
1086                 race_checkpoint_recordholders[j] = string_null;
1087         }
1088
1089         FOREACH_CLIENT(true, LAMBDA(
1090                 float p = it.race_place;
1091                 race_PreparePlayer(it);
1092                 it.race_place = p;
1093         ));
1094 }
1095
1096 void race_ImposePenaltyTime(entity pl, float penalty, string reason)
1097 {
1098         if(g_race_qualifying)
1099         {
1100                 pl.race_penalty_accumulator += penalty;
1101                 if(IS_REAL_CLIENT(pl))
1102                 {
1103                         msg_entity = pl;
1104                         WRITESPECTATABLE_MSG_ONE(msg_entity, {
1105                                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
1106                                 WriteByte(MSG_ONE, RACE_NET_PENALTY_QUALIFYING);
1107                                 WriteShort(MSG_ONE, TIME_ENCODE(penalty));
1108                                 WriteString(MSG_ONE, reason);
1109                         });
1110                 }
1111         }
1112         else
1113         {
1114                 pl.race_penalty = time + penalty;
1115                 if(IS_REAL_CLIENT(pl))
1116                 {
1117                         msg_entity = pl;
1118                         WRITESPECTATABLE_MSG_ONE(msg_entity, {
1119                                 WriteHeader(MSG_ONE, TE_CSQC_RACE);
1120                                 WriteByte(MSG_ONE, RACE_NET_PENALTY_RACE);
1121                                 WriteShort(MSG_ONE, TIME_ENCODE(penalty));
1122                                 WriteString(MSG_ONE, reason);
1123                         });
1124                 }
1125         }
1126 }
1127
1128 void penalty_touch(entity this, entity toucher)
1129 {
1130         EXACTTRIGGER_TOUCH(this, toucher);
1131         if(toucher.race_lastpenalty != this)
1132         {
1133                 toucher.race_lastpenalty = this;
1134                 race_ImposePenaltyTime(toucher, this.race_penalty, this.race_penalty_reason);
1135         }
1136 }
1137
1138 void penalty_use(entity this, entity actor, entity trigger)
1139 {
1140         race_ImposePenaltyTime(actor, this.race_penalty, this.race_penalty_reason);
1141 }
1142
1143 spawnfunc(trigger_race_penalty)
1144 {
1145         // TODO: find out why this wasnt done:
1146         //if(!g_cts && !g_race) { remove(this); return; }
1147
1148         EXACTTRIGGER_INIT;
1149
1150         this.use = penalty_use;
1151         if (!(this.spawnflags & 1))
1152                 settouch(this, penalty_touch);
1153
1154         if (this.race_penalty_reason == "")
1155                 this.race_penalty_reason = "missing a checkpoint";
1156         if (!this.race_penalty)
1157                 this.race_penalty = 5;
1158 }
1159
1160 float race_GetFractionalLapCount(entity e)
1161 {
1162         // interesting metrics (idea by KrimZon) to maybe sort players in the
1163         // scoreboard, immediately updates when overtaking
1164         //
1165         // requires the track to be built so you never get farther away from the
1166         // next checkpoint, though, and current Xonotic race maps are not built that
1167         // way
1168         //
1169         // also, this code is slow and would need optimization (i.e. "next CP"
1170         // links on CP entities)
1171
1172         float l;
1173         l = PlayerScore_Add(e, SP_RACE_LAPS, 0);
1174         if(CS(e).race_completed)
1175                 return l; // not fractional
1176
1177         vector o0, o1;
1178         float bestfraction, fraction;
1179         entity lastcp;
1180         float nextcpindex, lastcpindex;
1181
1182         nextcpindex = max(e.race_checkpoint, 0);
1183         lastcpindex = e.race_respawn_checkpoint;
1184         lastcp = e.race_respawn_spotref;
1185
1186         if(nextcpindex == lastcpindex)
1187                 return l; // finish
1188
1189         bestfraction = 1;
1190         IL_EACH(g_racecheckpoints, true,
1191         {
1192                 if(it.race_checkpoint != lastcpindex)
1193                         continue;
1194                 if(lastcp)
1195                         if(it != lastcp)
1196                                 continue;
1197                 o0 = (it.absmin + it.absmax) * 0.5;
1198                 IL_EACH(g_racecheckpoints, true,
1199                 {
1200                         if(it.race_checkpoint != nextcpindex)
1201                                 continue;
1202                         o1 = (it.absmin + it.absmax) * 0.5;
1203                         if(o0 == o1)
1204                                 continue;
1205                         fraction = bound(0.0001, vlen(e.origin - o1) / vlen(o0 - o1), 1);
1206                         if(fraction < bestfraction)
1207                                 bestfraction = fraction;
1208                 });
1209         });
1210
1211         // we are at CP "nextcpindex - bestfraction"
1212         // race_timed_checkpoint == 4: then nextcp==4 means 0.9999x, nextcp==0 means 0.0000x
1213         // race_timed_checkpoint == 0: then nextcp==0 means 0.9999x
1214         float c, nc;
1215         nc = race_highest_checkpoint + 1;
1216         c = ((nextcpindex - race_timed_checkpoint + nc + nc - 1) % nc) + 1 - bestfraction;
1217
1218         return l + c / nc;
1219 }