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