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