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