Merge branch 'master' into mirceakitsune/sandbox
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / miscfunctions.qc
1 var void remove(entity e);
2 void objerror(string s);
3 void droptofloor();
4 .vector dropped_origin;
5
6 void traceline_antilag (entity source, vector v1, vector v2, float nomonst, entity forent, float lag);
7 void crosshair_trace(entity pl)
8 {
9         traceline_antilag(pl, pl.cursor_trace_start, pl.cursor_trace_start + normalize(pl.cursor_trace_endpos - pl.cursor_trace_start) * MAX_SHOT_DISTANCE, MOVE_NORMAL, pl, ANTILAG_LATENCY(pl));
10 }
11 void crosshair_trace_plusvisibletriggers(entity pl)
12 {
13         entity first;
14         entity e;
15         first = findchainfloat(solid, SOLID_TRIGGER);
16
17         for (e = first; e; e = e.chain)
18                 if (e.model != "")
19                         e.solid = SOLID_BSP;
20
21         crosshair_trace(pl);
22
23         for (e = first; e; e = e.chain)
24                 e.solid = SOLID_TRIGGER;
25 }
26 void WarpZone_traceline_antilag (entity source, vector v1, vector v2, float nomonst, entity forent, float lag);
27 void WarpZone_crosshair_trace(entity pl)
28 {
29         WarpZone_traceline_antilag(pl, pl.cursor_trace_start, pl.cursor_trace_start + normalize(pl.cursor_trace_endpos - pl.cursor_trace_start) * MAX_SHOT_DISTANCE, MOVE_NORMAL, pl, ANTILAG_LATENCY(pl));
30 }
31
32 void() spawnfunc_info_player_deathmatch; // needed for the other spawnpoints
33 void() spawnpoint_use;
34 string GetMapname();
35 string ColoredTeamName(float t);
36
37 string admin_name(void)
38 {
39         if(autocvar_sv_adminnick != "")
40                 return autocvar_sv_adminnick;
41         else
42                 return "SERVER ADMIN";
43 }
44
45 float DistributeEvenly_amount;
46 float DistributeEvenly_totalweight;
47 void DistributeEvenly_Init(float amount, float totalweight)
48 {
49     if (DistributeEvenly_amount)
50     {
51         dprint("DistributeEvenly_Init: UNFINISHED DISTRIBUTION (", ftos(DistributeEvenly_amount), " for ");
52         dprint(ftos(DistributeEvenly_totalweight), " left!)\n");
53     }
54     if (totalweight == 0)
55         DistributeEvenly_amount = 0;
56     else
57         DistributeEvenly_amount = amount;
58     DistributeEvenly_totalweight = totalweight;
59 }
60 float DistributeEvenly_Get(float weight)
61 {
62     float f;
63     if (weight <= 0)
64         return 0;
65     f = floor(0.5 + DistributeEvenly_amount * weight / DistributeEvenly_totalweight);
66     DistributeEvenly_totalweight -= weight;
67     DistributeEvenly_amount -= f;
68     return f;
69 }
70
71 #define move_out_of_solid(e) WarpZoneLib_MoveOutOfSolid(e)
72
73
74 string STR_PLAYER = "player";
75 string STR_SPECTATOR = "spectator";
76 string STR_OBSERVER = "observer";
77
78 #if 0
79 #define FOR_EACH_CLIENT(v) for(v = world; (v = findflags(v, flags, FL_CLIENT)) != world; )
80 #define FOR_EACH_REALCLIENT(v) FOR_EACH_CLIENT(v) if(clienttype(v) == CLIENTTYPE_REAL)
81 #define FOR_EACH_PLAYER(v) for(v = world; (v = find(v, classname, STR_PLAYER)) != world; )
82 #define FOR_EACH_REALPLAYER(v) FOR_EACH_PLAYER(v) if(clienttype(v) == CLIENTTYPE_REAL)
83 #else
84 #define FOR_EACH_CLIENTSLOT(v) for(v = world; (v = nextent(v)) && (num_for_edict(v) <= maxclients); )
85 #define FOR_EACH_CLIENT(v) FOR_EACH_CLIENTSLOT(v) if(v.flags & FL_CLIENT)
86 #define FOR_EACH_REALCLIENT(v) FOR_EACH_CLIENT(v) if(clienttype(v) == CLIENTTYPE_REAL)
87 #define FOR_EACH_PLAYER(v) FOR_EACH_CLIENT(v) if(v.classname == STR_PLAYER)
88 #define FOR_EACH_REALPLAYER(v) FOR_EACH_REALCLIENT(v) if(v.classname == STR_PLAYER)
89 #endif
90
91 // copies a string to a tempstring (so one can strunzone it)
92 string strcat1(string s) = #115; // FRIK_FILE
93
94 float logfile_open;
95 float logfile;
96
97 void bcenterprint(string s)
98 {
99     // TODO replace by MSG_ALL (would show it to spectators too, though)?
100     entity head;
101     FOR_EACH_PLAYER(head)
102     if (clienttype(head) == CLIENTTYPE_REAL)
103         centerprint(head, s);
104 }
105
106 void GameLogEcho(string s)
107 {
108     string fn;
109     float matches;
110
111     if (autocvar_sv_eventlog_files)
112     {
113         if (!logfile_open)
114         {
115             logfile_open = TRUE;
116             matches = autocvar_sv_eventlog_files_counter + 1;
117             cvar_set("sv_eventlog_files_counter", ftos(matches));
118             fn = ftos(matches);
119             if (strlen(fn) < 8)
120                 fn = strcat(substring("00000000", 0, 8 - strlen(fn)), fn);
121             fn = strcat(autocvar_sv_eventlog_files_nameprefix, fn, autocvar_sv_eventlog_files_namesuffix);
122             logfile = fopen(fn, FILE_APPEND);
123             fputs(logfile, ":logversion:3\n");
124         }
125         if (logfile >= 0)
126         {
127             if (autocvar_sv_eventlog_files_timestamps)
128                 fputs(logfile, strcat(":time:", strftime(TRUE, "%Y-%m-%d %H:%M:%S", "\n", s, "\n")));
129             else
130                 fputs(logfile, strcat(s, "\n"));
131         }
132     }
133     if (autocvar_sv_eventlog_console)
134     {
135         print(s, "\n");
136     }
137 }
138
139 void GameLogInit()
140 {
141     logfile_open = 0;
142     // will be opened later
143 }
144
145 void GameLogClose()
146 {
147     if (logfile_open && logfile >= 0)
148     {
149         fclose(logfile);
150         logfile = -1;
151     }
152 }
153
154 vector PL_VIEW_OFS;
155 vector PL_MIN;
156 vector PL_MAX;
157 vector PL_HEAD;
158 vector PL_CROUCH_VIEW_OFS;
159 vector PL_CROUCH_MIN;
160 vector PL_CROUCH_MAX;
161
162 float spawnpoint_nag;
163 void relocate_spawnpoint()
164 {
165     PL_VIEW_OFS                             = stov(autocvar_sv_player_viewoffset);
166     PL_MIN                                  = stov(autocvar_sv_player_mins);
167     PL_MAX                                  = stov(autocvar_sv_player_maxs);
168     PL_HEAD                                 = stov(autocvar_sv_player_headsize);
169     PL_CROUCH_VIEW_OFS                      = stov(autocvar_sv_player_crouch_viewoffset);
170     PL_CROUCH_MIN                           = stov(autocvar_sv_player_crouch_mins);
171     PL_CROUCH_MAX                           = stov(autocvar_sv_player_crouch_maxs);
172
173     // nudge off the floor
174     setorigin(self, self.origin + '0 0 1');
175
176     tracebox(self.origin, PL_MIN, PL_MAX, self.origin, TRUE, self);
177     if (trace_startsolid)
178     {
179         vector o;
180         o = self.origin;
181         self.mins = PL_MIN;
182         self.maxs = PL_MAX;
183         if (!move_out_of_solid(self))
184             objerror("could not get out of solid at all!");
185         print("^1NOTE: this map needs FIXING. Spawnpoint at ", vtos(o - '0 0 1'));
186         print(" needs to be moved out of solid, e.g. by '", ftos(self.origin_x - o_x));
187         print(" ", ftos(self.origin_y - o_y));
188         print(" ", ftos(self.origin_z - o_z), "'\n");
189         if (autocvar_g_spawnpoints_auto_move_out_of_solid)
190         {
191             if (!spawnpoint_nag)
192                 print("\{1}^1NOTE: this map needs FIXING (it contains spawnpoints in solid, see server log)\n");
193             spawnpoint_nag = 1;
194         }
195         else
196         {
197             setorigin(self, o);
198             self.mins = self.maxs = '0 0 0';
199             objerror("player spawn point in solid, mapper sucks!\n");
200             return;
201         }
202     }
203
204     self.use = spawnpoint_use;
205     self.team_saved = self.team;
206     if (!self.cnt)
207         self.cnt = 1;
208
209     if (have_team_spawns != 0)
210         if (self.team)
211             have_team_spawns = 1;
212     have_team_spawns_forteam[self.team] = 1;
213
214     if (autocvar_r_showbboxes)
215     {
216         // show where spawnpoints point at too
217         makevectors(self.angles);
218         entity e;
219         e = spawn();
220         e.classname = "info_player_foo";
221         setorigin(e, self.origin + v_forward * 24);
222         setsize(e, '-8 -8 -8', '8 8 8');
223         e.solid = SOLID_TRIGGER;
224     }
225 }
226
227 #define strstr strstrofs
228 /*
229 // NOTE: DO NOT USE THIS FUNCTION TOO OFTEN.
230 // IT WILL MOST PROBABLY DESTROY _ALL_ OTHER TEMP
231 // STRINGS AND TAKE QUITE LONG. haystack and needle MUST
232 // BE CONSTANT OR strzoneD!
233 float strstr(string haystack, string needle, float offset)
234 {
235         float len, endpos;
236         string found;
237         len = strlen(needle);
238         endpos = strlen(haystack) - len;
239         while(offset <= endpos)
240         {
241                 found = substring(haystack, offset, len);
242                 if(found == needle)
243                         return offset;
244                 offset = offset + 1;
245         }
246         return -1;
247 }
248 */
249
250 float NUM_NEAREST_ENTITIES = 4;
251 entity nearest_entity[NUM_NEAREST_ENTITIES];
252 float nearest_length[NUM_NEAREST_ENTITIES];
253 entity findnearest(vector point, .string field, string value, vector axismod)
254 {
255     entity localhead;
256     float i;
257     float j;
258     float len;
259     vector dist;
260
261     float num_nearest;
262     num_nearest = 0;
263
264     localhead = find(world, field, value);
265     while (localhead)
266     {
267         if ((localhead.items == IT_KEY1 || localhead.items == IT_KEY2) && localhead.target == "###item###")
268             dist = localhead.oldorigin;
269         else
270             dist = localhead.origin;
271         dist = dist - point;
272         dist = dist_x * axismod_x * '1 0 0' + dist_y * axismod_y * '0 1 0' + dist_z * axismod_z * '0 0 1';
273         len = vlen(dist);
274
275         for (i = 0; i < num_nearest; ++i)
276         {
277             if (len < nearest_length[i])
278                 break;
279         }
280
281         // now i tells us where to insert at
282         //   INSERTION SORT! YOU'VE SEEN IT! RUN!
283         if (i < NUM_NEAREST_ENTITIES)
284         {
285             for (j = NUM_NEAREST_ENTITIES - 1; j >= i; --j)
286             {
287                 nearest_length[j + 1] = nearest_length[j];
288                 nearest_entity[j + 1] = nearest_entity[j];
289             }
290             nearest_length[i] = len;
291             nearest_entity[i] = localhead;
292             if (num_nearest < NUM_NEAREST_ENTITIES)
293                 num_nearest = num_nearest + 1;
294         }
295
296         localhead = find(localhead, field, value);
297     }
298
299     // now use the first one from our list that we can see
300     for (i = 0; i < num_nearest; ++i)
301     {
302         traceline(point, nearest_entity[i].origin, TRUE, world);
303         if (trace_fraction == 1)
304         {
305             if (i != 0)
306             {
307                 dprint("Nearest point (");
308                 dprint(nearest_entity[0].netname);
309                 dprint(") is not visible, using a visible one.\n");
310             }
311             return nearest_entity[i];
312         }
313     }
314
315     if (num_nearest == 0)
316         return world;
317
318     dprint("Not seeing any location point, using nearest as fallback.\n");
319     /* DEBUGGING CODE:
320     dprint("Candidates were: ");
321     for(j = 0; j < num_nearest; ++j)
322     {
323         if(j != 0)
324                 dprint(", ");
325         dprint(nearest_entity[j].netname);
326     }
327     dprint("\n");
328     */
329
330     return nearest_entity[0];
331 }
332
333 void spawnfunc_target_location()
334 {
335     self.classname = "target_location";
336     // location name in netname
337     // eventually support: count, teamgame selectors, line of sight?
338 }
339
340 void spawnfunc_info_location()
341 {
342     self.classname = "target_location";
343     self.message = self.netname;
344 }
345
346 string NearestLocation(vector p)
347 {
348     entity loc;
349     string ret;
350     ret = "somewhere";
351     loc = findnearest(p, classname, "target_location", '1 1 1');
352     if (loc)
353     {
354         ret = loc.message;
355     }
356     else
357     {
358         loc = findnearest(p, target, "###item###", '1 1 4');
359         if (loc)
360             ret = loc.netname;
361     }
362     return ret;
363 }
364
365 string formatmessage(string msg)
366 {
367         float p, p1, p2;
368         float n;
369         vector cursor;
370         entity cursor_ent;
371         string escape;
372         string replacement;
373         p = 0;
374         n = 7;
375
376         WarpZone_crosshair_trace(self);
377         cursor = trace_endpos;
378         cursor_ent = trace_ent;
379
380         while (1) {
381                 if (n < 1)
382                         break; // too many replacements
383
384                 n = n - 1;
385                 p1 = strstr(msg, "%", p); // NOTE: this destroys msg as it's a tempstring!
386                 p2 = strstr(msg, "\\", p); // NOTE: this destroys msg as it's a tempstring!
387
388                 if (p1 < 0)
389                         p1 = p2;
390
391                 if (p2 < 0)
392                         p2 = p1;
393
394                 p = min(p1, p2);
395
396                 if (p < 0)
397                         break;
398
399                 replacement = substring(msg, p, 2);
400                 escape = substring(msg, p + 1, 1);
401
402                 if (escape == "%")
403                         replacement = "%";
404                 else if (escape == "\\")
405                         replacement = "\\";
406                 else if (escape == "n")
407                         replacement = "\n";
408                 else if (escape == "a")
409                         replacement = ftos(floor(self.armorvalue));
410                 else if (escape == "h")
411                         replacement = ftos(floor(self.health));
412                 else if (escape == "l")
413                         replacement = NearestLocation(self.origin);
414                 else if (escape == "y")
415                         replacement = NearestLocation(cursor);
416                 else if (escape == "d")
417                         replacement = NearestLocation(self.death_origin);
418                 else if (escape == "w") {
419                         float wep;
420                         wep = self.weapon;
421                         if (!wep)
422                                 wep = self.switchweapon;
423                         if (!wep)
424                                 wep = self.cnt;
425                         replacement = W_Name(wep);
426                 } else if (escape == "W") {
427                         if (self.items & IT_SHELLS) replacement = "shells";
428                         else if (self.items & IT_NAILS) replacement = "bullets";
429                         else if (self.items & IT_ROCKETS) replacement = "rockets";
430                         else if (self.items & IT_CELLS) replacement = "cells";
431                         else replacement = "batteries"; // ;)
432                 } else if (escape == "x") {
433                         replacement = cursor_ent.netname;
434                         if (!replacement || !cursor_ent)
435                                 replacement = "nothing";
436                 } else if (escape == "s")
437                         replacement = ftos(vlen(self.velocity - self.velocity_z * '0 0 1'));
438                 else if (escape == "S")
439                         replacement = ftos(vlen(self.velocity));
440
441                 msg = strcat(substring(msg, 0, p), replacement, substring(msg, p+2, strlen(msg) - (p+2)));
442                 p = p + strlen(replacement);
443         }
444         return msg;
445 }
446
447 float boolean(float value) { // if value is 0 return FALSE (0), otherwise return TRUE (1)
448         return (value == 0) ? FALSE : TRUE;
449 }
450
451 /*
452 =============
453 GetCvars
454 =============
455 Called with:
456   0:  sends the request
457   >0: receives a cvar from name=argv(f) value=argv(f+1)
458 */
459 void GetCvars_handleString(string thisname, float f, .string field, string name)
460 {
461         if (f < 0)
462         {
463                 if (self.field)
464                         strunzone(self.field);
465                 self.field = string_null;
466         }
467         else if (f > 0)
468         {
469                 if (thisname == name)
470                 {
471                         if (self.field)
472                                 strunzone(self.field);
473                         self.field = strzone(argv(f + 1));
474                 }
475         }
476         else
477                 stuffcmd(self, strcat("cl_cmd sendcvar ", name, "\n"));
478 }
479 void GetCvars_handleString_Fixup(string thisname, float f, .string field, string name, string(string) func)
480 {
481         GetCvars_handleString(thisname, f, field, name);
482         if (f >= 0) // also initialize to the fitting value for "" when sending cvars out
483                 if (thisname == name)
484                 {
485                         string s;
486                         s = func(strcat1(self.field));
487                         if (s != self.field)
488                         {
489                                 strunzone(self.field);
490                                 self.field = strzone(s);
491                         }
492                 }
493 }
494 void GetCvars_handleFloat(string thisname, float f, .float field, string name)
495 {
496         if (f < 0)
497         {
498         }
499         else if (f > 0)
500         {
501                 if (thisname == name)
502                         self.field = stof(argv(f + 1));
503         }
504         else
505                 stuffcmd(self, strcat("cl_cmd sendcvar ", name, "\n"));
506 }
507 void GetCvars_handleFloatOnce(string thisname, float f, .float field, string name)
508 {
509         if (f < 0)
510         {
511         }
512         else if (f > 0)
513         {
514                 if (thisname == name)
515                 {
516                         if(!self.field)
517                         {
518                                 self.field = stof(argv(f + 1));
519                                 if(!self.field)
520                                         self.field = -1;
521                         }
522                 }
523         }
524         else
525         {
526                 if(!self.field)
527                         stuffcmd(self, strcat("cl_cmd sendcvar ", name, "\n"));
528         }
529 }
530 float w_getbestweapon(entity e);
531 string W_FixWeaponOrder_ForceComplete_AndBuildImpulseList(string wo)
532 {
533         string o;
534         o = W_FixWeaponOrder_ForceComplete(wo);
535         if(self.weaponorder_byimpulse)
536         {
537                 strunzone(self.weaponorder_byimpulse);
538                 self.weaponorder_byimpulse = string_null;
539         }
540         self.weaponorder_byimpulse = strzone(W_FixWeaponOrder_BuildImpulseList(o));
541         return o;
542 }
543 void GetCvars(float f)
544 {
545         string s;
546
547         if (f > 0)
548                 s = strcat1(argv(f));
549
550         get_cvars_f = f;
551         get_cvars_s = s;
552         MUTATOR_CALLHOOK(GetCvars);
553         GetCvars_handleFloat(s, f, autoswitch, "cl_autoswitch");
554         GetCvars_handleFloat(s, f, cvar_cl_autoscreenshot, "cl_autoscreenshot");
555         GetCvars_handleFloat(s, f, cvar_cl_playerdetailreduction, "cl_playerdetailreduction");
556         GetCvars_handleString(s, f, cvar_g_xonoticversion, "g_xonoticversion");
557         GetCvars_handleFloat(s, f, cvar_cl_handicap, "cl_handicap");
558         GetCvars_handleFloat(s, f, cvar_cl_clippedspectating, "cl_clippedspectating");
559         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriority, "cl_weaponpriority", W_FixWeaponOrder_ForceComplete_AndBuildImpulseList);
560         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[0], "cl_weaponpriority0", W_FixWeaponOrder_AllowIncomplete);
561         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[1], "cl_weaponpriority1", W_FixWeaponOrder_AllowIncomplete);
562         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[2], "cl_weaponpriority2", W_FixWeaponOrder_AllowIncomplete);
563         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[3], "cl_weaponpriority3", W_FixWeaponOrder_AllowIncomplete);
564         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[4], "cl_weaponpriority4", W_FixWeaponOrder_AllowIncomplete);
565         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[5], "cl_weaponpriority5", W_FixWeaponOrder_AllowIncomplete);
566         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[6], "cl_weaponpriority6", W_FixWeaponOrder_AllowIncomplete);
567         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[7], "cl_weaponpriority7", W_FixWeaponOrder_AllowIncomplete);
568         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[8], "cl_weaponpriority8", W_FixWeaponOrder_AllowIncomplete);
569         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[9], "cl_weaponpriority9", W_FixWeaponOrder_AllowIncomplete);
570         GetCvars_handleFloat(s, f, cvar_cl_weaponimpulsemode, "cl_weaponimpulsemode");
571         GetCvars_handleFloat(s, f, cvar_cl_autotaunt, "cl_autotaunt");
572         GetCvars_handleFloat(s, f, cvar_cl_noantilag, "cl_noantilag");
573         GetCvars_handleFloat(s, f, cvar_cl_voice_directional, "cl_voice_directional");
574         GetCvars_handleFloat(s, f, cvar_cl_voice_directional_taunt_attenuation, "cl_voice_directional_taunt_attenuation");
575         GetCvars_handleFloat(s, f, cvar_cl_accuracy_data_share, "cl_accuracy_data_share");
576         GetCvars_handleFloat(s, f, cvar_cl_accuracy_data_receive, "cl_accuracy_data_receive");
577
578         self.cvar_cl_accuracy_data_share = boolean(self.cvar_cl_accuracy_data_share);
579         self.cvar_cl_accuracy_data_receive = boolean(self.cvar_cl_accuracy_data_receive);
580
581 #ifdef ALLOW_FORCEMODELS
582         GetCvars_handleFloat(s, f, cvar_cl_forceplayermodels, "cl_forceplayermodels");
583         GetCvars_handleFloat(s, f, cvar_cl_forceplayermodelsfromxonotic, "cl_forceplayermodelsfromxonotic");
584 #endif
585         GetCvars_handleFloatOnce(s, f, cvar_cl_gunalign, "cl_gunalign");
586         GetCvars_handleFloat(s, f, cvar_cl_allow_uid2name, "cl_allow_uid2name");
587         GetCvars_handleFloat(s, f, cvar_cl_allow_uidtracking, "cl_allow_uidtracking");
588         GetCvars_handleFloat(s, f, cvar_cl_movement_track_canjump, "cl_movement_track_canjump");
589         GetCvars_handleFloat(s, f, cvar_cl_newusekeysupported, "cl_newusekeysupported");
590
591         // fixup of switchweapon (needed for LMS or when spectating is disabled, as PutClientInServer comes too early)
592         if (f > 0)
593         {
594                 if (s == "cl_weaponpriority")
595                         self.switchweapon = w_getbestweapon(self);
596                 if (s == "cl_allow_uidtracking")
597                         PlayerStats_AddPlayer(self);
598         }
599 }
600
601 void backtrace(string msg)
602 {
603     float dev, war;
604     dev = autocvar_developer;
605     war = autocvar_prvm_backtraceforwarnings;
606     cvar_set("developer", "1");
607     cvar_set("prvm_backtraceforwarnings", "1");
608     print("\n");
609     print("--- CUT HERE ---\nWARNING: ");
610     print(msg);
611     print("\n");
612     remove(world); // isn't there any better way to cause a backtrace?
613     print("\n--- CUT UNTIL HERE ---\n");
614     cvar_set("developer", ftos(dev));
615     cvar_set("prvm_backtraceforwarnings", ftos(war));
616 }
617
618 string Team_ColorCode(float teamid)
619 {
620     if (teamid == COLOR_TEAM1)
621         return "^1";
622     else if (teamid == COLOR_TEAM2)
623         return "^4";
624     else if (teamid == COLOR_TEAM3)
625         return "^3";
626     else if (teamid == COLOR_TEAM4)
627         return "^6";
628     else
629         return "^7";
630 }
631
632 string Team_ColorName(float t)
633 {
634     // fixme: Search for team entities and get their .netname's!
635     if (t == COLOR_TEAM1)
636         return "Red";
637     if (t == COLOR_TEAM2)
638         return "Blue";
639     if (t == COLOR_TEAM3)
640         return "Yellow";
641     if (t == COLOR_TEAM4)
642         return "Pink";
643     return "Neutral";
644 }
645
646 string Team_ColorNameLowerCase(float t)
647 {
648     // fixme: Search for team entities and get their .netname's!
649     if (t == COLOR_TEAM1)
650         return "red";
651     if (t == COLOR_TEAM2)
652         return "blue";
653     if (t == COLOR_TEAM3)
654         return "yellow";
655     if (t == COLOR_TEAM4)
656         return "pink";
657     return "neutral";
658 }
659
660 float ColourToNumber(string team_colour)
661 {
662         if (team_colour == "red")
663                 return COLOR_TEAM1;
664
665         if (team_colour == "blue")
666                 return COLOR_TEAM2;
667
668         if (team_colour == "yellow")
669                 return COLOR_TEAM3;
670
671         if (team_colour == "pink")
672                 return COLOR_TEAM4;
673
674         if (team_colour == "auto")
675                 return 0;
676
677         return -1;
678 }
679
680 float NumberToTeamNumber(float number)
681 {
682         if (number == 1)
683                 return COLOR_TEAM1;
684
685         if (number == 2)
686                 return COLOR_TEAM2;
687
688         if (number == 3)
689                 return COLOR_TEAM3;
690
691         if (number == 4)
692                 return COLOR_TEAM4;
693
694         return -1;
695 }
696
697 // decolorizes and team colors the player name when needed
698 string playername(entity p)
699 {
700     string t;
701     if (teamplay && !intermission_running && p.classname == "player")
702     {
703         t = Team_ColorCode(p.team);
704         return strcat(t, strdecolorize(p.netname));
705     }
706     else
707         return p.netname;
708 }
709
710 vector randompos(vector m1, vector m2)
711 {
712     vector v;
713     m2 = m2 - m1;
714     v_x = m2_x * random() + m1_x;
715     v_y = m2_y * random() + m1_y;
716     v_z = m2_z * random() + m1_z;
717     return  v;
718 }
719
720 //#NO AUTOCVARS START
721
722 float g_pickup_shells;
723 float g_pickup_shells_max;
724 float g_pickup_nails;
725 float g_pickup_nails_max;
726 float g_pickup_rockets;
727 float g_pickup_rockets_max;
728 float g_pickup_cells;
729 float g_pickup_cells_max;
730 float g_pickup_fuel;
731 float g_pickup_fuel_jetpack;
732 float g_pickup_fuel_max;
733 float g_pickup_armorsmall;
734 float g_pickup_armorsmall_max;
735 float g_pickup_armorsmall_anyway;
736 float g_pickup_armormedium;
737 float g_pickup_armormedium_max;
738 float g_pickup_armormedium_anyway;
739 float g_pickup_armorbig;
740 float g_pickup_armorbig_max;
741 float g_pickup_armorbig_anyway;
742 float g_pickup_armorlarge;
743 float g_pickup_armorlarge_max;
744 float g_pickup_armorlarge_anyway;
745 float g_pickup_healthsmall;
746 float g_pickup_healthsmall_max;
747 float g_pickup_healthsmall_anyway;
748 float g_pickup_healthmedium;
749 float g_pickup_healthmedium_max;
750 float g_pickup_healthmedium_anyway;
751 float g_pickup_healthlarge;
752 float g_pickup_healthlarge_max;
753 float g_pickup_healthlarge_anyway;
754 float g_pickup_healthmega;
755 float g_pickup_healthmega_max;
756 float g_pickup_healthmega_anyway;
757 float g_pickup_ammo_anyway;
758 float g_pickup_weapons_anyway;
759 float g_weaponarena;
760 float g_weaponarena_random;
761 float g_weaponarena_random_with_laser;
762 string g_weaponarena_list;
763 float g_weaponspeedfactor;
764 float g_weaponratefactor;
765 float g_weapondamagefactor;
766 float g_weaponforcefactor;
767 float g_weaponspreadfactor;
768
769 float start_weapons;
770 float start_items;
771 float start_ammo_shells;
772 float start_ammo_nails;
773 float start_ammo_rockets;
774 float start_ammo_cells;
775 float start_ammo_fuel;
776 float start_health;
777 float start_armorvalue;
778 float warmup_start_weapons;
779 float warmup_start_ammo_shells;
780 float warmup_start_ammo_nails;
781 float warmup_start_ammo_rockets;
782 float warmup_start_ammo_cells;
783 float warmup_start_ammo_fuel;
784 float warmup_start_health;
785 float warmup_start_armorvalue;
786 float g_weapon_stay;
787 float g_ghost_items;
788
789 entity get_weaponinfo(float w);
790
791 float want_weapon(string cvarprefix, entity weaponinfo, float allguns)
792 {
793         var float i = weaponinfo.weapon;
794
795         if (!i)
796                 return 0;
797
798         var float t = cvar(strcat(cvarprefix, weaponinfo.netname));
799
800         if (t < 0) // "default" weapon selection
801         {
802                 if (g_lms || g_ca || allguns)
803                         t = (weaponinfo.spawnflags & WEP_FLAG_NORMAL);
804                 else if(t < -1)
805                         t = 0;
806                 else if (g_cts)
807                         t = (i == WEP_SHOTGUN);
808                 else if (g_nexball)
809                         t = 0; // weapon is set a few lines later
810                 else
811                         t = (i == WEP_LASER || i == WEP_SHOTGUN);
812                 if(g_grappling_hook) // if possible, redirect off-hand hook to on-hand hook
813                         t |= (i == WEP_HOOK);
814         }
815
816         // we cannot disable porto in Nexball, we must force it
817         if(g_nexball && i == WEP_PORTO)
818                 t = 1;
819
820         return t;
821 }
822
823 void readplayerstartcvars()
824 {
825         entity e;
826         float i, j, t;
827         string s;
828
829         // initialize starting values for players
830         start_weapons = 0;
831         start_items = 0;
832         start_ammo_shells = 0;
833         start_ammo_nails = 0;
834         start_ammo_rockets = 0;
835         start_ammo_cells = 0;
836         start_health = cvar("g_balance_health_start");
837         start_armorvalue = cvar("g_balance_armor_start");
838
839         g_weaponarena = 0;
840         s = cvar_string("g_weaponarena");
841         if (s == "0" || s == "")
842         {
843                 if(g_lms || g_ca)
844                         s = "most";
845         }
846
847         if (s == "0" || s == "")
848         {
849                 // no arena
850         }
851         else if (s == "off")
852         {
853                 // forcibly turn off weaponarena
854         }
855         else if (s == "all")
856         {
857                 g_weaponarena_list = "All Weapons";
858                 for (j = WEP_FIRST; j <= WEP_LAST; ++j)
859                 {
860                         e = get_weaponinfo(j);
861                         g_weaponarena |= e.weapons;
862                         weapon_action(e.weapon, WR_PRECACHE);
863                 }
864         }
865         else if (s == "most")
866         {
867                 g_weaponarena_list = "Most Weapons";
868                 for (j = WEP_FIRST; j <= WEP_LAST; ++j)
869                 {
870                         e = get_weaponinfo(j);
871                         if (e.spawnflags & WEP_FLAG_NORMAL)
872                         {
873                                 g_weaponarena |= e.weapons;
874                                 weapon_action(e.weapon, WR_PRECACHE);
875                         }
876                 }
877         }
878         else if (s == "none")
879         {
880                 g_weaponarena_list = "No Weapons";
881                 g_weaponarena = WEPBIT_ALL + 1; // this supports no single weapon bit!
882         }
883         else
884         {
885                 t = tokenize_console(s);
886                 g_weaponarena_list = "";
887                 for (i = 0; i < t; ++i)
888                 {
889                         s = argv(i);
890                         for (j = WEP_FIRST; j <= WEP_LAST; ++j)
891                         {
892                                 e = get_weaponinfo(j);
893                                 if (e.netname == s)
894                                 {
895                                         g_weaponarena |= e.weapons;
896                                         weapon_action(e.weapon, WR_PRECACHE);
897                                         g_weaponarena_list = strcat(g_weaponarena_list, e.message, " & ");
898                                         break;
899                                 }
900                         }
901                         if (j > WEP_LAST)
902                         {
903                                 print("The weapon mutator list contains an unknown weapon ", s, ". Skipped.\n");
904                         }
905                 }
906                 g_weaponarena_list = strzone(substring(g_weaponarena_list, 0, strlen(g_weaponarena_list) - 3));
907         }
908
909         if(g_weaponarena)
910                 g_weaponarena_random = cvar("g_weaponarena_random");
911         else
912                 g_weaponarena_random = 0;
913         g_weaponarena_random_with_laser = cvar("g_weaponarena_random_with_laser");
914
915         if (g_weaponarena)
916         {
917                 start_weapons = g_weaponarena;
918                 if(!(g_lms || g_ca))
919                         start_items |= IT_UNLIMITED_AMMO;
920         }
921         else if (g_minstagib)
922         {
923                 start_health = 100;
924                 start_armorvalue = 0;
925                 start_weapons = WEPBIT_MINSTANEX;
926                 weapon_action(WEP_MINSTANEX, WR_PRECACHE);
927                 g_minstagib_invis_alpha = cvar("g_minstagib_invis_alpha");
928
929                 if (g_minstagib_invis_alpha <= 0)
930                         g_minstagib_invis_alpha = -1;
931         }
932         else
933         {
934                 for (i = WEP_FIRST; i <= WEP_LAST; ++i)
935                 {
936                         e = get_weaponinfo(i);
937                         if(want_weapon("g_start_weapon_", e, FALSE))
938                                 start_weapons |= e.weapons;
939                 }
940         }
941
942         if(!cvar("g_use_ammunition"))
943                 start_items |= IT_UNLIMITED_AMMO;
944
945         if(g_minstagib)
946         {
947                 start_ammo_cells = cvar("g_minstagib_ammo_start");
948                 start_ammo_fuel = cvar("g_start_ammo_fuel");
949         }
950         else if(start_items & IT_UNLIMITED_WEAPON_AMMO)
951         {
952                 start_ammo_rockets = 999;
953                 start_ammo_shells = 999;
954                 start_ammo_cells = 999;
955                 start_ammo_nails = 999;
956                 start_ammo_fuel = 999;
957         }
958         else
959         {
960                 if(g_lms || g_ca)
961                 {
962                         start_ammo_shells = cvar("g_lms_start_ammo_shells");
963                         start_ammo_nails = cvar("g_lms_start_ammo_nails");
964                         start_ammo_rockets = cvar("g_lms_start_ammo_rockets");
965                         start_ammo_cells = cvar("g_lms_start_ammo_cells");
966                         start_ammo_fuel = cvar("g_lms_start_ammo_fuel");
967                 }
968                 else
969                 {
970                         start_ammo_shells = cvar("g_start_ammo_shells");
971                         start_ammo_nails = cvar("g_start_ammo_nails");
972                         start_ammo_rockets = cvar("g_start_ammo_rockets");
973                         start_ammo_cells = cvar("g_start_ammo_cells");
974                         start_ammo_fuel = cvar("g_start_ammo_fuel");
975                 }
976         }
977
978         if (g_lms || g_ca)
979         {
980                 start_health = cvar("g_lms_start_health");
981                 start_armorvalue = cvar("g_lms_start_armor");
982         }
983
984         if (inWarmupStage)
985         {
986                 warmup_start_ammo_shells = start_ammo_shells;
987                 warmup_start_ammo_nails = start_ammo_nails;
988                 warmup_start_ammo_rockets = start_ammo_rockets;
989                 warmup_start_ammo_cells = start_ammo_cells;
990                 warmup_start_ammo_fuel = start_ammo_fuel;
991                 warmup_start_health = start_health;
992                 warmup_start_armorvalue = start_armorvalue;
993                 warmup_start_weapons = start_weapons;
994
995                 if (!g_weaponarena && !g_minstagib && !g_ca)
996                 {
997                         warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
998                         warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
999                         warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
1000                         warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
1001                         warmup_start_ammo_fuel = cvar("g_warmup_start_ammo_fuel");
1002                         warmup_start_health = cvar("g_warmup_start_health");
1003                         warmup_start_armorvalue = cvar("g_warmup_start_armor");
1004                         warmup_start_weapons = 0;
1005                         for (i = WEP_FIRST; i <= WEP_LAST; ++i)
1006                         {
1007                                 e = get_weaponinfo(i);
1008                                 if(want_weapon("g_start_weapon_", e, cvar("g_warmup_allguns")))
1009                                         warmup_start_weapons |= e.weapons;
1010                         }
1011                 }
1012         }
1013
1014         if (g_jetpack || (g_grappling_hook && (start_weapons & WEPBIT_HOOK)))
1015         {
1016                 g_grappling_hook = 0; // these two can't coexist, as they use the same button
1017                 start_items |= IT_FUEL_REGEN;
1018                 start_ammo_fuel = max(start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
1019                 warmup_start_ammo_fuel = max(warmup_start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
1020         }
1021
1022         if (g_jetpack)
1023                 start_items |= IT_JETPACK;
1024
1025         if (g_weapon_stay == 2)
1026         {
1027                 if (!start_ammo_shells) start_ammo_shells = g_pickup_shells;
1028                 if (!start_ammo_nails) start_ammo_nails = g_pickup_nails;
1029                 if (!start_ammo_cells) start_ammo_cells = g_pickup_cells;
1030                 if (!start_ammo_rockets) start_ammo_rockets = g_pickup_rockets;
1031                 if (!start_ammo_fuel) start_ammo_fuel = g_pickup_fuel;
1032                 if (!warmup_start_ammo_shells) warmup_start_ammo_shells = g_pickup_shells;
1033                 if (!warmup_start_ammo_nails) warmup_start_ammo_nails = g_pickup_nails;
1034                 if (!warmup_start_ammo_cells) warmup_start_ammo_cells = g_pickup_cells;
1035                 if (!warmup_start_ammo_rockets) warmup_start_ammo_rockets = g_pickup_rockets;
1036                 if (!warmup_start_ammo_fuel) warmup_start_ammo_fuel = g_pickup_fuel;
1037         }
1038
1039         MUTATOR_CALLHOOK(SetStartItems);
1040
1041         for (i = WEP_FIRST; i <= WEP_LAST; ++i)
1042         {
1043                 e = get_weaponinfo(i);
1044                 if(e.weapons & (start_weapons | warmup_start_weapons))
1045                         weapon_action(e.weapon, WR_PRECACHE);
1046         }
1047
1048         start_ammo_shells = max(0, start_ammo_shells);
1049         start_ammo_nails = max(0, start_ammo_nails);
1050         start_ammo_cells = max(0, start_ammo_cells);
1051         start_ammo_rockets = max(0, start_ammo_rockets);
1052         start_ammo_fuel = max(0, start_ammo_fuel);
1053
1054         warmup_start_ammo_shells = max(0, warmup_start_ammo_shells);
1055         warmup_start_ammo_nails = max(0, warmup_start_ammo_nails);
1056         warmup_start_ammo_cells = max(0, warmup_start_ammo_cells);
1057         warmup_start_ammo_rockets = max(0, warmup_start_ammo_rockets);
1058         warmup_start_ammo_fuel = max(0, warmup_start_ammo_fuel);
1059 }
1060
1061 float g_bugrigs;
1062 float g_bugrigs_planar_movement;
1063 float g_bugrigs_planar_movement_car_jumping;
1064 float g_bugrigs_reverse_spinning;
1065 float g_bugrigs_reverse_speeding;
1066 float g_bugrigs_reverse_stopping;
1067 float g_bugrigs_air_steering;
1068 float g_bugrigs_angle_smoothing;
1069 float g_bugrigs_friction_floor;
1070 float g_bugrigs_friction_brake;
1071 float g_bugrigs_friction_air;
1072 float g_bugrigs_accel;
1073 float g_bugrigs_speed_ref;
1074 float g_bugrigs_speed_pow;
1075 float g_bugrigs_steer;
1076
1077 float g_touchexplode;
1078 float g_touchexplode_radius;
1079 float g_touchexplode_damage;
1080 float g_touchexplode_edgedamage;
1081 float g_touchexplode_force;
1082
1083 float sv_autotaunt;
1084 float sv_taunt;
1085
1086 float sv_pitch_min;
1087 float sv_pitch_max;
1088 float sv_pitch_fixyaw;
1089
1090 string GetGametype(); // g_world.qc
1091 void readlevelcvars(void)
1092 {
1093         // first load all the mutators
1094         if(cvar("g_invincible_projectiles"))
1095                 MUTATOR_ADD(mutator_invincibleprojectiles);
1096         if(cvar("g_nix"))
1097                 MUTATOR_ADD(mutator_nix);
1098         if(cvar("g_dodging"))
1099                 MUTATOR_ADD(mutator_dodging);
1100         if(cvar("g_rocket_flying"))
1101                 MUTATOR_ADD(mutator_rocketflying);
1102         if(cvar("g_vampire"))
1103                 MUTATOR_ADD(mutator_vampire);
1104         if(cvar("g_sandbox"))
1105                 MUTATOR_ADD(sandbox);
1106
1107         if(cvar("sv_allow_fullbright"))
1108                 serverflags |= SERVERFLAG_ALLOW_FULLBRIGHT;
1109
1110     g_bugrigs = cvar("g_bugrigs");
1111     g_bugrigs_planar_movement = cvar("g_bugrigs_planar_movement");
1112     g_bugrigs_planar_movement_car_jumping = cvar("g_bugrigs_planar_movement_car_jumping");
1113     g_bugrigs_reverse_spinning = cvar("g_bugrigs_reverse_spinning");
1114     g_bugrigs_reverse_speeding = cvar("g_bugrigs_reverse_speeding");
1115     g_bugrigs_reverse_stopping = cvar("g_bugrigs_reverse_stopping");
1116     g_bugrigs_air_steering = cvar("g_bugrigs_air_steering");
1117     g_bugrigs_angle_smoothing = cvar("g_bugrigs_angle_smoothing");
1118     g_bugrigs_friction_floor = cvar("g_bugrigs_friction_floor");
1119     g_bugrigs_friction_brake = cvar("g_bugrigs_friction_brake");
1120     g_bugrigs_friction_air = cvar("g_bugrigs_friction_air");
1121     g_bugrigs_accel = cvar("g_bugrigs_accel");
1122     g_bugrigs_speed_ref = cvar("g_bugrigs_speed_ref");
1123     g_bugrigs_speed_pow = cvar("g_bugrigs_speed_pow");
1124     g_bugrigs_steer = cvar("g_bugrigs_steer");
1125
1126     g_touchexplode = cvar("g_touchexplode");
1127     g_touchexplode_radius = cvar("g_touchexplode_radius");
1128     g_touchexplode_damage = cvar("g_touchexplode_damage");
1129     g_touchexplode_edgedamage = cvar("g_touchexplode_edgedamage");
1130     g_touchexplode_force = cvar("g_touchexplode_force");
1131
1132 #ifdef ALLOW_FORCEMODELS
1133         sv_clforceplayermodels = cvar("sv_clforceplayermodels");
1134 #endif
1135         sv_loddistance1 = cvar("sv_loddistance1");
1136         sv_loddistance2 = cvar("sv_loddistance2");
1137
1138         if(sv_loddistance2 <= sv_loddistance1)
1139                 sv_loddistance2 = 1073741824; // enough to turn off LOD 2 reliably
1140
1141         sv_clones = cvar("sv_clones");
1142         sv_gentle = cvar("sv_gentle");
1143         sv_foginterval = cvar("sv_foginterval");
1144         g_cloaked = cvar("g_cloaked");
1145     if(g_cts)
1146         g_cloaked = 1; // always enable cloak in CTS
1147         g_jump_grunt = cvar("g_jump_grunt");
1148         g_footsteps = cvar("g_footsteps");
1149         g_grappling_hook = cvar("g_grappling_hook");
1150         g_jetpack = cvar("g_jetpack");
1151         g_midair = cvar("g_midair");
1152         g_minstagib = cvar("g_minstagib");
1153         g_norecoil = cvar("g_norecoil");
1154         g_bloodloss = cvar("g_bloodloss");
1155         sv_maxidle = cvar("sv_maxidle");
1156         sv_maxidle_spectatorsareidle = cvar("sv_maxidle_spectatorsareidle");
1157         g_ctf_reverse = cvar("g_ctf_reverse");
1158         sv_autotaunt = cvar("sv_autotaunt");
1159         sv_taunt = cvar("sv_taunt");
1160
1161         inWarmupStage = cvar("g_warmup");
1162         g_warmup_limit = cvar("g_warmup_limit");
1163         g_warmup_allguns = cvar("g_warmup_allguns");
1164         g_warmup_allow_timeout = cvar("g_warmup_allow_timeout");
1165
1166         if ((g_race && g_race_qualifying == 2) || g_runematch || g_arena || g_assault || cvar("g_campaign"))
1167                 inWarmupStage = 0; // these modes cannot work together, sorry
1168
1169         g_pickup_respawntime_weapon = cvar("g_pickup_respawntime_weapon");
1170         g_pickup_respawntime_ammo = cvar("g_pickup_respawntime_ammo");
1171         g_pickup_respawntime_short = cvar("g_pickup_respawntime_short");
1172         g_pickup_respawntime_medium = cvar("g_pickup_respawntime_medium");
1173         g_pickup_respawntime_long = cvar("g_pickup_respawntime_long");
1174         g_pickup_respawntime_powerup = cvar("g_pickup_respawntime_powerup");
1175         g_pickup_respawntimejitter_weapon = cvar("g_pickup_respawntimejitter_weapon");
1176         g_pickup_respawntimejitter_ammo = cvar("g_pickup_respawntimejitter_ammo");
1177         g_pickup_respawntimejitter_short = cvar("g_pickup_respawntimejitter_short");
1178         g_pickup_respawntimejitter_medium = cvar("g_pickup_respawntimejitter_medium");
1179         g_pickup_respawntimejitter_long = cvar("g_pickup_respawntimejitter_long");
1180         g_pickup_respawntimejitter_powerup = cvar("g_pickup_respawntimejitter_powerup");
1181
1182         g_weaponspeedfactor = cvar("g_weaponspeedfactor");
1183         g_weaponratefactor = cvar("g_weaponratefactor");
1184         g_weapondamagefactor = cvar("g_weapondamagefactor");
1185         g_weaponforcefactor = cvar("g_weaponforcefactor");
1186         g_weaponspreadfactor = cvar("g_weaponspreadfactor");
1187
1188         g_pickup_shells = cvar("g_pickup_shells");
1189         g_pickup_shells_max = cvar("g_pickup_shells_max");
1190         g_pickup_nails = cvar("g_pickup_nails");
1191         g_pickup_nails_max = cvar("g_pickup_nails_max");
1192         g_pickup_rockets = cvar("g_pickup_rockets");
1193         g_pickup_rockets_max = cvar("g_pickup_rockets_max");
1194         g_pickup_cells = cvar("g_pickup_cells");
1195         g_pickup_cells_max = cvar("g_pickup_cells_max");
1196         g_pickup_fuel = cvar("g_pickup_fuel");
1197         g_pickup_fuel_jetpack = cvar("g_pickup_fuel_jetpack");
1198         g_pickup_fuel_max = cvar("g_pickup_fuel_max");
1199         g_pickup_armorsmall = cvar("g_pickup_armorsmall");
1200         g_pickup_armorsmall_max = cvar("g_pickup_armorsmall_max");
1201         g_pickup_armorsmall_anyway = cvar("g_pickup_armorsmall_anyway");
1202         g_pickup_armormedium = cvar("g_pickup_armormedium");
1203         g_pickup_armormedium_max = cvar("g_pickup_armormedium_max");
1204         g_pickup_armormedium_anyway = cvar("g_pickup_armormedium_anyway");
1205         g_pickup_armorbig = cvar("g_pickup_armorbig");
1206         g_pickup_armorbig_max = cvar("g_pickup_armorbig_max");
1207         g_pickup_armorbig_anyway = cvar("g_pickup_armorbig_anyway");
1208         g_pickup_armorlarge = cvar("g_pickup_armorlarge");
1209         g_pickup_armorlarge_max = cvar("g_pickup_armorlarge_max");
1210         g_pickup_armorlarge_anyway = cvar("g_pickup_armorlarge_anyway");
1211         g_pickup_healthsmall = cvar("g_pickup_healthsmall");
1212         g_pickup_healthsmall_max = cvar("g_pickup_healthsmall_max");
1213         g_pickup_healthsmall_anyway = cvar("g_pickup_healthsmall_anyway");
1214         g_pickup_healthmedium = cvar("g_pickup_healthmedium");
1215         g_pickup_healthmedium_max = cvar("g_pickup_healthmedium_max");
1216         g_pickup_healthmedium_anyway = cvar("g_pickup_healthmedium_anyway");
1217         g_pickup_healthlarge = cvar("g_pickup_healthlarge");
1218         g_pickup_healthlarge_max = cvar("g_pickup_healthlarge_max");
1219         g_pickup_healthlarge_anyway = cvar("g_pickup_healthlarge_anyway");
1220         g_pickup_healthmega = cvar("g_pickup_healthmega");
1221         g_pickup_healthmega_max = cvar("g_pickup_healthmega_max");
1222         g_pickup_healthmega_anyway = cvar("g_pickup_healthmega_anyway");
1223
1224         g_pickup_ammo_anyway = cvar("g_pickup_ammo_anyway");
1225         g_pickup_weapons_anyway = cvar("g_pickup_weapons_anyway");
1226
1227         g_pinata = cvar("g_pinata");
1228
1229     g_weapon_stay = cvar(strcat("g_", GetGametype(), "_weapon_stay"));
1230     if(!g_weapon_stay)
1231         g_weapon_stay = cvar("g_weapon_stay");
1232
1233         g_ghost_items = cvar("g_ghost_items");
1234
1235         if(g_ghost_items >= 1)
1236                 g_ghost_items = 0.25; // default alpha value
1237
1238         if not(inWarmupStage && !g_ca)
1239                 game_starttime = cvar("g_start_delay");
1240
1241         sv_pitch_min = cvar("sv_pitch_min");
1242         sv_pitch_max = cvar("sv_pitch_max");
1243         sv_pitch_fixyaw = cvar("sv_pitch_fixyaw");
1244
1245         readplayerstartcvars();
1246 }
1247
1248 //#NO AUTOCVARS END
1249
1250 // Sound functions
1251 string precache_sound (string s) = #19;
1252 float precache_sound_index (string s) = #19;
1253
1254 #define SND_VOLUME      1
1255 #define SND_ATTENUATION 2
1256 #define SND_LARGEENTITY 8
1257 #define SND_LARGESOUND  16
1258
1259 float sound_allowed(float dest, entity e)
1260 {
1261     // sounds from world may always pass
1262     for (;;)
1263     {
1264         if (e.classname == "body")
1265             e = e.enemy;
1266         else if (e.realowner && e.realowner != e)
1267             e = e.realowner;
1268         else if (e.owner && e.owner != e)
1269             e = e.owner;
1270         else
1271             break;
1272     }
1273     // sounds to self may always pass
1274     if (dest == MSG_ONE)
1275         if (e == msg_entity)
1276             return TRUE;
1277     // sounds by players can be removed
1278     if (autocvar_bot_sound_monopoly)
1279         if (clienttype(e) == CLIENTTYPE_REAL)
1280             return FALSE;
1281     // anything else may pass
1282     return TRUE;
1283 }
1284
1285 #ifdef COMPAT_XON010_CHANNELS
1286 void(entity e, float chan, string samp, float vol, float atten) sound_builtin = #8;
1287 void sound(entity e, float chan, string samp, float vol, float atten)
1288 {
1289     if (!sound_allowed(MSG_BROADCAST, e))
1290         return;
1291     sound_builtin(e, chan, samp, vol, atten);
1292 }
1293 #else
1294 #undef sound
1295 void sound(entity e, float chan, string samp, float vol, float atten)
1296 {
1297     if (!sound_allowed(MSG_BROADCAST, e))
1298         return;
1299     sound7(e, chan, samp, vol, atten, 0, 0);
1300 }
1301 #endif
1302
1303 void soundtoat(float dest, entity e, vector o, float chan, string samp, float vol, float atten)
1304 {
1305     float entno, idx;
1306
1307     if (!sound_allowed(dest, e))
1308         return;
1309
1310     entno = num_for_edict(e);
1311     idx = precache_sound_index(samp);
1312
1313     float sflags;
1314     sflags = 0;
1315
1316     atten = floor(atten * 64);
1317     vol = floor(vol * 255);
1318
1319     if (vol != 255)
1320         sflags |= SND_VOLUME;
1321     if (atten != 64)
1322         sflags |= SND_ATTENUATION;
1323     if (entno >= 8192 || chan < 0 || chan > 7)
1324         sflags |= SND_LARGEENTITY;
1325     if (idx >= 256)
1326         sflags |= SND_LARGESOUND;
1327
1328     WriteByte(dest, SVC_SOUND);
1329     WriteByte(dest, sflags);
1330     if (sflags & SND_VOLUME)
1331         WriteByte(dest, vol);
1332     if (sflags & SND_ATTENUATION)
1333         WriteByte(dest, atten);
1334     if (sflags & SND_LARGEENTITY)
1335     {
1336         WriteShort(dest, entno);
1337         WriteByte(dest, chan);
1338     }
1339     else
1340     {
1341         WriteShort(dest, entno * 8 + chan);
1342     }
1343     if (sflags & SND_LARGESOUND)
1344         WriteShort(dest, idx);
1345     else
1346         WriteByte(dest, idx);
1347
1348     WriteCoord(dest, o_x);
1349     WriteCoord(dest, o_y);
1350     WriteCoord(dest, o_z);
1351 }
1352 void soundto(float dest, entity e, float chan, string samp, float vol, float atten)
1353 {
1354     vector o;
1355
1356     if (!sound_allowed(dest, e))
1357         return;
1358
1359     o = e.origin + 0.5 * (e.mins + e.maxs);
1360     soundtoat(dest, e, o, chan, samp, vol, atten);
1361 }
1362 void soundat(entity e, vector o, float chan, string samp, float vol, float atten)
1363 {
1364     soundtoat(((chan & 8) ? MSG_ALL : MSG_BROADCAST), e, o, chan, samp, vol, atten);
1365 }
1366 void stopsoundto(float dest, entity e, float chan)
1367 {
1368     float entno;
1369
1370     if (!sound_allowed(dest, e))
1371         return;
1372
1373     entno = num_for_edict(e);
1374
1375     if (entno >= 8192 || chan < 0 || chan > 7)
1376     {
1377         float idx, sflags;
1378         idx = precache_sound_index("misc/null.wav");
1379         sflags = SND_LARGEENTITY;
1380         if (idx >= 256)
1381             sflags |= SND_LARGESOUND;
1382         WriteByte(dest, SVC_SOUND);
1383         WriteByte(dest, sflags);
1384         WriteShort(dest, entno);
1385         WriteByte(dest, chan);
1386         if (sflags & SND_LARGESOUND)
1387             WriteShort(dest, idx);
1388         else
1389             WriteByte(dest, idx);
1390         WriteCoord(dest, e.origin_x);
1391         WriteCoord(dest, e.origin_y);
1392         WriteCoord(dest, e.origin_z);
1393     }
1394     else
1395     {
1396         WriteByte(dest, SVC_STOPSOUND);
1397         WriteShort(dest, entno * 8 + chan);
1398     }
1399 }
1400 void stopsound(entity e, float chan)
1401 {
1402     if (!sound_allowed(MSG_BROADCAST, e))
1403         return;
1404
1405     stopsoundto(MSG_BROADCAST, e, chan); // unreliable, gets there fast
1406     stopsoundto(MSG_ALL, e, chan); // in case of packet loss
1407 }
1408
1409 void play2(entity e, string filename)
1410 {
1411     //stuffcmd(e, strcat("play2 ", filename, "\n"));
1412     msg_entity = e;
1413     soundtoat(MSG_ONE, world, '0 0 0', CH_INFO, filename, VOL_BASE, ATTN_NONE);
1414 }
1415
1416 // use this one if you might be causing spam (e.g. from touch functions that might get called more than once per frame)
1417 .float spamtime;
1418 float spamsound(entity e, float chan, string samp, float vol, float atten)
1419 {
1420     if (!sound_allowed(MSG_BROADCAST, e))
1421         return FALSE;
1422
1423     if (time > e.spamtime)
1424     {
1425         e.spamtime = time;
1426         sound(e, chan, samp, vol, atten);
1427         return TRUE;
1428     }
1429     return FALSE;
1430 }
1431
1432 void play2team(float t, string filename)
1433 {
1434     entity head;
1435
1436     if (autocvar_bot_sound_monopoly)
1437         return;
1438
1439     FOR_EACH_REALPLAYER(head)
1440     {
1441         if (head.team == t)
1442             play2(head, filename);
1443     }
1444 }
1445
1446 void play2all(string samp)
1447 {
1448     if (autocvar_bot_sound_monopoly)
1449         return;
1450
1451     sound(world, CH_INFO, samp, VOL_BASE, ATTN_NONE);
1452 }
1453
1454 void PrecachePlayerSounds(string f);
1455 void precache_playermodel(string m)
1456 {
1457         float globhandle, i, n;
1458         string f;
1459
1460         if(substring(m, -9,5) == "_lod1")
1461                 return;
1462         if(substring(m, -9,5) == "_lod2")
1463                 return;
1464         precache_model(m);
1465         if(sv_loddistance1)
1466         {
1467                 f = strcat(substring(m, 0, -5), "_lod1", substring(m, -4, -1));
1468                 if(fexists(f))
1469                         precache_model(f);
1470                 f = strcat(substring(m, 0, -5), "_lod2", substring(m, -4, -1));
1471                 if(fexists(f))
1472                         precache_model(f);
1473         }
1474
1475         globhandle = search_begin(strcat(m, "_*.sounds"), TRUE, FALSE);
1476         if (globhandle < 0)
1477                 return;
1478         n = search_getsize(globhandle);
1479         for (i = 0; i < n; ++i)
1480         {
1481                 //print(search_getfilename(globhandle, i), "\n");
1482                 f = search_getfilename(globhandle, i);
1483                 PrecachePlayerSounds(f);
1484         }
1485         search_end(globhandle);
1486 }
1487 void precache_all_playermodels(string pattern)
1488 {
1489         float globhandle, i, n;
1490         string f;
1491
1492         globhandle = search_begin(pattern, TRUE, FALSE);
1493         if (globhandle < 0)
1494                 return;
1495         n = search_getsize(globhandle);
1496         for (i = 0; i < n; ++i)
1497         {
1498                 //print(search_getfilename(globhandle, i), "\n");
1499                 f = search_getfilename(globhandle, i);
1500                 precache_playermodel(f);
1501         }
1502         search_end(globhandle);
1503 }
1504
1505 void precache()
1506 {
1507     // gamemode related things
1508     precache_model ("models/misc/chatbubble.spr");
1509     if (g_runematch)
1510     {
1511         precache_model ("models/runematch/curse.mdl");
1512         precache_model ("models/runematch/rune.mdl");
1513     }
1514
1515 #ifdef TTURRETS_ENABLED
1516     if (autocvar_g_turrets)
1517         turrets_precash();
1518 #endif
1519
1520     // Precache all player models if desired
1521     if (autocvar_sv_precacheplayermodels)
1522     {
1523         PrecachePlayerSounds("sound/player/default.sounds");
1524         precache_all_playermodels("models/player/*.zym");
1525         precache_all_playermodels("models/player/*.dpm");
1526         precache_all_playermodels("models/player/*.md3");
1527         precache_all_playermodels("models/player/*.psk");
1528         precache_all_playermodels("models/player/*.iqm");
1529     }
1530
1531     if (autocvar_sv_defaultcharacter)
1532     {
1533         string s;
1534         s = autocvar_sv_defaultplayermodel_red;
1535         if (s != "")
1536             precache_playermodel(s);
1537         s = autocvar_sv_defaultplayermodel_blue;
1538         if (s != "")
1539             precache_playermodel(s);
1540         s = autocvar_sv_defaultplayermodel_yellow;
1541         if (s != "")
1542             precache_playermodel(s);
1543         s = autocvar_sv_defaultplayermodel_pink;
1544         if (s != "")
1545             precache_playermodel(s);
1546         s = autocvar_sv_defaultplayermodel;
1547         if (s != "")
1548             precache_playermodel(s);
1549     }
1550
1551     if (g_footsteps)
1552     {
1553         PrecacheGlobalSound((globalsound_step = "misc/footstep0 6"));
1554         PrecacheGlobalSound((globalsound_metalstep = "misc/metalfootstep0 6"));
1555     }
1556
1557     // gore and miscellaneous sounds
1558     //precache_sound ("misc/h2ohit.wav");
1559     precache_model ("models/hook.md3");
1560     precache_sound ("misc/armorimpact.wav");
1561     precache_sound ("misc/bodyimpact1.wav");
1562     precache_sound ("misc/bodyimpact2.wav");
1563     precache_sound ("misc/gib.wav");
1564     precache_sound ("misc/gib_splat01.wav");
1565     precache_sound ("misc/gib_splat02.wav");
1566     precache_sound ("misc/gib_splat03.wav");
1567     precache_sound ("misc/gib_splat04.wav");
1568     PrecacheGlobalSound((globalsound_fall = "misc/hitground 4"));
1569     PrecacheGlobalSound((globalsound_metalfall = "misc/metalhitground 4"));
1570     precache_sound ("misc/null.wav");
1571     precache_sound ("misc/spawn.wav");
1572     precache_sound ("misc/talk.wav");
1573     precache_sound ("misc/teleport.wav");
1574     precache_sound ("misc/poweroff.wav");
1575     precache_sound ("player/lava.wav");
1576     precache_sound ("player/slime.wav");
1577
1578     if (g_jetpack)
1579         precache_sound ("misc/jetpack_fly.wav");
1580
1581     precache_model ("models/sprites/0.spr32");
1582     precache_model ("models/sprites/1.spr32");
1583     precache_model ("models/sprites/2.spr32");
1584     precache_model ("models/sprites/3.spr32");
1585     precache_model ("models/sprites/4.spr32");
1586     precache_model ("models/sprites/5.spr32");
1587     precache_model ("models/sprites/6.spr32");
1588     precache_model ("models/sprites/7.spr32");
1589     precache_model ("models/sprites/8.spr32");
1590     precache_model ("models/sprites/9.spr32");
1591     precache_model ("models/sprites/10.spr32");
1592
1593     // common weapon precaches
1594         precache_sound ("weapons/reload.wav"); // until weapons have individual reload sounds, precache the reload sound here
1595     precache_sound ("weapons/weapon_switch.wav");
1596     precache_sound ("weapons/weaponpickup.wav");
1597     precache_sound ("weapons/unavailable.wav");
1598     precache_sound ("weapons/dryfire.wav");
1599     if (g_grappling_hook)
1600     {
1601         precache_sound ("weapons/hook_fire.wav"); // hook
1602         precache_sound ("weapons/hook_impact.wav"); // hook
1603     }
1604
1605     if(autocvar_sv_precacheweapons)
1606     {
1607         //precache weapon models/sounds
1608         float wep;
1609         wep = WEP_FIRST;
1610         while (wep <= WEP_LAST)
1611         {
1612             weapon_action(wep, WR_PRECACHE);
1613             wep = wep + 1;
1614         }
1615     }
1616
1617     precache_model("models/elaser.mdl");
1618     precache_model("models/laser.mdl");
1619     precache_model("models/ebomb.mdl");
1620
1621 #if 0
1622     // Disabled this code because it simply does not work (e.g. ignores bgmvolume, overlaps with "cd loop" controlled tracks).
1623
1624     if (!self.noise && self.music) // quake 3 uses the music field
1625         self.noise = self.music;
1626
1627     // plays music for the level if there is any
1628     if (self.noise)
1629     {
1630         precache_sound (self.noise);
1631         ambientsound ('0 0 0', self.noise, VOL_BASE, ATTN_NONE);
1632     }
1633 #endif
1634 }
1635
1636 // sorry, but using \ in macros breaks line numbers
1637 #define WRITESPECTATABLE_MSG_ONE_VARNAME(varname,statement) entity varname; varname = msg_entity; FOR_EACH_REALCLIENT(msg_entity) if(msg_entity == varname || (msg_entity.classname == STR_SPECTATOR && msg_entity.enemy == varname)) statement msg_entity = varname
1638 #define WRITESPECTATABLE_MSG_ONE(statement) WRITESPECTATABLE_MSG_ONE_VARNAME(oldmsg_entity, statement)
1639 #define WRITESPECTATABLE(msg,statement) if(msg == MSG_ONE) { WRITESPECTATABLE_MSG_ONE(statement); } else statement float WRITESPECTATABLE_workaround = 0
1640
1641
1642 void Send_CSQC_Centerprint_Generic(entity e, float id, string s, float duration, float countdown_num)
1643 {
1644         if (clienttype(e) == CLIENTTYPE_REAL)
1645         {
1646                 msg_entity = e;
1647                 WRITESPECTATABLE_MSG_ONE({
1648                         WriteByte(MSG_ONE, SVC_TEMPENTITY);
1649                         WriteByte(MSG_ONE, TE_CSQC_CENTERPRINT_GENERIC);
1650                         WriteByte(MSG_ONE, id);
1651                         WriteString(MSG_ONE, s);
1652                         if (id != 0 && s != "")
1653                         {
1654                                 WriteByte(MSG_ONE, duration);
1655                                 WriteByte(MSG_ONE, countdown_num);
1656                         }
1657                 });
1658         }
1659 }
1660 void Send_CSQC_Centerprint_Generic_Expire(entity e, float id)
1661 {
1662         Send_CSQC_Centerprint_Generic(e, id, "", 1, 0);
1663 }
1664 // WARNING: this kills the trace globals
1665 #define EXACTTRIGGER_TOUCH if(WarpZoneLib_ExactTrigger_Touch()) return
1666 #define EXACTTRIGGER_INIT  WarpZoneLib_ExactTrigger_Init()
1667
1668 #define INITPRIO_FIRST              0
1669 #define INITPRIO_GAMETYPE           0
1670 #define INITPRIO_GAMETYPE_FALLBACK  1
1671 #define INITPRIO_FINDTARGET        10
1672 #define INITPRIO_DROPTOFLOOR       20
1673 #define INITPRIO_SETLOCATION       90
1674 #define INITPRIO_LINKDOORS         91
1675 #define INITPRIO_LAST              99
1676
1677 .void(void) initialize_entity;
1678 .float initialize_entity_order;
1679 .entity initialize_entity_next;
1680 entity initialize_entity_first;
1681
1682 void make_safe_for_remove(entity e)
1683 {
1684     if (e.initialize_entity)
1685     {
1686         entity ent, prev;
1687         for (ent = initialize_entity_first; ent; )
1688         {
1689             if ((ent == e) || ((ent.classname == "initialize_entity") && (ent.enemy == e)))
1690             {
1691                 //print("make_safe_for_remove: getting rid of initializer ", etos(ent), "\n");
1692                 // skip it in linked list
1693                 if (prev)
1694                 {
1695                     prev.initialize_entity_next = ent.initialize_entity_next;
1696                     ent = prev.initialize_entity_next;
1697                 }
1698                 else
1699                 {
1700                     initialize_entity_first = ent.initialize_entity_next;
1701                     ent = initialize_entity_first;
1702                 }
1703             }
1704             else
1705             {
1706                 prev = ent;
1707                 ent = ent.initialize_entity_next;
1708             }
1709         }
1710     }
1711 }
1712
1713 void objerror(string s)
1714 {
1715     make_safe_for_remove(self);
1716     objerror_builtin(s);
1717 }
1718
1719 .float remove_except_protected_forbidden;
1720 void remove_except_protected(entity e)
1721 {
1722         if(e.remove_except_protected_forbidden)
1723                 error("not allowed to remove this at this point");
1724         remove_builtin(e);
1725 }
1726
1727 void remove_unsafely(entity e)
1728 {
1729     if(e.classname == "spike")
1730         error("Removing spikes is forbidden (crylink bug), please report");
1731     remove_builtin(e);
1732 }
1733
1734 void remove_safely(entity e)
1735 {
1736     make_safe_for_remove(e);
1737     remove_builtin(e);
1738 }
1739
1740 void InitializeEntity(entity e, void(void) func, float order)
1741 {
1742     entity prev, cur;
1743
1744     if (!e || e.initialize_entity)
1745     {
1746         // make a proxy initializer entity
1747         entity e_old;
1748         e_old = e;
1749         e = spawn();
1750         e.classname = "initialize_entity";
1751         e.enemy = e_old;
1752     }
1753
1754     e.initialize_entity = func;
1755     e.initialize_entity_order = order;
1756
1757     cur = initialize_entity_first;
1758     for (;;)
1759     {
1760         if (!cur || cur.initialize_entity_order > order)
1761         {
1762             // insert between prev and cur
1763             if (prev)
1764                 prev.initialize_entity_next = e;
1765             else
1766                 initialize_entity_first = e;
1767             e.initialize_entity_next = cur;
1768             return;
1769         }
1770         prev = cur;
1771         cur = cur.initialize_entity_next;
1772     }
1773 }
1774 void InitializeEntitiesRun()
1775 {
1776     entity startoflist;
1777     startoflist = initialize_entity_first;
1778     initialize_entity_first = world;
1779     remove = remove_except_protected;
1780     for (self = startoflist; self; self = self.initialize_entity_next)
1781     {
1782         self.remove_except_protected_forbidden = 1;
1783     }
1784     for (self = startoflist; self; )
1785     {
1786         entity e;
1787         var void(void) func;
1788         e = self.initialize_entity_next;
1789         func = self.initialize_entity;
1790         self.initialize_entity_order = 0;
1791         self.initialize_entity = func_null;
1792         self.initialize_entity_next = world;
1793         self.remove_except_protected_forbidden = 0;
1794         if (self.classname == "initialize_entity")
1795         {
1796             entity e_old;
1797             e_old = self.enemy;
1798             remove_builtin(self);
1799             self = e_old;
1800         }
1801         //dprint("Delayed initialization: ", self.classname, "\n");
1802         if(func != func_null)
1803             func();
1804         else
1805         {
1806             eprint(self);
1807             backtrace(strcat("Null function in: ", self.classname, "\n"));
1808         }
1809         self = e;
1810     }
1811     remove = remove_unsafely;
1812 }
1813
1814 .float uncustomizeentityforclient_set;
1815 .void(void) uncustomizeentityforclient;
1816 void(void) SUB_Nullpointer = #0;
1817 void UncustomizeEntitiesRun()
1818 {
1819     entity oldself;
1820     oldself = self;
1821     for (self = world; (self = findfloat(self, uncustomizeentityforclient_set, 1)); )
1822         self.uncustomizeentityforclient();
1823     self = oldself;
1824 }
1825 void SetCustomizer(entity e, float(void) customizer, void(void) uncustomizer)
1826 {
1827     e.customizeentityforclient = customizer;
1828     e.uncustomizeentityforclient = uncustomizer;
1829     e.uncustomizeentityforclient_set = (uncustomizer != SUB_Nullpointer);
1830 }
1831
1832 .float nottargeted;
1833 #define IFTARGETED if(!self.nottargeted && self.targetname != "")
1834
1835 void() SUB_Remove;
1836 void Net_LinkEntity(entity e, float docull, float dt, float(entity, float) sendfunc)
1837 {
1838     vector mi, ma;
1839
1840     if (e.classname == "")
1841         e.classname = "net_linked";
1842
1843     if (e.model == "" || self.modelindex == 0)
1844     {
1845         mi = e.mins;
1846         ma = e.maxs;
1847         setmodel(e, "null");
1848         setsize(e, mi, ma);
1849     }
1850
1851     e.SendEntity = sendfunc;
1852     e.SendFlags = 0xFFFFFF;
1853
1854     if (!docull)
1855         e.effects |= EF_NODEPTHTEST;
1856
1857     if (dt)
1858     {
1859         e.nextthink = time + dt;
1860         e.think = SUB_Remove;
1861     }
1862 }
1863
1864 void adaptor_think2touch()
1865 {
1866     entity o;
1867     o = other;
1868     other = world;
1869     self.touch();
1870     other = o;
1871 }
1872
1873 void adaptor_think2use()
1874 {
1875     entity o, a;
1876     o = other;
1877     a = activator;
1878     activator = world;
1879     other = world;
1880     self.use();
1881     other = o;
1882     activator = a;
1883 }
1884
1885 void adaptor_think2use_hittype_splash() // for timed projectile detonation
1886 {
1887         if not(self.flags & FL_ONGROUND) // if onground, we ARE touching something, but HITTYPE_SPLASH is to be networked if the damage causing projectile is not touching ANYTHING
1888                 self.projectiledeathtype |= HITTYPE_SPLASH;
1889         adaptor_think2use();
1890 }
1891
1892 // deferred dropping
1893 void DropToFloor_Handler()
1894 {
1895     droptofloor_builtin();
1896     self.dropped_origin = self.origin;
1897 }
1898
1899 void droptofloor()
1900 {
1901     InitializeEntity(self, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
1902 }
1903
1904
1905
1906 float trace_hits_box_a0, trace_hits_box_a1;
1907
1908 float trace_hits_box_1d(float end, float thmi, float thma)
1909 {
1910     if (end == 0)
1911     {
1912         // just check if x is in range
1913         if (0 < thmi)
1914             return FALSE;
1915         if (0 > thma)
1916             return FALSE;
1917     }
1918     else
1919     {
1920         // do the trace with respect to x
1921         // 0 -> end has to stay in thmi -> thma
1922         trace_hits_box_a0 = max(trace_hits_box_a0, min(thmi / end, thma / end));
1923         trace_hits_box_a1 = min(trace_hits_box_a1, max(thmi / end, thma / end));
1924         if (trace_hits_box_a0 > trace_hits_box_a1)
1925             return FALSE;
1926     }
1927     return TRUE;
1928 }
1929
1930 float trace_hits_box(vector start, vector end, vector thmi, vector thma)
1931 {
1932     end -= start;
1933     thmi -= start;
1934     thma -= start;
1935     // now it is a trace from 0 to end
1936
1937     trace_hits_box_a0 = 0;
1938     trace_hits_box_a1 = 1;
1939
1940     if (!trace_hits_box_1d(end_x, thmi_x, thma_x))
1941         return FALSE;
1942     if (!trace_hits_box_1d(end_y, thmi_y, thma_y))
1943         return FALSE;
1944     if (!trace_hits_box_1d(end_z, thmi_z, thma_z))
1945         return FALSE;
1946
1947     return TRUE;
1948 }
1949
1950 float tracebox_hits_box(vector start, vector mi, vector ma, vector end, vector thmi, vector thma)
1951 {
1952     return trace_hits_box(start, end, thmi - ma, thma - mi);
1953 }
1954
1955 float SUB_NoImpactCheck()
1956 {
1957         // zero hitcontents = this is not the real impact, but either the
1958         // mirror-impact of something hitting the projectile instead of the
1959         // projectile hitting the something, or a touchareagrid one. Neither of
1960         // these stop the projectile from moving, so...
1961         if(trace_dphitcontents == 0)
1962         {
1963                 //dprint("A hit happened with zero hit contents... DEBUG THIS, this should never happen for projectiles! Projectile will self-destruct.\n");
1964                 dprint(sprintf(_("A hit from a projectile happened with no hit contents! DEBUG THIS, this should never happen for projectiles! Profectile will self-destruct. (edict: %d, classname: %s, origin: %s)\n"), num_for_edict(self), self.classname, vtos(self.origin)));
1965                 checkclient();
1966         }
1967     if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1968         return 1;
1969     if (other == world && self.size != '0 0 0')
1970     {
1971         vector tic;
1972         tic = self.velocity * sys_frametime;
1973         tic = tic + normalize(tic) * vlen(self.maxs - self.mins);
1974         traceline(self.origin - tic, self.origin + tic, MOVE_NORMAL, self);
1975         if (trace_fraction >= 1)
1976         {
1977             dprint("Odd... did not hit...?\n");
1978         }
1979         else if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1980         {
1981             dprint("Detected and prevented the sky-grapple bug.\n");
1982             return 1;
1983         }
1984     }
1985
1986     return 0;
1987 }
1988
1989 #define SUB_OwnerCheck() (other && (other == self.owner))
1990
1991 void RemoveGrapplingHook(entity pl);
1992 void W_Crylink_Dequeue(entity e);
1993 float WarpZone_Projectile_Touch_ImpactFilter_Callback()
1994 {
1995         if(SUB_OwnerCheck())
1996                 return TRUE;
1997         if(SUB_NoImpactCheck())
1998         {
1999                 if(self.classname == "grapplinghook")
2000                         RemoveGrapplingHook(self.realowner);
2001                 else if(self.classname == "spike")
2002                 {
2003                         W_Crylink_Dequeue(self);
2004                         remove(self);
2005                 }
2006                 else
2007                         remove(self);
2008                 return TRUE;
2009         }
2010         if(trace_ent && trace_ent.solid > SOLID_TRIGGER)
2011                 UpdateCSQCProjectile(self);
2012         return FALSE;
2013 }
2014 #define PROJECTILE_TOUCH if(WarpZone_Projectile_Touch()) return
2015
2016 float MAX_IPBAN_URIS           = 16;
2017                               
2018 float URI_GET_DISCARD          = 0;
2019 float URI_GET_IPBAN            = 1;
2020 float URI_GET_IPBAN_END        = 16;
2021
2022 void URI_Get_Callback(float id, float status, string data)
2023 {
2024     dprint("Received HTTP request data for id ", ftos(id), "; status is ", ftos(status), "\nData is:\n");
2025     dprint(data);
2026     dprint("\nEnd of data.\n");
2027
2028     if(url_URI_Get_Callback(id, status, data))
2029     {
2030         // handled
2031     }
2032     else if (id == URI_GET_DISCARD)
2033     {
2034         // discard
2035     }
2036     else if (id >= URI_GET_IPBAN && id <= URI_GET_IPBAN_END)
2037     {
2038         // online ban list
2039         OnlineBanList_URI_Get_Callback(id, status, data);
2040     }
2041     else
2042     {
2043         print("Received HTTP request data for an invalid id ", ftos(id), ".\n");
2044     }
2045 }
2046
2047 void print_to(entity e, string s)
2048 {
2049     if (e)
2050         sprint(e, strcat(s, "\n"));
2051     else
2052         print(s, "\n");
2053 }
2054
2055 string uid2name(string myuid) {
2056         string s;
2057         s = db_get(ServerProgsDB, strcat("/uid2name/", myuid));
2058
2059         // FIXME remove this later after 0.6 release
2060         // convert old style broken records to correct style
2061         if(s == "")
2062         {
2063                 s = db_get(ServerProgsDB, strcat("uid2name", myuid));
2064                 if(s != "")
2065                 {
2066                         db_put(ServerProgsDB, strcat("/uid2name/", myuid), s);
2067                         db_put(ServerProgsDB, strcat("uid2name", myuid), "");
2068                 }
2069         }
2070         
2071         if(s == "")
2072                 s = "^1Unregistered Player";
2073         return s;
2074 }
2075
2076 float race_readTime(string map, float pos)
2077 {
2078         string rr;
2079         if(g_cts)
2080                 rr = CTS_RECORD;
2081         else
2082                 rr = RACE_RECORD;
2083
2084         return stof(db_get(ServerProgsDB, strcat(map, rr, "time", ftos(pos))));
2085 }
2086
2087 string race_readUID(string map, float pos)
2088 {
2089         string rr;
2090         if(g_cts)
2091                 rr = CTS_RECORD;
2092         else
2093                 rr = RACE_RECORD;
2094
2095         return db_get(ServerProgsDB, strcat(map, rr, "crypto_idfp", ftos(pos)));
2096 }
2097
2098 float race_readPos(string map, float t) {
2099         float i;
2100         for (i = 1; i <= RANKINGS_CNT; ++i)
2101                 if (race_readTime(map, i) == 0 || race_readTime(map, i) > t)
2102                         return i;
2103
2104         return 0; // pos is zero if unranked
2105 }
2106
2107 void race_writeTime(string map, float t, string myuid)
2108 {
2109         string rr;
2110         if(g_cts)
2111                 rr = CTS_RECORD;
2112         else
2113                 rr = RACE_RECORD;
2114
2115         float newpos;
2116         newpos = race_readPos(map, t);
2117
2118         float i, prevpos;
2119         for(i = 1; i <= RANKINGS_CNT; ++i)
2120         {
2121                 if(race_readUID(map, i) == myuid)
2122                         prevpos = i;
2123         }
2124         if (prevpos) { // player improved his existing record, only have to iterate on ranks between new and old recs
2125                 for (i = prevpos; i > newpos; --i) {
2126                         db_put(ServerProgsDB, strcat(map, rr, "time", ftos(i)), ftos(race_readTime(map, i - 1)));
2127                         db_put(ServerProgsDB, strcat(map, rr, "crypto_idfp", ftos(i)), race_readUID(map, i - 1));
2128                 }
2129         } else { // player has no ranked record yet
2130                 for (i = RANKINGS_CNT; i > newpos; --i) {
2131                         db_put(ServerProgsDB, strcat(map, rr, "time", ftos(i)), ftos(race_readTime(map, i - 1)));
2132                         db_put(ServerProgsDB, strcat(map, rr, "crypto_idfp", ftos(i)), race_readUID(map, i - 1));
2133                 }
2134         }
2135
2136         // store new time itself
2137         db_put(ServerProgsDB, strcat(map, rr, "time", ftos(newpos)), ftos(t));
2138         db_put(ServerProgsDB, strcat(map, rr, "crypto_idfp", ftos(newpos)), myuid);
2139 }
2140
2141 string race_readName(string map, float pos)
2142 {
2143         string rr;
2144         if(g_cts)
2145                 rr = CTS_RECORD;
2146         else
2147                 rr = RACE_RECORD;
2148
2149         return uid2name(db_get(ServerProgsDB, strcat(map, rr, "crypto_idfp", ftos(pos))));
2150 }
2151
2152 string race_placeName(float pos) {
2153         if(floor((mod(pos, 100))/10) * 10 != 10) // examples: 12th, 111th, 213th will not execute this block
2154         {
2155                 if(mod(pos, 10) == 1)
2156                         return strcat(ftos(pos), "st");
2157                 else if(mod(pos, 10) == 2)
2158                         return strcat(ftos(pos), "nd");
2159                 else if(mod(pos, 10) == 3)
2160                         return strcat(ftos(pos), "rd");
2161                 else
2162                         return strcat(ftos(pos), "th");
2163         }
2164         else
2165                 return strcat(ftos(pos), "th");
2166 }
2167 string getrecords(float page) // 50 records per page
2168 {
2169     float rec;
2170     string h;
2171     float r;
2172     float i;
2173     string s;
2174
2175     rec = 0;
2176
2177     s = "";
2178
2179     if (g_ctf)
2180     {
2181         for (i = page * 200; i < MapInfo_count && i < page * 200 + 200; ++i)
2182         {
2183             if (MapInfo_Get_ByID(i))
2184             {
2185                 r = stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, "/captimerecord/time")));
2186                 if (r == 0)
2187                     continue;
2188                 // TODO: uid2name
2189                 h = db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, "/captimerecord/netname"));
2190                 s = strcat(s, strpad(32, MapInfo_Map_bspname), " ", strpad(-6, ftos_decimals(r, 2)), " ", h, "\n");
2191                 ++rec;
2192             }
2193         }
2194     }
2195
2196     if (g_race)
2197     {
2198         for (i = page * 200; i < MapInfo_count && i < page * 200 + 200; ++i)
2199         {
2200             if (MapInfo_Get_ByID(i))
2201             {
2202                 r = race_readTime(MapInfo_Map_bspname, 1);
2203                 if (r == 0)
2204                     continue;
2205                 h = race_readName(MapInfo_Map_bspname, 1);
2206                 s = strcat(s, strpad(32, MapInfo_Map_bspname), " ", strpad(-8, TIME_ENCODED_TOSTRING(r)), " ", h, "\n");
2207                 ++rec;
2208             }
2209         }
2210     }
2211
2212     if (g_cts)
2213     {
2214         for (i = page * 200; i < MapInfo_count && i < page * 200 + 200; ++i)
2215         {
2216             if (MapInfo_Get_ByID(i))
2217             {
2218                 r = race_readTime(MapInfo_Map_bspname, 1);
2219                 if (r == 0)
2220                     continue;
2221                 h = race_readName(MapInfo_Map_bspname, 1);
2222                 s = strcat(s, strpad(32, MapInfo_Map_bspname), " ", strpad(-8, TIME_ENCODED_TOSTRING(r)), " ", h, "\n");
2223                 ++rec;
2224             }
2225         }
2226     }
2227
2228     MapInfo_ClearTemps();
2229
2230     if (s == "" && page == 0)
2231         return "No records are available on this server.\n";
2232     else
2233         return s;
2234 }
2235
2236 string getrankings()
2237 {
2238     string n;
2239     float t;
2240     float i;
2241     string s;
2242     string p;
2243     string map;
2244
2245     s = "";
2246
2247     map = GetMapname();
2248
2249     for (i = 1; i <= RANKINGS_CNT; ++i)
2250     {
2251         t = race_readTime(map, i);
2252         if (t == 0)
2253             continue;
2254         n = race_readName(map, i);
2255         p = race_placeName(i);
2256         s = strcat(s, strpad(8, p), " ", strpad(-8, TIME_ENCODED_TOSTRING(t)), " ", n, "\n");
2257     }
2258
2259     MapInfo_ClearTemps();
2260
2261     if (s == "")
2262         return strcat("No records are available for the map: ", map, "\n");
2263     else
2264         return strcat("Records for ", map, ":\n", s);
2265 }
2266
2267 #define LADDER_FIRSTPOINT 100
2268 #define LADDER_CNT 10
2269         // position X still gives LADDER_FIRSTPOINT/X points
2270 #define LADDER_SIZE 30
2271         // ladder shows the top X players
2272 string top_uids[LADDER_SIZE];
2273 float top_scores[LADDER_SIZE];
2274 string getladder()
2275 {
2276     float i, j, k, uidcnt;
2277     string s, temp_s;
2278
2279     s = "";
2280     temp_s = "";
2281
2282     string rr;
2283     if(g_cts)
2284         rr = CTS_RECORD;
2285     else
2286         rr = RACE_RECORD;
2287
2288     string myuid;
2289
2290     for (k = 0; k < MapInfo_count; ++k)
2291     {
2292         if (MapInfo_Get_ByID(k))
2293         {
2294                 for (i = 0; i <= LADDER_CNT; ++i) { // i = 0 because it is the speed award
2295                         if(i == 0) // speed award
2296                         {
2297                                 if(stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, rr, "speed/speed"))) == 0)
2298                                         continue;
2299
2300                                 myuid = db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, rr, "speed/crypto_idfp"));
2301                         }
2302                         else // normal record, if it exists (else break)
2303                         {
2304                                 if(race_readTime(MapInfo_Map_bspname, i) == 0)
2305                                         continue;
2306
2307                                 myuid = race_readUID(MapInfo_Map_bspname, i);
2308                         }
2309
2310                         // string s contains:
2311                         // arg 0 = # of speed recs
2312                         // arg 1 = # of 1st place recs
2313                         // arg 2 = # of 2nd place recs
2314                         // ... etc
2315                         // LADDER_CNT+1 = total points
2316
2317                         temp_s = db_get(TemporaryDB, strcat("ladder", myuid));
2318                         if (temp_s == "")
2319                         {
2320                             db_put(TemporaryDB, strcat("uid", ftos(uidcnt)), myuid);
2321                             ++uidcnt;
2322                             for (j = 0; j <= LADDER_CNT + 1; ++j)
2323                             {
2324                                 if(j != LADDER_CNT + 1)
2325                                     temp_s = strcat(temp_s, "0 ");
2326                                 else
2327                                     temp_s = strcat(temp_s, "0");
2328                             }
2329                         }
2330
2331                         tokenize_console(temp_s);
2332                         s = "";
2333
2334                         if(i == 0) // speed award
2335                             for (j = 0; j <= LADDER_CNT; ++j) // loop over each arg in the string
2336                             {
2337                                 if(j == 0) // speed award
2338                                     s = strcat(s, ftos(stof(argv(j)) +1)); // add 1 to speed rec count and write
2339                                 else
2340                                     s = strcat(s, " ", argv(j)); // just copy over everything else
2341                             }
2342                         else // record
2343                             for (j = 0; j <= LADDER_CNT; ++j) // loop over each arg in the string
2344                             {
2345                                 if(j == 0)
2346                                     s = strcat(s, argv(j)); // speed award, dont prefix with " "
2347                                 else if(j == i) // wanted rec!
2348                                     s = strcat(s, " ", ftos(stof(argv(j)) +1)); // update argv(j)
2349                                 else
2350                                     s = strcat(s, " ", argv(j)); // just copy over everything else
2351                             }
2352
2353                         // total points are (by default) calculated like this:
2354                         // speedrec = floor(100 / 10) = 10 points
2355                         // 1st place = floor(100 / 1) = 100 points
2356                         // 2nd place = floor(100 / 2) = 50 points
2357                         // 3rd place = floor(100 / 3) = 33 points
2358                         // 4th place = floor(100 / 4) = 25 points
2359                         // 5th place = floor(100 / 5) = 20 points
2360                         // ... etc
2361
2362                         if(i == 0)
2363                             s = strcat(s, " ", ftos(stof(argv(LADDER_CNT+1)) + LADDER_FIRSTPOINT / 10)); // speed award, add LADDER_FIRSTPOINT / 10 points
2364                         else
2365                             s = strcat(s, " ", ftos(stof(argv(LADDER_CNT+1)) + floor(LADDER_FIRSTPOINT / i))); // record, add LADDER_FIRSTPOINT / i points
2366
2367                         db_put(TemporaryDB, strcat("ladder", myuid), s);
2368                 }
2369         }
2370     }
2371
2372     float thiscnt;
2373     string thisuid;
2374     for (i = 0; i <= uidcnt; ++i) // for each known uid
2375     {
2376         thisuid = db_get(TemporaryDB, strcat("uid", ftos(i)));
2377         temp_s = db_get(TemporaryDB, strcat("ladder", thisuid));
2378         tokenize_console(temp_s);
2379         thiscnt = stof(argv(LADDER_CNT+1));
2380
2381         if(thiscnt > top_scores[LADDER_SIZE-1])
2382         for (j = 0; j < LADDER_SIZE; ++j) // for each place in ladder
2383         {
2384             if(thiscnt > top_scores[j])
2385             {
2386                 for (k = LADDER_SIZE-1; k >= j; --k)
2387                 {
2388                     top_uids[k] = top_uids[k-1];
2389                     top_scores[k] = top_scores[k-1];
2390                 }
2391                 top_uids[j] = thisuid;
2392                 top_scores[j] = thiscnt;
2393                 break;
2394             }
2395         }
2396     }
2397
2398     s = "^3-----------------------\n\n";
2399
2400     s = strcat(s, "Pos ^3|");
2401     s = strcat(s, " ^7Total  ^3|");
2402     for (i = 1; i <= LADDER_CNT; ++i)
2403     {
2404         s = strcat(s, " ^7", race_placeName(i), " ^3|");
2405     }
2406     s = strcat(s, " ^7Speed awards ^3| ^7Name");
2407
2408     s = strcat(s, "\n^3----+--------");
2409     for (i = 1; i <= min(9, LADDER_CNT); ++i)
2410     {
2411         s = strcat(s, "+-----");
2412     }
2413 #if LADDER_CNT > 9
2414     for (i = 1; i <= LADDER_CNT - 9; ++i)
2415     {
2416         s = strcat(s, "+------");
2417     }
2418 #endif
2419
2420     s = strcat(s, "+--------------+--------------------\n");
2421
2422     for (i = 0; i < LADDER_SIZE; ++i)
2423     {
2424         temp_s = db_get(TemporaryDB, strcat("ladder", top_uids[i]));
2425         tokenize_console(temp_s);
2426         if (argv(LADDER_CNT+1) == "") // total is 0, skip
2427             continue;
2428         s = strcat(s, strpad(4, race_placeName(i+1)), "^3| ^7"); // pos
2429         s = strcat(s, strpad(7, argv(LADDER_CNT+1)), "^3| ^7"); // total
2430         for (j = 1; j <= min(9, LADDER_CNT); ++j)
2431         {
2432             s = strcat(s, strpad(4, argv(j)), "^3| ^7"); // 1st, 2nd, 3rd etc cnt
2433         }
2434 #if LADDER_CNT > 9
2435         for (j = 10; j <= LADDER_CNT; ++j)
2436         {
2437             s = strcat(s, strpad(4, argv(j)), " ^3| ^7"); // 1st, 2nd, 3rd etc cnt
2438         }
2439 #endif
2440
2441         s = strcat(s, strpad(13, argv(0)), "^3| ^7"); // speed award cnt
2442         s = strcat(s, uid2name(top_uids[i]), "\n"); // name
2443     }
2444
2445     MapInfo_ClearTemps();
2446
2447     if (s == "")
2448         return "No ladder on this server!\n";
2449     else
2450         return strcat("Top ", ftos(LADDER_SIZE), " ladder rankings:\n", s);
2451 }
2452
2453
2454 float MoveToRandomMapLocation(entity e, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
2455 {
2456     float m, i;
2457     vector start, org, delta, end, enddown, mstart;
2458     entity sp;
2459
2460     m = e.dphitcontentsmask;
2461     e.dphitcontentsmask = goodcontents | badcontents;
2462
2463     org = world.mins;
2464     delta = world.maxs - world.mins;
2465
2466     for (i = 0; i < attempts; ++i)
2467     {
2468         start_x = org_x + random() * delta_x;
2469         start_y = org_y + random() * delta_y;
2470         start_z = org_z + random() * delta_z;
2471
2472         // rule 1: start inside world bounds, and outside
2473         // solid, and don't start from somewhere where you can
2474         // fall down to evil
2475         tracebox(start, e.mins, e.maxs, start - '0 0 1' * delta_z, MOVE_NORMAL, e);
2476         if (trace_fraction >= 1)
2477             continue;
2478         if (trace_startsolid)
2479             continue;
2480         if (trace_dphitcontents & badcontents)
2481             continue;
2482         if (trace_dphitq3surfaceflags & badsurfaceflags)
2483             continue;
2484
2485         // rule 2: if we are too high, lower the point
2486         if (trace_fraction * delta_z > maxaboveground)
2487             start = trace_endpos + '0 0 1' * maxaboveground;
2488         enddown = trace_endpos;
2489
2490         // rule 3: make sure we aren't outside the map. This only works
2491         // for somewhat well formed maps. A good rule of thumb is that
2492         // the map should have a convex outside hull.
2493         // these can be traceLINES as we already verified the starting box
2494         mstart = start + 0.5 * (e.mins + e.maxs);
2495         traceline(mstart, mstart + '1 0 0' * delta_x, MOVE_NORMAL, e);
2496         if (trace_fraction >= 1)
2497             continue;
2498         traceline(mstart, mstart - '1 0 0' * delta_x, MOVE_NORMAL, e);
2499         if (trace_fraction >= 1)
2500             continue;
2501         traceline(mstart, mstart + '0 1 0' * delta_y, MOVE_NORMAL, e);
2502         if (trace_fraction >= 1)
2503             continue;
2504         traceline(mstart, mstart - '0 1 0' * delta_y, MOVE_NORMAL, e);
2505         if (trace_fraction >= 1)
2506             continue;
2507         traceline(mstart, mstart + '0 0 1' * delta_z, MOVE_NORMAL, e);
2508         if (trace_fraction >= 1)
2509             continue;
2510
2511         // rule 4: we must "see" some spawnpoint
2512         for(sp = world; (sp = find(sp, classname, "info_player_deathmatch")); )
2513                 if(checkpvs(mstart, sp))
2514                         break;
2515         if(!sp)
2516         {
2517                 for(sp = world; (sp = findflags(sp, flags, FL_ITEM)); )
2518                         if(checkpvs(mstart, sp))
2519                                 break;
2520                 if(!sp)
2521                         continue;
2522         }
2523
2524         // find a random vector to "look at"
2525         end_x = org_x + random() * delta_x;
2526         end_y = org_y + random() * delta_y;
2527         end_z = org_z + random() * delta_z;
2528         end = start + normalize(end - start) * vlen(delta);
2529
2530         // rule 4: start TO end must not be too short
2531         tracebox(start, e.mins, e.maxs, end, MOVE_NORMAL, e);
2532         if (trace_startsolid)
2533             continue;
2534         if (trace_fraction < minviewdistance / vlen(delta))
2535             continue;
2536
2537         // rule 5: don't want to look at sky
2538         if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY)
2539             continue;
2540
2541         // rule 6: we must not end up in trigger_hurt
2542         if (tracebox_hits_trigger_hurt(start, e.mins, e.maxs, enddown))
2543             continue;
2544
2545         break;
2546     }
2547
2548     e.dphitcontentsmask = m;
2549
2550     if (i < attempts)
2551     {
2552         setorigin(e, start);
2553         e.angles = vectoangles(end - start);
2554         dprint("Needed ", ftos(i + 1), " attempts\n");
2555         return TRUE;
2556     }
2557     else
2558         return FALSE;
2559 }
2560
2561 float zcurveparticles_effectno;
2562 vector zcurveparticles_start;
2563 float zcurveparticles_spd;
2564
2565 void endzcurveparticles()
2566 {
2567         if(zcurveparticles_effectno)
2568         {
2569                 // terminator
2570                 WriteShort(MSG_BROADCAST, zcurveparticles_spd | 0x8000);
2571         }
2572         zcurveparticles_effectno = 0;
2573 }
2574
2575 void zcurveparticles(float effectno, vector start, vector end, float end_dz, float spd)
2576 {
2577         spd = bound(0, floor(spd / 16), 32767);
2578         if(effectno != zcurveparticles_effectno || start != zcurveparticles_start)
2579         {
2580                 endzcurveparticles();
2581                 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
2582                 WriteByte(MSG_BROADCAST, TE_CSQC_ZCURVEPARTICLES);
2583                 WriteShort(MSG_BROADCAST, effectno);
2584                 WriteCoord(MSG_BROADCAST, start_x);
2585                 WriteCoord(MSG_BROADCAST, start_y);
2586                 WriteCoord(MSG_BROADCAST, start_z);
2587                 zcurveparticles_effectno = effectno;
2588                 zcurveparticles_start = start;
2589         }
2590         else
2591                 WriteShort(MSG_BROADCAST, zcurveparticles_spd);
2592         WriteCoord(MSG_BROADCAST, end_x);
2593         WriteCoord(MSG_BROADCAST, end_y);
2594         WriteCoord(MSG_BROADCAST, end_z);
2595         WriteCoord(MSG_BROADCAST, end_dz);
2596         zcurveparticles_spd = spd;
2597 }
2598
2599 void zcurveparticles_from_tracetoss(float effectno, vector start, vector end, vector vel)
2600 {
2601         float end_dz;
2602         vector vecxy, velxy;
2603
2604         vecxy = end - start;
2605         vecxy_z = 0;
2606         velxy = vel;
2607         velxy_z = 0;
2608
2609         if (vlen(velxy) < 0.000001 * fabs(vel_z))
2610         {
2611                 endzcurveparticles();
2612                 trailparticles(world, effectno, start, end);
2613                 return;
2614         }
2615
2616         end_dz = vlen(vecxy) / vlen(velxy) * vel_z - (end_z - start_z);
2617         zcurveparticles(effectno, start, end, end_dz, vlen(vel));
2618 }
2619
2620 void write_recordmarker(entity pl, float tstart, float dt)
2621 {
2622     GameLogEcho(strcat(":recordset:", ftos(pl.playerid), ":", ftos(dt)));
2623
2624     // also write a marker into demo files for demotc-race-record-extractor to find
2625     stuffcmd(pl,
2626              strcat(
2627                  strcat("//", strconv(2, 0, 0, GetGametype()), " RECORD SET ", TIME_ENCODED_TOSTRING(TIME_ENCODE(dt))),
2628                  " ", ftos(tstart), " ", ftos(dt), "\n"));
2629 }
2630
2631 vector shotorg_adjustfromclient(vector vecs, float y_is_right, float allowcenter, float algn)
2632 {
2633         switch(algn)
2634         {
2635                 default:
2636                 case 3: // right
2637                         break;
2638
2639                 case 4: // left
2640                         vecs_y = -vecs_y;
2641                         break;
2642
2643                 case 1:
2644                         if(allowcenter) // 2: allow center handedness
2645                         {
2646                                 // center
2647                                 vecs_y = 0;
2648                                 vecs_z -= 2;
2649                         }
2650                         else
2651                         {
2652                                 // right
2653                         }
2654                         break;
2655
2656                 case 2:
2657                         if(allowcenter) // 2: allow center handedness
2658                         {
2659                                 // center
2660                                 vecs_y = 0;
2661                                 vecs_z -= 2;
2662                         }
2663                         else
2664                         {
2665                                 // left
2666                                 vecs_y = -vecs_y;
2667                         }
2668                         break;
2669         }
2670         return vecs;
2671 }
2672
2673 vector shotorg_adjust_values(vector vecs, float y_is_right, float visual, float algn)
2674 {
2675         string s;
2676         vector v;
2677
2678         if (autocvar_g_shootfromeye)
2679         {
2680                 if (visual)
2681                 {
2682                         vecs_y = 0;
2683                         vecs_z -= 2;
2684                 }
2685                 else
2686                 {
2687                         vecs_y = 0;
2688                         vecs_z = 0;
2689                 }
2690         }
2691         else if (autocvar_g_shootfromcenter)
2692         {
2693                 vecs_y = 0;
2694                 vecs_z -= 2;
2695         }
2696         else if ((s = autocvar_g_shootfromfixedorigin) != "")
2697         {
2698                 v = stov(s);
2699                 if (y_is_right)
2700                         v_y = -v_y;
2701                 if (v_x != 0)
2702                         vecs_x = v_x;
2703                 vecs_y = v_y;
2704                 vecs_z = v_z;
2705         }
2706         else if (autocvar_g_shootfromclient)
2707         {
2708                 vecs = shotorg_adjustfromclient(vecs, y_is_right, (autocvar_g_shootfromclient >= 2), algn);
2709         }
2710         return vecs;
2711 }
2712
2713 vector shotorg_adjust(vector vecs, float y_is_right, float visual)
2714 {
2715         return shotorg_adjust_values(vecs, y_is_right, visual, self.owner.cvar_cl_gunalign);
2716 }
2717
2718
2719 void attach_sameorigin(entity e, entity to, string tag)
2720 {
2721     vector org, t_forward, t_left, t_up, e_forward, e_up;
2722     vector org0, ang0;
2723     float tagscale;
2724
2725     ang0 = e.angles;
2726     org0 = e.origin;
2727
2728     org = e.origin - gettaginfo(to, gettagindex(to, tag));
2729     tagscale = pow(vlen(v_forward), -2); // undo a scale on the tag
2730     t_forward = v_forward * tagscale;
2731     t_left = v_right * -tagscale;
2732     t_up = v_up * tagscale;
2733
2734     e.origin_x = org * t_forward;
2735     e.origin_y = org * t_left;
2736     e.origin_z = org * t_up;
2737
2738     // current forward and up directions
2739     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
2740                 e.angles = AnglesTransform_FromVAngles(e.angles);
2741         else
2742                 e.angles = AnglesTransform_FromAngles(e.angles);
2743     fixedmakevectors(e.angles);
2744
2745     // untransform forward, up!
2746     e_forward_x = v_forward * t_forward;
2747     e_forward_y = v_forward * t_left;
2748     e_forward_z = v_forward * t_up;
2749     e_up_x = v_up * t_forward;
2750     e_up_y = v_up * t_left;
2751     e_up_z = v_up * t_up;
2752
2753     e.angles = fixedvectoangles2(e_forward, e_up);
2754     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
2755                 e.angles = AnglesTransform_ToVAngles(e.angles);
2756         else
2757                 e.angles = AnglesTransform_ToAngles(e.angles);
2758
2759     setattachment(e, to, tag);
2760     setorigin(e, e.origin);
2761 }
2762
2763 void detach_sameorigin(entity e)
2764 {
2765     vector org;
2766     org = gettaginfo(e, 0);
2767     e.angles = fixedvectoangles2(v_forward, v_up);
2768     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
2769                 e.angles = AnglesTransform_ToVAngles(e.angles);
2770         else
2771                 e.angles = AnglesTransform_ToAngles(e.angles);
2772     setorigin(e, org);
2773     setattachment(e, world, "");
2774     setorigin(e, e.origin);
2775 }
2776
2777 void follow_sameorigin(entity e, entity to)
2778 {
2779     e.movetype = MOVETYPE_FOLLOW; // make the hole follow
2780     e.aiment = to; // make the hole follow bmodel
2781     e.punchangle = to.angles; // the original angles of bmodel
2782     e.view_ofs = e.origin - to.origin; // relative origin
2783     e.v_angle = e.angles - to.angles; // relative angles
2784 }
2785
2786 void unfollow_sameorigin(entity e)
2787 {
2788     e.movetype = MOVETYPE_NONE;
2789 }
2790
2791 entity gettaginfo_relative_ent;
2792 vector gettaginfo_relative(entity e, float tag)
2793 {
2794     if (!gettaginfo_relative_ent)
2795     {
2796         gettaginfo_relative_ent = spawn();
2797         gettaginfo_relative_ent.effects = EF_NODRAW;
2798     }
2799     gettaginfo_relative_ent.model = e.model;
2800     gettaginfo_relative_ent.modelindex = e.modelindex;
2801     gettaginfo_relative_ent.frame = e.frame;
2802     return gettaginfo(gettaginfo_relative_ent, tag);
2803 }
2804
2805 void SoundEntity_StartSound(entity pl, float chan, string samp, float vol, float attn)
2806 {
2807     float p;
2808     p = pow(2, chan);
2809     if (pl.soundentity.cnt & p)
2810         return;
2811     soundtoat(MSG_ALL, pl.soundentity, gettaginfo(pl.soundentity, 0), chan, samp, vol, attn);
2812     pl.soundentity.cnt |= p;
2813 }
2814
2815 void SoundEntity_StopSound(entity pl, float chan)
2816 {
2817     float p;
2818     p = pow(2, chan);
2819     if (pl.soundentity.cnt & p)
2820     {
2821         stopsoundto(MSG_ALL, pl.soundentity, chan);
2822         pl.soundentity.cnt &~= p;
2823     }
2824 }
2825
2826 void SoundEntity_Attach(entity pl)
2827 {
2828     pl.soundentity = spawn();
2829     pl.soundentity.classname = "soundentity";
2830     pl.soundentity.owner = pl;
2831     setattachment(pl.soundentity, pl, "");
2832     setmodel(pl.soundentity, "null");
2833 }
2834
2835 void SoundEntity_Detach(entity pl)
2836 {
2837     float i;
2838     for (i = 0; i <= 7; ++i)
2839         SoundEntity_StopSound(pl, i);
2840 }
2841
2842
2843 float ParseCommandPlayerSlotTarget_firsttoken;
2844 entity GetCommandPlayerSlotTargetFromTokenizedCommand(float tokens, float idx) // idx = start index
2845 {
2846         string s;
2847         entity e, head;
2848         float n;
2849
2850         s = string_null;
2851
2852         ParseCommandPlayerSlotTarget_firsttoken = -1;
2853
2854         if (tokens > idx)
2855         {
2856                 if (substring(argv(idx), 0, 1) == "#")
2857                 {
2858                         s = substring(argv(idx), 1, -1);
2859                         ++idx;
2860                         if (s == "") if (tokens > idx)
2861                         {
2862                                 s = argv(idx);
2863                                 ++idx;
2864                         }
2865                         ParseCommandPlayerSlotTarget_firsttoken = idx;
2866                         n = stof(s);
2867                         if (s == ftos(n) && n > 0 && n <= maxclients)
2868                         {
2869                                 e = edict_num(n);
2870                                 if (e.flags & FL_CLIENT)
2871                                         return e;
2872                         }
2873                 }
2874                 else
2875                 {
2876                         // it must be a nick name
2877                         s = argv(idx);
2878                         ++idx;
2879                         ParseCommandPlayerSlotTarget_firsttoken = idx;
2880
2881                         n = 0;
2882                         FOR_EACH_CLIENT(head)
2883                                 if (head.netname == s)
2884                                 {
2885                                         e = head;
2886                                         ++n;
2887                                 }
2888                         if (n == 1)
2889                                 return e;
2890
2891                         s = strdecolorize(s);
2892                         n = 0;
2893                         FOR_EACH_CLIENT(head)
2894                                 if (strdecolorize(head.netname) == s)
2895                                 {
2896                                         e = head;
2897                                         ++n;
2898                                 }
2899                         if (n == 1)
2900                                 return e;
2901                 }
2902         }
2903
2904         return world;
2905 }
2906
2907 .float scale2;
2908
2909 float modeleffect_SendEntity(entity to, float sf)
2910 {
2911         float f;
2912         WriteByte(MSG_ENTITY, ENT_CLIENT_MODELEFFECT);
2913
2914         f = 0;
2915         if(self.velocity != '0 0 0')
2916                 f |= 1;
2917         if(self.angles != '0 0 0')
2918                 f |= 2;
2919         if(self.avelocity != '0 0 0')
2920                 f |= 4;
2921
2922         WriteByte(MSG_ENTITY, f);
2923         WriteShort(MSG_ENTITY, self.modelindex);
2924         WriteByte(MSG_ENTITY, self.skin);
2925         WriteByte(MSG_ENTITY, self.frame);
2926         WriteCoord(MSG_ENTITY, self.origin_x);
2927         WriteCoord(MSG_ENTITY, self.origin_y);
2928         WriteCoord(MSG_ENTITY, self.origin_z);
2929         if(f & 1)
2930         {
2931                 WriteCoord(MSG_ENTITY, self.velocity_x);
2932                 WriteCoord(MSG_ENTITY, self.velocity_y);
2933                 WriteCoord(MSG_ENTITY, self.velocity_z);
2934         }
2935         if(f & 2)
2936         {
2937                 WriteCoord(MSG_ENTITY, self.angles_x);
2938                 WriteCoord(MSG_ENTITY, self.angles_y);
2939                 WriteCoord(MSG_ENTITY, self.angles_z);
2940         }
2941         if(f & 4)
2942         {
2943                 WriteCoord(MSG_ENTITY, self.avelocity_x);
2944                 WriteCoord(MSG_ENTITY, self.avelocity_y);
2945                 WriteCoord(MSG_ENTITY, self.avelocity_z);
2946         }
2947         WriteShort(MSG_ENTITY, self.scale * 256.0);
2948         WriteShort(MSG_ENTITY, self.scale2 * 256.0);
2949         WriteByte(MSG_ENTITY, self.teleport_time * 100.0);
2950         WriteByte(MSG_ENTITY, self.fade_time * 100.0);
2951         WriteByte(MSG_ENTITY, self.alpha * 255.0);
2952
2953         return TRUE;
2954 }
2955
2956 void modeleffect_spawn(string m, float s, float f, vector o, vector v, vector ang, vector angv, float s0, float s2, float a, float t1, float t2)
2957 {
2958         entity e;
2959         float sz;
2960         e = spawn();
2961         e.classname = "modeleffect";
2962         setmodel(e, m);
2963         e.frame = f;
2964         setorigin(e, o);
2965         e.velocity = v;
2966         e.angles = ang;
2967         e.avelocity = angv;
2968         e.alpha = a;
2969         e.teleport_time = t1;
2970         e.fade_time = t2;
2971         e.skin = s;
2972         if(s0 >= 0)
2973                 e.scale = s0 / max6(-e.mins_x, -e.mins_y, -e.mins_z, e.maxs_x, e.maxs_y, e.maxs_z);
2974         else
2975                 e.scale = -s0;
2976         if(s2 >= 0)
2977                 e.scale2 = s2 / max6(-e.mins_x, -e.mins_y, -e.mins_z, e.maxs_x, e.maxs_y, e.maxs_z);
2978         else
2979                 e.scale2 = -s2;
2980         sz = max(e.scale, e.scale2);
2981         setsize(e, e.mins * sz, e.maxs * sz);
2982         Net_LinkEntity(e, FALSE, 0.1, modeleffect_SendEntity);
2983 }
2984
2985 void shockwave_spawn(string m, vector org, float sz, float t1, float t2)
2986 {
2987         return modeleffect_spawn(m, 0, 0, org, '0 0 0', '0 0 0', '0 0 0', 0, sz, 1, t1, t2);
2988 }
2989
2990 float randombit(float bits)
2991 {
2992         if not(bits & (bits-1)) // this ONLY holds for powers of two!
2993                 return bits;
2994
2995         float n, f, b, r;
2996
2997         r = random();
2998         b = 0;
2999         n = 0;
3000
3001         for(f = 1; f <= bits; f *= 2)
3002         {
3003                 if(bits & f)
3004                 {
3005                         ++n;
3006                         r *= n;
3007                         if(r <= 1)
3008                                 b = f;
3009                         else
3010                                 r = (r - 1) / (n - 1);
3011                 }
3012         }
3013
3014         return b;
3015 }
3016
3017 float randombits(float bits, float k, float error_return)
3018 {
3019         float r;
3020         r = 0;
3021         while(k > 0 && bits != r)
3022         {
3023                 r += randombit(bits - r);
3024                 --k;
3025         }
3026         if(error_return)
3027                 if(k > 0)
3028                         return -1; // all
3029         return r;
3030 }
3031
3032 void randombit_test(float bits, float iter)
3033 {
3034         while(iter > 0)
3035         {
3036                 print(ftos(randombit(bits)), "\n");
3037                 --iter;
3038         }
3039 }
3040
3041 float ExponentialFalloff(float mindist, float maxdist, float halflifedist, float d)
3042 {
3043         if(halflifedist > 0)
3044                 return pow(0.5, (bound(mindist, d, maxdist) - mindist) / halflifedist);
3045         else if(halflifedist < 0)
3046                 return pow(0.5, (bound(mindist, d, maxdist) - maxdist) / halflifedist);
3047         else
3048                 return 1;
3049 }
3050
3051
3052
3053
3054 #ifdef RELEASE
3055 #define cvar_string_normal cvar_string_builtin
3056 #define cvar_normal cvar_builtin
3057 #else
3058 string cvar_string_normal(string n)
3059 {
3060         if not(cvar_type(n) & 1)
3061                 backtrace(strcat("Attempt to access undefined cvar: ", n));
3062         return cvar_string_builtin(n);
3063 }
3064
3065 float cvar_normal(string n)
3066 {
3067         return stof(cvar_string_normal(n));
3068 }
3069 #endif
3070 #define cvar_set_normal cvar_set_builtin
3071
3072 void defer_think()
3073 {
3074     entity oself;
3075
3076     oself           = self;
3077     self            = self.owner;
3078     oself.think     = SUB_Remove;
3079     oself.nextthink = time;
3080
3081     oself.use();
3082 }
3083
3084 /*
3085     Execute func() after time + fdelay.
3086     self when func is executed = self when defer is called
3087 */
3088 void defer(float fdelay, void() func)
3089 {
3090     entity e;
3091
3092     e           = spawn();
3093     e.owner     = self;
3094     e.use       = func;
3095     e.think     = defer_think;
3096     e.nextthink = time + fdelay;
3097 }
3098
3099 .string aiment_classname;
3100 .float aiment_deadflag;
3101 void SetMovetypeFollow(entity ent, entity e)
3102 {
3103         // FIXME this may not be warpzone aware
3104         ent.movetype = MOVETYPE_FOLLOW; // make the hole follow
3105         ent.solid = SOLID_NOT; // MOVETYPE_FOLLOW is always non-solid - this means this cannot be teleported by warpzones any more! Instead, we must notice when our owner gets teleported.
3106         ent.aiment = e; // make the hole follow bmodel
3107         ent.punchangle = e.angles; // the original angles of bmodel
3108         ent.view_ofs = ent.origin - e.origin; // relative origin
3109         ent.v_angle = ent.angles - e.angles; // relative angles
3110         ent.aiment_classname = strzone(e.classname);
3111         ent.aiment_deadflag = e.deadflag;
3112 }
3113 void UnsetMovetypeFollow(entity ent)
3114 {
3115         ent.movetype = MOVETYPE_FLY;
3116         PROJECTILE_MAKETRIGGER(ent);
3117         ent.aiment = world;
3118 }
3119 float LostMovetypeFollow(entity ent)
3120 {
3121 /*
3122         if(ent.movetype != MOVETYPE_FOLLOW)
3123                 if(ent.aiment)
3124                         error("???");
3125 */
3126         if(ent.aiment)
3127         {
3128                 if(ent.aiment.classname != ent.aiment_classname)
3129                         return 1;
3130                 if(ent.aiment.deadflag != ent.aiment_deadflag)
3131                         return 1;
3132         }
3133         return 0;
3134 }
3135
3136 float isPushable(entity e)
3137 {
3138         if(e.iscreature)
3139                 return TRUE;
3140         switch(e.classname)
3141         {
3142                 case "body":
3143                 case "droppedweapon":
3144                 case "keepawayball":
3145                 case "nexball_basketball":
3146                 case "nexball_football":
3147                         return TRUE;
3148                 case "bullet": // antilagged bullets can't hit this either
3149                         return FALSE;
3150         }
3151         if (e.projectiledeathtype)
3152                 return TRUE;
3153         return FALSE;
3154 }