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