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