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