]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/miscfunctions.qc
now REALLY remove dead players
[divverent/nexuiz.git] / data / qcsrc / server / miscfunctions.qc
1 void() spawnfunc_info_player_deathmatch; // needed for the other spawnpoints
2 void() spawnpoint_use;
3 string ColoredTeamName(float t);
4
5 float RandomSelection_totalweight;
6 float RandomSelection_best_priority;
7 entity RandomSelection_chosen_ent;
8 float RandomSelection_chosen_float;
9 void RandomSelection_Init()
10 {
11         RandomSelection_totalweight = 0;
12         RandomSelection_chosen_ent = world;
13         RandomSelection_chosen_float = 0;
14         RandomSelection_best_priority = -1;
15 }
16 void RandomSelection_Add(entity e, float f, float weight, float priority)
17 {
18         if(priority > RandomSelection_best_priority)
19         {
20                 RandomSelection_best_priority = priority;
21                 RandomSelection_chosen_ent = e;
22                 RandomSelection_chosen_float = f;
23                 RandomSelection_totalweight = weight;
24         }
25         else if(priority == RandomSelection_best_priority)
26         {
27                 RandomSelection_totalweight += weight;
28                 if(random() * RandomSelection_totalweight <= weight)
29                 {
30                         RandomSelection_chosen_ent = e;
31                         RandomSelection_chosen_float = f;
32                 }
33         }
34 }
35
36 float DistributeEvenly_amount;
37 float DistributeEvenly_totalweight;
38 void DistributeEvenly_Init(float amount, float totalweight)
39 {
40         if(DistributeEvenly_amount)
41         {
42                 dprint("DistributeEvenly_Init: UNFINISHED DISTRIBUTION (", ftos(DistributeEvenly_amount), " for ");
43                 dprint(ftos(DistributeEvenly_totalweight), " left!)\n");
44         }
45         if(totalweight == 0)
46                 DistributeEvenly_amount = 0;
47         else
48                 DistributeEvenly_amount = amount;
49         DistributeEvenly_totalweight = totalweight;
50 }
51 float DistributeEvenly_Get(float weight)
52 {
53         float f;
54         if(weight <= 0)
55                 return 0;
56         f = floor(0.5 + DistributeEvenly_amount * weight / DistributeEvenly_totalweight);
57         DistributeEvenly_totalweight -= weight;
58         DistributeEvenly_amount -= f;
59         return f;
60 }
61
62 void move_out_of_solid_expand(entity e, vector by)
63 {
64         float eps = 0.0625;
65         tracebox(e.origin, e.mins - '1 1 1' * eps, e.maxs + '1 1 1' * eps, e.origin + by, MOVE_WORLDONLY, e);
66         if(trace_startsolid)
67                 return;
68         if(trace_fraction < 1)
69         {
70                 // hit something
71                 // adjust origin in the other direction...
72                 e.origin = e.origin - by * (1 - trace_fraction);
73         }
74 }
75
76 float move_out_of_solid(entity e)
77 {
78         vector o, m0, m1;
79
80         o = e.origin;
81         traceline(o, o, MOVE_WORLDONLY, e);
82         if(trace_startsolid)
83                 return 0;
84
85         tracebox(o, e.mins, e.maxs, o, MOVE_WORLDONLY, e);
86         if(!trace_startsolid)
87                 return 1;
88
89         m0 = e.mins;
90         m1 = e.maxs;
91         e.mins = '0 0 0';
92         e.maxs = '0 0 0';
93         move_out_of_solid_expand(e, '1 0 0' * m0_x); e.mins_x = m0_x;
94         move_out_of_solid_expand(e, '1 0 0' * m1_x); e.maxs_x = m1_x;
95         move_out_of_solid_expand(e, '0 1 0' * m0_y); e.mins_y = m0_y;
96         move_out_of_solid_expand(e, '0 1 0' * m1_y); e.maxs_y = m1_y;
97         move_out_of_solid_expand(e, '0 0 1' * m0_z); e.mins_z = m0_z;
98         move_out_of_solid_expand(e, '0 0 1' * m1_z); e.maxs_z = m1_z;
99         setorigin(e, e.origin);
100
101         tracebox(e.origin, e.mins, e.maxs, e.origin, MOVE_WORLDONLY, e);
102         if(trace_startsolid)
103         {
104                 setorigin(e, o);
105                 return 0;
106         }
107
108         return 1;
109 }
110
111 string STR_PLAYER = "player";
112 string STR_SPECTATOR = "spectator";
113 string STR_OBSERVER = "observer";
114
115 #if 0
116 #define FOR_EACH_CLIENT(v) for(v = world; (v = findflags(v, flags, FL_CLIENT)) != world; )
117 #define FOR_EACH_REALCLIENT(v) FOR_EACH_CLIENT(v) if(clienttype(v) == CLIENTTYPE_REAL)
118 #define FOR_EACH_PLAYER(v) for(v = world; (v = find(v, classname, STR_PLAYER)) != world; )
119 #define FOR_EACH_REALPLAYER(v) FOR_EACH_PLAYER(v) if(clienttype(v) == CLIENTTYPE_REAL)
120 #else
121 #define FOR_EACH_CLIENTSLOT(v) for(v = world; (v = nextent(v)) && (num_for_edict(v) <= maxclients); )
122 #define FOR_EACH_CLIENT(v) FOR_EACH_CLIENTSLOT(v) if(v.flags & FL_CLIENT)
123 #define FOR_EACH_REALCLIENT(v) FOR_EACH_CLIENT(v) if(clienttype(v) == CLIENTTYPE_REAL)
124 #define FOR_EACH_PLAYER(v) FOR_EACH_CLIENT(v) if(v.classname == STR_PLAYER)
125 #define FOR_EACH_REALPLAYER(v) FOR_EACH_REALCLIENT(v) if(v.classname == STR_PLAYER)
126 #endif
127
128 // copies a string to a tempstring (so one can strunzone it)
129 string strcat1(string s) = #115; // FRIK_FILE
130
131 float logfile_open;
132 float logfile;
133
134 void bcenterprint(string s)
135 {
136         // TODO replace by MSG_ALL (would show it to spectators too, though)?
137         entity head;
138         FOR_EACH_PLAYER(head)
139                 if(clienttype(head) == CLIENTTYPE_REAL)
140                         centerprint(head, s);
141 }
142
143 void GameLogEcho(string s)
144 {
145         string fn;
146         float matches;
147
148         if(cvar("sv_eventlog_files"))
149         {
150                 if(!logfile_open)
151                 {
152                         logfile_open = TRUE;
153                         matches = cvar("sv_eventlog_files_counter") + 1;
154                         cvar_set("sv_eventlog_files_counter", ftos(matches));
155                         fn = ftos(matches);
156                         if(strlen(fn) < 8)
157                                 fn = strcat(substring("00000000", 0, 8 - strlen(fn)), fn);
158                         fn = strcat(cvar_string("sv_eventlog_files_nameprefix"), fn, cvar_string("sv_eventlog_files_namesuffix"));
159                         logfile = fopen(fn, FILE_APPEND);
160                         fputs(logfile, ":logversion:2\n");
161                 }
162                 if(logfile >= 0)
163                 {
164                         if(cvar("sv_eventlog_files_timestamps"))
165                                 fputs(logfile, strcat(":time:", strftime(TRUE, "%Y-%m-%d %H:%M:%S", "\n", s, "\n")));
166                         else
167                                 fputs(logfile, strcat(s, "\n"));
168                 }
169         }
170         if(cvar("sv_eventlog_console"))
171         {
172                 print(s, "\n");
173         }
174 }
175
176 void GameLogInit()
177 {
178         logfile_open = 0;
179         // will be opened later
180 }
181
182 void GameLogClose()
183 {
184         if(logfile_open && logfile >= 0)
185         {
186                 fclose(logfile);
187                 logfile = -1;
188         }
189 }
190
191 float spawnpoint_nag;
192 void relocate_spawnpoint()
193 {
194         // nudge off the floor
195         setorigin(self, self.origin + '0 0 1');
196
197         tracebox(self.origin, PL_MIN, PL_MAX, self.origin, TRUE, self);
198         if (trace_startsolid)
199         {
200                 vector o;
201                 o = self.origin;
202                 self.mins = PL_MIN;
203                 self.maxs = PL_MAX;
204                 if(!move_out_of_solid(self))
205                         objerror("could not get out of solid at all!");
206                 print("^1NOTE: this map needs FIXING. Spawnpoint at ", vtos(o - '0 0 1'));
207                 print(" needs to be moved out of solid, e.g. by '", ftos(self.origin_x - o_x));
208                 print(" ", ftos(self.origin_y - o_y));
209                 print(" ", ftos(self.origin_z - o_z), "'\n");
210                 if(cvar("g_spawnpoints_auto_move_out_of_solid"))
211                 {
212                         if(!spawnpoint_nag)
213                                 print("\{1}^1NOTE: this map needs FIXING (it contains spawnpoints in solid, see server log)\n");
214                         spawnpoint_nag = 1;
215                 }
216                 else
217                 {
218                         self.origin = o;
219                         self.mins = self.maxs = '0 0 0';
220                         objerror("player spawn point in solid, mapper sucks!\n");
221                         return;
222                 }
223         }
224
225         if(cvar("g_spawnpoints_autodrop"))
226         {
227                 setsize(self, PL_MIN, PL_MAX);
228                 droptofloor();
229         }
230
231         self.use = spawnpoint_use;
232         self.team_saved = self.team;
233         if(!self.cnt)
234                 self.cnt = 1;
235
236         if(g_ctf || g_assault || g_onslaught || g_domination)
237         if(self.team)
238                 have_team_spawns = 1;
239
240         if(cvar("r_showbboxes"))
241         {
242                 // show where spawnpoints point at too
243                 makevectors(self.angles);
244                 entity e;
245                 e = spawn();
246                 e.classname = "info_player_foo";
247                 setorigin(e, self.origin + v_forward * 24);
248                 setsize(e, '-8 -8 -8', '8 8 8');
249                 e.solid = SOLID_TRIGGER;
250         }
251 }
252
253 #define strstr strstrofs
254 /*
255 // NOTE: DO NOT USE THIS FUNCTION TOO OFTEN.
256 // IT WILL MOST PROBABLY DESTROY _ALL_ OTHER TEMP
257 // STRINGS AND TAKE QUITE LONG. haystack and needle MUST
258 // BE CONSTANT OR strzoneD!
259 float strstr(string haystack, string needle, float offset)
260 {
261         float len, endpos;
262         string found;
263         len = strlen(needle);
264         endpos = strlen(haystack) - len;
265         while(offset <= endpos)
266         {
267                 found = substring(haystack, offset, len);
268                 if(found == needle)
269                         return offset;
270                 offset = offset + 1;
271         }
272         return -1;
273 }
274 */
275
276 float NUM_NEAREST_ENTITIES = 4;
277 entity nearest_entity[NUM_NEAREST_ENTITIES];
278 float nearest_length[NUM_NEAREST_ENTITIES];
279 entity findnearest(vector point, .string field, string value, vector axismod)
280 {
281         entity localhead;
282         float i;
283         float j;
284         float len;
285         vector dist;
286
287         float num_nearest;
288         num_nearest = 0;
289
290         localhead = find(world, field, value);
291         while(localhead)
292         {
293                 if((localhead.items == IT_KEY1 || localhead.items == IT_KEY2) && localhead.target == "###item###")
294                         dist = localhead.oldorigin;
295                 else
296                         dist = localhead.origin;
297                 dist = dist - point;
298                 dist = dist_x * axismod_x * '1 0 0' + dist_y * axismod_y * '0 1 0' + dist_z * axismod_z * '0 0 1';
299                 len = vlen(dist);
300
301                 for(i = 0; i < num_nearest; ++i)
302                 {
303                         if(len < nearest_length[i])
304                                 break;
305                 }
306
307                 // now i tells us where to insert at
308                 //   INSERTION SORT! YOU'VE SEEN IT! RUN!
309                 if(i < NUM_NEAREST_ENTITIES)
310                 {
311                         for(j = NUM_NEAREST_ENTITIES - 1; j >= i; --j)
312                         {
313                                 nearest_length[j + 1] = nearest_length[j];
314                                 nearest_entity[j + 1] = nearest_entity[j];
315                         }
316                         nearest_length[i] = len;
317                         nearest_entity[i] = localhead;
318                         if(num_nearest < NUM_NEAREST_ENTITIES)
319                                 num_nearest = num_nearest + 1;
320                 }
321
322                 localhead = find(localhead, field, value);
323         }
324
325         // now use the first one from our list that we can see
326         for(i = 0; i < num_nearest; ++i)
327         {
328                 traceline(point, nearest_entity[i].origin, TRUE, world);
329                 if(trace_fraction == 1)
330                 {
331                         if(i != 0)
332                         {
333                                 dprint("Nearest point (");
334                                 dprint(nearest_entity[0].netname);
335                                 dprint(") is not visible, using a visible one.\n");
336                         }
337                         return nearest_entity[i];
338                 }
339         }
340
341         if(num_nearest == 0)
342                 return world;
343
344         dprint("Not seeing any location point, using nearest as fallback.\n");
345         /* DEBUGGING CODE:
346         dprint("Candidates were: ");
347         for(j = 0; j < num_nearest; ++j)
348         {
349                 if(j != 0)
350                         dprint(", ");
351                 dprint(nearest_entity[j].netname);
352         }
353         dprint("\n");
354         */
355
356         return nearest_entity[0];
357 }
358
359 void spawnfunc_target_location()
360 {
361         self.classname = "target_location";
362         // location name in netname
363         // eventually support: count, teamgame selectors, line of sight?
364 };
365
366 void spawnfunc_info_location()
367 {
368         self.classname = "target_location";
369         self.message = self.netname;
370 };
371
372 string NearestLocation(vector p)
373 {
374         entity loc;
375         string ret;
376         ret = "somewhere";
377         loc = findnearest(p, classname, "target_location", '1 1 1');
378         if(loc)
379         {
380                 ret = loc.message;
381         }
382         else
383         {
384                 loc = findnearest(p, target, "###item###", '1 1 4');
385                 if(loc)
386                         ret = loc.netname;
387         }
388         return ret;
389 }
390
391 string formatmessage(string msg)
392 {
393         float p;
394         float n;
395         string msg_save;
396         string escape;
397         string replacement;
398         msg_save = strzone(msg);
399         p = 0;
400         n = 7;
401         while(1)
402         {
403                 if(n < 1)
404                         break; // too many replacements
405                 n = n - 1;
406                 p = strstr(msg_save, "%", p); // NOTE: this destroys msg as it's a tempstring!
407                 if(p < 0)
408                         break;
409                 replacement = substring(msg_save, p, 2);
410                 escape = substring(msg_save, p + 1, 1);
411                 if(escape == "%")
412                         replacement = "%";
413                 else if(escape == "a")
414                         replacement = ftos(floor(self.armorvalue));
415                 else if(escape == "h")
416                         replacement = ftos(floor(self.health));
417                 else if(escape == "l")
418                         replacement = NearestLocation(self.origin);
419                 else if(escape == "y")
420                         replacement = NearestLocation(self.cursor_trace_endpos);
421                 else if(escape == "d")
422                         replacement = NearestLocation(self.death_origin);
423                 else if(escape == "w")
424                 {
425                         float wep;
426                         wep = self.weapon;
427                         if(!wep)
428                                 wep = self.switchweapon;
429                         if(!wep)
430                                 wep = self.cnt;
431                         replacement = W_Name(wep);
432                 }
433                 else if(escape == "W")
434                 {
435                         if(self.items & IT_SHELLS) replacement = "shells";
436                         else if(self.items & IT_NAILS) replacement = "bullets";
437                         else if(self.items & IT_ROCKETS) replacement = "rockets";
438                         else if(self.items & IT_CELLS) replacement = "cells";
439                         else replacement = "batteries"; // ;)
440                 }
441                 else if(escape == "x")
442                 {
443                         replacement = self.cursor_trace_ent.netname;
444                         if(!replacement || !self.cursor_trace_ent)
445                                 replacement = "nothing";
446                 }
447                 else if(escape == "p")
448                 {
449                         if(self.last_selected_player)
450                                 replacement = self.last_selected_player.netname;
451                         else
452                                 replacement = "(nobody)";
453                 }
454                 msg = strcat(substring(msg_save, 0, p), replacement);
455                 msg = strcat(msg, substring(msg_save, p+2, strlen(msg_save) - (p+2)));
456                 strunzone(msg_save);
457                 msg_save = strzone(msg);
458                 p = p + 2;
459         }
460         msg = strcat(msg_save, "");
461         strunzone(msg_save);
462         return msg;
463 }
464
465 /*
466 =============
467 GetCvars
468 =============
469 Called with:
470   0:  sends the request
471   >0: receives a cvar from name=argv(f) value=argv(f+1)
472 */
473 void GetCvars_handleString(string thisname, float f, .string field, string name)
474 {
475         if(f < 0)
476         {
477                 if(self.field)
478                         strunzone(self.field);
479         }
480         else if(f > 0)
481         {
482                 if(thisname == name)
483                 {
484                         if(self.field)
485                                 strunzone(self.field);
486                         self.field = strzone(argv(f + 1));
487                 }
488         }
489         else
490                 stuffcmd(self, strcat("sendcvar ", name, "\n"));
491 }
492 void GetCvars_handleString_Fixup(string thisname, float f, .string field, string name, string(string) func)
493 {
494         GetCvars_handleString(thisname, f, field, name);
495         if(f >= 0) // also initialize to the fitting value for "" when sending cvars out
496         if(thisname == name)
497         {
498                 string s;
499                 s = func(strcat1(self.field));
500                 if(s != self.field)
501                 {
502                         strunzone(self.field);
503                         self.field = strzone(s);
504                 }
505         }
506 }
507 void GetCvars_handleFloat(string thisname, float f, .float field, string name)
508 {
509         if(f < 0)
510         {
511         }
512         else if(f > 0)
513         {
514                 if(thisname == name)
515                         self.field = stof(argv(f + 1));
516         }
517         else
518                 stuffcmd(self, strcat("sendcvar ", name, "\n"));
519 }
520 string W_FixWeaponOrder_ForceComplete(string s);
521 string W_FixWeaponOrder_AllowIncomplete(string s);
522 float w_getbestweapon(entity e);
523 void GetCvars(float f)
524 {
525         string s;
526         if(f > 0)
527                 s = strcat1(argv(f));
528         GetCvars_handleFloat(s, f, autoswitch, "cl_autoswitch");
529         GetCvars_handleFloat(s, f, cvar_cl_hidewaypoints, "cl_hidewaypoints");
530         GetCvars_handleFloat(s, f, cvar_cl_playerdetailreduction, "cl_playerdetailreduction");
531         GetCvars_handleFloat(s, f, cvar_cl_nogibs, "cl_nogibs");
532         GetCvars_handleFloat(s, f, cvar_scr_centertime, "scr_centertime");
533         GetCvars_handleFloat(s, f, cvar_cl_shownames, "cl_shownames");
534         GetCvars_handleString(s, f, cvar_g_nexuizversion, "g_nexuizversion");
535         GetCvars_handleFloat(s, f, cvar_cl_handicap, "cl_handicap");
536         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriority, "cl_weaponpriority", W_FixWeaponOrder_ForceComplete);
537         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[0], "cl_weaponpriority0", W_FixWeaponOrder_AllowIncomplete);
538         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[1], "cl_weaponpriority1", W_FixWeaponOrder_AllowIncomplete);
539         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[2], "cl_weaponpriority2", W_FixWeaponOrder_AllowIncomplete);
540         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[3], "cl_weaponpriority3", W_FixWeaponOrder_AllowIncomplete);
541         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[4], "cl_weaponpriority4", W_FixWeaponOrder_AllowIncomplete);
542         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[5], "cl_weaponpriority5", W_FixWeaponOrder_AllowIncomplete);
543         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[6], "cl_weaponpriority6", W_FixWeaponOrder_AllowIncomplete);
544         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[7], "cl_weaponpriority7", W_FixWeaponOrder_AllowIncomplete);
545         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[8], "cl_weaponpriority8", W_FixWeaponOrder_AllowIncomplete);
546         GetCvars_handleString_Fixup(s, f, cvar_cl_weaponpriorities[9], "cl_weaponpriority9", W_FixWeaponOrder_AllowIncomplete);
547
548         // fixup of switchweapon (needed for LMS or when spectating is disabled, as PutClientInServer comes too early)
549         if(f > 0)
550         {
551                 if(s == "cl_weaponpriority")
552                         self.switchweapon = w_getbestweapon(self);
553         }
554 }
555
556 float fexists(string f)
557 {
558         float fh;
559         fh = fopen(f, FILE_READ);
560         if(fh < 0)
561                 return FALSE;
562         fclose(fh);
563         return TRUE;
564 }
565
566 void backtrace(string msg)
567 {
568         float dev;
569         dev = cvar("developer");
570         cvar_set("developer", "1");
571         dprint("\n");
572         dprint("--- CUT HERE ---\nWARNING: ");
573         dprint(msg);
574         dprint("\n");
575         remove(world); // isn't there any better way to cause a backtrace?
576         dprint("\n--- CUT UNTIL HERE ---\n");
577         cvar_set("developer", ftos(dev));
578 }
579
580 string Team_ColorCode(float teamid)
581 {
582         if(teamid == COLOR_TEAM1)
583                 return "^1";
584         else if(teamid == COLOR_TEAM2)
585                 return "^4";
586         else if(teamid == COLOR_TEAM3)
587                 return "^3";
588         else if(teamid == COLOR_TEAM4)
589                 return "^6";
590         else
591                 return "^7";
592 }
593 string Team_ColorName(float t)
594 {
595         // fixme: Search for team entities and get their .netname's!
596         if(t == COLOR_TEAM1)
597                 return "Red";
598         if(t == COLOR_TEAM2)
599                 return "Blue";
600         if(t == COLOR_TEAM3)
601                 return "Yellow";
602         if(t == COLOR_TEAM4)
603                 return "Pink";
604         return "Neutral";
605 }
606 string Team_ColorNameLowerCase(float t)
607 {
608         // fixme: Search for team entities and get their .netname's!
609         if(t == COLOR_TEAM1)
610                 return "red";
611         if(t == COLOR_TEAM2)
612                 return "blue";
613         if(t == COLOR_TEAM3)
614                 return "yellow";
615         if(t == COLOR_TEAM4)
616                 return "pink";
617         return "neutral";
618 }
619
620 #define CENTERPRIO_POINT 1
621 #define CENTERPRIO_SPAM 2
622 #define CENTERPRIO_REBALANCE 2
623 #define CENTERPRIO_VOTE 4
624 #define CENTERPRIO_NORMAL 5
625 #define CENTERPRIO_MAPVOTE 9
626 #define CENTERPRIO_IDLEKICK 50
627 #define CENTERPRIO_ADMIN 99
628 .float centerprint_priority;
629 .float centerprint_expires;
630 void centerprint_atprio(entity e, float prio, string s)
631 {
632         if(intermission_running)
633                 if(prio < CENTERPRIO_MAPVOTE)
634                         return;
635         if(time > e.centerprint_expires)
636                 e.centerprint_priority = 0;
637         if(prio >= e.centerprint_priority)
638         {
639                 e.centerprint_priority = prio;
640                 if(timeoutStatus == 2)
641                         e.centerprint_expires = time + (e.cvar_scr_centertime * TIMEOUT_SLOWMO_VALUE);
642                 else
643                         e.centerprint_expires = time + e.cvar_scr_centertime;
644                 centerprint_builtin(e, s);
645         }
646 }
647 void centerprint_expire(entity e, float prio)
648 {
649         if(prio == e.centerprint_priority)
650         {
651                 e.centerprint_priority = 0;
652                 centerprint_builtin(e, "");
653         }
654 }
655 void centerprint(entity e, string s)
656 {
657         centerprint_atprio(e, CENTERPRIO_NORMAL, s);
658 }
659
660 // decolorizes and team colors the player name when needed
661 string playername(entity p)
662 {
663         string t;
664         if(teams_matter && !intermission_running && p.classname == "player")
665         {
666                 t = Team_ColorCode(p.team);
667                 return strcat(t, strdecolorize(p.netname));
668         }
669         else
670                 return p.netname;
671 }
672
673 vector randompos(vector m1, vector m2)
674 {
675         local vector v;
676         m2 = m2 - m1;
677         v_x = m2_x * random() + m1_x;
678         v_y = m2_y * random() + m1_y;
679         v_z = m2_z * random() + m1_z;
680         return  v;
681 };
682
683 // requires that m2>m1 in all coordinates, and that m4>m3
684 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;};
685
686 // requires the same, but is a stronger condition
687 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;};
688
689 float g_pickup_shells;
690 float g_pickup_shells_max;
691 float g_pickup_nails;
692 float g_pickup_nails_max;
693 float g_pickup_rockets;
694 float g_pickup_rockets_max;
695 float g_pickup_cells;
696 float g_pickup_cells_max;
697 float g_pickup_armorsmall;
698 float g_pickup_armorsmall_max;
699 float g_pickup_armormedium;
700 float g_pickup_armormedium_max;
701 float g_pickup_armorlarge;
702 float g_pickup_armorlarge_max;
703 float g_pickup_healthsmall;
704 float g_pickup_healthsmall_max;
705 float g_pickup_healthmedium;
706 float g_pickup_healthmedium_max;
707 float g_pickup_healthlarge;
708 float g_pickup_healthlarge_max;
709 float g_pickup_healthmega;
710 float g_pickup_healthmega_max;
711
712 float start_weapons;
713 float start_items;
714 float start_ammo_shells;
715 float start_ammo_nails;
716 float start_ammo_rockets;
717 float start_ammo_cells;
718 float start_health;
719 float start_armorvalue;
720 float warmup_start_weapons;
721 float warmup_start_ammo_shells;
722 float warmup_start_ammo_nails;
723 float warmup_start_ammo_rockets;
724 float warmup_start_ammo_cells;
725 float warmup_start_health;
726 float warmup_start_armorvalue;
727
728 entity get_weaponinfo(float w);
729
730 void readplayerstartcvars() 
731 {
732         entity e;
733         float i;
734
735         // initialize starting values for players
736         start_weapons = 0;
737         start_items = 0;
738         start_ammo_shells = 0;
739         start_ammo_nails = 0;
740         start_ammo_rockets = 0;
741         start_ammo_cells = 0;
742         start_health = cvar("g_balance_health_start");
743         start_armorvalue = cvar("g_balance_armor_start");
744
745         if(g_rocketarena)
746         {
747                 start_weapons = WEPBIT_ROCKET_LAUNCHER;
748                 weapon_action(WEP_ROCKET_LAUNCHER, WR_PRECACHE);
749                 start_ammo_rockets = 999;
750                 start_items |= IT_UNLIMITED_AMMO;
751         }
752         else if(g_nixnex)
753         {
754                 start_weapons = 0;
755                 // will be done later
756         }
757         else if(g_minstagib)
758         {
759                 start_health = 100;
760                 start_armorvalue = 0;
761                 start_weapons = WEPBIT_MINSTANEX;
762                 weapon_action(WEP_MINSTANEX, WR_PRECACHE);
763                 start_ammo_cells = cvar("g_minstagib_ammo_start");
764                 g_minstagib_invis_alpha = cvar("g_minstagib_invis_alpha");
765         }
766         else
767         {
768                 if(g_lms)
769                 {
770                         start_ammo_shells = cvar("g_lms_start_ammo_shells");
771                         start_ammo_nails = cvar("g_lms_start_ammo_nails");
772                         start_ammo_rockets = cvar("g_lms_start_ammo_rockets");
773                         start_ammo_cells = cvar("g_lms_start_ammo_cells");
774                         start_health = cvar("g_lms_start_health");
775                         start_armorvalue = cvar("g_lms_start_armor");
776                 } else if (cvar("g_use_ammunition")) {
777                         start_ammo_shells = cvar("g_start_ammo_shells");
778                         start_ammo_nails = cvar("g_start_ammo_nails");
779                         start_ammo_rockets = cvar("g_start_ammo_rockets");
780                         start_ammo_cells = cvar("g_start_ammo_cells");
781                 } else {
782                         start_ammo_shells = cvar("g_pickup_shells_max");
783                         start_ammo_nails = cvar("g_pickup_nails_max");
784                         start_ammo_rockets = cvar("g_pickup_rockets_max");
785                         start_ammo_cells = cvar("g_pickup_cells_max");
786                         start_items |= IT_UNLIMITED_AMMO;
787                 }
788
789                 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
790                 {
791                         e = get_weaponinfo(i);
792                         if(!(e.weapon))
793                                 continue;
794                         if(((e.spawnflags & 1) && g_lms) || cvar(strcat("g_start_weapon_", e.netname)))
795                         {
796                                 start_weapons |= e.weapons;
797                                 weapon_action(e.weapon, WR_PRECACHE);
798                         }
799                 }
800         }
801
802         if(inWarmupStage)
803         {
804                 warmup_start_ammo_shells = start_ammo_shells;
805                 warmup_start_ammo_nails = start_ammo_nails;
806                 warmup_start_ammo_rockets = start_ammo_rockets;
807                 warmup_start_ammo_cells = start_ammo_cells;
808                 warmup_start_health = start_health;
809                 warmup_start_armorvalue = start_armorvalue;
810                 warmup_start_weapons = start_weapons;
811
812                 if(!g_rocketarena && !g_nixnex && !g_minstagib)
813                 {
814                         if(cvar("g_use_ammunition"))
815                         {
816                                 warmup_start_ammo_shells = cvar("g_warmup_start_ammo_shells");
817                                 warmup_start_ammo_cells = cvar("g_warmup_start_ammo_cells");
818                                 warmup_start_ammo_nails = cvar("g_warmup_start_ammo_nails");
819                                 warmup_start_ammo_rockets = cvar("g_warmup_start_ammo_rockets");
820                         }
821                         warmup_start_health = cvar("g_warmup_start_health");
822                         warmup_start_armorvalue = cvar("g_warmup_start_armor");
823                         if(cvar("g_warmup_allguns"))
824                         {
825                                 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
826                                 {
827                                         e = get_weaponinfo(i);
828                                         if(!(e.weapon))
829                                                 continue;
830                                         if(e.spawnflags & 1)
831                                         {
832                                                 warmup_start_weapons |= e.weapons;
833                                                 weapon_action(e.weapon, WR_PRECACHE);
834                                         }
835                                 }
836                         }
837                 }
838         }
839 }
840
841 void readlevelcvars(void)
842 {
843         sv_cheats = cvar("sv_cheats");
844         sv_gentle = cvar("sv_gentle");
845         sv_foginterval = cvar("sv_foginterval");
846         g_cloaked = cvar("g_cloaked");
847         g_jump_grunt = cvar("g_jump_grunt");
848         g_footsteps = cvar("g_footsteps");
849         g_grappling_hook = cvar("g_grappling_hook");
850         g_laserguided_missile = cvar("g_laserguided_missile");
851         g_midair = cvar("g_midair");
852         g_minstagib = cvar("g_minstagib");
853         g_nixnex = cvar("g_nixnex");
854         g_nixnex_with_laser = cvar("g_nixnex_with_laser");
855         g_norecoil = cvar("g_norecoil");
856         g_rocketarena = cvar("g_rocketarena");
857         g_vampire = cvar("g_vampire");
858         sv_maxidle = cvar("sv_maxidle");
859         sv_maxidle_spectatorsareidle = cvar("sv_maxidle_spectatorsareidle");
860         sv_pogostick = cvar("sv_pogostick");
861         sv_doublejump = cvar("sv_doublejump");
862
863         inWarmupStage = cvar("g_warmup");
864         g_warmup_limit = cvar("g_warmup_limit");
865         g_warmup_allguns = cvar("g_warmup_allguns");
866         g_warmup_allow_timeout = cvar("g_warmup_allow_timeout");
867
868         if(g_race && g_race_qualifying == 2 || g_arena || g_assault || cvar("g_campaign"))
869                 inWarmupStage = 0; // these modes cannot work together, sorry
870
871         g_pickup_respawntime_short = cvar("g_pickup_respawntime_short");
872         g_pickup_respawntime_medium = cvar("g_pickup_respawntime_medium");
873         g_pickup_respawntime_long = cvar("g_pickup_respawntime_long");
874         g_pickup_respawntime_powerup = cvar("g_pickup_respawntime_powerup");
875
876         if(g_minstagib) g_nixnex = g_rocketarena = 0;
877         if(g_nixnex) g_rocketarena = 0;
878
879         g_pickup_shells                    = cvar("g_pickup_shells");
880         g_pickup_shells_max                = cvar("g_pickup_shells_max");
881         g_pickup_nails                     = cvar("g_pickup_nails");
882         g_pickup_nails_max                 = cvar("g_pickup_nails_max");
883         g_pickup_rockets                   = cvar("g_pickup_rockets");
884         g_pickup_rockets_max               = cvar("g_pickup_rockets_max");
885         g_pickup_cells                     = cvar("g_pickup_cells");
886         g_pickup_cells_max                 = cvar("g_pickup_cells_max");
887         g_pickup_armorsmall                = cvar("g_pickup_armorsmall");
888         g_pickup_armorsmall_max            = cvar("g_pickup_armorsmall_max");
889         g_pickup_armormedium               = cvar("g_pickup_armormedium");
890         g_pickup_armormedium_max           = cvar("g_pickup_armormedium_max");
891         g_pickup_armorlarge                = cvar("g_pickup_armorlarge");
892         g_pickup_armorlarge_max            = cvar("g_pickup_armorlarge_max");
893         g_pickup_healthsmall               = cvar("g_pickup_healthsmall");
894         g_pickup_healthsmall_max           = cvar("g_pickup_healthsmall_max");
895         g_pickup_healthmedium              = cvar("g_pickup_healthmedium");
896         g_pickup_healthmedium_max          = cvar("g_pickup_healthmedium_max");
897         g_pickup_healthlarge               = cvar("g_pickup_healthlarge");
898         g_pickup_healthlarge_max           = cvar("g_pickup_healthlarge_max");
899         g_pickup_healthmega                = cvar("g_pickup_healthmega");
900         g_pickup_healthmega_max            = cvar("g_pickup_healthmega_max");
901
902         readplayerstartcvars();
903 }
904
905 /*
906 // TODO sound pack system
907 string soundpack;
908
909 string precache_sound_builtin (string s) = #19;
910 void(entity e, float chan, string samp, float vol, float atten) sound_builtin = #8;
911 string precache_sound(string s)
912 {
913         return precache_sound_builtin(strcat(soundpack, s));
914 }
915 void play2(entity e, string filename)
916 {
917         stuffcmd(e, strcat("play2 ", soundpack, filename, "\n"));
918 }
919 void sound(entity e, float chan, string samp, float vol, float atten)
920 {
921         sound_builtin(e, chan, strcat(soundpack, samp), vol, atten);
922 }
923 */
924
925 // Sound functions
926 string precache_sound (string s) = #19;
927 void(entity e, float chan, string samp, float vol, float atten) sound = #8;
928 float precache_sound_index (string s) = #19;
929
930 void soundtoat(float dest, entity e, vector o, float chan, string samp, float vol, float atten)
931 {
932         WriteByte(dest, 6);
933         WriteByte(dest, 27); // all bits except SND_LOOPING
934         WriteByte(dest, vol * 255);
935         WriteByte(dest, atten * 64);
936         WriteEntity(dest, e);
937         WriteByte(dest, chan);
938         WriteShort(dest, precache_sound_index(samp));
939         WriteCoord(dest, o_x);
940         WriteCoord(dest, o_y);
941         WriteCoord(dest, o_z);
942 }
943 void soundto(float dest, entity e, float chan, string samp, float vol, float atten)
944 {
945         vector o;
946         o = e.origin + 0.5 * (e.mins + e.maxs);
947         soundtoat(dest, e, o, chan, samp, vol, atten);
948 }
949 void soundat(entity e, vector o, float chan, string samp, float vol, float atten)
950 {
951         soundtoat(MSG_BROADCAST, e, o, chan, samp, vol, atten);
952 }
953
954 void play2(entity e, string filename)
955 {
956         //stuffcmd(e, strcat("play2 ", filename, "\n"));
957         msg_entity = e;
958         soundtoat(MSG_ONE, world, '0 0 0', CHAN_AUTO, filename, VOL_BASE, ATTN_NONE);
959 }
960
961 .float announcetime;
962 void announce(entity player, string msg)
963 {
964         if(time > player.announcetime)
965         if(clienttype(player) == CLIENTTYPE_REAL)
966         {
967                 player.announcetime = time + 0.3;
968                 play2(player, msg);
969         }
970 }
971
972 void play2team(float t, string filename)
973 {
974         local entity head;
975         FOR_EACH_REALPLAYER(head)
976         {
977                 if (head.team == t)
978                         play2(head, filename);
979         }
980 }
981
982 void play2all(string samp)
983 {
984         sound(world, CHAN_AUTO, samp, VOL_BASE, ATTN_NONE);
985 }
986
987 void PrecachePlayerSounds(string f);
988 void precache_all_models(string pattern)
989 {
990         float globhandle, i, n;
991         string f;
992
993         globhandle = search_begin(pattern, TRUE, FALSE);
994         if(globhandle < 0)
995                 return;
996         n = search_getsize(globhandle);
997         for(i = 0; i < n; ++i)
998         {
999                 //print(search_getfilename(globhandle, i), "\n");
1000                 f = search_getfilename(globhandle, i);
1001                 precache_model(f);
1002                 PrecachePlayerSounds(strcat(f, ".sounds"));
1003         }
1004         search_end(globhandle);
1005 }
1006
1007 void precache()
1008 {
1009         // gamemode related things
1010         precache_model ("models/misc/chatbubble.spr");
1011         precache_model ("models/misc/teambubble.spr");
1012         if (g_runematch)
1013         {
1014                 precache_model ("models/runematch/curse.mdl");
1015                 precache_model ("models/runematch/rune.mdl");
1016         }
1017
1018         // Precache all player models if desired
1019         if (cvar("sv_precacheplayermodels"))
1020         {
1021                 PrecachePlayerSounds("sound/player/default.sounds");
1022                 precache_all_models("models/player/*.zym");
1023                 precache_all_models("models/player/*.dpm");
1024                 precache_all_models("models/player/*.md3");
1025                 precache_all_models("models/player/*.psk");
1026                 //precache_model("models/player/carni.zym");
1027                 //precache_model("models/player/crash.zym");
1028                 //precache_model("models/player/grunt.zym");
1029                 //precache_model("models/player/headhunter.zym");
1030                 //precache_model("models/player/insurrectionist.zym");
1031                 //precache_model("models/player/jeandarc.zym");
1032                 //precache_model("models/player/lurk.zym");
1033                 //precache_model("models/player/lycanthrope.zym");
1034                 //precache_model("models/player/marine.zym");
1035                 //precache_model("models/player/nexus.zym");
1036                 //precache_model("models/player/pyria.zym");
1037                 //precache_model("models/player/shock.zym");
1038                 //precache_model("models/player/skadi.zym");
1039                 //precache_model("models/player/specop.zym");
1040                 //precache_model("models/player/visitant.zym");
1041         }
1042
1043         if (g_footsteps)
1044         {
1045                 PrecacheGlobalSound((globalsound_step = "misc/footstep0 6"));
1046                 PrecacheGlobalSound((globalsound_metalstep = "misc/metalfootstep0 6"));
1047         }
1048
1049         // gore and miscellaneous sounds
1050         //precache_sound ("misc/h2ohit.wav");
1051         precache_model ("models/gibs/bloodyskull.md3");
1052         precache_model ("models/gibs/chunk.mdl");
1053         precache_model ("models/gibs/eye.md3");
1054         precache_model ("models/gibs/gib1.md3");
1055         precache_model ("models/gibs/gib2.md3");
1056         precache_model ("models/gibs/gib3.md3");
1057         precache_model ("models/gibs/gib4.md3");
1058         precache_model ("models/gibs/gib5.md3");
1059         precache_model ("models/gibs/gib6.md3");
1060         precache_model ("models/gibs/smallchest.md3");
1061         precache_model ("models/gibs/chest.md3");
1062         precache_model ("models/gibs/arm.md3");
1063         precache_model ("models/gibs/leg1.md3");
1064         precache_model ("models/gibs/leg2.md3");
1065         precache_model ("models/hook.md3");
1066         precache_sound ("misc/armorimpact.wav");
1067         precache_sound ("misc/bodyimpact1.wav");
1068         precache_sound ("misc/bodyimpact2.wav");
1069         precache_sound ("misc/gib.wav");
1070         precache_sound ("misc/gib_splat01.wav");
1071         precache_sound ("misc/gib_splat02.wav");
1072         precache_sound ("misc/gib_splat03.wav");
1073         precache_sound ("misc/gib_splat04.wav");
1074         precache_sound ("misc/hit.wav");
1075         PrecacheGlobalSound((globalsound_fall = "misc/hitground 4"));
1076         PrecacheGlobalSound((globalsound_metalfall = "misc/metalhitground 4"));
1077         precache_sound ("misc/null.wav");
1078         precache_sound ("misc/spawn.wav");
1079         precache_sound ("misc/talk.wav");
1080         precache_sound ("misc/teleport.wav");
1081         precache_sound ("player/lava.wav");
1082         precache_sound ("player/slime.wav");
1083
1084         // announcer sounds - male
1085         //precache_sound ("announcer/male/electrobitch.wav");
1086         precache_sound ("announcer/male/03kills.wav");
1087         precache_sound ("announcer/male/05kills.wav");
1088         precache_sound ("announcer/male/10kills.wav");
1089         precache_sound ("announcer/male/15kills.wav");
1090         precache_sound ("announcer/male/20kills.wav");
1091         precache_sound ("announcer/male/25kills.wav");
1092         precache_sound ("announcer/male/30kills.wav");
1093         precache_sound ("announcer/male/botlike.wav");
1094         precache_sound ("announcer/male/yoda.wav");
1095
1096         // announcer sounds - robotic
1097         precache_sound ("announcer/robotic/prepareforbattle.wav");
1098         precache_sound ("announcer/robotic/begin.wav");
1099         precache_sound ("announcer/robotic/timeoutcalled.wav");
1100         precache_sound ("announcer/robotic/1fragleft.wav");
1101         precache_sound ("announcer/robotic/1minuteremains.wav");
1102         precache_sound ("announcer/robotic/2fragsleft.wav");
1103         precache_sound ("announcer/robotic/3fragsleft.wav");
1104         if (g_minstagib)
1105         {
1106                 precache_sound ("announcer/robotic/lastsecond.wav");
1107                 precache_sound ("announcer/robotic/narrowly.wav");
1108         }
1109
1110         precache_model ("models/sprites/1.spr32");
1111         precache_model ("models/sprites/2.spr32");
1112         precache_model ("models/sprites/3.spr32");
1113         precache_model ("models/sprites/4.spr32");
1114         precache_model ("models/sprites/5.spr32");
1115         precache_model ("models/sprites/6.spr32");
1116         precache_model ("models/sprites/7.spr32");
1117         precache_model ("models/sprites/8.spr32");
1118         precache_model ("models/sprites/9.spr32");
1119         precache_model ("models/sprites/10.spr32");
1120         precache_sound ("announcer/robotic/1.ogg");
1121         precache_sound ("announcer/robotic/2.ogg");
1122         precache_sound ("announcer/robotic/3.ogg");
1123         precache_sound ("announcer/robotic/4.ogg");
1124         precache_sound ("announcer/robotic/5.ogg");
1125         precache_sound ("announcer/robotic/6.ogg");
1126         precache_sound ("announcer/robotic/7.ogg");
1127         precache_sound ("announcer/robotic/8.ogg");
1128         precache_sound ("announcer/robotic/9.ogg");
1129         precache_sound ("announcer/robotic/10.ogg");
1130
1131         // common weapon precaches
1132         precache_sound ("weapons/weapon_switch.wav");
1133         precache_sound ("weapons/weaponpickup.wav");
1134         if (cvar("g_grappling_hook"))
1135         {
1136                 precache_sound ("weapons/hook_fire.wav"); // hook
1137                 precache_sound ("weapons/hook_impact.wav"); // hook
1138         }
1139
1140         if (cvar("sv_precacheweapons") || g_nixnex)
1141         {
1142                 //precache weapon models/sounds
1143                 local float wep;
1144                 wep = WEP_FIRST;
1145                 while (wep <= WEP_LAST)
1146                 {
1147                         weapon_action(wep, WR_PRECACHE);
1148                         wep = wep + 1;
1149                 }
1150         }
1151
1152         // plays music for the level if there is any
1153         if (self.noise)
1154         {
1155                 precache_sound (self.noise);
1156                 ambientsound ('0 0 0', self.noise, VOL_BASE, ATTN_NONE);
1157         }
1158 }
1159
1160 // sorry, but using \ in macros breaks line numbers
1161 #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
1162 #define WRITESPECTATABLE_MSG_ONE(statement) WRITESPECTATABLE_MSG_ONE_VARNAME(oldmsg_entity, statement)
1163 #define WRITESPECTATABLE(msg,statement) if(msg == MSG_ONE) { WRITESPECTATABLE_MSG_ONE(statement); } else statement float WRITESPECTATABLE_workaround = 0
1164
1165 vector ExactTriggerHit_mins;
1166 vector ExactTriggerHit_maxs;
1167 float ExactTriggerHit_Recurse()
1168 {
1169         float s;
1170         entity se;
1171         float f;
1172
1173         tracebox('0 0 0', ExactTriggerHit_mins, ExactTriggerHit_maxs, '0 0 0', MOVE_NORMAL, other);
1174         if not(trace_ent)
1175                 return 0;
1176         if(trace_ent == self)
1177                 return 1;
1178
1179         se = trace_ent;
1180         s = se.solid;
1181         se.solid = SOLID_NOT;
1182         f = ExactTriggerHit_Recurse();
1183         se.solid = s;
1184
1185         return f;
1186 }
1187
1188 float ExactTriggerHit()
1189 {
1190         float f, s;
1191
1192         if not(self.modelindex)
1193                 return 1;
1194
1195         s = self.solid;
1196         self.solid = SOLID_BSP;
1197         ExactTriggerHit_mins = other.absmin;
1198         ExactTriggerHit_maxs = other.absmax;
1199         f = ExactTriggerHit_Recurse();
1200         self.solid = s;
1201
1202         return f;
1203 }
1204
1205 // WARNING: this kills the trace globals
1206 #define EXACTTRIGGER_TOUCH if not(ExactTriggerHit()) return
1207 #define EXACTTRIGGER_INIT  InitSolidBSPTrigger(); self.solid = SOLID_TRIGGER
1208
1209 #define INITPRIO_FIRST              0
1210 #define INITPRIO_GAMETYPE           0
1211 #define INITPRIO_GAMETYPE_FALLBACK  1
1212 #define INITPRIO_CVARS              5
1213 #define INITPRIO_FINDTARGET        10
1214 #define INITPRIO_SETLOCATION       90
1215 #define INITPRIO_LINKDOORS         91
1216 #define INITPRIO_LAST              99
1217
1218 .void(void) initialize_entity;
1219 .float initialize_entity_order;
1220 .entity initialize_entity_next;
1221 entity initialize_entity_first;
1222 void InitializeEntity(entity e, void(void) func, float order)
1223 {
1224         entity prev, cur;
1225
1226         if(!e || e.initialize_entity)
1227         {
1228                 // make a proxy initializer entity
1229                 entity e_old;
1230                 e_old = e;
1231                 e = spawn();
1232                 e.classname = "initialize_entity";
1233                 e.enemy = e_old;
1234         }
1235
1236         e.initialize_entity = func;
1237         e.initialize_entity_order = order;
1238
1239         cur = initialize_entity_first;
1240         for(;;)
1241         {
1242                 if(!cur || cur.initialize_entity_order > order)
1243                 {
1244                         // insert between prev and cur
1245                         if(prev)
1246                                 prev.initialize_entity_next = e;
1247                         else
1248                                 initialize_entity_first = e;
1249                         e.initialize_entity_next = cur;
1250                         return;
1251                 }
1252                 prev = cur;
1253                 cur = cur.initialize_entity_next;
1254         }
1255 }
1256 void InitializeEntitiesRun()
1257 {
1258         for(self = initialize_entity_first; self; )
1259         {
1260                 entity e;
1261                 var void(void) func;
1262                 e = self.initialize_entity_next;
1263                 func = self.initialize_entity;
1264                 self.initialize_entity_order = 0;
1265                 self.initialize_entity = func_null;
1266                 self.initialize_entity_next = world;
1267                 if(self.classname == "initialize_entity")
1268                 {
1269                         entity e_old;
1270                         e_old = self.enemy;
1271                         remove(self);
1272                         self = e_old;
1273                 }
1274                 dprint("Delayed initialization: ", self.classname, "\n");
1275                 func();
1276                 self = e;
1277         }
1278         initialize_entity_first = world;
1279 }
1280
1281 .float uncustomizeentityforclient_set;
1282 .void(void) uncustomizeentityforclient;
1283 void(void) SUB_Nullpointer = #0;
1284 void UncustomizeEntitiesRun()
1285 {
1286         entity oldself;
1287         oldself = self;
1288         for(self = world; (self = findfloat(self, uncustomizeentityforclient_set, 1)); )
1289                 self.uncustomizeentityforclient();
1290         self = oldself;
1291 }
1292 void SetCustomizer(entity e, float(void) customizer, void(void) uncustomizer)
1293 {
1294         e.customizeentityforclient = customizer;
1295         e.uncustomizeentityforclient = uncustomizer;
1296         e.uncustomizeentityforclient_set = (uncustomizer != SUB_Nullpointer);
1297 }
1298
1299 .float nottargeted;
1300 #define IFTARGETED if(!self.nottargeted && self.targetname != "")
1301
1302 float power2of(float e)
1303 {
1304         return pow(2, e);
1305 }
1306 float log2of(float x)
1307 {
1308         // NOTE: generated code
1309         if(x > 2048)
1310                 if(x > 131072)
1311                         if(x > 1048576)
1312                                 if(x > 4194304)
1313                                         return 23;
1314                                 else
1315                                         if(x > 2097152)
1316                                                 return 22;
1317                                         else
1318                                                 return 21;
1319                         else
1320                                 if(x > 524288)
1321                                         return 20;
1322                                 else
1323                                         if(x > 262144)
1324                                                 return 19;
1325                                         else
1326                                                 return 18;
1327                 else
1328                         if(x > 16384)
1329                                 if(x > 65536)
1330                                         return 17;
1331                                 else
1332                                         if(x > 32768)
1333                                                 return 16;
1334                                         else
1335                                                 return 15;
1336                         else
1337                                 if(x > 8192)
1338                                         return 14;
1339                                 else
1340                                         if(x > 4096)
1341                                                 return 13;
1342                                         else
1343                                                 return 12;
1344         else
1345                 if(x > 32)
1346                         if(x > 256)
1347                                 if(x > 1024)
1348                                         return 11;
1349                                 else
1350                                         if(x > 512)
1351                                                 return 10;
1352                                         else
1353                                                 return 9;
1354                         else
1355                                 if(x > 128)
1356                                         return 8;
1357                                 else
1358                                         if(x > 64)
1359                                                 return 7;
1360                                         else
1361                                                 return 6;
1362                 else
1363                         if(x > 4)
1364                                 if(x > 16)
1365                                         return 5;
1366                                 else
1367                                         if(x > 8)
1368                                                 return 4;
1369                                         else
1370                                                 return 3;
1371                         else
1372                                 if(x > 2)
1373                                         return 2;
1374                                 else
1375                                         if(x > 1)
1376                                                 return 1;
1377                                         else
1378                                                 return 0;
1379 }
1380
1381 //
1382 // func_breakable 
1383 // - basically func_assault_destructible for general gameplay use
1384 //
1385 float () crandom;
1386 void () SUB_UseTargets, assault_destructible_use, SUB_Remove, SUB_Null;
1387 void LaunchDebris (string debrisname) =
1388 {
1389         local   entity dbr;
1390         
1391         if (debrisname == "" || !debrisname)
1392                 return;
1393         
1394         dbr = spawn();
1395         dbr.origin = self.origin;
1396         setmodel (dbr, debrisname );
1397         setsize (dbr, '0 0 0', '0 0 0');
1398         dbr.velocity_x = 70 * crandom();
1399         dbr.velocity_y = 70 * crandom();
1400         dbr.velocity_z = 140 + 70 * random();
1401         dbr.movetype = MOVETYPE_BOUNCE;
1402         dbr.solid = SOLID_BBOX;
1403         dbr.avelocity_x = random()*600;
1404         dbr.avelocity_y = random()*600;
1405         dbr.avelocity_z = random()*600;
1406         dbr.think = SUB_Remove;
1407         dbr.nextthink = time + 13 + random()*10;
1408 };
1409
1410 .string debris1, debris2, debris3;
1411 .string mdl_dead;
1412 void func_breakable_destroy() {
1413         if (self.mdl_dead)
1414                 setmodel(self, self.mdl_dead);
1415         else {
1416                 self.model = "";
1417                 self.solid = SOLID_NOT;
1418         }
1419         self.takedamage = DAMAGE_NO;
1420         
1421         // now throw around the debris
1422         LaunchDebris(self.debris1);
1423         LaunchDebris(self.debris2);
1424         LaunchDebris(self.debris3);
1425         
1426         SUB_UseTargets();
1427         
1428         self.event_damage = SUB_Null;
1429 }
1430
1431 void func_breakable_damage(entity inflictor, entity attacker, float damage, float deathtype, vector hitloc, vector force) {
1432
1433         if(self.cnt > 0) {
1434                 self.health = self.health - damage;
1435                 // add pain effects?
1436         }
1437
1438         if(self.health < 0) {
1439                 activator = attacker;
1440                 func_breakable_destroy();
1441         }
1442 }
1443
1444 // destructible walls that can be used to trigger target_objective_decrease
1445 void spawnfunc_func_breakable() {
1446         if(!self.health)
1447                 self.health = 100;
1448
1449         self.max_health = self.health;
1450
1451         //self.cnt = 0; // not yet activated
1452
1453
1454
1455         self.classname = "func_breakable";      
1456         self.mdl = self.model;
1457         setmodel(self, self.mdl);
1458         
1459         self.solid = SOLID_BSP;
1460         
1461         // precache all the models
1462         if (self.mdl_dead)
1463                 precache_model(self.mdl_dead);
1464         if (self.debris1)
1465                 precache_model(self.debris1);
1466         if (self.debris2)
1467                 precache_model(self.debris2);
1468         if (self.debris3)
1469                 precache_model(self.debris3);
1470         
1471         self.use = assault_destructible_use;    // shared use function, b/c they woudl do the same thing anyways
1472         self.event_damage = func_breakable_damage;
1473 }
1474
1475 void Net_LinkEntity(entity e)
1476 {
1477         e.model = "net_entity";
1478         e.modelindex = 1;
1479         e.effects = EF_NODEPTHTEST | EF_LOWPRECISION;
1480 }
1481