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