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