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