]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/miscfunctions.qc
cb7c66f02125d59a46fa37622668c7b0c88ca5ae
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / miscfunctions.qc
1 #include "miscfunctions.qh"
2 #include "antilag.qh"
3 #include "command/common.qh"
4 #include "constants.qh"
5 #include "g_hook.qh"
6 #include "ipban.qh"
7 #include "mutators/all.qh"
8 #include "t_items.qh"
9 #include "weapons/accuracy.qh"
10 #include "weapons/csqcprojectile.qh"
11 #include "weapons/selection.qh"
12 #include "../common/command/generic.qh"
13 #include "../common/constants.qh"
14 #include "../common/deathtypes/all.qh"
15 #include "../common/mapinfo.qh"
16 #include "../common/notifications.qh"
17 #include "../common/playerstats.qh"
18 #include "../common/teams.qh"
19 #include "../common/triggers/subs.qh"
20 #include "../common/util.qh"
21 #include "../common/turrets/sv_turrets.qh"
22 #include "../common/weapons/all.qh"
23 #include "../common/vehicles/sv_vehicles.qh"
24 #include "../common/vehicles/vehicle.qh"
25 #include "../common/items/all.qc"
26 #include "../lib/csqcmodel/sv_model.qh"
27 #include "../lib/warpzone/anglestransform.qh"
28 #include "../lib/warpzone/server.qh"
29
30 void crosshair_trace(entity pl)
31 {
32         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));
33 }
34 void crosshair_trace_plusvisibletriggers(entity pl)
35 {
36         entity first;
37         entity e;
38         first = findchainfloat(solid, SOLID_TRIGGER);
39
40         for (e = first; e; e = e.chain)
41                 if (e.model != "")
42                         e.solid = SOLID_BSP;
43
44         crosshair_trace(pl);
45
46         for (e = first; e; e = e.chain)
47                 e.solid = SOLID_TRIGGER;
48 }
49 void WarpZone_crosshair_trace(entity pl)
50 {
51         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));
52 }
53
54
55 string admin_name(void)
56 {
57         if(autocvar_sv_adminnick != "")
58                 return autocvar_sv_adminnick;
59         else
60                 return "SERVER ADMIN";
61 }
62
63 void DistributeEvenly_Init(float amount, float totalweight)
64 {
65     if (DistributeEvenly_amount)
66     {
67         LOG_TRACE("DistributeEvenly_Init: UNFINISHED DISTRIBUTION (", ftos(DistributeEvenly_amount), " for ");
68         LOG_TRACE(ftos(DistributeEvenly_totalweight), " left!)\n");
69     }
70     if (totalweight == 0)
71         DistributeEvenly_amount = 0;
72     else
73         DistributeEvenly_amount = amount;
74     DistributeEvenly_totalweight = totalweight;
75 }
76 float DistributeEvenly_Get(float weight)
77 {
78     float f;
79     if (weight <= 0)
80         return 0;
81     f = floor(0.5 + DistributeEvenly_amount * weight / DistributeEvenly_totalweight);
82     DistributeEvenly_totalweight -= weight;
83     DistributeEvenly_amount -= f;
84     return f;
85 }
86 float DistributeEvenly_GetRandomized(float weight)
87 {
88     float f;
89     if (weight <= 0)
90         return 0;
91     f = floor(random() + DistributeEvenly_amount * weight / DistributeEvenly_totalweight);
92     DistributeEvenly_totalweight -= weight;
93     DistributeEvenly_amount -= f;
94     return f;
95 }
96
97
98 void GameLogEcho(string s)
99 {
100     string fn;
101     int matches;
102
103     if (autocvar_sv_eventlog_files)
104     {
105         if (!logfile_open)
106         {
107             logfile_open = true;
108             matches = autocvar_sv_eventlog_files_counter + 1;
109             cvar_set("sv_eventlog_files_counter", itos(matches));
110             fn = ftos(matches);
111             if (strlen(fn) < 8)
112                 fn = strcat(substring("00000000", 0, 8 - strlen(fn)), fn);
113             fn = strcat(autocvar_sv_eventlog_files_nameprefix, fn, autocvar_sv_eventlog_files_namesuffix);
114             logfile = fopen(fn, FILE_APPEND);
115             fputs(logfile, ":logversion:3\n");
116         }
117         if (logfile >= 0)
118         {
119             if (autocvar_sv_eventlog_files_timestamps)
120                 fputs(logfile, strcat(":time:", strftime(true, "%Y-%m-%d %H:%M:%S", "\n", s, "\n")));
121             else
122                 fputs(logfile, strcat(s, "\n"));
123         }
124     }
125     if (autocvar_sv_eventlog_console)
126     {
127         LOG_INFO(s, "\n");
128     }
129 }
130
131 void GameLogInit()
132 {
133     logfile_open = 0;
134     // will be opened later
135 }
136
137 void GameLogClose()
138 {
139     if (logfile_open && logfile >= 0)
140     {
141         fclose(logfile);
142         logfile = -1;
143     }
144 }
145
146 entity findnearest(vector point, .string field, string value, vector axismod)
147 {
148     entity localhead;
149     float i;
150     float j;
151     float len;
152     vector dist;
153
154     float num_nearest;
155     num_nearest = 0;
156
157     localhead = find(world, field, value);
158     while (localhead)
159     {
160         if ((localhead.items == IT_KEY1 || localhead.items == IT_KEY2) && localhead.target == "###item###")
161             dist = localhead.oldorigin;
162         else
163             dist = localhead.origin;
164         dist = dist - point;
165         dist = dist.x * axismod.x * '1 0 0' + dist.y * axismod.y * '0 1 0' + dist.z * axismod.z * '0 0 1';
166         len = vlen(dist);
167
168         for (i = 0; i < num_nearest; ++i)
169         {
170             if (len < nearest_length[i])
171                 break;
172         }
173
174         // now i tells us where to insert at
175         //   INSERTION SORT! YOU'VE SEEN IT! RUN!
176         if (i < NUM_NEAREST_ENTITIES)
177         {
178             for (j = NUM_NEAREST_ENTITIES - 1; j >= i; --j)
179             {
180                 nearest_length[j + 1] = nearest_length[j];
181                 nearest_entity[j + 1] = nearest_entity[j];
182             }
183             nearest_length[i] = len;
184             nearest_entity[i] = localhead;
185             if (num_nearest < NUM_NEAREST_ENTITIES)
186                 num_nearest = num_nearest + 1;
187         }
188
189         localhead = find(localhead, field, value);
190     }
191
192     // now use the first one from our list that we can see
193     for (i = 0; i < num_nearest; ++i)
194     {
195         traceline(point, nearest_entity[i].origin, true, world);
196         if (trace_fraction == 1)
197         {
198             if (i != 0)
199             {
200                 LOG_TRACE("Nearest point (");
201                 LOG_TRACE(nearest_entity[0].netname);
202                 LOG_TRACE(") is not visible, using a visible one.\n");
203             }
204             return nearest_entity[i];
205         }
206     }
207
208     if (num_nearest == 0)
209         return world;
210
211     LOG_TRACE("Not seeing any location point, using nearest as fallback.\n");
212     /* DEBUGGING CODE:
213     dprint("Candidates were: ");
214     for(j = 0; j < num_nearest; ++j)
215     {
216         if(j != 0)
217                 dprint(", ");
218         dprint(nearest_entity[j].netname);
219     }
220     dprint("\n");
221     */
222
223     return nearest_entity[0];
224 }
225
226 string NearestLocation(vector p)
227 {
228     entity loc;
229     string ret;
230     ret = "somewhere";
231     loc = findnearest(p, classname, "target_location", '1 1 1');
232     if (loc)
233     {
234         ret = loc.message;
235     }
236     else
237     {
238         loc = findnearest(p, target, "###item###", '1 1 4');
239         if (loc)
240             ret = loc.netname;
241     }
242     return ret;
243 }
244
245 string formatmessage(string msg)
246 {SELFPARAM();
247         float p, p1, p2;
248         float n;
249         vector cursor;
250         entity cursor_ent;
251         string escape;
252         string replacement;
253         string ammoitems;
254         p = 0;
255         n = 7;
256
257         ammoitems = "batteries";
258         if(self.items & ITEM_Plasma.m_itemid) ammoitems = ITEM_Plasma.m_name;
259         if(self.items & ITEM_Cells.m_itemid) ammoitems = ITEM_Cells.m_name;
260         if(self.items & ITEM_Rockets.m_itemid) ammoitems = ITEM_Rockets.m_name;
261         if(self.items & ITEM_Shells.m_itemid) ammoitems = ITEM_Shells.m_name;
262
263         WarpZone_crosshair_trace(self);
264         cursor = trace_endpos;
265         cursor_ent = trace_ent;
266
267         while (1) {
268                 if (n < 1)
269                         break; // too many replacements
270
271                 n = n - 1;
272                 p1 = strstr(msg, "%", p); // NOTE: this destroys msg as it's a tempstring!
273                 p2 = strstr(msg, "\\", p); // NOTE: this destroys msg as it's a tempstring!
274
275                 if (p1 < 0)
276                         p1 = p2;
277
278                 if (p2 < 0)
279                         p2 = p1;
280
281                 p = min(p1, p2);
282
283                 if (p < 0)
284                         break;
285
286                 replacement = substring(msg, p, 2);
287                 escape = substring(msg, p + 1, 1);
288
289                 switch(escape)
290                 {
291                         case "%": replacement = "%"; break;
292                         case "\\":replacement = "\\"; break;
293                         case "n": replacement = "\n"; break;
294                         case "a": replacement = ftos(floor(self.armorvalue)); break;
295                         case "h": replacement = ftos(floor(self.health)); break;
296                         case "l": replacement = NearestLocation(self.origin); break;
297                         case "y": replacement = NearestLocation(cursor); break;
298                         case "d": replacement = NearestLocation(self.death_origin); break;
299                         case "w": replacement = WEP_NAME(((!self.weapon) ? (!self.switchweapon ? self.cnt : self.switchweapon) : self.weapon)); break;
300                         case "W": replacement = ammoitems; break;
301                         case "x": replacement = ((cursor_ent.netname == "" || !cursor_ent) ? "nothing" : cursor_ent.netname); break;
302                         case "s": replacement = ftos(vlen(self.velocity - self.velocity_z * '0 0 1')); break;
303                         case "S": replacement = ftos(vlen(self.velocity)); break;
304                         case "t": replacement = seconds_tostring(ceil(max(0, autocvar_timelimit * 60 + game_starttime - time))); break;
305                         case "T": replacement = seconds_tostring(floor(time - game_starttime)); break;
306                         default:
307                         {
308                                 MUTATOR_CALLHOOK(FormatMessage, escape, replacement, msg);
309                                 escape = format_escape;
310                                 replacement = format_replacement;
311                                 break;
312                         }
313                 }
314
315                 msg = strcat(substring(msg, 0, p), replacement, substring(msg, p+2, strlen(msg) - (p+2)));
316                 p = p + strlen(replacement);
317         }
318         return msg;
319 }
320
321 /*
322 =============
323 GetCvars
324 =============
325 Called with:
326   0:  sends the request
327   >0: receives a cvar from name=argv(f) value=argv(f+1)
328 */
329 void GetCvars_handleString(string thisname, float f, .string field, string name)
330 {SELFPARAM();
331         if (f < 0)
332         {
333                 if (self.(field))
334                         strunzone(self.(field));
335                 self.(field) = string_null;
336         }
337         else if (f > 0)
338         {
339                 if (thisname == name)
340                 {
341                         if (self.(field))
342                                 strunzone(self.(field));
343                         self.(field) = strzone(argv(f + 1));
344                 }
345         }
346         else
347                 stuffcmd(self, strcat("cl_cmd sendcvar ", name, "\n"));
348 }
349 void GetCvars_handleString_Fixup(string thisname, float f, .string field, string name, string(string) func)
350 {SELFPARAM();
351         GetCvars_handleString(thisname, f, field, name);
352         if (f >= 0) // also initialize to the fitting value for "" when sending cvars out
353                 if (thisname == name)
354                 {
355                         string s = func(strcat1(self.(field)));
356                         if (s != self.(field))
357                         {
358                                 strunzone(self.(field));
359                                 self.(field) = strzone(s);
360                         }
361                 }
362 }
363 void GetCvars_handleFloat(string thisname, float f, .float field, string name)
364 {SELFPARAM();
365         if (f < 0)
366         {
367         }
368         else if (f > 0)
369         {
370                 if (thisname == name)
371                         self.(field) = stof(argv(f + 1));
372         }
373         else
374                 stuffcmd(self, strcat("cl_cmd sendcvar ", name, "\n"));
375 }
376 void GetCvars_handleFloatOnce(string thisname, float f, .float field, string name)
377 {SELFPARAM();
378         if (f < 0)
379         {
380         }
381         else if (f > 0)
382         {
383                 if (thisname == name)
384                 {
385                         if (!self.(field))
386                         {
387                                 self.(field) = stof(argv(f + 1));
388                                 if (!self.(field))
389                                         self.(field) = -1;
390                         }
391                 }
392         }
393         else
394         {
395                 if (!self.(field))
396                         stuffcmd(self, strcat("cl_cmd sendcvar ", name, "\n"));
397         }
398 }
399 string W_FixWeaponOrder_ForceComplete_AndBuildImpulseList(string wo)
400 {SELFPARAM();
401         string o;
402         o = W_FixWeaponOrder_ForceComplete(wo);
403         if(self.weaponorder_byimpulse)
404         {
405                 strunzone(self.weaponorder_byimpulse);
406                 self.weaponorder_byimpulse = string_null;
407         }
408         self.weaponorder_byimpulse = strzone(W_FixWeaponOrder_BuildImpulseList(o));
409         return o;
410 }
411 void GetCvars(float f)
412 {SELFPARAM();
413         string s = string_null;
414
415         if (f > 0)
416                 s = strcat1(argv(f));
417
418         get_cvars_f = f;
419         get_cvars_s = s;
420         MUTATOR_CALLHOOK(GetCvars);
421
422         Notification_GetCvars();
423
424         ReplicateVars(this, s, f);
425
426         GetCvars_handleFloat(s, f, autoswitch, "cl_autoswitch");
427         GetCvars_handleFloat(s, f, cvar_cl_autoscreenshot, "cl_autoscreenshot");
428         GetCvars_handleFloat(s, f, cvar_cl_jetpack_jump, "cl_jetpack_jump");
429         GetCvars_handleString(s, f, cvar_g_xonoticversion, "g_xonoticversion");
430         GetCvars_handleString(s, f, cvar_cl_physics, "cl_physics");
431         GetCvars_handleFloat(s, f, cvar_cl_handicap, "cl_handicap");
432         GetCvars_handleFloat(s, f, cvar_cl_clippedspectating, "cl_clippedspectating");
433         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriority, "cl_weaponpriority", W_FixWeaponOrder_ForceComplete_AndBuildImpulseList);
434         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[0], "cl_weaponpriority0", W_FixWeaponOrder_AllowIncomplete);
435         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[1], "cl_weaponpriority1", W_FixWeaponOrder_AllowIncomplete);
436         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[2], "cl_weaponpriority2", W_FixWeaponOrder_AllowIncomplete);
437         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[3], "cl_weaponpriority3", W_FixWeaponOrder_AllowIncomplete);
438         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[4], "cl_weaponpriority4", W_FixWeaponOrder_AllowIncomplete);
439         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[5], "cl_weaponpriority5", W_FixWeaponOrder_AllowIncomplete);
440         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[6], "cl_weaponpriority6", W_FixWeaponOrder_AllowIncomplete);
441         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[7], "cl_weaponpriority7", W_FixWeaponOrder_AllowIncomplete);
442         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[8], "cl_weaponpriority8", W_FixWeaponOrder_AllowIncomplete);
443         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[9], "cl_weaponpriority9", W_FixWeaponOrder_AllowIncomplete);
444         GetCvars_handleFloat(s, f, cvar_cl_weaponimpulsemode, "cl_weaponimpulsemode");
445         GetCvars_handleFloat(s, f, cvar_cl_autotaunt, "cl_autotaunt");
446         GetCvars_handleFloat(s, f, cvar_cl_noantilag, "cl_noantilag");
447         GetCvars_handleFloat(s, f, cvar_cl_voice_directional, "cl_voice_directional");
448         GetCvars_handleFloat(s, f, cvar_cl_voice_directional_taunt_attenuation, "cl_voice_directional_taunt_attenuation");
449
450         GetCvars_handleFloatOnce(s, f, cvar_cl_gunalign, "cl_gunalign");
451         GetCvars_handleFloat(s, f, cvar_cl_allow_uid2name, "cl_allow_uid2name");
452         GetCvars_handleFloat(s, f, cvar_cl_allow_uidtracking, "cl_allow_uidtracking");
453         GetCvars_handleFloat(s, f, cvar_cl_movement_track_canjump, "cl_movement_track_canjump");
454         GetCvars_handleFloat(s, f, cvar_cl_newusekeysupported, "cl_newusekeysupported");
455
456         // fixup of switchweapon (needed for LMS or when spectating is disabled, as PutClientInServer comes too early)
457         if (f > 0)
458         {
459                 if (s == "cl_weaponpriority")
460                         self.switchweapon = w_getbestweapon(self);
461                 if (s == "cl_allow_uidtracking")
462                         PlayerStats_GameReport_AddPlayer(self);
463         }
464 }
465
466 // decolorizes and team colors the player name when needed
467 string playername(entity p)
468 {
469     string t;
470     if (teamplay && !intermission_running && IS_PLAYER(p))
471     {
472         t = Team_ColorCode(p.team);
473         return strcat(t, strdecolorize(p.netname));
474     }
475     else
476         return p.netname;
477 }
478
479 float want_weapon(entity weaponinfo, float allguns) // WEAPONTODO: what still needs done?
480 {
481         int i = weaponinfo.weapon;
482         int d = 0;
483         bool allow_mutatorblocked = false;
484
485         if(!i)
486                 return 0;
487
488         bool mutator_returnvalue = MUTATOR_CALLHOOK(WantWeapon, weaponinfo, d, allguns, allow_mutatorblocked);
489         d = ret_float;
490         allguns = want_allguns;
491         allow_mutatorblocked = false;
492
493         if(allguns)
494         {
495                 if(weaponinfo.spawnflags & WEP_FLAG_NORMAL)
496                         d = true;
497                 else
498                         d = false;
499         }
500         else if(!mutator_returnvalue)
501                 d = !(!weaponinfo.weaponstart);
502
503         if(!allow_mutatorblocked && (weaponinfo.spawnflags & WEP_FLAG_MUTATORBLOCKED)) // never default mutator blocked guns
504                 d = 0;
505
506         float t = weaponinfo.weaponstartoverride;
507
508         //print(strcat("want_weapon: ", weaponinfo.netname, " - d: ", ftos(d), ", t: ", ftos(t), ". \n"));
509
510         // bit order in t:
511         // 1: want or not
512         // 2: is default?
513         // 4: is set by default?
514         if(t < 0)
515                 t = 4 | (3 * d);
516         else
517                 t |= (2 * d);
518
519         return t;
520 }
521
522 void readplayerstartcvars()
523 {
524         entity e;
525         float i, j, t;
526         string s;
527
528         // initialize starting values for players
529         start_weapons = '0 0 0';
530         start_weapons_default = '0 0 0';
531         start_weapons_defaultmask = '0 0 0';
532         start_items = 0;
533         start_ammo_shells = 0;
534         start_ammo_nails = 0;
535         start_ammo_rockets = 0;
536         start_ammo_cells = 0;
537         start_ammo_plasma = 0;
538         start_health = cvar("g_balance_health_start");
539         start_armorvalue = cvar("g_balance_armor_start");
540
541         g_weaponarena = 0;
542         g_weaponarena_weapons = '0 0 0';
543
544         s = cvar_string("g_weaponarena");
545
546         MUTATOR_CALLHOOK(SetWeaponArena, s);
547         s = ret_string;
548
549         if (s == "0" || s == "")
550         {
551                 // no arena
552         }
553         else if (s == "off")
554         {
555                 // forcibly turn off weaponarena
556         }
557         else if (s == "all" || s == "1")
558         {
559                 g_weaponarena = 1;
560                 g_weaponarena_list = "All Weapons";
561                 for (j = WEP_FIRST; j <= WEP_LAST; ++j)
562                 {
563                         e = get_weaponinfo(j);
564                         if (!(e.spawnflags & WEP_FLAG_MUTATORBLOCKED))
565                                 g_weaponarena_weapons |= WepSet_FromWeapon(j);
566                 }
567         }
568         else if (s == "most")
569         {
570                 g_weaponarena = 1;
571                 g_weaponarena_list = "Most Weapons";
572                 for (j = WEP_FIRST; j <= WEP_LAST; ++j)
573                 {
574                         e = get_weaponinfo(j);
575                         if (!(e.spawnflags & WEP_FLAG_MUTATORBLOCKED))
576                                 if (e.spawnflags & WEP_FLAG_NORMAL)
577                                         g_weaponarena_weapons |= WepSet_FromWeapon(j);
578                 }
579         }
580         else if (s == "none")
581         {
582                 g_weaponarena = 1;
583                 g_weaponarena_list = "No Weapons";
584         }
585         else
586         {
587                 g_weaponarena = 1;
588                 t = tokenize_console(s);
589                 g_weaponarena_list = "";
590                 for (i = 0; i < t; ++i)
591                 {
592                         s = argv(i);
593                         for (j = WEP_FIRST; j <= WEP_LAST; ++j)
594                         {
595                                 e = get_weaponinfo(j);
596                                 if (e.netname == s)
597                                 {
598                                         g_weaponarena_weapons |= WepSet_FromWeapon(j);
599                                         g_weaponarena_list = strcat(g_weaponarena_list, e.m_name, " & ");
600                                         break;
601                                 }
602                         }
603                         if (j > WEP_LAST)
604                         {
605                                 LOG_INFO("The weapon mutator list contains an unknown weapon ", s, ". Skipped.\n");
606                         }
607                 }
608                 g_weaponarena_list = strzone(substring(g_weaponarena_list, 0, strlen(g_weaponarena_list) - 3));
609         }
610
611         if(g_weaponarena)
612                 g_weaponarena_random = cvar("g_weaponarena_random");
613         else
614                 g_weaponarena_random = 0;
615         g_weaponarena_random_with_blaster = cvar("g_weaponarena_random_with_blaster");
616
617         if (g_weaponarena)
618         {
619                 g_weapon_stay = 0; // incompatible
620                 start_weapons = g_weaponarena_weapons;
621                 start_items |= IT_UNLIMITED_AMMO;
622         }
623         else
624         {
625                 for (i = WEP_FIRST; i <= WEP_LAST; ++i)
626                 {
627                         e = get_weaponinfo(i);
628                         int w = want_weapon(e, false);
629                         if(w & 1)
630                                 start_weapons |= WepSet_FromWeapon(i);
631                         if(w & 2)
632                                 start_weapons_default |= WepSet_FromWeapon(i);
633                         if(w & 4)
634                                 start_weapons_defaultmask |= WepSet_FromWeapon(i);
635                 }
636         }
637
638         if(!cvar("g_use_ammunition"))
639                 start_items |= IT_UNLIMITED_AMMO;
640
641         if(start_items & IT_UNLIMITED_WEAPON_AMMO)
642         {
643                 start_ammo_shells = 999;
644                 start_ammo_nails = 999;
645                 start_ammo_rockets = 999;
646                 start_ammo_cells = 999;
647                 start_ammo_plasma = 999;
648                 start_ammo_fuel = 999;
649         }
650         else
651         {
652                 start_ammo_shells = cvar("g_start_ammo_shells");
653                 start_ammo_nails = cvar("g_start_ammo_nails");
654                 start_ammo_rockets = cvar("g_start_ammo_rockets");
655                 start_ammo_cells = cvar("g_start_ammo_cells");
656                 start_ammo_plasma = cvar("g_start_ammo_plasma");
657                 start_ammo_fuel = cvar("g_start_ammo_fuel");
658         }
659
660         if (warmup_stage)
661         {
662                 warmup_start_ammo_shells = start_ammo_shells;
663                 warmup_start_ammo_nails = start_ammo_nails;
664                 warmup_start_ammo_rockets = start_ammo_rockets;
665                 warmup_start_ammo_cells = start_ammo_cells;
666                 warmup_start_ammo_plasma = start_ammo_plasma;
667                 warmup_start_ammo_fuel = start_ammo_fuel;
668                 warmup_start_health = start_health;
669                 warmup_start_armorvalue = start_armorvalue;
670                 warmup_start_weapons = start_weapons;
671                 warmup_start_weapons_default = start_weapons_default;
672                 warmup_start_weapons_defaultmask = start_weapons_defaultmask;
673
674                 if (!g_weaponarena && !g_ca && !g_freezetag)
675                 {
676                         warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
677                         warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
678                         warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
679                         warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
680                         warmup_start_ammo_plasma = cvar("g_warmup_start_ammo_plasma");
681                         warmup_start_ammo_fuel = cvar("g_warmup_start_ammo_fuel");
682                         warmup_start_health = cvar("g_warmup_start_health");
683                         warmup_start_armorvalue = cvar("g_warmup_start_armor");
684                         warmup_start_weapons = '0 0 0';
685                         warmup_start_weapons_default = '0 0 0';
686                         warmup_start_weapons_defaultmask = '0 0 0';
687                         for (i = WEP_FIRST; i <= WEP_LAST; ++i)
688                         {
689                                 e = get_weaponinfo(i);
690                                 int w = want_weapon(e, g_warmup_allguns);
691                                 if(w & 1)
692                                         warmup_start_weapons |= WepSet_FromWeapon(i);
693                                 if(w & 2)
694                                         warmup_start_weapons_default |= WepSet_FromWeapon(i);
695                                 if(w & 4)
696                                         warmup_start_weapons_defaultmask |= WepSet_FromWeapon(i);
697                         }
698                 }
699         }
700
701         if (g_jetpack)
702                 start_items |= ITEM_Jetpack.m_itemid;
703
704         MUTATOR_CALLHOOK(SetStartItems);
705
706         if (start_items & ITEM_Jetpack.m_itemid)
707         {
708                 start_items |= ITEM_JetpackRegen.m_itemid;
709                 start_ammo_fuel = max(start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
710                 warmup_start_ammo_fuel = max(warmup_start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
711         }
712
713         WepSet precache_weapons = start_weapons;
714         if (g_warmup_allguns != 1)
715                 precache_weapons |= warmup_start_weapons;
716         for (i = WEP_FIRST; i <= WEP_LAST; ++i)
717         {
718                 e = get_weaponinfo(i);
719                 if(precache_weapons & WepSet_FromWeapon(i)) {
720                         Weapon w = get_weaponinfo(i);
721                         w.wr_init(w);
722                 }
723         }
724
725         start_ammo_shells = max(0, start_ammo_shells);
726         start_ammo_nails = max(0, start_ammo_nails);
727         start_ammo_rockets = max(0, start_ammo_rockets);
728         start_ammo_cells = max(0, start_ammo_cells);
729         start_ammo_plasma = max(0, start_ammo_plasma);
730         start_ammo_fuel = max(0, start_ammo_fuel);
731
732         warmup_start_ammo_shells = max(0, warmup_start_ammo_shells);
733         warmup_start_ammo_nails = max(0, warmup_start_ammo_nails);
734         warmup_start_ammo_rockets = max(0, warmup_start_ammo_rockets);
735         warmup_start_ammo_cells = max(0, warmup_start_ammo_cells);
736         warmup_start_ammo_plasma = max(0, warmup_start_ammo_plasma);
737         warmup_start_ammo_fuel = max(0, warmup_start_ammo_fuel);
738 }
739
740 float sound_allowed(float destin, entity e)
741 {
742     // sounds from world may always pass
743     for (;;)
744     {
745         if (e.classname == "body")
746             e = e.enemy;
747         else if (e.realowner && e.realowner != e)
748             e = e.realowner;
749         else if (e.owner && e.owner != e)
750             e = e.owner;
751         else
752             break;
753     }
754     // sounds to self may always pass
755     if (destin == MSG_ONE)
756         if (e == msg_entity)
757             return true;
758     // sounds by players can be removed
759     if (autocvar_bot_sound_monopoly)
760         if (IS_REAL_CLIENT(e))
761             return false;
762     // anything else may pass
763     return true;
764 }
765
766 void soundtoat(float _dest, entity e, vector o, float chan, string samp, float vol, float attenu)
767 {
768     float entno, idx;
769
770     if (!sound_allowed(_dest, e))
771         return;
772
773     entno = num_for_edict(e);
774     idx = precache_sound_index(samp);
775
776     int sflags;
777     sflags = 0;
778
779     attenu = floor(attenu * 64);
780     vol = floor(vol * 255);
781
782     if (vol != 255)
783         sflags |= SND_VOLUME;
784     if (attenu != 64)
785         sflags |= SND_ATTENUATION;
786     if (entno >= 8192 || chan < 0 || chan > 7)
787         sflags |= SND_LARGEENTITY;
788     if (idx >= 256)
789         sflags |= SND_LARGESOUND;
790
791     WriteByte(_dest, SVC_SOUND);
792     WriteByte(_dest, sflags);
793     if (sflags & SND_VOLUME)
794         WriteByte(_dest, vol);
795     if (sflags & SND_ATTENUATION)
796         WriteByte(_dest, attenu);
797     if (sflags & SND_LARGEENTITY)
798     {
799         WriteShort(_dest, entno);
800         WriteByte(_dest, chan);
801     }
802     else
803     {
804         WriteShort(_dest, entno * 8 + chan);
805     }
806     if (sflags & SND_LARGESOUND)
807         WriteShort(_dest, idx);
808     else
809         WriteByte(_dest, idx);
810
811     WriteCoord(_dest, o.x);
812     WriteCoord(_dest, o.y);
813     WriteCoord(_dest, o.z);
814 }
815 void soundto(float _dest, entity e, float chan, string samp, float vol, float _atten)
816 {
817     vector o;
818
819     if (!sound_allowed(_dest, e))
820         return;
821
822     o = e.origin + 0.5 * (e.mins + e.maxs);
823     soundtoat(_dest, e, o, chan, samp, vol, _atten);
824 }
825 void soundat(entity e, vector o, float chan, string samp, float vol, float _atten)
826 {
827     soundtoat(((chan & 8) ? MSG_ALL : MSG_BROADCAST), e, o, chan, samp, vol, _atten);
828 }
829 void stopsoundto(float _dest, entity e, float chan)
830 {
831     float entno;
832
833     if (!sound_allowed(_dest, e))
834         return;
835
836     entno = num_for_edict(e);
837
838     if (entno >= 8192 || chan < 0 || chan > 7)
839     {
840         float idx, sflags;
841         idx = precache_sound_index(SND(Null));
842         sflags = SND_LARGEENTITY;
843         if (idx >= 256)
844             sflags |= SND_LARGESOUND;
845         WriteByte(_dest, SVC_SOUND);
846         WriteByte(_dest, sflags);
847         WriteShort(_dest, entno);
848         WriteByte(_dest, chan);
849         if (sflags & SND_LARGESOUND)
850             WriteShort(_dest, idx);
851         else
852             WriteByte(_dest, idx);
853         WriteCoord(_dest, e.origin.x);
854         WriteCoord(_dest, e.origin.y);
855         WriteCoord(_dest, e.origin.z);
856     }
857     else
858     {
859         WriteByte(_dest, SVC_STOPSOUND);
860         WriteShort(_dest, entno * 8 + chan);
861     }
862 }
863 void stopsound(entity e, float chan)
864 {
865     if (!sound_allowed(MSG_BROADCAST, e))
866         return;
867
868     stopsoundto(MSG_BROADCAST, e, chan); // unreliable, gets there fast
869     stopsoundto(MSG_ALL, e, chan); // in case of packet loss
870 }
871
872 void play2(entity e, string filename)
873 {
874     //stuffcmd(e, strcat("play2 ", filename, "\n"));
875     msg_entity = e;
876     soundtoat(MSG_ONE, world, '0 0 0', CH_INFO, filename, VOL_BASE, ATTEN_NONE);
877 }
878
879 // use this one if you might be causing spam (e.g. from touch functions that might get called more than once per frame)
880 .float spamtime;
881 float spamsound(entity e, float chan, string samp, float vol, float _atten)
882 {
883     if (!sound_allowed(MSG_BROADCAST, e))
884         return false;
885
886     if (time > e.spamtime)
887     {
888         e.spamtime = time;
889         _sound(e, chan, samp, vol, _atten);
890         return true;
891     }
892     return false;
893 }
894
895 void play2team(float t, string filename)
896 {
897     entity head;
898
899     if (autocvar_bot_sound_monopoly)
900         return;
901
902     FOR_EACH_REALPLAYER(head)
903     {
904         if (head.team == t)
905             play2(head, filename);
906     }
907 }
908
909 void play2all(string samp)
910 {
911     if (autocvar_bot_sound_monopoly)
912         return;
913
914     _sound(world, CH_INFO, samp, VOL_BASE, ATTEN_NONE);
915 }
916
917 void PrecachePlayerSounds(string f);
918 void precache_playermodel(string m)
919 {
920         float globhandle, i, n;
921         string f;
922
923         if(substring(m, -9,5) == "_lod1")
924                 return;
925         if(substring(m, -9,5) == "_lod2")
926                 return;
927         precache_model(m);
928         f = strcat(substring(m, 0, -5), "_lod1", substring(m, -4, -1));
929         if(fexists(f))
930                 precache_model(f);
931         f = strcat(substring(m, 0, -5), "_lod2", substring(m, -4, -1));
932         if(fexists(f))
933                 precache_model(f);
934
935         globhandle = search_begin(strcat(m, "_*.sounds"), true, false);
936         if (globhandle < 0)
937                 return;
938         n = search_getsize(globhandle);
939         for (i = 0; i < n; ++i)
940         {
941                 //print(search_getfilename(globhandle, i), "\n");
942                 f = search_getfilename(globhandle, i);
943                 PrecachePlayerSounds(f);
944         }
945         search_end(globhandle);
946 }
947 void precache_all_playermodels(string pattern)
948 {
949         float globhandle, i, n;
950         string f;
951
952         globhandle = search_begin(pattern, true, false);
953         if (globhandle < 0)
954                 return;
955         n = search_getsize(globhandle);
956         for (i = 0; i < n; ++i)
957         {
958                 //print(search_getfilename(globhandle, i), "\n");
959                 f = search_getfilename(globhandle, i);
960                 precache_playermodel(f);
961         }
962         search_end(globhandle);
963 }
964
965 void precache_playermodels(string s)
966 {
967         if(s != "")
968         {
969                 int n = tokenize_console(s);
970                 precache_playermodel(argv(0));
971
972                 for (int i = 1; i < n; ++i)
973                         precache_model(argv(i));
974         }
975 }
976
977 void precache()
978 {SELFPARAM();
979     // gamemode related things
980
981     // Precache all player models if desired
982     if (autocvar_sv_precacheplayermodels)
983     {
984         PrecachePlayerSounds("sound/player/default.sounds");
985         precache_all_playermodels("models/player/*.zym");
986         precache_all_playermodels("models/player/*.dpm");
987         precache_all_playermodels("models/player/*.md3");
988         precache_all_playermodels("models/player/*.psk");
989         precache_all_playermodels("models/player/*.iqm");
990     }
991
992     if (autocvar_sv_defaultcharacter)
993     {
994                 precache_playermodels(autocvar_sv_defaultplayermodel_red);
995                 precache_playermodels(autocvar_sv_defaultplayermodel_blue);
996                 precache_playermodels(autocvar_sv_defaultplayermodel_yellow);
997                 precache_playermodels(autocvar_sv_defaultplayermodel_pink);
998                 precache_playermodels(autocvar_sv_defaultplayermodel);
999     }
1000
1001     if (g_footsteps)
1002     {
1003         PrecacheGlobalSound((globalsound_step = "misc/footstep0 6"));
1004         PrecacheGlobalSound((globalsound_metalstep = "misc/metalfootstep0 6"));
1005     }
1006
1007     // gore and miscellaneous sounds
1008     PrecacheGlobalSound((globalsound_fall = "misc/hitground 4"));
1009     PrecacheGlobalSound((globalsound_metalfall = "misc/metalhitground 4"));
1010
1011 #if 0
1012     // Disabled this code because it simply does not work (e.g. ignores bgmvolume, overlaps with "cd loop" controlled tracks).
1013
1014     if (!self.noise && self.music) // quake 3 uses the music field
1015         self.noise = self.music;
1016
1017     // plays music for the level if there is any
1018     if (self.noise)
1019     {
1020         precache_sound (self.noise);
1021         ambientsound ('0 0 0', self.noise, VOL_BASE, ATTEN_NONE);
1022     }
1023 #endif
1024 }
1025
1026
1027 void make_safe_for_remove(entity e)
1028 {
1029     if (e.initialize_entity)
1030     {
1031         entity ent, prev = world;
1032         for (ent = initialize_entity_first; ent; )
1033         {
1034             if ((ent == e) || ((ent.classname == "initialize_entity") && (ent.enemy == e)))
1035             {
1036                 //print("make_safe_for_remove: getting rid of initializer ", etos(ent), "\n");
1037                 // skip it in linked list
1038                 if (prev)
1039                 {
1040                     prev.initialize_entity_next = ent.initialize_entity_next;
1041                     ent = prev.initialize_entity_next;
1042                 }
1043                 else
1044                 {
1045                     initialize_entity_first = ent.initialize_entity_next;
1046                     ent = initialize_entity_first;
1047                 }
1048             }
1049             else
1050             {
1051                 prev = ent;
1052                 ent = ent.initialize_entity_next;
1053             }
1054         }
1055     }
1056 }
1057
1058 void objerror(string s)
1059 {SELFPARAM();
1060     make_safe_for_remove(self);
1061     builtin_objerror(s);
1062 }
1063
1064 .float remove_except_protected_forbidden;
1065 void remove_except_protected(entity e)
1066 {
1067         if(e.remove_except_protected_forbidden)
1068                 error("not allowed to remove this at this point");
1069         builtin_remove(e);
1070 }
1071
1072 void remove_unsafely(entity e)
1073 {
1074     if(e.classname == "spike")
1075         error("Removing spikes is forbidden (crylink bug), please report");
1076     builtin_remove(e);
1077 }
1078
1079 void remove_safely(entity e)
1080 {
1081     make_safe_for_remove(e);
1082     builtin_remove(e);
1083 }
1084
1085 void InitializeEntity(entity e, void(void) func, float order)
1086 {
1087     entity prev, cur;
1088
1089     if (!e || e.initialize_entity)
1090     {
1091         // make a proxy initializer entity
1092         entity e_old = e;
1093         e = new(initialize_entity);
1094         e.enemy = e_old;
1095     }
1096
1097     e.initialize_entity = func;
1098     e.initialize_entity_order = order;
1099
1100     cur = initialize_entity_first;
1101     prev = world;
1102     for (;;)
1103     {
1104         if (!cur || cur.initialize_entity_order > order)
1105         {
1106             // insert between prev and cur
1107             if (prev)
1108                 prev.initialize_entity_next = e;
1109             else
1110                 initialize_entity_first = e;
1111             e.initialize_entity_next = cur;
1112             return;
1113         }
1114         prev = cur;
1115         cur = cur.initialize_entity_next;
1116     }
1117 }
1118 void InitializeEntitiesRun()
1119 {SELFPARAM();
1120     entity startoflist = initialize_entity_first;
1121     initialize_entity_first = NULL;
1122     remove = remove_except_protected;
1123     for (entity e = startoflist; e; e = e.initialize_entity_next)
1124     {
1125                 e.remove_except_protected_forbidden = 1;
1126     }
1127     for (entity e = startoflist; e; )
1128     {
1129                 e.remove_except_protected_forbidden = 0;
1130         e.initialize_entity_order = 0;
1131         entity next = e.initialize_entity_next;
1132         e.initialize_entity_next = NULL;
1133         var void() func = e.initialize_entity;
1134         e.initialize_entity = func_null;
1135         if (e.classname == "initialize_entity")
1136         {
1137             entity wrappee = e.enemy;
1138             builtin_remove(e);
1139             e = wrappee;
1140         }
1141         //dprint("Delayed initialization: ", e.classname, "\n");
1142         if (func)
1143         {
1144                 WITH(entity, self, e, func());
1145         }
1146         else
1147         {
1148             eprint(e);
1149             backtrace(strcat("Null function in: ", e.classname, "\n"));
1150         }
1151         e = next;
1152     }
1153     remove = remove_unsafely;
1154 }
1155
1156 .float(entity) isEliminated;
1157 bool EliminatedPlayers_SendEntity(entity this, entity to, float sendflags)
1158 {
1159         float i, f, b;
1160         entity e;
1161         WriteHeader(MSG_ENTITY, ENT_CLIENT_ELIMINATEDPLAYERS);
1162         WriteByte(MSG_ENTITY, sendflags);
1163
1164         if(sendflags & 1)
1165         {
1166                 for(i = 1; i <= maxclients; i += 8)
1167                 {
1168                         for(f = 0, e = edict_num(i), b = 1; b < 256; b *= 2, e = nextent(e))
1169                         {
1170                                 if(eliminatedPlayers.isEliminated(e))
1171                                         f |= b;
1172                         }
1173                         WriteByte(MSG_ENTITY, f);
1174                 }
1175         }
1176
1177         return true;
1178 }
1179
1180 void EliminatedPlayers_Init(float(entity) isEliminated_func)
1181 {
1182         if(eliminatedPlayers)
1183         {
1184                 backtrace("Can't spawn eliminatedPlayers again!");
1185                 return;
1186         }
1187         Net_LinkEntity(eliminatedPlayers = spawn(), false, 0, EliminatedPlayers_SendEntity);
1188         eliminatedPlayers.isEliminated = isEliminated_func;
1189 }
1190
1191
1192 void adaptor_think2touch()
1193 {SELFPARAM();
1194     entity o;
1195     o = other;
1196     other = world;
1197     self.touch();
1198     other = o;
1199 }
1200
1201 void adaptor_think2use()
1202 {SELFPARAM();
1203     entity o, a;
1204     o = other;
1205     a = activator;
1206     activator = world;
1207     other = world;
1208     self.use();
1209     other = o;
1210     activator = a;
1211 }
1212
1213 void adaptor_think2use_hittype_splash() // for timed projectile detonation
1214 {SELFPARAM();
1215         if(!(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
1216                 self.projectiledeathtype |= HITTYPE_SPLASH;
1217         adaptor_think2use();
1218 }
1219
1220 // deferred dropping
1221 void DropToFloor_Handler()
1222 {SELFPARAM();
1223     builtin_droptofloor();
1224     self.dropped_origin = self.origin;
1225 }
1226
1227 void droptofloor()
1228 {SELFPARAM();
1229     InitializeEntity(self, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
1230 }
1231
1232
1233
1234 float trace_hits_box_a0, trace_hits_box_a1;
1235
1236 float trace_hits_box_1d(float end, float thmi, float thma)
1237 {
1238     if (end == 0)
1239     {
1240         // just check if x is in range
1241         if (0 < thmi)
1242             return false;
1243         if (0 > thma)
1244             return false;
1245     }
1246     else
1247     {
1248         // do the trace with respect to x
1249         // 0 -> end has to stay in thmi -> thma
1250         trace_hits_box_a0 = max(trace_hits_box_a0, min(thmi / end, thma / end));
1251         trace_hits_box_a1 = min(trace_hits_box_a1, max(thmi / end, thma / end));
1252         if (trace_hits_box_a0 > trace_hits_box_a1)
1253             return false;
1254     }
1255     return true;
1256 }
1257
1258 float trace_hits_box(vector start, vector end, vector thmi, vector thma)
1259 {
1260     end -= start;
1261     thmi -= start;
1262     thma -= start;
1263     // now it is a trace from 0 to end
1264
1265     trace_hits_box_a0 = 0;
1266     trace_hits_box_a1 = 1;
1267
1268     if (!trace_hits_box_1d(end.x, thmi.x, thma.x))
1269         return false;
1270     if (!trace_hits_box_1d(end.y, thmi.y, thma.y))
1271         return false;
1272     if (!trace_hits_box_1d(end.z, thmi.z, thma.z))
1273         return false;
1274
1275     return true;
1276 }
1277
1278 float tracebox_hits_box(vector start, vector mi, vector ma, vector end, vector thmi, vector thma)
1279 {
1280     return trace_hits_box(start, end, thmi - ma, thma - mi);
1281 }
1282
1283 float SUB_NoImpactCheck()
1284 {SELFPARAM();
1285         // zero hitcontents = this is not the real impact, but either the
1286         // mirror-impact of something hitting the projectile instead of the
1287         // projectile hitting the something, or a touchareagrid one. Neither of
1288         // these stop the projectile from moving, so...
1289         if(trace_dphitcontents == 0)
1290         {
1291                 //dprint("A hit happened with zero hit contents... DEBUG THIS, this should never happen for projectiles! Projectile will self-destruct.\n");
1292                 LOG_TRACEF("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));
1293                 checkclient();
1294         }
1295     if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1296         return 1;
1297     if (other == world && self.size != '0 0 0')
1298     {
1299         vector tic;
1300         tic = self.velocity * sys_frametime;
1301         tic = tic + normalize(tic) * vlen(self.maxs - self.mins);
1302         traceline(self.origin - tic, self.origin + tic, MOVE_NORMAL, self);
1303         if (trace_fraction >= 1)
1304         {
1305             LOG_TRACE("Odd... did not hit...?\n");
1306         }
1307         else if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1308         {
1309             LOG_TRACE("Detected and prevented the sky-grapple bug.\n");
1310             return 1;
1311         }
1312     }
1313
1314     return 0;
1315 }
1316
1317 #define SUB_OwnerCheck() (other && (other == self.owner))
1318
1319 void W_Crylink_Dequeue(entity e);
1320 float WarpZone_Projectile_Touch_ImpactFilter_Callback()
1321 {SELFPARAM();
1322         if(SUB_OwnerCheck())
1323                 return true;
1324         if(SUB_NoImpactCheck())
1325         {
1326                 if(self.classname == "nade")
1327                         return false; // no checks here
1328                 else if(self.classname == "grapplinghook")
1329                         RemoveGrapplingHook(self.realowner);
1330                 else if(self.classname == "spike")
1331                 {
1332                         W_Crylink_Dequeue(self);
1333                         remove(self);
1334                 }
1335                 else
1336                         remove(self);
1337                 return true;
1338         }
1339         if(trace_ent && trace_ent.solid > SOLID_TRIGGER)
1340                 UpdateCSQCProjectile(self);
1341         return false;
1342 }
1343
1344
1345 void URI_Get_Callback(float id, float status, string data)
1346 {
1347         if(url_URI_Get_Callback(id, status, data))
1348         {
1349                 // handled
1350         }
1351         else if (id == URI_GET_DISCARD)
1352         {
1353                 // discard
1354         }
1355         else if (id >= URI_GET_CURL && id <= URI_GET_CURL_END)
1356         {
1357                 // sv_cmd curl
1358                 Curl_URI_Get_Callback(id, status, data);
1359         }
1360         else if (id >= URI_GET_IPBAN && id <= URI_GET_IPBAN_END)
1361         {
1362                 // online ban list
1363                 OnlineBanList_URI_Get_Callback(id, status, data);
1364         }
1365         else
1366         {
1367                 LOG_INFO("Received HTTP request data for an invalid id ", ftos(id), ".\n");
1368         }
1369 }
1370
1371 string uid2name(string myuid) {
1372         string s;
1373         s = db_get(ServerProgsDB, strcat("/uid2name/", myuid));
1374
1375         // FIXME remove this later after 0.6 release
1376         // convert old style broken records to correct style
1377         if(s == "")
1378         {
1379                 s = db_get(ServerProgsDB, strcat("uid2name", myuid));
1380                 if(s != "")
1381                 {
1382                         db_put(ServerProgsDB, strcat("/uid2name/", myuid), s);
1383                         db_put(ServerProgsDB, strcat("uid2name", myuid), "");
1384                 }
1385         }
1386
1387         if(s == "")
1388                 s = "^1Unregistered Player";
1389         return s;
1390 }
1391
1392 float MoveToRandomLocationWithinBounds(entity e, vector boundmin, vector boundmax, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1393 {
1394     float m, i;
1395     vector start, org, delta, end, enddown, mstart;
1396     entity sp;
1397
1398     m = e.dphitcontentsmask;
1399     e.dphitcontentsmask = goodcontents | badcontents;
1400
1401     org = boundmin;
1402     delta = boundmax - boundmin;
1403
1404     start = end = org;
1405
1406     for (i = 0; i < attempts; ++i)
1407     {
1408         start.x = org.x + random() * delta.x;
1409         start.y = org.y + random() * delta.y;
1410         start.z = org.z + random() * delta.z;
1411
1412         // rule 1: start inside world bounds, and outside
1413         // solid, and don't start from somewhere where you can
1414         // fall down to evil
1415         tracebox(start, e.mins, e.maxs, start - '0 0 1' * delta.z, MOVE_NORMAL, e);
1416         if (trace_fraction >= 1)
1417             continue;
1418         if (trace_startsolid)
1419             continue;
1420         if (trace_dphitcontents & badcontents)
1421             continue;
1422         if (trace_dphitq3surfaceflags & badsurfaceflags)
1423             continue;
1424
1425         // rule 2: if we are too high, lower the point
1426         if (trace_fraction * delta.z > maxaboveground)
1427             start = trace_endpos + '0 0 1' * maxaboveground;
1428         enddown = trace_endpos;
1429
1430         // rule 3: make sure we aren't outside the map. This only works
1431         // for somewhat well formed maps. A good rule of thumb is that
1432         // the map should have a convex outside hull.
1433         // these can be traceLINES as we already verified the starting box
1434         mstart = start + 0.5 * (e.mins + e.maxs);
1435         traceline(mstart, mstart + '1 0 0' * delta.x, MOVE_NORMAL, e);
1436         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1437             continue;
1438         traceline(mstart, mstart - '1 0 0' * delta.x, MOVE_NORMAL, e);
1439         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1440             continue;
1441         traceline(mstart, mstart + '0 1 0' * delta.y, MOVE_NORMAL, e);
1442         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1443             continue;
1444         traceline(mstart, mstart - '0 1 0' * delta.y, MOVE_NORMAL, e);
1445         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1446             continue;
1447         traceline(mstart, mstart + '0 0 1' * delta.z, MOVE_NORMAL, e);
1448         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1449             continue;
1450
1451         // rule 4: we must "see" some spawnpoint or item
1452         for(sp = world; (sp = find(sp, classname, "info_player_deathmatch")); )
1453                 if(checkpvs(mstart, sp))
1454                         if((traceline(mstart, sp.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1455                                 break;
1456         if(!sp)
1457         {
1458                 for(sp = world; (sp = findflags(sp, flags, FL_ITEM)); )
1459                         if(checkpvs(mstart, sp))
1460                                 if((traceline(mstart, sp.origin + (sp.mins + sp.maxs) * 0.5, MOVE_NORMAL, e), trace_fraction) >= 1)
1461                                         break;
1462                 if(!sp)
1463                         continue;
1464         }
1465
1466         // find a random vector to "look at"
1467         end.x = org.x + random() * delta.x;
1468         end.y = org.y + random() * delta.y;
1469         end.z = org.z + random() * delta.z;
1470         end = start + normalize(end - start) * vlen(delta);
1471
1472         // rule 4: start TO end must not be too short
1473         tracebox(start, e.mins, e.maxs, end, MOVE_NORMAL, e);
1474         if (trace_startsolid)
1475             continue;
1476         if (trace_fraction < minviewdistance / vlen(delta))
1477             continue;
1478
1479         // rule 5: don't want to look at sky
1480         if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY)
1481             continue;
1482
1483         // rule 6: we must not end up in trigger_hurt
1484         if (tracebox_hits_trigger_hurt(start, e.mins, e.maxs, enddown))
1485             continue;
1486
1487         break;
1488     }
1489
1490     e.dphitcontentsmask = m;
1491
1492     if (i < attempts)
1493     {
1494         setorigin(e, start);
1495         e.angles = vectoangles(end - start);
1496         LOG_TRACE("Needed ", ftos(i + 1), " attempts\n");
1497         return true;
1498     }
1499     else
1500         return false;
1501 }
1502
1503 float MoveToRandomMapLocation(entity e, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1504 {
1505         return MoveToRandomLocationWithinBounds(e, world.mins, world.maxs, goodcontents, badcontents, badsurfaceflags, attempts, maxaboveground, minviewdistance);
1506 }
1507
1508 void write_recordmarker(entity pl, float tstart, float dt)
1509 {
1510     GameLogEcho(strcat(":recordset:", ftos(pl.playerid), ":", ftos(dt)));
1511
1512     // also write a marker into demo files for demotc-race-record-extractor to find
1513     stuffcmd(pl,
1514              strcat(
1515                  strcat("//", strconv(2, 0, 0, GetGametype()), " RECORD SET ", TIME_ENCODED_TOSTRING(TIME_ENCODE(dt))),
1516                  " ", ftos(tstart), " ", ftos(dt), "\n"));
1517 }
1518
1519 void attach_sameorigin(entity e, entity to, string tag)
1520 {
1521     vector org, t_forward, t_left, t_up, e_forward, e_up;
1522     float tagscale;
1523
1524     org = e.origin - gettaginfo(to, gettagindex(to, tag));
1525     tagscale = pow(vlen(v_forward), -2); // undo a scale on the tag
1526     t_forward = v_forward * tagscale;
1527     t_left = v_right * -tagscale;
1528     t_up = v_up * tagscale;
1529
1530     e.origin_x = org * t_forward;
1531     e.origin_y = org * t_left;
1532     e.origin_z = org * t_up;
1533
1534     // current forward and up directions
1535     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1536                 e.angles = AnglesTransform_FromVAngles(e.angles);
1537         else
1538                 e.angles = AnglesTransform_FromAngles(e.angles);
1539     fixedmakevectors(e.angles);
1540
1541     // untransform forward, up!
1542     e_forward.x = v_forward * t_forward;
1543     e_forward.y = v_forward * t_left;
1544     e_forward.z = v_forward * t_up;
1545     e_up.x = v_up * t_forward;
1546     e_up.y = v_up * t_left;
1547     e_up.z = v_up * t_up;
1548
1549     e.angles = fixedvectoangles2(e_forward, e_up);
1550     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1551                 e.angles = AnglesTransform_ToVAngles(e.angles);
1552         else
1553                 e.angles = AnglesTransform_ToAngles(e.angles);
1554
1555     setattachment(e, to, tag);
1556     setorigin(e, e.origin);
1557 }
1558
1559 void detach_sameorigin(entity e)
1560 {
1561     vector org;
1562     org = gettaginfo(e, 0);
1563     e.angles = fixedvectoangles2(v_forward, v_up);
1564     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1565                 e.angles = AnglesTransform_ToVAngles(e.angles);
1566         else
1567                 e.angles = AnglesTransform_ToAngles(e.angles);
1568     setorigin(e, org);
1569     setattachment(e, world, "");
1570     setorigin(e, e.origin);
1571 }
1572
1573 void follow_sameorigin(entity e, entity to)
1574 {
1575     e.movetype = MOVETYPE_FOLLOW; // make the hole follow
1576     e.aiment = to; // make the hole follow bmodel
1577     e.punchangle = to.angles; // the original angles of bmodel
1578     e.view_ofs = e.origin - to.origin; // relative origin
1579     e.v_angle = e.angles - to.angles; // relative angles
1580 }
1581
1582 void unfollow_sameorigin(entity e)
1583 {
1584     e.movetype = MOVETYPE_NONE;
1585 }
1586
1587 entity gettaginfo_relative_ent;
1588 vector gettaginfo_relative(entity e, float tag)
1589 {
1590     if (!gettaginfo_relative_ent)
1591     {
1592         gettaginfo_relative_ent = spawn();
1593         gettaginfo_relative_ent.effects = EF_NODRAW;
1594     }
1595     gettaginfo_relative_ent.model = e.model;
1596     gettaginfo_relative_ent.modelindex = e.modelindex;
1597     gettaginfo_relative_ent.frame = e.frame;
1598     return gettaginfo(gettaginfo_relative_ent, tag);
1599 }
1600
1601 .float scale2;
1602
1603 bool modeleffect_SendEntity(entity this, entity to, int sf)
1604 {
1605         float f;
1606         WriteHeader(MSG_ENTITY, ENT_CLIENT_MODELEFFECT);
1607
1608         f = 0;
1609         if(self.velocity != '0 0 0')
1610                 f |= 1;
1611         if(self.angles != '0 0 0')
1612                 f |= 2;
1613         if(self.avelocity != '0 0 0')
1614                 f |= 4;
1615
1616         WriteByte(MSG_ENTITY, f);
1617         WriteShort(MSG_ENTITY, self.modelindex);
1618         WriteByte(MSG_ENTITY, self.skin);
1619         WriteByte(MSG_ENTITY, self.frame);
1620         WriteCoord(MSG_ENTITY, self.origin.x);
1621         WriteCoord(MSG_ENTITY, self.origin.y);
1622         WriteCoord(MSG_ENTITY, self.origin.z);
1623         if(f & 1)
1624         {
1625                 WriteCoord(MSG_ENTITY, self.velocity.x);
1626                 WriteCoord(MSG_ENTITY, self.velocity.y);
1627                 WriteCoord(MSG_ENTITY, self.velocity.z);
1628         }
1629         if(f & 2)
1630         {
1631                 WriteCoord(MSG_ENTITY, self.angles.x);
1632                 WriteCoord(MSG_ENTITY, self.angles.y);
1633                 WriteCoord(MSG_ENTITY, self.angles.z);
1634         }
1635         if(f & 4)
1636         {
1637                 WriteCoord(MSG_ENTITY, self.avelocity.x);
1638                 WriteCoord(MSG_ENTITY, self.avelocity.y);
1639                 WriteCoord(MSG_ENTITY, self.avelocity.z);
1640         }
1641         WriteShort(MSG_ENTITY, self.scale * 256.0);
1642         WriteShort(MSG_ENTITY, self.scale2 * 256.0);
1643         WriteByte(MSG_ENTITY, self.teleport_time * 100.0);
1644         WriteByte(MSG_ENTITY, self.fade_time * 100.0);
1645         WriteByte(MSG_ENTITY, self.alpha * 255.0);
1646
1647         return true;
1648 }
1649
1650 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)
1651 {
1652         entity e = new(modeleffect);
1653         _setmodel(e, m);
1654         e.frame = f;
1655         setorigin(e, o);
1656         e.velocity = v;
1657         e.angles = ang;
1658         e.avelocity = angv;
1659         e.alpha = a;
1660         e.teleport_time = t1;
1661         e.fade_time = t2;
1662         e.skin = s;
1663         if(s0 >= 0)
1664                 e.scale = s0 / max6(-e.mins.x, -e.mins.y, -e.mins.z, e.maxs.x, e.maxs.y, e.maxs.z);
1665         else
1666                 e.scale = -s0;
1667         if(s2 >= 0)
1668                 e.scale2 = s2 / max6(-e.mins.x, -e.mins.y, -e.mins.z, e.maxs.x, e.maxs.y, e.maxs.z);
1669         else
1670                 e.scale2 = -s2;
1671         float sz = max(e.scale, e.scale2);
1672         setsize(e, e.mins * sz, e.maxs * sz);
1673         Net_LinkEntity(e, false, 0.1, modeleffect_SendEntity);
1674 }
1675
1676 void shockwave_spawn(string m, vector org, float sz, float t1, float t2)
1677 {
1678         return modeleffect_spawn(m, 0, 0, org, '0 0 0', '0 0 0', '0 0 0', 0, sz, 1, t1, t2);
1679 }
1680
1681 float randombit(float bits)
1682 {
1683         if(!(bits & (bits-1))) // this ONLY holds for powers of two!
1684                 return bits;
1685
1686         float n, f, b, r;
1687
1688         r = random();
1689         b = 0;
1690         n = 0;
1691
1692         for(f = 1; f <= bits; f *= 2)
1693         {
1694                 if(bits & f)
1695                 {
1696                         ++n;
1697                         r *= n;
1698                         if(r <= 1)
1699                                 b = f;
1700                         else
1701                                 r = (r - 1) / (n - 1);
1702                 }
1703         }
1704
1705         return b;
1706 }
1707
1708 float randombits(float bits, float k, float error_return)
1709 {
1710         float r;
1711         r = 0;
1712         while(k > 0 && bits != r)
1713         {
1714                 r += randombit(bits - r);
1715                 --k;
1716         }
1717         if(error_return)
1718                 if(k > 0)
1719                         return -1; // all
1720         return r;
1721 }
1722
1723 void randombit_test(float bits, float iter)
1724 {
1725         while(iter > 0)
1726         {
1727                 LOG_INFO(ftos(randombit(bits)), "\n");
1728                 --iter;
1729         }
1730 }
1731
1732 float ExponentialFalloff(float mindist, float maxdist, float halflifedist, float d)
1733 {
1734         if(halflifedist > 0)
1735                 return pow(0.5, (bound(mindist, d, maxdist) - mindist) / halflifedist);
1736         else if(halflifedist < 0)
1737                 return pow(0.5, (bound(mindist, d, maxdist) - maxdist) / halflifedist);
1738         else
1739                 return 1;
1740 }
1741
1742
1743 .string aiment_classname;
1744 .float aiment_deadflag;
1745 void SetMovetypeFollow(entity ent, entity e)
1746 {
1747         // FIXME this may not be warpzone aware
1748         ent.movetype = MOVETYPE_FOLLOW; // make the hole follow
1749         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.
1750         ent.aiment = e; // make the hole follow bmodel
1751         ent.punchangle = e.angles; // the original angles of bmodel
1752         ent.view_ofs = ent.origin - e.origin; // relative origin
1753         ent.v_angle = ent.angles - e.angles; // relative angles
1754         ent.aiment_classname = strzone(e.classname);
1755         ent.aiment_deadflag = e.deadflag;
1756 }
1757 void UnsetMovetypeFollow(entity ent)
1758 {
1759         ent.movetype = MOVETYPE_FLY;
1760         PROJECTILE_MAKETRIGGER(ent);
1761         ent.aiment = world;
1762 }
1763 float LostMovetypeFollow(entity ent)
1764 {
1765 /*
1766         if(ent.movetype != MOVETYPE_FOLLOW)
1767                 if(ent.aiment)
1768                         error("???");
1769 */
1770         if(ent.aiment)
1771         {
1772                 if(ent.aiment.classname != ent.aiment_classname)
1773                         return 1;
1774                 if(ent.aiment.deadflag != ent.aiment_deadflag)
1775                         return 1;
1776         }
1777         return 0;
1778 }
1779
1780 float isPushable(entity e)
1781 {
1782         if(e.pushable)
1783                 return true;
1784         if(IS_VEHICLE(e))
1785                 return false;
1786         if(e.iscreature)
1787                 return true;
1788         switch(e.classname)
1789         {
1790                 case "body":
1791                 case "droppedweapon":
1792                 case "keepawayball":
1793                 case "nexball_basketball":
1794                 case "nexball_football":
1795                         return true;
1796                 case "bullet": // antilagged bullets can't hit this either
1797                         return false;
1798         }
1799         if (e.projectiledeathtype)
1800                 return true;
1801         return false;
1802 }