]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/miscfunctions.qc
Fix kill/teamchange/spectate not working in vehicles
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / miscfunctions.qc
1 var void remove(entity e);
2 void objerror(string s);
3 void droptofloor();
4 .vector dropped_origin;
5
6 void traceline_antilag (entity source, vector v1, vector v2, float nomonst, entity forent, float lag);
7 void crosshair_trace(entity pl)
8 {
9         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));
10 }
11 void crosshair_trace_plusvisibletriggers(entity pl)
12 {
13         entity first;
14         entity e;
15         first = findchainfloat(solid, SOLID_TRIGGER);
16
17         for (e = first; e; e = e.chain)
18                 if (e.model != "")
19                         e.solid = SOLID_BSP;
20
21         crosshair_trace(pl);
22
23         for (e = first; e; e = e.chain)
24                 e.solid = SOLID_TRIGGER;
25 }
26 void WarpZone_traceline_antilag (entity source, vector v1, vector v2, float nomonst, entity forent, float lag);
27 void WarpZone_crosshair_trace(entity pl)
28 {
29         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));
30 }
31
32 void() spawnfunc_info_player_deathmatch; // needed for the other spawnpoints
33 void() spawnpoint_use;
34 string GetMapname();
35 string ColoredTeamName(float t);
36
37 string admin_name(void)
38 {
39         if(autocvar_sv_adminnick != "")
40                 return autocvar_sv_adminnick;
41         else
42                 return "SERVER ADMIN";
43 }
44
45 float DistributeEvenly_amount;
46 float DistributeEvenly_totalweight;
47 void DistributeEvenly_Init(float amount, float totalweight)
48 {
49     if (DistributeEvenly_amount)
50     {
51         dprint("DistributeEvenly_Init: UNFINISHED DISTRIBUTION (", ftos(DistributeEvenly_amount), " for ");
52         dprint(ftos(DistributeEvenly_totalweight), " left!)\n");
53     }
54     if (totalweight == 0)
55         DistributeEvenly_amount = 0;
56     else
57         DistributeEvenly_amount = amount;
58     DistributeEvenly_totalweight = totalweight;
59 }
60 float DistributeEvenly_Get(float weight)
61 {
62     float f;
63     if (weight <= 0)
64         return 0;
65     f = floor(0.5 + DistributeEvenly_amount * weight / DistributeEvenly_totalweight);
66     DistributeEvenly_totalweight -= weight;
67     DistributeEvenly_amount -= f;
68     return f;
69 }
70 float DistributeEvenly_GetRandomized(float weight)
71 {
72     float f;
73     if (weight <= 0)
74         return 0;
75     f = floor(random() + DistributeEvenly_amount * weight / DistributeEvenly_totalweight);
76     DistributeEvenly_totalweight -= weight;
77     DistributeEvenly_amount -= f;
78     return f;
79 }
80
81 #define move_out_of_solid(e) WarpZoneLib_MoveOutOfSolid(e)
82
83
84 string STR_PLAYER = "player";
85 string STR_SPECTATOR = "spectator";
86 string STR_OBSERVER = "observer";
87
88 #if 0
89 #define FOR_EACH_CLIENT(v) for(v = world; (v = findflags(v, flags, FL_CLIENT)) != world; )
90 #define FOR_EACH_REALCLIENT(v) FOR_EACH_CLIENT(v) if(clienttype(v) == CLIENTTYPE_REAL)
91 #define FOR_EACH_PLAYER(v) for(v = world; (v = find(v, classname, STR_PLAYER)) != world; )
92 #define FOR_EACH_REALPLAYER(v) FOR_EACH_PLAYER(v) if(clienttype(v) == CLIENTTYPE_REAL)
93 #else
94 #define FOR_EACH_CLIENTSLOT(v) for(v = world; (v = nextent(v)) && (num_for_edict(v) <= maxclients); )
95 #define FOR_EACH_CLIENT(v) FOR_EACH_CLIENTSLOT(v) if(v.flags & FL_CLIENT)
96 #define FOR_EACH_REALCLIENT(v) FOR_EACH_CLIENT(v) if(clienttype(v) == CLIENTTYPE_REAL)
97 #define FOR_EACH_PLAYER(v) FOR_EACH_CLIENT(v) if(v.classname == STR_PLAYER)
98 #define FOR_EACH_REALPLAYER(v) FOR_EACH_REALCLIENT(v) if(v.classname == STR_PLAYER)
99 #endif
100
101 // copies a string to a tempstring (so one can strunzone it)
102 string strcat1(string s) = #115; // FRIK_FILE
103
104 float logfile_open;
105 float logfile;
106
107 void bcenterprint(string s)
108 {
109     // TODO replace by MSG_ALL (would show it to spectators too, though)?
110     entity head;
111     FOR_EACH_PLAYER(head)
112     if (clienttype(head) == CLIENTTYPE_REAL)
113         centerprint(head, s);
114 }
115
116 void GameLogEcho(string s)
117 {
118     string fn;
119     float matches;
120
121     if (autocvar_sv_eventlog_files)
122     {
123         if (!logfile_open)
124         {
125             logfile_open = TRUE;
126             matches = autocvar_sv_eventlog_files_counter + 1;
127             cvar_set("sv_eventlog_files_counter", ftos(matches));
128             fn = ftos(matches);
129             if (strlen(fn) < 8)
130                 fn = strcat(substring("00000000", 0, 8 - strlen(fn)), fn);
131             fn = strcat(autocvar_sv_eventlog_files_nameprefix, fn, autocvar_sv_eventlog_files_namesuffix);
132             logfile = fopen(fn, FILE_APPEND);
133             fputs(logfile, ":logversion:3\n");
134         }
135         if (logfile >= 0)
136         {
137             if (autocvar_sv_eventlog_files_timestamps)
138                 fputs(logfile, strcat(":time:", strftime(TRUE, "%Y-%m-%d %H:%M:%S", "\n", s, "\n")));
139             else
140                 fputs(logfile, strcat(s, "\n"));
141         }
142     }
143     if (autocvar_sv_eventlog_console)
144     {
145         print(s, "\n");
146     }
147 }
148
149 void GameLogInit()
150 {
151     logfile_open = 0;
152     // will be opened later
153 }
154
155 void GameLogClose()
156 {
157     if (logfile_open && logfile >= 0)
158     {
159         fclose(logfile);
160         logfile = -1;
161     }
162 }
163
164 float spawnpoint_nag;
165 void relocate_spawnpoint()
166 {
167     // nudge off the floor
168     setorigin(self, self.origin + '0 0 1');
169
170     tracebox(self.origin, PL_MIN, PL_MAX, self.origin, TRUE, self);
171     if (trace_startsolid)
172     {
173         vector o;
174         o = self.origin;
175         self.mins = PL_MIN;
176         self.maxs = PL_MAX;
177         if (!move_out_of_solid(self))
178             objerror("could not get out of solid at all!");
179         print("^1NOTE: this map needs FIXING. Spawnpoint at ", vtos(o - '0 0 1'));
180         print(" needs to be moved out of solid, e.g. by '", ftos(self.origin_x - o_x));
181         print(" ", ftos(self.origin_y - o_y));
182         print(" ", ftos(self.origin_z - o_z), "'\n");
183         if (autocvar_g_spawnpoints_auto_move_out_of_solid)
184         {
185             if (!spawnpoint_nag)
186                 print("\{1}^1NOTE: this map needs FIXING (it contains spawnpoints in solid, see server log)\n");
187             spawnpoint_nag = 1;
188         }
189         else
190         {
191             setorigin(self, o);
192             self.mins = self.maxs = '0 0 0';
193             objerror("player spawn point in solid, mapper sucks!\n");
194             return;
195         }
196     }
197
198     self.use = spawnpoint_use;
199     self.team_saved = self.team;
200     if (!self.cnt)
201         self.cnt = 1;
202
203     if (have_team_spawns != 0)
204         if (self.team)
205             have_team_spawns = 1;
206     have_team_spawns_forteam[self.team] = 1;
207
208     if (autocvar_r_showbboxes)
209     {
210         // show where spawnpoints point at too
211         makevectors(self.angles);
212         entity e;
213         e = spawn();
214         e.classname = "info_player_foo";
215         setorigin(e, self.origin + v_forward * 24);
216         setsize(e, '-8 -8 -8', '8 8 8');
217         e.solid = SOLID_TRIGGER;
218     }
219 }
220
221 #define strstr strstrofs
222 /*
223 // NOTE: DO NOT USE THIS FUNCTION TOO OFTEN.
224 // IT WILL MOST PROBABLY DESTROY _ALL_ OTHER TEMP
225 // STRINGS AND TAKE QUITE LONG. haystack and needle MUST
226 // BE CONSTANT OR strzoneD!
227 float strstr(string haystack, string needle, float offset)
228 {
229         float len, endpos;
230         string found;
231         len = strlen(needle);
232         endpos = strlen(haystack) - len;
233         while(offset <= endpos)
234         {
235                 found = substring(haystack, offset, len);
236                 if(found == needle)
237                         return offset;
238                 offset = offset + 1;
239         }
240         return -1;
241 }
242 */
243
244 float NUM_NEAREST_ENTITIES = 4;
245 entity nearest_entity[NUM_NEAREST_ENTITIES];
246 float nearest_length[NUM_NEAREST_ENTITIES];
247 entity findnearest(vector point, .string field, string value, vector axismod)
248 {
249     entity localhead;
250     float i;
251     float j;
252     float len;
253     vector dist;
254
255     float num_nearest;
256     num_nearest = 0;
257
258     localhead = find(world, field, value);
259     while (localhead)
260     {
261         if ((localhead.items == IT_KEY1 || localhead.items == IT_KEY2) && localhead.target == "###item###")
262             dist = localhead.oldorigin;
263         else
264             dist = localhead.origin;
265         dist = dist - point;
266         dist = dist_x * axismod_x * '1 0 0' + dist_y * axismod_y * '0 1 0' + dist_z * axismod_z * '0 0 1';
267         len = vlen(dist);
268
269         for (i = 0; i < num_nearest; ++i)
270         {
271             if (len < nearest_length[i])
272                 break;
273         }
274
275         // now i tells us where to insert at
276         //   INSERTION SORT! YOU'VE SEEN IT! RUN!
277         if (i < NUM_NEAREST_ENTITIES)
278         {
279             for (j = NUM_NEAREST_ENTITIES - 1; j >= i; --j)
280             {
281                 nearest_length[j + 1] = nearest_length[j];
282                 nearest_entity[j + 1] = nearest_entity[j];
283             }
284             nearest_length[i] = len;
285             nearest_entity[i] = localhead;
286             if (num_nearest < NUM_NEAREST_ENTITIES)
287                 num_nearest = num_nearest + 1;
288         }
289
290         localhead = find(localhead, field, value);
291     }
292
293     // now use the first one from our list that we can see
294     for (i = 0; i < num_nearest; ++i)
295     {
296         traceline(point, nearest_entity[i].origin, TRUE, world);
297         if (trace_fraction == 1)
298         {
299             if (i != 0)
300             {
301                 dprint("Nearest point (");
302                 dprint(nearest_entity[0].netname);
303                 dprint(") is not visible, using a visible one.\n");
304             }
305             return nearest_entity[i];
306         }
307     }
308
309     if (num_nearest == 0)
310         return world;
311
312     dprint("Not seeing any location point, using nearest as fallback.\n");
313     /* DEBUGGING CODE:
314     dprint("Candidates were: ");
315     for(j = 0; j < num_nearest; ++j)
316     {
317         if(j != 0)
318                 dprint(", ");
319         dprint(nearest_entity[j].netname);
320     }
321     dprint("\n");
322     */
323
324     return nearest_entity[0];
325 }
326
327 void spawnfunc_target_location()
328 {
329     self.classname = "target_location";
330     // location name in netname
331     // eventually support: count, teamgame selectors, line of sight?
332 }
333
334 void spawnfunc_info_location()
335 {
336     self.classname = "target_location";
337     self.message = self.netname;
338 }
339
340 string NearestLocation(vector p)
341 {
342     entity loc;
343     string ret;
344     ret = "somewhere";
345     loc = findnearest(p, classname, "target_location", '1 1 1');
346     if (loc)
347     {
348         ret = loc.message;
349     }
350     else
351     {
352         loc = findnearest(p, target, "###item###", '1 1 4');
353         if (loc)
354             ret = loc.netname;
355     }
356     return ret;
357 }
358
359 string formatmessage(string msg)
360 {
361         float p, p1, p2;
362         float n;
363         vector cursor;
364         entity cursor_ent;
365         string escape;
366         string replacement;
367         p = 0;
368         n = 7;
369
370         WarpZone_crosshair_trace(self);
371         cursor = trace_endpos;
372         cursor_ent = trace_ent;
373
374         while (1) {
375                 if (n < 1)
376                         break; // too many replacements
377
378                 n = n - 1;
379                 p1 = strstr(msg, "%", p); // NOTE: this destroys msg as it's a tempstring!
380                 p2 = strstr(msg, "\\", p); // NOTE: this destroys msg as it's a tempstring!
381
382                 if (p1 < 0)
383                         p1 = p2;
384
385                 if (p2 < 0)
386                         p2 = p1;
387
388                 p = min(p1, p2);
389
390                 if (p < 0)
391                         break;
392
393                 replacement = substring(msg, p, 2);
394                 escape = substring(msg, p + 1, 1);
395
396                 if (escape == "%")
397                         replacement = "%";
398                 else if (escape == "\\")
399                         replacement = "\\";
400                 else if (escape == "n")
401                         replacement = "\n";
402                 else if (escape == "a")
403                         replacement = ftos(floor(self.armorvalue));
404                 else if (escape == "h")
405                         replacement = ftos(floor(self.health));
406                 else if (escape == "l")
407                         replacement = NearestLocation(self.origin);
408                 else if (escape == "y")
409                         replacement = NearestLocation(cursor);
410                 else if (escape == "d")
411                         replacement = NearestLocation(self.death_origin);
412                 else if (escape == "w") {
413                         float wep;
414                         wep = self.weapon;
415                         if (!wep)
416                                 wep = self.switchweapon;
417                         if (!wep)
418                                 wep = self.cnt;
419                         replacement = W_Name(wep);
420                 } else if (escape == "W") {
421                         if (self.items & IT_SHELLS) replacement = "shells";
422                         else if (self.items & IT_NAILS) replacement = "bullets";
423                         else if (self.items & IT_ROCKETS) replacement = "rockets";
424                         else if (self.items & IT_CELLS) replacement = "cells";
425                         else replacement = "batteries"; // ;)
426                 } else if (escape == "x") {
427                         replacement = cursor_ent.netname;
428                         if (!replacement || !cursor_ent)
429                                 replacement = "nothing";
430                 } else if (escape == "s")
431                         replacement = ftos(vlen(self.velocity - self.velocity_z * '0 0 1'));
432                 else if (escape == "S")
433                         replacement = ftos(vlen(self.velocity));
434
435                 msg = strcat(substring(msg, 0, p), replacement, substring(msg, p+2, strlen(msg) - (p+2)));
436                 p = p + strlen(replacement);
437         }
438         return msg;
439 }
440
441 float boolean(float value) { // if value is 0 return FALSE (0), otherwise return TRUE (1)
442         return (value == 0) ? FALSE : TRUE;
443 }
444
445 /*
446 =============
447 GetCvars
448 =============
449 Called with:
450   0:  sends the request
451   >0: receives a cvar from name=argv(f) value=argv(f+1)
452 */
453 void GetCvars_handleString(string thisname, float f, .string field, string name)
454 {
455         if (f < 0)
456         {
457                 if (self.field)
458                         strunzone(self.field);
459                 self.field = string_null;
460         }
461         else if (f > 0)
462         {
463                 if (thisname == name)
464                 {
465                         if (self.field)
466                                 strunzone(self.field);
467                         self.field = strzone(argv(f + 1));
468                 }
469         }
470         else
471                 stuffcmd(self, strcat("cl_cmd sendcvar ", name, "\n"));
472 }
473 void GetCvars_handleString_Fixup(string thisname, float f, .string field, string name, string(string) func)
474 {
475         GetCvars_handleString(thisname, f, field, name);
476         if (f >= 0) // also initialize to the fitting value for "" when sending cvars out
477                 if (thisname == name)
478                 {
479                         string s;
480                         s = func(strcat1(self.field));
481                         if (s != self.field)
482                         {
483                                 strunzone(self.field);
484                                 self.field = strzone(s);
485                         }
486                 }
487 }
488 void GetCvars_handleFloat(string thisname, float f, .float field, string name)
489 {
490         if (f < 0)
491         {
492         }
493         else if (f > 0)
494         {
495                 if (thisname == name)
496                         self.field = stof(argv(f + 1));
497         }
498         else
499                 stuffcmd(self, strcat("cl_cmd sendcvar ", name, "\n"));
500 }
501 void GetCvars_handleFloatOnce(string thisname, float f, .float field, string name)
502 {
503         if (f < 0)
504         {
505         }
506         else if (f > 0)
507         {
508                 if (thisname == name)
509                 {
510                         if(!self.field)
511                         {
512                                 self.field = stof(argv(f + 1));
513                                 if(!self.field)
514                                         self.field = -1;
515                         }
516                 }
517         }
518         else
519         {
520                 if(!self.field)
521                         stuffcmd(self, strcat("cl_cmd sendcvar ", name, "\n"));
522         }
523 }
524 float w_getbestweapon(entity e);
525 string W_FixWeaponOrder_ForceComplete_AndBuildImpulseList(string wo)
526 {
527         string o;
528         o = W_FixWeaponOrder_ForceComplete(wo);
529         if(self.weaponorder_byimpulse)
530         {
531                 strunzone(self.weaponorder_byimpulse);
532                 self.weaponorder_byimpulse = string_null;
533         }
534         self.weaponorder_byimpulse = strzone(W_FixWeaponOrder_BuildImpulseList(o));
535         return o;
536 }
537 void GetCvars(float f)
538 {
539         string s = string_null;
540
541         if (f > 0)
542                 s = strcat1(argv(f));
543
544         get_cvars_f = f;
545         get_cvars_s = s;
546         MUTATOR_CALLHOOK(GetCvars);
547         GetCvars_handleFloat(s, f, autoswitch, "cl_autoswitch");
548         GetCvars_handleFloat(s, f, cvar_cl_autoscreenshot, "cl_autoscreenshot");
549         GetCvars_handleString(s, f, cvar_g_xonoticversion, "g_xonoticversion");
550         GetCvars_handleFloat(s, f, cvar_cl_handicap, "cl_handicap");
551         GetCvars_handleFloat(s, f, cvar_cl_clippedspectating, "cl_clippedspectating");
552         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriority, "cl_weaponpriority", W_FixWeaponOrder_ForceComplete_AndBuildImpulseList);
553         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[0], "cl_weaponpriority0", W_FixWeaponOrder_AllowIncomplete);
554         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[1], "cl_weaponpriority1", W_FixWeaponOrder_AllowIncomplete);
555         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[2], "cl_weaponpriority2", W_FixWeaponOrder_AllowIncomplete);
556         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[3], "cl_weaponpriority3", W_FixWeaponOrder_AllowIncomplete);
557         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[4], "cl_weaponpriority4", W_FixWeaponOrder_AllowIncomplete);
558         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[5], "cl_weaponpriority5", W_FixWeaponOrder_AllowIncomplete);
559         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[6], "cl_weaponpriority6", W_FixWeaponOrder_AllowIncomplete);
560         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[7], "cl_weaponpriority7", W_FixWeaponOrder_AllowIncomplete);
561         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[8], "cl_weaponpriority8", W_FixWeaponOrder_AllowIncomplete);
562         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[9], "cl_weaponpriority9", W_FixWeaponOrder_AllowIncomplete);
563         GetCvars_handleFloat(s, f, cvar_cl_weaponimpulsemode, "cl_weaponimpulsemode");
564         GetCvars_handleFloat(s, f, cvar_cl_autotaunt, "cl_autotaunt");
565         GetCvars_handleFloat(s, f, cvar_cl_noantilag, "cl_noantilag");
566         GetCvars_handleFloat(s, f, cvar_cl_voice_directional, "cl_voice_directional");
567         GetCvars_handleFloat(s, f, cvar_cl_voice_directional_taunt_attenuation, "cl_voice_directional_taunt_attenuation");
568         GetCvars_handleFloat(s, f, cvar_cl_accuracy_data_share, "cl_accuracy_data_share");
569         GetCvars_handleFloat(s, f, cvar_cl_accuracy_data_receive, "cl_accuracy_data_receive");
570
571         self.cvar_cl_accuracy_data_share = boolean(self.cvar_cl_accuracy_data_share);
572         self.cvar_cl_accuracy_data_receive = boolean(self.cvar_cl_accuracy_data_receive);
573
574 #ifdef ALLOW_FORCEMODELS
575         GetCvars_handleFloat(s, f, cvar_cl_forceplayermodels, "cl_forceplayermodels");
576         GetCvars_handleFloat(s, f, cvar_cl_forceplayermodelsfromxonotic, "cl_forceplayermodelsfromxonotic");
577 #endif
578         GetCvars_handleFloatOnce(s, f, cvar_cl_gunalign, "cl_gunalign");
579         GetCvars_handleFloat(s, f, cvar_cl_allow_uid2name, "cl_allow_uid2name");
580         GetCvars_handleFloat(s, f, cvar_cl_allow_uidtracking, "cl_allow_uidtracking");
581         GetCvars_handleFloat(s, f, cvar_cl_movement_track_canjump, "cl_movement_track_canjump");
582         GetCvars_handleFloat(s, f, cvar_cl_newusekeysupported, "cl_newusekeysupported");
583
584         // fixup of switchweapon (needed for LMS or when spectating is disabled, as PutClientInServer comes too early)
585         if (f > 0)
586         {
587                 if (s == "cl_weaponpriority")
588                         self.switchweapon = w_getbestweapon(self);
589                 if (s == "cl_allow_uidtracking")
590                         PlayerStats_AddPlayer(self);
591         }
592 }
593
594 void backtrace(string msg)
595 {
596     float dev, war;
597     dev = autocvar_developer;
598     war = autocvar_prvm_backtraceforwarnings;
599     cvar_set("developer", "1");
600     cvar_set("prvm_backtraceforwarnings", "1");
601     print("\n");
602     print("--- CUT HERE ---\nWARNING: ");
603     print(msg);
604     print("\n");
605     remove(world); // isn't there any better way to cause a backtrace?
606     print("\n--- CUT UNTIL HERE ---\n");
607     cvar_set("developer", ftos(dev));
608     cvar_set("prvm_backtraceforwarnings", ftos(war));
609 }
610
611 string Team_ColorCode(float teamid)
612 {
613     if (teamid == COLOR_TEAM1)
614         return "^1";
615     else if (teamid == COLOR_TEAM2)
616         return "^4";
617     else if (teamid == COLOR_TEAM3)
618         return "^3";
619     else if (teamid == COLOR_TEAM4)
620         return "^6";
621     else
622         return "^7";
623 }
624
625 string Team_ColorName(float t)
626 {
627     // fixme: Search for team entities and get their .netname's!
628     if (t == COLOR_TEAM1)
629         return "Red";
630     if (t == COLOR_TEAM2)
631         return "Blue";
632     if (t == COLOR_TEAM3)
633         return "Yellow";
634     if (t == COLOR_TEAM4)
635         return "Pink";
636     return "Neutral";
637 }
638
639 string Team_ColorNameLowerCase(float t)
640 {
641     // fixme: Search for team entities and get their .netname's!
642     if (t == COLOR_TEAM1)
643         return "red";
644     if (t == COLOR_TEAM2)
645         return "blue";
646     if (t == COLOR_TEAM3)
647         return "yellow";
648     if (t == COLOR_TEAM4)
649         return "pink";
650     return "neutral";
651 }
652
653 float ColourToNumber(string team_colour)
654 {
655         if (team_colour == "red")
656                 return COLOR_TEAM1;
657
658         if (team_colour == "blue")
659                 return COLOR_TEAM2;
660
661         if (team_colour == "yellow")
662                 return COLOR_TEAM3;
663
664         if (team_colour == "pink")
665                 return COLOR_TEAM4;
666
667         if (team_colour == "auto")
668                 return 0;
669
670         return -1;
671 }
672
673 float NumberToTeamNumber(float number)
674 {
675         if (number == 1)
676                 return COLOR_TEAM1;
677
678         if (number == 2)
679                 return COLOR_TEAM2;
680
681         if (number == 3)
682                 return COLOR_TEAM3;
683
684         if (number == 4)
685                 return COLOR_TEAM4;
686
687         return -1;
688 }
689
690 // decolorizes and team colors the player name when needed
691 string playername(entity p)
692 {
693     string t;
694     if (teamplay && !intermission_running && p.classname == "player")
695     {
696         t = Team_ColorCode(p.team);
697         return strcat(t, strdecolorize(p.netname));
698     }
699     else
700         return p.netname;
701 }
702
703 vector randompos(vector m1, vector m2)
704 {
705     vector v;
706     m2 = m2 - m1;
707     v_x = m2_x * random() + m1_x;
708     v_y = m2_y * random() + m1_y;
709     v_z = m2_z * random() + m1_z;
710     return  v;
711 }
712
713 //#NO AUTOCVARS START
714
715 float g_pickup_shells;
716 float g_pickup_shells_max;
717 float g_pickup_nails;
718 float g_pickup_nails_max;
719 float g_pickup_rockets;
720 float g_pickup_rockets_max;
721 float g_pickup_cells;
722 float g_pickup_cells_max;
723 float g_pickup_fuel;
724 float g_pickup_fuel_jetpack;
725 float g_pickup_fuel_max;
726 float g_pickup_armorsmall;
727 float g_pickup_armorsmall_max;
728 float g_pickup_armorsmall_anyway;
729 float g_pickup_armormedium;
730 float g_pickup_armormedium_max;
731 float g_pickup_armormedium_anyway;
732 float g_pickup_armorbig;
733 float g_pickup_armorbig_max;
734 float g_pickup_armorbig_anyway;
735 float g_pickup_armorlarge;
736 float g_pickup_armorlarge_max;
737 float g_pickup_armorlarge_anyway;
738 float g_pickup_healthsmall;
739 float g_pickup_healthsmall_max;
740 float g_pickup_healthsmall_anyway;
741 float g_pickup_healthmedium;
742 float g_pickup_healthmedium_max;
743 float g_pickup_healthmedium_anyway;
744 float g_pickup_healthlarge;
745 float g_pickup_healthlarge_max;
746 float g_pickup_healthlarge_anyway;
747 float g_pickup_healthmega;
748 float g_pickup_healthmega_max;
749 float g_pickup_healthmega_anyway;
750 float g_pickup_ammo_anyway;
751 float g_pickup_weapons_anyway;
752 float g_weaponarena;
753 WEPSET_DECLARE_A(g_weaponarena_weapons);
754 float g_weaponarena_random;
755 float g_weaponarena_random_with_laser;
756 string g_weaponarena_list;
757 float g_weaponspeedfactor;
758 float g_weaponratefactor;
759 float g_weapondamagefactor;
760 float g_weaponforcefactor;
761 float g_weaponspreadfactor;
762
763 WEPSET_DECLARE_A(start_weapons);
764 WEPSET_DECLARE_A(start_weapons_default);
765 WEPSET_DECLARE_A(start_weapons_defaultmask);
766 float start_items;
767 float start_ammo_shells;
768 float start_ammo_nails;
769 float start_ammo_rockets;
770 float start_ammo_cells;
771 float start_ammo_fuel;
772 float start_health;
773 float start_armorvalue;
774 WEPSET_DECLARE_A(warmup_start_weapons);
775 WEPSET_DECLARE_A(warmup_start_weapons_default);
776 WEPSET_DECLARE_A(warmup_start_weapons_defaultmask);
777 float warmup_start_ammo_shells;
778 float warmup_start_ammo_nails;
779 float warmup_start_ammo_rockets;
780 float warmup_start_ammo_cells;
781 float warmup_start_ammo_fuel;
782 float warmup_start_health;
783 float warmup_start_armorvalue;
784 float g_weapon_stay;
785
786 entity get_weaponinfo(float w);
787
788 float want_weapon(string cvarprefix, entity weaponinfo, float allguns)
789 {
790         var float i = weaponinfo.weapon;
791         var float d = 0;
792
793         if (!i)
794                 return 0;
795
796         if (g_lms || g_ca || allguns)
797         {
798                 if(weaponinfo.spawnflags & WEP_FLAG_NORMAL)
799                         d = TRUE;
800                 else
801                         d = FALSE;
802         }
803         else if (g_cts)
804                 d = (i == WEP_SHOTGUN);
805         else if (g_nexball)
806                 d = 0; // weapon is set a few lines later
807         else
808                 d = (i == WEP_LASER || i == WEP_SHOTGUN);
809                 
810         if(g_grappling_hook) // if possible, redirect off-hand hook to on-hand hook
811                 d |= (i == WEP_HOOK);
812         if(weaponinfo.spawnflags & WEP_FLAG_MUTATORBLOCKED) // never default mutator blocked guns
813                 d = 0;
814
815         var float t = cvar(strcat(cvarprefix, weaponinfo.netname));
816         
817         //print(strcat("want_weapon: ", weaponinfo.netname, " - d: ", ftos(d), ", t: ", ftos(t), ". \n"));
818         
819         // bit order in t:
820         // 1: want or not
821         // 2: is default?
822         // 4: is set by default?
823         if(t < 0)
824                 t = 4 | (3 * d);
825         else
826                 t |= (2 * d);
827
828         return t;
829 }
830
831 void readplayerstartcvars()
832 {
833         entity e;
834         float i, j, t;
835         string s;
836
837         // initialize starting values for players
838         WEPSET_CLEAR_A(start_weapons);
839         WEPSET_CLEAR_A(start_weapons_default);
840         WEPSET_CLEAR_A(start_weapons_defaultmask);
841         start_items = 0;
842         start_ammo_shells = 0;
843         start_ammo_nails = 0;
844         start_ammo_rockets = 0;
845         start_ammo_cells = 0;
846         start_health = cvar("g_balance_health_start");
847         start_armorvalue = cvar("g_balance_armor_start");
848
849         g_weaponarena = 0;
850         WEPSET_CLEAR_A(g_weaponarena_weapons);
851
852         s = cvar_string("g_weaponarena");
853         if (s == "0" || s == "")
854         {
855                 if(g_lms || g_ca)
856                         s = "most";
857         }
858
859         if (s == "0" || s == "")
860         {
861                 // no arena
862         }
863         else if (s == "off")
864         {
865                 // forcibly turn off weaponarena
866         }
867         else if (s == "all")
868         {
869                 g_weaponarena = 1;
870                 g_weaponarena_list = "All Weapons";
871                 for (j = WEP_FIRST; j <= WEP_LAST; ++j)
872                 {
873                         e = get_weaponinfo(j);
874                         if not(e.spawnflags & WEP_FLAG_MUTATORBLOCKED)
875                                 WEPSET_OR_AW(g_weaponarena_weapons, j);
876                 }
877         }
878         else if (s == "most")
879         {
880                 g_weaponarena = 1;
881                 g_weaponarena_list = "Most Weapons";
882                 for (j = WEP_FIRST; j <= WEP_LAST; ++j)
883                 {
884                         e = get_weaponinfo(j);
885                         if not(e.spawnflags & WEP_FLAG_MUTATORBLOCKED)
886                                 if (e.spawnflags & WEP_FLAG_NORMAL)
887                                         WEPSET_OR_AW(g_weaponarena_weapons, j);
888                 }
889         }
890         else if (s == "none")
891         {
892                 g_weaponarena = 1;
893                 g_weaponarena_list = "No Weapons";
894         }
895         else
896         {
897                 g_weaponarena = 1;
898                 t = tokenize_console(s);
899                 g_weaponarena_list = "";
900                 for (i = 0; i < t; ++i)
901                 {
902                         s = argv(i);
903                         for (j = WEP_FIRST; j <= WEP_LAST; ++j)
904                         {
905                                 e = get_weaponinfo(j);
906                                 if (e.netname == s)
907                                 {
908                                         WEPSET_OR_AW(g_weaponarena_weapons, j);
909                                         g_weaponarena_list = strcat(g_weaponarena_list, e.message, " & ");
910                                         break;
911                                 }
912                         }
913                         if (j > WEP_LAST)
914                         {
915                                 print("The weapon mutator list contains an unknown weapon ", s, ". Skipped.\n");
916                         }
917                 }
918                 g_weaponarena_list = strzone(substring(g_weaponarena_list, 0, strlen(g_weaponarena_list) - 3));
919         }
920
921         if(g_weaponarena)
922                 g_weaponarena_random = cvar("g_weaponarena_random");
923         else
924                 g_weaponarena_random = 0;
925         g_weaponarena_random_with_laser = cvar("g_weaponarena_random_with_laser");
926
927         if (g_weaponarena)
928         {
929                 g_minstagib = 0; // incompatible
930                 g_pinata = 0; // incompatible
931                 g_weapon_stay = 0; // incompatible
932                 WEPSET_COPY_AA(start_weapons, g_weaponarena_weapons);
933                 if(!(g_lms || g_ca))
934                         start_items |= IT_UNLIMITED_AMMO;
935         }
936         else if (g_minstagib)
937         {
938                 g_pinata = 0; // incompatible
939                 g_weapon_stay = 0; // incompatible
940                 g_bloodloss = 0; // incompatible
941                 start_health = 100;
942                 start_armorvalue = 0;
943                 WEPSET_COPY_AW(start_weapons, WEP_MINSTANEX);
944                 g_minstagib_invis_alpha = cvar("g_minstagib_invis_alpha");
945                 start_items |= IT_UNLIMITED_SUPERWEAPONS;
946
947                 if (g_minstagib_invis_alpha <= 0)
948                         g_minstagib_invis_alpha = -1;
949         }
950         else
951         {
952                 for (i = WEP_FIRST; i <= WEP_LAST; ++i)
953                 {
954                         e = get_weaponinfo(i);
955                         float w = want_weapon("g_start_weapon_", e, FALSE);
956                         if(w & 1)
957                                 WEPSET_OR_AW(start_weapons, i);
958                         if(w & 2)
959                                 WEPSET_OR_AW(start_weapons_default, i);
960                         if(w & 4)
961                                 WEPSET_OR_AW(start_weapons_defaultmask, i);
962                 }
963         }
964
965         if(!cvar("g_use_ammunition"))
966                 start_items |= IT_UNLIMITED_AMMO;
967
968         if(cvar("g_nexball"))
969                 start_items |= IT_UNLIMITED_SUPERWEAPONS; // FIXME BAD BAD BAD BAD HACK, NEXBALL SHOULDN'T ABUSE PORTO'S WEAPON SLOT
970
971         if(g_minstagib)
972         {
973                 start_ammo_cells = cvar("g_minstagib_ammo_start");
974                 start_ammo_fuel = cvar("g_start_ammo_fuel");
975         }
976         else if(start_items & IT_UNLIMITED_WEAPON_AMMO)
977         {
978                 start_ammo_rockets = 999;
979                 start_ammo_shells = 999;
980                 start_ammo_cells = 999;
981                 start_ammo_nails = 999;
982                 start_ammo_fuel = 999;
983         }
984         else
985         {
986                 if(g_lms || g_ca)
987                 {
988                         start_ammo_shells = cvar("g_lms_start_ammo_shells");
989                         start_ammo_nails = cvar("g_lms_start_ammo_nails");
990                         start_ammo_rockets = cvar("g_lms_start_ammo_rockets");
991                         start_ammo_cells = cvar("g_lms_start_ammo_cells");
992                         start_ammo_fuel = cvar("g_lms_start_ammo_fuel");
993                 }
994                 else
995                 {
996                         start_ammo_shells = cvar("g_start_ammo_shells");
997                         start_ammo_nails = cvar("g_start_ammo_nails");
998                         start_ammo_rockets = cvar("g_start_ammo_rockets");
999                         start_ammo_cells = cvar("g_start_ammo_cells");
1000                         start_ammo_fuel = cvar("g_start_ammo_fuel");
1001                 }
1002         }
1003
1004         if (g_lms || g_ca)
1005         {
1006                 start_health = cvar("g_lms_start_health");
1007                 start_armorvalue = cvar("g_lms_start_armor");
1008         }
1009
1010         if (inWarmupStage)
1011         {
1012                 warmup_start_ammo_shells = start_ammo_shells;
1013                 warmup_start_ammo_nails = start_ammo_nails;
1014                 warmup_start_ammo_rockets = start_ammo_rockets;
1015                 warmup_start_ammo_cells = start_ammo_cells;
1016                 warmup_start_ammo_fuel = start_ammo_fuel;
1017                 warmup_start_health = start_health;
1018                 warmup_start_armorvalue = start_armorvalue;
1019                 WEPSET_COPY_AA(warmup_start_weapons, start_weapons);
1020                 WEPSET_COPY_AA(warmup_start_weapons_default, start_weapons_default);
1021                 WEPSET_COPY_AA(warmup_start_weapons_defaultmask, start_weapons_defaultmask);
1022
1023                 if (!g_weaponarena && !g_minstagib && !g_ca)
1024                 {
1025                         warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
1026                         warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
1027                         warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
1028                         warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
1029                         warmup_start_ammo_fuel = cvar("g_warmup_start_ammo_fuel");
1030                         warmup_start_health = cvar("g_warmup_start_health");
1031                         warmup_start_armorvalue = cvar("g_warmup_start_armor");
1032                         WEPSET_CLEAR_A(warmup_start_weapons);
1033                         WEPSET_CLEAR_A(warmup_start_weapons_default);
1034                         WEPSET_CLEAR_A(warmup_start_weapons_defaultmask);
1035                         for (i = WEP_FIRST; i <= WEP_LAST; ++i)
1036                         {
1037                                 e = get_weaponinfo(i);
1038                                 float w = want_weapon("g_start_weapon_", e, cvar("g_warmup_allguns"));
1039                                 if(w & 1)
1040                                         WEPSET_OR_AW(warmup_start_weapons, i);
1041                                 if(w & 2)
1042                                         WEPSET_OR_AW(warmup_start_weapons_default, i);
1043                                 if(w & 4)
1044                                         WEPSET_OR_AW(warmup_start_weapons_defaultmask, i);
1045                         }
1046                 }
1047         }
1048
1049         if (g_jetpack)
1050                 start_items |= IT_JETPACK;
1051
1052         MUTATOR_CALLHOOK(SetStartItems);
1053
1054         if ((start_items & IT_JETPACK) || (g_grappling_hook && WEPSET_CONTAINS_AW(start_weapons, WEP_HOOK)))
1055         {
1056                 g_grappling_hook = 0; // these two can't coexist, as they use the same button
1057                 start_items |= IT_FUEL_REGEN;
1058                 start_ammo_fuel = max(start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
1059                 warmup_start_ammo_fuel = max(warmup_start_ammo_fuel, cvar("g_balance_fuel_rotstable"));
1060         }
1061
1062         for (i = WEP_FIRST; i <= WEP_LAST; ++i)
1063         {
1064                 e = get_weaponinfo(i);
1065                 if(WEPSET_CONTAINS_AW(start_weapons, i) || WEPSET_CONTAINS_AW(warmup_start_weapons, i))
1066                         weapon_action(i, WR_PRECACHE);
1067         }
1068
1069         start_ammo_shells = max(0, start_ammo_shells);
1070         start_ammo_nails = max(0, start_ammo_nails);
1071         start_ammo_cells = max(0, start_ammo_cells);
1072         start_ammo_rockets = max(0, start_ammo_rockets);
1073         start_ammo_fuel = max(0, start_ammo_fuel);
1074
1075         warmup_start_ammo_shells = max(0, warmup_start_ammo_shells);
1076         warmup_start_ammo_nails = max(0, warmup_start_ammo_nails);
1077         warmup_start_ammo_cells = max(0, warmup_start_ammo_cells);
1078         warmup_start_ammo_rockets = max(0, warmup_start_ammo_rockets);
1079         warmup_start_ammo_fuel = max(0, warmup_start_ammo_fuel);
1080 }
1081
1082 float g_bugrigs;
1083 float g_bugrigs_planar_movement;
1084 float g_bugrigs_planar_movement_car_jumping;
1085 float g_bugrigs_reverse_spinning;
1086 float g_bugrigs_reverse_speeding;
1087 float g_bugrigs_reverse_stopping;
1088 float g_bugrigs_air_steering;
1089 float g_bugrigs_angle_smoothing;
1090 float g_bugrigs_friction_floor;
1091 float g_bugrigs_friction_brake;
1092 float g_bugrigs_friction_air;
1093 float g_bugrigs_accel;
1094 float g_bugrigs_speed_ref;
1095 float g_bugrigs_speed_pow;
1096 float g_bugrigs_steer;
1097
1098 float g_touchexplode;
1099 float g_touchexplode_radius;
1100 float g_touchexplode_damage;
1101 float g_touchexplode_edgedamage;
1102 float g_touchexplode_force;
1103
1104 float sv_autotaunt;
1105 float sv_taunt;
1106
1107 float sv_pitch_min;
1108 float sv_pitch_max;
1109 float sv_pitch_fixyaw;
1110
1111 string GetGametype(); // g_world.qc
1112 void readlevelcvars(void)
1113 {
1114         g_minstagib = cvar("g_minstagib");
1115
1116         // load ALL the mutators
1117         if(cvar("g_dodging"))
1118                 MUTATOR_ADD(mutator_dodging);
1119         if(cvar("g_spawn_near_teammate"))
1120                 MUTATOR_ADD(mutator_spawn_near_teammate);
1121         if(!g_minstagib)
1122         {
1123                 if(cvar("g_invincible_projectiles"))
1124                         MUTATOR_ADD(mutator_invincibleprojectiles);
1125                 if(cvar("g_new_toys"))
1126                         MUTATOR_ADD(mutator_new_toys);
1127                 if(cvar("g_nix"))
1128                         MUTATOR_ADD(mutator_nix);
1129                 if(cvar("g_rocket_flying"))
1130                         MUTATOR_ADD(mutator_rocketflying);
1131                 if(cvar("g_vampire"))
1132                         MUTATOR_ADD(mutator_vampire);           
1133                 if(cvar("g_superspectate"))
1134                         MUTATOR_ADD(mutator_superspec);
1135         }
1136
1137         // is this a mutator? is this a mode?
1138         if(cvar("g_sandbox"))
1139                 MUTATOR_ADD(sandbox);
1140
1141         if(cvar("sv_allow_fullbright"))
1142                 serverflags |= SERVERFLAG_ALLOW_FULLBRIGHT;
1143
1144     g_bugrigs = cvar("g_bugrigs");
1145     g_bugrigs_planar_movement = cvar("g_bugrigs_planar_movement");
1146     g_bugrigs_planar_movement_car_jumping = cvar("g_bugrigs_planar_movement_car_jumping");
1147     g_bugrigs_reverse_spinning = cvar("g_bugrigs_reverse_spinning");
1148     g_bugrigs_reverse_speeding = cvar("g_bugrigs_reverse_speeding");
1149     g_bugrigs_reverse_stopping = cvar("g_bugrigs_reverse_stopping");
1150     g_bugrigs_air_steering = cvar("g_bugrigs_air_steering");
1151     g_bugrigs_angle_smoothing = cvar("g_bugrigs_angle_smoothing");
1152     g_bugrigs_friction_floor = cvar("g_bugrigs_friction_floor");
1153     g_bugrigs_friction_brake = cvar("g_bugrigs_friction_brake");
1154     g_bugrigs_friction_air = cvar("g_bugrigs_friction_air");
1155     g_bugrigs_accel = cvar("g_bugrigs_accel");
1156     g_bugrigs_speed_ref = cvar("g_bugrigs_speed_ref");
1157     g_bugrigs_speed_pow = cvar("g_bugrigs_speed_pow");
1158     g_bugrigs_steer = cvar("g_bugrigs_steer");
1159
1160     g_touchexplode = cvar("g_touchexplode");
1161     g_touchexplode_radius = cvar("g_touchexplode_radius");
1162     g_touchexplode_damage = cvar("g_touchexplode_damage");
1163     g_touchexplode_edgedamage = cvar("g_touchexplode_edgedamage");
1164     g_touchexplode_force = cvar("g_touchexplode_force");
1165
1166 #ifdef ALLOW_FORCEMODELS
1167         sv_clforceplayermodels = cvar("sv_clforceplayermodels");
1168 #endif
1169
1170         sv_clones = cvar("sv_clones");
1171         sv_gentle = cvar("sv_gentle");
1172         sv_foginterval = cvar("sv_foginterval");
1173         g_cloaked = cvar("g_cloaked");
1174     if(g_cts)
1175         g_cloaked = 1; // always enable cloak in CTS
1176         g_jump_grunt = cvar("g_jump_grunt");
1177         g_footsteps = cvar("g_footsteps");
1178         g_grappling_hook = cvar("g_grappling_hook");
1179         g_jetpack = cvar("g_jetpack");
1180         g_midair = cvar("g_midair");
1181         g_norecoil = cvar("g_norecoil");
1182         g_bloodloss = cvar("g_bloodloss");
1183         sv_maxidle = cvar("sv_maxidle");
1184         sv_maxidle_spectatorsareidle = cvar("sv_maxidle_spectatorsareidle");
1185         g_ctf_reverse = cvar("g_ctf_reverse");
1186         sv_autotaunt = cvar("sv_autotaunt");
1187         sv_taunt = cvar("sv_taunt");
1188
1189         inWarmupStage = cvar("g_warmup");
1190         g_warmup_limit = cvar("g_warmup_limit");
1191         g_warmup_allguns = cvar("g_warmup_allguns");
1192         g_warmup_allow_timeout = cvar("g_warmup_allow_timeout");
1193
1194         if ((g_race && g_race_qualifying == 2) || g_runematch || g_arena || g_assault || cvar("g_campaign"))
1195                 inWarmupStage = 0; // these modes cannot work together, sorry
1196
1197         g_pickup_respawntime_weapon = cvar("g_pickup_respawntime_weapon");
1198         g_pickup_respawntime_superweapon = cvar("g_pickup_respawntime_superweapon");
1199         g_pickup_respawntime_ammo = cvar("g_pickup_respawntime_ammo");
1200         g_pickup_respawntime_short = cvar("g_pickup_respawntime_short");
1201         g_pickup_respawntime_medium = cvar("g_pickup_respawntime_medium");
1202         g_pickup_respawntime_long = cvar("g_pickup_respawntime_long");
1203         g_pickup_respawntime_powerup = cvar("g_pickup_respawntime_powerup");
1204         g_pickup_respawntimejitter_weapon = cvar("g_pickup_respawntimejitter_weapon");
1205         g_pickup_respawntimejitter_superweapon = cvar("g_pickup_respawntimejitter_superweapon");
1206         g_pickup_respawntimejitter_ammo = cvar("g_pickup_respawntimejitter_ammo");
1207         g_pickup_respawntimejitter_short = cvar("g_pickup_respawntimejitter_short");
1208         g_pickup_respawntimejitter_medium = cvar("g_pickup_respawntimejitter_medium");
1209         g_pickup_respawntimejitter_long = cvar("g_pickup_respawntimejitter_long");
1210         g_pickup_respawntimejitter_powerup = cvar("g_pickup_respawntimejitter_powerup");
1211
1212         g_weaponspeedfactor = cvar("g_weaponspeedfactor");
1213         g_weaponratefactor = cvar("g_weaponratefactor");
1214         g_weapondamagefactor = cvar("g_weapondamagefactor");
1215         g_weaponforcefactor = cvar("g_weaponforcefactor");
1216         g_weaponspreadfactor = cvar("g_weaponspreadfactor");
1217
1218         g_pickup_shells = cvar("g_pickup_shells");
1219         g_pickup_shells_max = cvar("g_pickup_shells_max");
1220         g_pickup_nails = cvar("g_pickup_nails");
1221         g_pickup_nails_max = cvar("g_pickup_nails_max");
1222         g_pickup_rockets = cvar("g_pickup_rockets");
1223         g_pickup_rockets_max = cvar("g_pickup_rockets_max");
1224         g_pickup_cells = cvar("g_pickup_cells");
1225         g_pickup_cells_max = cvar("g_pickup_cells_max");
1226         g_pickup_fuel = cvar("g_pickup_fuel");
1227         g_pickup_fuel_jetpack = cvar("g_pickup_fuel_jetpack");
1228         g_pickup_fuel_max = cvar("g_pickup_fuel_max");
1229         g_pickup_armorsmall = cvar("g_pickup_armorsmall");
1230         g_pickup_armorsmall_max = cvar("g_pickup_armorsmall_max");
1231         g_pickup_armorsmall_anyway = cvar("g_pickup_armorsmall_anyway");
1232         g_pickup_armormedium = cvar("g_pickup_armormedium");
1233         g_pickup_armormedium_max = cvar("g_pickup_armormedium_max");
1234         g_pickup_armormedium_anyway = cvar("g_pickup_armormedium_anyway");
1235         g_pickup_armorbig = cvar("g_pickup_armorbig");
1236         g_pickup_armorbig_max = cvar("g_pickup_armorbig_max");
1237         g_pickup_armorbig_anyway = cvar("g_pickup_armorbig_anyway");
1238         g_pickup_armorlarge = cvar("g_pickup_armorlarge");
1239         g_pickup_armorlarge_max = cvar("g_pickup_armorlarge_max");
1240         g_pickup_armorlarge_anyway = cvar("g_pickup_armorlarge_anyway");
1241         g_pickup_healthsmall = cvar("g_pickup_healthsmall");
1242         g_pickup_healthsmall_max = cvar("g_pickup_healthsmall_max");
1243         g_pickup_healthsmall_anyway = cvar("g_pickup_healthsmall_anyway");
1244         g_pickup_healthmedium = cvar("g_pickup_healthmedium");
1245         g_pickup_healthmedium_max = cvar("g_pickup_healthmedium_max");
1246         g_pickup_healthmedium_anyway = cvar("g_pickup_healthmedium_anyway");
1247         g_pickup_healthlarge = cvar("g_pickup_healthlarge");
1248         g_pickup_healthlarge_max = cvar("g_pickup_healthlarge_max");
1249         g_pickup_healthlarge_anyway = cvar("g_pickup_healthlarge_anyway");
1250         g_pickup_healthmega = cvar("g_pickup_healthmega");
1251         g_pickup_healthmega_max = cvar("g_pickup_healthmega_max");
1252         g_pickup_healthmega_anyway = cvar("g_pickup_healthmega_anyway");
1253
1254         g_pickup_ammo_anyway = cvar("g_pickup_ammo_anyway");
1255         g_pickup_weapons_anyway = cvar("g_pickup_weapons_anyway");
1256
1257         g_pinata = cvar("g_pinata");
1258
1259     g_weapon_stay = cvar(strcat("g_", GetGametype(), "_weapon_stay"));
1260     if(!g_weapon_stay)
1261         g_weapon_stay = cvar("g_weapon_stay");
1262
1263         if not(inWarmupStage && !g_ca)
1264                 game_starttime = cvar("g_start_delay");
1265
1266         sv_pitch_min = cvar("sv_pitch_min");
1267         sv_pitch_max = cvar("sv_pitch_max");
1268         sv_pitch_fixyaw = cvar("sv_pitch_fixyaw");
1269
1270         readplayerstartcvars();
1271 }
1272
1273 //#NO AUTOCVARS END
1274
1275 // Sound functions
1276 string precache_sound (string s) = #19;
1277 float precache_sound_index (string s) = #19;
1278
1279 #define SND_VOLUME      1
1280 #define SND_ATTENUATION 2
1281 #define SND_LARGEENTITY 8
1282 #define SND_LARGESOUND  16
1283
1284 float sound_allowed(float dest, entity e)
1285 {
1286     // sounds from world may always pass
1287     for (;;)
1288     {
1289         if (e.classname == "body")
1290             e = e.enemy;
1291         else if (e.realowner && e.realowner != e)
1292             e = e.realowner;
1293         else if (e.owner && e.owner != e)
1294             e = e.owner;
1295         else
1296             break;
1297     }
1298     // sounds to self may always pass
1299     if (dest == MSG_ONE)
1300         if (e == msg_entity)
1301             return TRUE;
1302     // sounds by players can be removed
1303     if (autocvar_bot_sound_monopoly)
1304         if (clienttype(e) == CLIENTTYPE_REAL)
1305             return FALSE;
1306     // anything else may pass
1307     return TRUE;
1308 }
1309
1310 #ifdef COMPAT_XON010_CHANNELS
1311 void(entity e, float chan, string samp, float vol, float atten) builtin_sound = #8;
1312 void sound(entity e, float chan, string samp, float vol, float atten)
1313 {
1314     if (!sound_allowed(MSG_BROADCAST, e))
1315         return;
1316     builtin_sound(e, chan, samp, vol, atten);
1317 }
1318 #else
1319 #undef sound
1320 void sound(entity e, float chan, string samp, float vol, float atten)
1321 {
1322     if (!sound_allowed(MSG_BROADCAST, e))
1323         return;
1324     sound7(e, chan, samp, vol, atten, 0, 0);
1325 }
1326 #endif
1327
1328 void soundtoat(float dest, entity e, vector o, float chan, string samp, float vol, float atten)
1329 {
1330     float entno, idx;
1331
1332     if (!sound_allowed(dest, e))
1333         return;
1334
1335     entno = num_for_edict(e);
1336     idx = precache_sound_index(samp);
1337
1338     float sflags;
1339     sflags = 0;
1340
1341     atten = floor(atten * 64);
1342     vol = floor(vol * 255);
1343
1344     if (vol != 255)
1345         sflags |= SND_VOLUME;
1346     if (atten != 64)
1347         sflags |= SND_ATTENUATION;
1348     if (entno >= 8192 || chan < 0 || chan > 7)
1349         sflags |= SND_LARGEENTITY;
1350     if (idx >= 256)
1351         sflags |= SND_LARGESOUND;
1352
1353     WriteByte(dest, SVC_SOUND);
1354     WriteByte(dest, sflags);
1355     if (sflags & SND_VOLUME)
1356         WriteByte(dest, vol);
1357     if (sflags & SND_ATTENUATION)
1358         WriteByte(dest, atten);
1359     if (sflags & SND_LARGEENTITY)
1360     {
1361         WriteShort(dest, entno);
1362         WriteByte(dest, chan);
1363     }
1364     else
1365     {
1366         WriteShort(dest, entno * 8 + chan);
1367     }
1368     if (sflags & SND_LARGESOUND)
1369         WriteShort(dest, idx);
1370     else
1371         WriteByte(dest, idx);
1372
1373     WriteCoord(dest, o_x);
1374     WriteCoord(dest, o_y);
1375     WriteCoord(dest, o_z);
1376 }
1377 void soundto(float dest, entity e, float chan, string samp, float vol, float atten)
1378 {
1379     vector o;
1380
1381     if (!sound_allowed(dest, e))
1382         return;
1383
1384     o = e.origin + 0.5 * (e.mins + e.maxs);
1385     soundtoat(dest, e, o, chan, samp, vol, atten);
1386 }
1387 void soundat(entity e, vector o, float chan, string samp, float vol, float atten)
1388 {
1389     soundtoat(((chan & 8) ? MSG_ALL : MSG_BROADCAST), e, o, chan, samp, vol, atten);
1390 }
1391 void stopsoundto(float dest, entity e, float chan)
1392 {
1393     float entno;
1394
1395     if (!sound_allowed(dest, e))
1396         return;
1397
1398     entno = num_for_edict(e);
1399
1400     if (entno >= 8192 || chan < 0 || chan > 7)
1401     {
1402         float idx, sflags;
1403         idx = precache_sound_index("misc/null.wav");
1404         sflags = SND_LARGEENTITY;
1405         if (idx >= 256)
1406             sflags |= SND_LARGESOUND;
1407         WriteByte(dest, SVC_SOUND);
1408         WriteByte(dest, sflags);
1409         WriteShort(dest, entno);
1410         WriteByte(dest, chan);
1411         if (sflags & SND_LARGESOUND)
1412             WriteShort(dest, idx);
1413         else
1414             WriteByte(dest, idx);
1415         WriteCoord(dest, e.origin_x);
1416         WriteCoord(dest, e.origin_y);
1417         WriteCoord(dest, e.origin_z);
1418     }
1419     else
1420     {
1421         WriteByte(dest, SVC_STOPSOUND);
1422         WriteShort(dest, entno * 8 + chan);
1423     }
1424 }
1425 void stopsound(entity e, float chan)
1426 {
1427     if (!sound_allowed(MSG_BROADCAST, e))
1428         return;
1429
1430     stopsoundto(MSG_BROADCAST, e, chan); // unreliable, gets there fast
1431     stopsoundto(MSG_ALL, e, chan); // in case of packet loss
1432 }
1433
1434 void play2(entity e, string filename)
1435 {
1436     //stuffcmd(e, strcat("play2 ", filename, "\n"));
1437     msg_entity = e;
1438     soundtoat(MSG_ONE, world, '0 0 0', CH_INFO, filename, VOL_BASE, ATTN_NONE);
1439 }
1440
1441 // use this one if you might be causing spam (e.g. from touch functions that might get called more than once per frame)
1442 .float spamtime;
1443 float spamsound(entity e, float chan, string samp, float vol, float atten)
1444 {
1445     if (!sound_allowed(MSG_BROADCAST, e))
1446         return FALSE;
1447
1448     if (time > e.spamtime)
1449     {
1450         e.spamtime = time;
1451         sound(e, chan, samp, vol, atten);
1452         return TRUE;
1453     }
1454     return FALSE;
1455 }
1456
1457 void play2team(float t, string filename)
1458 {
1459     entity head;
1460
1461     if (autocvar_bot_sound_monopoly)
1462         return;
1463
1464     FOR_EACH_REALPLAYER(head)
1465     {
1466         if (head.team == t)
1467             play2(head, filename);
1468     }
1469 }
1470
1471 void play2all(string samp)
1472 {
1473     if (autocvar_bot_sound_monopoly)
1474         return;
1475
1476     sound(world, CH_INFO, samp, VOL_BASE, ATTN_NONE);
1477 }
1478
1479 void PrecachePlayerSounds(string f);
1480 void precache_playermodel(string m)
1481 {
1482         float globhandle, i, n;
1483         string f;
1484
1485         if(substring(m, -9,5) == "_lod1")
1486                 return;
1487         if(substring(m, -9,5) == "_lod2")
1488                 return;
1489         precache_model(m);
1490         f = strcat(substring(m, 0, -5), "_lod1", substring(m, -4, -1));
1491         if(fexists(f))
1492                 precache_model(f);
1493         f = strcat(substring(m, 0, -5), "_lod2", substring(m, -4, -1));
1494         if(fexists(f))
1495                 precache_model(f);
1496
1497         globhandle = search_begin(strcat(m, "_*.sounds"), TRUE, FALSE);
1498         if (globhandle < 0)
1499                 return;
1500         n = search_getsize(globhandle);
1501         for (i = 0; i < n; ++i)
1502         {
1503                 //print(search_getfilename(globhandle, i), "\n");
1504                 f = search_getfilename(globhandle, i);
1505                 PrecachePlayerSounds(f);
1506         }
1507         search_end(globhandle);
1508 }
1509 void precache_all_playermodels(string pattern)
1510 {
1511         float globhandle, i, n;
1512         string f;
1513
1514         globhandle = search_begin(pattern, TRUE, FALSE);
1515         if (globhandle < 0)
1516                 return;
1517         n = search_getsize(globhandle);
1518         for (i = 0; i < n; ++i)
1519         {
1520                 //print(search_getfilename(globhandle, i), "\n");
1521                 f = search_getfilename(globhandle, i);
1522                 precache_playermodel(f);
1523         }
1524         search_end(globhandle);
1525 }
1526
1527 void precache()
1528 {
1529     // gamemode related things
1530     precache_model ("models/misc/chatbubble.spr");
1531     if (g_runematch)
1532     {
1533         precache_model ("models/runematch/curse.mdl");
1534         precache_model ("models/runematch/rune.mdl");
1535     }
1536
1537 #ifdef TTURRETS_ENABLED
1538     if (autocvar_g_turrets)
1539         turrets_precash();
1540 #endif
1541
1542     // Precache all player models if desired
1543     if (autocvar_sv_precacheplayermodels)
1544     {
1545         PrecachePlayerSounds("sound/player/default.sounds");
1546         precache_all_playermodels("models/player/*.zym");
1547         precache_all_playermodels("models/player/*.dpm");
1548         precache_all_playermodels("models/player/*.md3");
1549         precache_all_playermodels("models/player/*.psk");
1550         precache_all_playermodels("models/player/*.iqm");
1551     }
1552
1553     if (autocvar_sv_defaultcharacter)
1554     {
1555         string s;
1556         s = autocvar_sv_defaultplayermodel_red;
1557         if (s != "")
1558             precache_playermodel(s);
1559         s = autocvar_sv_defaultplayermodel_blue;
1560         if (s != "")
1561             precache_playermodel(s);
1562         s = autocvar_sv_defaultplayermodel_yellow;
1563         if (s != "")
1564             precache_playermodel(s);
1565         s = autocvar_sv_defaultplayermodel_pink;
1566         if (s != "")
1567             precache_playermodel(s);
1568         s = autocvar_sv_defaultplayermodel;
1569         if (s != "")
1570             precache_playermodel(s);
1571     }
1572
1573     if (g_footsteps)
1574     {
1575         PrecacheGlobalSound((globalsound_step = "misc/footstep0 6"));
1576         PrecacheGlobalSound((globalsound_metalstep = "misc/metalfootstep0 6"));
1577     }
1578
1579     // gore and miscellaneous sounds
1580     //precache_sound ("misc/h2ohit.wav");
1581     precache_model ("models/hook.md3");
1582     precache_sound ("misc/armorimpact.wav");
1583     precache_sound ("misc/bodyimpact1.wav");
1584     precache_sound ("misc/bodyimpact2.wav");
1585     precache_sound ("misc/gib.wav");
1586     precache_sound ("misc/gib_splat01.wav");
1587     precache_sound ("misc/gib_splat02.wav");
1588     precache_sound ("misc/gib_splat03.wav");
1589     precache_sound ("misc/gib_splat04.wav");
1590     PrecacheGlobalSound((globalsound_fall = "misc/hitground 4"));
1591     PrecacheGlobalSound((globalsound_metalfall = "misc/metalhitground 4"));
1592     precache_sound ("misc/null.wav");
1593     precache_sound ("misc/spawn.wav");
1594     precache_sound ("misc/talk.wav");
1595     precache_sound ("misc/teleport.wav");
1596     precache_sound ("misc/poweroff.wav");
1597     precache_sound ("player/lava.wav");
1598     precache_sound ("player/slime.wav");
1599
1600     if (g_jetpack)
1601         precache_sound ("misc/jetpack_fly.wav");
1602
1603     precache_model ("models/sprites/0.spr32");
1604     precache_model ("models/sprites/1.spr32");
1605     precache_model ("models/sprites/2.spr32");
1606     precache_model ("models/sprites/3.spr32");
1607     precache_model ("models/sprites/4.spr32");
1608     precache_model ("models/sprites/5.spr32");
1609     precache_model ("models/sprites/6.spr32");
1610     precache_model ("models/sprites/7.spr32");
1611     precache_model ("models/sprites/8.spr32");
1612     precache_model ("models/sprites/9.spr32");
1613     precache_model ("models/sprites/10.spr32");
1614
1615     // common weapon precaches
1616         precache_sound ("weapons/reload.wav"); // until weapons have individual reload sounds, precache the reload sound here
1617     precache_sound ("weapons/weapon_switch.wav");
1618     precache_sound ("weapons/weaponpickup.wav");
1619     precache_sound ("weapons/unavailable.wav");
1620     precache_sound ("weapons/dryfire.wav");
1621     if (g_grappling_hook)
1622     {
1623         precache_sound ("weapons/hook_fire.wav"); // hook
1624         precache_sound ("weapons/hook_impact.wav"); // hook
1625     }
1626
1627     if(autocvar_sv_precacheweapons)
1628     {
1629         //precache weapon models/sounds
1630         float wep;
1631         wep = WEP_FIRST;
1632         while (wep <= WEP_LAST)
1633         {
1634             weapon_action(wep, WR_PRECACHE);
1635             wep = wep + 1;
1636         }
1637     }
1638
1639     precache_model("models/elaser.mdl");
1640     precache_model("models/laser.mdl");
1641     precache_model("models/ebomb.mdl");
1642
1643 #if 0
1644     // Disabled this code because it simply does not work (e.g. ignores bgmvolume, overlaps with "cd loop" controlled tracks).
1645
1646     if (!self.noise && self.music) // quake 3 uses the music field
1647         self.noise = self.music;
1648
1649     // plays music for the level if there is any
1650     if (self.noise)
1651     {
1652         precache_sound (self.noise);
1653         ambientsound ('0 0 0', self.noise, VOL_BASE, ATTN_NONE);
1654     }
1655 #endif
1656 }
1657
1658 // sorry, but using \ in macros breaks line numbers
1659 #define WRITESPECTATABLE_MSG_ONE_VARNAME(varname,statement) entity varname; varname = msg_entity; FOR_EACH_REALCLIENT(msg_entity) if(msg_entity == varname || (msg_entity.classname == STR_SPECTATOR && msg_entity.enemy == varname)) statement msg_entity = varname
1660 #define WRITESPECTATABLE_MSG_ONE(statement) WRITESPECTATABLE_MSG_ONE_VARNAME(oldmsg_entity, statement)
1661 #define WRITESPECTATABLE(msg,statement) if(msg == MSG_ONE) { WRITESPECTATABLE_MSG_ONE(statement); } else statement float WRITESPECTATABLE_workaround = 0
1662
1663
1664 void Send_CSQC_Centerprint_Generic(entity e, float id, string s, float duration, float countdown_num)
1665 {
1666         if ((clienttype(e) == CLIENTTYPE_REAL) && (e.flags & FL_CLIENT))
1667         {
1668                 msg_entity = e;
1669                 WRITESPECTATABLE_MSG_ONE({
1670                         WriteByte(MSG_ONE, SVC_TEMPENTITY);
1671                         WriteByte(MSG_ONE, TE_CSQC_CENTERPRINT_GENERIC);
1672                         WriteByte(MSG_ONE, id);
1673                         WriteString(MSG_ONE, s);
1674                         if (id != 0 && s != "")
1675                         {
1676                                 WriteByte(MSG_ONE, duration);
1677                                 WriteByte(MSG_ONE, countdown_num);
1678                         }
1679                 });
1680         }
1681 }
1682 void Send_CSQC_Centerprint_Generic_Expire(entity e, float id)
1683 {
1684         Send_CSQC_Centerprint_Generic(e, id, "", 1, 0);
1685 }
1686 // WARNING: this kills the trace globals
1687 #define EXACTTRIGGER_TOUCH if(WarpZoneLib_ExactTrigger_Touch()) return
1688 #define EXACTTRIGGER_INIT  WarpZoneLib_ExactTrigger_Init()
1689
1690 #define INITPRIO_FIRST              0
1691 #define INITPRIO_GAMETYPE           0
1692 #define INITPRIO_GAMETYPE_FALLBACK  1
1693 #define INITPRIO_FINDTARGET        10
1694 #define INITPRIO_DROPTOFLOOR       20
1695 #define INITPRIO_SETLOCATION       90
1696 #define INITPRIO_LINKDOORS         91
1697 #define INITPRIO_LAST              99
1698
1699 .void(void) initialize_entity;
1700 .float initialize_entity_order;
1701 .entity initialize_entity_next;
1702 entity initialize_entity_first;
1703
1704 void make_safe_for_remove(entity e)
1705 {
1706     if (e.initialize_entity)
1707     {
1708         entity ent, prev = world;
1709         for (ent = initialize_entity_first; ent; )
1710         {
1711             if ((ent == e) || ((ent.classname == "initialize_entity") && (ent.enemy == e)))
1712             {
1713                 //print("make_safe_for_remove: getting rid of initializer ", etos(ent), "\n");
1714                 // skip it in linked list
1715                 if (prev)
1716                 {
1717                     prev.initialize_entity_next = ent.initialize_entity_next;
1718                     ent = prev.initialize_entity_next;
1719                 }
1720                 else
1721                 {
1722                     initialize_entity_first = ent.initialize_entity_next;
1723                     ent = initialize_entity_first;
1724                 }
1725             }
1726             else
1727             {
1728                 prev = ent;
1729                 ent = ent.initialize_entity_next;
1730             }
1731         }
1732     }
1733 }
1734
1735 void objerror(string s)
1736 {
1737     make_safe_for_remove(self);
1738     builtin_objerror(s);
1739 }
1740
1741 .float remove_except_protected_forbidden;
1742 void remove_except_protected(entity e)
1743 {
1744         if(e.remove_except_protected_forbidden)
1745                 error("not allowed to remove this at this point");
1746         builtin_remove(e);
1747 }
1748
1749 void remove_unsafely(entity e)
1750 {
1751     if(e.classname == "spike")
1752         error("Removing spikes is forbidden (crylink bug), please report");
1753     builtin_remove(e);
1754 }
1755
1756 void remove_safely(entity e)
1757 {
1758     make_safe_for_remove(e);
1759     builtin_remove(e);
1760 }
1761
1762 void InitializeEntity(entity e, void(void) func, float order)
1763 {
1764     entity prev, cur;
1765
1766     if (!e || e.initialize_entity)
1767     {
1768         // make a proxy initializer entity
1769         entity e_old;
1770         e_old = e;
1771         e = spawn();
1772         e.classname = "initialize_entity";
1773         e.enemy = e_old;
1774     }
1775
1776     e.initialize_entity = func;
1777     e.initialize_entity_order = order;
1778
1779     cur = initialize_entity_first;
1780     prev = world;
1781     for (;;)
1782     {
1783         if (!cur || cur.initialize_entity_order > order)
1784         {
1785             // insert between prev and cur
1786             if (prev)
1787                 prev.initialize_entity_next = e;
1788             else
1789                 initialize_entity_first = e;
1790             e.initialize_entity_next = cur;
1791             return;
1792         }
1793         prev = cur;
1794         cur = cur.initialize_entity_next;
1795     }
1796 }
1797 void InitializeEntitiesRun()
1798 {
1799     entity startoflist;
1800     startoflist = initialize_entity_first;
1801     initialize_entity_first = world;
1802     remove = remove_except_protected;
1803     for (self = startoflist; self; self = self.initialize_entity_next)
1804     {
1805         self.remove_except_protected_forbidden = 1;
1806     }
1807     for (self = startoflist; self; )
1808     {
1809         entity e;
1810         var void(void) func;
1811         e = self.initialize_entity_next;
1812         func = self.initialize_entity;
1813         self.initialize_entity_order = 0;
1814         self.initialize_entity = func_null;
1815         self.initialize_entity_next = world;
1816         self.remove_except_protected_forbidden = 0;
1817         if (self.classname == "initialize_entity")
1818         {
1819             entity e_old;
1820             e_old = self.enemy;
1821             builtin_remove(self);
1822             self = e_old;
1823         }
1824         //dprint("Delayed initialization: ", self.classname, "\n");
1825         if(func != func_null)
1826             func();
1827         else
1828         {
1829             eprint(self);
1830             backtrace(strcat("Null function in: ", self.classname, "\n"));
1831         }
1832         self = e;
1833     }
1834     remove = remove_unsafely;
1835 }
1836
1837 .float uncustomizeentityforclient_set;
1838 .void(void) uncustomizeentityforclient;
1839 void(void) SUB_Nullpointer = #0;
1840 void UncustomizeEntitiesRun()
1841 {
1842     entity oldself;
1843     oldself = self;
1844     for (self = world; (self = findfloat(self, uncustomizeentityforclient_set, 1)); )
1845         self.uncustomizeentityforclient();
1846     self = oldself;
1847 }
1848 void SetCustomizer(entity e, float(void) customizer, void(void) uncustomizer)
1849 {
1850     e.customizeentityforclient = customizer;
1851     e.uncustomizeentityforclient = uncustomizer;
1852     e.uncustomizeentityforclient_set = (uncustomizer != SUB_Nullpointer);
1853 }
1854
1855 .float nottargeted;
1856 #define IFTARGETED if(!self.nottargeted && self.targetname != "")
1857
1858 void() SUB_Remove;
1859 void Net_LinkEntity(entity e, float docull, float dt, float(entity, float) sendfunc)
1860 {
1861     vector mi, ma;
1862
1863     if (e.classname == "")
1864         e.classname = "net_linked";
1865
1866     if (e.model == "" || self.modelindex == 0)
1867     {
1868         mi = e.mins;
1869         ma = e.maxs;
1870         setmodel(e, "null");
1871         setsize(e, mi, ma);
1872     }
1873
1874     e.SendEntity = sendfunc;
1875     e.SendFlags = 0xFFFFFF;
1876
1877     if (!docull)
1878         e.effects |= EF_NODEPTHTEST;
1879
1880     if (dt)
1881     {
1882         e.nextthink = time + dt;
1883         e.think = SUB_Remove;
1884     }
1885 }
1886
1887 void adaptor_think2touch()
1888 {
1889     entity o;
1890     o = other;
1891     other = world;
1892     self.touch();
1893     other = o;
1894 }
1895
1896 void adaptor_think2use()
1897 {
1898     entity o, a;
1899     o = other;
1900     a = activator;
1901     activator = world;
1902     other = world;
1903     self.use();
1904     other = o;
1905     activator = a;
1906 }
1907
1908 void adaptor_think2use_hittype_splash() // for timed projectile detonation
1909 {
1910         if not(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
1911                 self.projectiledeathtype |= HITTYPE_SPLASH;
1912         adaptor_think2use();
1913 }
1914
1915 // deferred dropping
1916 void DropToFloor_Handler()
1917 {
1918     builtin_droptofloor();
1919     self.dropped_origin = self.origin;
1920 }
1921
1922 void droptofloor()
1923 {
1924     InitializeEntity(self, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
1925 }
1926
1927
1928
1929 float trace_hits_box_a0, trace_hits_box_a1;
1930
1931 float trace_hits_box_1d(float end, float thmi, float thma)
1932 {
1933     if (end == 0)
1934     {
1935         // just check if x is in range
1936         if (0 < thmi)
1937             return FALSE;
1938         if (0 > thma)
1939             return FALSE;
1940     }
1941     else
1942     {
1943         // do the trace with respect to x
1944         // 0 -> end has to stay in thmi -> thma
1945         trace_hits_box_a0 = max(trace_hits_box_a0, min(thmi / end, thma / end));
1946         trace_hits_box_a1 = min(trace_hits_box_a1, max(thmi / end, thma / end));
1947         if (trace_hits_box_a0 > trace_hits_box_a1)
1948             return FALSE;
1949     }
1950     return TRUE;
1951 }
1952
1953 float trace_hits_box(vector start, vector end, vector thmi, vector thma)
1954 {
1955     end -= start;
1956     thmi -= start;
1957     thma -= start;
1958     // now it is a trace from 0 to end
1959
1960     trace_hits_box_a0 = 0;
1961     trace_hits_box_a1 = 1;
1962
1963     if (!trace_hits_box_1d(end_x, thmi_x, thma_x))
1964         return FALSE;
1965     if (!trace_hits_box_1d(end_y, thmi_y, thma_y))
1966         return FALSE;
1967     if (!trace_hits_box_1d(end_z, thmi_z, thma_z))
1968         return FALSE;
1969
1970     return TRUE;
1971 }
1972
1973 float tracebox_hits_box(vector start, vector mi, vector ma, vector end, vector thmi, vector thma)
1974 {
1975     return trace_hits_box(start, end, thmi - ma, thma - mi);
1976 }
1977
1978 float SUB_NoImpactCheck()
1979 {
1980         // zero hitcontents = this is not the real impact, but either the
1981         // mirror-impact of something hitting the projectile instead of the
1982         // projectile hitting the something, or a touchareagrid one. Neither of
1983         // these stop the projectile from moving, so...
1984         if(trace_dphitcontents == 0)
1985         {
1986                 //dprint("A hit happened with zero hit contents... DEBUG THIS, this should never happen for projectiles! Projectile will self-destruct.\n");
1987                 dprint(sprintf(_("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)));
1988                 checkclient();
1989         }
1990     if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1991         return 1;
1992     if (other == world && self.size != '0 0 0')
1993     {
1994         vector tic;
1995         tic = self.velocity * sys_frametime;
1996         tic = tic + normalize(tic) * vlen(self.maxs - self.mins);
1997         traceline(self.origin - tic, self.origin + tic, MOVE_NORMAL, self);
1998         if (trace_fraction >= 1)
1999         {
2000             dprint("Odd... did not hit...?\n");
2001         }
2002         else if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
2003         {
2004             dprint("Detected and prevented the sky-grapple bug.\n");
2005             return 1;
2006         }
2007     }
2008
2009     return 0;
2010 }
2011
2012 #define SUB_OwnerCheck() (other && (other == self.owner))
2013
2014 void RemoveGrapplingHook(entity pl);
2015 void W_Crylink_Dequeue(entity e);
2016 float WarpZone_Projectile_Touch_ImpactFilter_Callback()
2017 {
2018         if(SUB_OwnerCheck())
2019                 return TRUE;
2020         if(SUB_NoImpactCheck())
2021         {
2022                 if(self.classname == "grapplinghook")
2023                         RemoveGrapplingHook(self.realowner);
2024                 else if(self.classname == "spike")
2025                 {
2026                         W_Crylink_Dequeue(self);
2027                         remove(self);
2028                 }
2029                 else
2030                         remove(self);
2031                 return TRUE;
2032         }
2033         if(trace_ent && trace_ent.solid > SOLID_TRIGGER)
2034                 UpdateCSQCProjectile(self);
2035         return FALSE;
2036 }
2037 #define PROJECTILE_TOUCH if(WarpZone_Projectile_Touch()) return
2038
2039 #define ITEM_TOUCH_NEEDKILL() (((trace_dpstartcontents | trace_dphitcontents) & DPCONTENTS_NODROP) || (trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY))
2040 #define ITEM_DAMAGE_NEEDKILL(dt) (((dt) == DEATH_HURTTRIGGER) || ((dt) == DEATH_SLIME) || ((dt) == DEATH_LAVA) || ((dt) == DEATH_SWAMP))
2041
2042 void URI_Get_Callback(float id, float status, string data)
2043 {
2044         if(url_URI_Get_Callback(id, status, data))
2045         {
2046                 // handled
2047         }
2048         else if (id == URI_GET_DISCARD)
2049         {
2050                 // discard
2051         }
2052         else if (id >= URI_GET_CURL && id <= URI_GET_CURL_END)
2053         {
2054                 // sv_cmd curl
2055                 Curl_URI_Get_Callback(id, status, data);
2056         }
2057         else if (id >= URI_GET_IPBAN && id <= URI_GET_IPBAN_END)
2058         {
2059                 // online ban list
2060                 OnlineBanList_URI_Get_Callback(id, status, data);
2061         }
2062         else
2063         {
2064                 print("Received HTTP request data for an invalid id ", ftos(id), ".\n");
2065         }
2066 }
2067
2068 string uid2name(string myuid) {
2069         string s;
2070         s = db_get(ServerProgsDB, strcat("/uid2name/", myuid));
2071
2072         // FIXME remove this later after 0.6 release
2073         // convert old style broken records to correct style
2074         if(s == "")
2075         {
2076                 s = db_get(ServerProgsDB, strcat("uid2name", myuid));
2077                 if(s != "")
2078                 {
2079                         db_put(ServerProgsDB, strcat("/uid2name/", myuid), s);
2080                         db_put(ServerProgsDB, strcat("uid2name", myuid), "");
2081                 }
2082         }
2083         
2084         if(s == "")
2085                 s = "^1Unregistered Player";
2086         return s;
2087 }
2088
2089 float race_readTime(string map, float pos)
2090 {
2091         string rr;
2092         if(g_cts)
2093                 rr = CTS_RECORD;
2094         else
2095                 rr = RACE_RECORD;
2096
2097         return stof(db_get(ServerProgsDB, strcat(map, rr, "time", ftos(pos))));
2098 }
2099
2100 string race_readUID(string map, float pos)
2101 {
2102         string rr;
2103         if(g_cts)
2104                 rr = CTS_RECORD;
2105         else
2106                 rr = RACE_RECORD;
2107
2108         return db_get(ServerProgsDB, strcat(map, rr, "crypto_idfp", ftos(pos)));
2109 }
2110
2111 float race_readPos(string map, float t) {
2112         float i;
2113         for (i = 1; i <= RANKINGS_CNT; ++i)
2114                 if (race_readTime(map, i) == 0 || race_readTime(map, i) > t)
2115                         return i;
2116
2117         return 0; // pos is zero if unranked
2118 }
2119
2120 void race_writeTime(string map, float t, string myuid)
2121 {
2122         string rr;
2123         if(g_cts)
2124                 rr = CTS_RECORD;
2125         else
2126                 rr = RACE_RECORD;
2127
2128         float newpos;
2129         newpos = race_readPos(map, t);
2130
2131         float i, prevpos = 0;
2132         for(i = 1; i <= RANKINGS_CNT; ++i)
2133         {
2134                 if(race_readUID(map, i) == myuid)
2135                         prevpos = i;
2136         }
2137         if (prevpos) { // player improved his existing record, only have to iterate on ranks between new and old recs
2138                 for (i = prevpos; i > newpos; --i) {
2139                         db_put(ServerProgsDB, strcat(map, rr, "time", ftos(i)), ftos(race_readTime(map, i - 1)));
2140                         db_put(ServerProgsDB, strcat(map, rr, "crypto_idfp", ftos(i)), race_readUID(map, i - 1));
2141                 }
2142         } else { // player has no ranked record yet
2143                 for (i = RANKINGS_CNT; i > newpos; --i) {
2144                         db_put(ServerProgsDB, strcat(map, rr, "time", ftos(i)), ftos(race_readTime(map, i - 1)));
2145                         db_put(ServerProgsDB, strcat(map, rr, "crypto_idfp", ftos(i)), race_readUID(map, i - 1));
2146                 }
2147         }
2148
2149         // store new time itself
2150         db_put(ServerProgsDB, strcat(map, rr, "time", ftos(newpos)), ftos(t));
2151         db_put(ServerProgsDB, strcat(map, rr, "crypto_idfp", ftos(newpos)), myuid);
2152 }
2153
2154 string race_readName(string map, float pos)
2155 {
2156         string rr;
2157         if(g_cts)
2158                 rr = CTS_RECORD;
2159         else
2160                 rr = RACE_RECORD;
2161
2162         return uid2name(db_get(ServerProgsDB, strcat(map, rr, "crypto_idfp", ftos(pos))));
2163 }
2164
2165 string race_placeName(float pos) {
2166         if(floor((mod(pos, 100))/10) * 10 != 10) // examples: 12th, 111th, 213th will not execute this block
2167         {
2168                 if(mod(pos, 10) == 1)
2169                         return strcat(ftos(pos), "st");
2170                 else if(mod(pos, 10) == 2)
2171                         return strcat(ftos(pos), "nd");
2172                 else if(mod(pos, 10) == 3)
2173                         return strcat(ftos(pos), "rd");
2174                 else
2175                         return strcat(ftos(pos), "th");
2176         }
2177         else
2178                 return strcat(ftos(pos), "th");
2179 }
2180
2181 float MoveToRandomMapLocation(entity e, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
2182 {
2183     float m, i;
2184     vector start, org, delta, end, enddown, mstart;
2185     entity sp;
2186
2187     m = e.dphitcontentsmask;
2188     e.dphitcontentsmask = goodcontents | badcontents;
2189
2190     org = world.mins;
2191     delta = world.maxs - world.mins;
2192
2193     start = end = org;
2194
2195     for (i = 0; i < attempts; ++i)
2196     {
2197         start_x = org_x + random() * delta_x;
2198         start_y = org_y + random() * delta_y;
2199         start_z = org_z + random() * delta_z;
2200
2201         // rule 1: start inside world bounds, and outside
2202         // solid, and don't start from somewhere where you can
2203         // fall down to evil
2204         tracebox(start, e.mins, e.maxs, start - '0 0 1' * delta_z, MOVE_NORMAL, e);
2205         if (trace_fraction >= 1)
2206             continue;
2207         if (trace_startsolid)
2208             continue;
2209         if (trace_dphitcontents & badcontents)
2210             continue;
2211         if (trace_dphitq3surfaceflags & badsurfaceflags)
2212             continue;
2213
2214         // rule 2: if we are too high, lower the point
2215         if (trace_fraction * delta_z > maxaboveground)
2216             start = trace_endpos + '0 0 1' * maxaboveground;
2217         enddown = trace_endpos;
2218
2219         // rule 3: make sure we aren't outside the map. This only works
2220         // for somewhat well formed maps. A good rule of thumb is that
2221         // the map should have a convex outside hull.
2222         // these can be traceLINES as we already verified the starting box
2223         mstart = start + 0.5 * (e.mins + e.maxs);
2224         traceline(mstart, mstart + '1 0 0' * delta_x, MOVE_NORMAL, e);
2225         if (trace_fraction >= 1)
2226             continue;
2227         traceline(mstart, mstart - '1 0 0' * delta_x, MOVE_NORMAL, e);
2228         if (trace_fraction >= 1)
2229             continue;
2230         traceline(mstart, mstart + '0 1 0' * delta_y, MOVE_NORMAL, e);
2231         if (trace_fraction >= 1)
2232             continue;
2233         traceline(mstart, mstart - '0 1 0' * delta_y, MOVE_NORMAL, e);
2234         if (trace_fraction >= 1)
2235             continue;
2236         traceline(mstart, mstart + '0 0 1' * delta_z, MOVE_NORMAL, e);
2237         if (trace_fraction >= 1)
2238             continue;
2239
2240         // rule 4: we must "see" some spawnpoint
2241         for(sp = world; (sp = find(sp, classname, "info_player_deathmatch")); )
2242                 if(checkpvs(mstart, sp))
2243                         break;
2244         if(!sp)
2245         {
2246                 for(sp = world; (sp = findflags(sp, flags, FL_ITEM)); )
2247                         if(checkpvs(mstart, sp))
2248                                 break;
2249                 if(!sp)
2250                         continue;
2251         }
2252
2253         // find a random vector to "look at"
2254         end_x = org_x + random() * delta_x;
2255         end_y = org_y + random() * delta_y;
2256         end_z = org_z + random() * delta_z;
2257         end = start + normalize(end - start) * vlen(delta);
2258
2259         // rule 4: start TO end must not be too short
2260         tracebox(start, e.mins, e.maxs, end, MOVE_NORMAL, e);
2261         if (trace_startsolid)
2262             continue;
2263         if (trace_fraction < minviewdistance / vlen(delta))
2264             continue;
2265
2266         // rule 5: don't want to look at sky
2267         if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY)
2268             continue;
2269
2270         // rule 6: we must not end up in trigger_hurt
2271         if (tracebox_hits_trigger_hurt(start, e.mins, e.maxs, enddown))
2272             continue;
2273
2274         break;
2275     }
2276
2277     e.dphitcontentsmask = m;
2278
2279     if (i < attempts)
2280     {
2281         setorigin(e, start);
2282         e.angles = vectoangles(end - start);
2283         dprint("Needed ", ftos(i + 1), " attempts\n");
2284         return TRUE;
2285     }
2286     else
2287         return FALSE;
2288 }
2289
2290 float zcurveparticles_effectno;
2291 vector zcurveparticles_start;
2292 float zcurveparticles_spd;
2293
2294 void endzcurveparticles()
2295 {
2296         if(zcurveparticles_effectno)
2297         {
2298                 // terminator
2299                 WriteShort(MSG_BROADCAST, zcurveparticles_spd | 0x8000);
2300         }
2301         zcurveparticles_effectno = 0;
2302 }
2303
2304 void zcurveparticles(float effectno, vector start, vector end, float end_dz, float spd)
2305 {
2306         spd = bound(0, floor(spd / 16), 32767);
2307         if(effectno != zcurveparticles_effectno || start != zcurveparticles_start)
2308         {
2309                 endzcurveparticles();
2310                 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
2311                 WriteByte(MSG_BROADCAST, TE_CSQC_ZCURVEPARTICLES);
2312                 WriteShort(MSG_BROADCAST, effectno);
2313                 WriteCoord(MSG_BROADCAST, start_x);
2314                 WriteCoord(MSG_BROADCAST, start_y);
2315                 WriteCoord(MSG_BROADCAST, start_z);
2316                 zcurveparticles_effectno = effectno;
2317                 zcurveparticles_start = start;
2318         }
2319         else
2320                 WriteShort(MSG_BROADCAST, zcurveparticles_spd);
2321         WriteCoord(MSG_BROADCAST, end_x);
2322         WriteCoord(MSG_BROADCAST, end_y);
2323         WriteCoord(MSG_BROADCAST, end_z);
2324         WriteCoord(MSG_BROADCAST, end_dz);
2325         zcurveparticles_spd = spd;
2326 }
2327
2328 void zcurveparticles_from_tracetoss(float effectno, vector start, vector end, vector vel)
2329 {
2330         float end_dz;
2331         vector vecxy, velxy;
2332
2333         vecxy = end - start;
2334         vecxy_z = 0;
2335         velxy = vel;
2336         velxy_z = 0;
2337
2338         if (vlen(velxy) < 0.000001 * fabs(vel_z))
2339         {
2340                 endzcurveparticles();
2341                 trailparticles(world, effectno, start, end);
2342                 return;
2343         }
2344
2345         end_dz = vlen(vecxy) / vlen(velxy) * vel_z - (end_z - start_z);
2346         zcurveparticles(effectno, start, end, end_dz, vlen(vel));
2347 }
2348
2349 void write_recordmarker(entity pl, float tstart, float dt)
2350 {
2351     GameLogEcho(strcat(":recordset:", ftos(pl.playerid), ":", ftos(dt)));
2352
2353     // also write a marker into demo files for demotc-race-record-extractor to find
2354     stuffcmd(pl,
2355              strcat(
2356                  strcat("//", strconv(2, 0, 0, GetGametype()), " RECORD SET ", TIME_ENCODED_TOSTRING(TIME_ENCODE(dt))),
2357                  " ", ftos(tstart), " ", ftos(dt), "\n"));
2358 }
2359
2360 vector shotorg_adjustfromclient(vector vecs, float y_is_right, float allowcenter, float algn)
2361 {
2362         switch(algn)
2363         {
2364                 default:
2365                 case 3: // right
2366                         break;
2367
2368                 case 4: // left
2369                         vecs_y = -vecs_y;
2370                         break;
2371
2372                 case 1:
2373                         if(allowcenter) // 2: allow center handedness
2374                         {
2375                                 // center
2376                                 vecs_y = 0;
2377                                 vecs_z -= 2;
2378                         }
2379                         else
2380                         {
2381                                 // right
2382                         }
2383                         break;
2384
2385                 case 2:
2386                         if(allowcenter) // 2: allow center handedness
2387                         {
2388                                 // center
2389                                 vecs_y = 0;
2390                                 vecs_z -= 2;
2391                         }
2392                         else
2393                         {
2394                                 // left
2395                                 vecs_y = -vecs_y;
2396                         }
2397                         break;
2398         }
2399         return vecs;
2400 }
2401
2402 vector shotorg_adjust_values(vector vecs, float y_is_right, float visual, float algn)
2403 {
2404         string s;
2405         vector v;
2406
2407         if (autocvar_g_shootfromeye)
2408         {
2409                 if (visual)
2410                 {
2411                         vecs_y = 0;
2412                         vecs_z -= 2;
2413                 }
2414                 else
2415                 {
2416                         vecs_y = 0;
2417                         vecs_z = 0;
2418                 }
2419         }
2420         else if (autocvar_g_shootfromcenter)
2421         {
2422                 vecs_y = 0;
2423                 vecs_z -= 2;
2424         }
2425         else if ((s = autocvar_g_shootfromfixedorigin) != "")
2426         {
2427                 v = stov(s);
2428                 if (y_is_right)
2429                         v_y = -v_y;
2430                 if (v_x != 0)
2431                         vecs_x = v_x;
2432                 vecs_y = v_y;
2433                 vecs_z = v_z;
2434         }
2435         else if (autocvar_g_shootfromclient)
2436         {
2437                 vecs = shotorg_adjustfromclient(vecs, y_is_right, (autocvar_g_shootfromclient >= 2), algn);
2438         }
2439         return vecs;
2440 }
2441
2442 vector shotorg_adjust(vector vecs, float y_is_right, float visual)
2443 {
2444         return shotorg_adjust_values(vecs, y_is_right, visual, self.owner.cvar_cl_gunalign);
2445 }
2446
2447
2448 void attach_sameorigin(entity e, entity to, string tag)
2449 {
2450     vector org, t_forward, t_left, t_up, e_forward, e_up;
2451     float tagscale;
2452
2453     org = e.origin - gettaginfo(to, gettagindex(to, tag));
2454     tagscale = pow(vlen(v_forward), -2); // undo a scale on the tag
2455     t_forward = v_forward * tagscale;
2456     t_left = v_right * -tagscale;
2457     t_up = v_up * tagscale;
2458
2459     e.origin_x = org * t_forward;
2460     e.origin_y = org * t_left;
2461     e.origin_z = org * t_up;
2462
2463     // current forward and up directions
2464     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
2465                 e.angles = AnglesTransform_FromVAngles(e.angles);
2466         else
2467                 e.angles = AnglesTransform_FromAngles(e.angles);
2468     fixedmakevectors(e.angles);
2469
2470     // untransform forward, up!
2471     e_forward_x = v_forward * t_forward;
2472     e_forward_y = v_forward * t_left;
2473     e_forward_z = v_forward * t_up;
2474     e_up_x = v_up * t_forward;
2475     e_up_y = v_up * t_left;
2476     e_up_z = v_up * t_up;
2477
2478     e.angles = fixedvectoangles2(e_forward, e_up);
2479     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
2480                 e.angles = AnglesTransform_ToVAngles(e.angles);
2481         else
2482                 e.angles = AnglesTransform_ToAngles(e.angles);
2483
2484     setattachment(e, to, tag);
2485     setorigin(e, e.origin);
2486 }
2487
2488 void detach_sameorigin(entity e)
2489 {
2490     vector org;
2491     org = gettaginfo(e, 0);
2492     e.angles = fixedvectoangles2(v_forward, v_up);
2493     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
2494                 e.angles = AnglesTransform_ToVAngles(e.angles);
2495         else
2496                 e.angles = AnglesTransform_ToAngles(e.angles);
2497     setorigin(e, org);
2498     setattachment(e, world, "");
2499     setorigin(e, e.origin);
2500 }
2501
2502 void follow_sameorigin(entity e, entity to)
2503 {
2504     e.movetype = MOVETYPE_FOLLOW; // make the hole follow
2505     e.aiment = to; // make the hole follow bmodel
2506     e.punchangle = to.angles; // the original angles of bmodel
2507     e.view_ofs = e.origin - to.origin; // relative origin
2508     e.v_angle = e.angles - to.angles; // relative angles
2509 }
2510
2511 void unfollow_sameorigin(entity e)
2512 {
2513     e.movetype = MOVETYPE_NONE;
2514 }
2515
2516 entity gettaginfo_relative_ent;
2517 vector gettaginfo_relative(entity e, float tag)
2518 {
2519     if (!gettaginfo_relative_ent)
2520     {
2521         gettaginfo_relative_ent = spawn();
2522         gettaginfo_relative_ent.effects = EF_NODRAW;
2523     }
2524     gettaginfo_relative_ent.model = e.model;
2525     gettaginfo_relative_ent.modelindex = e.modelindex;
2526     gettaginfo_relative_ent.frame = e.frame;
2527     return gettaginfo(gettaginfo_relative_ent, tag);
2528 }
2529
2530 void SoundEntity_StartSound(entity pl, float chan, string samp, float vol, float attn)
2531 {
2532     float p;
2533     p = pow(2, chan);
2534     if (pl.soundentity.cnt & p)
2535         return;
2536     soundtoat(MSG_ALL, pl.soundentity, gettaginfo(pl.soundentity, 0), chan, samp, vol, attn);
2537     pl.soundentity.cnt |= p;
2538 }
2539
2540 void SoundEntity_StopSound(entity pl, float chan)
2541 {
2542     float p;
2543     p = pow(2, chan);
2544     if (pl.soundentity.cnt & p)
2545     {
2546         stopsoundto(MSG_ALL, pl.soundentity, chan);
2547         pl.soundentity.cnt &~= p;
2548     }
2549 }
2550
2551 void SoundEntity_Attach(entity pl)
2552 {
2553     pl.soundentity = spawn();
2554     pl.soundentity.classname = "soundentity";
2555     pl.soundentity.owner = pl;
2556     setattachment(pl.soundentity, pl, "");
2557     setmodel(pl.soundentity, "null");
2558 }
2559
2560 void SoundEntity_Detach(entity pl)
2561 {
2562     float i;
2563     for (i = 0; i <= 7; ++i)
2564         SoundEntity_StopSound(pl, i);
2565 }
2566
2567 .float scale2;
2568
2569 float modeleffect_SendEntity(entity to, float sf)
2570 {
2571         float f;
2572         WriteByte(MSG_ENTITY, ENT_CLIENT_MODELEFFECT);
2573
2574         f = 0;
2575         if(self.velocity != '0 0 0')
2576                 f |= 1;
2577         if(self.angles != '0 0 0')
2578                 f |= 2;
2579         if(self.avelocity != '0 0 0')
2580                 f |= 4;
2581
2582         WriteByte(MSG_ENTITY, f);
2583         WriteShort(MSG_ENTITY, self.modelindex);
2584         WriteByte(MSG_ENTITY, self.skin);
2585         WriteByte(MSG_ENTITY, self.frame);
2586         WriteCoord(MSG_ENTITY, self.origin_x);
2587         WriteCoord(MSG_ENTITY, self.origin_y);
2588         WriteCoord(MSG_ENTITY, self.origin_z);
2589         if(f & 1)
2590         {
2591                 WriteCoord(MSG_ENTITY, self.velocity_x);
2592                 WriteCoord(MSG_ENTITY, self.velocity_y);
2593                 WriteCoord(MSG_ENTITY, self.velocity_z);
2594         }
2595         if(f & 2)
2596         {
2597                 WriteCoord(MSG_ENTITY, self.angles_x);
2598                 WriteCoord(MSG_ENTITY, self.angles_y);
2599                 WriteCoord(MSG_ENTITY, self.angles_z);
2600         }
2601         if(f & 4)
2602         {
2603                 WriteCoord(MSG_ENTITY, self.avelocity_x);
2604                 WriteCoord(MSG_ENTITY, self.avelocity_y);
2605                 WriteCoord(MSG_ENTITY, self.avelocity_z);
2606         }
2607         WriteShort(MSG_ENTITY, self.scale * 256.0);
2608         WriteShort(MSG_ENTITY, self.scale2 * 256.0);
2609         WriteByte(MSG_ENTITY, self.teleport_time * 100.0);
2610         WriteByte(MSG_ENTITY, self.fade_time * 100.0);
2611         WriteByte(MSG_ENTITY, self.alpha * 255.0);
2612
2613         return TRUE;
2614 }
2615
2616 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)
2617 {
2618         entity e;
2619         float sz;
2620         e = spawn();
2621         e.classname = "modeleffect";
2622         setmodel(e, m);
2623         e.frame = f;
2624         setorigin(e, o);
2625         e.velocity = v;
2626         e.angles = ang;
2627         e.avelocity = angv;
2628         e.alpha = a;
2629         e.teleport_time = t1;
2630         e.fade_time = t2;
2631         e.skin = s;
2632         if(s0 >= 0)
2633                 e.scale = s0 / max6(-e.mins_x, -e.mins_y, -e.mins_z, e.maxs_x, e.maxs_y, e.maxs_z);
2634         else
2635                 e.scale = -s0;
2636         if(s2 >= 0)
2637                 e.scale2 = s2 / max6(-e.mins_x, -e.mins_y, -e.mins_z, e.maxs_x, e.maxs_y, e.maxs_z);
2638         else
2639                 e.scale2 = -s2;
2640         sz = max(e.scale, e.scale2);
2641         setsize(e, e.mins * sz, e.maxs * sz);
2642         Net_LinkEntity(e, FALSE, 0.1, modeleffect_SendEntity);
2643 }
2644
2645 void shockwave_spawn(string m, vector org, float sz, float t1, float t2)
2646 {
2647         return modeleffect_spawn(m, 0, 0, org, '0 0 0', '0 0 0', '0 0 0', 0, sz, 1, t1, t2);
2648 }
2649
2650 float randombit(float bits)
2651 {
2652         if not(bits & (bits-1)) // this ONLY holds for powers of two!
2653                 return bits;
2654
2655         float n, f, b, r;
2656
2657         r = random();
2658         b = 0;
2659         n = 0;
2660
2661         for(f = 1; f <= bits; f *= 2)
2662         {
2663                 if(bits & f)
2664                 {
2665                         ++n;
2666                         r *= n;
2667                         if(r <= 1)
2668                                 b = f;
2669                         else
2670                                 r = (r - 1) / (n - 1);
2671                 }
2672         }
2673
2674         return b;
2675 }
2676
2677 float randombits(float bits, float k, float error_return)
2678 {
2679         float r;
2680         r = 0;
2681         while(k > 0 && bits != r)
2682         {
2683                 r += randombit(bits - r);
2684                 --k;
2685         }
2686         if(error_return)
2687                 if(k > 0)
2688                         return -1; // all
2689         return r;
2690 }
2691
2692 void randombit_test(float bits, float iter)
2693 {
2694         while(iter > 0)
2695         {
2696                 print(ftos(randombit(bits)), "\n");
2697                 --iter;
2698         }
2699 }
2700
2701 float ExponentialFalloff(float mindist, float maxdist, float halflifedist, float d)
2702 {
2703         if(halflifedist > 0)
2704                 return pow(0.5, (bound(mindist, d, maxdist) - mindist) / halflifedist);
2705         else if(halflifedist < 0)
2706                 return pow(0.5, (bound(mindist, d, maxdist) - maxdist) / halflifedist);
2707         else
2708                 return 1;
2709 }
2710
2711
2712
2713
2714 #ifdef RELEASE
2715 #define cvar_string_normal builtin_cvar_string
2716 #define cvar_normal builtin_cvar
2717 #else
2718 string cvar_string_normal(string n)
2719 {
2720         if not(cvar_type(n) & 1)
2721                 backtrace(strcat("Attempt to access undefined cvar: ", n));
2722         return builtin_cvar_string(n);
2723 }
2724
2725 float cvar_normal(string n)
2726 {
2727         return stof(cvar_string_normal(n));
2728 }
2729 #endif
2730 #define cvar_set_normal builtin_cvar_set
2731
2732 void defer_think()
2733 {
2734     entity oself;
2735
2736     oself           = self;
2737     self            = self.owner;
2738     oself.think     = SUB_Remove;
2739     oself.nextthink = time;
2740
2741     oself.use();
2742 }
2743
2744 /*
2745     Execute func() after time + fdelay.
2746     self when func is executed = self when defer is called
2747 */
2748 void defer(float fdelay, void() func)
2749 {
2750     entity e;
2751
2752     e           = spawn();
2753     e.owner     = self;
2754     e.use       = func;
2755     e.think     = defer_think;
2756     e.nextthink = time + fdelay;
2757 }
2758
2759 .string aiment_classname;
2760 .float aiment_deadflag;
2761 void SetMovetypeFollow(entity ent, entity e)
2762 {
2763         // FIXME this may not be warpzone aware
2764         ent.movetype = MOVETYPE_FOLLOW; // make the hole follow
2765         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.
2766         ent.aiment = e; // make the hole follow bmodel
2767         ent.punchangle = e.angles; // the original angles of bmodel
2768         ent.view_ofs = ent.origin - e.origin; // relative origin
2769         ent.v_angle = ent.angles - e.angles; // relative angles
2770         ent.aiment_classname = strzone(e.classname);
2771         ent.aiment_deadflag = e.deadflag;
2772 }
2773 void UnsetMovetypeFollow(entity ent)
2774 {
2775         ent.movetype = MOVETYPE_FLY;
2776         PROJECTILE_MAKETRIGGER(ent);
2777         ent.aiment = world;
2778 }
2779 float LostMovetypeFollow(entity ent)
2780 {
2781 /*
2782         if(ent.movetype != MOVETYPE_FOLLOW)
2783                 if(ent.aiment)
2784                         error("???");
2785 */
2786         if(ent.aiment)
2787         {
2788                 if(ent.aiment.classname != ent.aiment_classname)
2789                         return 1;
2790                 if(ent.aiment.deadflag != ent.aiment_deadflag)
2791                         return 1;
2792         }
2793         return 0;
2794 }
2795
2796 float isPushable(entity e)
2797 {
2798         if(e.iscreature)
2799                 return TRUE;
2800         switch(e.classname)
2801         {
2802                 case "body":
2803                 case "droppedweapon":
2804                 case "keepawayball":
2805                 case "nexball_basketball":
2806                 case "nexball_football":
2807                         return TRUE;
2808                 case "bullet": // antilagged bullets can't hit this either
2809                         return FALSE;
2810         }
2811         if (e.projectiledeathtype)
2812                 return TRUE;
2813         return FALSE;
2814 }