]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/miscfunctions.qc
3a4680ebb94366867b11d1c9c11829e055302eec
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / miscfunctions.qc
1 #include "miscfunctions.qh"
2 #include "antilag.qh"
3 #include "command/common.qh"
4 #include "constants.qh"
5 #include "g_hook.qh"
6 #include "ipban.qh"
7 #include "mutators/all.qh"
8 #include "t_items.qh"
9 #include "weapons/accuracy.qh"
10 #include "weapons/csqcprojectile.qh"
11 #include "weapons/selection.qh"
12 #include "../common/command/generic.qh"
13 #include "../common/constants.qh"
14 #include "../common/deathtypes/all.qh"
15 #include "../common/mapinfo.qh"
16 #include "../common/notifications.qh"
17 #include "../common/playerstats.qh"
18 #include "../common/teams.qh"
19 #include "../common/triggers/subs.qh"
20 #include "../common/util.qh"
21 #include "../common/turrets/sv_turrets.qh"
22 #include "../common/weapons/all.qh"
23 #include "../common/vehicles/sv_vehicles.qh"
24 #include "../common/vehicles/vehicle.qh"
25 #include "../common/items/all.qc"
26 #include "../lib/csqcmodel/sv_model.qh"
27 #include "../lib/warpzone/anglestransform.qh"
28 #include "../lib/warpzone/server.qh"
29
30 void crosshair_trace(entity pl)
31 {
32         traceline_antilag(pl, pl.cursor_trace_start, pl.cursor_trace_start + normalize(pl.cursor_trace_endpos - pl.cursor_trace_start) * MAX_SHOT_DISTANCE, MOVE_NORMAL, pl, ANTILAG_LATENCY(pl));
33 }
34 void crosshair_trace_plusvisibletriggers(entity pl)
35 {
36         entity first;
37         entity e;
38         first = findchainfloat(solid, SOLID_TRIGGER);
39
40         for (e = first; e; e = e.chain)
41                 if (e.model != "")
42                         e.solid = SOLID_BSP;
43
44         crosshair_trace(pl);
45
46         for (e = first; e; e = e.chain)
47                 e.solid = SOLID_TRIGGER;
48 }
49 void WarpZone_crosshair_trace(entity pl)
50 {
51         WarpZone_traceline_antilag(pl, pl.cursor_trace_start, pl.cursor_trace_start + normalize(pl.cursor_trace_endpos - pl.cursor_trace_start) * MAX_SHOT_DISTANCE, MOVE_NORMAL, pl, ANTILAG_LATENCY(pl));
52 }
53
54
55 string admin_name(void)
56 {
57         if(autocvar_sv_adminnick != "")
58                 return autocvar_sv_adminnick;
59         else
60                 return "SERVER ADMIN";
61 }
62
63 void DistributeEvenly_Init(float amount, float totalweight)
64 {
65     if (DistributeEvenly_amount)
66     {
67         LOG_TRACE("DistributeEvenly_Init: UNFINISHED DISTRIBUTION (", ftos(DistributeEvenly_amount), " for ");
68         LOG_TRACE(ftos(DistributeEvenly_totalweight), " left!)\n");
69     }
70     if (totalweight == 0)
71         DistributeEvenly_amount = 0;
72     else
73         DistributeEvenly_amount = amount;
74     DistributeEvenly_totalweight = totalweight;
75 }
76 float DistributeEvenly_Get(float weight)
77 {
78     float f;
79     if (weight <= 0)
80         return 0;
81     f = floor(0.5 + DistributeEvenly_amount * weight / DistributeEvenly_totalweight);
82     DistributeEvenly_totalweight -= weight;
83     DistributeEvenly_amount -= f;
84     return f;
85 }
86 float DistributeEvenly_GetRandomized(float weight)
87 {
88     float f;
89     if (weight <= 0)
90         return 0;
91     f = floor(random() + DistributeEvenly_amount * weight / DistributeEvenly_totalweight);
92     DistributeEvenly_totalweight -= weight;
93     DistributeEvenly_amount -= f;
94     return f;
95 }
96
97
98 void GameLogEcho(string s)
99 {
100     string fn;
101     int matches;
102
103     if (autocvar_sv_eventlog_files)
104     {
105         if (!logfile_open)
106         {
107             logfile_open = true;
108             matches = autocvar_sv_eventlog_files_counter + 1;
109             cvar_set("sv_eventlog_files_counter", itos(matches));
110             fn = ftos(matches);
111             if (strlen(fn) < 8)
112                 fn = strcat(substring("00000000", 0, 8 - strlen(fn)), fn);
113             fn = strcat(autocvar_sv_eventlog_files_nameprefix, fn, autocvar_sv_eventlog_files_namesuffix);
114             logfile = fopen(fn, FILE_APPEND);
115             fputs(logfile, ":logversion:3\n");
116         }
117         if (logfile >= 0)
118         {
119             if (autocvar_sv_eventlog_files_timestamps)
120                 fputs(logfile, strcat(":time:", strftime(true, "%Y-%m-%d %H:%M:%S", "\n", s, "\n")));
121             else
122                 fputs(logfile, strcat(s, "\n"));
123         }
124     }
125     if (autocvar_sv_eventlog_console)
126     {
127         LOG_INFO(s, "\n");
128     }
129 }
130
131 void GameLogInit()
132 {
133     logfile_open = 0;
134     // will be opened later
135 }
136
137 void GameLogClose()
138 {
139     if (logfile_open && logfile >= 0)
140     {
141         fclose(logfile);
142         logfile = -1;
143     }
144 }
145
146 entity findnearest(vector point, .string field, string value, vector axismod)
147 {
148     entity localhead;
149     float i;
150     float j;
151     float len;
152     vector dist;
153
154     float num_nearest;
155     num_nearest = 0;
156
157     localhead = find(world, field, value);
158     while (localhead)
159     {
160         if ((localhead.items == IT_KEY1 || localhead.items == IT_KEY2) && localhead.target == "###item###")
161             dist = localhead.oldorigin;
162         else
163             dist = localhead.origin;
164         dist = dist - point;
165         dist = dist.x * axismod.x * '1 0 0' + dist.y * axismod.y * '0 1 0' + dist.z * axismod.z * '0 0 1';
166         len = vlen(dist);
167
168         for (i = 0; i < num_nearest; ++i)
169         {
170             if (len < nearest_length[i])
171                 break;
172         }
173
174         // now i tells us where to insert at
175         //   INSERTION SORT! YOU'VE SEEN IT! RUN!
176         if (i < NUM_NEAREST_ENTITIES)
177         {
178             for (j = NUM_NEAREST_ENTITIES - 1; j >= i; --j)
179             {
180                 nearest_length[j + 1] = nearest_length[j];
181                 nearest_entity[j + 1] = nearest_entity[j];
182             }
183             nearest_length[i] = len;
184             nearest_entity[i] = localhead;
185             if (num_nearest < NUM_NEAREST_ENTITIES)
186                 num_nearest = num_nearest + 1;
187         }
188
189         localhead = find(localhead, field, value);
190     }
191
192     // now use the first one from our list that we can see
193     for (i = 0; i < num_nearest; ++i)
194     {
195         traceline(point, nearest_entity[i].origin, true, world);
196         if (trace_fraction == 1)
197         {
198             if (i != 0)
199             {
200                 LOG_TRACE("Nearest point (");
201                 LOG_TRACE(nearest_entity[0].netname);
202                 LOG_TRACE(") is not visible, using a visible one.\n");
203             }
204             return nearest_entity[i];
205         }
206     }
207
208     if (num_nearest == 0)
209         return world;
210
211     LOG_TRACE("Not seeing any location point, using nearest as fallback.\n");
212     /* DEBUGGING CODE:
213     dprint("Candidates were: ");
214     for(j = 0; j < num_nearest; ++j)
215     {
216         if(j != 0)
217                 dprint(", ");
218         dprint(nearest_entity[j].netname);
219     }
220     dprint("\n");
221     */
222
223     return nearest_entity[0];
224 }
225
226 string NearestLocation(vector p)
227 {
228     entity loc;
229     string ret;
230     ret = "somewhere";
231     loc = findnearest(p, classname, "target_location", '1 1 1');
232     if (loc)
233     {
234         ret = loc.message;
235     }
236     else
237     {
238         loc = findnearest(p, target, "###item###", '1 1 4');
239         if (loc)
240             ret = loc.netname;
241     }
242     return ret;
243 }
244
245 string formatmessage(string msg)
246 {SELFPARAM();
247         float p, p1, p2;
248         float n;
249         vector cursor;
250         entity cursor_ent;
251         string escape;
252         string replacement;
253         string ammoitems;
254         p = 0;
255         n = 7;
256
257         ammoitems = "batteries";
258         if(self.items & ITEM_Plasma.m_itemid) ammoitems = ITEM_Plasma.m_name;
259         if(self.items & ITEM_Cells.m_itemid) ammoitems = ITEM_Cells.m_name;
260         if(self.items & ITEM_Rockets.m_itemid) ammoitems = ITEM_Rockets.m_name;
261         if(self.items & ITEM_Shells.m_itemid) ammoitems = ITEM_Shells.m_name;
262
263         WarpZone_crosshair_trace(self);
264         cursor = trace_endpos;
265         cursor_ent = trace_ent;
266
267         while (1) {
268                 if (n < 1)
269                         break; // too many replacements
270
271                 n = n - 1;
272                 p1 = strstr(msg, "%", p); // NOTE: this destroys msg as it's a tempstring!
273                 p2 = strstr(msg, "\\", p); // NOTE: this destroys msg as it's a tempstring!
274
275                 if (p1 < 0)
276                         p1 = p2;
277
278                 if (p2 < 0)
279                         p2 = p1;
280
281                 p = min(p1, p2);
282
283                 if (p < 0)
284                         break;
285
286                 replacement = substring(msg, p, 2);
287                 escape = substring(msg, p + 1, 1);
288
289                 switch(escape)
290                 {
291                         case "%": replacement = "%"; break;
292                         case "\\":replacement = "\\"; break;
293                         case "n": replacement = "\n"; break;
294                         case "a": replacement = ftos(floor(self.armorvalue)); break;
295                         case "h": replacement = ftos(floor(self.health)); break;
296                         case "l": replacement = NearestLocation(self.origin); break;
297                         case "y": replacement = NearestLocation(cursor); break;
298                         case "d": replacement = NearestLocation(self.death_origin); break;
299                         case "w": replacement = WEP_NAME((!self.weapon) ? (!self.switchweapon ? self.cnt : self.switchweapon) : self.weapon); break;
300                         case "W": replacement = ammoitems; break;
301                         case "x": replacement = ((cursor_ent.netname == "" || !cursor_ent) ? "nothing" : cursor_ent.netname); break;
302                         case "s": replacement = ftos(vlen(self.velocity - self.velocity_z * '0 0 1')); break;
303                         case "S": replacement = ftos(vlen(self.velocity)); break;
304                         case "t": replacement = seconds_tostring(ceil(max(0, autocvar_timelimit * 60 + game_starttime - time))); break;
305                         case "T": replacement = seconds_tostring(floor(time - game_starttime)); break;
306                         default:
307                         {
308                                 MUTATOR_CALLHOOK(FormatMessage, escape, replacement, msg);
309                                 escape = format_escape;
310                                 replacement = format_replacement;
311                                 break;
312                         }
313                 }
314
315                 msg = strcat(substring(msg, 0, p), replacement, substring(msg, p+2, strlen(msg) - (p+2)));
316                 p = p + strlen(replacement);
317         }
318         return msg;
319 }
320
321 /*
322 =============
323 GetCvars
324 =============
325 Called with:
326   0:  sends the request
327   >0: receives a cvar from name=argv(f) value=argv(f+1)
328 */
329 void GetCvars_handleString(string thisname, float f, .string field, string name)
330 {SELFPARAM();
331         if (f < 0)
332         {
333                 if (self.(field))
334                         strunzone(self.(field));
335                 self.(field) = string_null;
336         }
337         else if (f > 0)
338         {
339                 if (thisname == name)
340                 {
341                         if (self.(field))
342                                 strunzone(self.(field));
343                         self.(field) = strzone(argv(f + 1));
344                 }
345         }
346         else
347                 stuffcmd(self, strcat("cl_cmd sendcvar ", name, "\n"));
348 }
349 void GetCvars_handleString_Fixup(string thisname, float f, .string field, string name, string(string) func)
350 {SELFPARAM();
351         GetCvars_handleString(thisname, f, field, name);
352         if (f >= 0) // also initialize to the fitting value for "" when sending cvars out
353                 if (thisname == name)
354                 {
355                         string s = func(strcat1(self.(field)));
356                         if (s != self.(field))
357                         {
358                                 strunzone(self.(field));
359                                 self.(field) = strzone(s);
360                         }
361                 }
362 }
363 void GetCvars_handleFloat(string thisname, float f, .float field, string name)
364 {SELFPARAM();
365         if (f < 0)
366         {
367         }
368         else if (f > 0)
369         {
370                 if (thisname == name)
371                         self.(field) = stof(argv(f + 1));
372         }
373         else
374                 stuffcmd(self, strcat("cl_cmd sendcvar ", name, "\n"));
375 }
376 void GetCvars_handleFloatOnce(string thisname, float f, .float field, string name)
377 {SELFPARAM();
378         if (f < 0)
379         {
380         }
381         else if (f > 0)
382         {
383                 if (thisname == name)
384                 {
385                         if (!self.(field))
386                         {
387                                 self.(field) = stof(argv(f + 1));
388                                 if (!self.(field))
389                                         self.(field) = -1;
390                         }
391                 }
392         }
393         else
394         {
395                 if (!self.(field))
396                         stuffcmd(self, strcat("cl_cmd sendcvar ", name, "\n"));
397         }
398 }
399 string W_FixWeaponOrder_ForceComplete_AndBuildImpulseList(string wo)
400 {SELFPARAM();
401         string o;
402         o = W_FixWeaponOrder_ForceComplete(wo);
403         if(self.weaponorder_byimpulse)
404         {
405                 strunzone(self.weaponorder_byimpulse);
406                 self.weaponorder_byimpulse = string_null;
407         }
408         self.weaponorder_byimpulse = strzone(W_FixWeaponOrder_BuildImpulseList(o));
409         return o;
410 }
411 void GetCvars(float f)
412 {SELFPARAM();
413         string s = string_null;
414
415         if (f > 0)
416                 s = strcat1(argv(f));
417
418         get_cvars_f = f;
419         get_cvars_s = s;
420         MUTATOR_CALLHOOK(GetCvars);
421
422         Notification_GetCvars();
423
424         ReplicateVars(this, s, f);
425
426         GetCvars_handleFloat(s, f, autoswitch, "cl_autoswitch");
427         GetCvars_handleFloat(s, f, cvar_cl_autoscreenshot, "cl_autoscreenshot");
428         GetCvars_handleFloat(s, f, cvar_cl_jetpack_jump, "cl_jetpack_jump");
429         GetCvars_handleString(s, f, cvar_g_xonoticversion, "g_xonoticversion");
430         GetCvars_handleString(s, f, cvar_cl_physics, "cl_physics");
431         GetCvars_handleFloat(s, f, cvar_cl_handicap, "cl_handicap");
432         GetCvars_handleFloat(s, f, cvar_cl_clippedspectating, "cl_clippedspectating");
433         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriority, "cl_weaponpriority", W_FixWeaponOrder_ForceComplete_AndBuildImpulseList);
434         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[0], "cl_weaponpriority0", W_FixWeaponOrder_AllowIncomplete);
435         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[1], "cl_weaponpriority1", W_FixWeaponOrder_AllowIncomplete);
436         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[2], "cl_weaponpriority2", W_FixWeaponOrder_AllowIncomplete);
437         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[3], "cl_weaponpriority3", W_FixWeaponOrder_AllowIncomplete);
438         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[4], "cl_weaponpriority4", W_FixWeaponOrder_AllowIncomplete);
439         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[5], "cl_weaponpriority5", W_FixWeaponOrder_AllowIncomplete);
440         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[6], "cl_weaponpriority6", W_FixWeaponOrder_AllowIncomplete);
441         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[7], "cl_weaponpriority7", W_FixWeaponOrder_AllowIncomplete);
442         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[8], "cl_weaponpriority8", W_FixWeaponOrder_AllowIncomplete);
443         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[9], "cl_weaponpriority9", W_FixWeaponOrder_AllowIncomplete);
444         GetCvars_handleFloat(s, f, cvar_cl_weaponimpulsemode, "cl_weaponimpulsemode");
445         GetCvars_handleFloat(s, f, cvar_cl_autotaunt, "cl_autotaunt");
446         GetCvars_handleFloat(s, f, cvar_cl_noantilag, "cl_noantilag");
447         GetCvars_handleFloat(s, f, cvar_cl_voice_directional, "cl_voice_directional");
448         GetCvars_handleFloat(s, f, cvar_cl_voice_directional_taunt_attenuation, "cl_voice_directional_taunt_attenuation");
449         GetCvars_handleFloat(s, f, cvar_cl_accuracy_data_share, "cl_accuracy_data_share");
450         GetCvars_handleFloat(s, f, cvar_cl_accuracy_data_receive, "cl_accuracy_data_receive");
451
452         self.cvar_cl_accuracy_data_share = boolean(self.cvar_cl_accuracy_data_share);
453         self.cvar_cl_accuracy_data_receive = boolean(self.cvar_cl_accuracy_data_receive);
454
455         GetCvars_handleFloatOnce(s, f, cvar_cl_gunalign, "cl_gunalign");
456         GetCvars_handleFloat(s, f, cvar_cl_allow_uid2name, "cl_allow_uid2name");
457         GetCvars_handleFloat(s, f, cvar_cl_allow_uidtracking, "cl_allow_uidtracking");
458         GetCvars_handleFloat(s, f, cvar_cl_movement_track_canjump, "cl_movement_track_canjump");
459         GetCvars_handleFloat(s, f, cvar_cl_newusekeysupported, "cl_newusekeysupported");
460
461         // fixup of switchweapon (needed for LMS or when spectating is disabled, as PutClientInServer comes too early)
462         if (f > 0)
463         {
464                 if (s == "cl_weaponpriority")
465                         self.switchweapon = w_getbestweapon(self);
466                 if (s == "cl_allow_uidtracking")
467                         PlayerStats_GameReport_AddPlayer(self);
468         }
469 }
470
471 // decolorizes and team colors the player name when needed
472 string playername(entity p)
473 {
474     string t;
475     if (teamplay && !intermission_running && IS_PLAYER(p))
476     {
477         t = Team_ColorCode(p.team);
478         return strcat(t, strdecolorize(p.netname));
479     }
480     else
481         return p.netname;
482 }
483
484 float want_weapon(entity weaponinfo, float allguns) // WEAPONTODO: what still needs done?
485 {
486         int i = weaponinfo.weapon;
487         int d = 0;
488         bool allow_mutatorblocked = false;
489
490         if(!i)
491                 return 0;
492
493         bool mutator_returnvalue = MUTATOR_CALLHOOK(WantWeapon, weaponinfo, d, allguns, allow_mutatorblocked);
494         d = ret_float;
495         allguns = want_allguns;
496         allow_mutatorblocked = false;
497
498         if(allguns)
499         {
500                 if(weaponinfo.spawnflags & WEP_FLAG_NORMAL)
501                         d = true;
502                 else
503                         d = false;
504         }
505         else if(!mutator_returnvalue)
506                 d = !(!weaponinfo.weaponstart);
507
508         if(!allow_mutatorblocked && (weaponinfo.spawnflags & WEP_FLAG_MUTATORBLOCKED)) // never default mutator blocked guns
509                 d = 0;
510
511         float t = weaponinfo.weaponstartoverride;
512
513         //print(strcat("want_weapon: ", weaponinfo.netname, " - d: ", ftos(d), ", t: ", ftos(t), ". \n"));
514
515         // bit order in t:
516         // 1: want or not
517         // 2: is default?
518         // 4: is set by default?
519         if(t < 0)
520                 t = 4 | (3 * d);
521         else
522                 t |= (2 * d);
523
524         return t;
525 }
526
527 void readplayerstartcvars()
528 {
529         entity e;
530         float i, j, t;
531         string s;
532
533         // initialize starting values for players
534         start_weapons = '0 0 0';
535         start_weapons_default = '0 0 0';
536         start_weapons_defaultmask = '0 0 0';
537         start_items = 0;
538         start_ammo_shells = 0;
539         start_ammo_nails = 0;
540         start_ammo_rockets = 0;
541         start_ammo_cells = 0;
542         start_ammo_plasma = 0;
543         start_health = cvar("g_balance_health_start");
544         start_armorvalue = cvar("g_balance_armor_start");
545
546         g_weaponarena = 0;
547         g_weaponarena_weapons = '0 0 0';
548
549         s = cvar_string("g_weaponarena");
550
551         MUTATOR_CALLHOOK(SetWeaponArena, s);
552         s = ret_string;
553
554         if (s == "0" || s == "")
555         {
556                 // no arena
557         }
558         else if (s == "off")
559         {
560                 // forcibly turn off weaponarena
561         }
562         else if (s == "all" || s == "1")
563         {
564                 g_weaponarena = 1;
565                 g_weaponarena_list = "All Weapons";
566                 for (j = WEP_FIRST; j <= WEP_LAST; ++j)
567                 {
568                         e = get_weaponinfo(j);
569                         if (!(e.spawnflags & WEP_FLAG_MUTATORBLOCKED))
570                                 g_weaponarena_weapons |= WepSet_FromWeapon(j);
571                 }
572         }
573         else if (s == "most")
574         {
575                 g_weaponarena = 1;
576                 g_weaponarena_list = "Most Weapons";
577                 for (j = WEP_FIRST; j <= WEP_LAST; ++j)
578                 {
579                         e = get_weaponinfo(j);
580                         if (!(e.spawnflags & WEP_FLAG_MUTATORBLOCKED))
581                                 if (e.spawnflags & WEP_FLAG_NORMAL)
582                                         g_weaponarena_weapons |= WepSet_FromWeapon(j);
583                 }
584         }
585         else if (s == "none")
586         {
587                 g_weaponarena = 1;
588                 g_weaponarena_list = "No Weapons";
589         }
590         else
591         {
592                 g_weaponarena = 1;
593                 t = tokenize_console(s);
594                 g_weaponarena_list = "";
595                 for (i = 0; i < t; ++i)
596                 {
597                         s = argv(i);
598                         for (j = WEP_FIRST; j <= WEP_LAST; ++j)
599                         {
600                                 e = get_weaponinfo(j);
601                                 if (e.netname == s)
602                                 {
603                                         g_weaponarena_weapons |= WepSet_FromWeapon(j);
604                                         g_weaponarena_list = strcat(g_weaponarena_list, e.message, " & ");
605                                         break;
606                                 }
607                         }
608                         if (j > WEP_LAST)
609                         {
610                                 LOG_INFO("The weapon mutator list contains an unknown weapon ", s, ". Skipped.\n");
611                         }
612                 }
613                 g_weaponarena_list = strzone(substring(g_weaponarena_list, 0, strlen(g_weaponarena_list) - 3));
614         }
615
616         if(g_weaponarena)
617                 g_weaponarena_random = cvar("g_weaponarena_random");
618         else
619                 g_weaponarena_random = 0;
620         g_weaponarena_random_with_blaster = cvar("g_weaponarena_random_with_blaster");
621
622         if (g_weaponarena)
623         {
624                 g_weapon_stay = 0; // incompatible
625                 start_weapons = g_weaponarena_weapons;
626                 start_items |= IT_UNLIMITED_AMMO;
627         }
628         else
629         {
630                 for (i = WEP_FIRST; i <= WEP_LAST; ++i)
631                 {
632                         e = get_weaponinfo(i);
633                         int w = want_weapon(e, false);
634                         if(w & 1)
635                                 start_weapons |= WepSet_FromWeapon(i);
636                         if(w & 2)
637                                 start_weapons_default |= WepSet_FromWeapon(i);
638                         if(w & 4)
639                                 start_weapons_defaultmask |= WepSet_FromWeapon(i);
640                 }
641         }
642
643         if(!cvar("g_use_ammunition"))
644                 start_items |= IT_UNLIMITED_AMMO;
645
646         if(start_items & IT_UNLIMITED_WEAPON_AMMO)
647         {
648                 start_ammo_shells = 999;
649                 start_ammo_nails = 999;
650                 start_ammo_rockets = 999;
651                 start_ammo_cells = 999;
652                 start_ammo_plasma = 999;
653                 start_ammo_fuel = 999;
654         }
655         else
656         {
657                 start_ammo_shells = cvar("g_start_ammo_shells");
658                 start_ammo_nails = cvar("g_start_ammo_nails");
659                 start_ammo_rockets = cvar("g_start_ammo_rockets");
660                 start_ammo_cells = cvar("g_start_ammo_cells");
661                 start_ammo_plasma = cvar("g_start_ammo_plasma");
662                 start_ammo_fuel = cvar("g_start_ammo_fuel");
663         }
664
665         if (warmup_stage)
666         {
667                 warmup_start_ammo_shells = start_ammo_shells;
668                 warmup_start_ammo_nails = start_ammo_nails;
669                 warmup_start_ammo_rockets = start_ammo_rockets;
670                 warmup_start_ammo_cells = start_ammo_cells;
671                 warmup_start_ammo_plasma = start_ammo_plasma;
672                 warmup_start_ammo_fuel = start_ammo_fuel;
673                 warmup_start_health = start_health;
674                 warmup_start_armorvalue = start_armorvalue;
675                 warmup_start_weapons = start_weapons;
676                 warmup_start_weapons_default = start_weapons_default;
677                 warmup_start_weapons_defaultmask = start_weapons_defaultmask;
678
679                 if (!g_weaponarena && !g_ca && !g_freezetag)
680                 {
681                         warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
682                         warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
683                         warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
684                         warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
685                         warmup_start_ammo_plasma = cvar("g_warmup_start_ammo_plasma");
686                         warmup_start_ammo_fuel = cvar("g_warmup_start_ammo_fuel");
687                         warmup_start_health = cvar("g_warmup_start_health");
688                         warmup_start_armorvalue = cvar("g_warmup_start_armor");
689                         warmup_start_weapons = '0 0 0';
690                         warmup_start_weapons_default = '0 0 0';
691                         warmup_start_weapons_defaultmask = '0 0 0';
692                         for (i = WEP_FIRST; i <= WEP_LAST; ++i)
693                         {
694                                 e = get_weaponinfo(i);
695                                 int w = want_weapon(e, g_warmup_allguns);
696                                 if(w & 1)
697                                         warmup_start_weapons |= WepSet_FromWeapon(i);
698                                 if(w & 2)
699                                         warmup_start_weapons_default |= WepSet_FromWeapon(i);
700                                 if(w & 4)
701                                         warmup_start_weapons_defaultmask |= WepSet_FromWeapon(i);
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         for (i = WEP_FIRST; i <= WEP_LAST; ++i)
722         {
723                 e = get_weaponinfo(i);
724                 if(precache_weapons & WepSet_FromWeapon(i)) {
725                         Weapon w = get_weaponinfo(i);
726                         w.wr_init(w);
727                 }
728         }
729
730         start_ammo_shells = max(0, start_ammo_shells);
731         start_ammo_nails = max(0, start_ammo_nails);
732         start_ammo_rockets = max(0, start_ammo_rockets);
733         start_ammo_cells = max(0, start_ammo_cells);
734         start_ammo_plasma = max(0, start_ammo_plasma);
735         start_ammo_fuel = max(0, start_ammo_fuel);
736
737         warmup_start_ammo_shells = max(0, warmup_start_ammo_shells);
738         warmup_start_ammo_nails = max(0, warmup_start_ammo_nails);
739         warmup_start_ammo_rockets = max(0, warmup_start_ammo_rockets);
740         warmup_start_ammo_cells = max(0, warmup_start_ammo_cells);
741         warmup_start_ammo_plasma = max(0, warmup_start_ammo_plasma);
742         warmup_start_ammo_fuel = max(0, warmup_start_ammo_fuel);
743 }
744
745 float sound_allowed(float destin, entity e)
746 {
747     // sounds from world may always pass
748     for (;;)
749     {
750         if (e.classname == "body")
751             e = e.enemy;
752         else if (e.realowner && e.realowner != e)
753             e = e.realowner;
754         else if (e.owner && e.owner != e)
755             e = e.owner;
756         else
757             break;
758     }
759     // sounds to self may always pass
760     if (destin == MSG_ONE)
761         if (e == msg_entity)
762             return true;
763     // sounds by players can be removed
764     if (autocvar_bot_sound_monopoly)
765         if (IS_REAL_CLIENT(e))
766             return false;
767     // anything else may pass
768     return true;
769 }
770
771 void soundtoat(float _dest, entity e, vector o, float chan, string samp, float vol, float attenu)
772 {
773     float entno, idx;
774
775     if (!sound_allowed(_dest, e))
776         return;
777
778     entno = num_for_edict(e);
779     idx = precache_sound_index(samp);
780
781     int sflags;
782     sflags = 0;
783
784     attenu = floor(attenu * 64);
785     vol = floor(vol * 255);
786
787     if (vol != 255)
788         sflags |= SND_VOLUME;
789     if (attenu != 64)
790         sflags |= SND_ATTENUATION;
791     if (entno >= 8192 || chan < 0 || chan > 7)
792         sflags |= SND_LARGEENTITY;
793     if (idx >= 256)
794         sflags |= SND_LARGESOUND;
795
796     WriteByte(_dest, SVC_SOUND);
797     WriteByte(_dest, sflags);
798     if (sflags & SND_VOLUME)
799         WriteByte(_dest, vol);
800     if (sflags & SND_ATTENUATION)
801         WriteByte(_dest, attenu);
802     if (sflags & SND_LARGEENTITY)
803     {
804         WriteShort(_dest, entno);
805         WriteByte(_dest, chan);
806     }
807     else
808     {
809         WriteShort(_dest, entno * 8 + chan);
810     }
811     if (sflags & SND_LARGESOUND)
812         WriteShort(_dest, idx);
813     else
814         WriteByte(_dest, idx);
815
816     WriteCoord(_dest, o.x);
817     WriteCoord(_dest, o.y);
818     WriteCoord(_dest, o.z);
819 }
820 void soundto(float _dest, entity e, float chan, string samp, float vol, float _atten)
821 {
822     vector o;
823
824     if (!sound_allowed(_dest, e))
825         return;
826
827     o = e.origin + 0.5 * (e.mins + e.maxs);
828     soundtoat(_dest, e, o, chan, samp, vol, _atten);
829 }
830 void soundat(entity e, vector o, float chan, string samp, float vol, float _atten)
831 {
832     soundtoat(((chan & 8) ? MSG_ALL : MSG_BROADCAST), e, o, chan, samp, vol, _atten);
833 }
834 void stopsoundto(float _dest, entity e, float chan)
835 {
836     float entno;
837
838     if (!sound_allowed(_dest, e))
839         return;
840
841     entno = num_for_edict(e);
842
843     if (entno >= 8192 || chan < 0 || chan > 7)
844     {
845         float idx, sflags;
846         idx = precache_sound_index(SND(Null));
847         sflags = SND_LARGEENTITY;
848         if (idx >= 256)
849             sflags |= SND_LARGESOUND;
850         WriteByte(_dest, SVC_SOUND);
851         WriteByte(_dest, sflags);
852         WriteShort(_dest, entno);
853         WriteByte(_dest, chan);
854         if (sflags & SND_LARGESOUND)
855             WriteShort(_dest, idx);
856         else
857             WriteByte(_dest, idx);
858         WriteCoord(_dest, e.origin.x);
859         WriteCoord(_dest, e.origin.y);
860         WriteCoord(_dest, e.origin.z);
861     }
862     else
863     {
864         WriteByte(_dest, SVC_STOPSOUND);
865         WriteShort(_dest, entno * 8 + chan);
866     }
867 }
868 void stopsound(entity e, float chan)
869 {
870     if (!sound_allowed(MSG_BROADCAST, e))
871         return;
872
873     stopsoundto(MSG_BROADCAST, e, chan); // unreliable, gets there fast
874     stopsoundto(MSG_ALL, e, chan); // in case of packet loss
875 }
876
877 void play2(entity e, string filename)
878 {
879     //stuffcmd(e, strcat("play2 ", filename, "\n"));
880     msg_entity = e;
881     soundtoat(MSG_ONE, world, '0 0 0', CH_INFO, filename, VOL_BASE, ATTEN_NONE);
882 }
883
884 // use this one if you might be causing spam (e.g. from touch functions that might get called more than once per frame)
885 .float spamtime;
886 float spamsound(entity e, float chan, string samp, float vol, float _atten)
887 {
888     if (!sound_allowed(MSG_BROADCAST, e))
889         return false;
890
891     if (time > e.spamtime)
892     {
893         e.spamtime = time;
894         _sound(e, chan, samp, vol, _atten);
895         return true;
896     }
897     return false;
898 }
899
900 void play2team(float t, string filename)
901 {
902     entity head;
903
904     if (autocvar_bot_sound_monopoly)
905         return;
906
907     FOR_EACH_REALPLAYER(head)
908     {
909         if (head.team == t)
910             play2(head, filename);
911     }
912 }
913
914 void play2all(string samp)
915 {
916     if (autocvar_bot_sound_monopoly)
917         return;
918
919     _sound(world, CH_INFO, samp, VOL_BASE, ATTEN_NONE);
920 }
921
922 void PrecachePlayerSounds(string f);
923 void precache_playermodel(string m)
924 {
925         float globhandle, i, n;
926         string f;
927
928         if(substring(m, -9,5) == "_lod1")
929                 return;
930         if(substring(m, -9,5) == "_lod2")
931                 return;
932         precache_model(m);
933         f = strcat(substring(m, 0, -5), "_lod1", substring(m, -4, -1));
934         if(fexists(f))
935                 precache_model(f);
936         f = strcat(substring(m, 0, -5), "_lod2", substring(m, -4, -1));
937         if(fexists(f))
938                 precache_model(f);
939
940         globhandle = search_begin(strcat(m, "_*.sounds"), true, false);
941         if (globhandle < 0)
942                 return;
943         n = search_getsize(globhandle);
944         for (i = 0; i < n; ++i)
945         {
946                 //print(search_getfilename(globhandle, i), "\n");
947                 f = search_getfilename(globhandle, i);
948                 PrecachePlayerSounds(f);
949         }
950         search_end(globhandle);
951 }
952 void precache_all_playermodels(string pattern)
953 {
954         float globhandle, i, n;
955         string f;
956
957         globhandle = search_begin(pattern, true, false);
958         if (globhandle < 0)
959                 return;
960         n = search_getsize(globhandle);
961         for (i = 0; i < n; ++i)
962         {
963                 //print(search_getfilename(globhandle, i), "\n");
964                 f = search_getfilename(globhandle, i);
965                 precache_playermodel(f);
966         }
967         search_end(globhandle);
968 }
969
970 void precache_playermodels(string s)
971 {
972         if(s != "")
973         {
974                 int n = tokenize_console(s);
975                 precache_playermodel(argv(0));
976
977                 for (int i = 1; i < n; ++i)
978                         precache_model(argv(i));
979         }
980 }
981
982 void precache()
983 {SELFPARAM();
984     // gamemode related things
985
986     // Precache all player models if desired
987     if (autocvar_sv_precacheplayermodels)
988     {
989         PrecachePlayerSounds("sound/player/default.sounds");
990         precache_all_playermodels("models/player/*.zym");
991         precache_all_playermodels("models/player/*.dpm");
992         precache_all_playermodels("models/player/*.md3");
993         precache_all_playermodels("models/player/*.psk");
994         precache_all_playermodels("models/player/*.iqm");
995     }
996
997     if (autocvar_sv_defaultcharacter)
998     {
999                 precache_playermodels(autocvar_sv_defaultplayermodel_red);
1000                 precache_playermodels(autocvar_sv_defaultplayermodel_blue);
1001                 precache_playermodels(autocvar_sv_defaultplayermodel_yellow);
1002                 precache_playermodels(autocvar_sv_defaultplayermodel_pink);
1003                 precache_playermodels(autocvar_sv_defaultplayermodel);
1004     }
1005
1006     if (g_footsteps)
1007     {
1008         PrecacheGlobalSound((globalsound_step = "misc/footstep0 6"));
1009         PrecacheGlobalSound((globalsound_metalstep = "misc/metalfootstep0 6"));
1010     }
1011
1012     // gore and miscellaneous sounds
1013     PrecacheGlobalSound((globalsound_fall = "misc/hitground 4"));
1014     PrecacheGlobalSound((globalsound_metalfall = "misc/metalhitground 4"));
1015
1016 #if 0
1017     // Disabled this code because it simply does not work (e.g. ignores bgmvolume, overlaps with "cd loop" controlled tracks).
1018
1019     if (!self.noise && self.music) // quake 3 uses the music field
1020         self.noise = self.music;
1021
1022     // plays music for the level if there is any
1023     if (self.noise)
1024     {
1025         precache_sound (self.noise);
1026         ambientsound ('0 0 0', self.noise, VOL_BASE, ATTEN_NONE);
1027     }
1028 #endif
1029 }
1030
1031
1032 void make_safe_for_remove(entity e)
1033 {
1034     if (e.initialize_entity)
1035     {
1036         entity ent, prev = world;
1037         for (ent = initialize_entity_first; ent; )
1038         {
1039             if ((ent == e) || ((ent.classname == "initialize_entity") && (ent.enemy == e)))
1040             {
1041                 //print("make_safe_for_remove: getting rid of initializer ", etos(ent), "\n");
1042                 // skip it in linked list
1043                 if (prev)
1044                 {
1045                     prev.initialize_entity_next = ent.initialize_entity_next;
1046                     ent = prev.initialize_entity_next;
1047                 }
1048                 else
1049                 {
1050                     initialize_entity_first = ent.initialize_entity_next;
1051                     ent = initialize_entity_first;
1052                 }
1053             }
1054             else
1055             {
1056                 prev = ent;
1057                 ent = ent.initialize_entity_next;
1058             }
1059         }
1060     }
1061 }
1062
1063 void objerror(string s)
1064 {SELFPARAM();
1065     make_safe_for_remove(self);
1066     builtin_objerror(s);
1067 }
1068
1069 .float remove_except_protected_forbidden;
1070 void remove_except_protected(entity e)
1071 {
1072         if(e.remove_except_protected_forbidden)
1073                 error("not allowed to remove this at this point");
1074         builtin_remove(e);
1075 }
1076
1077 void remove_unsafely(entity e)
1078 {
1079     if(e.classname == "spike")
1080         error("Removing spikes is forbidden (crylink bug), please report");
1081     builtin_remove(e);
1082 }
1083
1084 void remove_safely(entity e)
1085 {
1086     make_safe_for_remove(e);
1087     builtin_remove(e);
1088 }
1089
1090 void InitializeEntity(entity e, void(void) func, float order)
1091 {
1092     entity prev, cur;
1093
1094     if (!e || e.initialize_entity)
1095     {
1096         // make a proxy initializer entity
1097         entity e_old = e;
1098         e = new(initialize_entity);
1099         e.enemy = e_old;
1100     }
1101
1102     e.initialize_entity = func;
1103     e.initialize_entity_order = order;
1104
1105     cur = initialize_entity_first;
1106     prev = world;
1107     for (;;)
1108     {
1109         if (!cur || cur.initialize_entity_order > order)
1110         {
1111             // insert between prev and cur
1112             if (prev)
1113                 prev.initialize_entity_next = e;
1114             else
1115                 initialize_entity_first = e;
1116             e.initialize_entity_next = cur;
1117             return;
1118         }
1119         prev = cur;
1120         cur = cur.initialize_entity_next;
1121     }
1122 }
1123 void InitializeEntitiesRun()
1124 {SELFPARAM();
1125     entity startoflist = initialize_entity_first;
1126     initialize_entity_first = NULL;
1127     remove = remove_except_protected;
1128     for (entity e = startoflist; e; e = e.initialize_entity_next)
1129     {
1130                 e.remove_except_protected_forbidden = 1;
1131     }
1132     for (entity e = startoflist; e; )
1133     {
1134                 e.remove_except_protected_forbidden = 0;
1135         e.initialize_entity_order = 0;
1136         entity next = e.initialize_entity_next;
1137         e.initialize_entity_next = NULL;
1138         var void() func = e.initialize_entity;
1139         e.initialize_entity = func_null;
1140         if (e.classname == "initialize_entity")
1141         {
1142             entity wrappee = e.enemy;
1143             builtin_remove(e);
1144             e = wrappee;
1145         }
1146         //dprint("Delayed initialization: ", e.classname, "\n");
1147         if (func)
1148         {
1149                 WITH(entity, self, e, func());
1150         }
1151         else
1152         {
1153             eprint(e);
1154             backtrace(strcat("Null function in: ", e.classname, "\n"));
1155         }
1156         e = next;
1157     }
1158     remove = remove_unsafely;
1159 }
1160
1161 .float(entity) isEliminated;
1162 bool EliminatedPlayers_SendEntity(entity this, entity to, float sendflags)
1163 {
1164         float i, f, b;
1165         entity e;
1166         WriteByte(MSG_ENTITY, ENT_CLIENT_ELIMINATEDPLAYERS);
1167         WriteByte(MSG_ENTITY, sendflags);
1168
1169         if(sendflags & 1)
1170         {
1171                 for(i = 1; i <= maxclients; i += 8)
1172                 {
1173                         for(f = 0, e = edict_num(i), b = 1; b < 256; b *= 2, e = nextent(e))
1174                         {
1175                                 if(eliminatedPlayers.isEliminated(e))
1176                                         f |= b;
1177                         }
1178                         WriteByte(MSG_ENTITY, f);
1179                 }
1180         }
1181
1182         return true;
1183 }
1184
1185 void EliminatedPlayers_Init(float(entity) isEliminated_func)
1186 {
1187         if(eliminatedPlayers)
1188         {
1189                 backtrace("Can't spawn eliminatedPlayers again!");
1190                 return;
1191         }
1192         Net_LinkEntity(eliminatedPlayers = spawn(), false, 0, EliminatedPlayers_SendEntity);
1193         eliminatedPlayers.isEliminated = isEliminated_func;
1194 }
1195
1196
1197 void adaptor_think2touch()
1198 {SELFPARAM();
1199     entity o;
1200     o = other;
1201     other = world;
1202     self.touch();
1203     other = o;
1204 }
1205
1206 void adaptor_think2use()
1207 {SELFPARAM();
1208     entity o, a;
1209     o = other;
1210     a = activator;
1211     activator = world;
1212     other = world;
1213     self.use();
1214     other = o;
1215     activator = a;
1216 }
1217
1218 void adaptor_think2use_hittype_splash() // for timed projectile detonation
1219 {SELFPARAM();
1220         if(!(self.flags & FL_ONGROUND)) // if onground, we ARE touching something, but HITTYPE_SPLASH is to be networked if the damage causing projectile is not touching ANYTHING
1221                 self.projectiledeathtype |= HITTYPE_SPLASH;
1222         adaptor_think2use();
1223 }
1224
1225 // deferred dropping
1226 void DropToFloor_Handler()
1227 {SELFPARAM();
1228     builtin_droptofloor();
1229     self.dropped_origin = self.origin;
1230 }
1231
1232 void droptofloor()
1233 {SELFPARAM();
1234     InitializeEntity(self, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
1235 }
1236
1237
1238
1239 float trace_hits_box_a0, trace_hits_box_a1;
1240
1241 float trace_hits_box_1d(float end, float thmi, float thma)
1242 {
1243     if (end == 0)
1244     {
1245         // just check if x is in range
1246         if (0 < thmi)
1247             return false;
1248         if (0 > thma)
1249             return false;
1250     }
1251     else
1252     {
1253         // do the trace with respect to x
1254         // 0 -> end has to stay in thmi -> thma
1255         trace_hits_box_a0 = max(trace_hits_box_a0, min(thmi / end, thma / end));
1256         trace_hits_box_a1 = min(trace_hits_box_a1, max(thmi / end, thma / end));
1257         if (trace_hits_box_a0 > trace_hits_box_a1)
1258             return false;
1259     }
1260     return true;
1261 }
1262
1263 float trace_hits_box(vector start, vector end, vector thmi, vector thma)
1264 {
1265     end -= start;
1266     thmi -= start;
1267     thma -= start;
1268     // now it is a trace from 0 to end
1269
1270     trace_hits_box_a0 = 0;
1271     trace_hits_box_a1 = 1;
1272
1273     if (!trace_hits_box_1d(end.x, thmi.x, thma.x))
1274         return false;
1275     if (!trace_hits_box_1d(end.y, thmi.y, thma.y))
1276         return false;
1277     if (!trace_hits_box_1d(end.z, thmi.z, thma.z))
1278         return false;
1279
1280     return true;
1281 }
1282
1283 float tracebox_hits_box(vector start, vector mi, vector ma, vector end, vector thmi, vector thma)
1284 {
1285     return trace_hits_box(start, end, thmi - ma, thma - mi);
1286 }
1287
1288 float SUB_NoImpactCheck()
1289 {SELFPARAM();
1290         // zero hitcontents = this is not the real impact, but either the
1291         // mirror-impact of something hitting the projectile instead of the
1292         // projectile hitting the something, or a touchareagrid one. Neither of
1293         // these stop the projectile from moving, so...
1294         if(trace_dphitcontents == 0)
1295         {
1296                 //dprint("A hit happened with zero hit contents... DEBUG THIS, this should never happen for projectiles! Projectile will self-destruct.\n");
1297                 LOG_TRACEF("A hit from a projectile happened with no hit contents! DEBUG THIS, this should never happen for projectiles! Profectile will self-destruct. (edict: %d, classname: %s, origin: %s)\n", num_for_edict(self), self.classname, vtos(self.origin));
1298                 checkclient();
1299         }
1300     if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1301         return 1;
1302     if (other == world && self.size != '0 0 0')
1303     {
1304         vector tic;
1305         tic = self.velocity * sys_frametime;
1306         tic = tic + normalize(tic) * vlen(self.maxs - self.mins);
1307         traceline(self.origin - tic, self.origin + tic, MOVE_NORMAL, self);
1308         if (trace_fraction >= 1)
1309         {
1310             LOG_TRACE("Odd... did not hit...?\n");
1311         }
1312         else if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1313         {
1314             LOG_TRACE("Detected and prevented the sky-grapple bug.\n");
1315             return 1;
1316         }
1317     }
1318
1319     return 0;
1320 }
1321
1322 #define SUB_OwnerCheck() (other && (other == self.owner))
1323
1324 void W_Crylink_Dequeue(entity e);
1325 float WarpZone_Projectile_Touch_ImpactFilter_Callback()
1326 {SELFPARAM();
1327         if(SUB_OwnerCheck())
1328                 return true;
1329         if(SUB_NoImpactCheck())
1330         {
1331                 if(self.classname == "nade")
1332                         return false; // no checks here
1333                 else if(self.classname == "grapplinghook")
1334                         RemoveGrapplingHook(self.realowner);
1335                 else if(self.classname == "spike")
1336                 {
1337                         W_Crylink_Dequeue(self);
1338                         remove(self);
1339                 }
1340                 else
1341                         remove(self);
1342                 return true;
1343         }
1344         if(trace_ent && trace_ent.solid > SOLID_TRIGGER)
1345                 UpdateCSQCProjectile(self);
1346         return false;
1347 }
1348
1349
1350 void URI_Get_Callback(float id, float status, string data)
1351 {
1352         if(url_URI_Get_Callback(id, status, data))
1353         {
1354                 // handled
1355         }
1356         else if (id == URI_GET_DISCARD)
1357         {
1358                 // discard
1359         }
1360         else if (id >= URI_GET_CURL && id <= URI_GET_CURL_END)
1361         {
1362                 // sv_cmd curl
1363                 Curl_URI_Get_Callback(id, status, data);
1364         }
1365         else if (id >= URI_GET_IPBAN && id <= URI_GET_IPBAN_END)
1366         {
1367                 // online ban list
1368                 OnlineBanList_URI_Get_Callback(id, status, data);
1369         }
1370         else
1371         {
1372                 LOG_INFO("Received HTTP request data for an invalid id ", ftos(id), ".\n");
1373         }
1374 }
1375
1376 string uid2name(string myuid) {
1377         string s;
1378         s = db_get(ServerProgsDB, strcat("/uid2name/", myuid));
1379
1380         // FIXME remove this later after 0.6 release
1381         // convert old style broken records to correct style
1382         if(s == "")
1383         {
1384                 s = db_get(ServerProgsDB, strcat("uid2name", myuid));
1385                 if(s != "")
1386                 {
1387                         db_put(ServerProgsDB, strcat("/uid2name/", myuid), s);
1388                         db_put(ServerProgsDB, strcat("uid2name", myuid), "");
1389                 }
1390         }
1391
1392         if(s == "")
1393                 s = "^1Unregistered Player";
1394         return s;
1395 }
1396
1397 float MoveToRandomLocationWithinBounds(entity e, vector boundmin, vector boundmax, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1398 {
1399     float m, i;
1400     vector start, org, delta, end, enddown, mstart;
1401     entity sp;
1402
1403     m = e.dphitcontentsmask;
1404     e.dphitcontentsmask = goodcontents | badcontents;
1405
1406     org = boundmin;
1407     delta = boundmax - boundmin;
1408
1409     start = end = org;
1410
1411     for (i = 0; i < attempts; ++i)
1412     {
1413         start.x = org.x + random() * delta.x;
1414         start.y = org.y + random() * delta.y;
1415         start.z = org.z + random() * delta.z;
1416
1417         // rule 1: start inside world bounds, and outside
1418         // solid, and don't start from somewhere where you can
1419         // fall down to evil
1420         tracebox(start, e.mins, e.maxs, start - '0 0 1' * delta.z, MOVE_NORMAL, e);
1421         if (trace_fraction >= 1)
1422             continue;
1423         if (trace_startsolid)
1424             continue;
1425         if (trace_dphitcontents & badcontents)
1426             continue;
1427         if (trace_dphitq3surfaceflags & badsurfaceflags)
1428             continue;
1429
1430         // rule 2: if we are too high, lower the point
1431         if (trace_fraction * delta.z > maxaboveground)
1432             start = trace_endpos + '0 0 1' * maxaboveground;
1433         enddown = trace_endpos;
1434
1435         // rule 3: make sure we aren't outside the map. This only works
1436         // for somewhat well formed maps. A good rule of thumb is that
1437         // the map should have a convex outside hull.
1438         // these can be traceLINES as we already verified the starting box
1439         mstart = start + 0.5 * (e.mins + e.maxs);
1440         traceline(mstart, mstart + '1 0 0' * delta.x, MOVE_NORMAL, e);
1441         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1442             continue;
1443         traceline(mstart, mstart - '1 0 0' * delta.x, MOVE_NORMAL, e);
1444         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1445             continue;
1446         traceline(mstart, mstart + '0 1 0' * delta.y, MOVE_NORMAL, e);
1447         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1448             continue;
1449         traceline(mstart, mstart - '0 1 0' * delta.y, MOVE_NORMAL, e);
1450         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1451             continue;
1452         traceline(mstart, mstart + '0 0 1' * delta.z, MOVE_NORMAL, e);
1453         if (trace_fraction >= 1 || trace_dphittexturename == "common/caulk")
1454             continue;
1455
1456         // rule 4: we must "see" some spawnpoint or item
1457         for(sp = world; (sp = find(sp, classname, "info_player_deathmatch")); )
1458                 if(checkpvs(mstart, sp))
1459                         if((traceline(mstart, sp.origin, MOVE_NORMAL, e), trace_fraction) >= 1)
1460                                 break;
1461         if(!sp)
1462         {
1463                 for(sp = world; (sp = findflags(sp, flags, FL_ITEM)); )
1464                         if(checkpvs(mstart, sp))
1465                                 if((traceline(mstart, sp.origin + (sp.mins + sp.maxs) * 0.5, MOVE_NORMAL, e), trace_fraction) >= 1)
1466                                         break;
1467                 if(!sp)
1468                         continue;
1469         }
1470
1471         // find a random vector to "look at"
1472         end.x = org.x + random() * delta.x;
1473         end.y = org.y + random() * delta.y;
1474         end.z = org.z + random() * delta.z;
1475         end = start + normalize(end - start) * vlen(delta);
1476
1477         // rule 4: start TO end must not be too short
1478         tracebox(start, e.mins, e.maxs, end, MOVE_NORMAL, e);
1479         if (trace_startsolid)
1480             continue;
1481         if (trace_fraction < minviewdistance / vlen(delta))
1482             continue;
1483
1484         // rule 5: don't want to look at sky
1485         if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY)
1486             continue;
1487
1488         // rule 6: we must not end up in trigger_hurt
1489         if (tracebox_hits_trigger_hurt(start, e.mins, e.maxs, enddown))
1490             continue;
1491
1492         break;
1493     }
1494
1495     e.dphitcontentsmask = m;
1496
1497     if (i < attempts)
1498     {
1499         setorigin(e, start);
1500         e.angles = vectoangles(end - start);
1501         LOG_TRACE("Needed ", ftos(i + 1), " attempts\n");
1502         return true;
1503     }
1504     else
1505         return false;
1506 }
1507
1508 float MoveToRandomMapLocation(entity e, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1509 {
1510         return MoveToRandomLocationWithinBounds(e, world.mins, world.maxs, goodcontents, badcontents, badsurfaceflags, attempts, maxaboveground, minviewdistance);
1511 }
1512
1513 void write_recordmarker(entity pl, float tstart, float dt)
1514 {
1515     GameLogEcho(strcat(":recordset:", ftos(pl.playerid), ":", ftos(dt)));
1516
1517     // also write a marker into demo files for demotc-race-record-extractor to find
1518     stuffcmd(pl,
1519              strcat(
1520                  strcat("//", strconv(2, 0, 0, GetGametype()), " RECORD SET ", TIME_ENCODED_TOSTRING(TIME_ENCODE(dt))),
1521                  " ", ftos(tstart), " ", ftos(dt), "\n"));
1522 }
1523
1524 void attach_sameorigin(entity e, entity to, string tag)
1525 {
1526     vector org, t_forward, t_left, t_up, e_forward, e_up;
1527     float tagscale;
1528
1529     org = e.origin - gettaginfo(to, gettagindex(to, tag));
1530     tagscale = pow(vlen(v_forward), -2); // undo a scale on the tag
1531     t_forward = v_forward * tagscale;
1532     t_left = v_right * -tagscale;
1533     t_up = v_up * tagscale;
1534
1535     e.origin_x = org * t_forward;
1536     e.origin_y = org * t_left;
1537     e.origin_z = org * t_up;
1538
1539     // current forward and up directions
1540     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1541                 e.angles = AnglesTransform_FromVAngles(e.angles);
1542         else
1543                 e.angles = AnglesTransform_FromAngles(e.angles);
1544     fixedmakevectors(e.angles);
1545
1546     // untransform forward, up!
1547     e_forward.x = v_forward * t_forward;
1548     e_forward.y = v_forward * t_left;
1549     e_forward.z = v_forward * t_up;
1550     e_up.x = v_up * t_forward;
1551     e_up.y = v_up * t_left;
1552     e_up.z = v_up * t_up;
1553
1554     e.angles = fixedvectoangles2(e_forward, e_up);
1555     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1556                 e.angles = AnglesTransform_ToVAngles(e.angles);
1557         else
1558                 e.angles = AnglesTransform_ToAngles(e.angles);
1559
1560     setattachment(e, to, tag);
1561     setorigin(e, e.origin);
1562 }
1563
1564 void detach_sameorigin(entity e)
1565 {
1566     vector org;
1567     org = gettaginfo(e, 0);
1568     e.angles = fixedvectoangles2(v_forward, v_up);
1569     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1570                 e.angles = AnglesTransform_ToVAngles(e.angles);
1571         else
1572                 e.angles = AnglesTransform_ToAngles(e.angles);
1573     setorigin(e, org);
1574     setattachment(e, world, "");
1575     setorigin(e, e.origin);
1576 }
1577
1578 void follow_sameorigin(entity e, entity to)
1579 {
1580     e.movetype = MOVETYPE_FOLLOW; // make the hole follow
1581     e.aiment = to; // make the hole follow bmodel
1582     e.punchangle = to.angles; // the original angles of bmodel
1583     e.view_ofs = e.origin - to.origin; // relative origin
1584     e.v_angle = e.angles - to.angles; // relative angles
1585 }
1586
1587 void unfollow_sameorigin(entity e)
1588 {
1589     e.movetype = MOVETYPE_NONE;
1590 }
1591
1592 entity gettaginfo_relative_ent;
1593 vector gettaginfo_relative(entity e, float tag)
1594 {
1595     if (!gettaginfo_relative_ent)
1596     {
1597         gettaginfo_relative_ent = spawn();
1598         gettaginfo_relative_ent.effects = EF_NODRAW;
1599     }
1600     gettaginfo_relative_ent.model = e.model;
1601     gettaginfo_relative_ent.modelindex = e.modelindex;
1602     gettaginfo_relative_ent.frame = e.frame;
1603     return gettaginfo(gettaginfo_relative_ent, tag);
1604 }
1605
1606 .float scale2;
1607
1608 bool modeleffect_SendEntity(entity this, entity to, int sf)
1609 {
1610         float f;
1611         WriteByte(MSG_ENTITY, ENT_CLIENT_MODELEFFECT);
1612
1613         f = 0;
1614         if(self.velocity != '0 0 0')
1615                 f |= 1;
1616         if(self.angles != '0 0 0')
1617                 f |= 2;
1618         if(self.avelocity != '0 0 0')
1619                 f |= 4;
1620
1621         WriteByte(MSG_ENTITY, f);
1622         WriteShort(MSG_ENTITY, self.modelindex);
1623         WriteByte(MSG_ENTITY, self.skin);
1624         WriteByte(MSG_ENTITY, self.frame);
1625         WriteCoord(MSG_ENTITY, self.origin.x);
1626         WriteCoord(MSG_ENTITY, self.origin.y);
1627         WriteCoord(MSG_ENTITY, self.origin.z);
1628         if(f & 1)
1629         {
1630                 WriteCoord(MSG_ENTITY, self.velocity.x);
1631                 WriteCoord(MSG_ENTITY, self.velocity.y);
1632                 WriteCoord(MSG_ENTITY, self.velocity.z);
1633         }
1634         if(f & 2)
1635         {
1636                 WriteCoord(MSG_ENTITY, self.angles.x);
1637                 WriteCoord(MSG_ENTITY, self.angles.y);
1638                 WriteCoord(MSG_ENTITY, self.angles.z);
1639         }
1640         if(f & 4)
1641         {
1642                 WriteCoord(MSG_ENTITY, self.avelocity.x);
1643                 WriteCoord(MSG_ENTITY, self.avelocity.y);
1644                 WriteCoord(MSG_ENTITY, self.avelocity.z);
1645         }
1646         WriteShort(MSG_ENTITY, self.scale * 256.0);
1647         WriteShort(MSG_ENTITY, self.scale2 * 256.0);
1648         WriteByte(MSG_ENTITY, self.teleport_time * 100.0);
1649         WriteByte(MSG_ENTITY, self.fade_time * 100.0);
1650         WriteByte(MSG_ENTITY, self.alpha * 255.0);
1651
1652         return true;
1653 }
1654
1655 void modeleffect_spawn(string m, float s, float f, vector o, vector v, vector ang, vector angv, float s0, float s2, float a, float t1, float t2)
1656 {
1657         entity e;
1658         float sz;
1659         e = spawn();
1660         e.classname = "modeleffect";
1661         _setmodel(e, m);
1662         e.frame = f;
1663         setorigin(e, o);
1664         e.velocity = v;
1665         e.angles = ang;
1666         e.avelocity = angv;
1667         e.alpha = a;
1668         e.teleport_time = t1;
1669         e.fade_time = t2;
1670         e.skin = s;
1671         if(s0 >= 0)
1672                 e.scale = s0 / max6(-e.mins.x, -e.mins.y, -e.mins.z, e.maxs.x, e.maxs.y, e.maxs.z);
1673         else
1674                 e.scale = -s0;
1675         if(s2 >= 0)
1676                 e.scale2 = s2 / max6(-e.mins.x, -e.mins.y, -e.mins.z, e.maxs.x, e.maxs.y, e.maxs.z);
1677         else
1678                 e.scale2 = -s2;
1679         sz = max(e.scale, e.scale2);
1680         setsize(e, e.mins * sz, e.maxs * sz);
1681         Net_LinkEntity(e, false, 0.1, modeleffect_SendEntity);
1682 }
1683
1684 void shockwave_spawn(string m, vector org, float sz, float t1, float t2)
1685 {
1686         return modeleffect_spawn(m, 0, 0, org, '0 0 0', '0 0 0', '0 0 0', 0, sz, 1, t1, t2);
1687 }
1688
1689 float randombit(float bits)
1690 {
1691         if(!(bits & (bits-1))) // this ONLY holds for powers of two!
1692                 return bits;
1693
1694         float n, f, b, r;
1695
1696         r = random();
1697         b = 0;
1698         n = 0;
1699
1700         for(f = 1; f <= bits; f *= 2)
1701         {
1702                 if(bits & f)
1703                 {
1704                         ++n;
1705                         r *= n;
1706                         if(r <= 1)
1707                                 b = f;
1708                         else
1709                                 r = (r - 1) / (n - 1);
1710                 }
1711         }
1712
1713         return b;
1714 }
1715
1716 float randombits(float bits, float k, float error_return)
1717 {
1718         float r;
1719         r = 0;
1720         while(k > 0 && bits != r)
1721         {
1722                 r += randombit(bits - r);
1723                 --k;
1724         }
1725         if(error_return)
1726                 if(k > 0)
1727                         return -1; // all
1728         return r;
1729 }
1730
1731 void randombit_test(float bits, float iter)
1732 {
1733         while(iter > 0)
1734         {
1735                 LOG_INFO(ftos(randombit(bits)), "\n");
1736                 --iter;
1737         }
1738 }
1739
1740 float ExponentialFalloff(float mindist, float maxdist, float halflifedist, float d)
1741 {
1742         if(halflifedist > 0)
1743                 return pow(0.5, (bound(mindist, d, maxdist) - mindist) / halflifedist);
1744         else if(halflifedist < 0)
1745                 return pow(0.5, (bound(mindist, d, maxdist) - maxdist) / halflifedist);
1746         else
1747                 return 1;
1748 }
1749
1750
1751 .string aiment_classname;
1752 .float aiment_deadflag;
1753 void SetMovetypeFollow(entity ent, entity e)
1754 {
1755         // FIXME this may not be warpzone aware
1756         ent.movetype = MOVETYPE_FOLLOW; // make the hole follow
1757         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.
1758         ent.aiment = e; // make the hole follow bmodel
1759         ent.punchangle = e.angles; // the original angles of bmodel
1760         ent.view_ofs = ent.origin - e.origin; // relative origin
1761         ent.v_angle = ent.angles - e.angles; // relative angles
1762         ent.aiment_classname = strzone(e.classname);
1763         ent.aiment_deadflag = e.deadflag;
1764 }
1765 void UnsetMovetypeFollow(entity ent)
1766 {
1767         ent.movetype = MOVETYPE_FLY;
1768         PROJECTILE_MAKETRIGGER(ent);
1769         ent.aiment = world;
1770 }
1771 float LostMovetypeFollow(entity ent)
1772 {
1773 /*
1774         if(ent.movetype != MOVETYPE_FOLLOW)
1775                 if(ent.aiment)
1776                         error("???");
1777 */
1778         if(ent.aiment)
1779         {
1780                 if(ent.aiment.classname != ent.aiment_classname)
1781                         return 1;
1782                 if(ent.aiment.deadflag != ent.aiment_deadflag)
1783                         return 1;
1784         }
1785         return 0;
1786 }
1787
1788 float isPushable(entity e)
1789 {
1790         if(e.pushable)
1791                 return true;
1792         if(IS_VEHICLE(e))
1793                 return false;
1794         if(e.iscreature)
1795                 return true;
1796         switch(e.classname)
1797         {
1798                 case "body":
1799                 case "droppedweapon":
1800                 case "keepawayball":
1801                 case "nexball_basketball":
1802                 case "nexball_football":
1803                         return true;
1804                 case "bullet": // antilagged bullets can't hit this either
1805                         return false;
1806         }
1807         if (e.projectiledeathtype)
1808                 return true;
1809         return false;
1810 }