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