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