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