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