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