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