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