]> git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/miscfunctions.qc
Move server-side chat handling to its own file, and add a note about miscfunctions
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / miscfunctions.qc
1 // NOTE: Please do NOT add new functions to this file! It is a dumping ground that is in the process of being cleaned up, please find a proper home for your code!
2
3 #include "miscfunctions.qh"
4
5 #include "antilag.qh"
6 #include "command/common.qh"
7 #include "client.qh"
8 #include "damage.qh"
9 #include "hook.qh"
10 #include "world.qh"
11 #include <server/gamelog.qh>
12 #include "ipban.qh"
13 #include <server/intermission.qh>
14 #include <server/items/items.qh>
15 #include <server/mutators/_mod.qh>
16 #include <server/spawnpoints.qh>
17 #include <server/main.qh>
18 #include "mapvoting.qh"
19 #include "resources.qh"
20 #include <server/items/spawning.qh>
21 #include "player.qh"
22 #include "weapons/accuracy.qh"
23 #include "weapons/common.qh"
24 #include "weapons/csqcprojectile.qh"
25 #include "weapons/selection.qh"
26 #include "../common/command/_mod.qh"
27 #include "../common/constants.qh"
28 #include <common/net_linked.qh>
29 #include <common/weapons/weapon/crylink.qh>
30 #include "../common/deathtypes/all.qh"
31 #include "../common/mapinfo.qh"
32 #include "../common/notifications/all.qh"
33 #include "../common/playerstats.qh"
34 #include "../common/teams.qh"
35 #include "../common/mapobjects/subs.qh"
36 #include <common/mapobjects/trigger/hurt.qh>
37 #include <common/mapobjects/target/location.qh>
38 #include "../common/util.qh"
39 #include "../common/turrets/sv_turrets.qh"
40 #include <common/weapons/_all.qh>
41 #include "../common/vehicles/sv_vehicles.qh"
42 #include "../common/vehicles/vehicle.qh"
43 #include "../common/items/_mod.qh"
44 #include "../common/state.qh"
45 #include "../common/effects/qc/globalsound.qh"
46 #include "../common/wepent.qh"
47 #include <common/weapons/weapon.qh>
48 #include "../lib/csqcmodel/sv_model.qh"
49 #include "../lib/warpzone/anglestransform.qh"
50 #include "../lib/warpzone/server.qh"
51
52 void crosshair_trace(entity pl)
53 {
54         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));
55 }
56
57 void crosshair_trace_plusvisibletriggers(entity pl)
58 {
59         crosshair_trace_plusvisibletriggers__is_wz(pl, false);
60 }
61
62 void WarpZone_crosshair_trace_plusvisibletriggers(entity pl)
63 {
64         crosshair_trace_plusvisibletriggers__is_wz(pl, true);
65 }
66
67 void crosshair_trace_plusvisibletriggers__is_wz(entity pl, bool is_wz)
68 {
69         FOREACH_ENTITY_FLOAT(solid, SOLID_TRIGGER,
70         {
71                 if(it.model != "")
72                 {
73                         it.solid = SOLID_BSP;
74                         IL_PUSH(g_ctrace_changed, it);
75                 }
76         });
77
78         if (is_wz)
79                 WarpZone_crosshair_trace(pl);
80         else
81                 crosshair_trace(pl);
82
83         IL_EACH(g_ctrace_changed, true, { it.solid = SOLID_TRIGGER; });
84
85         IL_CLEAR(g_ctrace_changed);
86 }
87
88 void WarpZone_crosshair_trace(entity pl)
89 {
90         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));
91 }
92
93 /*
94 =============
95 GetCvars
96 =============
97 Called with:
98   0:  sends the request
99   >0: receives a cvar from name=argv(f) value=argv(f+1)
100 */
101 void GetCvars_handleString(entity this, entity store, string thisname, float f, .string field, string name)
102 {
103         if (f < 0)
104         {
105                 strfree(store.(field));
106         }
107         else if (f > 0)
108         {
109                 if (thisname == name)
110                 {
111                         strcpy(store.(field), argv(f + 1));
112                 }
113         }
114         else
115                 stuffcmd(this, strcat("cl_cmd sendcvar ", name, "\n"));
116 }
117 void GetCvars_handleString_Fixup(entity this, entity store, string thisname, float f, .string field, string name, string(entity, string) func)
118 {
119         GetCvars_handleString(this, store, thisname, f, field, name);
120         if (f >= 0) // also initialize to the fitting value for "" when sending cvars out
121                 if (thisname == name)
122                 {
123                         string s = func(this, strcat1(store.(field)));
124                         if (s != store.(field))
125                         {
126                                 strcpy(store.(field), s);
127                         }
128                 }
129 }
130 void GetCvars_handleFloat(entity this, entity store, string thisname, float f, .float field, string name)
131 {
132         if (f < 0)
133         {
134         }
135         else if (f > 0)
136         {
137                 if (thisname == name)
138                         store.(field) = stof(argv(f + 1));
139         }
140         else
141                 stuffcmd(this, strcat("cl_cmd sendcvar ", name, "\n"));
142 }
143 void GetCvars_handleFloatOnce(entity this, entity store, string thisname, float f, .float field, string name)
144 {
145         if (f < 0)
146         {
147         }
148         else if (f > 0)
149         {
150                 if (thisname == name)
151                 {
152                         if (!store.(field))
153                         {
154                                 store.(field) = stof(argv(f + 1));
155                                 if (!store.(field))
156                                         store.(field) = -1;
157                         }
158                 }
159         }
160         else
161         {
162                 if (!store.(field))
163                         stuffcmd(this, strcat("cl_cmd sendcvar ", name, "\n"));
164         }
165 }
166 string W_FixWeaponOrder_ForceComplete_AndBuildImpulseList(entity this, string wo)
167 {
168         string o = W_FixWeaponOrder_ForceComplete(wo);
169         strcpy(CS(this).weaponorder_byimpulse, W_FixWeaponOrder_BuildImpulseList(o));
170         return o;
171 }
172
173 /**
174  * @param f -1: cleanup, 0: request, 1: receive
175  */
176 void GetCvars(entity this, entity store, int f)
177 {
178         string s = string_null;
179
180         if (f == 0)
181                 LOG_INFO("Warning: requesting cvar values is deprecated. Client should send them automatically using REPLICATE.\n");
182
183         if (f > 0)
184                 s = strcat1(argv(f));
185
186         get_cvars_f = f;
187         get_cvars_s = s;
188         MUTATOR_CALLHOOK(GetCvars);
189
190         Notification_GetCvars(this);
191
192         ReplicateVars(this, store, s, f);
193
194         GetCvars_handleString_Fixup(this, store, s, f, cvar_cl_weaponpriority, "cl_weaponpriority", W_FixWeaponOrder_ForceComplete_AndBuildImpulseList);
195         GetCvars_handleString_Fixup(this, store, s, f, cvar_cl_weaponpriorities[0], "cl_weaponpriority0", W_FixWeaponOrder_AllowIncomplete);
196         GetCvars_handleString_Fixup(this, store, s, f, cvar_cl_weaponpriorities[1], "cl_weaponpriority1", W_FixWeaponOrder_AllowIncomplete);
197         GetCvars_handleString_Fixup(this, store, s, f, cvar_cl_weaponpriorities[2], "cl_weaponpriority2", W_FixWeaponOrder_AllowIncomplete);
198         GetCvars_handleString_Fixup(this, store, s, f, cvar_cl_weaponpriorities[3], "cl_weaponpriority3", W_FixWeaponOrder_AllowIncomplete);
199         GetCvars_handleString_Fixup(this, store, s, f, cvar_cl_weaponpriorities[4], "cl_weaponpriority4", W_FixWeaponOrder_AllowIncomplete);
200         GetCvars_handleString_Fixup(this, store, s, f, cvar_cl_weaponpriorities[5], "cl_weaponpriority5", W_FixWeaponOrder_AllowIncomplete);
201         GetCvars_handleString_Fixup(this, store, s, f, cvar_cl_weaponpriorities[6], "cl_weaponpriority6", W_FixWeaponOrder_AllowIncomplete);
202         GetCvars_handleString_Fixup(this, store, s, f, cvar_cl_weaponpriorities[7], "cl_weaponpriority7", W_FixWeaponOrder_AllowIncomplete);
203         GetCvars_handleString_Fixup(this, store, s, f, cvar_cl_weaponpriorities[8], "cl_weaponpriority8", W_FixWeaponOrder_AllowIncomplete);
204         GetCvars_handleString_Fixup(this, store, s, f, cvar_cl_weaponpriorities[9], "cl_weaponpriority9", W_FixWeaponOrder_AllowIncomplete);
205
206         GetCvars_handleFloat(this, store, s, f, cvar_cl_allow_uidtracking, "cl_allow_uidtracking");
207
208         // fixup of switchweapon (needed for LMS or when spectating is disabled, as PutClientInServer comes too early)
209         if (f > 0)
210         {
211                 if (s == "cl_weaponpriority")
212                 {
213                         for(int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
214                         {
215                                 .entity weaponentity = weaponentities[slot];
216                                 if (this.(weaponentity) && (this.(weaponentity).m_weapon != WEP_Null || slot == 0))
217                                         this.(weaponentity).m_switchweapon = w_getbestweapon(this, weaponentity);
218                         }
219                 }
220                 if (s == "cl_allow_uidtracking")
221                         PlayerStats_GameReport_AddPlayer(this);
222                 //if (s == "cl_gunalign")
223                         //W_ResetGunAlign(this, store.cvar_cl_gunalign);
224         }
225 }
226
227 // decolorizes and team colors the player name when needed
228 string playername(entity p, bool team_colorize)
229 {
230     string t;
231     if (team_colorize && teamplay && !intermission_running && IS_PLAYER(p))
232     {
233         t = Team_ColorCode(p.team);
234         return strcat(t, strdecolorize(p.netname));
235     }
236     else
237         return p.netname;
238 }
239
240 float want_weapon(entity weaponinfo, float allguns)
241 {
242         int d = 0;
243         bool allow_mutatorblocked = false;
244
245         if(!weaponinfo.m_id)
246                 return 0;
247
248         bool mutator_returnvalue = MUTATOR_CALLHOOK(WantWeapon, weaponinfo, d, allguns, allow_mutatorblocked);
249         d = M_ARGV(1, float);
250         allguns = M_ARGV(2, bool);
251         allow_mutatorblocked = M_ARGV(3, bool);
252
253         if(allguns)
254                 d = boolean((weaponinfo.spawnflags & WEP_FLAG_NORMAL) && !(weaponinfo.spawnflags & (WEP_FLAG_HIDDEN | WEP_FLAG_SPECIALATTACK)));
255         else if(!mutator_returnvalue)
256                 d = !(!weaponinfo.weaponstart);
257
258         if(!allow_mutatorblocked && (weaponinfo.spawnflags & WEP_FLAG_MUTATORBLOCKED)) // never default mutator blocked guns
259                 d = 0;
260
261         float t = weaponinfo.weaponstartoverride;
262
263         //LOG_INFOF("want_weapon: %s - d: %d t: %d\n", weaponinfo.netname, d, t);
264
265         // bit order in t:
266         // 1: want or not
267         // 2: is default?
268         // 4: is set by default?
269         if(t < 0)
270                 t = 4 | (3 * d);
271         else
272                 t |= (2 * d);
273
274         return t;
275 }
276
277 /// Weapons the player normally starts with outside weapon arena.
278 WepSet weapons_start()
279 {
280         WepSet ret = '0 0 0';
281         FOREACH(Weapons, it != WEP_Null, {
282                 int w = want_weapon(it, false);
283                 if (w & 1)
284                         ret |= it.m_wepset;
285         });
286         return ret;
287 }
288
289 WepSet weapons_all()
290 {
291         WepSet ret = '0 0 0';
292         FOREACH(Weapons, it != WEP_Null, {
293                 if (!(it.spawnflags & (WEP_FLAG_MUTATORBLOCKED | WEP_FLAG_SPECIALATTACK)))
294                         ret |= it.m_wepset;
295         });
296         return ret;
297 }
298
299 WepSet weapons_devall()
300 {
301         WepSet ret = '0 0 0';
302         FOREACH(Weapons, it != WEP_Null,
303         {
304                 ret |= it.m_wepset;
305         });
306         return ret;
307 }
308
309 WepSet weapons_most()
310 {
311         WepSet ret = '0 0 0';
312         FOREACH(Weapons, it != WEP_Null, {
313                 if ((it.spawnflags & WEP_FLAG_NORMAL) && !(it.spawnflags & (WEP_FLAG_MUTATORBLOCKED | WEP_FLAG_HIDDEN | WEP_FLAG_SPECIALATTACK)))
314                         ret |= it.m_wepset;
315         });
316         return ret;
317 }
318
319 void weaponarena_available_all_update(entity this)
320 {
321         if (weaponsInMapAll)
322         {
323                 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | (weaponsInMapAll & weapons_all());
324         }
325         else
326         {
327                 // if no weapons are available on the map, just fall back to all weapons arena
328                 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_all();
329         }
330 }
331
332 void weaponarena_available_devall_update(entity this)
333 {
334         if (weaponsInMapAll)
335         {
336                 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | weaponsInMapAll;
337         }
338         else
339         {
340                 // if no weapons are available on the map, just fall back to devall weapons arena
341                 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_devall();
342         }
343 }
344
345 void weaponarena_available_most_update(entity this)
346 {
347         if (weaponsInMapAll)
348         {
349                 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_start() | (weaponsInMapAll & weapons_most());
350         }
351         else
352         {
353                 // if no weapons are available on the map, just fall back to most weapons arena
354                 start_weapons = warmup_start_weapons = g_weaponarena_weapons = weapons_most();
355         }
356 }
357
358 void readplayerstartcvars()
359 {
360         // initialize starting values for players
361         start_weapons = '0 0 0';
362         start_weapons_default = '0 0 0';
363         start_weapons_defaultmask = '0 0 0';
364         start_items = 0;
365         start_ammo_shells = 0;
366         start_ammo_nails = 0;
367         start_ammo_rockets = 0;
368         start_ammo_cells = 0;
369         start_ammo_plasma = 0;
370         if (random_start_ammo == NULL)
371         {
372                 random_start_ammo = spawn();
373         }
374         start_health = cvar("g_balance_health_start");
375         start_armorvalue = cvar("g_balance_armor_start");
376
377         g_weaponarena = 0;
378         g_weaponarena_weapons = '0 0 0';
379
380         string s = cvar_string("g_weaponarena");
381
382         MUTATOR_CALLHOOK(SetWeaponArena, s);
383         s = M_ARGV(0, string);
384
385         if (s == "0" || s == "")
386         {
387                 // no arena
388         }
389         else if (s == "off")
390         {
391                 // forcibly turn off weaponarena
392         }
393         else if (s == "all" || s == "1")
394         {
395                 g_weaponarena = 1;
396                 g_weaponarena_list = "All Weapons";
397                 g_weaponarena_weapons = weapons_all();
398         }
399         else if (s == "devall")
400         {
401                 g_weaponarena = 1;
402                 g_weaponarena_list = "Dev All Weapons";
403                 g_weaponarena_weapons = weapons_devall();
404         }
405         else if (s == "most")
406         {
407                 g_weaponarena = 1;
408                 g_weaponarena_list = "Most Weapons";
409                 g_weaponarena_weapons = weapons_most();
410         }
411         else if (s == "all_available")
412         {
413                 g_weaponarena = 1;
414                 g_weaponarena_list = "All Available Weapons";
415
416                 // this needs to run after weaponsInMapAll is initialized
417                 InitializeEntity(NULL, weaponarena_available_all_update, INITPRIO_FINDTARGET);
418         }
419         else if (s == "devall_available")
420         {
421                 g_weaponarena = 1;
422                 g_weaponarena_list = "Dev All Available Weapons";
423
424                 // this needs to run after weaponsInMapAll is initialized
425                 InitializeEntity(NULL, weaponarena_available_devall_update, INITPRIO_FINDTARGET);
426         }
427         else if (s == "most_available")
428         {
429                 g_weaponarena = 1;
430                 g_weaponarena_list = "Most Available Weapons";
431
432                 // this needs to run after weaponsInMapAll is initialized
433                 InitializeEntity(NULL, weaponarena_available_most_update, INITPRIO_FINDTARGET);
434         }
435         else if (s == "none")
436         {
437                 g_weaponarena = 1;
438                 g_weaponarena_list = "No Weapons";
439         }
440         else
441         {
442                 g_weaponarena = 1;
443                 float t = tokenize_console(s);
444                 g_weaponarena_list = "";
445                 for (int j = 0; j < t; ++j)
446                 {
447                         s = argv(j);
448                         Weapon wep = Weapon_from_name(s);
449                         if(wep != WEP_Null)
450                         {
451                                 g_weaponarena_weapons |= (wep.m_wepset);
452                                 g_weaponarena_list = strcat(g_weaponarena_list, wep.m_name, " & ");
453                         }
454                 }
455                 g_weaponarena_list = strzone(substring(g_weaponarena_list, 0, strlen(g_weaponarena_list) - 3));
456         }
457
458         if (g_weaponarena)
459         {
460                 g_weapon_stay = 0; // incompatible
461                 start_weapons = g_weaponarena_weapons;
462                 start_items |= IT_UNLIMITED_AMMO | IT_UNLIMITED_SUPERWEAPONS;
463         }
464         else
465         {
466                 FOREACH(Weapons, it != WEP_Null, {
467                         int w = want_weapon(it, false);
468                         WepSet s = it.m_wepset;
469                         if(w & 1)
470                                 start_weapons |= s;
471                         if(w & 2)
472                                 start_weapons_default |= s;
473                         if(w & 4)
474                                 start_weapons_defaultmask |= s;
475                 });
476         }
477
478         if(cvar("g_balance_superweapons_time") < 0)
479                 start_items |= IT_UNLIMITED_SUPERWEAPONS;
480
481         if(!cvar("g_use_ammunition"))
482                 start_items |= IT_UNLIMITED_AMMO;
483
484         if(start_items & IT_UNLIMITED_AMMO)
485         {
486                 start_ammo_shells = 999;
487                 start_ammo_nails = 999;
488                 start_ammo_rockets = 999;
489                 start_ammo_cells = 999;
490                 start_ammo_plasma = 999;
491                 start_ammo_fuel = 999;
492         }
493         else
494         {
495                 start_ammo_shells = cvar("g_start_ammo_shells");
496                 start_ammo_nails = cvar("g_start_ammo_nails");
497                 start_ammo_rockets = cvar("g_start_ammo_rockets");
498                 start_ammo_cells = cvar("g_start_ammo_cells");
499                 start_ammo_plasma = cvar("g_start_ammo_plasma");
500                 start_ammo_fuel = cvar("g_start_ammo_fuel");
501                 random_start_weapons_count = cvar("g_random_start_weapons_count");
502                 SetResource(random_start_ammo, RES_SHELLS, cvar("g_random_start_shells"));
503                 SetResource(random_start_ammo, RES_BULLETS, cvar("g_random_start_bullets"));
504                 SetResource(random_start_ammo, RES_ROCKETS,cvar("g_random_start_rockets"));
505                 SetResource(random_start_ammo, RES_CELLS, cvar("g_random_start_cells"));
506                 SetResource(random_start_ammo, RES_PLASMA, cvar("g_random_start_plasma"));
507         }
508
509         warmup_start_ammo_shells = start_ammo_shells;
510         warmup_start_ammo_nails = start_ammo_nails;
511         warmup_start_ammo_rockets = start_ammo_rockets;
512         warmup_start_ammo_cells = start_ammo_cells;
513         warmup_start_ammo_plasma = start_ammo_plasma;
514         warmup_start_ammo_fuel = start_ammo_fuel;
515         warmup_start_health = start_health;
516         warmup_start_armorvalue = start_armorvalue;
517         warmup_start_weapons = start_weapons;
518         warmup_start_weapons_default = start_weapons_default;
519         warmup_start_weapons_defaultmask = start_weapons_defaultmask;
520
521         if (!g_weaponarena)
522         {
523                 warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
524                 warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
525                 warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
526                 warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
527                 warmup_start_ammo_plasma = cvar("g_warmup_start_ammo_plasma");
528                 warmup_start_ammo_fuel = cvar("g_warmup_start_ammo_fuel");
529                 warmup_start_health = cvar("g_warmup_start_health");
530                 warmup_start_armorvalue = cvar("g_warmup_start_armor");
531                 warmup_start_weapons = '0 0 0';
532                 warmup_start_weapons_default = '0 0 0';
533                 warmup_start_weapons_defaultmask = '0 0 0';
534                 FOREACH(Weapons, it != WEP_Null, {
535                         int w = want_weapon(it, autocvar_g_warmup_allguns);
536                         WepSet s = it.m_wepset;
537                         if(w & 1)
538                                 warmup_start_weapons |= s;
539                         if(w & 2)
540                                 warmup_start_weapons_default |= s;
541                         if(w & 4)
542                                 warmup_start_weapons_defaultmask |= s;
543                 });
544         }
545
546         if (autocvar_g_jetpack)
547                 start_items |= ITEM_Jetpack.m_itemid;
548
549         MUTATOR_CALLHOOK(SetStartItems);
550
551         if (start_items & ITEM_Jetpack.m_itemid)
552         {
553                 start_items |= ITEM_JetpackRegen.m_itemid;
554                 start_ammo_fuel = max(start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
555                 warmup_start_ammo_fuel = max(warmup_start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
556         }
557
558         start_ammo_shells = max(0, start_ammo_shells);
559         start_ammo_nails = max(0, start_ammo_nails);
560         start_ammo_rockets = max(0, start_ammo_rockets);
561         start_ammo_cells = max(0, start_ammo_cells);
562         start_ammo_plasma = max(0, start_ammo_plasma);
563         start_ammo_fuel = max(0, start_ammo_fuel);
564         SetResource(random_start_ammo, RES_SHELLS,
565                 max(0, GetResource(random_start_ammo, RES_SHELLS)));
566         SetResource(random_start_ammo, RES_BULLETS,
567                 max(0, GetResource(random_start_ammo, RES_BULLETS)));
568         SetResource(random_start_ammo, RES_ROCKETS,
569                 max(0, GetResource(random_start_ammo, RES_ROCKETS)));
570         SetResource(random_start_ammo, RES_CELLS,
571                 max(0, GetResource(random_start_ammo, RES_CELLS)));
572         SetResource(random_start_ammo, RES_PLASMA,
573                 max(0, GetResource(random_start_ammo, RES_PLASMA)));
574
575         warmup_start_ammo_shells = max(0, warmup_start_ammo_shells);
576         warmup_start_ammo_nails = max(0, warmup_start_ammo_nails);
577         warmup_start_ammo_rockets = max(0, warmup_start_ammo_rockets);
578         warmup_start_ammo_cells = max(0, warmup_start_ammo_cells);
579         warmup_start_ammo_plasma = max(0, warmup_start_ammo_plasma);
580         warmup_start_ammo_fuel = max(0, warmup_start_ammo_fuel);
581 }
582
583 void precache_playermodel(string m)
584 {
585         int globhandle, i, n;
586         string f;
587
588         // remove :<skinnumber> suffix
589         int j = strstrofs(m, ":", 0);
590         if(j >= 0)
591                 m = substring(m, 0, j);
592
593         if(substring(m, -9, 5) == "_lod1")
594                 return;
595         if(substring(m, -9, 5) == "_lod2")
596                 return;
597         precache_model(m);
598         f = strcat(substring(m, 0, -5), "_lod1", substring(m, -4, -1));
599         if(fexists(f))
600                 precache_model(f);
601         f = strcat(substring(m, 0, -5), "_lod2", substring(m, -4, -1));
602         if(fexists(f))
603                 precache_model(f);
604
605         globhandle = search_begin(strcat(m, "_*.sounds"), true, false);
606         if (globhandle < 0)
607                 return;
608         n = search_getsize(globhandle);
609         for (i = 0; i < n; ++i)
610         {
611                 //print(search_getfilename(globhandle, i), "\n");
612                 f = search_getfilename(globhandle, i);
613                 PrecachePlayerSounds(f);
614         }
615         search_end(globhandle);
616 }
617 void precache_all_playermodels(string pattern)
618 {
619         int globhandle = search_begin(pattern, true, false);
620         if (globhandle < 0) return;
621         int n = search_getsize(globhandle);
622         for (int i = 0; i < n; ++i)
623         {
624                 string s = search_getfilename(globhandle, i);
625                 precache_playermodel(s);
626         }
627         search_end(globhandle);
628 }
629
630 void precache_playermodels(string s)
631 {
632         FOREACH_WORD(s, true, { precache_playermodel(it); });
633 }
634
635 PRECACHE(PlayerModels)
636 {
637     // Precache all player models if desired
638     if (autocvar_sv_precacheplayermodels)
639     {
640         PrecachePlayerSounds("sound/player/default.sounds");
641         precache_all_playermodels("models/player/*.zym");
642         precache_all_playermodels("models/player/*.dpm");
643         precache_all_playermodels("models/player/*.md3");
644         precache_all_playermodels("models/player/*.psk");
645         precache_all_playermodels("models/player/*.iqm");
646     }
647
648     if (autocvar_sv_defaultcharacter)
649     {
650                 precache_playermodels(autocvar_sv_defaultplayermodel_red);
651                 precache_playermodels(autocvar_sv_defaultplayermodel_blue);
652                 precache_playermodels(autocvar_sv_defaultplayermodel_yellow);
653                 precache_playermodels(autocvar_sv_defaultplayermodel_pink);
654                 precache_playermodels(autocvar_sv_defaultplayermodel);
655     }
656 }
657
658 void InitializeEntity(entity e, void(entity this) func, int order)
659 {
660     entity prev, cur;
661
662     if (!e || e.initialize_entity)
663     {
664         // make a proxy initializer entity
665         entity e_old = e;
666         e = new(initialize_entity);
667         e.enemy = e_old;
668     }
669
670     e.initialize_entity = func;
671     e.initialize_entity_order = order;
672
673     cur = initialize_entity_first;
674     prev = NULL;
675     for (;;)
676     {
677         if (!cur || cur.initialize_entity_order > order)
678         {
679             // insert between prev and cur
680             if (prev)
681                 prev.initialize_entity_next = e;
682             else
683                 initialize_entity_first = e;
684             e.initialize_entity_next = cur;
685             return;
686         }
687         prev = cur;
688         cur = cur.initialize_entity_next;
689     }
690 }
691 void InitializeEntitiesRun()
692 {
693     entity startoflist = initialize_entity_first;
694     initialize_entity_first = NULL;
695     delete_fn = remove_except_protected;
696     for (entity e = startoflist; e; e = e.initialize_entity_next)
697     {
698                 e.remove_except_protected_forbidden = 1;
699     }
700     for (entity e = startoflist; e; )
701     {
702                 e.remove_except_protected_forbidden = 0;
703         e.initialize_entity_order = 0;
704         entity next = e.initialize_entity_next;
705         e.initialize_entity_next = NULL;
706         var void(entity this) func = e.initialize_entity;
707         e.initialize_entity = func_null;
708         if (e.classname == "initialize_entity")
709         {
710             entity wrappee = e.enemy;
711             builtin_remove(e);
712             e = wrappee;
713         }
714         //dprint("Delayed initialization: ", e.classname, "\n");
715         if (func)
716         {
717                 func(e);
718         }
719         else
720         {
721             eprint(e);
722             backtrace(strcat("Null function in: ", e.classname, "\n"));
723         }
724         e = next;
725     }
726     delete_fn = remove_unsafely;
727 }
728
729 void adaptor_think2use_hittype_splash(entity this) // for timed projectile detonation
730 {
731         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
732                 this.projectiledeathtype |= HITTYPE_SPLASH;
733         adaptor_think2use(this);
734 }
735
736 // deferred dropping
737 void DropToFloor_Handler(entity this)
738 {
739     WITHSELF(this, builtin_droptofloor());
740     this.dropped_origin = this.origin;
741 }
742
743 void droptofloor(entity this)
744 {
745     InitializeEntity(this, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
746 }
747
748
749
750 float trace_hits_box_a0, trace_hits_box_a1;
751
752 float trace_hits_box_1d(float end, float thmi, float thma)
753 {
754     if (end == 0)
755     {
756         // just check if x is in range
757         if (0 < thmi)
758             return false;
759         if (0 > thma)
760             return false;
761     }
762     else
763     {
764         // do the trace with respect to x
765         // 0 -> end has to stay in thmi -> thma
766         trace_hits_box_a0 = max(trace_hits_box_a0, min(thmi / end, thma / end));
767         trace_hits_box_a1 = min(trace_hits_box_a1, max(thmi / end, thma / end));
768         if (trace_hits_box_a0 > trace_hits_box_a1)
769             return false;
770     }
771     return true;
772 }
773
774 float trace_hits_box(vector start, vector end, vector thmi, vector thma)
775 {
776     end -= start;
777     thmi -= start;
778     thma -= start;
779     // now it is a trace from 0 to end
780
781     trace_hits_box_a0 = 0;
782     trace_hits_box_a1 = 1;
783
784     if (!trace_hits_box_1d(end.x, thmi.x, thma.x))
785         return false;
786     if (!trace_hits_box_1d(end.y, thmi.y, thma.y))
787         return false;
788     if (!trace_hits_box_1d(end.z, thmi.z, thma.z))
789         return false;
790
791     return true;
792 }
793
794 float tracebox_hits_box(vector start, vector mi, vector ma, vector end, vector thmi, vector thma)
795 {
796     return trace_hits_box(start, end, thmi - ma, thma - mi);
797 }
798
799 bool SUB_NoImpactCheck(entity this, entity toucher)
800 {
801         // zero hitcontents = this is not the real impact, but either the
802         // mirror-impact of something hitting the projectile instead of the
803         // projectile hitting the something, or a touchareagrid one. Neither of
804         // these stop the projectile from moving, so...
805         if(trace_dphitcontents == 0)
806         {
807                 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);
808                 checkclient(this); // TODO: .health is checked in the engine with this, possibly replace with a QC function?
809         }
810     if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
811         return true;
812     if (toucher == NULL && this.size != '0 0 0')
813     {
814         vector tic;
815         tic = this.velocity * sys_frametime;
816         tic = tic + normalize(tic) * vlen(this.maxs - this.mins);
817         traceline(this.origin - tic, this.origin + tic, MOVE_NORMAL, this);
818         if (trace_fraction >= 1)
819         {
820             LOG_TRACE("Odd... did not hit...?");
821         }
822         else if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
823         {
824             LOG_TRACE("Detected and prevented the sky-grapple bug.");
825             return true;
826         }
827     }
828
829     return false;
830 }
831
832 bool WarpZone_Projectile_Touch_ImpactFilter_Callback(entity this, entity toucher)
833 {
834         // owner check
835         if(toucher && toucher == this.owner)
836                 return true;
837         if(SUB_NoImpactCheck(this, toucher))
838         {
839                 if(this.classname == "nade")
840                         return false; // no checks here
841                 else if(this.classname == "grapplinghook")
842                         RemoveHook(this);
843                 else
844                         delete(this);
845                 return true;
846         }
847         if(trace_ent && trace_ent.solid > SOLID_TRIGGER)
848                 UpdateCSQCProjectile(this);
849         return false;
850 }
851
852 /** engine callback */
853 void URI_Get_Callback(float id, float status, string data)
854 {
855         if(url_URI_Get_Callback(id, status, data))
856         {
857                 // handled
858         }
859         else if (id == URI_GET_DISCARD)
860         {
861                 // discard
862         }
863         else if (id >= URI_GET_CURL && id <= URI_GET_CURL_END)
864         {
865                 // sv_cmd curl
866                 Curl_URI_Get_Callback(id, status, data);
867         }
868         else if (id >= URI_GET_IPBAN && id <= URI_GET_IPBAN_END)
869         {
870                 // online ban list
871                 OnlineBanList_URI_Get_Callback(id, status, data);
872         }
873         else if (MUTATOR_CALLHOOK(URI_GetCallback, id, status, data))
874         {
875                 // handled by a mutator
876         }
877         else
878         {
879                 LOG_INFO("Received HTTP request data for an invalid id ", ftos(id), ".");
880         }
881 }
882
883 string uid2name(string myuid)
884 {
885         string s = db_get(ServerProgsDB, strcat("/uid2name/", myuid));
886
887         // FIXME remove this later after 0.6 release
888         // convert old style broken records to correct style
889         if(s == "")
890         {
891                 s = db_get(ServerProgsDB, strcat("uid2name", myuid));
892                 if(s != "")
893                 {
894                         db_put(ServerProgsDB, strcat("/uid2name/", myuid), s);
895                         db_remove(ServerProgsDB, strcat("uid2name", myuid));
896                 }
897         }
898
899         if(s == "")
900                 s = "^1Unregistered Player";
901         return s;
902 }
903
904 bool MoveToRandomLocationWithinBounds(entity e, vector boundmin, vector boundmax, float goodcontents, float badcontents, float badsurfaceflags, int attempts, float maxaboveground, float minviewdistance)
905 {
906     float m = e.dphitcontentsmask;
907     e.dphitcontentsmask = goodcontents | badcontents;
908
909     vector org = boundmin;
910     vector delta = boundmax - boundmin;
911
912     vector start, end;
913     start = end = org;
914     int j; // used after the loop
915     for(j = 0; j < attempts; ++j)
916     {
917         start.x = org.x + random() * delta.x;
918         start.y = org.y + random() * delta.y;
919         start.z = org.z + random() * delta.z;
920
921         // rule 1: start inside world bounds, and outside
922         // solid, and don't start from somewhere where you can
923         // fall down to evil
924         tracebox(start, e.mins, e.maxs, start - '0 0 1' * delta.z, MOVE_NORMAL, e);
925         if (trace_fraction >= 1)
926             continue;
927         if (trace_startsolid)
928             continue;
929         if (trace_dphitcontents & badcontents)
930             continue;
931         if (trace_dphitq3surfaceflags & badsurfaceflags)
932             continue;
933
934         // rule 2: if we are too high, lower the point
935         if (trace_fraction * delta.z > maxaboveground)
936             start = trace_endpos + '0 0 1' * maxaboveground;
937         vector enddown = trace_endpos;
938
939         // rule 3: make sure we aren't outside the map. This only works
940         // for somewhat well formed maps. A good rule of thumb is that
941         // the map should have a convex outside hull.
942         // these can be traceLINES as we already verified the starting box
943         vector mstart = start + 0.5 * (e.mins + e.maxs);
944         traceline(mstart, mstart + '1 0 0' * delta.x, MOVE_NORMAL, e);
945         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
946             continue;
947         traceline(mstart, mstart - '1 0 0' * delta.x, MOVE_NORMAL, e);
948         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
949             continue;
950         traceline(mstart, mstart + '0 1 0' * delta.y, MOVE_NORMAL, e);
951         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
952             continue;
953         traceline(mstart, mstart - '0 1 0' * delta.y, MOVE_NORMAL, e);
954         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
955             continue;
956         traceline(mstart, mstart + '0 0 1' * delta.z, MOVE_NORMAL, e);
957         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
958             continue;
959
960                 // rule 4: we must "see" some spawnpoint or item
961             entity sp = NULL;
962             IL_EACH(g_spawnpoints, checkpvs(mstart, it),
963             {
964                 if((traceline(mstart, it.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
965                 {
966                         sp = it;
967                         break;
968                 }
969             });
970                 if(!sp)
971                 {
972                         int items_checked = 0;
973                         IL_EACH(g_items, checkpvs(mstart, it),
974                         {
975                                 if((traceline(mstart, it.origin + (it.mins + it.maxs) * 0.5, MOVE_NORMAL, e), trace_fraction) >= 1)
976                                 {
977                                         sp = it;
978                                         break;
979                                 }
980
981                                 ++items_checked;
982                                 if(items_checked >= attempts)
983                                         break; // sanity
984                         });
985
986                         if(!sp)
987                                 continue;
988                 }
989
990         // find a random vector to "look at"
991         end.x = org.x + random() * delta.x;
992         end.y = org.y + random() * delta.y;
993         end.z = org.z + random() * delta.z;
994         end = start + normalize(end - start) * vlen(delta);
995
996         // rule 4: start TO end must not be too short
997         tracebox(start, e.mins, e.maxs, end, MOVE_NORMAL, e);
998         if(trace_startsolid)
999             continue;
1000         if(trace_fraction < minviewdistance / vlen(delta))
1001             continue;
1002
1003         // rule 5: don't want to look at sky
1004         if(trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY)
1005             continue;
1006
1007         // rule 6: we must not end up in trigger_hurt
1008         if(tracebox_hits_trigger_hurt(start, e.mins, e.maxs, enddown))
1009             continue;
1010
1011         break;
1012     }
1013
1014     e.dphitcontentsmask = m;
1015
1016     if(j < attempts)
1017     {
1018         setorigin(e, start);
1019         e.angles = vectoangles(end - start);
1020         LOG_DEBUG("Needed ", ftos(j + 1), " attempts");
1021         return true;
1022     }
1023     return false;
1024 }
1025
1026 float MoveToRandomMapLocation(entity e, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1027 {
1028         return MoveToRandomLocationWithinBounds(e, world.mins, world.maxs, goodcontents, badcontents, badsurfaceflags, attempts, maxaboveground, minviewdistance);
1029 }
1030
1031 void write_recordmarker(entity pl, float tstart, float dt)
1032 {
1033     GameLogEcho(strcat(":recordset:", ftos(pl.playerid), ":", ftos(dt)));
1034
1035     // also write a marker into demo files for demotc-race-record-extractor to find
1036     stuffcmd(pl,
1037              strcat(
1038                  strcat("//", strconv(2, 0, 0, GetGametype()), " RECORD SET ", TIME_ENCODED_TOSTRING(TIME_ENCODE(dt))),
1039                  " ", ftos(tstart), " ", ftos(dt), "\n"));
1040 }
1041
1042 void attach_sameorigin(entity e, entity to, string tag)
1043 {
1044     vector org, t_forward, t_left, t_up, e_forward, e_up;
1045     float tagscale;
1046
1047     org = e.origin - gettaginfo(to, gettagindex(to, tag));
1048     tagscale = (vlen(v_forward) ** -2); // undo a scale on the tag
1049     t_forward = v_forward * tagscale;
1050     t_left = v_right * -tagscale;
1051     t_up = v_up * tagscale;
1052
1053     e.origin_x = org * t_forward;
1054     e.origin_y = org * t_left;
1055     e.origin_z = org * t_up;
1056
1057     // current forward and up directions
1058     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1059                 e.angles = AnglesTransform_FromVAngles(e.angles);
1060         else
1061                 e.angles = AnglesTransform_FromAngles(e.angles);
1062     fixedmakevectors(e.angles);
1063
1064     // untransform forward, up!
1065     e_forward.x = v_forward * t_forward;
1066     e_forward.y = v_forward * t_left;
1067     e_forward.z = v_forward * t_up;
1068     e_up.x = v_up * t_forward;
1069     e_up.y = v_up * t_left;
1070     e_up.z = v_up * t_up;
1071
1072     e.angles = fixedvectoangles2(e_forward, e_up);
1073     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1074                 e.angles = AnglesTransform_ToVAngles(e.angles);
1075         else
1076                 e.angles = AnglesTransform_ToAngles(e.angles);
1077
1078     setattachment(e, to, tag);
1079     setorigin(e, e.origin);
1080 }
1081
1082 void detach_sameorigin(entity e)
1083 {
1084     vector org;
1085     org = gettaginfo(e, 0);
1086     e.angles = fixedvectoangles2(v_forward, v_up);
1087     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1088                 e.angles = AnglesTransform_ToVAngles(e.angles);
1089         else
1090                 e.angles = AnglesTransform_ToAngles(e.angles);
1091     setorigin(e, org);
1092     setattachment(e, NULL, "");
1093     setorigin(e, e.origin);
1094 }
1095
1096 void follow_sameorigin(entity e, entity to)
1097 {
1098     set_movetype(e, MOVETYPE_FOLLOW); // make the hole follow
1099     e.aiment = to; // make the hole follow bmodel
1100     e.punchangle = to.angles; // the original angles of bmodel
1101     e.view_ofs = e.origin - to.origin; // relative origin
1102     e.v_angle = e.angles - to.angles; // relative angles
1103 }
1104
1105 #if 0
1106 // TODO: unused, likely for a reason, possibly needs extensions (allow setting the new movetype as a parameter?)
1107 void unfollow_sameorigin(entity e)
1108 {
1109     set_movetype(e, MOVETYPE_NONE);
1110 }
1111 #endif
1112
1113 .string aiment_classname;
1114 .float aiment_deadflag;
1115 void SetMovetypeFollow(entity ent, entity e)
1116 {
1117         // FIXME this may not be warpzone aware
1118         set_movetype(ent, MOVETYPE_FOLLOW); // make the hole follow
1119         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.
1120         ent.aiment = e; // make the hole follow bmodel
1121         ent.punchangle = e.angles; // the original angles of bmodel
1122         ent.view_ofs = ent.origin - e.origin; // relative origin
1123         ent.v_angle = ent.angles - e.angles; // relative angles
1124         ent.aiment_classname = strzone(e.classname);
1125         ent.aiment_deadflag = e.deadflag;
1126 }
1127 void UnsetMovetypeFollow(entity ent)
1128 {
1129         set_movetype(ent, MOVETYPE_FLY);
1130         PROJECTILE_MAKETRIGGER(ent);
1131         ent.aiment = NULL;
1132 }
1133 float LostMovetypeFollow(entity ent)
1134 {
1135 /*
1136         if(ent.move_movetype != MOVETYPE_FOLLOW)
1137                 if(ent.aiment)
1138                         error("???");
1139 */
1140         if(ent.aiment)
1141         {
1142                 if(ent.aiment.classname != ent.aiment_classname)
1143                         return 1;
1144                 if(ent.aiment.deadflag != ent.aiment_deadflag)
1145                         return 1;
1146         }
1147         return 0;
1148 }