]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/miscfunctions.qc
Merge branch 'Mario/balance_v2' into 'master'
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / miscfunctions.qc
1 #include "miscfunctions.qh"
2 #include "antilag.qh"
3 #include "command/common.qh"
4 #include "constants.qh"
5 #include "g_hook.qh"
6 #include "ipban.qh"
7 #include "mutators/all.qh"
8 #include "../common/t_items.qh"
9 #include "weapons/accuracy.qh"
10 #include "weapons/csqcprojectile.qh"
11 #include "weapons/selection.qh"
12 #include "../common/command/generic.qh"
13 #include "../common/constants.qh"
14 #include "../common/deathtypes/all.qh"
15 #include "../common/mapinfo.qh"
16 #include "../common/notifications.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 = ((PS(self).m_weapon == WEP_Null) ? ((PS(self).m_switchweapon == WEP_Null) ? Weapons_from(self.cnt) : PS(self).m_switchweapon) : PS(self).m_weapon).m_name; 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_handleFloat(s, f, cvar_cl_allow_uid2name, "cl_allow_uid2name");
421         GetCvars_handleFloat(s, f, cvar_cl_allow_uidtracking, "cl_allow_uidtracking");
422         GetCvars_handleFloat(s, f, cvar_cl_movement_track_canjump, "cl_movement_track_canjump");
423         GetCvars_handleFloat(s, f, cvar_cl_newusekeysupported, "cl_newusekeysupported");
424
425         // fixup of switchweapon (needed for LMS or when spectating is disabled, as PutClientInServer comes too early)
426         if (f > 0)
427         {
428                 if (s == "cl_weaponpriority")
429                         if (PS(self)) PS(self).m_switchweapon = w_getbestweapon(self);
430                 if (s == "cl_allow_uidtracking")
431                         PlayerStats_GameReport_AddPlayer(self);
432         }
433 }
434
435 // decolorizes and team colors the player name when needed
436 string playername(entity p)
437 {
438     string t;
439     if (teamplay && !intermission_running && IS_PLAYER(p))
440     {
441         t = Team_ColorCode(p.team);
442         return strcat(t, strdecolorize(p.netname));
443     }
444     else
445         return p.netname;
446 }
447
448 float want_weapon(entity weaponinfo, float allguns) // WEAPONTODO: what still needs done?
449 {
450         int i = weaponinfo.m_id;
451         int d = 0;
452         bool allow_mutatorblocked = false;
453
454         if(!i)
455                 return 0;
456
457         bool mutator_returnvalue = MUTATOR_CALLHOOK(WantWeapon, weaponinfo, d, allguns, allow_mutatorblocked);
458         d = ret_float;
459         allguns = want_allguns;
460         allow_mutatorblocked = false;
461
462         if(allguns)
463         {
464                 if(weaponinfo.spawnflags & WEP_FLAG_NORMAL)
465                         d = true;
466                 else
467                         d = false;
468         }
469         else if(!mutator_returnvalue)
470                 d = !(!weaponinfo.weaponstart);
471
472         if(!allow_mutatorblocked && (weaponinfo.spawnflags & WEP_FLAG_MUTATORBLOCKED)) // never default mutator blocked guns
473                 d = 0;
474
475         float t = weaponinfo.weaponstartoverride;
476
477         //print(strcat("want_weapon: ", weaponinfo.netname, " - d: ", ftos(d), ", t: ", ftos(t), ". \n"));
478
479         // bit order in t:
480         // 1: want or not
481         // 2: is default?
482         // 4: is set by default?
483         if(t < 0)
484                 t = 4 | (3 * d);
485         else
486                 t |= (2 * d);
487
488         return t;
489 }
490
491 void readplayerstartcvars()
492 {
493         float i, t;
494         string s;
495
496         // initialize starting values for players
497         start_weapons = '0 0 0';
498         start_weapons_default = '0 0 0';
499         start_weapons_defaultmask = '0 0 0';
500         start_items = 0;
501         start_ammo_shells = 0;
502         start_ammo_nails = 0;
503         start_ammo_rockets = 0;
504         start_ammo_cells = 0;
505         start_ammo_plasma = 0;
506         start_health = cvar("g_balance_health_start");
507         start_armorvalue = cvar("g_balance_armor_start");
508
509         g_weaponarena = 0;
510         g_weaponarena_weapons = '0 0 0';
511
512         s = cvar_string("g_weaponarena");
513
514         MUTATOR_CALLHOOK(SetWeaponArena, s);
515         s = ret_string;
516
517         if (s == "0" || s == "")
518         {
519                 // no arena
520         }
521         else if (s == "off")
522         {
523                 // forcibly turn off weaponarena
524         }
525         else if (s == "all" || s == "1")
526         {
527                 g_weaponarena = 1;
528                 g_weaponarena_list = "All Weapons";
529                 FOREACH(Weapons, it != WEP_Null, LAMBDA(
530                         if(!(it.spawnflags & WEP_FLAG_MUTATORBLOCKED))
531                                 g_weaponarena_weapons |= (it.m_wepset);
532                 ));
533         }
534         else if (s == "most")
535         {
536                 g_weaponarena = 1;
537                 g_weaponarena_list = "Most Weapons";
538                 FOREACH(Weapons, it != WEP_Null, LAMBDA(
539                         if(!(it.spawnflags & WEP_FLAG_MUTATORBLOCKED))
540                                 if(it.spawnflags & WEP_FLAG_NORMAL)
541                                         g_weaponarena_weapons |= (it.m_wepset);
542                 ));
543         }
544         else if (s == "none")
545         {
546                 g_weaponarena = 1;
547                 g_weaponarena_list = "No Weapons";
548         }
549         else
550         {
551                 g_weaponarena = 1;
552                 t = tokenize_console(s);
553                 g_weaponarena_list = "";
554                 for (i = 0; i < t; ++i)
555                 {
556                         s = argv(i);
557                         FOREACH(Weapons, it != WEP_Null, LAMBDA(
558                                 if(it.netname == s)
559                                 {
560                                         g_weaponarena_weapons |= (it.m_wepset);
561                                         g_weaponarena_list = strcat(g_weaponarena_list, it.m_name, " & ");
562                                         break;
563                                 }
564                         ));
565                 }
566                 g_weaponarena_list = strzone(substring(g_weaponarena_list, 0, strlen(g_weaponarena_list) - 3));
567         }
568
569         if(g_weaponarena)
570                 g_weaponarena_random = cvar("g_weaponarena_random");
571         else
572                 g_weaponarena_random = 0;
573         g_weaponarena_random_with_blaster = cvar("g_weaponarena_random_with_blaster");
574
575         if (g_weaponarena)
576         {
577                 g_weapon_stay = 0; // incompatible
578                 start_weapons = g_weaponarena_weapons;
579                 start_items |= IT_UNLIMITED_AMMO;
580         }
581         else
582         {
583                 FOREACH(Weapons, it != WEP_Null, LAMBDA(
584                         int w = want_weapon(it, false);
585                         WepSet s = it.m_wepset;
586                         if(w & 1)
587                                 start_weapons |= s;
588                         if(w & 2)
589                                 start_weapons_default |= s;
590                         if(w & 4)
591                                 start_weapons_defaultmask |= s;
592                 ));
593         }
594
595         if(!cvar("g_use_ammunition"))
596                 start_items |= IT_UNLIMITED_AMMO;
597
598         if(start_items & IT_UNLIMITED_WEAPON_AMMO)
599         {
600                 start_ammo_shells = 999;
601                 start_ammo_nails = 999;
602                 start_ammo_rockets = 999;
603                 start_ammo_cells = 999;
604                 start_ammo_plasma = 999;
605                 start_ammo_fuel = 999;
606         }
607         else
608         {
609                 start_ammo_shells = cvar("g_start_ammo_shells");
610                 start_ammo_nails = cvar("g_start_ammo_nails");
611                 start_ammo_rockets = cvar("g_start_ammo_rockets");
612                 start_ammo_cells = cvar("g_start_ammo_cells");
613                 start_ammo_plasma = cvar("g_start_ammo_plasma");
614                 start_ammo_fuel = cvar("g_start_ammo_fuel");
615         }
616
617         if (warmup_stage)
618         {
619                 warmup_start_ammo_shells = start_ammo_shells;
620                 warmup_start_ammo_nails = start_ammo_nails;
621                 warmup_start_ammo_rockets = start_ammo_rockets;
622                 warmup_start_ammo_cells = start_ammo_cells;
623                 warmup_start_ammo_plasma = start_ammo_plasma;
624                 warmup_start_ammo_fuel = start_ammo_fuel;
625                 warmup_start_health = start_health;
626                 warmup_start_armorvalue = start_armorvalue;
627                 warmup_start_weapons = start_weapons;
628                 warmup_start_weapons_default = start_weapons_default;
629                 warmup_start_weapons_defaultmask = start_weapons_defaultmask;
630
631                 if (!g_weaponarena && !g_ca && !g_freezetag)
632                 {
633                         warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
634                         warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
635                         warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
636                         warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
637                         warmup_start_ammo_plasma = cvar("g_warmup_start_ammo_plasma");
638                         warmup_start_ammo_fuel = cvar("g_warmup_start_ammo_fuel");
639                         warmup_start_health = cvar("g_warmup_start_health");
640                         warmup_start_armorvalue = cvar("g_warmup_start_armor");
641                         warmup_start_weapons = '0 0 0';
642                         warmup_start_weapons_default = '0 0 0';
643                         warmup_start_weapons_defaultmask = '0 0 0';
644                         FOREACH(Weapons, it != WEP_Null, LAMBDA(
645                                 int w = want_weapon(it, g_warmup_allguns);
646                                 WepSet s = (it.m_wepset);
647                                 if(w & 1)
648                                         warmup_start_weapons |= s;
649                                 if(w & 2)
650                                         warmup_start_weapons_default |= s;
651                                 if(w & 4)
652                                         warmup_start_weapons_defaultmask |= s;
653                         ));
654                 }
655         }
656
657         if (g_jetpack)
658                 start_items |= ITEM_Jetpack.m_itemid;
659
660         MUTATOR_CALLHOOK(SetStartItems);
661
662         if (start_items & ITEM_Jetpack.m_itemid)
663         {
664                 start_items |= ITEM_JetpackRegen.m_itemid;
665                 start_ammo_fuel = max(start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
666                 warmup_start_ammo_fuel = max(warmup_start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
667         }
668
669         WepSet precache_weapons = start_weapons;
670         if (g_warmup_allguns != 1)
671                 precache_weapons |= warmup_start_weapons;
672         FOREACH(Weapons, it != WEP_Null, LAMBDA(
673                 if(precache_weapons & (it.m_wepset))
674                         it.wr_init(it);
675         ));
676
677         start_ammo_shells = max(0, start_ammo_shells);
678         start_ammo_nails = max(0, start_ammo_nails);
679         start_ammo_rockets = max(0, start_ammo_rockets);
680         start_ammo_cells = max(0, start_ammo_cells);
681         start_ammo_plasma = max(0, start_ammo_plasma);
682         start_ammo_fuel = max(0, start_ammo_fuel);
683
684         warmup_start_ammo_shells = max(0, warmup_start_ammo_shells);
685         warmup_start_ammo_nails = max(0, warmup_start_ammo_nails);
686         warmup_start_ammo_rockets = max(0, warmup_start_ammo_rockets);
687         warmup_start_ammo_cells = max(0, warmup_start_ammo_cells);
688         warmup_start_ammo_plasma = max(0, warmup_start_ammo_plasma);
689         warmup_start_ammo_fuel = max(0, warmup_start_ammo_fuel);
690 }
691
692 void precache_playermodel(string m)
693 {
694         float globhandle, i, n;
695         string f;
696
697         if(substring(m, -9,5) == "_lod1")
698                 return;
699         if(substring(m, -9,5) == "_lod2")
700                 return;
701         precache_model(m);
702         f = strcat(substring(m, 0, -5), "_lod1", substring(m, -4, -1));
703         if(fexists(f))
704                 precache_model(f);
705         f = strcat(substring(m, 0, -5), "_lod2", substring(m, -4, -1));
706         if(fexists(f))
707                 precache_model(f);
708
709         globhandle = search_begin(strcat(m, "_*.sounds"), true, false);
710         if (globhandle < 0)
711                 return;
712         n = search_getsize(globhandle);
713         for (i = 0; i < n; ++i)
714         {
715                 //print(search_getfilename(globhandle, i), "\n");
716                 f = search_getfilename(globhandle, i);
717                 PrecachePlayerSounds(f);
718         }
719         search_end(globhandle);
720 }
721 void precache_all_playermodels(string pattern)
722 {
723         int globhandle = search_begin(pattern, true, false);
724         if (globhandle < 0) return;
725         int n = search_getsize(globhandle);
726         for (int i = 0; i < n; ++i)
727         {
728                 string s = search_getfilename(globhandle, i);
729                 precache_playermodel(s);
730         }
731         search_end(globhandle);
732 }
733
734 void precache_playermodels(string s)
735 {
736         FOREACH_WORD(s, true, LAMBDA(precache_playermodel(it)));
737 }
738
739 void precache()
740 {SELFPARAM();
741     // gamemode related things
742
743     // Precache all player models if desired
744     if (autocvar_sv_precacheplayermodels)
745     {
746         PrecachePlayerSounds("sound/player/default.sounds");
747         precache_all_playermodels("models/player/*.zym");
748         precache_all_playermodels("models/player/*.dpm");
749         precache_all_playermodels("models/player/*.md3");
750         precache_all_playermodels("models/player/*.psk");
751         precache_all_playermodels("models/player/*.iqm");
752     }
753
754     if (autocvar_sv_defaultcharacter)
755     {
756                 precache_playermodels(autocvar_sv_defaultplayermodel_red);
757                 precache_playermodels(autocvar_sv_defaultplayermodel_blue);
758                 precache_playermodels(autocvar_sv_defaultplayermodel_yellow);
759                 precache_playermodels(autocvar_sv_defaultplayermodel_pink);
760                 precache_playermodels(autocvar_sv_defaultplayermodel);
761     }
762
763 #if 0
764     // Disabled this code because it simply does not work (e.g. ignores bgmvolume, overlaps with "cd loop" controlled tracks).
765
766     if (!self.noise && self.music) // quake 3 uses the music field
767         self.noise = self.music;
768
769     // plays music for the level if there is any
770     if (self.noise)
771     {
772         precache_sound (self.noise);
773         ambientsound ('0 0 0', self.noise, VOL_BASE, ATTEN_NONE);
774     }
775 #endif
776 }
777
778
779 void make_safe_for_remove(entity e)
780 {
781     if (e.initialize_entity)
782     {
783         entity ent, prev = world;
784         for (ent = initialize_entity_first; ent; )
785         {
786             if ((ent == e) || ((ent.classname == "initialize_entity") && (ent.enemy == e)))
787             {
788                 //print("make_safe_for_remove: getting rid of initializer ", etos(ent), "\n");
789                 // skip it in linked list
790                 if (prev)
791                 {
792                     prev.initialize_entity_next = ent.initialize_entity_next;
793                     ent = prev.initialize_entity_next;
794                 }
795                 else
796                 {
797                     initialize_entity_first = ent.initialize_entity_next;
798                     ent = initialize_entity_first;
799                 }
800             }
801             else
802             {
803                 prev = ent;
804                 ent = ent.initialize_entity_next;
805             }
806         }
807     }
808 }
809
810 void objerror(string s)
811 {SELFPARAM();
812     make_safe_for_remove(self);
813     builtin_objerror(s);
814 }
815
816 .float remove_except_protected_forbidden;
817 void remove_except_protected(entity e)
818 {
819         if(e.remove_except_protected_forbidden)
820                 error("not allowed to remove this at this point");
821         builtin_remove(e);
822 }
823
824 void remove_unsafely(entity e)
825 {
826     if(e.classname == "spike")
827         error("Removing spikes is forbidden (crylink bug), please report");
828     builtin_remove(e);
829 }
830
831 void remove_safely(entity e)
832 {
833     make_safe_for_remove(e);
834     builtin_remove(e);
835 }
836
837 void InitializeEntity(entity e, void() func, float order)
838 {
839     entity prev, cur;
840
841     if (!e || e.initialize_entity)
842     {
843         // make a proxy initializer entity
844         entity e_old = e;
845         e = new(initialize_entity);
846         e.enemy = e_old;
847     }
848
849     e.initialize_entity = func;
850     e.initialize_entity_order = order;
851
852     cur = initialize_entity_first;
853     prev = world;
854     for (;;)
855     {
856         if (!cur || cur.initialize_entity_order > order)
857         {
858             // insert between prev and cur
859             if (prev)
860                 prev.initialize_entity_next = e;
861             else
862                 initialize_entity_first = e;
863             e.initialize_entity_next = cur;
864             return;
865         }
866         prev = cur;
867         cur = cur.initialize_entity_next;
868     }
869 }
870 void InitializeEntitiesRun()
871 {SELFPARAM();
872     entity startoflist = initialize_entity_first;
873     initialize_entity_first = NULL;
874     remove = remove_except_protected;
875     for (entity e = startoflist; e; e = e.initialize_entity_next)
876     {
877                 e.remove_except_protected_forbidden = 1;
878     }
879     for (entity e = startoflist; e; )
880     {
881                 e.remove_except_protected_forbidden = 0;
882         e.initialize_entity_order = 0;
883         entity next = e.initialize_entity_next;
884         e.initialize_entity_next = NULL;
885         var void() func = e.initialize_entity;
886         e.initialize_entity = func_null;
887         if (e.classname == "initialize_entity")
888         {
889             entity wrappee = e.enemy;
890             builtin_remove(e);
891             e = wrappee;
892         }
893         //dprint("Delayed initialization: ", e.classname, "\n");
894         if (func)
895         {
896                 WITH(entity, self, e, func());
897         }
898         else
899         {
900             eprint(e);
901             backtrace(strcat("Null function in: ", e.classname, "\n"));
902         }
903         e = next;
904     }
905     remove = remove_unsafely;
906 }
907
908 .float(entity) isEliminated;
909 bool EliminatedPlayers_SendEntity(entity this, entity to, float sendflags)
910 {
911         float i, f, b;
912         entity e;
913         WriteHeader(MSG_ENTITY, ENT_CLIENT_ELIMINATEDPLAYERS);
914         WriteByte(MSG_ENTITY, sendflags);
915
916         if(sendflags & 1)
917         {
918                 for(i = 1; i <= maxclients; i += 8)
919                 {
920                         for(f = 0, e = edict_num(i), b = 1; b < 256; b *= 2, e = nextent(e))
921                         {
922                                 if(eliminatedPlayers.isEliminated(e))
923                                         f |= b;
924                         }
925                         WriteByte(MSG_ENTITY, f);
926                 }
927         }
928
929         return true;
930 }
931
932 void EliminatedPlayers_Init(float(entity) isEliminated_func)
933 {
934         if(eliminatedPlayers)
935         {
936                 backtrace("Can't spawn eliminatedPlayers again!");
937                 return;
938         }
939         Net_LinkEntity(eliminatedPlayers = spawn(), false, 0, EliminatedPlayers_SendEntity);
940         eliminatedPlayers.isEliminated = isEliminated_func;
941 }
942
943
944 void adaptor_think2touch()
945 {SELFPARAM();
946     entity o;
947     o = other;
948     other = world;
949     self.touch();
950     other = o;
951 }
952
953 void adaptor_think2use()
954 {SELFPARAM();
955     entity o, a;
956     o = other;
957     a = activator;
958     activator = world;
959     other = world;
960     self.use();
961     other = o;
962     activator = a;
963 }
964
965 void adaptor_think2use_hittype_splash() // for timed projectile detonation
966 {SELFPARAM();
967         if(!(IS_ONGROUND(self))) // if onground, we ARE touching something, but HITTYPE_SPLASH is to be networked if the damage causing projectile is not touching ANYTHING
968                 self.projectiledeathtype |= HITTYPE_SPLASH;
969         adaptor_think2use();
970 }
971
972 // deferred dropping
973 void DropToFloor_Handler()
974 {SELFPARAM();
975     builtin_droptofloor();
976     self.dropped_origin = self.origin;
977 }
978
979 void droptofloor()
980 {SELFPARAM();
981     InitializeEntity(self, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
982 }
983
984
985
986 float trace_hits_box_a0, trace_hits_box_a1;
987
988 float trace_hits_box_1d(float end, float thmi, float thma)
989 {
990     if (end == 0)
991     {
992         // just check if x is in range
993         if (0 < thmi)
994             return false;
995         if (0 > thma)
996             return false;
997     }
998     else
999     {
1000         // do the trace with respect to x
1001         // 0 -> end has to stay in thmi -> thma
1002         trace_hits_box_a0 = max(trace_hits_box_a0, min(thmi / end, thma / end));
1003         trace_hits_box_a1 = min(trace_hits_box_a1, max(thmi / end, thma / end));
1004         if (trace_hits_box_a0 > trace_hits_box_a1)
1005             return false;
1006     }
1007     return true;
1008 }
1009
1010 float trace_hits_box(vector start, vector end, vector thmi, vector thma)
1011 {
1012     end -= start;
1013     thmi -= start;
1014     thma -= start;
1015     // now it is a trace from 0 to end
1016
1017     trace_hits_box_a0 = 0;
1018     trace_hits_box_a1 = 1;
1019
1020     if (!trace_hits_box_1d(end.x, thmi.x, thma.x))
1021         return false;
1022     if (!trace_hits_box_1d(end.y, thmi.y, thma.y))
1023         return false;
1024     if (!trace_hits_box_1d(end.z, thmi.z, thma.z))
1025         return false;
1026
1027     return true;
1028 }
1029
1030 float tracebox_hits_box(vector start, vector mi, vector ma, vector end, vector thmi, vector thma)
1031 {
1032     return trace_hits_box(start, end, thmi - ma, thma - mi);
1033 }
1034
1035 float SUB_NoImpactCheck()
1036 {SELFPARAM();
1037         // zero hitcontents = this is not the real impact, but either the
1038         // mirror-impact of something hitting the projectile instead of the
1039         // projectile hitting the something, or a touchareagrid one. Neither of
1040         // these stop the projectile from moving, so...
1041         if(trace_dphitcontents == 0)
1042         {
1043                 //dprint("A hit happened with zero hit contents... DEBUG THIS, this should never happen for projectiles! Projectile will self-destruct.\n");
1044                 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", etof(self), self.classname, vtos(self.origin));
1045                 checkclient();
1046         }
1047     if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1048         return 1;
1049     if (other == world && self.size != '0 0 0')
1050     {
1051         vector tic;
1052         tic = self.velocity * sys_frametime;
1053         tic = tic + normalize(tic) * vlen(self.maxs - self.mins);
1054         traceline(self.origin - tic, self.origin + tic, MOVE_NORMAL, self);
1055         if (trace_fraction >= 1)
1056         {
1057             LOG_TRACE("Odd... did not hit...?\n");
1058         }
1059         else if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1060         {
1061             LOG_TRACE("Detected and prevented the sky-grapple bug.\n");
1062             return 1;
1063         }
1064     }
1065
1066     return 0;
1067 }
1068
1069 #define SUB_OwnerCheck() (other && (other == self.owner))
1070
1071 void W_Crylink_Dequeue(entity e);
1072 float WarpZone_Projectile_Touch_ImpactFilter_Callback()
1073 {SELFPARAM();
1074         if(SUB_OwnerCheck())
1075                 return true;
1076         if(SUB_NoImpactCheck())
1077         {
1078                 if(self.classname == "nade")
1079                         return false; // no checks here
1080                 else if(self.classname == "grapplinghook")
1081                         RemoveGrapplingHook(self.realowner);
1082                 else if(self.classname == "spike")
1083                 {
1084                         W_Crylink_Dequeue(self);
1085                         remove(self);
1086                 }
1087                 else
1088                         remove(self);
1089                 return true;
1090         }
1091         if(trace_ent && trace_ent.solid > SOLID_TRIGGER)
1092                 UpdateCSQCProjectile(self);
1093         return false;
1094 }
1095
1096 /** engine callback */
1097 void URI_Get_Callback(float id, float status, string data)
1098 {
1099         if(url_URI_Get_Callback(id, status, data))
1100         {
1101                 // handled
1102         }
1103         else if (id == URI_GET_DISCARD)
1104         {
1105                 // discard
1106         }
1107         else if (id >= URI_GET_CURL && id <= URI_GET_CURL_END)
1108         {
1109                 // sv_cmd curl
1110                 Curl_URI_Get_Callback(id, status, data);
1111         }
1112         else if (id >= URI_GET_IPBAN && id <= URI_GET_IPBAN_END)
1113         {
1114                 // online ban list
1115                 OnlineBanList_URI_Get_Callback(id, status, data);
1116         }
1117         else if (MUTATOR_CALLHOOK(URI_GetCallback, id, status, data))
1118         {
1119                 // handled by a mutator
1120         }
1121         else
1122         {
1123                 LOG_INFO("Received HTTP request data for an invalid id ", ftos(id), ".\n");
1124         }
1125 }
1126
1127 string uid2name(string myuid) {
1128         string s;
1129         s = db_get(ServerProgsDB, strcat("/uid2name/", myuid));
1130
1131         // FIXME remove this later after 0.6 release
1132         // convert old style broken records to correct style
1133         if(s == "")
1134         {
1135                 s = db_get(ServerProgsDB, strcat("uid2name", myuid));
1136                 if(s != "")
1137                 {
1138                         db_put(ServerProgsDB, strcat("/uid2name/", myuid), s);
1139                         db_remove(ServerProgsDB, strcat("uid2name", myuid));
1140                 }
1141         }
1142
1143         if(s == "")
1144                 s = "^1Unregistered Player";
1145         return s;
1146 }
1147
1148 float MoveToRandomLocationWithinBounds(entity e, vector boundmin, vector boundmax, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1149 {
1150     float m, i;
1151     vector start, org, delta, end, enddown, mstart;
1152     entity sp;
1153
1154     m = e.dphitcontentsmask;
1155     e.dphitcontentsmask = goodcontents | badcontents;
1156
1157     org = boundmin;
1158     delta = boundmax - boundmin;
1159
1160     start = end = org;
1161
1162     for (i = 0; i < attempts; ++i)
1163     {
1164         start.x = org.x + random() * delta.x;
1165         start.y = org.y + random() * delta.y;
1166         start.z = org.z + random() * delta.z;
1167
1168         // rule 1: start inside world bounds, and outside
1169         // solid, and don't start from somewhere where you can
1170         // fall down to evil
1171         tracebox(start, e.mins, e.maxs, start - '0 0 1' * delta.z, MOVE_NORMAL, e);
1172         if (trace_fraction >= 1)
1173             continue;
1174         if (trace_startsolid)
1175             continue;
1176         if (trace_dphitcontents & badcontents)
1177             continue;
1178         if (trace_dphitq3surfaceflags & badsurfaceflags)
1179             continue;
1180
1181         // rule 2: if we are too high, lower the point
1182         if (trace_fraction * delta.z > maxaboveground)
1183             start = trace_endpos + '0 0 1' * maxaboveground;
1184         enddown = trace_endpos;
1185
1186         // rule 3: make sure we aren't outside the map. This only works
1187         // for somewhat well formed maps. A good rule of thumb is that
1188         // the map should have a convex outside hull.
1189         // these can be traceLINES as we already verified the starting box
1190         mstart = start + 0.5 * (e.mins + e.maxs);
1191         traceline(mstart, mstart + '1 0 0' * delta.x, MOVE_NORMAL, e);
1192         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1193             continue;
1194         traceline(mstart, mstart - '1 0 0' * delta.x, MOVE_NORMAL, e);
1195         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1196             continue;
1197         traceline(mstart, mstart + '0 1 0' * delta.y, MOVE_NORMAL, e);
1198         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1199             continue;
1200         traceline(mstart, mstart - '0 1 0' * delta.y, MOVE_NORMAL, e);
1201         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1202             continue;
1203         traceline(mstart, mstart + '0 0 1' * delta.z, MOVE_NORMAL, e);
1204         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1205             continue;
1206
1207         // rule 4: we must "see" some spawnpoint or item
1208         for(sp = world; (sp = find(sp, classname, "info_player_deathmatch")); )
1209                 if(checkpvs(mstart, sp))
1210                         if((traceline(mstart, sp.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1211                                 break;
1212         if(!sp)
1213         {
1214                 for(sp = world; (sp = findflags(sp, flags, FL_ITEM)); )
1215                         if(checkpvs(mstart, sp))
1216                                 if((traceline(mstart, sp.origin + (sp.mins + sp.maxs) * 0.5, MOVE_NORMAL, e), trace_fraction) >= 1)
1217                                         break;
1218                 if(!sp)
1219                         continue;
1220         }
1221
1222         // find a random vector to "look at"
1223         end.x = org.x + random() * delta.x;
1224         end.y = org.y + random() * delta.y;
1225         end.z = org.z + random() * delta.z;
1226         end = start + normalize(end - start) * vlen(delta);
1227
1228         // rule 4: start TO end must not be too short
1229         tracebox(start, e.mins, e.maxs, end, MOVE_NORMAL, e);
1230         if (trace_startsolid)
1231             continue;
1232         if (trace_fraction < minviewdistance / vlen(delta))
1233             continue;
1234
1235         // rule 5: don't want to look at sky
1236         if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY)
1237             continue;
1238
1239         // rule 6: we must not end up in trigger_hurt
1240         if (tracebox_hits_trigger_hurt(start, e.mins, e.maxs, enddown))
1241             continue;
1242
1243         break;
1244     }
1245
1246     e.dphitcontentsmask = m;
1247
1248     if (i < attempts)
1249     {
1250         setorigin(e, start);
1251         e.angles = vectoangles(end - start);
1252         LOG_TRACE("Needed ", ftos(i + 1), " attempts\n");
1253         return true;
1254     }
1255     else
1256         return false;
1257 }
1258
1259 float MoveToRandomMapLocation(entity e, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1260 {
1261         return MoveToRandomLocationWithinBounds(e, world.mins, world.maxs, goodcontents, badcontents, badsurfaceflags, attempts, maxaboveground, minviewdistance);
1262 }
1263
1264 void write_recordmarker(entity pl, float tstart, float dt)
1265 {
1266     GameLogEcho(strcat(":recordset:", ftos(pl.playerid), ":", ftos(dt)));
1267
1268     // also write a marker into demo files for demotc-race-record-extractor to find
1269     stuffcmd(pl,
1270              strcat(
1271                  strcat("//", strconv(2, 0, 0, GetGametype()), " RECORD SET ", TIME_ENCODED_TOSTRING(TIME_ENCODE(dt))),
1272                  " ", ftos(tstart), " ", ftos(dt), "\n"));
1273 }
1274
1275 void attach_sameorigin(entity e, entity to, string tag)
1276 {
1277     vector org, t_forward, t_left, t_up, e_forward, e_up;
1278     float tagscale;
1279
1280     org = e.origin - gettaginfo(to, gettagindex(to, tag));
1281     tagscale = pow(vlen(v_forward), -2); // undo a scale on the tag
1282     t_forward = v_forward * tagscale;
1283     t_left = v_right * -tagscale;
1284     t_up = v_up * tagscale;
1285
1286     e.origin_x = org * t_forward;
1287     e.origin_y = org * t_left;
1288     e.origin_z = org * t_up;
1289
1290     // current forward and up directions
1291     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1292                 e.angles = AnglesTransform_FromVAngles(e.angles);
1293         else
1294                 e.angles = AnglesTransform_FromAngles(e.angles);
1295     fixedmakevectors(e.angles);
1296
1297     // untransform forward, up!
1298     e_forward.x = v_forward * t_forward;
1299     e_forward.y = v_forward * t_left;
1300     e_forward.z = v_forward * t_up;
1301     e_up.x = v_up * t_forward;
1302     e_up.y = v_up * t_left;
1303     e_up.z = v_up * t_up;
1304
1305     e.angles = fixedvectoangles2(e_forward, e_up);
1306     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1307                 e.angles = AnglesTransform_ToVAngles(e.angles);
1308         else
1309                 e.angles = AnglesTransform_ToAngles(e.angles);
1310
1311     setattachment(e, to, tag);
1312     setorigin(e, e.origin);
1313 }
1314
1315 void detach_sameorigin(entity e)
1316 {
1317     vector org;
1318     org = gettaginfo(e, 0);
1319     e.angles = fixedvectoangles2(v_forward, v_up);
1320     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1321                 e.angles = AnglesTransform_ToVAngles(e.angles);
1322         else
1323                 e.angles = AnglesTransform_ToAngles(e.angles);
1324     setorigin(e, org);
1325     setattachment(e, world, "");
1326     setorigin(e, e.origin);
1327 }
1328
1329 void follow_sameorigin(entity e, entity to)
1330 {
1331     e.movetype = MOVETYPE_FOLLOW; // make the hole follow
1332     e.aiment = to; // make the hole follow bmodel
1333     e.punchangle = to.angles; // the original angles of bmodel
1334     e.view_ofs = e.origin - to.origin; // relative origin
1335     e.v_angle = e.angles - to.angles; // relative angles
1336 }
1337
1338 void unfollow_sameorigin(entity e)
1339 {
1340     e.movetype = MOVETYPE_NONE;
1341 }
1342
1343 entity gettaginfo_relative_ent;
1344 vector gettaginfo_relative(entity e, float tag)
1345 {
1346     if (!gettaginfo_relative_ent)
1347     {
1348         gettaginfo_relative_ent = spawn();
1349         gettaginfo_relative_ent.effects = EF_NODRAW;
1350     }
1351     gettaginfo_relative_ent.model = e.model;
1352     gettaginfo_relative_ent.modelindex = e.modelindex;
1353     gettaginfo_relative_ent.frame = e.frame;
1354     return gettaginfo(gettaginfo_relative_ent, tag);
1355 }
1356
1357 .string aiment_classname;
1358 .float aiment_deadflag;
1359 void SetMovetypeFollow(entity ent, entity e)
1360 {
1361         // FIXME this may not be warpzone aware
1362         ent.movetype = MOVETYPE_FOLLOW; // make the hole follow
1363         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.
1364         ent.aiment = e; // make the hole follow bmodel
1365         ent.punchangle = e.angles; // the original angles of bmodel
1366         ent.view_ofs = ent.origin - e.origin; // relative origin
1367         ent.v_angle = ent.angles - e.angles; // relative angles
1368         ent.aiment_classname = strzone(e.classname);
1369         ent.aiment_deadflag = e.deadflag;
1370 }
1371 void UnsetMovetypeFollow(entity ent)
1372 {
1373         ent.movetype = MOVETYPE_FLY;
1374         PROJECTILE_MAKETRIGGER(ent);
1375         ent.aiment = world;
1376 }
1377 float LostMovetypeFollow(entity ent)
1378 {
1379 /*
1380         if(ent.movetype != MOVETYPE_FOLLOW)
1381                 if(ent.aiment)
1382                         error("???");
1383 */
1384         if(ent.aiment)
1385         {
1386                 if(ent.aiment.classname != ent.aiment_classname)
1387                         return 1;
1388                 if(ent.aiment.deadflag != ent.aiment_deadflag)
1389                         return 1;
1390         }
1391         return 0;
1392 }
1393
1394 float isPushable(entity e)
1395 {
1396         if(e.pushable)
1397                 return true;
1398         if(IS_VEHICLE(e))
1399                 return false;
1400         if(e.iscreature)
1401                 return true;
1402         switch(e.classname)
1403         {
1404                 case "body":
1405                 case "droppedweapon":
1406                 case "keepawayball":
1407                 case "nexball_basketball":
1408                 case "nexball_football":
1409                         return true;
1410                 case "bullet": // antilagged bullets can't hit this either
1411                         return false;
1412         }
1413         if (e.projectiledeathtype)
1414                 return true;
1415         return false;
1416 }