]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/miscfunctions.qc
add a new cheat "impulse 404"; some CSQC refactorings; distribute prandom seed as...
[divverent/nexuiz.git] / data / 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() spawnfunc_info_player_deathmatch; // needed for the other spawnpoints
7 void() spawnpoint_use;
8 string ColoredTeamName(float t);
9
10 float RandomSelection_totalweight;
11 float RandomSelection_best_priority;
12 entity RandomSelection_chosen_ent;
13 float RandomSelection_chosen_float;
14 void RandomSelection_Init()
15 {
16         RandomSelection_totalweight = 0;
17         RandomSelection_chosen_ent = world;
18         RandomSelection_chosen_float = 0;
19         RandomSelection_best_priority = -1;
20 }
21 void RandomSelection_Add(entity e, float f, float weight, float priority)
22 {
23         if(priority > RandomSelection_best_priority)
24         {
25                 RandomSelection_best_priority = priority;
26                 RandomSelection_chosen_ent = e;
27                 RandomSelection_chosen_float = f;
28                 RandomSelection_totalweight = weight;
29         }
30         else if(priority == RandomSelection_best_priority)
31         {
32                 RandomSelection_totalweight += weight;
33                 if(random() * RandomSelection_totalweight <= weight)
34                 {
35                         RandomSelection_chosen_ent = e;
36                         RandomSelection_chosen_float = f;
37                 }
38         }
39 }
40
41 float DistributeEvenly_amount;
42 float DistributeEvenly_totalweight;
43 void DistributeEvenly_Init(float amount, float totalweight)
44 {
45         if(DistributeEvenly_amount)
46         {
47                 dprint("DistributeEvenly_Init: UNFINISHED DISTRIBUTION (", ftos(DistributeEvenly_amount), " for ");
48                 dprint(ftos(DistributeEvenly_totalweight), " left!)\n");
49         }
50         if(totalweight == 0)
51                 DistributeEvenly_amount = 0;
52         else
53                 DistributeEvenly_amount = amount;
54         DistributeEvenly_totalweight = totalweight;
55 }
56 float DistributeEvenly_Get(float weight)
57 {
58         float f;
59         if(weight <= 0)
60                 return 0;
61         f = floor(0.5 + DistributeEvenly_amount * weight / DistributeEvenly_totalweight);
62         DistributeEvenly_totalweight -= weight;
63         DistributeEvenly_amount -= f;
64         return f;
65 }
66
67 void move_out_of_solid_expand(entity e, vector by)
68 {
69         float eps = 0.0625;
70         tracebox(e.origin, e.mins - '1 1 1' * eps, e.maxs + '1 1 1' * eps, e.origin + by, MOVE_WORLDONLY, e);
71         if(trace_startsolid)
72                 return;
73         if(trace_fraction < 1)
74         {
75                 // hit something
76                 // adjust origin in the other direction...
77                 e.origin = e.origin - by * (1 - trace_fraction);
78         }
79 }
80
81 float move_out_of_solid(entity e)
82 {
83         vector o, m0, m1;
84
85         o = e.origin;
86         traceline(o, o, MOVE_WORLDONLY, e);
87         if(trace_startsolid)
88                 return 0;
89
90         tracebox(o, e.mins, e.maxs, o, MOVE_WORLDONLY, e);
91         if(!trace_startsolid)
92                 return 1;
93
94         m0 = e.mins;
95         m1 = e.maxs;
96         e.mins = '0 0 0';
97         e.maxs = '0 0 0';
98         move_out_of_solid_expand(e, '1 0 0' * m0_x); e.mins_x = m0_x;
99         move_out_of_solid_expand(e, '1 0 0' * m1_x); e.maxs_x = m1_x;
100         move_out_of_solid_expand(e, '0 1 0' * m0_y); e.mins_y = m0_y;
101         move_out_of_solid_expand(e, '0 1 0' * m1_y); e.maxs_y = m1_y;
102         move_out_of_solid_expand(e, '0 0 1' * m0_z); e.mins_z = m0_z;
103         move_out_of_solid_expand(e, '0 0 1' * m1_z); e.maxs_z = m1_z;
104         setorigin(e, e.origin);
105
106         tracebox(e.origin, e.mins, e.maxs, e.origin, MOVE_WORLDONLY, e);
107         if(trace_startsolid)
108         {
109                 setorigin(e, o);
110                 return 0;
111         }
112
113         return 1;
114 }
115
116 string STR_PLAYER = "player";
117 string STR_SPECTATOR = "spectator";
118 string STR_OBSERVER = "observer";
119
120 #if 0
121 #define FOR_EACH_CLIENT(v) for(v = world; (v = findflags(v, flags, FL_CLIENT)) != world; )
122 #define FOR_EACH_REALCLIENT(v) FOR_EACH_CLIENT(v) if(clienttype(v) == CLIENTTYPE_REAL)
123 #define FOR_EACH_PLAYER(v) for(v = world; (v = find(v, classname, STR_PLAYER)) != world; )
124 #define FOR_EACH_REALPLAYER(v) FOR_EACH_PLAYER(v) if(clienttype(v) == CLIENTTYPE_REAL)
125 #else
126 #define FOR_EACH_CLIENTSLOT(v) for(v = world; (v = nextent(v)) && (num_for_edict(v) <= maxclients); )
127 #define FOR_EACH_CLIENT(v) FOR_EACH_CLIENTSLOT(v) if(v.flags & FL_CLIENT)
128 #define FOR_EACH_REALCLIENT(v) FOR_EACH_CLIENT(v) if(clienttype(v) == CLIENTTYPE_REAL)
129 #define FOR_EACH_PLAYER(v) FOR_EACH_CLIENT(v) if(v.classname == STR_PLAYER)
130 #define FOR_EACH_REALPLAYER(v) FOR_EACH_REALCLIENT(v) if(v.classname == STR_PLAYER)
131 #endif
132
133 // copies a string to a tempstring (so one can strunzone it)
134 string strcat1(string s) = #115; // FRIK_FILE
135
136 float logfile_open;
137 float logfile;
138
139 void bcenterprint(string s)
140 {
141         // TODO replace by MSG_ALL (would show it to spectators too, though)?
142         entity head;
143         FOR_EACH_PLAYER(head)
144                 if(clienttype(head) == CLIENTTYPE_REAL)
145                         centerprint(head, s);
146 }
147
148 void GameLogEcho(string s)
149 {
150         string fn;
151         float matches;
152
153         if(cvar("sv_eventlog_files"))
154         {
155                 if(!logfile_open)
156                 {
157                         logfile_open = TRUE;
158                         matches = cvar("sv_eventlog_files_counter") + 1;
159                         cvar_set("sv_eventlog_files_counter", ftos(matches));
160                         fn = ftos(matches);
161                         if(strlen(fn) < 8)
162                                 fn = strcat(substring("00000000", 0, 8 - strlen(fn)), fn);
163                         fn = strcat(cvar_string("sv_eventlog_files_nameprefix"), fn, cvar_string("sv_eventlog_files_namesuffix"));
164                         logfile = fopen(fn, FILE_APPEND);
165                         fputs(logfile, ":logversion:3\n");
166                 }
167                 if(logfile >= 0)
168                 {
169                         if(cvar("sv_eventlog_files_timestamps"))
170                                 fputs(logfile, strcat(":time:", strftime(TRUE, "%Y-%m-%d %H:%M:%S", "\n", s, "\n")));
171                         else
172                                 fputs(logfile, strcat(s, "\n"));
173                 }
174         }
175         if(cvar("sv_eventlog_console"))
176         {
177                 print(s, "\n");
178         }
179 }
180
181 void GameLogInit()
182 {
183         logfile_open = 0;
184         // will be opened later
185 }
186
187 void GameLogClose()
188 {
189         if(logfile_open && logfile >= 0)
190         {
191                 fclose(logfile);
192                 logfile = -1;
193         }
194 }
195
196 float spawnpoint_nag;
197 void relocate_spawnpoint()
198 {
199         // nudge off the floor
200         setorigin(self, self.origin + '0 0 1');
201
202         tracebox(self.origin, PL_MIN, PL_MAX, self.origin, TRUE, self);
203         if (trace_startsolid)
204         {
205                 vector o;
206                 o = self.origin;
207                 self.mins = PL_MIN;
208                 self.maxs = PL_MAX;
209                 if(!move_out_of_solid(self))
210                         objerror("could not get out of solid at all!");
211                 print("^1NOTE: this map needs FIXING. Spawnpoint at ", vtos(o - '0 0 1'));
212                 print(" needs to be moved out of solid, e.g. by '", ftos(self.origin_x - o_x));
213                 print(" ", ftos(self.origin_y - o_y));
214                 print(" ", ftos(self.origin_z - o_z), "'\n");
215                 if(cvar("g_spawnpoints_auto_move_out_of_solid"))
216                 {
217                         if(!spawnpoint_nag)
218                                 print("\{1}^1NOTE: this map needs FIXING (it contains spawnpoints in solid, see server log)\n");
219                         spawnpoint_nag = 1;
220                 }
221                 else
222                 {
223                         self.origin = o;
224                         self.mins = self.maxs = '0 0 0';
225                         objerror("player spawn point in solid, mapper sucks!\n");
226                         return;
227                 }
228         }
229
230         if(cvar("g_spawnpoints_autodrop"))
231         {
232                 setsize(self, PL_MIN, PL_MAX);
233                 droptofloor();
234         }
235
236         self.use = spawnpoint_use;
237         self.team_saved = self.team;
238         if(!self.cnt)
239                 self.cnt = 1;
240
241         if(g_ctf || g_assault || g_onslaught || g_domination)
242         if(self.team)
243                 have_team_spawns = 1;
244
245         if(cvar("r_showbboxes"))
246         {
247                 // show where spawnpoints point at too
248                 makevectors(self.angles);
249                 entity e;
250                 e = spawn();
251                 e.classname = "info_player_foo";
252                 setorigin(e, self.origin + v_forward * 24);
253                 setsize(e, '-8 -8 -8', '8 8 8');
254                 e.solid = SOLID_TRIGGER;
255         }
256 }
257
258 #define strstr strstrofs
259 /*
260 // NOTE: DO NOT USE THIS FUNCTION TOO OFTEN.
261 // IT WILL MOST PROBABLY DESTROY _ALL_ OTHER TEMP
262 // STRINGS AND TAKE QUITE LONG. haystack and needle MUST
263 // BE CONSTANT OR strzoneD!
264 float strstr(string haystack, string needle, float offset)
265 {
266         float len, endpos;
267         string found;
268         len = strlen(needle);
269         endpos = strlen(haystack) - len;
270         while(offset <= endpos)
271         {
272                 found = substring(haystack, offset, len);
273                 if(found == needle)
274                         return offset;
275                 offset = offset + 1;
276         }
277         return -1;
278 }
279 */
280
281 float NUM_NEAREST_ENTITIES = 4;
282 entity nearest_entity[NUM_NEAREST_ENTITIES];
283 float nearest_length[NUM_NEAREST_ENTITIES];
284 entity findnearest(vector point, .string field, string value, vector axismod)
285 {
286         entity localhead;
287         float i;
288         float j;
289         float len;
290         vector dist;
291
292         float num_nearest;
293         num_nearest = 0;
294
295         localhead = find(world, field, value);
296         while(localhead)
297         {
298                 if((localhead.items == IT_KEY1 || localhead.items == IT_KEY2) && localhead.target == "###item###")
299                         dist = localhead.oldorigin;
300                 else
301                         dist = localhead.origin;
302                 dist = dist - point;
303                 dist = dist_x * axismod_x * '1 0 0' + dist_y * axismod_y * '0 1 0' + dist_z * axismod_z * '0 0 1';
304                 len = vlen(dist);
305
306                 for(i = 0; i < num_nearest; ++i)
307                 {
308                         if(len < nearest_length[i])
309                                 break;
310                 }
311
312                 // now i tells us where to insert at
313                 //   INSERTION SORT! YOU'VE SEEN IT! RUN!
314                 if(i < NUM_NEAREST_ENTITIES)
315                 {
316                         for(j = NUM_NEAREST_ENTITIES - 1; j >= i; --j)
317                         {
318                                 nearest_length[j + 1] = nearest_length[j];
319                                 nearest_entity[j + 1] = nearest_entity[j];
320                         }
321                         nearest_length[i] = len;
322                         nearest_entity[i] = localhead;
323                         if(num_nearest < NUM_NEAREST_ENTITIES)
324                                 num_nearest = num_nearest + 1;
325                 }
326
327                 localhead = find(localhead, field, value);
328         }
329
330         // now use the first one from our list that we can see
331         for(i = 0; i < num_nearest; ++i)
332         {
333                 traceline(point, nearest_entity[i].origin, TRUE, world);
334                 if(trace_fraction == 1)
335                 {
336                         if(i != 0)
337                         {
338                                 dprint("Nearest point (");
339                                 dprint(nearest_entity[0].netname);
340                                 dprint(") is not visible, using a visible one.\n");
341                         }
342                         return nearest_entity[i];
343                 }
344         }
345
346         if(num_nearest == 0)
347                 return world;
348
349         dprint("Not seeing any location point, using nearest as fallback.\n");
350         /* DEBUGGING CODE:
351         dprint("Candidates were: ");
352         for(j = 0; j < num_nearest; ++j)
353         {
354                 if(j != 0)
355                         dprint(", ");
356                 dprint(nearest_entity[j].netname);
357         }
358         dprint("\n");
359         */
360
361         return nearest_entity[0];
362 }
363
364 void spawnfunc_target_location()
365 {
366         self.classname = "target_location";
367         // location name in netname
368         // eventually support: count, teamgame selectors, line of sight?
369 };
370
371 void spawnfunc_info_location()
372 {
373         self.classname = "target_location";
374         self.message = self.netname;
375 };
376
377 string NearestLocation(vector p)
378 {
379         entity loc;
380         string ret;
381         ret = "somewhere";
382         loc = findnearest(p, classname, "target_location", '1 1 1');
383         if(loc)
384         {
385                 ret = loc.message;
386         }
387         else
388         {
389                 loc = findnearest(p, target, "###item###", '1 1 4');
390                 if(loc)
391                         ret = loc.netname;
392         }
393         return ret;
394 }
395
396 string formatmessage(string msg)
397 {
398         float p;
399         float n;
400         string msg_save;
401         string escape;
402         string replacement;
403         msg_save = strzone(msg);
404         p = 0;
405         n = 7;
406         while(1)
407         {
408                 if(n < 1)
409                         break; // too many replacements
410                 n = n - 1;
411                 p = strstr(msg_save, "%", p); // NOTE: this destroys msg as it's a tempstring!
412                 if(p < 0)
413                         break;
414                 replacement = substring(msg_save, p, 2);
415                 escape = substring(msg_save, p + 1, 1);
416                 if(escape == "%")
417                         replacement = "%";
418                 else if(escape == "a")
419                         replacement = ftos(floor(self.armorvalue));
420                 else if(escape == "h")
421                         replacement = ftos(floor(self.health));
422                 else if(escape == "l")
423                         replacement = NearestLocation(self.origin);
424                 else if(escape == "y")
425                         replacement = NearestLocation(self.cursor_trace_endpos);
426                 else if(escape == "d")
427                         replacement = NearestLocation(self.death_origin);
428                 else if(escape == "w")
429                 {
430                         float wep;
431                         wep = self.weapon;
432                         if(!wep)
433                                 wep = self.switchweapon;
434                         if(!wep)
435                                 wep = self.cnt;
436                         replacement = W_Name(wep);
437                 }
438                 else if(escape == "W")
439                 {
440                         if(self.items & IT_SHELLS) replacement = "shells";
441                         else if(self.items & IT_NAILS) replacement = "bullets";
442                         else if(self.items & IT_ROCKETS) replacement = "rockets";
443                         else if(self.items & IT_CELLS) replacement = "cells";
444                         else replacement = "batteries"; // ;)
445                 }
446                 else if(escape == "x")
447                 {
448                         replacement = self.cursor_trace_ent.netname;
449                         if(!replacement || !self.cursor_trace_ent)
450                                 replacement = "nothing";
451                 }
452                 else if(escape == "p")
453                 {
454                         if(self.last_selected_player)
455                                 replacement = self.last_selected_player.netname;
456                         else
457                                 replacement = "(nobody)";
458                 }
459                 msg = strcat(substring(msg_save, 0, p), replacement);
460                 msg = strcat(msg, substring(msg_save, p+2, strlen(msg_save) - (p+2)));
461                 strunzone(msg_save);
462                 msg_save = strzone(msg);
463                 p = p + 2;
464         }
465         msg = strcat(msg_save, "");
466         strunzone(msg_save);
467         return msg;
468 }
469
470 /*
471 =============
472 GetCvars
473 =============
474 Called with:
475   0:  sends the request
476   >0: receives a cvar from name=argv(f) value=argv(f+1)
477 */
478 void GetCvars_handleString(string thisname, float f, .string field, string name)
479 {
480         if(f < 0)
481         {
482                 if(self.field)
483                         strunzone(self.field);
484                 self.field = string_null;
485         }
486         else if(f > 0)
487         {
488                 if(thisname == name)
489                 {
490                         if(self.field)
491                                 strunzone(self.field);
492                         self.field = strzone(argv(f + 1));
493                 }
494         }
495         else
496                 stuffcmd(self, strcat("sendcvar ", name, "\n"));
497 }
498 void GetCvars_handleString_Fixup(string thisname, float f, .string field, string name, string(string) func)
499 {
500         GetCvars_handleString(thisname, f, field, name);
501         if(f >= 0) // also initialize to the fitting value for "" when sending cvars out
502         if(thisname == name)
503         {
504                 string s;
505                 s = func(strcat1(self.field));
506                 if(s != self.field)
507                 {
508                         strunzone(self.field);
509                         self.field = strzone(s);
510                 }
511         }
512 }
513 void GetCvars_handleFloat(string thisname, float f, .float field, string name)
514 {
515         if(f < 0)
516         {
517         }
518         else if(f > 0)
519         {
520                 if(thisname == name)
521                         self.field = stof(argv(f + 1));
522         }
523         else
524                 stuffcmd(self, strcat("sendcvar ", name, "\n"));
525 }
526 string W_FixWeaponOrder_ForceComplete(string s);
527 string W_FixWeaponOrder_AllowIncomplete(string s);
528 float w_getbestweapon(entity e);
529 void GetCvars(float f)
530 {
531         string s;
532         if(f > 0)
533                 s = strcat1(argv(f));
534         GetCvars_handleFloat(s, f, autoswitch, "cl_autoswitch");
535         GetCvars_handleFloat(s, f, cvar_cl_playerdetailreduction, "cl_playerdetailreduction");
536         GetCvars_handleFloat(s, f, cvar_scr_centertime, "scr_centertime");
537         GetCvars_handleFloat(s, f, cvar_cl_shownames, "cl_shownames");
538         GetCvars_handleString(s, f, cvar_g_nexuizversion, "g_nexuizversion");
539         GetCvars_handleFloat(s, f, cvar_cl_handicap, "cl_handicap");
540         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriority, "cl_weaponpriority", W_FixWeaponOrder_ForceComplete);
541         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[0], "cl_weaponpriority0", W_FixWeaponOrder_AllowIncomplete);
542         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[1], "cl_weaponpriority1", W_FixWeaponOrder_AllowIncomplete);
543         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[2], "cl_weaponpriority2", W_FixWeaponOrder_AllowIncomplete);
544         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[3], "cl_weaponpriority3", W_FixWeaponOrder_AllowIncomplete);
545         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[4], "cl_weaponpriority4", W_FixWeaponOrder_AllowIncomplete);
546         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[5], "cl_weaponpriority5", W_FixWeaponOrder_AllowIncomplete);
547         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[6], "cl_weaponpriority6", W_FixWeaponOrder_AllowIncomplete);
548         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[7], "cl_weaponpriority7", W_FixWeaponOrder_AllowIncomplete);
549         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[8], "cl_weaponpriority8", W_FixWeaponOrder_AllowIncomplete);
550         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[9], "cl_weaponpriority9", W_FixWeaponOrder_AllowIncomplete);
551         GetCvars_handleFloat(s, f, cvar_cl_autotaunt, "cl_autotaunt");
552         GetCvars_handleFloat(s, f, cvar_cl_voice_directional, "cl_voice_directional");
553         GetCvars_handleFloat(s, f, cvar_cl_voice_directional_taunt_attenuation, "cl_voice_directional_taunt_attenuation");
554         GetCvars_handleFloat(s, f, cvar_cl_hitsound, "cl_hitsound");
555
556         // fixup of switchweapon (needed for LMS or when spectating is disabled, as PutClientInServer comes too early)
557         if(f > 0)
558         {
559                 if(s == "cl_weaponpriority")
560                         self.switchweapon = w_getbestweapon(self);
561         }
562 }
563
564 float fexists(string f)
565 {
566         float fh;
567         fh = fopen(f, FILE_READ);
568         if(fh < 0)
569                 return FALSE;
570         fclose(fh);
571         return TRUE;
572 }
573
574 void backtrace(string msg)
575 {
576         float dev;
577         dev = cvar("developer");
578         cvar_set("developer", "1");
579         dprint("\n");
580         dprint("--- CUT HERE ---\nWARNING: ");
581         dprint(msg);
582         dprint("\n");
583         remove(world); // isn't there any better way to cause a backtrace?
584         dprint("\n--- CUT UNTIL HERE ---\n");
585         cvar_set("developer", ftos(dev));
586 }
587
588 string Team_ColorCode(float teamid)
589 {
590         if(teamid == COLOR_TEAM1)
591                 return "^1";
592         else if(teamid == COLOR_TEAM2)
593                 return "^4";
594         else if(teamid == COLOR_TEAM3)
595                 return "^3";
596         else if(teamid == COLOR_TEAM4)
597                 return "^6";
598         else
599                 return "^7";
600 }
601 string Team_ColorName(float t)
602 {
603         // fixme: Search for team entities and get their .netname's!
604         if(t == COLOR_TEAM1)
605                 return "Red";
606         if(t == COLOR_TEAM2)
607                 return "Blue";
608         if(t == COLOR_TEAM3)
609                 return "Yellow";
610         if(t == COLOR_TEAM4)
611                 return "Pink";
612         return "Neutral";
613 }
614 string Team_ColorNameLowerCase(float t)
615 {
616         // fixme: Search for team entities and get their .netname's!
617         if(t == COLOR_TEAM1)
618                 return "red";
619         if(t == COLOR_TEAM2)
620                 return "blue";
621         if(t == COLOR_TEAM3)
622                 return "yellow";
623         if(t == COLOR_TEAM4)
624                 return "pink";
625         return "neutral";
626 }
627
628 #define CENTERPRIO_POINT 1
629 #define CENTERPRIO_SPAM 2
630 #define CENTERPRIO_VOTE 4
631 #define CENTERPRIO_NORMAL 5
632 #define CENTERPRIO_SHIELDING 7
633 #define CENTERPRIO_MAPVOTE 9
634 #define CENTERPRIO_IDLEKICK 50
635 #define CENTERPRIO_ADMIN 99
636 .float centerprint_priority;
637 .float centerprint_expires;
638 void centerprint_atprio(entity e, float prio, string s)
639 {
640         if(intermission_running)
641                 if(prio < CENTERPRIO_MAPVOTE)
642                         return;
643         if(time > e.centerprint_expires)
644                 e.centerprint_priority = 0;
645         if(prio >= e.centerprint_priority)
646         {
647                 e.centerprint_priority = prio;
648                 if(timeoutStatus == 2)
649                         e.centerprint_expires = time + (e.cvar_scr_centertime * TIMEOUT_SLOWMO_VALUE);
650                 else
651                         e.centerprint_expires = time + e.cvar_scr_centertime;
652                 centerprint_builtin(e, s);
653         }
654 }
655 void centerprint_expire(entity e, float prio)
656 {
657         if(prio == e.centerprint_priority)
658         {
659                 e.centerprint_priority = 0;
660                 centerprint_builtin(e, "");
661         }
662 }
663 void centerprint(entity e, string s)
664 {
665         centerprint_atprio(e, CENTERPRIO_NORMAL, s);
666 }
667
668 // decolorizes and team colors the player name when needed
669 string playername(entity p)
670 {
671         string t;
672         if(teams_matter && !intermission_running && p.classname == "player")
673         {
674                 t = Team_ColorCode(p.team);
675                 return strcat(t, strdecolorize(p.netname));
676         }
677         else
678                 return p.netname;
679 }
680
681 vector randompos(vector m1, vector m2)
682 {
683         local vector v;
684         m2 = m2 - m1;
685         v_x = m2_x * random() + m1_x;
686         v_y = m2_y * random() + m1_y;
687         v_z = m2_z * random() + m1_z;
688         return  v;
689 };
690
691 float g_pickup_shells;
692 float g_pickup_shells_max;
693 float g_pickup_nails;
694 float g_pickup_nails_max;
695 float g_pickup_rockets;
696 float g_pickup_rockets_max;
697 float g_pickup_cells;
698 float g_pickup_cells_max;
699 float g_pickup_armorsmall;
700 float g_pickup_armorsmall_max;
701 float g_pickup_armormedium;
702 float g_pickup_armormedium_max;
703 float g_pickup_armorlarge;
704 float g_pickup_armorlarge_max;
705 float g_pickup_healthsmall;
706 float g_pickup_healthsmall_max;
707 float g_pickup_healthmedium;
708 float g_pickup_healthmedium_max;
709 float g_pickup_healthlarge;
710 float g_pickup_healthlarge_max;
711 float g_pickup_healthmega;
712 float g_pickup_healthmega_max;
713 float g_weaponarena;
714 string g_weaponarena_list;
715
716 float start_weapons;
717 float start_items;
718 float start_ammo_shells;
719 float start_ammo_nails;
720 float start_ammo_rockets;
721 float start_ammo_cells;
722 float start_health;
723 float start_armorvalue;
724 float warmup_start_weapons;
725 float warmup_start_ammo_shells;
726 float warmup_start_ammo_nails;
727 float warmup_start_ammo_rockets;
728 float warmup_start_ammo_cells;
729 float warmup_start_health;
730 float warmup_start_armorvalue;
731 float g_weapon_stay;
732
733 entity get_weaponinfo(float w);
734
735 void readplayerstartcvars()
736 {
737         entity e;
738         float i, j, t;
739         string s;
740
741         // initialize starting values for players
742         start_weapons = 0;
743         start_items = 0;
744         start_ammo_shells = 0;
745         start_ammo_nails = 0;
746         start_ammo_rockets = 0;
747         start_ammo_cells = 0;
748         start_health = cvar("g_balance_health_start");
749         start_armorvalue = cvar("g_balance_armor_start");
750
751         g_weaponarena = 0;
752         s = cvar_string("g_weaponarena");
753         if(s == "0")
754         {
755         }
756         else if(s == "all")
757         {
758                 g_weaponarena_list = "All Weapons";
759                 for(j = WEP_FIRST; j <= WEP_LAST; ++j)
760                 {
761                         e = get_weaponinfo(j);
762                         g_weaponarena |= e.weapons;
763                         weapon_action(e.weapon, WR_PRECACHE);
764                 }
765         }
766         else if(s == "most")
767         {
768                 g_weaponarena_list = "Most Weapons";
769                 for(j = WEP_FIRST; j <= WEP_LAST; ++j)
770                 {
771                         e = get_weaponinfo(j);
772                         if(e.spawnflags & WEPSPAWNFLAG_NORMAL)
773                         {
774                                 g_weaponarena |= e.weapons;
775                                 weapon_action(e.weapon, WR_PRECACHE);
776                         }
777                 }
778         }
779         else
780         {
781                 t = tokenize_sane(s);
782                 g_weaponarena_list = "";
783                 for(i = 0; i < t; ++i)
784                 {
785                         s = argv(i);
786                         for(j = WEP_FIRST; j <= WEP_LAST; ++j)
787                         {
788                                 e = get_weaponinfo(j);
789                                 if(e.netname == s)
790                                 {
791                                         g_weaponarena |= e.weapons;
792                                         weapon_action(e.weapon, WR_PRECACHE);
793                                         g_weaponarena_list = strcat(g_weaponarena_list, e.message, " & ");
794                                         break;
795                                 }
796                         }
797                         if(j > WEP_LAST)
798                         {
799                                 print("The weapon mutator list contains an unknown weapon ", s, ". Skipped.\n");
800                         }
801                 }
802                 g_weaponarena_list = strzone(substring(g_weaponarena_list, 0, strlen(g_weaponarena_list) - 3));
803         }
804
805         if(g_weaponarena)
806         {
807                 start_weapons = g_weaponarena;
808                 start_ammo_rockets = 999;
809                 start_ammo_shells = 999;
810                 start_ammo_cells = 999;
811                 start_ammo_nails = 999;
812                 start_items |= IT_UNLIMITED_AMMO;
813         }
814         else if(g_nixnex)
815         {
816                 start_weapons = 0;
817                 // will be done later
818                 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
819                 {
820                         e = get_weaponinfo(i);
821                         if(!(e.weapon))
822                                 continue;
823                         weapon_action(e.weapon, WR_PRECACHE);
824                 }
825         }
826         else if(g_minstagib)
827         {
828                 start_health = 100;
829                 start_armorvalue = 0;
830                 start_weapons = WEPBIT_MINSTANEX;
831                 weapon_action(WEP_MINSTANEX, WR_PRECACHE);
832                 start_ammo_cells = cvar("g_minstagib_ammo_start");
833                 g_minstagib_invis_alpha = cvar("g_minstagib_invis_alpha");
834
835                 if(g_minstagib_invis_alpha <= 0)
836                         g_minstagib_invis_alpha = -1;
837         }
838         else
839         {
840                 if(g_lms)
841                 {
842                         start_ammo_shells = cvar("g_lms_start_ammo_shells");
843                         start_ammo_nails = cvar("g_lms_start_ammo_nails");
844                         start_ammo_rockets = cvar("g_lms_start_ammo_rockets");
845                         start_ammo_cells = cvar("g_lms_start_ammo_cells");
846                         start_health = cvar("g_lms_start_health");
847                         start_armorvalue = cvar("g_lms_start_armor");
848                 } else if (cvar("g_use_ammunition")) {
849                         start_ammo_shells = cvar("g_start_ammo_shells");
850                         start_ammo_nails = cvar("g_start_ammo_nails");
851                         start_ammo_rockets = cvar("g_start_ammo_rockets");
852                         start_ammo_cells = cvar("g_start_ammo_cells");
853                 } else {
854                         start_ammo_shells = cvar("g_pickup_shells_max");
855                         start_ammo_nails = cvar("g_pickup_nails_max");
856                         start_ammo_rockets = cvar("g_pickup_rockets_max");
857                         start_ammo_cells = cvar("g_pickup_cells_max");
858                         start_items |= IT_UNLIMITED_AMMO;
859                 }
860
861                 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
862                 {
863                         e = get_weaponinfo(i);
864                         if(!(e.weapon))
865                                 continue;
866                         if(((e.spawnflags & WEPSPAWNFLAG_NORMAL) && g_lms) || cvar(strcat("g_start_weapon_", e.netname)))
867                         {
868                                 start_weapons |= e.weapons;
869                                 weapon_action(e.weapon, WR_PRECACHE);
870                         }
871                 }
872         }
873
874         if(inWarmupStage)
875         {
876                 warmup_start_ammo_shells = start_ammo_shells;
877                 warmup_start_ammo_nails = start_ammo_nails;
878                 warmup_start_ammo_rockets = start_ammo_rockets;
879                 warmup_start_ammo_cells = start_ammo_cells;
880                 warmup_start_health = start_health;
881                 warmup_start_armorvalue = start_armorvalue;
882                 warmup_start_weapons = start_weapons;
883
884                 if(!g_weaponarena && !g_nixnex && !g_minstagib)
885                 {
886                         if(cvar("g_use_ammunition"))
887                         {
888                                 warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
889                                 warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
890                                 warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
891                                 warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
892                         }
893                         warmup_start_health = cvar("g_warmup_start_health");
894                         warmup_start_armorvalue = cvar("g_warmup_start_armor");
895                         if(cvar("g_warmup_allguns"))
896                         {
897                                 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
898                                 {
899                                         e = get_weaponinfo(i);
900                                         if(!(e.weapon))
901                                                 continue;
902                                         if(e.spawnflags & WEPSPAWNFLAG_NORMAL)
903                                         {
904                                                 warmup_start_weapons |= e.weapons;
905                                                 weapon_action(e.weapon, WR_PRECACHE);
906                                         }
907                                 }
908                         }
909                 }
910         }
911
912         if(g_grappling_hook) // offhand hook
913         {
914                 start_weapons &~= WEPBIT_HOOK;
915                 warmup_start_weapons &~= WEPBIT_HOOK;
916         }
917
918         if(g_weapon_stay == 2)
919         {
920                 if(!start_ammo_shells) start_ammo_shells = g_pickup_shells;
921                 if(!start_ammo_nails) start_ammo_shells = g_pickup_nails;
922                 if(!start_ammo_cells) start_ammo_shells = g_pickup_cells;
923                 if(!start_ammo_rockets) start_ammo_shells = g_pickup_rockets;
924                 if(!warmup_start_ammo_shells) warmup_start_ammo_shells = g_pickup_shells;
925                 if(!warmup_start_ammo_nails) warmup_start_ammo_shells = g_pickup_nails;
926                 if(!warmup_start_ammo_cells) warmup_start_ammo_shells = g_pickup_cells;
927                 if(!warmup_start_ammo_rockets) warmup_start_ammo_shells = g_pickup_rockets;
928         }
929
930         start_ammo_shells = max(0, start_ammo_shells);
931         start_ammo_nails = max(0, start_ammo_nails);
932         start_ammo_cells = max(0, start_ammo_cells);
933         start_ammo_rockets = max(0, start_ammo_rockets);
934
935         warmup_start_ammo_shells = max(0, warmup_start_ammo_shells);
936         warmup_start_ammo_nails = max(0, warmup_start_ammo_nails);
937         warmup_start_ammo_cells = max(0, warmup_start_ammo_cells);
938         warmup_start_ammo_rockets = max(0, warmup_start_ammo_rockets);
939 }
940
941 float g_bugrigs;
942 float g_bugrigs_planar_movement;
943 float g_bugrigs_planar_movement_car_jumping;
944 float g_bugrigs_reverse_spinning;
945 float g_bugrigs_reverse_speeding;
946 float g_bugrigs_reverse_stopping;
947 float g_bugrigs_air_steering;
948 float g_bugrigs_angle_smoothing;
949 float g_bugrigs_friction_floor;
950 float g_bugrigs_friction_brake;
951 float g_bugrigs_friction_air;
952 float g_bugrigs_accel;
953 float g_bugrigs_speed_ref;
954 float g_bugrigs_speed_pow;
955 float g_bugrigs_steer;
956
957 float g_touchexplode;
958 float g_touchexplode_radius;
959 float g_touchexplode_damage;
960 float g_touchexplode_edgedamage;
961 float g_touchexplode_force;
962
963 void readlevelcvars(void)
964 {
965         g_bugrigs = cvar("g_bugrigs");
966         g_bugrigs_planar_movement = cvar("g_bugrigs_planar_movement");
967         g_bugrigs_planar_movement_car_jumping = cvar("g_bugrigs_planar_movement_car_jumping");
968         g_bugrigs_reverse_spinning = cvar("g_bugrigs_reverse_spinning");
969         g_bugrigs_reverse_speeding = cvar("g_bugrigs_reverse_speeding");
970         g_bugrigs_reverse_stopping = cvar("g_bugrigs_reverse_stopping");
971         g_bugrigs_air_steering = cvar("g_bugrigs_air_steering");
972         g_bugrigs_angle_smoothing = cvar("g_bugrigs_angle_smoothing");
973         g_bugrigs_friction_floor = cvar("g_bugrigs_friction_floor");
974         g_bugrigs_friction_brake = cvar("g_bugrigs_friction_brake");
975         g_bugrigs_friction_air = cvar("g_bugrigs_friction_air");
976         g_bugrigs_accel = cvar("g_bugrigs_accel");
977         g_bugrigs_speed_ref = cvar("g_bugrigs_speed_ref");
978         g_bugrigs_speed_pow = cvar("g_bugrigs_speed_pow");
979         g_bugrigs_steer = cvar("g_bugrigs_steer");
980
981         g_touchexplode = cvar("g_touchexplode");
982         g_touchexplode_radius = cvar("g_touchexplode_radius");
983         g_touchexplode_damage = cvar("g_touchexplode_damage");
984         g_touchexplode_edgedamage = cvar("g_touchexplode_edgedamage");
985         g_touchexplode_force = cvar("g_touchexplode_force");
986
987         sv_clones = cvar("sv_clones");
988         sv_cheats = cvar("sv_cheats");
989         sv_gentle = cvar("sv_gentle");
990         sv_foginterval = cvar("sv_foginterval");
991         g_cloaked = cvar("g_cloaked");
992         g_jump_grunt = cvar("g_jump_grunt");
993         g_footsteps = cvar("g_footsteps");
994         g_grappling_hook = cvar("g_grappling_hook");
995         g_laserguided_missile = cvar("g_laserguided_missile");
996         g_midair = cvar("g_midair");
997         g_minstagib = cvar("g_minstagib");
998         g_nixnex = cvar("g_nixnex");
999         g_nixnex_with_laser = cvar("g_nixnex_with_laser");
1000         g_norecoil = cvar("g_norecoil");
1001         g_vampire = cvar("g_vampire");
1002         g_bloodloss = cvar("g_bloodloss");
1003         sv_maxidle = cvar("sv_maxidle");
1004         sv_maxidle_spectatorsareidle = cvar("sv_maxidle_spectatorsareidle");
1005         sv_pogostick = cvar("sv_pogostick");
1006         sv_doublejump = cvar("sv_doublejump");
1007         g_maplist_allow_hidden = cvar("g_maplist_allow_hidden");
1008         g_ctf_reverse = cvar("g_ctf_reverse");
1009
1010         inWarmupStage = cvar("g_warmup");
1011         g_warmup_limit = cvar("g_warmup_limit");
1012         g_warmup_allguns = cvar("g_warmup_allguns");
1013         g_warmup_allow_timeout = cvar("g_warmup_allow_timeout");
1014
1015         if(g_race && g_race_qualifying == 2 || g_arena || g_assault || cvar("g_campaign"))
1016                 inWarmupStage = 0; // these modes cannot work together, sorry
1017
1018         g_pickup_respawntime_weapon = cvar("g_pickup_respawntime_weapon");
1019         g_pickup_respawntime_ammo = cvar("g_pickup_respawntime_ammo");
1020         g_pickup_respawntime_short = cvar("g_pickup_respawntime_short");
1021         g_pickup_respawntime_medium = cvar("g_pickup_respawntime_medium");
1022         g_pickup_respawntime_long = cvar("g_pickup_respawntime_long");
1023         g_pickup_respawntime_powerup = cvar("g_pickup_respawntime_powerup");
1024
1025         if(g_minstagib) g_nixnex = g_weaponarena = 0;
1026         if(g_nixnex) g_weaponarena = 0;
1027         g_weaponarena = 0;
1028
1029         g_pickup_shells                    = cvar("g_pickup_shells");
1030         g_pickup_shells_max                = cvar("g_pickup_shells_max");
1031         g_pickup_nails                     = cvar("g_pickup_nails");
1032         g_pickup_nails_max                 = cvar("g_pickup_nails_max");
1033         g_pickup_rockets                   = cvar("g_pickup_rockets");
1034         g_pickup_rockets_max               = cvar("g_pickup_rockets_max");
1035         g_pickup_cells                     = cvar("g_pickup_cells");
1036         g_pickup_cells_max                 = cvar("g_pickup_cells_max");
1037         g_pickup_armorsmall                = cvar("g_pickup_armorsmall");
1038         g_pickup_armorsmall_max            = cvar("g_pickup_armorsmall_max");
1039         g_pickup_armormedium               = cvar("g_pickup_armormedium");
1040         g_pickup_armormedium_max           = cvar("g_pickup_armormedium_max");
1041         g_pickup_armorlarge                = cvar("g_pickup_armorlarge");
1042         g_pickup_armorlarge_max            = cvar("g_pickup_armorlarge_max");
1043         g_pickup_healthsmall               = cvar("g_pickup_healthsmall");
1044         g_pickup_healthsmall_max           = cvar("g_pickup_healthsmall_max");
1045         g_pickup_healthmedium              = cvar("g_pickup_healthmedium");
1046         g_pickup_healthmedium_max          = cvar("g_pickup_healthmedium_max");
1047         g_pickup_healthlarge               = cvar("g_pickup_healthlarge");
1048         g_pickup_healthlarge_max           = cvar("g_pickup_healthlarge_max");
1049         g_pickup_healthmega                = cvar("g_pickup_healthmega");
1050         g_pickup_healthmega_max            = cvar("g_pickup_healthmega_max");
1051
1052         g_weapon_stay = cvar("g_weapon_stay");
1053         if(!g_weapon_stay && (cvar("deathmatch") == 2))
1054                 g_weapon_stay = 1;
1055
1056         if not(inWarmupStage)
1057         {
1058                 game_starttime                 = cvar("g_start_delay");
1059                 if(game_starttime)
1060                 {
1061                         restartAnnouncer = spawn();
1062                         restartAnnouncer.think = restartAnnouncer_Think;
1063                         restartAnnouncer.nextthink = time + 0.1;
1064                         restartAnnouncer.spawnflags = 0;
1065                 }
1066         }
1067
1068         readplayerstartcvars();
1069 }
1070
1071 /*
1072 // TODO sound pack system
1073 string soundpack;
1074
1075 string precache_sound_builtin (string s) = #19;
1076 void(entity e, float chan, string samp, float vol, float atten) sound_builtin = #8;
1077 string precache_sound(string s)
1078 {
1079         return precache_sound_builtin(strcat(soundpack, s));
1080 }
1081 void play2(entity e, string filename)
1082 {
1083         stuffcmd(e, strcat("play2 ", soundpack, filename, "\n"));
1084 }
1085 void sound(entity e, float chan, string samp, float vol, float atten)
1086 {
1087         sound_builtin(e, chan, strcat(soundpack, samp), vol, atten);
1088 }
1089 */
1090
1091 // Sound functions
1092 string precache_sound (string s) = #19;
1093 void(entity e, float chan, string samp, float vol, float atten) sound = #8;
1094 float precache_sound_index (string s) = #19;
1095
1096 #define SND_VOLUME      1
1097 #define SND_ATTENUATION 2
1098 #define SND_LARGEENTITY 8
1099 #define SND_LARGESOUND  16
1100
1101 void soundtoat(float dest, entity e, vector o, float chan, string samp, float vol, float atten)
1102 {
1103         float entno, idx;
1104         entno = num_for_edict(e);
1105         idx = precache_sound_index(samp);
1106
1107         float sflags;
1108         sflags = 0;
1109
1110         atten = floor(atten * 64);
1111         vol = floor(vol * 255);
1112
1113         if(vol != 255)
1114                 sflags |= SND_VOLUME;
1115         if(atten != 64)
1116                 sflags |= SND_ATTENUATION;
1117         if(entno >= 8192)
1118                 sflags |= SND_LARGEENTITY;
1119         if(idx >= 256)
1120                 sflags |= SND_LARGESOUND;
1121
1122         WriteByte(dest, SVC_SOUND);
1123         WriteByte(dest, sflags);
1124         if(sflags & SND_VOLUME)
1125                 WriteByte(dest, vol * 255);
1126         if(sflags & SND_ATTENUATION)
1127                 WriteByte(dest, atten);
1128         if(sflags & SND_LARGEENTITY)
1129         {
1130                 WriteShort(dest, entno);
1131                 WriteByte(dest, chan);
1132         }
1133         else
1134         {
1135                 WriteShort(dest, entno * 8 + chan);
1136         }
1137         if(sflags & SND_LARGESOUND)
1138                 WriteShort(dest, idx);
1139         else
1140                 WriteByte(dest, idx);
1141
1142         WriteCoord(dest, o_x);
1143         WriteCoord(dest, o_y);
1144         WriteCoord(dest, o_z);
1145 }
1146 void soundto(float dest, entity e, float chan, string samp, float vol, float atten)
1147 {
1148         vector o;
1149         o = e.origin + 0.5 * (e.mins + e.maxs);
1150         soundtoat(dest, e, o, chan, samp, vol, atten);
1151 }
1152 void soundat(entity e, vector o, float chan, string samp, float vol, float atten)
1153 {
1154         soundtoat(MSG_BROADCAST, e, o, chan, samp, vol, atten);
1155 }
1156 void stopsoundto(float dest, entity e, float chan)
1157 {
1158         float entno;
1159         entno = num_for_edict(e);
1160
1161         if(entno >= 8192)
1162         {
1163                 float idx, sflags;
1164                 idx = precache_sound_index("misc/null.wav");
1165                 sflags = SND_LARGEENTITY;
1166                 if(idx >= 256)
1167                         sflags |= SND_LARGESOUND;
1168                 WriteByte(dest, SVC_SOUND);
1169                 WriteByte(dest, sflags);
1170                 WriteShort(dest, entno);
1171                 WriteByte(dest, chan);
1172                 if(sflags & SND_LARGESOUND)
1173                         WriteShort(dest, idx);
1174                 else
1175                         WriteByte(dest, idx);
1176                 WriteCoord(dest, e.origin_x);
1177                 WriteCoord(dest, e.origin_y);
1178                 WriteCoord(dest, e.origin_z);
1179         }
1180         else
1181         {
1182                 WriteByte(dest, SVC_STOPSOUND);
1183                 WriteShort(dest, entno * 8 + chan);
1184         }
1185 }
1186 void stopsound(entity e, float chan)
1187 {
1188         stopsoundto(MSG_BROADCAST, e, chan); // unreliable, gets there fast
1189         stopsoundto(MSG_ALL, e, chan); // in case of packet loss
1190 }
1191
1192 void play2(entity e, string filename)
1193 {
1194         //stuffcmd(e, strcat("play2 ", filename, "\n"));
1195         msg_entity = e;
1196         soundtoat(MSG_ONE, world, '0 0 0', CHAN_AUTO, filename, VOL_BASE, ATTN_NONE);
1197 }
1198
1199 .float announcetime;
1200 float announce(entity player, string msg)
1201 {
1202         if(time > player.announcetime)
1203         if(clienttype(player) == CLIENTTYPE_REAL)
1204         {
1205                 player.announcetime = time + 0.8;
1206                 play2(player, msg);
1207                 return TRUE;
1208         }
1209         return FALSE;
1210 }
1211
1212 void play2team(float t, string filename)
1213 {
1214         local entity head;
1215         FOR_EACH_REALPLAYER(head)
1216         {
1217                 if (head.team == t)
1218                         play2(head, filename);
1219         }
1220 }
1221
1222 void play2all(string samp)
1223 {
1224         sound(world, CHAN_AUTO, samp, VOL_BASE, ATTN_NONE);
1225 }
1226
1227 void PrecachePlayerSounds(string f);
1228 void precache_all_models(string pattern)
1229 {
1230         float globhandle, i, n;
1231         string f;
1232
1233         globhandle = search_begin(pattern, TRUE, FALSE);
1234         if(globhandle < 0)
1235                 return;
1236         n = search_getsize(globhandle);
1237         for(i = 0; i < n; ++i)
1238         {
1239                 //print(search_getfilename(globhandle, i), "\n");
1240                 f = search_getfilename(globhandle, i);
1241                 precache_model(f);
1242                 PrecachePlayerSounds(strcat(f, ".sounds"));
1243         }
1244         search_end(globhandle);
1245 }
1246
1247 void precache()
1248 {
1249         // gamemode related things
1250         precache_model ("null");
1251         precache_model ("models/misc/chatbubble.spr");
1252         precache_model ("models/misc/teambubble.spr");
1253         if (g_runematch)
1254         {
1255                 precache_model ("models/runematch/curse.mdl");
1256                 precache_model ("models/runematch/rune.mdl");
1257         }
1258
1259 #ifdef TTURRETS_ENABLED
1260     if(cvar("g_turrets"))
1261         turrets_precash();
1262 #endif
1263
1264         // Precache all player models if desired
1265         if (cvar("sv_precacheplayermodels"))
1266         {
1267                 PrecachePlayerSounds("sound/player/default.sounds");
1268                 precache_all_models("models/player/*.zym");
1269                 precache_all_models("models/player/*.dpm");
1270                 precache_all_models("models/player/*.md3");
1271                 precache_all_models("models/player/*.psk");
1272                 //precache_model("models/player/carni.zym");
1273                 //precache_model("models/player/crash.zym");
1274                 //precache_model("models/player/grunt.zym");
1275                 //precache_model("models/player/headhunter.zym");
1276                 //precache_model("models/player/insurrectionist.zym");
1277                 //precache_model("models/player/jeandarc.zym");
1278                 //precache_model("models/player/lurk.zym");
1279                 //precache_model("models/player/lycanthrope.zym");
1280                 //precache_model("models/player/marine.zym");
1281                 //precache_model("models/player/nexus.zym");
1282                 //precache_model("models/player/pyria.zym");
1283                 //precache_model("models/player/shock.zym");
1284                 //precache_model("models/player/skadi.zym");
1285                 //precache_model("models/player/specop.zym");
1286                 //precache_model("models/player/visitant.zym");
1287         }
1288
1289         if(cvar("sv_defaultcharacter"))
1290         {
1291                 string s;
1292                 s = cvar_string("sv_defaultplayermodel_red");
1293                 if(s != "")
1294                 {
1295                         precache_model(s);
1296                         PrecachePlayerSounds(strcat(s, ".sounds"));
1297                 }
1298                 s = cvar_string("sv_defaultplayermodel_blue");
1299                 if(s != "")
1300                 {
1301                         precache_model(s);
1302                         PrecachePlayerSounds(strcat(s, ".sounds"));
1303                 }
1304                 s = cvar_string("sv_defaultplayermodel_yellow");
1305                 if(s != "")
1306                 {
1307                         precache_model(s);
1308                         PrecachePlayerSounds(strcat(s, ".sounds"));
1309                 }
1310                 s = cvar_string("sv_defaultplayermodel_pink");
1311                 if(s != "")
1312                 {
1313                         precache_model(s);
1314                         PrecachePlayerSounds(strcat(s, ".sounds"));
1315                 }
1316                 s = cvar_string("sv_defaultplayermodel");
1317                 if(s != "")
1318                 {
1319                         precache_model(s);
1320                         PrecachePlayerSounds(strcat(s, ".sounds"));
1321                 }
1322         }
1323
1324         if (g_footsteps)
1325         {
1326                 PrecacheGlobalSound((globalsound_step = "misc/footstep0 6"));
1327                 PrecacheGlobalSound((globalsound_metalstep = "misc/metalfootstep0 6"));
1328         }
1329
1330         // gore and miscellaneous sounds
1331         //precache_sound ("misc/h2ohit.wav");
1332         precache_model ("models/hook.md3");
1333         precache_sound ("misc/armorimpact.wav");
1334         precache_sound ("misc/bodyimpact1.wav");
1335         precache_sound ("misc/bodyimpact2.wav");
1336         precache_sound ("misc/gib.wav");
1337         precache_sound ("misc/gib_splat01.wav");
1338         precache_sound ("misc/gib_splat02.wav");
1339         precache_sound ("misc/gib_splat03.wav");
1340         precache_sound ("misc/gib_splat04.wav");
1341         precache_sound ("misc/hit.wav");
1342         PrecacheGlobalSound((globalsound_fall = "misc/hitground 4"));
1343         PrecacheGlobalSound((globalsound_metalfall = "misc/metalhitground 4"));
1344         precache_sound ("misc/null.wav");
1345         precache_sound ("misc/spawn.wav");
1346         precache_sound ("misc/talk.wav");
1347         precache_sound ("misc/teleport.wav");
1348         precache_sound ("player/lava.wav");
1349         precache_sound ("player/slime.wav");
1350
1351         // announcer sounds - male
1352         precache_sound ("announcer/male/electrobitch.wav");
1353         precache_sound ("announcer/male/airshot.wav");
1354         precache_sound ("announcer/male/03kills.wav");
1355         precache_sound ("announcer/male/05kills.wav");
1356         precache_sound ("announcer/male/10kills.wav");
1357         precache_sound ("announcer/male/15kills.wav");
1358         precache_sound ("announcer/male/20kills.wav");
1359         precache_sound ("announcer/male/25kills.wav");
1360         precache_sound ("announcer/male/30kills.wav");
1361         precache_sound ("announcer/male/botlike.wav");
1362         precache_sound ("announcer/male/yoda.wav");
1363         precache_sound ("announcer/male/headshot.wav");
1364         precache_sound ("announcer/male/impressive.wav");
1365
1366         // announcer sounds - robotic
1367         precache_sound ("announcer/robotic/prepareforbattle.wav");
1368         precache_sound ("announcer/robotic/begin.wav");
1369         precache_sound ("announcer/robotic/timeoutcalled.wav");
1370         precache_sound ("announcer/robotic/1fragleft.wav");
1371         precache_sound ("announcer/robotic/1minuteremains.wav");
1372         precache_sound ("announcer/robotic/2fragsleft.wav");
1373         precache_sound ("announcer/robotic/3fragsleft.wav");
1374         if (g_minstagib)
1375         {
1376                 precache_sound ("announcer/robotic/lastsecond.wav");
1377                 precache_sound ("announcer/robotic/narrowly.wav");
1378         }
1379
1380         precache_model ("models/sprites/1.spr32");
1381         precache_model ("models/sprites/2.spr32");
1382         precache_model ("models/sprites/3.spr32");
1383         precache_model ("models/sprites/4.spr32");
1384         precache_model ("models/sprites/5.spr32");
1385         precache_model ("models/sprites/6.spr32");
1386         precache_model ("models/sprites/7.spr32");
1387         precache_model ("models/sprites/8.spr32");
1388         precache_model ("models/sprites/9.spr32");
1389         precache_model ("models/sprites/10.spr32");
1390         precache_sound ("announcer/robotic/1.wav");
1391         precache_sound ("announcer/robotic/2.wav");
1392         precache_sound ("announcer/robotic/3.wav");
1393         precache_sound ("announcer/robotic/4.wav");
1394         precache_sound ("announcer/robotic/5.wav");
1395         precache_sound ("announcer/robotic/6.wav");
1396         precache_sound ("announcer/robotic/7.wav");
1397         precache_sound ("announcer/robotic/8.wav");
1398         precache_sound ("announcer/robotic/9.wav");
1399         precache_sound ("announcer/robotic/10.wav");
1400
1401         // common weapon precaches
1402         precache_sound ("weapons/weapon_switch.wav");
1403         precache_sound ("weapons/weaponpickup.wav");
1404         if (cvar("g_grappling_hook"))
1405         {
1406                 precache_sound ("weapons/hook_fire.wav"); // hook
1407                 precache_sound ("weapons/hook_impact.wav"); // hook
1408         }
1409
1410         if (cvar("sv_precacheweapons") || g_nixnex)
1411         {
1412                 //precache weapon models/sounds
1413                 local float wep;
1414                 wep = WEP_FIRST;
1415                 while (wep <= WEP_LAST)
1416                 {
1417                         weapon_action(wep, WR_PRECACHE);
1418                         wep = wep + 1;
1419                 }
1420         }
1421
1422         precache_model("models/elaser.mdl");
1423         precache_model("models/laser.mdl");
1424         precache_model("models/ebomb.mdl");
1425
1426 #if 0
1427         // Disabled this code because it simply does not work (e.g. ignores bgmvolume, overlaps with "cd loop" controlled tracks).
1428
1429         if (!self.noise && self.music) // quake 3 uses the music field
1430                 self.noise = self.music;
1431
1432         // plays music for the level if there is any
1433         if (self.noise)
1434         {
1435                 precache_sound (self.noise);
1436                 ambientsound ('0 0 0', self.noise, VOL_BASE, ATTN_NONE);
1437         }
1438 #endif
1439 }
1440
1441 // sorry, but using \ in macros breaks line numbers
1442 #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
1443 #define WRITESPECTATABLE_MSG_ONE(statement) WRITESPECTATABLE_MSG_ONE_VARNAME(oldmsg_entity, statement)
1444 #define WRITESPECTATABLE(msg,statement) if(msg == MSG_ONE) { WRITESPECTATABLE_MSG_ONE(statement); } else statement float WRITESPECTATABLE_workaround = 0
1445
1446 vector ExactTriggerHit_mins;
1447 vector ExactTriggerHit_maxs;
1448 float ExactTriggerHit_Recurse()
1449 {
1450         float s;
1451         entity se;
1452         float f;
1453
1454         tracebox('0 0 0', ExactTriggerHit_mins, ExactTriggerHit_maxs, '0 0 0', MOVE_NORMAL, other);
1455         if not(trace_ent)
1456                 return 0;
1457         if(trace_ent == self)
1458                 return 1;
1459
1460         se = trace_ent;
1461         s = se.solid;
1462         se.solid = SOLID_NOT;
1463         f = ExactTriggerHit_Recurse();
1464         se.solid = s;
1465
1466         return f;
1467 }
1468
1469 float ExactTriggerHit()
1470 {
1471         float f, s;
1472
1473         if not(self.modelindex)
1474                 return 1;
1475
1476         s = self.solid;
1477         self.solid = SOLID_BSP;
1478         ExactTriggerHit_mins = other.absmin;
1479         ExactTriggerHit_maxs = other.absmax;
1480         f = ExactTriggerHit_Recurse();
1481         self.solid = s;
1482
1483         return f;
1484 }
1485
1486 // WARNING: this kills the trace globals
1487 #define EXACTTRIGGER_TOUCH if not(ExactTriggerHit()) return
1488 #define EXACTTRIGGER_INIT  InitSolidBSPTrigger(); self.solid = SOLID_TRIGGER
1489
1490 #define INITPRIO_FIRST              0
1491 #define INITPRIO_GAMETYPE           0
1492 #define INITPRIO_GAMETYPE_FALLBACK  1
1493 #define INITPRIO_CVARS              5
1494 #define INITPRIO_FINDTARGET        10
1495 #define INITPRIO_DROPTOFLOOR       20
1496 #define INITPRIO_SETLOCATION       90
1497 #define INITPRIO_LINKDOORS         91
1498 #define INITPRIO_LAST              99
1499
1500 .void(void) initialize_entity;
1501 .float initialize_entity_order;
1502 .entity initialize_entity_next;
1503 entity initialize_entity_first;
1504
1505 void make_safe_for_remove(entity e)
1506 {
1507         if(e.initialize_entity)
1508         {
1509                 entity ent, prev;
1510                 for(ent = initialize_entity_first; ent; )
1511                 {
1512                         if((ent == e) || ((ent.classname == "initialize_entity") && (ent.enemy == e)))
1513                         {
1514                                 print("make_safe_for_remove: getting rid of initializer ", etos(ent), "\n");
1515                                 // skip it in linked list
1516                                 if(prev)
1517                                 {
1518                                         prev.initialize_entity_next = ent.initialize_entity_next;
1519                                         ent = prev.initialize_entity_next;
1520                                 }
1521                                 else
1522                                 {
1523                                         initialize_entity_first = ent.initialize_entity_next;
1524                                         ent = initialize_entity_first;
1525                                 }
1526                         }
1527                         else
1528                         {
1529                                 prev = ent;
1530                                 ent = ent.initialize_entity_next;
1531                         }
1532                 }
1533         }
1534 }
1535
1536 void objerror(string s)
1537 {
1538         make_safe_for_remove(self);
1539         objerror_builtin(s);
1540 }
1541
1542 void remove_unsafely(entity e)
1543
1544         remove_builtin(e);
1545 }
1546
1547 void remove_safely(entity e)
1548 {
1549         make_safe_for_remove(e);
1550         remove_builtin(e);
1551 }
1552
1553 void InitializeEntity(entity e, void(void) func, float order)
1554 {
1555         entity prev, cur;
1556
1557         if(!e || e.initialize_entity)
1558         {
1559                 // make a proxy initializer entity
1560                 entity e_old;
1561                 e_old = e;
1562                 e = spawn();
1563                 e.classname = "initialize_entity";
1564                 e.enemy = e_old;
1565         }
1566
1567         e.initialize_entity = func;
1568         e.initialize_entity_order = order;
1569
1570         cur = initialize_entity_first;
1571         for(;;)
1572         {
1573                 if(!cur || cur.initialize_entity_order > order)
1574                 {
1575                         // insert between prev and cur
1576                         if(prev)
1577                                 prev.initialize_entity_next = e;
1578                         else
1579                                 initialize_entity_first = e;
1580                         e.initialize_entity_next = cur;
1581                         return;
1582                 }
1583                 prev = cur;
1584                 cur = cur.initialize_entity_next;
1585         }
1586 }
1587 void InitializeEntitiesRun()
1588 {
1589         entity startoflist;
1590         startoflist = initialize_entity_first;
1591         initialize_entity_first = world;
1592         for(self = startoflist; self; )
1593         {
1594                 entity e;
1595                 var void(void) func;
1596                 e = self.initialize_entity_next;
1597                 func = self.initialize_entity;
1598                 self.initialize_entity_order = 0;
1599                 self.initialize_entity = func_null;
1600                 self.initialize_entity_next = world;
1601                 if(self.classname == "initialize_entity")
1602                 {
1603                         entity e_old;
1604                         e_old = self.enemy;
1605                         remove_builtin(self);
1606                         self = e_old;
1607                 }
1608                 //dprint("Delayed initialization: ", self.classname, "\n");
1609                 func();
1610                 self = e;
1611         }
1612 }
1613
1614 .float uncustomizeentityforclient_set;
1615 .void(void) uncustomizeentityforclient;
1616 void(void) SUB_Nullpointer = #0;
1617 void UncustomizeEntitiesRun()
1618 {
1619         entity oldself;
1620         oldself = self;
1621         for(self = world; (self = findfloat(self, uncustomizeentityforclient_set, 1)); )
1622                 self.uncustomizeentityforclient();
1623         self = oldself;
1624 }
1625 void SetCustomizer(entity e, float(void) customizer, void(void) uncustomizer)
1626 {
1627         e.customizeentityforclient = customizer;
1628         e.uncustomizeentityforclient = uncustomizer;
1629         e.uncustomizeentityforclient_set = (uncustomizer != SUB_Nullpointer);
1630 }
1631
1632 .float nottargeted;
1633 #define IFTARGETED if(!self.nottargeted && self.targetname != "")
1634
1635 void() SUB_Remove;
1636 void Net_LinkEntity(entity e, float docull, float dt, float(entity, float) sendfunc)
1637 {
1638         vector mi, ma;
1639
1640         if(e.classname == "")
1641                 e.classname = "net_linked";
1642
1643         if(e.model == "" || self.modelindex == 0)
1644         {
1645                 mi = self.mins;
1646                 ma = self.maxs;
1647                 setmodel(e, "null");
1648                 setsize(e, mi, ma);
1649         }
1650
1651         e.SendEntity = sendfunc;
1652         e.SendFlags = 0xFFFFFF;
1653
1654         if(!docull)
1655                 e.effects |= EF_NODEPTHTEST;
1656
1657         if(dt)
1658         {
1659                 e.nextthink = time + dt;
1660                 e.think = SUB_Remove;
1661         }
1662 }
1663
1664 void adaptor_think2touch()
1665 {
1666         entity o;
1667         o = other;
1668         other = world;
1669         self.touch();
1670         other = o;
1671 }
1672
1673 void adaptor_think2use()
1674 {
1675         entity o, a;
1676         o = other;
1677         a = activator;
1678         activator = world;
1679         other = world;
1680         self.use();
1681         other = o;
1682         activator = a;
1683 }
1684
1685 // deferred dropping
1686 void DropToFloor_Handler()
1687 {
1688         droptofloor_builtin();
1689         self.dropped_origin = self.origin;
1690 }
1691
1692 void droptofloor()
1693 {
1694         InitializeEntity(self, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
1695 }
1696
1697
1698
1699 float trace_hits_box_a0, trace_hits_box_a1;
1700
1701 float trace_hits_box_1d(float end, float thmi, float thma)
1702 {
1703         if(end == 0)
1704         {
1705                 // just check if x is in range
1706                 if(0 < thmi)
1707                         return FALSE;
1708                 if(0 > thma)
1709                         return FALSE;
1710         }
1711         else
1712         {
1713                 // do the trace with respect to x
1714                 // 0 -> end has to stay in thmi -> thma
1715                 trace_hits_box_a0 = max(trace_hits_box_a0, min(thmi / end, thma / end));
1716                 trace_hits_box_a1 = min(trace_hits_box_a1, max(thmi / end, thma / end));
1717                 if(trace_hits_box_a0 > trace_hits_box_a1)
1718                         return FALSE;
1719         }
1720         return TRUE;
1721 }
1722
1723 float trace_hits_box(vector start, vector end, vector thmi, vector thma)
1724 {
1725         end -= start;
1726         thmi -= start;
1727         thma -= start;
1728         // now it is a trace from 0 to end
1729
1730         trace_hits_box_a0 = 0;
1731         trace_hits_box_a1 = 1;
1732
1733         if(!trace_hits_box_1d(end_x, thmi_x, thma_x))
1734                 return FALSE;
1735         if(!trace_hits_box_1d(end_y, thmi_y, thma_y))
1736                 return FALSE;
1737         if(!trace_hits_box_1d(end_z, thmi_z, thma_z))
1738                 return FALSE;
1739
1740         return TRUE;
1741 }
1742
1743 float tracebox_hits_box(vector start, vector mi, vector ma, vector end, vector thmi, vector thma)
1744 {
1745         return trace_hits_box(start, end, thmi - ma, thma - mi);
1746 }
1747
1748 float SUB_NoImpactCheck()
1749 {
1750         if(trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1751                 return 1;
1752         if(other == world && self.size != '0 0 0')
1753         {
1754                 vector tic;
1755                 tic = self.velocity * sys_ticrate;
1756                 tic = tic + normalize(tic) * vlen(self.maxs - self.mins);
1757                 traceline(self.origin - tic, self.origin + tic, MOVE_NORMAL, self);
1758                 if(trace_fraction >= 1)
1759                 {
1760                         dprint("Odd... did not hit...?\n");
1761                 }
1762                 else if (trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT)
1763                 {
1764                         dprint("Detected and prevented the sky-grapple bug.\n");
1765                         return 1;
1766                 }
1767         }
1768
1769         return 0;
1770 }
1771
1772 #define SUB_OwnerCheck() (other && (other == self.owner))
1773
1774 #define PROJECTILE_TOUCH do { if(SUB_OwnerCheck()) return; if(SUB_NoImpactCheck()) { remove(self); return; } } while(0)
1775 #define PROJECTILE_TOUCH_NOSOUND do { if(SUB_OwnerCheck()) return; if(SUB_NoImpactCheck()) { stopsound(self, CHAN_PAIN); remove(self); return; } } while(0)
1776
1777 float MAX_IPBAN_URIS = 16;
1778
1779 float URI_GET_DISCARD   = 0;
1780 float URI_GET_IPBAN     = 1;
1781 float URI_GET_IPBAN_END = 16;
1782
1783 void URI_Get_Callback(float id, float status, string data)
1784 {
1785         dprint("Received HTTP request data for id ", ftos(id), "; status is ", ftos(status), "\nData is\n:");
1786         dprint(data);
1787         dprint("\nEnd of data.\n");
1788
1789         if(id == URI_GET_DISCARD)
1790         {
1791                 // discard
1792         }
1793         else if(id >= URI_GET_IPBAN && id <= URI_GET_IPBAN_END)
1794         {
1795                 // online ban list
1796                 OnlineBanList_URI_Get_Callback(id, status, data);
1797         }
1798         else
1799         {
1800                 print("Received HTTP request data for an invalid id ", ftos(id), ".\n");
1801         }
1802 }
1803
1804 void print_to(entity e, string s)
1805 {
1806         if(e)
1807                 sprint(e, strcat(s, "\n"));
1808         else
1809                 print(s, "\n");
1810 }
1811
1812 string getrecords()
1813 {
1814         float rec;
1815         string h;
1816         float r;
1817         float i;
1818         string s;
1819
1820         rec = 0;
1821         
1822         s = "";
1823
1824         if(g_ctf)
1825         {
1826                 for(i = 0; i < MapInfo_count; ++i)
1827                 {
1828                         if(MapInfo_Get_ByID(i))
1829                         {
1830                                 r = stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, "/captimerecord/time")));
1831                                 if(r == 0)
1832                                         continue;
1833                                 h = db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, "/captimerecord/netname"));
1834                                 s = strcat(s, strpad(32, MapInfo_Map_bspname), " ", strpad(-6, ftos_decimals(r, 2)), " ", h, "\n");
1835                                 ++rec;
1836                         }
1837                 }
1838         }
1839
1840         if(g_race)
1841         {
1842                 for(i = 0; i < MapInfo_count; ++i)
1843                 {
1844                         if(MapInfo_Get_ByID(i))
1845                         {
1846                                 r = stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, "/racerecord/time")));
1847                                 if(r == 0)
1848                                         continue;
1849                                 h = db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, "/racerecord/netname"));
1850                                 s = strcat(s, strpad(32, MapInfo_Map_bspname), " ", strpad(-8, mmsss(r)), " ", h, "\n");
1851                                 ++rec;
1852                         }
1853                 }
1854         }
1855
1856         if(s == "")
1857                 return "No records are available on this server.\n";
1858         else
1859                 return strcat("Records on this server:\n", s);
1860 }
1861
1862 float MoveToRandomMapLocation(entity e, float goodcontents, float badcontents, float badsurfaceflags, float attempts, float maxaboveground, float minviewdistance)
1863 {
1864         float m, i;
1865         vector start, org, delta, end, enddown, mstart;
1866
1867         m = e.dphitcontentsmask;
1868         e.dphitcontentsmask = goodcontents | badcontents;
1869
1870         org = world.mins;
1871         delta = world.maxs - world.mins;
1872
1873         for(i = 0; i < attempts; ++i)
1874         {
1875                 start_x = org_x + random() * delta_x;
1876                 start_y = org_y + random() * delta_y;
1877                 start_z = org_z + random() * delta_z;
1878
1879                 // rule 1: start inside world bounds, and outside
1880                 // solid, and don't start from somewhere where you can
1881                 // fall down to evil
1882                 tracebox(start, e.mins, e.maxs, start - '0 0 1' * delta_z, MOVE_NORMAL, e);
1883                 if(trace_fraction >= 1)
1884                         continue;
1885                 if(trace_startsolid)
1886                         continue;
1887                 if(trace_dphitcontents & badcontents)
1888                         continue;
1889                 if(trace_dphitq3surfaceflags & badsurfaceflags)
1890                         continue;
1891
1892                 // rule 2: if we are too high, lower the point
1893                 if(trace_fraction * delta_z > maxaboveground)
1894                         start = trace_endpos + '0 0 1' * maxaboveground;
1895                 enddown = trace_endpos;
1896
1897                 // rule 3: make sure we aren't outside the map. This only works
1898                 // for somewhat well formed maps. A good rule of thumb is that
1899                 // the map should have a convex outside hull.
1900                 // these can be traceLINES as we already verified the starting box
1901                 mstart = start + 0.5 * (e.mins + e.maxs);
1902                 traceline(mstart, mstart + '1 0 0' * delta_x, MOVE_NORMAL, e);
1903                 if(trace_fraction >= 1)
1904                         continue;
1905                 traceline(mstart, mstart - '1 0 0' * delta_x, MOVE_NORMAL, e);
1906                 if(trace_fraction >= 1)
1907                         continue;
1908                 traceline(mstart, mstart + '0 1 0' * delta_y, MOVE_NORMAL, e);
1909                 if(trace_fraction >= 1)
1910                         continue;
1911                 traceline(mstart, mstart - '0 1 0' * delta_y, MOVE_NORMAL, e);
1912                 if(trace_fraction >= 1)
1913                         continue;
1914                 traceline(mstart, mstart + '0 0 1' * delta_z, MOVE_NORMAL, e);
1915                 if(trace_fraction >= 1)
1916                         continue;
1917
1918                 // find a random vector to "look at"
1919                 end_x = org_x + random() * delta_x;
1920                 end_y = org_y + random() * delta_y;
1921                 end_z = org_z + random() * delta_z;
1922                 end = start + normalize(end - start) * vlen(delta);
1923
1924                 // rule 4: start TO end must not be too short
1925                 tracebox(start, e.mins, e.maxs, end, MOVE_NORMAL, e);
1926                 if(trace_startsolid)
1927                         continue;
1928                 if(trace_fraction < minviewdistance / vlen(delta))
1929                         continue;
1930
1931                 // rule 5: don't want to look at sky
1932                 if(trace_dphitq3surfaceflags & Q3SURFACEFLAG_SKY)
1933                         continue;
1934
1935                 // rule 6: we must not end up in trigger_hurt
1936                 if(tracebox_hits_trigger_hurt(start, e.mins, e.maxs, enddown))
1937                 {
1938                         dprint("trigger_hurt! ouch! and nothing else could find it!\n");
1939                         continue;
1940                 }
1941
1942                 break;
1943         }
1944
1945         e.dphitcontentsmask = m;
1946
1947         if(i < attempts)
1948         {
1949                 setorigin(e, start);
1950                 e.angles = vectoangles(end - start);
1951                 dprint("Needed ", ftos(i + 1), " attempts\n");
1952                 return TRUE;
1953         }
1954         else
1955                 return FALSE;
1956 }