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