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