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