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