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