]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/miscfunctions.qc
c36e1eda8c782ff4cf10e793c24ec724cbce1500
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / miscfunctions.qc
1 #include "miscfunctions.qh"
2 #include "antilag.qh"
3 #include "command/common.qh"
4 #include "constants.qh"
5 #include "g_hook.qh"
6 #include "ipban.qh"
7 #include "mutators/_mod.qh"
8 #include "../common/t_items.qh"
9 #include "weapons/accuracy.qh"
10 #include "weapons/csqcprojectile.qh"
11 #include "weapons/selection.qh"
12 #include "../common/command/_mod.qh"
13 #include "../common/constants.qh"
14 #include <common/net_linked.qh>
15 #include "../common/deathtypes/all.qh"
16 #include "../common/mapinfo.qh"
17 #include "../common/notifications/all.qh"
18 #include "../common/playerstats.qh"
19 #include "../common/teams.qh"
20 #include "../common/triggers/subs.qh"
21 #include "../common/util.qh"
22 #include "../common/turrets/sv_turrets.qh"
23 #include <common/weapons/_all.qh>
24 #include "../common/vehicles/sv_vehicles.qh"
25 #include "../common/vehicles/vehicle.qh"
26 #include "../common/items/_mod.qh"
27 #include "../common/state.qh"
28 #include "../common/effects/qc/globalsound.qh"
29 #include "../common/wepent.qh"
30 #include "../lib/csqcmodel/sv_model.qh"
31 #include "../lib/warpzone/anglestransform.qh"
32 #include "../lib/warpzone/server.qh"
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 .bool ctrace_solidchanged;
39 void crosshair_trace_plusvisibletriggers(entity pl)
40 {
41         FOREACH_ENTITY_FLOAT(solid, SOLID_TRIGGER,
42         {
43                 if(it.model != "")
44                 {
45                         it.solid = SOLID_BSP;
46                         it.ctrace_solidchanged = true;
47                 }
48         });
49
50         crosshair_trace(pl);
51
52         FOREACH_ENTITY_FLOAT(ctrace_solidchanged, true,
53         {
54                 it.solid = SOLID_TRIGGER;
55                 it.ctrace_solidchanged = false;
56         });
57 }
58 void WarpZone_crosshair_trace(entity pl)
59 {
60         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));
61 }
62
63
64 string admin_name()
65 {
66         if(autocvar_sv_adminnick != "")
67                 return autocvar_sv_adminnick;
68         else
69                 return "SERVER ADMIN";
70 }
71
72
73 void GameLogEcho(string s)
74 {
75     string fn;
76     int matches;
77
78     if (autocvar_sv_eventlog_files)
79     {
80         if (!logfile_open)
81         {
82             logfile_open = true;
83             matches = autocvar_sv_eventlog_files_counter + 1;
84             cvar_set("sv_eventlog_files_counter", itos(matches));
85             fn = ftos(matches);
86             if (strlen(fn) < 8)
87                 fn = strcat(substring("00000000", 0, 8 - strlen(fn)), fn);
88             fn = strcat(autocvar_sv_eventlog_files_nameprefix, fn, autocvar_sv_eventlog_files_namesuffix);
89             logfile = fopen(fn, FILE_APPEND);
90             fputs(logfile, ":logversion:3\n");
91         }
92         if (logfile >= 0)
93         {
94             if (autocvar_sv_eventlog_files_timestamps)
95                 fputs(logfile, strcat(":time:", strftime(true, "%Y-%m-%d %H:%M:%S", "\n", s, "\n")));
96             else
97                 fputs(logfile, strcat(s, "\n"));
98         }
99     }
100     if (autocvar_sv_eventlog_console)
101     {
102         dedicated_print(strcat(s, "\n"));
103     }
104 }
105
106 void GameLogInit()
107 {
108     logfile_open = 0;
109     // will be opened later
110 }
111
112 void GameLogClose()
113 {
114     if (logfile_open && logfile >= 0)
115     {
116         fclose(logfile);
117         logfile = -1;
118     }
119 }
120
121 entity findnearest(vector point, .string field, string value, vector axismod)
122 {
123     entity localhead;
124     float i;
125     float j;
126     float len;
127     vector dist;
128
129     float num_nearest;
130     num_nearest = 0;
131
132     localhead = find(NULL, field, value);
133     while (localhead)
134     {
135         if ((localhead.items == IT_KEY1 || localhead.items == IT_KEY2) && localhead.target == "###item###")
136             dist = localhead.oldorigin;
137         else
138             dist = localhead.origin;
139         dist = dist - point;
140         dist = dist.x * axismod.x * '1 0 0' + dist.y * axismod.y * '0 1 0' + dist.z * axismod.z * '0 0 1';
141         len = vlen(dist);
142
143         for (i = 0; i < num_nearest; ++i)
144         {
145             if (len < nearest_length[i])
146                 break;
147         }
148
149         // now i tells us where to insert at
150         //   INSERTION SORT! YOU'VE SEEN IT! RUN!
151         if (i < NUM_NEAREST_ENTITIES)
152         {
153             for (j = NUM_NEAREST_ENTITIES - 1; j >= i; --j)
154             {
155                 nearest_length[j + 1] = nearest_length[j];
156                 nearest_entity[j + 1] = nearest_entity[j];
157             }
158             nearest_length[i] = len;
159             nearest_entity[i] = localhead;
160             if (num_nearest < NUM_NEAREST_ENTITIES)
161                 num_nearest = num_nearest + 1;
162         }
163
164         localhead = find(localhead, field, value);
165     }
166
167     // now use the first one from our list that we can see
168     for (i = 0; i < num_nearest; ++i)
169     {
170         traceline(point, nearest_entity[i].origin, true, NULL);
171         if (trace_fraction == 1)
172         {
173             if (i != 0)
174             {
175                 LOG_TRACE("Nearest point (");
176                 LOG_TRACE(nearest_entity[0].netname);
177                 LOG_TRACE(") is not visible, using a visible one.");
178             }
179             return nearest_entity[i];
180         }
181     }
182
183     if (num_nearest == 0)
184         return NULL;
185
186     LOG_TRACE("Not seeing any location point, using nearest as fallback.");
187     /* DEBUGGING CODE:
188     dprint("Candidates were: ");
189     for(j = 0; j < num_nearest; ++j)
190     {
191         if(j != 0)
192                 dprint(", ");
193         dprint(nearest_entity[j].netname);
194     }
195     dprint("\n");
196     */
197
198     return nearest_entity[0];
199 }
200
201 string NearestLocation(vector p)
202 {
203     entity loc;
204     string ret;
205     ret = "somewhere";
206     loc = findnearest(p, classname, "target_location", '1 1 1');
207     if (loc)
208     {
209         ret = loc.message;
210     }
211     else
212     {
213         loc = findnearest(p, target, "###item###", '1 1 4');
214         if (loc)
215             ret = loc.netname;
216     }
217     return ret;
218 }
219
220 string formatmessage(entity this, string msg)
221 {
222         float p, p1, p2;
223         float n;
224         vector cursor;
225         entity cursor_ent;
226         string escape;
227         string replacement;
228         string ammoitems;
229         p = 0;
230         n = 7;
231
232         ammoitems = "batteries";
233         switch((PS(this).m_weapon).ammo_field)
234         {
235                 case ammo_shells:  ammoitems = ITEM_Shells.m_name;      break;
236                 case ammo_nails:   ammoitems = ITEM_Bullets.m_name;     break;
237                 case ammo_rockets: ammoitems = ITEM_Rockets.m_name;     break;
238                 case ammo_cells:   ammoitems = ITEM_Cells.m_name;       break;
239                 case ammo_plasma:  ammoitems = ITEM_Plasma.m_name;      break;
240                 case ammo_fuel:    ammoitems = ITEM_JetpackFuel.m_name; break;
241         }
242
243         WarpZone_crosshair_trace(this);
244         cursor = trace_endpos;
245         cursor_ent = trace_ent;
246
247         MUTATOR_CALLHOOK(PreFormatMessage, this, msg);
248         msg = M_ARGV(1, string);
249
250         while (1) {
251                 if (n < 1)
252                         break; // too many replacements
253
254                 n = n - 1;
255                 p1 = strstrofs(msg, "%", p); // NOTE: this destroys msg as it's a tempstring!
256                 p2 = strstrofs(msg, "\\", p); // NOTE: this destroys msg as it's a tempstring!
257
258                 if (p1 < 0)
259                         p1 = p2;
260
261                 if (p2 < 0)
262                         p2 = p1;
263
264                 p = min(p1, p2);
265
266                 if (p < 0)
267                         break;
268
269                 replacement = substring(msg, p, 2);
270                 escape = substring(msg, p + 1, 1);
271
272                 .entity weaponentity = weaponentities[0]; // TODO: unhardcode
273
274                 switch(escape)
275                 {
276                         case "%": replacement = "%"; break;
277                         case "\\":replacement = "\\"; break;
278                         case "n": replacement = "\n"; break;
279                         case "a": replacement = ftos(floor(this.armorvalue)); break;
280                         case "h": replacement = ftos(floor(this.health)); break;
281                         case "l": replacement = NearestLocation(this.origin); break;
282                         case "y": replacement = NearestLocation(cursor); break;
283                         case "d": replacement = NearestLocation(this.death_origin); break;
284                         case "w": replacement = ((this.(weaponentity).m_weapon == WEP_Null) ? ((this.(weaponentity).m_switchweapon == WEP_Null) ? Weapons_from(this.(weaponentity).cnt) : this.(weaponentity).m_switchweapon) : this.(weaponentity).m_weapon).m_name; break;
285                         case "W": replacement = ammoitems; break;
286                         case "x": replacement = ((cursor_ent.netname == "" || !cursor_ent) ? "nothing" : cursor_ent.netname); break;
287                         case "s": replacement = ftos(vlen(this.velocity - this.velocity_z * '0 0 1')); break;
288                         case "S": replacement = ftos(vlen(this.velocity)); break;
289                         case "t": replacement = seconds_tostring(ceil(max(0, autocvar_timelimit * 60 + game_starttime - time))); break;
290                         case "T": replacement = seconds_tostring(floor(time - game_starttime)); break;
291                         default:
292                         {
293                                 MUTATOR_CALLHOOK(FormatMessage, this, escape, replacement, msg);
294                                 replacement = M_ARGV(2, string);
295                                 break;
296                         }
297                 }
298
299                 msg = strcat(substring(msg, 0, p), replacement, substring(msg, p+2, strlen(msg) - (p+2)));
300                 p = p + strlen(replacement);
301         }
302         return msg;
303 }
304
305 /*
306 =============
307 GetCvars
308 =============
309 Called with:
310   0:  sends the request
311   >0: receives a cvar from name=argv(f) value=argv(f+1)
312 */
313 void GetCvars_handleString(entity this, string thisname, float f, .string field, string name)
314 {
315         if (f < 0)
316         {
317                 if (this.(field))
318                         strunzone(this.(field));
319                 this.(field) = string_null;
320         }
321         else if (f > 0)
322         {
323                 if (thisname == name)
324                 {
325                         if (this.(field))
326                                 strunzone(this.(field));
327                         this.(field) = strzone(argv(f + 1));
328                 }
329         }
330         else
331                 stuffcmd(this, strcat("cl_cmd sendcvar ", name, "\n"));
332 }
333 void GetCvars_handleString_Fixup(entity this, string thisname, float f, .string field, string name, string(entity, string) func)
334 {
335         GetCvars_handleString(this, thisname, f, field, name);
336         if (f >= 0) // also initialize to the fitting value for "" when sending cvars out
337                 if (thisname == name)
338                 {
339                         string s = func(this, strcat1(this.(field)));
340                         if (s != this.(field))
341                         {
342                                 strunzone(this.(field));
343                                 this.(field) = strzone(s);
344                         }
345                 }
346 }
347 void GetCvars_handleFloat(entity this, string thisname, float f, .float field, string name)
348 {
349         if (f < 0)
350         {
351         }
352         else if (f > 0)
353         {
354                 if (thisname == name)
355                         this.(field) = stof(argv(f + 1));
356         }
357         else
358                 stuffcmd(this, strcat("cl_cmd sendcvar ", name, "\n"));
359 }
360 void GetCvars_handleFloatOnce(entity this, string thisname, float f, .float field, string name)
361 {
362         if (f < 0)
363         {
364         }
365         else if (f > 0)
366         {
367                 if (thisname == name)
368                 {
369                         if (!this.(field))
370                         {
371                                 this.(field) = stof(argv(f + 1));
372                                 if (!this.(field))
373                                         this.(field) = -1;
374                         }
375                 }
376         }
377         else
378         {
379                 if (!this.(field))
380                         stuffcmd(this, strcat("cl_cmd sendcvar ", name, "\n"));
381         }
382 }
383 string W_FixWeaponOrder_ForceComplete_AndBuildImpulseList(entity this, string wo)
384 {
385         string o;
386         o = W_FixWeaponOrder_ForceComplete(wo);
387         if(this.weaponorder_byimpulse)
388         {
389                 strunzone(this.weaponorder_byimpulse);
390                 this.weaponorder_byimpulse = string_null;
391         }
392         this.weaponorder_byimpulse = strzone(W_FixWeaponOrder_BuildImpulseList(o));
393         return o;
394 }
395
396 REPLICATE(autoswitch, bool, "cl_autoswitch");
397
398 REPLICATE(cvar_cl_allow_uid2name, bool, "cl_allow_uid2name");
399
400 REPLICATE(cvar_cl_autoscreenshot, int, "cl_autoscreenshot");
401
402 REPLICATE(cvar_cl_autotaunt, float, "cl_autotaunt");
403
404 REPLICATE(cvar_cl_clippedspectating, bool, "cl_clippedspectating");
405
406 REPLICATE(cvar_cl_handicap, float, "cl_handicap");
407
408 REPLICATE(cvar_cl_jetpack_jump, bool, "cl_jetpack_jump");
409
410 REPLICATE(cvar_cl_movement_track_canjump, bool, "cl_movement_track_canjump");
411
412 REPLICATE(cvar_cl_newusekeysupported, bool, "cl_newusekeysupported");
413
414 REPLICATE(cvar_cl_noantilag, bool, "cl_noantilag");
415
416 REPLICATE(cvar_cl_physics, string, "cl_physics");
417
418 REPLICATE(cvar_cl_voice_directional, int, "cl_voice_directional");
419
420 REPLICATE(cvar_cl_voice_directional_taunt_attenuation, float, "cl_voice_directional_taunt_attenuation");
421
422 REPLICATE(cvar_cl_weaponimpulsemode, int, "cl_weaponimpulsemode");
423
424 REPLICATE(cvar_g_xonoticversion, string, "g_xonoticversion");
425
426 /**
427  * @param f -1: cleanup, 0: request, 1: receive
428  */
429 void GetCvars(entity this, int f)
430 {
431         string s = string_null;
432
433         if (f > 0)
434                 s = strcat1(argv(f));
435
436         get_cvars_f = f;
437         get_cvars_s = s;
438         MUTATOR_CALLHOOK(GetCvars);
439
440         Notification_GetCvars(this);
441
442         ReplicateVars(this, s, f);
443
444         GetCvars_handleString_Fixup(this, s, f, cvar_cl_weaponpriority, "cl_weaponpriority", W_FixWeaponOrder_ForceComplete_AndBuildImpulseList);
445         GetCvars_handleString_Fixup(this, s, f, cvar_cl_weaponpriorities[0], "cl_weaponpriority0", W_FixWeaponOrder_AllowIncomplete);
446         GetCvars_handleString_Fixup(this, s, f, cvar_cl_weaponpriorities[1], "cl_weaponpriority1", W_FixWeaponOrder_AllowIncomplete);
447         GetCvars_handleString_Fixup(this, s, f, cvar_cl_weaponpriorities[2], "cl_weaponpriority2", W_FixWeaponOrder_AllowIncomplete);
448         GetCvars_handleString_Fixup(this, s, f, cvar_cl_weaponpriorities[3], "cl_weaponpriority3", W_FixWeaponOrder_AllowIncomplete);
449         GetCvars_handleString_Fixup(this, s, f, cvar_cl_weaponpriorities[4], "cl_weaponpriority4", W_FixWeaponOrder_AllowIncomplete);
450         GetCvars_handleString_Fixup(this, s, f, cvar_cl_weaponpriorities[5], "cl_weaponpriority5", W_FixWeaponOrder_AllowIncomplete);
451         GetCvars_handleString_Fixup(this, s, f, cvar_cl_weaponpriorities[6], "cl_weaponpriority6", W_FixWeaponOrder_AllowIncomplete);
452         GetCvars_handleString_Fixup(this, s, f, cvar_cl_weaponpriorities[7], "cl_weaponpriority7", W_FixWeaponOrder_AllowIncomplete);
453         GetCvars_handleString_Fixup(this, s, f, cvar_cl_weaponpriorities[8], "cl_weaponpriority8", W_FixWeaponOrder_AllowIncomplete);
454         GetCvars_handleString_Fixup(this, s, f, cvar_cl_weaponpriorities[9], "cl_weaponpriority9", W_FixWeaponOrder_AllowIncomplete);
455
456         GetCvars_handleFloat(this, s, f, cvar_cl_allow_uidtracking, "cl_allow_uidtracking");
457
458         // fixup of switchweapon (needed for LMS or when spectating is disabled, as PutClientInServer comes too early)
459         if (f > 0)
460         {
461                 if (s == "cl_weaponpriority")
462                 {
463                         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
464                         {
465                                 .entity weaponentity = weaponentities[slot];
466                                 if (this.(weaponentity) && (this.(weaponentity).m_weapon != WEP_Null || slot == 0))
467                                         this.(weaponentity).m_switchweapon = w_getbestweapon(this, weaponentity);
468                         }
469                 }
470                 if (s == "cl_allow_uidtracking")
471                         PlayerStats_GameReport_AddPlayer(this);
472         }
473 }
474
475 // decolorizes and team colors the player name when needed
476 string playername(entity p)
477 {
478     string t;
479     if (teamplay && !gameover && IS_PLAYER(p))
480     {
481         t = Team_ColorCode(p.team);
482         return strcat(t, strdecolorize(p.netname));
483     }
484     else
485         return p.netname;
486 }
487
488 float want_weapon(entity weaponinfo, float allguns) // WEAPONTODO: what still needs done?
489 {
490         int i = weaponinfo.m_id;
491         int d = 0;
492         bool allow_mutatorblocked = false;
493
494         if(!i)
495                 return 0;
496
497         bool mutator_returnvalue = MUTATOR_CALLHOOK(WantWeapon, weaponinfo, d, allguns, allow_mutatorblocked);
498         d = M_ARGV(1, float);
499         allguns = M_ARGV(2, bool);
500         allow_mutatorblocked = M_ARGV(3, bool);
501
502         if(allguns)
503         {
504                 if(weaponinfo.spawnflags & WEP_FLAG_NORMAL)
505                         d = true;
506                 else
507                         d = false;
508         }
509         else if(!mutator_returnvalue)
510                 d = !(!weaponinfo.weaponstart);
511
512         if(!allow_mutatorblocked && (weaponinfo.spawnflags & WEP_FLAG_MUTATORBLOCKED)) // never default mutator blocked guns
513                 d = 0;
514
515         float t = weaponinfo.weaponstartoverride;
516
517         //print(strcat("want_weapon: ", weaponinfo.netname, " - d: ", ftos(d), ", t: ", ftos(t), ". \n"));
518
519         // bit order in t:
520         // 1: want or not
521         // 2: is default?
522         // 4: is set by default?
523         if(t < 0)
524                 t = 4 | (3 * d);
525         else
526                 t |= (2 * d);
527
528         return t;
529 }
530
531 void readplayerstartcvars()
532 {
533         float i, t;
534         string s;
535
536         // initialize starting values for players
537         start_weapons = '0 0 0';
538         start_weapons_default = '0 0 0';
539         start_weapons_defaultmask = '0 0 0';
540         start_items = 0;
541         start_ammo_shells = 0;
542         start_ammo_nails = 0;
543         start_ammo_rockets = 0;
544         start_ammo_cells = 0;
545         start_ammo_plasma = 0;
546         start_health = cvar("g_balance_health_start");
547         start_armorvalue = cvar("g_balance_armor_start");
548
549         g_weaponarena = 0;
550         g_weaponarena_weapons = '0 0 0';
551
552         s = cvar_string("g_weaponarena");
553
554         MUTATOR_CALLHOOK(SetWeaponArena, s);
555         s = M_ARGV(0, string);
556
557         if (s == "0" || s == "")
558         {
559                 // no arena
560         }
561         else if (s == "off")
562         {
563                 // forcibly turn off weaponarena
564         }
565         else if (s == "all" || s == "1")
566         {
567                 g_weaponarena = 1;
568                 g_weaponarena_list = "All Weapons";
569                 FOREACH(Weapons, it != WEP_Null, LAMBDA(
570                         if(!(it.spawnflags & WEP_FLAG_MUTATORBLOCKED))
571                                 g_weaponarena_weapons |= (it.m_wepset);
572                 ));
573         }
574         else if (s == "devall")
575         {
576                 g_weaponarena = 1;
577                 g_weaponarena_list = "All Weapons"; // TODO: report as more than just all weapons?
578                 FOREACH(Weapons, it != WEP_Null,
579                 {
580                         g_weaponarena_weapons |= (it.m_wepset);
581                 });
582         }
583         else if (s == "most")
584         {
585                 g_weaponarena = 1;
586                 g_weaponarena_list = "Most Weapons";
587                 FOREACH(Weapons, it != WEP_Null, LAMBDA(
588                         if(!(it.spawnflags & WEP_FLAG_MUTATORBLOCKED))
589                                 if(it.spawnflags & WEP_FLAG_NORMAL)
590                                         g_weaponarena_weapons |= (it.m_wepset);
591                 ));
592         }
593         else if (s == "none")
594         {
595                 g_weaponarena = 1;
596                 g_weaponarena_list = "No Weapons";
597         }
598         else
599         {
600                 g_weaponarena = 1;
601                 t = tokenize_console(s);
602                 g_weaponarena_list = "";
603                 for (i = 0; i < t; ++i)
604                 {
605                         s = argv(i);
606                         FOREACH(Weapons, it != WEP_Null, LAMBDA(
607                                 if(it.netname == s)
608                                 {
609                                         g_weaponarena_weapons |= (it.m_wepset);
610                                         g_weaponarena_list = strcat(g_weaponarena_list, it.m_name, " & ");
611                                         break;
612                                 }
613                         ));
614                 }
615                 g_weaponarena_list = strzone(substring(g_weaponarena_list, 0, strlen(g_weaponarena_list) - 3));
616         }
617
618         if(g_weaponarena)
619                 g_weaponarena_random = cvar("g_weaponarena_random");
620         else
621                 g_weaponarena_random = 0;
622         g_weaponarena_random_with_blaster = cvar("g_weaponarena_random_with_blaster");
623
624         if (g_weaponarena)
625         {
626                 g_weapon_stay = 0; // incompatible
627                 start_weapons = g_weaponarena_weapons;
628                 start_items |= IT_UNLIMITED_AMMO;
629         }
630         else
631         {
632                 FOREACH(Weapons, it != WEP_Null, LAMBDA(
633                         int w = want_weapon(it, false);
634                         WepSet s = it.m_wepset;
635                         if(w & 1)
636                                 start_weapons |= s;
637                         if(w & 2)
638                                 start_weapons_default |= s;
639                         if(w & 4)
640                                 start_weapons_defaultmask |= s;
641                 ));
642         }
643
644         if(!cvar("g_use_ammunition"))
645                 start_items |= IT_UNLIMITED_AMMO;
646
647         if(start_items & IT_UNLIMITED_WEAPON_AMMO)
648         {
649                 start_ammo_shells = 999;
650                 start_ammo_nails = 999;
651                 start_ammo_rockets = 999;
652                 start_ammo_cells = 999;
653                 start_ammo_plasma = 999;
654                 start_ammo_fuel = 999;
655         }
656         else
657         {
658                 start_ammo_shells = cvar("g_start_ammo_shells");
659                 start_ammo_nails = cvar("g_start_ammo_nails");
660                 start_ammo_rockets = cvar("g_start_ammo_rockets");
661                 start_ammo_cells = cvar("g_start_ammo_cells");
662                 start_ammo_plasma = cvar("g_start_ammo_plasma");
663                 start_ammo_fuel = cvar("g_start_ammo_fuel");
664         }
665
666         if (warmup_stage)
667         {
668                 warmup_start_ammo_shells = start_ammo_shells;
669                 warmup_start_ammo_nails = start_ammo_nails;
670                 warmup_start_ammo_rockets = start_ammo_rockets;
671                 warmup_start_ammo_cells = start_ammo_cells;
672                 warmup_start_ammo_plasma = start_ammo_plasma;
673                 warmup_start_ammo_fuel = start_ammo_fuel;
674                 warmup_start_health = start_health;
675                 warmup_start_armorvalue = start_armorvalue;
676                 warmup_start_weapons = start_weapons;
677                 warmup_start_weapons_default = start_weapons_default;
678                 warmup_start_weapons_defaultmask = start_weapons_defaultmask;
679
680                 if (!g_weaponarena && !g_ca && !g_freezetag)
681                 {
682                         warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
683                         warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
684                         warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
685                         warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
686                         warmup_start_ammo_plasma = cvar("g_warmup_start_ammo_plasma");
687                         warmup_start_ammo_fuel = cvar("g_warmup_start_ammo_fuel");
688                         warmup_start_health = cvar("g_warmup_start_health");
689                         warmup_start_armorvalue = cvar("g_warmup_start_armor");
690                         warmup_start_weapons = '0 0 0';
691                         warmup_start_weapons_default = '0 0 0';
692                         warmup_start_weapons_defaultmask = '0 0 0';
693                         FOREACH(Weapons, it != WEP_Null, LAMBDA(
694                                 int w = want_weapon(it, g_warmup_allguns);
695                                 WepSet s = (it.m_wepset);
696                                 if(w & 1)
697                                         warmup_start_weapons |= s;
698                                 if(w & 2)
699                                         warmup_start_weapons_default |= s;
700                                 if(w & 4)
701                                         warmup_start_weapons_defaultmask |= s;
702                         ));
703                 }
704         }
705
706         if (g_jetpack)
707                 start_items |= ITEM_Jetpack.m_itemid;
708
709         MUTATOR_CALLHOOK(SetStartItems);
710
711         if (start_items & ITEM_Jetpack.m_itemid)
712         {
713                 start_items |= ITEM_JetpackRegen.m_itemid;
714                 start_ammo_fuel = max(start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
715                 warmup_start_ammo_fuel = max(warmup_start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
716         }
717
718         WepSet precache_weapons = start_weapons;
719         if (g_warmup_allguns != 1)
720                 precache_weapons |= warmup_start_weapons;
721         FOREACH(Weapons, it != WEP_Null, LAMBDA(
722                 if(precache_weapons & (it.m_wepset))
723                         it.wr_init(it);
724         ));
725
726         start_ammo_shells = max(0, start_ammo_shells);
727         start_ammo_nails = max(0, start_ammo_nails);
728         start_ammo_rockets = max(0, start_ammo_rockets);
729         start_ammo_cells = max(0, start_ammo_cells);
730         start_ammo_plasma = max(0, start_ammo_plasma);
731         start_ammo_fuel = max(0, start_ammo_fuel);
732
733         warmup_start_ammo_shells = max(0, warmup_start_ammo_shells);
734         warmup_start_ammo_nails = max(0, warmup_start_ammo_nails);
735         warmup_start_ammo_rockets = max(0, warmup_start_ammo_rockets);
736         warmup_start_ammo_cells = max(0, warmup_start_ammo_cells);
737         warmup_start_ammo_plasma = max(0, warmup_start_ammo_plasma);
738         warmup_start_ammo_fuel = max(0, warmup_start_ammo_fuel);
739 }
740
741 void precache_playermodel(string m)
742 {
743         float globhandle, i, n;
744         string f;
745
746         if(substring(m, -9,5) == "_lod1")
747                 return;
748         if(substring(m, -9,5) == "_lod2")
749                 return;
750         precache_model(m);
751         f = strcat(substring(m, 0, -5), "_lod1", substring(m, -4, -1));
752         if(fexists(f))
753                 precache_model(f);
754         f = strcat(substring(m, 0, -5), "_lod2", substring(m, -4, -1));
755         if(fexists(f))
756                 precache_model(f);
757
758         globhandle = search_begin(strcat(m, "_*.sounds"), true, false);
759         if (globhandle < 0)
760                 return;
761         n = search_getsize(globhandle);
762         for (i = 0; i < n; ++i)
763         {
764                 //print(search_getfilename(globhandle, i), "\n");
765                 f = search_getfilename(globhandle, i);
766                 PrecachePlayerSounds(f);
767         }
768         search_end(globhandle);
769 }
770 void precache_all_playermodels(string pattern)
771 {
772         int globhandle = search_begin(pattern, true, false);
773         if (globhandle < 0) return;
774         int n = search_getsize(globhandle);
775         for (int i = 0; i < n; ++i)
776         {
777                 string s = search_getfilename(globhandle, i);
778                 precache_playermodel(s);
779         }
780         search_end(globhandle);
781 }
782
783 void precache_playermodels(string s)
784 {
785         FOREACH_WORD(s, true, LAMBDA(precache_playermodel(it)));
786 }
787
788 void precache()
789 {
790     // gamemode related things
791
792     // Precache all player models if desired
793     if (autocvar_sv_precacheplayermodels)
794     {
795         PrecachePlayerSounds("sound/player/default.sounds");
796         precache_all_playermodels("models/player/*.zym");
797         precache_all_playermodels("models/player/*.dpm");
798         precache_all_playermodels("models/player/*.md3");
799         precache_all_playermodels("models/player/*.psk");
800         precache_all_playermodels("models/player/*.iqm");
801     }
802
803     if (autocvar_sv_defaultcharacter)
804     {
805                 precache_playermodels(autocvar_sv_defaultplayermodel_red);
806                 precache_playermodels(autocvar_sv_defaultplayermodel_blue);
807                 precache_playermodels(autocvar_sv_defaultplayermodel_yellow);
808                 precache_playermodels(autocvar_sv_defaultplayermodel_pink);
809                 precache_playermodels(autocvar_sv_defaultplayermodel);
810     }
811
812 #if 0
813     // Disabled this code because it simply does not work (e.g. ignores bgmvolume, overlaps with "cd loop" controlled tracks).
814
815     if (!this.noise && this.music) // quake 3 uses the music field
816         this.noise = this.music;
817
818     // plays music for the level if there is any
819     if (this.noise)
820     {
821         precache_sound (this.noise);
822         ambientsound ('0 0 0', this.noise, VOL_BASE, ATTEN_NONE);
823     }
824 #endif
825 }
826
827
828 void make_safe_for_remove(entity e)
829 {
830     if (e.initialize_entity)
831     {
832         entity ent, prev = NULL;
833         for (ent = initialize_entity_first; ent; )
834         {
835             if ((ent == e) || ((ent.classname == "initialize_entity") && (ent.enemy == e)))
836             {
837                 //print("make_safe_for_remove: getting rid of initializer ", etos(ent), "\n");
838                 // skip it in linked list
839                 if (prev)
840                 {
841                     prev.initialize_entity_next = ent.initialize_entity_next;
842                     ent = prev.initialize_entity_next;
843                 }
844                 else
845                 {
846                     initialize_entity_first = ent.initialize_entity_next;
847                     ent = initialize_entity_first;
848                 }
849             }
850             else
851             {
852                 prev = ent;
853                 ent = ent.initialize_entity_next;
854             }
855         }
856     }
857 }
858
859 .float remove_except_protected_forbidden;
860 void remove_except_protected(entity e)
861 {
862         if(e.remove_except_protected_forbidden)
863                 error("not allowed to remove this at this point");
864         builtin_remove(e);
865 }
866
867 void remove_unsafely(entity e)
868 {
869     if(e.classname == "spike")
870         error("Removing spikes is forbidden (crylink bug), please report");
871     builtin_remove(e);
872 }
873
874 void remove_safely(entity e)
875 {
876     make_safe_for_remove(e);
877     builtin_remove(e);
878 }
879
880 void InitializeEntity(entity e, void(entity this) func, float order)
881 {
882     entity prev, cur;
883
884     if (!e || e.initialize_entity)
885     {
886         // make a proxy initializer entity
887         entity e_old = e;
888         e = new(initialize_entity);
889         e.enemy = e_old;
890     }
891
892     e.initialize_entity = func;
893     e.initialize_entity_order = order;
894
895     cur = initialize_entity_first;
896     prev = NULL;
897     for (;;)
898     {
899         if (!cur || cur.initialize_entity_order > order)
900         {
901             // insert between prev and cur
902             if (prev)
903                 prev.initialize_entity_next = e;
904             else
905                 initialize_entity_first = e;
906             e.initialize_entity_next = cur;
907             return;
908         }
909         prev = cur;
910         cur = cur.initialize_entity_next;
911     }
912 }
913 void InitializeEntitiesRun()
914 {
915     entity startoflist = initialize_entity_first;
916     initialize_entity_first = NULL;
917     delete_fn = remove_except_protected;
918     for (entity e = startoflist; e; e = e.initialize_entity_next)
919     {
920                 e.remove_except_protected_forbidden = 1;
921     }
922     for (entity e = startoflist; e; )
923     {
924                 e.remove_except_protected_forbidden = 0;
925         e.initialize_entity_order = 0;
926         entity next = e.initialize_entity_next;
927         e.initialize_entity_next = NULL;
928         var void(entity this) func = e.initialize_entity;
929         e.initialize_entity = func_null;
930         if (e.classname == "initialize_entity")
931         {
932             entity wrappee = e.enemy;
933             builtin_remove(e);
934             e = wrappee;
935         }
936         //dprint("Delayed initialization: ", e.classname, "\n");
937         if (func)
938         {
939                 func(e);
940         }
941         else
942         {
943             eprint(e);
944             backtrace(strcat("Null function in: ", e.classname, "\n"));
945         }
946         e = next;
947     }
948     delete_fn = remove_unsafely;
949 }
950
951 .float(entity) isEliminated;
952 bool EliminatedPlayers_SendEntity(entity this, entity to, float sendflags)
953 {
954         float i, f, b;
955         entity e;
956         WriteHeader(MSG_ENTITY, ENT_CLIENT_ELIMINATEDPLAYERS);
957         WriteByte(MSG_ENTITY, sendflags);
958
959         if(sendflags & 1)
960         {
961                 for(i = 1; i <= maxclients; i += 8)
962                 {
963                         for(f = 0, e = edict_num(i), b = 1; b < 256; b *= 2, e = nextent(e))
964                         {
965                                 if(eliminatedPlayers.isEliminated(e))
966                                         f |= b;
967                         }
968                         WriteByte(MSG_ENTITY, f);
969                 }
970         }
971
972         return true;
973 }
974
975 void EliminatedPlayers_Init(float(entity) isEliminated_func)
976 {
977         if(eliminatedPlayers)
978         {
979                 backtrace("Can't spawn eliminatedPlayers again!");
980                 return;
981         }
982         Net_LinkEntity(eliminatedPlayers = spawn(), false, 0, EliminatedPlayers_SendEntity);
983         eliminatedPlayers.isEliminated = isEliminated_func;
984 }
985
986
987
988
989 void adaptor_think2use_hittype_splash(entity this) // for timed projectile detonation
990 {
991         if(!(IS_ONGROUND(this))) // if onground, we ARE touching something, but HITTYPE_SPLASH is to be networked if the damage causing projectile is not touching ANYTHING
992                 this.projectiledeathtype |= HITTYPE_SPLASH;
993         adaptor_think2use(this);
994 }
995
996 // deferred dropping
997 void DropToFloor_Handler(entity this)
998 {
999     WITHSELF(this, builtin_droptofloor());
1000     this.dropped_origin = this.origin;
1001 }
1002
1003 void droptofloor(entity this)
1004 {
1005     InitializeEntity(this, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
1006 }
1007
1008
1009
1010 float trace_hits_box_a0, trace_hits_box_a1;
1011
1012 float trace_hits_box_1d(float end, float thmi, float thma)
1013 {
1014     if (end == 0)
1015     {
1016         // just check if x is in range
1017         if (0 < thmi)
1018             return false;
1019         if (0 > thma)
1020             return false;
1021     }
1022     else
1023     {
1024         // do the trace with respect to x
1025         // 0 -> end has to stay in thmi -> thma
1026         trace_hits_box_a0 = max(trace_hits_box_a0, min(thmi / end, thma / end));
1027         trace_hits_box_a1 = min(trace_hits_box_a1, max(thmi / end, thma / end));
1028         if (trace_hits_box_a0 > trace_hits_box_a1)
1029             return false;
1030     }
1031     return true;
1032 }
1033
1034 float trace_hits_box(vector start, vector end, vector thmi, vector thma)
1035 {
1036     end -= start;
1037     thmi -= start;
1038     thma -= start;
1039     // now it is a trace from 0 to end
1040
1041     trace_hits_box_a0 = 0;
1042     trace_hits_box_a1 = 1;
1043
1044     if (!trace_hits_box_1d(end.x, thmi.x, thma.x))
1045         return false;
1046     if (!trace_hits_box_1d(end.y, thmi.y, thma.y))
1047         return false;
1048     if (!trace_hits_box_1d(end.z, thmi.z, thma.z))
1049         return false;
1050
1051     return true;
1052 }
1053
1054 float tracebox_hits_box(vector start, vector mi, vector ma, vector end, vector thmi, vector thma)
1055 {
1056     return trace_hits_box(start, end, thmi - ma, thma - mi);
1057 }
1058
1059 bool SUB_NoImpactCheck(entity this, entity toucher)
1060 {
1061         // zero hitcontents = this is not the real impact, but either the
1062         // mirror-impact of something hitting the projectile instead of the
1063         // projectile hitting the something, or a touchareagrid one. Neither of
1064         // these stop the projectile from moving, so...
1065         if(trace_dphitcontents == 0)
1066         {
1067                 LOG_TRACEF("A hit from a projectile happened with no hit contents! DEBUG THIS, this should never happen for projectiles! Projectile will self-destruct. (edict: %i, classname: %s, origin: %v)", this, this.classname, this.origin);
1068                 checkclient(this);
1069         }
1070     if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1071         return true;
1072     if (toucher == NULL && this.size != '0 0 0')
1073     {
1074         vector tic;
1075         tic = this.velocity * sys_frametime;
1076         tic = tic + normalize(tic) * vlen(this.maxs - this.mins);
1077         traceline(this.origin - tic, this.origin + tic, MOVE_NORMAL, this);
1078         if (trace_fraction >= 1)
1079         {
1080             LOG_TRACE("Odd... did not hit...?");
1081         }
1082         else if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1083         {
1084             LOG_TRACE("Detected and prevented the sky-grapple bug.");
1085             return true;
1086         }
1087     }
1088
1089     return false;
1090 }
1091
1092 #define SUB_OwnerCheck(ent,oth) ((oth) && ((oth) == (ent).owner))
1093
1094 void W_Crylink_Dequeue(entity e);
1095 bool WarpZone_Projectile_Touch_ImpactFilter_Callback(entity this, entity toucher)
1096 {
1097         if(SUB_OwnerCheck(this, toucher))
1098                 return true;
1099         if(SUB_NoImpactCheck(this, toucher))
1100         {
1101                 if(this.classname == "nade")
1102                         return false; // no checks here
1103                 else if(this.classname == "grapplinghook")
1104                         RemoveHook(this);
1105                 else if(this.classname == "spike")
1106                 {
1107                         W_Crylink_Dequeue(this);
1108                         delete(this);
1109                 }
1110                 else
1111                         delete(this);
1112                 return true;
1113         }
1114         if(trace_ent && trace_ent.solid > SOLID_TRIGGER)
1115                 UpdateCSQCProjectile(this);
1116         return false;
1117 }
1118
1119 /** engine callback */
1120 void URI_Get_Callback(float id, float status, string data)
1121 {
1122         if(url_URI_Get_Callback(id, status, data))
1123         {
1124                 // handled
1125         }
1126         else if (id == URI_GET_DISCARD)
1127         {
1128                 // discard
1129         }
1130         else if (id >= URI_GET_CURL && id <= URI_GET_CURL_END)
1131         {
1132                 // sv_cmd curl
1133                 Curl_URI_Get_Callback(id, status, data);
1134         }
1135         else if (id >= URI_GET_IPBAN && id <= URI_GET_IPBAN_END)
1136         {
1137                 // online ban list
1138                 OnlineBanList_URI_Get_Callback(id, status, data);
1139         }
1140         else if (MUTATOR_CALLHOOK(URI_GetCallback, id, status, data))
1141         {
1142                 // handled by a mutator
1143         }
1144         else
1145         {
1146                 LOG_INFO("Received HTTP request data for an invalid id ", ftos(id), ".\n");
1147         }
1148 }
1149
1150 string uid2name(string myuid) {
1151         string s;
1152         s = db_get(ServerProgsDB, strcat("/uid2name/", myuid));
1153
1154         // FIXME remove this later after 0.6 release
1155         // convert old style broken records to correct style
1156         if(s == "")
1157         {
1158                 s = db_get(ServerProgsDB, strcat("uid2name", myuid));
1159                 if(s != "")
1160                 {
1161                         db_put(ServerProgsDB, strcat("/uid2name/", myuid), s);
1162                         db_remove(ServerProgsDB, strcat("uid2name", myuid));
1163                 }
1164         }
1165
1166         if(s == "")
1167                 s = "^1Unregistered Player";
1168         return s;
1169 }
1170
1171 float MoveToRandomLocationWithinBounds(entity e, vector boundmin, vector boundmax, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1172 {
1173     float m, i;
1174     vector start, org, delta, end, enddown, mstart;
1175
1176     m = e.dphitcontentsmask;
1177     e.dphitcontentsmask = goodcontents | badcontents;
1178
1179     org = boundmin;
1180     delta = boundmax - boundmin;
1181
1182     start = end = org;
1183
1184     for (i = 0; i < attempts; ++i)
1185     {
1186         start.x = org.x + random() * delta.x;
1187         start.y = org.y + random() * delta.y;
1188         start.z = org.z + random() * delta.z;
1189
1190         // rule 1: start inside world bounds, and outside
1191         // solid, and don't start from somewhere where you can
1192         // fall down to evil
1193         tracebox(start, e.mins, e.maxs, start - '0 0 1' * delta.z, MOVE_NORMAL, e);
1194         if (trace_fraction >= 1)
1195             continue;
1196         if (trace_startsolid)
1197             continue;
1198         if (trace_dphitcontents & badcontents)
1199             continue;
1200         if (trace_dphitq3surfaceflags & badsurfaceflags)
1201             continue;
1202
1203         // rule 2: if we are too high, lower the point
1204         if (trace_fraction * delta.z > maxaboveground)
1205             start = trace_endpos + '0 0 1' * maxaboveground;
1206         enddown = trace_endpos;
1207
1208         // rule 3: make sure we aren't outside the map. This only works
1209         // for somewhat well formed maps. A good rule of thumb is that
1210         // the map should have a convex outside hull.
1211         // these can be traceLINES as we already verified the starting box
1212         mstart = start + 0.5 * (e.mins + e.maxs);
1213         traceline(mstart, mstart + '1 0 0' * delta.x, MOVE_NORMAL, e);
1214         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1215             continue;
1216         traceline(mstart, mstart - '1 0 0' * delta.x, MOVE_NORMAL, e);
1217         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1218             continue;
1219         traceline(mstart, mstart + '0 1 0' * delta.y, MOVE_NORMAL, e);
1220         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1221             continue;
1222         traceline(mstart, mstart - '0 1 0' * delta.y, MOVE_NORMAL, e);
1223         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1224             continue;
1225         traceline(mstart, mstart + '0 0 1' * delta.z, MOVE_NORMAL, e);
1226         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1227             continue;
1228
1229         // rule 4: we must "see" some spawnpoint or item
1230     entity sp = NULL;
1231     IL_EACH(g_spawnpoints, checkpvs(mstart, it),
1232     {
1233         if((traceline(mstart, it.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1234         {
1235                 sp = it;
1236                 break;
1237         }
1238     });
1239         if(!sp)
1240         {
1241                 IL_EACH(g_items, checkpvs(mstart, it),
1242                 {
1243                         if((traceline(mstart, it.origin + (it.mins + it.maxs) * 0.5, MOVE_NORMAL, e), trace_fraction) >= 1)
1244                         {
1245                                 sp = it;
1246                                 break;
1247                         }
1248                 });
1249
1250                 if(!sp)
1251                         continue;
1252         }
1253
1254         // find a random vector to "look at"
1255         end.x = org.x + random() * delta.x;
1256         end.y = org.y + random() * delta.y;
1257         end.z = org.z + random() * delta.z;
1258         end = start + normalize(end - start) * vlen(delta);
1259
1260         // rule 4: start TO end must not be too short
1261         tracebox(start, e.mins, e.maxs, end, MOVE_NORMAL, e);
1262         if (trace_startsolid)
1263             continue;
1264         if (trace_fraction < minviewdistance / vlen(delta))
1265             continue;
1266
1267         // rule 5: don't want to look at sky
1268         if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY)
1269             continue;
1270
1271         // rule 6: we must not end up in trigger_hurt
1272         if (tracebox_hits_trigger_hurt(start, e.mins, e.maxs, enddown))
1273             continue;
1274
1275         break;
1276     }
1277
1278     e.dphitcontentsmask = m;
1279
1280     if (i < attempts)
1281     {
1282         setorigin(e, start);
1283         e.angles = vectoangles(end - start);
1284         LOG_TRACE("Needed ", ftos(i + 1), " attempts");
1285         return true;
1286     }
1287     else
1288         return false;
1289 }
1290
1291 float MoveToRandomMapLocation(entity e, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1292 {
1293         return MoveToRandomLocationWithinBounds(e, world.mins, world.maxs, goodcontents, badcontents, badsurfaceflags, attempts, maxaboveground, minviewdistance);
1294 }
1295
1296 void write_recordmarker(entity pl, float tstart, float dt)
1297 {
1298     GameLogEcho(strcat(":recordset:", ftos(pl.playerid), ":", ftos(dt)));
1299
1300     // also write a marker into demo files for demotc-race-record-extractor to find
1301     stuffcmd(pl,
1302              strcat(
1303                  strcat("//", strconv(2, 0, 0, GetGametype()), " RECORD SET ", TIME_ENCODED_TOSTRING(TIME_ENCODE(dt))),
1304                  " ", ftos(tstart), " ", ftos(dt), "\n"));
1305 }
1306
1307 void attach_sameorigin(entity e, entity to, string tag)
1308 {
1309     vector org, t_forward, t_left, t_up, e_forward, e_up;
1310     float tagscale;
1311
1312     org = e.origin - gettaginfo(to, gettagindex(to, tag));
1313     tagscale = pow(vlen(v_forward), -2); // undo a scale on the tag
1314     t_forward = v_forward * tagscale;
1315     t_left = v_right * -tagscale;
1316     t_up = v_up * tagscale;
1317
1318     e.origin_x = org * t_forward;
1319     e.origin_y = org * t_left;
1320     e.origin_z = org * t_up;
1321
1322     // current forward and up directions
1323     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1324                 e.angles = AnglesTransform_FromVAngles(e.angles);
1325         else
1326                 e.angles = AnglesTransform_FromAngles(e.angles);
1327     fixedmakevectors(e.angles);
1328
1329     // untransform forward, up!
1330     e_forward.x = v_forward * t_forward;
1331     e_forward.y = v_forward * t_left;
1332     e_forward.z = v_forward * t_up;
1333     e_up.x = v_up * t_forward;
1334     e_up.y = v_up * t_left;
1335     e_up.z = v_up * t_up;
1336
1337     e.angles = fixedvectoangles2(e_forward, e_up);
1338     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1339                 e.angles = AnglesTransform_ToVAngles(e.angles);
1340         else
1341                 e.angles = AnglesTransform_ToAngles(e.angles);
1342
1343     setattachment(e, to, tag);
1344     setorigin(e, e.origin);
1345 }
1346
1347 void detach_sameorigin(entity e)
1348 {
1349     vector org;
1350     org = gettaginfo(e, 0);
1351     e.angles = fixedvectoangles2(v_forward, v_up);
1352     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1353                 e.angles = AnglesTransform_ToVAngles(e.angles);
1354         else
1355                 e.angles = AnglesTransform_ToAngles(e.angles);
1356     setorigin(e, org);
1357     setattachment(e, NULL, "");
1358     setorigin(e, e.origin);
1359 }
1360
1361 void follow_sameorigin(entity e, entity to)
1362 {
1363     set_movetype(e, MOVETYPE_FOLLOW); // make the hole follow
1364     e.aiment = to; // make the hole follow bmodel
1365     e.punchangle = to.angles; // the original angles of bmodel
1366     e.view_ofs = e.origin - to.origin; // relative origin
1367     e.v_angle = e.angles - to.angles; // relative angles
1368 }
1369
1370 void unfollow_sameorigin(entity e)
1371 {
1372     set_movetype(e, MOVETYPE_NONE);
1373 }
1374
1375 entity gettaginfo_relative_ent;
1376 vector gettaginfo_relative(entity e, float tag)
1377 {
1378     if (!gettaginfo_relative_ent)
1379     {
1380         gettaginfo_relative_ent = spawn();
1381         gettaginfo_relative_ent.effects = EF_NODRAW;
1382     }
1383     gettaginfo_relative_ent.model = e.model;
1384     gettaginfo_relative_ent.modelindex = e.modelindex;
1385     gettaginfo_relative_ent.frame = e.frame;
1386     return gettaginfo(gettaginfo_relative_ent, tag);
1387 }
1388
1389 .string aiment_classname;
1390 .float aiment_deadflag;
1391 void SetMovetypeFollow(entity ent, entity e)
1392 {
1393         // FIXME this may not be warpzone aware
1394         set_movetype(ent, MOVETYPE_FOLLOW); // make the hole follow
1395         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.
1396         ent.aiment = e; // make the hole follow bmodel
1397         ent.punchangle = e.angles; // the original angles of bmodel
1398         ent.view_ofs = ent.origin - e.origin; // relative origin
1399         ent.v_angle = ent.angles - e.angles; // relative angles
1400         ent.aiment_classname = strzone(e.classname);
1401         ent.aiment_deadflag = e.deadflag;
1402 }
1403 void UnsetMovetypeFollow(entity ent)
1404 {
1405         set_movetype(ent, MOVETYPE_FLY);
1406         PROJECTILE_MAKETRIGGER(ent);
1407         ent.aiment = NULL;
1408 }
1409 float LostMovetypeFollow(entity ent)
1410 {
1411 /*
1412         if(ent.move_movetype != MOVETYPE_FOLLOW)
1413                 if(ent.aiment)
1414                         error("???");
1415 */
1416         if(ent.aiment)
1417         {
1418                 if(ent.aiment.classname != ent.aiment_classname)
1419                         return 1;
1420                 if(ent.aiment.deadflag != ent.aiment_deadflag)
1421                         return 1;
1422         }
1423         return 0;
1424 }
1425
1426 .bool pushable;
1427 bool isPushable(entity e)
1428 {
1429         if(e.pushable)
1430                 return true;
1431         if(IS_VEHICLE(e))
1432                 return false;
1433         if(e.iscreature)
1434                 return true;
1435         switch(e.classname)
1436         {
1437                 case "body":
1438                 case "droppedweapon":
1439                         return true;
1440                 case "bullet": // antilagged bullets can't hit this either
1441                         return false;
1442         }
1443         if (e.projectiledeathtype)
1444                 return true;
1445         return false;
1446 }