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