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