]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/miscfunctions.qc
clean up the func_breakable mess a bit; TODO merge it with assault's
[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:2\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         }
485         else if(f > 0)
486         {
487                 if(thisname == name)
488                 {
489                         if(self.field)
490                                 strunzone(self.field);
491                         self.field = strzone(argv(f + 1));
492                 }
493         }
494         else
495                 stuffcmd(self, strcat("sendcvar ", name, "\n"));
496 }
497 void GetCvars_handleString_Fixup(string thisname, float f, .string field, string name, string(string) func)
498 {
499         GetCvars_handleString(thisname, f, field, name);
500         if(f >= 0) // also initialize to the fitting value for "" when sending cvars out
501         if(thisname == name)
502         {
503                 string s;
504                 s = func(strcat1(self.field));
505                 if(s != self.field)
506                 {
507                         strunzone(self.field);
508                         self.field = strzone(s);
509                 }
510         }
511 }
512 void GetCvars_handleFloat(string thisname, float f, .float field, string name)
513 {
514         if(f < 0)
515         {
516         }
517         else if(f > 0)
518         {
519                 if(thisname == name)
520                         self.field = stof(argv(f + 1));
521         }
522         else
523                 stuffcmd(self, strcat("sendcvar ", name, "\n"));
524 }
525 string W_FixWeaponOrder_ForceComplete(string s);
526 string W_FixWeaponOrder_AllowIncomplete(string s);
527 float w_getbestweapon(entity e);
528 void GetCvars(float f)
529 {
530         string s;
531         if(f > 0)
532                 s = strcat1(argv(f));
533         GetCvars_handleFloat(s, f, autoswitch, "cl_autoswitch");
534         GetCvars_handleFloat(s, f, cvar_cl_playerdetailreduction, "cl_playerdetailreduction");
535         GetCvars_handleFloat(s, f, cvar_cl_nogibs, "cl_nogibs");
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
552         // fixup of switchweapon (needed for LMS or when spectating is disabled, as PutClientInServer comes too early)
553         if(f > 0)
554         {
555                 if(s == "cl_weaponpriority")
556                         self.switchweapon = w_getbestweapon(self);
557         }
558 }
559
560 float fexists(string f)
561 {
562         float fh;
563         fh = fopen(f, FILE_READ);
564         if(fh < 0)
565                 return FALSE;
566         fclose(fh);
567         return TRUE;
568 }
569
570 void backtrace(string msg)
571 {
572         float dev;
573         dev = cvar("developer");
574         cvar_set("developer", "1");
575         dprint("\n");
576         dprint("--- CUT HERE ---\nWARNING: ");
577         dprint(msg);
578         dprint("\n");
579         remove(world); // isn't there any better way to cause a backtrace?
580         dprint("\n--- CUT UNTIL HERE ---\n");
581         cvar_set("developer", ftos(dev));
582 }
583
584 string Team_ColorCode(float teamid)
585 {
586         if(teamid == COLOR_TEAM1)
587                 return "^1";
588         else if(teamid == COLOR_TEAM2)
589                 return "^4";
590         else if(teamid == COLOR_TEAM3)
591                 return "^3";
592         else if(teamid == COLOR_TEAM4)
593                 return "^6";
594         else
595                 return "^7";
596 }
597 string Team_ColorName(float t)
598 {
599         // fixme: Search for team entities and get their .netname's!
600         if(t == COLOR_TEAM1)
601                 return "Red";
602         if(t == COLOR_TEAM2)
603                 return "Blue";
604         if(t == COLOR_TEAM3)
605                 return "Yellow";
606         if(t == COLOR_TEAM4)
607                 return "Pink";
608         return "Neutral";
609 }
610 string Team_ColorNameLowerCase(float t)
611 {
612         // fixme: Search for team entities and get their .netname's!
613         if(t == COLOR_TEAM1)
614                 return "red";
615         if(t == COLOR_TEAM2)
616                 return "blue";
617         if(t == COLOR_TEAM3)
618                 return "yellow";
619         if(t == COLOR_TEAM4)
620                 return "pink";
621         return "neutral";
622 }
623
624 #define CENTERPRIO_POINT 1
625 #define CENTERPRIO_SPAM 2
626 #define CENTERPRIO_REBALANCE 2
627 #define CENTERPRIO_VOTE 4
628 #define CENTERPRIO_NORMAL 5
629 #define CENTERPRIO_MAPVOTE 9
630 #define CENTERPRIO_IDLEKICK 50
631 #define CENTERPRIO_ADMIN 99
632 .float centerprint_priority;
633 .float centerprint_expires;
634 void centerprint_atprio(entity e, float prio, string s)
635 {
636         if(intermission_running)
637                 if(prio < CENTERPRIO_MAPVOTE)
638                         return;
639         if(time > e.centerprint_expires)
640                 e.centerprint_priority = 0;
641         if(prio >= e.centerprint_priority)
642         {
643                 e.centerprint_priority = prio;
644                 if(timeoutStatus == 2)
645                         e.centerprint_expires = time + (e.cvar_scr_centertime * TIMEOUT_SLOWMO_VALUE);
646                 else
647                         e.centerprint_expires = time + e.cvar_scr_centertime;
648                 centerprint_builtin(e, s);
649         }
650 }
651 void centerprint_expire(entity e, float prio)
652 {
653         if(prio == e.centerprint_priority)
654         {
655                 e.centerprint_priority = 0;
656                 centerprint_builtin(e, "");
657         }
658 }
659 void centerprint(entity e, string s)
660 {
661         centerprint_atprio(e, CENTERPRIO_NORMAL, s);
662 }
663
664 // decolorizes and team colors the player name when needed
665 string playername(entity p)
666 {
667         string t;
668         if(teams_matter && !intermission_running && p.classname == "player")
669         {
670                 t = Team_ColorCode(p.team);
671                 return strcat(t, strdecolorize(p.netname));
672         }
673         else
674                 return p.netname;
675 }
676
677 vector randompos(vector m1, vector m2)
678 {
679         local vector v;
680         m2 = m2 - m1;
681         v_x = m2_x * random() + m1_x;
682         v_y = m2_y * random() + m1_y;
683         v_z = m2_z * random() + m1_z;
684         return  v;
685 };
686
687 // requires that m2>m1 in all coordinates, and that m4>m3
688 float boxesoverlap(vector m1, vector m2, vector m3, vector m4) {return m2_x >= m3_x && m1_x <= m4_x && m2_y >= m3_y && m1_y <= m4_y && m2_z >= m3_z && m1_z <= m4_z;};
689
690 // requires the same, but is a stronger condition
691 float boxinsidebox(vector smins, vector smaxs, vector bmins, vector bmaxs) {return smins_x >= bmins_x && smaxs_x <= bmaxs_x && smins_y >= bmins_y && smaxs_y <= bmaxs_y && smins_z >= bmins_z && smaxs_z <= bmaxs_z;};
692
693 float g_pickup_shells;
694 float g_pickup_shells_max;
695 float g_pickup_nails;
696 float g_pickup_nails_max;
697 float g_pickup_rockets;
698 float g_pickup_rockets_max;
699 float g_pickup_cells;
700 float g_pickup_cells_max;
701 float g_pickup_armorsmall;
702 float g_pickup_armorsmall_max;
703 float g_pickup_armormedium;
704 float g_pickup_armormedium_max;
705 float g_pickup_armorlarge;
706 float g_pickup_armorlarge_max;
707 float g_pickup_healthsmall;
708 float g_pickup_healthsmall_max;
709 float g_pickup_healthmedium;
710 float g_pickup_healthmedium_max;
711 float g_pickup_healthlarge;
712 float g_pickup_healthlarge_max;
713 float g_pickup_healthmega;
714 float g_pickup_healthmega_max;
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
732 entity get_weaponinfo(float w);
733
734 void readplayerstartcvars()
735 {
736         entity e;
737         float i;
738
739         // initialize starting values for players
740         start_weapons = 0;
741         start_items = 0;
742         start_ammo_shells = 0;
743         start_ammo_nails = 0;
744         start_ammo_rockets = 0;
745         start_ammo_cells = 0;
746         start_health = cvar("g_balance_health_start");
747         start_armorvalue = cvar("g_balance_armor_start");
748
749         if(g_rocketarena)
750         {
751                 start_weapons = WEPBIT_ROCKET_LAUNCHER;
752                 weapon_action(WEP_ROCKET_LAUNCHER, WR_PRECACHE);
753                 start_ammo_rockets = 999;
754                 start_items |= IT_UNLIMITED_AMMO;
755         }
756         else if(g_nixnex)
757         {
758                 start_weapons = 0;
759                 // will be done later
760         }
761         else if(g_minstagib)
762         {
763                 start_health = 100;
764                 start_armorvalue = 0;
765                 start_weapons = WEPBIT_MINSTANEX;
766                 weapon_action(WEP_MINSTANEX, WR_PRECACHE);
767                 start_ammo_cells = cvar("g_minstagib_ammo_start");
768                 g_minstagib_invis_alpha = cvar("g_minstagib_invis_alpha");
769         }
770         else
771         {
772                 if(g_lms)
773                 {
774                         start_ammo_shells = cvar("g_lms_start_ammo_shells");
775                         start_ammo_nails = cvar("g_lms_start_ammo_nails");
776                         start_ammo_rockets = cvar("g_lms_start_ammo_rockets");
777                         start_ammo_cells = cvar("g_lms_start_ammo_cells");
778                         start_health = cvar("g_lms_start_health");
779                         start_armorvalue = cvar("g_lms_start_armor");
780                 } else if (cvar("g_use_ammunition")) {
781                         start_ammo_shells = cvar("g_start_ammo_shells");
782                         start_ammo_nails = cvar("g_start_ammo_nails");
783                         start_ammo_rockets = cvar("g_start_ammo_rockets");
784                         start_ammo_cells = cvar("g_start_ammo_cells");
785                 } else {
786                         start_ammo_shells = cvar("g_pickup_shells_max");
787                         start_ammo_nails = cvar("g_pickup_nails_max");
788                         start_ammo_rockets = cvar("g_pickup_rockets_max");
789                         start_ammo_cells = cvar("g_pickup_cells_max");
790                         start_items |= IT_UNLIMITED_AMMO;
791                 }
792
793                 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
794                 {
795                         e = get_weaponinfo(i);
796                         if(!(e.weapon))
797                                 continue;
798                         if(((e.spawnflags & 1) && g_lms) || cvar(strcat("g_start_weapon_", e.netname)))
799                         {
800                                 start_weapons |= e.weapons;
801                                 weapon_action(e.weapon, WR_PRECACHE);
802                         }
803                 }
804         }
805
806         if(inWarmupStage)
807         {
808                 warmup_start_ammo_shells = start_ammo_shells;
809                 warmup_start_ammo_nails = start_ammo_nails;
810                 warmup_start_ammo_rockets = start_ammo_rockets;
811                 warmup_start_ammo_cells = start_ammo_cells;
812                 warmup_start_health = start_health;
813                 warmup_start_armorvalue = start_armorvalue;
814                 warmup_start_weapons = start_weapons;
815
816                 if(!g_rocketarena && !g_nixnex && !g_minstagib)
817                 {
818                         if(cvar("g_use_ammunition"))
819                         {
820                                 warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
821                                 warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
822                                 warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
823                                 warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
824                         }
825                         warmup_start_health = cvar("g_warmup_start_health");
826                         warmup_start_armorvalue = cvar("g_warmup_start_armor");
827                         if(cvar("g_warmup_allguns"))
828                         {
829                                 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
830                                 {
831                                         e = get_weaponinfo(i);
832                                         if(!(e.weapon))
833                                                 continue;
834                                         if(e.spawnflags & 1)
835                                         {
836                                                 warmup_start_weapons |= e.weapons;
837                                                 weapon_action(e.weapon, WR_PRECACHE);
838                                         }
839                                 }
840                         }
841                 }
842         }
843 }
844
845 void readlevelcvars(void)
846 {
847         sv_cheats = cvar("sv_cheats");
848         sv_gentle = cvar("sv_gentle");
849         sv_foginterval = cvar("sv_foginterval");
850         g_cloaked = cvar("g_cloaked");
851         g_jump_grunt = cvar("g_jump_grunt");
852         g_footsteps = cvar("g_footsteps");
853         g_grappling_hook = cvar("g_grappling_hook");
854         g_laserguided_missile = cvar("g_laserguided_missile");
855         g_midair = cvar("g_midair");
856         g_minstagib = cvar("g_minstagib");
857         g_nixnex = cvar("g_nixnex");
858         g_nixnex_with_laser = cvar("g_nixnex_with_laser");
859         g_norecoil = cvar("g_norecoil");
860         g_rocketarena = cvar("g_rocketarena");
861         g_vampire = cvar("g_vampire");
862         sv_maxidle = cvar("sv_maxidle");
863         sv_maxidle_spectatorsareidle = cvar("sv_maxidle_spectatorsareidle");
864         sv_pogostick = cvar("sv_pogostick");
865         sv_doublejump = cvar("sv_doublejump");
866         g_maplist_allow_hidden = cvar("g_maplist_allow_hidden");
867         g_ctf_reverse = cvar("g_ctf_reverse");
868
869         inWarmupStage = cvar("g_warmup");
870         g_warmup_limit = cvar("g_warmup_limit");
871         g_warmup_allguns = cvar("g_warmup_allguns");
872         g_warmup_allow_timeout = cvar("g_warmup_allow_timeout");
873
874         if(g_race && g_race_qualifying == 2 || g_arena || g_assault || cvar("g_campaign"))
875                 inWarmupStage = 0; // these modes cannot work together, sorry
876
877         g_pickup_respawntime_short = cvar("g_pickup_respawntime_short");
878         g_pickup_respawntime_medium = cvar("g_pickup_respawntime_medium");
879         g_pickup_respawntime_long = cvar("g_pickup_respawntime_long");
880         g_pickup_respawntime_powerup = cvar("g_pickup_respawntime_powerup");
881
882         if(g_minstagib) g_nixnex = g_rocketarena = 0;
883         if(g_nixnex) g_rocketarena = 0;
884
885         g_pickup_shells                    = cvar("g_pickup_shells");
886         g_pickup_shells_max                = cvar("g_pickup_shells_max");
887         g_pickup_nails                     = cvar("g_pickup_nails");
888         g_pickup_nails_max                 = cvar("g_pickup_nails_max");
889         g_pickup_rockets                   = cvar("g_pickup_rockets");
890         g_pickup_rockets_max               = cvar("g_pickup_rockets_max");
891         g_pickup_cells                     = cvar("g_pickup_cells");
892         g_pickup_cells_max                 = cvar("g_pickup_cells_max");
893         g_pickup_armorsmall                = cvar("g_pickup_armorsmall");
894         g_pickup_armorsmall_max            = cvar("g_pickup_armorsmall_max");
895         g_pickup_armormedium               = cvar("g_pickup_armormedium");
896         g_pickup_armormedium_max           = cvar("g_pickup_armormedium_max");
897         g_pickup_armorlarge                = cvar("g_pickup_armorlarge");
898         g_pickup_armorlarge_max            = cvar("g_pickup_armorlarge_max");
899         g_pickup_healthsmall               = cvar("g_pickup_healthsmall");
900         g_pickup_healthsmall_max           = cvar("g_pickup_healthsmall_max");
901         g_pickup_healthmedium              = cvar("g_pickup_healthmedium");
902         g_pickup_healthmedium_max          = cvar("g_pickup_healthmedium_max");
903         g_pickup_healthlarge               = cvar("g_pickup_healthlarge");
904         g_pickup_healthlarge_max           = cvar("g_pickup_healthlarge_max");
905         g_pickup_healthmega                = cvar("g_pickup_healthmega");
906         g_pickup_healthmega_max            = cvar("g_pickup_healthmega_max");
907
908         readplayerstartcvars();
909 }
910
911 /*
912 // TODO sound pack system
913 string soundpack;
914
915 string precache_sound_builtin (string s) = #19;
916 void(entity e, float chan, string samp, float vol, float atten) sound_builtin = #8;
917 string precache_sound(string s)
918 {
919         return precache_sound_builtin(strcat(soundpack, s));
920 }
921 void play2(entity e, string filename)
922 {
923         stuffcmd(e, strcat("play2 ", soundpack, filename, "\n"));
924 }
925 void sound(entity e, float chan, string samp, float vol, float atten)
926 {
927         sound_builtin(e, chan, strcat(soundpack, samp), vol, atten);
928 }
929 */
930
931 // Sound functions
932 string precache_sound (string s) = #19;
933 void(entity e, float chan, string samp, float vol, float atten) sound = #8;
934 float precache_sound_index (string s) = #19;
935
936 void soundtoat(float dest, entity e, vector o, float chan, string samp, float vol, float atten)
937 {
938         WriteByte(dest, 6);
939         WriteByte(dest, 27); // all bits except SND_LOOPING
940         WriteByte(dest, vol * 255);
941         WriteByte(dest, atten * 64);
942         WriteEntity(dest, e);
943         WriteByte(dest, chan);
944         WriteShort(dest, precache_sound_index(samp));
945         WriteCoord(dest, o_x);
946         WriteCoord(dest, o_y);
947         WriteCoord(dest, o_z);
948 }
949 void soundto(float dest, entity e, float chan, string samp, float vol, float atten)
950 {
951         vector o;
952         o = e.origin + 0.5 * (e.mins + e.maxs);
953         soundtoat(dest, e, o, chan, samp, vol, atten);
954 }
955 void soundat(entity e, vector o, float chan, string samp, float vol, float atten)
956 {
957         soundtoat(MSG_BROADCAST, e, o, chan, samp, vol, atten);
958 }
959
960 void play2(entity e, string filename)
961 {
962         //stuffcmd(e, strcat("play2 ", filename, "\n"));
963         msg_entity = e;
964         soundtoat(MSG_ONE, world, '0 0 0', CHAN_AUTO, filename, VOL_BASE, ATTN_NONE);
965 }
966
967 .float announcetime;
968 float announce(entity player, string msg)
969 {
970         if(time > player.announcetime)
971         if(clienttype(player) == CLIENTTYPE_REAL)
972         {
973                 player.announcetime = time + 0.3;
974                 play2(player, msg);
975                 return TRUE;
976         }
977         return FALSE;
978 }
979
980 void play2team(float t, string filename)
981 {
982         local entity head;
983         FOR_EACH_REALPLAYER(head)
984         {
985                 if (head.team == t)
986                         play2(head, filename);
987         }
988 }
989
990 void play2all(string samp)
991 {
992         sound(world, CHAN_AUTO, samp, VOL_BASE, ATTN_NONE);
993 }
994
995 void PrecachePlayerSounds(string f);
996 void precache_all_models(string pattern)
997 {
998         float globhandle, i, n;
999         string f;
1000
1001         globhandle = search_begin(pattern, TRUE, FALSE);
1002         if(globhandle < 0)
1003                 return;
1004         n = search_getsize(globhandle);
1005         for(i = 0; i < n; ++i)
1006         {
1007                 //print(search_getfilename(globhandle, i), "\n");
1008                 f = search_getfilename(globhandle, i);
1009                 precache_model(f);
1010                 PrecachePlayerSounds(strcat(f, ".sounds"));
1011         }
1012         search_end(globhandle);
1013 }
1014
1015 void precache()
1016 {
1017         // gamemode related things
1018         precache_model ("models/misc/chatbubble.spr");
1019         precache_model ("models/misc/teambubble.spr");
1020         if (g_runematch)
1021         {
1022                 precache_model ("models/runematch/curse.mdl");
1023                 precache_model ("models/runematch/rune.mdl");
1024         }
1025
1026 #ifdef TTURRETS_ENABLED
1027     if(cvar("g_turrets"))
1028         turrets_precash();
1029 #endif
1030
1031         // Precache all player models if desired
1032         if (cvar("sv_precacheplayermodels"))
1033         {
1034                 PrecachePlayerSounds("sound/player/default.sounds");
1035                 precache_all_models("models/player/*.zym");
1036                 precache_all_models("models/player/*.dpm");
1037                 precache_all_models("models/player/*.md3");
1038                 precache_all_models("models/player/*.psk");
1039                 //precache_model("models/player/carni.zym");
1040                 //precache_model("models/player/crash.zym");
1041                 //precache_model("models/player/grunt.zym");
1042                 //precache_model("models/player/headhunter.zym");
1043                 //precache_model("models/player/insurrectionist.zym");
1044                 //precache_model("models/player/jeandarc.zym");
1045                 //precache_model("models/player/lurk.zym");
1046                 //precache_model("models/player/lycanthrope.zym");
1047                 //precache_model("models/player/marine.zym");
1048                 //precache_model("models/player/nexus.zym");
1049                 //precache_model("models/player/pyria.zym");
1050                 //precache_model("models/player/shock.zym");
1051                 //precache_model("models/player/skadi.zym");
1052                 //precache_model("models/player/specop.zym");
1053                 //precache_model("models/player/visitant.zym");
1054         }
1055
1056         if (g_footsteps)
1057         {
1058                 PrecacheGlobalSound((globalsound_step = "misc/footstep0 6"));
1059                 PrecacheGlobalSound((globalsound_metalstep = "misc/metalfootstep0 6"));
1060         }
1061
1062         // gore and miscellaneous sounds
1063         //precache_sound ("misc/h2ohit.wav");
1064         precache_model ("models/gibs/bloodyskull.md3");
1065         precache_model ("models/gibs/chunk.mdl");
1066         precache_model ("models/gibs/eye.md3");
1067         precache_model ("models/gibs/gib1.md3");
1068         precache_model ("models/gibs/gib2.md3");
1069         precache_model ("models/gibs/gib3.md3");
1070         precache_model ("models/gibs/gib4.md3");
1071         precache_model ("models/gibs/gib5.md3");
1072         precache_model ("models/gibs/gib6.md3");
1073         precache_model ("models/gibs/smallchest.md3");
1074         precache_model ("models/gibs/chest.md3");
1075         precache_model ("models/gibs/arm.md3");
1076         precache_model ("models/gibs/leg1.md3");
1077         precache_model ("models/gibs/leg2.md3");
1078         precache_model ("models/hook.md3");
1079         precache_sound ("misc/armorimpact.wav");
1080         precache_sound ("misc/bodyimpact1.wav");
1081         precache_sound ("misc/bodyimpact2.wav");
1082         precache_sound ("misc/gib.wav");
1083         precache_sound ("misc/gib_splat01.wav");
1084         precache_sound ("misc/gib_splat02.wav");
1085         precache_sound ("misc/gib_splat03.wav");
1086         precache_sound ("misc/gib_splat04.wav");
1087         precache_sound ("misc/hit.wav");
1088         PrecacheGlobalSound((globalsound_fall = "misc/hitground 4"));
1089         PrecacheGlobalSound((globalsound_metalfall = "misc/metalhitground 4"));
1090         precache_sound ("misc/null.wav");
1091         precache_sound ("misc/spawn.wav");
1092         precache_sound ("misc/talk.wav");
1093         precache_sound ("misc/teleport.wav");
1094         precache_sound ("player/lava.wav");
1095         precache_sound ("player/slime.wav");
1096
1097         // announcer sounds - male
1098         precache_sound ("announcer/male/electrobitch.wav");
1099         precache_sound ("announcer/male/airshot.wav");
1100         precache_sound ("announcer/male/03kills.wav");
1101         precache_sound ("announcer/male/05kills.wav");
1102         precache_sound ("announcer/male/10kills.wav");
1103         precache_sound ("announcer/male/15kills.wav");
1104         precache_sound ("announcer/male/20kills.wav");
1105         precache_sound ("announcer/male/25kills.wav");
1106         precache_sound ("announcer/male/30kills.wav");
1107         precache_sound ("announcer/male/botlike.wav");
1108         precache_sound ("announcer/male/yoda.ogg");
1109         precache_sound ("announcer/male/headshot.ogg");
1110         precache_sound ("announcer/male/impressive.ogg");
1111
1112         // announcer sounds - robotic
1113         precache_sound ("announcer/robotic/prepareforbattle.wav");
1114         precache_sound ("announcer/robotic/begin.wav");
1115         precache_sound ("announcer/robotic/timeoutcalled.wav");
1116         precache_sound ("announcer/robotic/1fragleft.wav");
1117         precache_sound ("announcer/robotic/1minuteremains.wav");
1118         precache_sound ("announcer/robotic/2fragsleft.wav");
1119         precache_sound ("announcer/robotic/3fragsleft.wav");
1120         if (g_minstagib)
1121         {
1122                 precache_sound ("announcer/robotic/lastsecond.wav");
1123                 precache_sound ("announcer/robotic/narrowly.wav");
1124         }
1125
1126         precache_model ("models/sprites/1.spr32");
1127         precache_model ("models/sprites/2.spr32");
1128         precache_model ("models/sprites/3.spr32");
1129         precache_model ("models/sprites/4.spr32");
1130         precache_model ("models/sprites/5.spr32");
1131         precache_model ("models/sprites/6.spr32");
1132         precache_model ("models/sprites/7.spr32");
1133         precache_model ("models/sprites/8.spr32");
1134         precache_model ("models/sprites/9.spr32");
1135         precache_model ("models/sprites/10.spr32");
1136         precache_sound ("announcer/robotic/1.ogg");
1137         precache_sound ("announcer/robotic/2.ogg");
1138         precache_sound ("announcer/robotic/3.ogg");
1139         precache_sound ("announcer/robotic/4.ogg");
1140         precache_sound ("announcer/robotic/5.ogg");
1141         precache_sound ("announcer/robotic/6.ogg");
1142         precache_sound ("announcer/robotic/7.ogg");
1143         precache_sound ("announcer/robotic/8.ogg");
1144         precache_sound ("announcer/robotic/9.ogg");
1145         precache_sound ("announcer/robotic/10.ogg");
1146
1147         // common weapon precaches
1148         precache_sound ("weapons/weapon_switch.wav");
1149         precache_sound ("weapons/weaponpickup.wav");
1150         if (cvar("g_grappling_hook"))
1151         {
1152                 precache_sound ("weapons/hook_fire.wav"); // hook
1153                 precache_sound ("weapons/hook_impact.wav"); // hook
1154         }
1155
1156         if (cvar("sv_precacheweapons") || g_nixnex)
1157         {
1158                 //precache weapon models/sounds
1159                 local float wep;
1160                 wep = WEP_FIRST;
1161                 while (wep <= WEP_LAST)
1162                 {
1163                         weapon_action(wep, WR_PRECACHE);
1164                         wep = wep + 1;
1165                 }
1166         }
1167
1168         // plays music for the level if there is any
1169         if (self.noise)
1170         {
1171                 precache_sound (self.noise);
1172                 ambientsound ('0 0 0', self.noise, VOL_BASE, ATTN_NONE);
1173         }
1174 }
1175
1176 // sorry, but using \ in macros breaks line numbers
1177 #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
1178 #define WRITESPECTATABLE_MSG_ONE(statement) WRITESPECTATABLE_MSG_ONE_VARNAME(oldmsg_entity, statement)
1179 #define WRITESPECTATABLE(msg,statement) if(msg == MSG_ONE) { WRITESPECTATABLE_MSG_ONE(statement); } else statement float WRITESPECTATABLE_workaround = 0
1180
1181 vector ExactTriggerHit_mins;
1182 vector ExactTriggerHit_maxs;
1183 float ExactTriggerHit_Recurse()
1184 {
1185         float s;
1186         entity se;
1187         float f;
1188
1189         tracebox('0 0 0', ExactTriggerHit_mins, ExactTriggerHit_maxs, '0 0 0', MOVE_NORMAL, other);
1190         if not(trace_ent)
1191                 return 0;
1192         if(trace_ent == self)
1193                 return 1;
1194
1195         se = trace_ent;
1196         s = se.solid;
1197         se.solid = SOLID_NOT;
1198         f = ExactTriggerHit_Recurse();
1199         se.solid = s;
1200
1201         return f;
1202 }
1203
1204 float ExactTriggerHit()
1205 {
1206         float f, s;
1207
1208         if not(self.modelindex)
1209                 return 1;
1210
1211         s = self.solid;
1212         self.solid = SOLID_BSP;
1213         ExactTriggerHit_mins = other.absmin;
1214         ExactTriggerHit_maxs = other.absmax;
1215         f = ExactTriggerHit_Recurse();
1216         self.solid = s;
1217
1218         return f;
1219 }
1220
1221 // WARNING: this kills the trace globals
1222 #define EXACTTRIGGER_TOUCH if not(ExactTriggerHit()) return
1223 #define EXACTTRIGGER_INIT  InitSolidBSPTrigger(); self.solid = SOLID_TRIGGER
1224
1225 #define INITPRIO_FIRST              0
1226 #define INITPRIO_GAMETYPE           0
1227 #define INITPRIO_GAMETYPE_FALLBACK  1
1228 #define INITPRIO_CVARS              5
1229 #define INITPRIO_FINDTARGET        10
1230 #define INITPRIO_DROPTOFLOOR       20
1231 #define INITPRIO_SETLOCATION       90
1232 #define INITPRIO_LINKDOORS         91
1233 #define INITPRIO_LAST              99
1234
1235 .void(void) initialize_entity;
1236 .float initialize_entity_order;
1237 .entity initialize_entity_next;
1238 entity initialize_entity_first;
1239
1240 void make_safe_for_remove(entity e)
1241 {
1242         if(e.initialize_entity)
1243         {
1244                 entity ent, prev;
1245                 for(ent = initialize_entity_first; ent; )
1246                 {
1247                         if((ent == e) || ((ent.classname == "initialize_entity") && (ent.enemy == e)))
1248                         {
1249                                 print("make_safe_for_remove: getting rid of initializer ", etos(ent), "\n");
1250                                 // skip it in linked list
1251                                 if(prev)
1252                                 {
1253                                         prev.initialize_entity_next = ent.initialize_entity_next;
1254                                         ent = prev.initialize_entity_next;
1255                                 }
1256                                 else
1257                                 {
1258                                         initialize_entity_first = ent.initialize_entity_next;
1259                                         ent = initialize_entity_first;
1260                                 }
1261                         }
1262                         else
1263                         {
1264                                 prev = ent;
1265                                 ent = ent.initialize_entity_next;
1266                         }
1267                 }
1268         }
1269 }
1270
1271 void objerror(string s)
1272 {
1273         make_safe_for_remove(self);
1274         objerror_builtin(s);
1275 }
1276
1277 void remove_safely(entity e)
1278 {
1279         make_safe_for_remove(e);
1280         remove_builtin(e);
1281 }
1282
1283 void InitializeEntity(entity e, void(void) func, float order)
1284 {
1285         entity prev, cur;
1286
1287         if(!e || e.initialize_entity)
1288         {
1289                 // make a proxy initializer entity
1290                 entity e_old;
1291                 e_old = e;
1292                 e = spawn();
1293                 e.classname = "initialize_entity";
1294                 e.enemy = e_old;
1295         }
1296
1297         e.initialize_entity = func;
1298         e.initialize_entity_order = order;
1299
1300         cur = initialize_entity_first;
1301         for(;;)
1302         {
1303                 if(!cur || cur.initialize_entity_order > order)
1304                 {
1305                         // insert between prev and cur
1306                         if(prev)
1307                                 prev.initialize_entity_next = e;
1308                         else
1309                                 initialize_entity_first = e;
1310                         e.initialize_entity_next = cur;
1311                         return;
1312                 }
1313                 prev = cur;
1314                 cur = cur.initialize_entity_next;
1315         }
1316 }
1317 void InitializeEntitiesRun()
1318 {
1319         entity startoflist;
1320         startoflist = initialize_entity_first;
1321         initialize_entity_first = world;
1322         for(self = startoflist; self; )
1323         {
1324                 entity e;
1325                 var void(void) func;
1326                 e = self.initialize_entity_next;
1327                 func = self.initialize_entity;
1328                 self.initialize_entity_order = 0;
1329                 self.initialize_entity = func_null;
1330                 self.initialize_entity_next = world;
1331                 if(self.classname == "initialize_entity")
1332                 {
1333                         entity e_old;
1334                         e_old = self.enemy;
1335                         remove_builtin(self);
1336                         self = e_old;
1337                 }
1338                 dprint("Delayed initialization: ", self.classname, "\n");
1339                 func();
1340                 self = e;
1341         }
1342 }
1343
1344 .float uncustomizeentityforclient_set;
1345 .void(void) uncustomizeentityforclient;
1346 void(void) SUB_Nullpointer = #0;
1347 void UncustomizeEntitiesRun()
1348 {
1349         entity oldself;
1350         oldself = self;
1351         for(self = world; (self = findfloat(self, uncustomizeentityforclient_set, 1)); )
1352                 self.uncustomizeentityforclient();
1353         self = oldself;
1354 }
1355 void SetCustomizer(entity e, float(void) customizer, void(void) uncustomizer)
1356 {
1357         e.customizeentityforclient = customizer;
1358         e.uncustomizeentityforclient = uncustomizer;
1359         e.uncustomizeentityforclient_set = (uncustomizer != SUB_Nullpointer);
1360 }
1361
1362 .float nottargeted;
1363 #define IFTARGETED if(!self.nottargeted && self.targetname != "")
1364
1365 float power2of(float e)
1366 {
1367         return pow(2, e);
1368 }
1369 float log2of(float x)
1370 {
1371         // NOTE: generated code
1372         if(x > 2048)
1373                 if(x > 131072)
1374                         if(x > 1048576)
1375                                 if(x > 4194304)
1376                                         return 23;
1377                                 else
1378                                         if(x > 2097152)
1379                                                 return 22;
1380                                         else
1381                                                 return 21;
1382                         else
1383                                 if(x > 524288)
1384                                         return 20;
1385                                 else
1386                                         if(x > 262144)
1387                                                 return 19;
1388                                         else
1389                                                 return 18;
1390                 else
1391                         if(x > 16384)
1392                                 if(x > 65536)
1393                                         return 17;
1394                                 else
1395                                         if(x > 32768)
1396                                                 return 16;
1397                                         else
1398                                                 return 15;
1399                         else
1400                                 if(x > 8192)
1401                                         return 14;
1402                                 else
1403                                         if(x > 4096)
1404                                                 return 13;
1405                                         else
1406                                                 return 12;
1407         else
1408                 if(x > 32)
1409                         if(x > 256)
1410                                 if(x > 1024)
1411                                         return 11;
1412                                 else
1413                                         if(x > 512)
1414                                                 return 10;
1415                                         else
1416                                                 return 9;
1417                         else
1418                                 if(x > 128)
1419                                         return 8;
1420                                 else
1421                                         if(x > 64)
1422                                                 return 7;
1423                                         else
1424                                                 return 6;
1425                 else
1426                         if(x > 4)
1427                                 if(x > 16)
1428                                         return 5;
1429                                 else
1430                                         if(x > 8)
1431                                                 return 4;
1432                                         else
1433                                                 return 3;
1434                         else
1435                                 if(x > 2)
1436                                         return 2;
1437                                 else
1438                                         if(x > 1)
1439                                                 return 1;
1440                                         else
1441                                                 return 0;
1442 }
1443
1444 void Net_LinkEntity(entity e)
1445 {
1446         e.model = "net_entity";
1447         e.modelindex = 1;
1448         e.effects = EF_NODEPTHTEST | EF_LOWPRECISION;
1449 }
1450
1451 void adaptor_think2touch()
1452 {
1453         entity o;
1454         o = other;
1455         other = world;
1456         self.touch();
1457         other = o;
1458 }
1459
1460 void adaptor_think2use()
1461 {
1462         entity o, a;
1463         o = other;
1464         a = activator;
1465         activator = world;
1466         other = world;
1467         self.use();
1468         other = o;
1469         activator = a;
1470 }
1471
1472 // deferred dropping
1473 void DropToFloor_Handler()
1474 {
1475         droptofloor_builtin();
1476         self.dropped_origin = self.origin;
1477 }
1478
1479 void droptofloor()
1480 {
1481         InitializeEntity(self, DropToFloor_Handler, INITPRIO_DROPTOFLOOR);
1482 }
1483
1484
1485
1486 float trace_hits_box_a0, trace_hits_box_a1;
1487
1488 float trace_hits_box_1d(float end, float thmi, float thma)
1489 {
1490         if(end == 0)
1491         {
1492                 // just check if x is in range
1493                 if(0 < thmi)
1494                         return FALSE;
1495                 if(0 > thma)
1496                         return FALSE;
1497         }
1498         else
1499         {
1500                 // do the trace with respect to x
1501                 // 0 -> end has to stay in thmi -> thma
1502                 trace_hits_box_a0 = max(trace_hits_box_a0, min(thmi / end, thma / end));
1503                 trace_hits_box_a1 = min(trace_hits_box_a1, max(thmi / end, thma / end));
1504                 if(trace_hits_box_a0 > trace_hits_box_a1)
1505                         return FALSE;
1506         }
1507         return TRUE;
1508 }
1509
1510 float trace_hits_box(vector start, vector end, vector thmi, vector thma)
1511 {
1512         end -= start;
1513         thmi -= start;
1514         thma -= start;
1515         // now it is a trace from 0 to end
1516
1517         trace_hits_box_a0 = 0;
1518         trace_hits_box_a1 = 1;
1519
1520         if(!trace_hits_box_1d(end_x, thmi_x, thma_x))
1521                 return FALSE;
1522         if(!trace_hits_box_1d(end_y, thmi_y, thma_y))
1523                 return FALSE;
1524         if(!trace_hits_box_1d(end_z, thmi_z, thma_z))
1525                 return FALSE;
1526
1527         return TRUE;
1528 }
1529
1530 float tracebox_hits_box(vector start, vector mi, vector ma, vector end, vector thmi, vector thma)
1531 {
1532         return trace_hits_box(start, end, thmi - ma, thma - mi);
1533 }