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