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