]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/miscfunctions.qc
Merge branch 'Mario/csqc_refdef' into 'master'
[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         // initialize starting values for players
628         start_weapons = '0 0 0';
629         start_weapons_default = '0 0 0';
630         start_weapons_defaultmask = '0 0 0';
631         start_items = 0;
632         start_ammo_shells = 0;
633         start_ammo_nails = 0;
634         start_ammo_rockets = 0;
635         start_ammo_cells = 0;
636         start_ammo_plasma = 0;
637         if (random_start_ammo == NULL)
638         {
639                 random_start_ammo = spawn();
640         }
641         start_health = cvar("g_balance_health_start");
642         start_armorvalue = cvar("g_balance_armor_start");
643
644         g_weaponarena = 0;
645         g_weaponarena_weapons = '0 0 0';
646
647         string s = cvar_string("g_weaponarena");
648
649         MUTATOR_CALLHOOK(SetWeaponArena, s);
650         s = M_ARGV(0, string);
651
652         if (s == "0" || s == "")
653         {
654                 // no arena
655         }
656         else if (s == "off")
657         {
658                 // forcibly turn off weaponarena
659         }
660         else if (s == "all" || s == "1")
661         {
662                 g_weaponarena = 1;
663                 g_weaponarena_list = "All Weapons";
664                 g_weaponarena_weapons = weapons_all();
665         }
666         else if (s == "devall")
667         {
668                 g_weaponarena = 1;
669                 g_weaponarena_list = "Dev All Weapons";
670                 g_weaponarena_weapons = weapons_devall();
671         }
672         else if (s == "most")
673         {
674                 g_weaponarena = 1;
675                 g_weaponarena_list = "Most Weapons";
676                 g_weaponarena_weapons = weapons_most();
677         }
678         else if (s == "all_available")
679         {
680                 g_weaponarena = 1;
681                 g_weaponarena_list = "All Available Weapons";
682
683                 // this needs to run after weaponsInMapAll is initialized
684                 InitializeEntity(NULL, weaponarena_available_all_update, INITPRIO_FINDTARGET);
685         }
686         else if (s == "devall_available")
687         {
688                 g_weaponarena = 1;
689                 g_weaponarena_list = "Dev All Available Weapons";
690
691                 // this needs to run after weaponsInMapAll is initialized
692                 InitializeEntity(NULL, weaponarena_available_devall_update, INITPRIO_FINDTARGET);
693         }
694         else if (s == "most_available")
695         {
696                 g_weaponarena = 1;
697                 g_weaponarena_list = "Most Available Weapons";
698
699                 // this needs to run after weaponsInMapAll is initialized
700                 InitializeEntity(NULL, weaponarena_available_most_update, INITPRIO_FINDTARGET);
701         }
702         else if (s == "none")
703         {
704                 g_weaponarena = 1;
705                 g_weaponarena_list = "No Weapons";
706         }
707         else
708         {
709                 g_weaponarena = 1;
710                 float t = tokenize_console(s);
711                 g_weaponarena_list = "";
712                 for (int j = 0; j < t; ++j)
713                 {
714                         s = argv(j);
715                         Weapon wep = Weapons_fromstr(s);
716                         if(wep != WEP_Null)
717                         {
718                                 g_weaponarena_weapons |= (wep.m_wepset);
719                                 g_weaponarena_list = strcat(g_weaponarena_list, wep.m_name, " & ");
720                         }
721                 }
722                 g_weaponarena_list = strzone(substring(g_weaponarena_list, 0, strlen(g_weaponarena_list) - 3));
723         }
724
725         if (g_weaponarena)
726         {
727                 g_weapon_stay = 0; // incompatible
728                 start_weapons = g_weaponarena_weapons;
729                 start_items |= IT_UNLIMITED_AMMO | IT_UNLIMITED_SUPERWEAPONS;
730         }
731         else
732         {
733                 FOREACH(Weapons, it != WEP_Null, {
734                         int w = want_weapon(it, false);
735                         WepSet s = it.m_wepset;
736                         if(w & 1)
737                                 start_weapons |= s;
738                         if(w & 2)
739                                 start_weapons_default |= s;
740                         if(w & 4)
741                                 start_weapons_defaultmask |= s;
742                 });
743         }
744
745         if(cvar("g_balance_superweapons_time") < 0)
746                 start_items |= IT_UNLIMITED_SUPERWEAPONS;
747
748         if(!cvar("g_use_ammunition"))
749                 start_items |= IT_UNLIMITED_AMMO;
750
751         if(start_items & IT_UNLIMITED_AMMO)
752         {
753                 start_ammo_shells = 999;
754                 start_ammo_nails = 999;
755                 start_ammo_rockets = 999;
756                 start_ammo_cells = 999;
757                 start_ammo_plasma = 999;
758                 start_ammo_fuel = 999;
759         }
760         else
761         {
762                 start_ammo_shells = cvar("g_start_ammo_shells");
763                 start_ammo_nails = cvar("g_start_ammo_nails");
764                 start_ammo_rockets = cvar("g_start_ammo_rockets");
765                 start_ammo_cells = cvar("g_start_ammo_cells");
766                 start_ammo_plasma = cvar("g_start_ammo_plasma");
767                 start_ammo_fuel = cvar("g_start_ammo_fuel");
768                 random_start_weapons_count = cvar("g_random_start_weapons_count");
769                 SetResource(random_start_ammo, RES_SHELLS, cvar("g_random_start_shells"));
770                 SetResource(random_start_ammo, RES_BULLETS, cvar("g_random_start_bullets"));
771                 SetResource(random_start_ammo, RES_ROCKETS,cvar("g_random_start_rockets"));
772                 SetResource(random_start_ammo, RES_CELLS, cvar("g_random_start_cells"));
773                 SetResource(random_start_ammo, RES_PLASMA, cvar("g_random_start_plasma"));
774         }
775
776         warmup_start_ammo_shells = start_ammo_shells;
777         warmup_start_ammo_nails = start_ammo_nails;
778         warmup_start_ammo_rockets = start_ammo_rockets;
779         warmup_start_ammo_cells = start_ammo_cells;
780         warmup_start_ammo_plasma = start_ammo_plasma;
781         warmup_start_ammo_fuel = start_ammo_fuel;
782         warmup_start_health = start_health;
783         warmup_start_armorvalue = start_armorvalue;
784         warmup_start_weapons = start_weapons;
785         warmup_start_weapons_default = start_weapons_default;
786         warmup_start_weapons_defaultmask = start_weapons_defaultmask;
787
788         if (!g_weaponarena)
789         {
790                 warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
791                 warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
792                 warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
793                 warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
794                 warmup_start_ammo_plasma = cvar("g_warmup_start_ammo_plasma");
795                 warmup_start_ammo_fuel = cvar("g_warmup_start_ammo_fuel");
796                 warmup_start_health = cvar("g_warmup_start_health");
797                 warmup_start_armorvalue = cvar("g_warmup_start_armor");
798                 warmup_start_weapons = '0 0 0';
799                 warmup_start_weapons_default = '0 0 0';
800                 warmup_start_weapons_defaultmask = '0 0 0';
801                 FOREACH(Weapons, it != WEP_Null, {
802                         int w = want_weapon(it, g_warmup_allguns);
803                         WepSet s = it.m_wepset;
804                         if(w & 1)
805                                 warmup_start_weapons |= s;
806                         if(w & 2)
807                                 warmup_start_weapons_default |= s;
808                         if(w & 4)
809                                 warmup_start_weapons_defaultmask |= s;
810                 });
811         }
812
813         if (g_jetpack)
814                 start_items |= ITEM_Jetpack.m_itemid;
815
816         MUTATOR_CALLHOOK(SetStartItems);
817
818         if (start_items & ITEM_Jetpack.m_itemid)
819         {
820                 start_items |= ITEM_JetpackRegen.m_itemid;
821                 start_ammo_fuel = max(start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
822                 warmup_start_ammo_fuel = max(warmup_start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
823         }
824
825         start_ammo_shells = max(0, start_ammo_shells);
826         start_ammo_nails = max(0, start_ammo_nails);
827         start_ammo_rockets = max(0, start_ammo_rockets);
828         start_ammo_cells = max(0, start_ammo_cells);
829         start_ammo_plasma = max(0, start_ammo_plasma);
830         start_ammo_fuel = max(0, start_ammo_fuel);
831         SetResource(random_start_ammo, RES_SHELLS,
832                 max(0, GetResource(random_start_ammo, RES_SHELLS)));
833         SetResource(random_start_ammo, RES_BULLETS,
834                 max(0, GetResource(random_start_ammo, RES_BULLETS)));
835         SetResource(random_start_ammo, RES_ROCKETS,
836                 max(0, GetResource(random_start_ammo, RES_ROCKETS)));
837         SetResource(random_start_ammo, RES_CELLS,
838                 max(0, GetResource(random_start_ammo, RES_CELLS)));
839         SetResource(random_start_ammo, RES_PLASMA,
840                 max(0, GetResource(random_start_ammo, RES_PLASMA)));
841
842         warmup_start_ammo_shells = max(0, warmup_start_ammo_shells);
843         warmup_start_ammo_nails = max(0, warmup_start_ammo_nails);
844         warmup_start_ammo_rockets = max(0, warmup_start_ammo_rockets);
845         warmup_start_ammo_cells = max(0, warmup_start_ammo_cells);
846         warmup_start_ammo_plasma = max(0, warmup_start_ammo_plasma);
847         warmup_start_ammo_fuel = max(0, warmup_start_ammo_fuel);
848 }
849
850 void precache_playermodel(string m)
851 {
852         float globhandle, i, n;
853         string f;
854
855         if(substring(m, -9, 5) == "_lod1")
856                 return;
857         if(substring(m, -9, 5) == "_lod2")
858                 return;
859         precache_model(m);
860         f = strcat(substring(m, 0, -5), "_lod1", substring(m, -4, -1));
861         if(fexists(f))
862                 precache_model(f);
863         f = strcat(substring(m, 0, -5), "_lod2", substring(m, -4, -1));
864         if(fexists(f))
865                 precache_model(f);
866
867         globhandle = search_begin(strcat(m, "_*.sounds"), true, false);
868         if (globhandle < 0)
869                 return;
870         n = search_getsize(globhandle);
871         for (i = 0; i < n; ++i)
872         {
873                 //print(search_getfilename(globhandle, i), "\n");
874                 f = search_getfilename(globhandle, i);
875                 PrecachePlayerSounds(f);
876         }
877         search_end(globhandle);
878 }
879 void precache_all_playermodels(string pattern)
880 {
881         int globhandle = search_begin(pattern, true, false);
882         if (globhandle < 0) return;
883         int n = search_getsize(globhandle);
884         for (int i = 0; i < n; ++i)
885         {
886                 string s = search_getfilename(globhandle, i);
887                 precache_playermodel(s);
888         }
889         search_end(globhandle);
890 }
891
892 void precache_playermodels(string s)
893 {
894         FOREACH_WORD(s, true, { precache_playermodel(it); });
895 }
896
897 void precache()
898 {
899     // gamemode related things
900
901     // Precache all player models if desired
902     if (autocvar_sv_precacheplayermodels)
903     {
904         PrecachePlayerSounds("sound/player/default.sounds");
905         precache_all_playermodels("models/player/*.zym");
906         precache_all_playermodels("models/player/*.dpm");
907         precache_all_playermodels("models/player/*.md3");
908         precache_all_playermodels("models/player/*.psk");
909         precache_all_playermodels("models/player/*.iqm");
910     }
911
912     if (autocvar_sv_defaultcharacter)
913     {
914                 precache_playermodels(autocvar_sv_defaultplayermodel_red);
915                 precache_playermodels(autocvar_sv_defaultplayermodel_blue);
916                 precache_playermodels(autocvar_sv_defaultplayermodel_yellow);
917                 precache_playermodels(autocvar_sv_defaultplayermodel_pink);
918                 precache_playermodels(autocvar_sv_defaultplayermodel);
919     }
920
921 #if 0
922     // Disabled this code because it simply does not work (e.g. ignores bgmvolume, overlaps with "cd loop" controlled tracks).
923
924     if (!this.noise && this.music) // quake 3 uses the music field
925         this.noise = this.music;
926
927     // plays music for the level if there is any
928     if (this.noise)
929     {
930         precache_sound (this.noise);
931         ambientsound ('0 0 0', this.noise, VOL_BASE, ATTEN_NONE);
932     }
933 #endif
934 }
935
936
937 void make_safe_for_remove(entity e)
938 {
939     if (e.initialize_entity)
940     {
941         entity ent, prev = NULL;
942         for (ent = initialize_entity_first; ent; )
943         {
944             if ((ent == e) || ((ent.classname == "initialize_entity") && (ent.enemy == e)))
945             {
946                 //print("make_safe_for_remove: getting rid of initializer ", etos(ent), "\n");
947                 // skip it in linked list
948                 if (prev)
949                 {
950                     prev.initialize_entity_next = ent.initialize_entity_next;
951                     ent = prev.initialize_entity_next;
952                 }
953                 else
954                 {
955                     initialize_entity_first = ent.initialize_entity_next;
956                     ent = initialize_entity_first;
957                 }
958             }
959             else
960             {
961                 prev = ent;
962                 ent = ent.initialize_entity_next;
963             }
964         }
965     }
966 }
967
968 .float remove_except_protected_forbidden;
969 void remove_except_protected(entity e)
970 {
971         if(e.remove_except_protected_forbidden)
972                 error("not allowed to remove this at this point");
973         builtin_remove(e);
974 }
975
976 void remove_unsafely(entity e)
977 {
978     if(e.classname == "spike")
979         error("Removing spikes is forbidden (crylink bug), please report");
980     builtin_remove(e);
981 }
982
983 void remove_safely(entity e)
984 {
985     make_safe_for_remove(e);
986     builtin_remove(e);
987 }
988
989 void InitializeEntity(entity e, void(entity this) func, int order)
990 {
991     entity prev, cur;
992
993     if (!e || e.initialize_entity)
994     {
995         // make a proxy initializer entity
996         entity e_old = e;
997         e = new(initialize_entity);
998         e.enemy = e_old;
999     }
1000
1001     e.initialize_entity = func;
1002     e.initialize_entity_order = order;
1003
1004     cur = initialize_entity_first;
1005     prev = NULL;
1006     for (;;)
1007     {
1008         if (!cur || cur.initialize_entity_order > order)
1009         {
1010             // insert between prev and cur
1011             if (prev)
1012                 prev.initialize_entity_next = e;
1013             else
1014                 initialize_entity_first = e;
1015             e.initialize_entity_next = cur;
1016             return;
1017         }
1018         prev = cur;
1019         cur = cur.initialize_entity_next;
1020     }
1021 }
1022 void InitializeEntitiesRun()
1023 {
1024     entity startoflist = initialize_entity_first;
1025     initialize_entity_first = NULL;
1026     delete_fn = remove_except_protected;
1027     for (entity e = startoflist; e; e = e.initialize_entity_next)
1028     {
1029                 e.remove_except_protected_forbidden = 1;
1030     }
1031     for (entity e = startoflist; e; )
1032     {
1033                 e.remove_except_protected_forbidden = 0;
1034         e.initialize_entity_order = 0;
1035         entity next = e.initialize_entity_next;
1036         e.initialize_entity_next = NULL;
1037         var void(entity this) func = e.initialize_entity;
1038         e.initialize_entity = func_null;
1039         if (e.classname == "initialize_entity")
1040         {
1041             entity wrappee = e.enemy;
1042             builtin_remove(e);
1043             e = wrappee;
1044         }
1045         //dprint("Delayed initialization: ", e.classname, "\n");
1046         if (func)
1047         {
1048                 func(e);
1049         }
1050         else
1051         {
1052             eprint(e);
1053             backtrace(strcat("Null function in: ", e.classname, "\n"));
1054         }
1055         e = next;
1056     }
1057     delete_fn = remove_unsafely;
1058 }
1059
1060 .float(entity) isEliminated;
1061 bool EliminatedPlayers_SendEntity(entity this, entity to, float sendflags)
1062 {
1063         Stream out = MSG_ENTITY;
1064         WriteHeader(out, ENT_CLIENT_ELIMINATEDPLAYERS);
1065         serialize(byte, out, sendflags);
1066         if (sendflags & 1) {
1067                 for (int i = 1; i <= maxclients; i += 8) {
1068                         int f = 0;
1069                         entity e = edict_num(i);
1070                         for (int b = 0; b < 8; ++b, e = nextent(e)) {
1071                                 if (eliminatedPlayers.isEliminated(e)) {
1072                                         f |= BIT(b);
1073                                 }
1074                         }
1075                         serialize(byte, out, f);
1076                 }
1077         }
1078         return true;
1079 }
1080
1081 void EliminatedPlayers_Init(float(entity) isEliminated_func)
1082 {
1083         if(eliminatedPlayers)
1084         {
1085                 backtrace("Can't spawn eliminatedPlayers again!");
1086                 return;
1087         }
1088         Net_LinkEntity(eliminatedPlayers = spawn(), false, 0, EliminatedPlayers_SendEntity);
1089         eliminatedPlayers.isEliminated = isEliminated_func;
1090 }
1091
1092
1093
1094
1095 void adaptor_think2use_hittype_splash(entity this) // for timed projectile detonation
1096 {
1097         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
1098                 this.projectiledeathtype |= HITTYPE_SPLASH;
1099         adaptor_think2use(this);
1100 }
1101
1102 // deferred dropping
1103 void DropToFloor_Handler(entity this)
1104 {
1105     WITHSELF(this, builtin_droptofloor());
1106     this.dropped_origin = this.origin;
1107 }
1108
1109 void droptofloor(entity this)
1110 {
1111     InitializeEntity(this, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
1112 }
1113
1114
1115
1116 float trace_hits_box_a0, trace_hits_box_a1;
1117
1118 float trace_hits_box_1d(float end, float thmi, float thma)
1119 {
1120     if (end == 0)
1121     {
1122         // just check if x is in range
1123         if (0 < thmi)
1124             return false;
1125         if (0 > thma)
1126             return false;
1127     }
1128     else
1129     {
1130         // do the trace with respect to x
1131         // 0 -> end has to stay in thmi -> thma
1132         trace_hits_box_a0 = max(trace_hits_box_a0, min(thmi / end, thma / end));
1133         trace_hits_box_a1 = min(trace_hits_box_a1, max(thmi / end, thma / end));
1134         if (trace_hits_box_a0 > trace_hits_box_a1)
1135             return false;
1136     }
1137     return true;
1138 }
1139
1140 float trace_hits_box(vector start, vector end, vector thmi, vector thma)
1141 {
1142     end -= start;
1143     thmi -= start;
1144     thma -= start;
1145     // now it is a trace from 0 to end
1146
1147     trace_hits_box_a0 = 0;
1148     trace_hits_box_a1 = 1;
1149
1150     if (!trace_hits_box_1d(end.x, thmi.x, thma.x))
1151         return false;
1152     if (!trace_hits_box_1d(end.y, thmi.y, thma.y))
1153         return false;
1154     if (!trace_hits_box_1d(end.z, thmi.z, thma.z))
1155         return false;
1156
1157     return true;
1158 }
1159
1160 float tracebox_hits_box(vector start, vector mi, vector ma, vector end, vector thmi, vector thma)
1161 {
1162     return trace_hits_box(start, end, thmi - ma, thma - mi);
1163 }
1164
1165 bool SUB_NoImpactCheck(entity this, entity toucher)
1166 {
1167         // zero hitcontents = this is not the real impact, but either the
1168         // mirror-impact of something hitting the projectile instead of the
1169         // projectile hitting the something, or a touchareagrid one. Neither of
1170         // these stop the projectile from moving, so...
1171         if(trace_dphitcontents == 0)
1172         {
1173                 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);
1174                 checkclient(this); // TODO: .health is checked in the engine with this, possibly replace with a QC function?
1175         }
1176     if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1177         return true;
1178     if (toucher == NULL && this.size != '0 0 0')
1179     {
1180         vector tic;
1181         tic = this.velocity * sys_frametime;
1182         tic = tic + normalize(tic) * vlen(this.maxs - this.mins);
1183         traceline(this.origin - tic, this.origin + tic, MOVE_NORMAL, this);
1184         if (trace_fraction >= 1)
1185         {
1186             LOG_TRACE("Odd... did not hit...?");
1187         }
1188         else if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1189         {
1190             LOG_TRACE("Detected and prevented the sky-grapple bug.");
1191             return true;
1192         }
1193     }
1194
1195     return false;
1196 }
1197
1198 bool WarpZone_Projectile_Touch_ImpactFilter_Callback(entity this, entity toucher)
1199 {
1200         // owner check
1201         if(toucher && toucher == this.owner)
1202                 return true;
1203         if(SUB_NoImpactCheck(this, toucher))
1204         {
1205                 if(this.classname == "nade")
1206                         return false; // no checks here
1207                 else if(this.classname == "grapplinghook")
1208                         RemoveHook(this);
1209                 else
1210                         delete(this);
1211                 return true;
1212         }
1213         if(trace_ent && trace_ent.solid > SOLID_TRIGGER)
1214                 UpdateCSQCProjectile(this);
1215         return false;
1216 }
1217
1218 /** engine callback */
1219 void URI_Get_Callback(float id, float status, string data)
1220 {
1221         if(url_URI_Get_Callback(id, status, data))
1222         {
1223                 // handled
1224         }
1225         else if (id == URI_GET_DISCARD)
1226         {
1227                 // discard
1228         }
1229         else if (id >= URI_GET_CURL && id <= URI_GET_CURL_END)
1230         {
1231                 // sv_cmd curl
1232                 Curl_URI_Get_Callback(id, status, data);
1233         }
1234         else if (id >= URI_GET_IPBAN && id <= URI_GET_IPBAN_END)
1235         {
1236                 // online ban list
1237                 OnlineBanList_URI_Get_Callback(id, status, data);
1238         }
1239         else if (MUTATOR_CALLHOOK(URI_GetCallback, id, status, data))
1240         {
1241                 // handled by a mutator
1242         }
1243         else
1244         {
1245                 LOG_INFO("Received HTTP request data for an invalid id ", ftos(id), ".");
1246         }
1247 }
1248
1249 string uid2name(string myuid)
1250 {
1251         string s = db_get(ServerProgsDB, strcat("/uid2name/", myuid));
1252
1253         // FIXME remove this later after 0.6 release
1254         // convert old style broken records to correct style
1255         if(s == "")
1256         {
1257                 s = db_get(ServerProgsDB, strcat("uid2name", myuid));
1258                 if(s != "")
1259                 {
1260                         db_put(ServerProgsDB, strcat("/uid2name/", myuid), s);
1261                         db_remove(ServerProgsDB, strcat("uid2name", myuid));
1262                 }
1263         }
1264
1265         if(s == "")
1266                 s = "^1Unregistered Player";
1267         return s;
1268 }
1269
1270 bool MoveToRandomLocationWithinBounds(entity e, vector boundmin, vector boundmax, float goodcontents, float badcontents, float badsurfaceflags, int attempts, float maxaboveground, float minviewdistance)
1271 {
1272     float m = e.dphitcontentsmask;
1273     e.dphitcontentsmask = goodcontents | badcontents;
1274
1275     vector org = boundmin;
1276     vector delta = boundmax - boundmin;
1277
1278     vector start, end;
1279     start = end = org;
1280     int j; // used after the loop
1281     for(j = 0; j < attempts; ++j)
1282     {
1283         start.x = org.x + random() * delta.x;
1284         start.y = org.y + random() * delta.y;
1285         start.z = org.z + random() * delta.z;
1286
1287         // rule 1: start inside world bounds, and outside
1288         // solid, and don't start from somewhere where you can
1289         // fall down to evil
1290         tracebox(start, e.mins, e.maxs, start - '0 0 1' * delta.z, MOVE_NORMAL, e);
1291         if (trace_fraction >= 1)
1292             continue;
1293         if (trace_startsolid)
1294             continue;
1295         if (trace_dphitcontents & badcontents)
1296             continue;
1297         if (trace_dphitq3surfaceflags & badsurfaceflags)
1298             continue;
1299
1300         // rule 2: if we are too high, lower the point
1301         if (trace_fraction * delta.z > maxaboveground)
1302             start = trace_endpos + '0 0 1' * maxaboveground;
1303         vector enddown = trace_endpos;
1304
1305         // rule 3: make sure we aren't outside the map. This only works
1306         // for somewhat well formed maps. A good rule of thumb is that
1307         // the map should have a convex outside hull.
1308         // these can be traceLINES as we already verified the starting box
1309         vector mstart = start + 0.5 * (e.mins + e.maxs);
1310         traceline(mstart, mstart + '1 0 0' * delta.x, MOVE_NORMAL, e);
1311         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1312             continue;
1313         traceline(mstart, mstart - '1 0 0' * delta.x, MOVE_NORMAL, e);
1314         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1315             continue;
1316         traceline(mstart, mstart + '0 1 0' * delta.y, MOVE_NORMAL, e);
1317         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1318             continue;
1319         traceline(mstart, mstart - '0 1 0' * delta.y, MOVE_NORMAL, e);
1320         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1321             continue;
1322         traceline(mstart, mstart + '0 0 1' * delta.z, MOVE_NORMAL, e);
1323         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1324             continue;
1325
1326                 // rule 4: we must "see" some spawnpoint or item
1327             entity sp = NULL;
1328             IL_EACH(g_spawnpoints, checkpvs(mstart, it),
1329             {
1330                 if((traceline(mstart, it.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1331                 {
1332                         sp = it;
1333                         break;
1334                 }
1335             });
1336                 if(!sp)
1337                 {
1338                         int items_checked = 0;
1339                         IL_EACH(g_items, checkpvs(mstart, it),
1340                         {
1341                                 if((traceline(mstart, it.origin + (it.mins + it.maxs) * 0.5, MOVE_NORMAL, e), trace_fraction) >= 1)
1342                                 {
1343                                         sp = it;
1344                                         break;
1345                                 }
1346
1347                                 ++items_checked;
1348                                 if(items_checked >= attempts)
1349                                         break; // sanity
1350                         });
1351
1352                         if(!sp)
1353                                 continue;
1354                 }
1355
1356         // find a random vector to "look at"
1357         end.x = org.x + random() * delta.x;
1358         end.y = org.y + random() * delta.y;
1359         end.z = org.z + random() * delta.z;
1360         end = start + normalize(end - start) * vlen(delta);
1361
1362         // rule 4: start TO end must not be too short
1363         tracebox(start, e.mins, e.maxs, end, MOVE_NORMAL, e);
1364         if(trace_startsolid)
1365             continue;
1366         if(trace_fraction < minviewdistance / vlen(delta))
1367             continue;
1368
1369         // rule 5: don't want to look at sky
1370         if(trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY)
1371             continue;
1372
1373         // rule 6: we must not end up in trigger_hurt
1374         if(tracebox_hits_trigger_hurt(start, e.mins, e.maxs, enddown))
1375             continue;
1376
1377         break;
1378     }
1379
1380     e.dphitcontentsmask = m;
1381
1382     if(j < attempts)
1383     {
1384         setorigin(e, start);
1385         e.angles = vectoangles(end - start);
1386         LOG_DEBUG("Needed ", ftos(j + 1), " attempts");
1387         return true;
1388     }
1389     return false;
1390 }
1391
1392 float MoveToRandomMapLocation(entity e, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1393 {
1394         return MoveToRandomLocationWithinBounds(e, world.mins, world.maxs, goodcontents, badcontents, badsurfaceflags, attempts, maxaboveground, minviewdistance);
1395 }
1396
1397 void write_recordmarker(entity pl, float tstart, float dt)
1398 {
1399     GameLogEcho(strcat(":recordset:", ftos(pl.playerid), ":", ftos(dt)));
1400
1401     // also write a marker into demo files for demotc-race-record-extractor to find
1402     stuffcmd(pl,
1403              strcat(
1404                  strcat("//", strconv(2, 0, 0, GetGametype()), " RECORD SET ", TIME_ENCODED_TOSTRING(TIME_ENCODE(dt))),
1405                  " ", ftos(tstart), " ", ftos(dt), "\n"));
1406 }
1407
1408 void attach_sameorigin(entity e, entity to, string tag)
1409 {
1410     vector org, t_forward, t_left, t_up, e_forward, e_up;
1411     float tagscale;
1412
1413     org = e.origin - gettaginfo(to, gettagindex(to, tag));
1414     tagscale = (vlen(v_forward) ** -2); // undo a scale on the tag
1415     t_forward = v_forward * tagscale;
1416     t_left = v_right * -tagscale;
1417     t_up = v_up * tagscale;
1418
1419     e.origin_x = org * t_forward;
1420     e.origin_y = org * t_left;
1421     e.origin_z = org * t_up;
1422
1423     // current forward and up directions
1424     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1425                 e.angles = AnglesTransform_FromVAngles(e.angles);
1426         else
1427                 e.angles = AnglesTransform_FromAngles(e.angles);
1428     fixedmakevectors(e.angles);
1429
1430     // untransform forward, up!
1431     e_forward.x = v_forward * t_forward;
1432     e_forward.y = v_forward * t_left;
1433     e_forward.z = v_forward * t_up;
1434     e_up.x = v_up * t_forward;
1435     e_up.y = v_up * t_left;
1436     e_up.z = v_up * t_up;
1437
1438     e.angles = fixedvectoangles2(e_forward, e_up);
1439     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1440                 e.angles = AnglesTransform_ToVAngles(e.angles);
1441         else
1442                 e.angles = AnglesTransform_ToAngles(e.angles);
1443
1444     setattachment(e, to, tag);
1445     setorigin(e, e.origin);
1446 }
1447
1448 void detach_sameorigin(entity e)
1449 {
1450     vector org;
1451     org = gettaginfo(e, 0);
1452     e.angles = fixedvectoangles2(v_forward, v_up);
1453     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1454                 e.angles = AnglesTransform_ToVAngles(e.angles);
1455         else
1456                 e.angles = AnglesTransform_ToAngles(e.angles);
1457     setorigin(e, org);
1458     setattachment(e, NULL, "");
1459     setorigin(e, e.origin);
1460 }
1461
1462 void follow_sameorigin(entity e, entity to)
1463 {
1464     set_movetype(e, MOVETYPE_FOLLOW); // make the hole follow
1465     e.aiment = to; // make the hole follow bmodel
1466     e.punchangle = to.angles; // the original angles of bmodel
1467     e.view_ofs = e.origin - to.origin; // relative origin
1468     e.v_angle = e.angles - to.angles; // relative angles
1469 }
1470
1471 #if 0
1472 // TODO: unused, likely for a reason, possibly needs extensions (allow setting the new movetype as a parameter?)
1473 void unfollow_sameorigin(entity e)
1474 {
1475     set_movetype(e, MOVETYPE_NONE);
1476 }
1477 #endif
1478
1479 .string aiment_classname;
1480 .float aiment_deadflag;
1481 void SetMovetypeFollow(entity ent, entity e)
1482 {
1483         // FIXME this may not be warpzone aware
1484         set_movetype(ent, MOVETYPE_FOLLOW); // make the hole follow
1485         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.
1486         ent.aiment = e; // make the hole follow bmodel
1487         ent.punchangle = e.angles; // the original angles of bmodel
1488         ent.view_ofs = ent.origin - e.origin; // relative origin
1489         ent.v_angle = ent.angles - e.angles; // relative angles
1490         ent.aiment_classname = strzone(e.classname);
1491         ent.aiment_deadflag = e.deadflag;
1492 }
1493 void UnsetMovetypeFollow(entity ent)
1494 {
1495         set_movetype(ent, MOVETYPE_FLY);
1496         PROJECTILE_MAKETRIGGER(ent);
1497         ent.aiment = NULL;
1498 }
1499 float LostMovetypeFollow(entity ent)
1500 {
1501 /*
1502         if(ent.move_movetype != MOVETYPE_FOLLOW)
1503                 if(ent.aiment)
1504                         error("???");
1505 */
1506         if(ent.aiment)
1507         {
1508                 if(ent.aiment.classname != ent.aiment_classname)
1509                         return 1;
1510                 if(ent.aiment.deadflag != ent.aiment_deadflag)
1511                         return 1;
1512         }
1513         return 0;
1514 }
1515
1516 .bool pushable;
1517 bool isPushable(entity e)
1518 {
1519         if(e.pushable)
1520                 return true;
1521         if(IS_VEHICLE(e))
1522                 return false;
1523         if(e.iscreature)
1524                 return true;
1525         if (Item_IsLoot(e))
1526         {
1527                 return true;
1528         }
1529         switch(e.classname)
1530         {
1531                 case "body":
1532                         return true;
1533                 case "bullet": // antilagged bullets can't hit this either
1534                         return false;
1535         }
1536         if (e.projectiledeathtype)
1537                 return true;
1538         return false;
1539 }