]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/common/util.qc
Merge branch 'master' into terencehill/ft_autorevive_progress
[xonotic/xonotic-data.pk3dir.git] / qcsrc / common / util.qc
1 #include "util.qh"
2
3 #if defined(CSQC)
4     #include "constants.qh"
5         #include <client/mutators/_mod.qh>
6     #include "mapinfo.qh"
7     #include "notifications/all.qh"
8         #include "scores.qh"
9     #include <common/deathtypes/all.qh>
10         #include <common/gamemodes/_mod.qh>
11 #elif defined(MENUQC)
12 #elif defined(SVQC)
13     #include "constants.qh"
14         #include <server/mutators/_mod.qh>
15     #include "notifications/all.qh"
16     #include <common/deathtypes/all.qh>
17         #include <common/gamemodes/_mod.qh>
18         #include "scores.qh"
19     #include "mapinfo.qh"
20 #endif
21
22 #ifdef SVQC
23 float tracebox_inverted (vector v1, vector mi, vector ma, vector v2, float nomonsters, entity forent, float stopatentity, entity ignorestopatentity) // returns the number of traces done, for benchmarking
24 {
25         vector pos, dir, t;
26         float nudge;
27         entity stopentity;
28
29         //nudge = 2 * cvar("collision_impactnudge"); // why not?
30         nudge = 0.5;
31
32         dir = normalize(v2 - v1);
33
34         pos = v1 + dir * nudge;
35
36         float c;
37         c = 0;
38
39         for (;;)
40         {
41                 if(pos * dir >= v2 * dir)
42                 {
43                         // went too far
44                         trace_fraction = 1;
45                         trace_endpos = v2;
46                         return c;
47                 }
48
49                 tracebox(pos, mi, ma, v2, nomonsters, forent);
50                 ++c;
51
52                 if(c == 50)
53                 {
54                         LOG_TRACE("When tracing from ", vtos(v1), " to ", vtos(v2));
55                         LOG_TRACE("  Nudging gets us nowhere at ", vtos(pos));
56                         LOG_TRACE("  trace_endpos is ", vtos(trace_endpos));
57                         LOG_TRACE("  trace distance is ", ftos(vlen(pos - trace_endpos)));
58                 }
59
60                 stopentity = trace_ent;
61
62                 if(trace_startsolid)
63                 {
64                         // we started inside solid.
65                         // then trace from endpos to pos
66                         t = trace_endpos;
67                         tracebox(t, mi, ma, pos, nomonsters, forent);
68                         ++c;
69                         if(trace_startsolid)
70                         {
71                                 // t is still inside solid? bad
72                                 // force advance, then, and retry
73                                 pos = t + dir * nudge;
74
75                                 // but if we hit an entity, stop RIGHT before it
76                                 if(stopatentity && stopentity && stopentity != ignorestopatentity)
77                                 {
78                                         trace_ent = stopentity;
79                                         trace_endpos = t;
80                                         trace_fraction = ((trace_endpos - v1) * dir) / ((v2 - v1) * dir);
81                                         return c;
82                                 }
83                         }
84                         else
85                         {
86                                 // we actually LEFT solid!
87                                 trace_fraction = ((trace_endpos - v1) * dir) / ((v2 - v1) * dir);
88                                 return c;
89                         }
90                 }
91                 else
92                 {
93                         // pos is outside solid?!? but why?!? never mind, just return it.
94                         trace_endpos = pos;
95                         trace_fraction = ((trace_endpos - v1) * dir) / ((v2 - v1) * dir);
96                         return c;
97                 }
98         }
99 }
100
101 void traceline_inverted (vector v1, vector v2, float nomonsters, entity forent, float stopatentity, entity ignorestopatentity)
102 {
103         tracebox_inverted(v1, '0 0 0', '0 0 0', v2, nomonsters, forent, stopatentity, ignorestopatentity);
104 }
105 #endif
106
107 #ifdef GAMEQC
108 /*
109 ==================
110 findbetterlocation
111
112 Returns a point at least 12 units away from walls
113 (useful for explosion animations, although the blast is performed where it really happened)
114 Ripped from DPMod
115 ==================
116 */
117 vector findbetterlocation (vector org, float mindist)
118 {
119         vector vec = mindist * '1 0 0';
120         int c = 0;
121         while (c < 6)
122         {
123                 traceline (org, org + vec, true, NULL);
124                 vec = vec * -1;
125                 if (trace_fraction < 1)
126                 {
127                         vector loc = trace_endpos;
128                         traceline (loc, loc + vec, true, NULL);
129                         if (trace_fraction >= 1)
130                                 org = loc + vec;
131                 }
132                 if (c & 1)
133                 {
134                         float h = vec.y;
135                         vec.y = vec.x;
136                         vec.x = vec.z;
137                         vec.z = h;
138                 }
139                 c = c + 1;
140         }
141
142         return org;
143 }
144
145 /*
146 * Get "real" origin, in worldspace, even if ent is attached to something else.
147 */
148 vector real_origin(entity ent)
149 {
150         vector v = ((ent.absmin + ent.absmax) * 0.5);
151         entity e = ent.tag_entity;
152
153         while(e)
154         {
155                 v = v + ((e.absmin + e.absmax) * 0.5);
156                 e = e.tag_entity;
157         }
158
159         return v;
160 }
161 #endif
162
163 string wordwrap_buffer;
164
165 void wordwrap_buffer_put(string s)
166 {
167         wordwrap_buffer = strcat(wordwrap_buffer, s);
168 }
169
170 string wordwrap(string s, float l)
171 {
172         string r;
173         wordwrap_buffer = "";
174         wordwrap_cb(s, l, wordwrap_buffer_put);
175         r = wordwrap_buffer;
176         wordwrap_buffer = "";
177         return r;
178 }
179
180 #ifdef SVQC
181 entity _wordwrap_buffer_sprint_ent;
182 void wordwrap_buffer_sprint(string s)
183 {
184         wordwrap_buffer = strcat(wordwrap_buffer, s);
185         if(s == "\n")
186         {
187                 sprint(_wordwrap_buffer_sprint_ent, wordwrap_buffer);
188                 wordwrap_buffer = "";
189         }
190 }
191
192 void wordwrap_sprint(entity to, string s, float l)
193 {
194         wordwrap_buffer = "";
195         _wordwrap_buffer_sprint_ent = to;
196         wordwrap_cb(s, l, wordwrap_buffer_sprint);
197         _wordwrap_buffer_sprint_ent = NULL;
198         if(wordwrap_buffer != "")
199                 sprint(to, strcat(wordwrap_buffer, "\n"));
200         wordwrap_buffer = "";
201         return;
202 }
203 #endif
204
205 #ifndef SVQC
206 string draw_UseSkinFor(string pic)
207 {
208         if(substring(pic, 0, 1) == "/")
209                 return substring(pic, 1, strlen(pic)-1);
210         else
211                 return strcat(draw_currentSkin, "/", pic);
212 }
213 #endif
214
215 void wordwrap_cb(string s, float l, void(string) callback)
216 {
217         string c;
218         float lleft, i, j, wlen;
219
220         s = strzone(s);
221         lleft = l;
222         int len = strlen(s);
223         for (i = 0; i < len; ++i)
224         {
225                 if (substring(s, i, 2) == "\\n")
226                 {
227                         callback("\n");
228                         lleft = l;
229                         ++i;
230                 }
231                 else if (substring(s, i, 1) == "\n")
232                 {
233                         callback("\n");
234                         lleft = l;
235                 }
236                 else if (substring(s, i, 1) == " ")
237                 {
238                         if (lleft > 0)
239                         {
240                                 callback(" ");
241                                 --lleft;
242                         }
243                 }
244                 else
245                 {
246                         for (j = i+1; j < len; ++j)
247                                 //    ^^ this skips over the first character of a word, which
248                                 //       is ALWAYS part of the word
249                                 //       this is safe since if i+1 == strlen(s), i will become
250                                 //       strlen(s)-1 at the end of this block and the function
251                                 //       will terminate. A space can't be the first character we
252                                 //       read here, and neither can a \n be the start, since these
253                                 //       two cases have been handled above.
254                         {
255                                 c = substring(s, j, 1);
256                                 if (c == " ")
257                                         break;
258                                 if (c == "\\")
259                                         break;
260                                 if (c == "\n")
261                                         break;
262                                 // we need to keep this tempstring alive even if substring is
263                                 // called repeatedly, so call strcat even though we're not
264                                 // doing anything
265                                 callback("");
266                         }
267                         wlen = j - i;
268                         if (lleft < wlen)
269                         {
270                                 callback("\n");
271                                 lleft = l;
272                         }
273                         callback(substring(s, i, wlen));
274                         lleft -= wlen;
275                         i = j - 1;
276                 }
277         }
278         strunzone(s);
279 }
280
281 void depthfirst(entity start, .entity up, .entity downleft, .entity right, void(entity, entity) funcPre, void(entity, entity) funcPost, entity pass)
282 {
283         entity e;
284         e = start;
285         funcPre(pass, e);
286         while (e.(downleft))
287         {
288                 e = e.(downleft);
289                 funcPre(pass, e);
290         }
291         funcPost(pass, e);
292         while(e != start)
293         {
294                 if (e.(right))
295                 {
296                         e = e.(right);
297                         funcPre(pass, e);
298                         while (e.(downleft))
299                         {
300                                 e = e.(downleft);
301                                 funcPre(pass, e);
302                         }
303                 }
304                 else
305                         e = e.(up);
306                 funcPost(pass, e);
307         }
308 }
309
310 #ifdef GAMEQC
311 string ScoreString(int pFlags, float pValue)
312 {
313         string valstr;
314         float l;
315
316         pValue = floor(pValue + 0.5); // round
317
318         if((pValue == 0) && (pFlags & (SFL_HIDE_ZERO | SFL_RANK | SFL_TIME)))
319                 valstr = "";
320         else if(pFlags & SFL_RANK)
321                 valstr = count_ordinal(pValue);
322         else if(pFlags & SFL_TIME)
323                 valstr = TIME_ENCODED_TOSTRING(pValue);
324         else
325                 valstr = ftos(pValue);
326
327         return valstr;
328 }
329 #endif
330
331 // compressed vector format:
332 // like MD3, just even shorter
333 //   4 bit pitch (16 angles), 0 is -90, 8 is 0, 16 would be 90
334 //   5 bit yaw (32 angles), 0=0, 8=90, 16=180, 24=270
335 //   7 bit length (logarithmic encoding), 1/8 .. about 7844
336 //     length = 2^(length_encoded/8) / 8
337 // if pitch is 90, yaw does nothing and therefore indicates the sign (yaw is then either 11111 or 11110); 11111 is pointing DOWN
338 // thus, valid values are from 0000.11110.0000000 to 1111.11111.1111111
339 // the special value 0 indicates the zero vector
340
341 float lengthLogTable[128];
342
343 float invertLengthLog(float dist)
344 {
345         int l, r, m;
346
347         if(dist >= lengthLogTable[127])
348                 return 127;
349         if(dist <= lengthLogTable[0])
350                 return 0;
351
352         l = 0;
353         r = 127;
354
355         while(r - l > 1)
356         {
357                 m = floor((l + r) / 2);
358                 if(lengthLogTable[m] < dist)
359                         l = m;
360                 else
361                         r = m;
362         }
363
364         // now: r is >=, l is <
365         float lerr = (dist - lengthLogTable[l]);
366         float rerr = (lengthLogTable[r] - dist);
367         if(lerr < rerr)
368                 return l;
369         return r;
370 }
371
372 vector decompressShortVector(int data)
373 {
374         vector out;
375         if(data == 0)
376                 return '0 0 0';
377         float p = (data & 0xF000) / 0x1000;
378         float q = (data & 0x0F80) / 0x80;
379         int len = (data & 0x007F);
380
381         //print("\ndecompress: p ", ftos(p)); print("q ", ftos(q)); print("len ", ftos(len), "\n");
382
383         if(p == 0)
384         {
385                 out.x = 0;
386                 out.y = 0;
387                 if(q == 31)
388                         out.z = -1;
389                 else
390                         out.z = +1;
391         }
392         else
393         {
394                 q   = .19634954084936207740 * q;
395                 p = .19634954084936207740 * p - 1.57079632679489661922;
396                 out.x = cos(q) *  cos(p);
397                 out.y = sin(q) *  cos(p);
398                 out.z =          -sin(p);
399         }
400
401         //print("decompressed: ", vtos(out), "\n");
402
403         return out * lengthLogTable[len];
404 }
405
406 float compressShortVector(vector vec)
407 {
408         vector ang;
409         float p, y, len;
410         if(vec == '0 0 0')
411                 return 0;
412         //print("compress: ", vtos(vec), "\n");
413         ang = vectoangles(vec);
414         ang.x = -ang.x;
415         if(ang.x < -90)
416                 ang.x += 360;
417         if(ang.x < -90 && ang.x > +90)
418                 error("BOGUS vectoangles");
419         //print("angles: ", vtos(ang), "\n");
420
421         p = floor(0.5 + (ang.x + 90) * 16 / 180) & 15; // -90..90 to 0..14
422         if(p == 0)
423         {
424                 if(vec.z < 0)
425                         y = 31;
426                 else
427                         y = 30;
428         }
429         else
430                 y = floor(0.5 + ang.y * 32 / 360)          & 31; // 0..360 to 0..32
431         len = invertLengthLog(vlen(vec));
432
433         //print("compressed: p ", ftos(p)); print("y ", ftos(y)); print("len ", ftos(len), "\n");
434
435         return (p * 0x1000) + (y * 0x80) + len;
436 }
437
438 STATIC_INIT(compressShortVector)
439 {
440         float l = 1;
441         float f = (2 ** (1/8));
442         int i;
443         for(i = 0; i < 128; ++i)
444         {
445                 lengthLogTable[i] = l;
446                 l *= f;
447         }
448
449         if(cvar("developer") > 0)
450         {
451                 LOG_TRACE("Verifying vector compression table...");
452                 for(i = 0x0F00; i < 0xFFFF; ++i)
453                         if(i != compressShortVector(decompressShortVector(i)))
454                         {
455                                 LOG_FATALF(
456                                     "BROKEN vector compression: %s -> %s -> %s",
457                                     ftos(i),
458                                     vtos(decompressShortVector(i)),
459                                     ftos(compressShortVector(decompressShortVector(i)))
460                 );
461                         }
462                 LOG_TRACE("Done.");
463         }
464 }
465
466 #ifdef GAMEQC
467 float CheckWireframeBox(entity forent, vector v0, vector dvx, vector dvy, vector dvz)
468 {
469         traceline(v0, v0 + dvx, true, forent); if(trace_fraction < 1) return 0;
470         traceline(v0, v0 + dvy, true, forent); if(trace_fraction < 1) return 0;
471         traceline(v0, v0 + dvz, true, forent); if(trace_fraction < 1) return 0;
472         traceline(v0 + dvx, v0 + dvx + dvy, true, forent); if(trace_fraction < 1) return 0;
473         traceline(v0 + dvx, v0 + dvx + dvz, true, forent); if(trace_fraction < 1) return 0;
474         traceline(v0 + dvy, v0 + dvy + dvx, true, forent); if(trace_fraction < 1) return 0;
475         traceline(v0 + dvy, v0 + dvy + dvz, true, forent); if(trace_fraction < 1) return 0;
476         traceline(v0 + dvz, v0 + dvz + dvx, true, forent); if(trace_fraction < 1) return 0;
477         traceline(v0 + dvz, v0 + dvz + dvy, true, forent); if(trace_fraction < 1) return 0;
478         traceline(v0 + dvx + dvy, v0 + dvx + dvy + dvz, true, forent); if(trace_fraction < 1) return 0;
479         traceline(v0 + dvx + dvz, v0 + dvx + dvy + dvz, true, forent); if(trace_fraction < 1) return 0;
480         traceline(v0 + dvy + dvz, v0 + dvx + dvy + dvz, true, forent); if(trace_fraction < 1) return 0;
481         return 1;
482 }
483 #endif
484
485 string fixPriorityList(string order, float from, float to, float subtract, float complete)
486 {
487         string neworder;
488         float i, n, w;
489
490         n = tokenize_console(order);
491         neworder = "";
492         for(i = 0; i < n; ++i)
493         {
494                 w = stof(argv(i));
495                 if(w == floor(w))
496                 {
497                         if(w >= from && w <= to)
498                                 neworder = strcat(neworder, ftos(w), " ");
499                         else
500                         {
501                                 w -= subtract;
502                                 if(w >= from && w <= to)
503                                         neworder = strcat(neworder, ftos(w), " ");
504                         }
505                 }
506         }
507
508         if(complete)
509         {
510                 n = tokenize_console(neworder);
511                 for(w = to; w >= from; --w)
512                 {
513                         int wflags = REGISTRY_GET(Weapons, w).spawnflags;
514                         if(wflags & WEP_FLAG_SPECIALATTACK)
515                                 continue;
516                         for(i = 0; i < n; ++i)
517                                 if(stof(argv(i)) == w)
518                                         break;
519                         if(i == n) // not found
520                                 neworder = strcat(neworder, ftos(w), " ");
521                 }
522         }
523
524         return substring(neworder, 0, strlen(neworder) - 1);
525 }
526
527 string mapPriorityList(string order, string(string) mapfunc)
528 {
529         string neworder;
530         float n;
531
532         n = tokenize_console(order);
533         neworder = "";
534         for(float i = 0; i < n; ++i)
535                 neworder = strcat(neworder, mapfunc(argv(i)), " ");
536
537         return substring(neworder, 0, strlen(neworder) - 1);
538 }
539
540 string swapInPriorityList(string order, float i, float j)
541 {
542         float n = tokenize_console(order);
543
544         if(i >= 0 && i < n && j >= 0 && j < n && i != j)
545         {
546                 string s = "";
547                 for(float w = 0; w < n; ++w)
548                 {
549                         if(w == i)
550                                 s = strcat(s, argv(j), " ");
551                         else if(w == j)
552                                 s = strcat(s, argv(i), " ");
553                         else
554                                 s = strcat(s, argv(w), " ");
555                 }
556                 return substring(s, 0, strlen(s) - 1);
557         }
558
559         return order;
560 }
561
562 #ifdef GAMEQC
563 void get_mi_min_max(float mode)
564 {
565         vector mi, ma;
566
567         string s = mapname;
568         if(!strcasecmp(substring(s, 0, 5), "maps/"))
569                 s = substring(s, 5, strlen(s) - 5);
570         if(!strcasecmp(substring(s, strlen(s) - 4, 4), ".bsp"))
571                 s = substring(s, 0, strlen(s) - 4);
572         strcpy(mi_shortname, s);
573
574 #ifdef CSQC
575         mi = world.mins;
576         ma = world.maxs;
577 #else
578         mi = world.absmin;
579         ma = world.absmax;
580 #endif
581
582         mi_min = mi;
583         mi_max = ma;
584         MapInfo_Get_ByName(mi_shortname, 0, NULL);
585         if(MapInfo_Map_mins.x < MapInfo_Map_maxs.x)
586         {
587                 mi_min = MapInfo_Map_mins;
588                 mi_max = MapInfo_Map_maxs;
589         }
590         else
591         {
592                 // not specified
593                 if(mode)
594                 {
595                         // be clever
596                         tracebox('1 0 0' * mi.x,
597                                          '0 1 0' * mi.y + '0 0 1' * mi.z,
598                                          '0 1 0' * ma.y + '0 0 1' * ma.z,
599                                          '1 0 0' * ma.x,
600                                          MOVE_WORLDONLY,
601                                          NULL);
602                         if(!trace_startsolid)
603                                 mi_min.x = trace_endpos.x;
604
605                         tracebox('0 1 0' * mi.y,
606                                          '1 0 0' * mi.x + '0 0 1' * mi.z,
607                                          '1 0 0' * ma.x + '0 0 1' * ma.z,
608                                          '0 1 0' * ma.y,
609                                          MOVE_WORLDONLY,
610                                          NULL);
611                         if(!trace_startsolid)
612                                 mi_min.y = trace_endpos.y;
613
614                         tracebox('0 0 1' * mi.z,
615                                          '1 0 0' * mi.x + '0 1 0' * mi.y,
616                                          '1 0 0' * ma.x + '0 1 0' * ma.y,
617                                          '0 0 1' * ma.z,
618                                          MOVE_WORLDONLY,
619                                          NULL);
620                         if(!trace_startsolid)
621                                 mi_min.z = trace_endpos.z;
622
623                         tracebox('1 0 0' * ma.x,
624                                          '0 1 0' * mi.y + '0 0 1' * mi.z,
625                                          '0 1 0' * ma.y + '0 0 1' * ma.z,
626                                          '1 0 0' * mi.x,
627                                          MOVE_WORLDONLY,
628                                          NULL);
629                         if(!trace_startsolid)
630                                 mi_max.x = trace_endpos.x;
631
632                         tracebox('0 1 0' * ma.y,
633                                          '1 0 0' * mi.x + '0 0 1' * mi.z,
634                                          '1 0 0' * ma.x + '0 0 1' * ma.z,
635                                          '0 1 0' * mi.y,
636                                          MOVE_WORLDONLY,
637                                          NULL);
638                         if(!trace_startsolid)
639                                 mi_max.y = trace_endpos.y;
640
641                         tracebox('0 0 1' * ma.z,
642                                          '1 0 0' * mi.x + '0 1 0' * mi.y,
643                                          '1 0 0' * ma.x + '0 1 0' * ma.y,
644                                          '0 0 1' * mi.z,
645                                          MOVE_WORLDONLY,
646                                          NULL);
647                         if(!trace_startsolid)
648                                 mi_max.z = trace_endpos.z;
649                 }
650         }
651 }
652
653 void get_mi_min_max_texcoords(float mode)
654 {
655         vector extend;
656
657         get_mi_min_max(mode);
658
659         mi_picmin = mi_min;
660         mi_picmax = mi_max;
661
662         // extend mi_picmax to get a square aspect ratio
663         // center the map in that area
664         extend = mi_picmax - mi_picmin;
665         if(extend.y > extend.x)
666         {
667                 mi_picmin.x -= (extend.y - extend.x) * 0.5;
668                 mi_picmax.x += (extend.y - extend.x) * 0.5;
669         }
670         else
671         {
672                 mi_picmin.y -= (extend.x - extend.y) * 0.5;
673                 mi_picmax.y += (extend.x - extend.y) * 0.5;
674         }
675
676         // add another some percent
677         extend = (mi_picmax - mi_picmin) * (1 / 64.0);
678         mi_picmin -= extend;
679         mi_picmax += extend;
680
681         // calculate the texcoords
682         mi_pictexcoord0 = mi_pictexcoord1 = mi_pictexcoord2 = mi_pictexcoord3 = '0 0 0';
683         // first the two corners of the origin
684         mi_pictexcoord0_x = (mi_min.x - mi_picmin.x) / (mi_picmax.x - mi_picmin.x);
685         mi_pictexcoord0_y = (mi_min.y - mi_picmin.y) / (mi_picmax.y - mi_picmin.y);
686         mi_pictexcoord2_x = (mi_max.x - mi_picmin.x) / (mi_picmax.x - mi_picmin.x);
687         mi_pictexcoord2_y = (mi_max.y - mi_picmin.y) / (mi_picmax.y - mi_picmin.y);
688         // then the other corners
689         mi_pictexcoord1_x = mi_pictexcoord0_x;
690         mi_pictexcoord1_y = mi_pictexcoord2_y;
691         mi_pictexcoord3_x = mi_pictexcoord2_x;
692         mi_pictexcoord3_y = mi_pictexcoord0_y;
693 }
694 #endif
695
696 float cvar_settemp(string tmp_cvar, string tmp_value)
697 {
698         float created_saved_value;
699
700         created_saved_value = 0;
701
702         if (!(tmp_cvar || tmp_value))
703         {
704                 LOG_TRACE("Error: Invalid usage of cvar_settemp(string, string); !");
705                 return 0;
706         }
707
708         if(!cvar_type(tmp_cvar))
709         {
710                 LOG_INFOF("Error: cvar %s doesn't exist!", tmp_cvar);
711                 return 0;
712         }
713
714         IL_EACH(g_saved_cvars, it.netname == tmp_cvar,
715         {
716                 created_saved_value = -1; // skip creation
717                 break; // no need to continue
718         });
719
720         if(created_saved_value != -1)
721         {
722                 // creating a new entity to keep track of this cvar
723                 entity e = new_pure(saved_cvar_value);
724                 IL_PUSH(g_saved_cvars, e);
725                 e.netname = strzone(tmp_cvar);
726                 e.message = strzone(cvar_string(tmp_cvar));
727                 created_saved_value = 1;
728         }
729
730         // update the cvar to the value given
731         cvar_set(tmp_cvar, tmp_value);
732
733         return created_saved_value;
734 }
735
736 int cvar_settemp_restore()
737 {
738         int j = 0;
739         // FIXME this new-style loop fails!
740 #if 0
741         FOREACH_ENTITY_CLASS("saved_cvar_value", true,
742         {
743                 if(cvar_type(it.netname))
744                 {
745                         cvar_set(it.netname, it.message);
746                         strunzone(it.netname);
747                         strunzone(it.message);
748                         delete(it);
749                         ++j;
750                 }
751                 else
752                         LOG_INFOF("Error: cvar %s doesn't exist anymore! It can still be restored once it's manually recreated.", it.netname);
753         });
754
755 #else
756         entity e = NULL;
757         while((e = find(e, classname, "saved_cvar_value")))
758         {
759                 if(cvar_type(e.netname))
760                 {
761                         cvar_set(e.netname, e.message);
762                         delete(e);
763                         ++j;
764                 }
765                 else
766                         print(sprintf("Error: cvar %s doesn't exist anymore! It can still be restored once it's manually recreated.", e.netname));
767         }
768 #endif
769
770         return j;
771 }
772
773 bool isCaretEscaped(string theText, float pos)
774 {
775         int i = 0;
776         while(pos - i >= 1 && substring(theText, pos - i - 1, 1) == "^")
777                 ++i;
778         return (i & 1);
779 }
780
781 int skipIncompleteTag(string theText, float pos, int len)
782 {
783         int tag_start = -1;
784
785         if(substring(theText, pos - 1, 1) == "^")
786         {
787                 if(isCaretEscaped(theText, pos - 1) || pos >= len)
788                         return 0;
789
790                 int ch = str2chr(theText, pos);
791                 if(ch >= '0' && ch <= '9')
792                         return 1; // ^[0-9] color code found
793                 else if (ch == 'x')
794                         tag_start = pos - 1; // ^x tag found
795                 else
796                         return 0;
797         }
798         else
799         {
800                 for(int i = 2; pos - i >= 0 && i <= 4; ++i)
801                 {
802                         if(substring(theText, pos - i, 2) == "^x")
803                         {
804                                 tag_start = pos - i; // ^x tag found
805                                 break;
806                         }
807                 }
808         }
809
810         if(tag_start >= 0)
811         {
812                 if(tag_start + 5 < len)
813                 if(IS_HEXDIGIT(substring(theText, tag_start + 2, 1)))
814                 if(IS_HEXDIGIT(substring(theText, tag_start + 3, 1)))
815                 if(IS_HEXDIGIT(substring(theText, tag_start + 4, 1)))
816                 {
817                         if(!isCaretEscaped(theText, tag_start))
818                                 return 5 - (pos - tag_start); // ^xRGB color code found
819                 }
820         }
821         return 0;
822 }
823
824 float textLengthUpToWidth(string theText, float maxWidth, vector theSize, textLengthUpToWidth_widthFunction_t w)
825 {
826         // STOP.
827         // The following function is SLOW.
828         // For your safety and for the protection of those around you...
829         // DO NOT CALL THIS AT HOME.
830         // No really, don't.
831         if(w(theText, theSize) <= maxWidth)
832                 return strlen(theText); // yeah!
833
834         bool colors = (w("^7", theSize) == 0);
835
836         // binary search for right place to cut string
837         int len, left, right, middle;
838         left = 0;
839         right = len = strlen(theText);
840         int ofs = 0;
841         do
842         {
843                 middle = floor((left + right) / 2);
844                 if(colors)
845                         ofs = skipIncompleteTag(theText, middle, len);
846                 if(w(substring(theText, 0, middle + ofs), theSize) <= maxWidth)
847                         left = middle + ofs;
848                 else
849                         right = middle;
850         }
851         while(left < right - 1);
852
853         return left;
854 }
855
856 float textLengthUpToLength(string theText, float maxWidth, textLengthUpToLength_lenFunction_t w)
857 {
858         // STOP.
859         // The following function is SLOW.
860         // For your safety and for the protection of those around you...
861         // DO NOT CALL THIS AT HOME.
862         // No really, don't.
863         if(w(theText) <= maxWidth)
864                 return strlen(theText); // yeah!
865
866         bool colors = (w("^7") == 0);
867
868         // binary search for right place to cut string
869         int len, left, right, middle;
870         left = 0;
871         right = len = strlen(theText);
872         int ofs = 0;
873         do
874         {
875                 middle = floor((left + right) / 2);
876                 if(colors)
877                         ofs = skipIncompleteTag(theText, middle, len);
878                 if(w(substring(theText, 0, middle + ofs)) <= maxWidth)
879                         left = middle + ofs;
880                 else
881                         right = middle;
882         }
883         while(left < right - 1);
884
885         return left;
886 }
887
888 string find_last_color_code(string s)
889 {
890         int start = strstrofs(s, "^", 0);
891         if (start == -1) // no caret found
892                 return "";
893         int len = strlen(s)-1;
894         for(int i = len; i >= start; --i)
895         {
896                 if(substring(s, i, 1) != "^")
897                         continue;
898
899                 int carets = 1;
900                 while (i-carets >= start && substring(s, i-carets, 1) == "^")
901                         ++carets;
902
903                 // check if carets aren't all escaped
904                 if (carets & 1)
905                 {
906                         if(i+1 <= len)
907                         if(IS_DIGIT(substring(s, i+1, 1)))
908                                 return substring(s, i, 2);
909
910                         if(i+4 <= len)
911                         if(substring(s, i+1, 1) == "x")
912                         if(IS_HEXDIGIT(substring(s, i + 2, 1)))
913                         if(IS_HEXDIGIT(substring(s, i + 3, 1)))
914                         if(IS_HEXDIGIT(substring(s, i + 4, 1)))
915                                 return substring(s, i, 5);
916                 }
917                 i -= carets; // this also skips one char before the carets
918         }
919
920         return "";
921 }
922
923 string getWrappedLine(float w, vector theFontSize, textLengthUpToWidth_widthFunction_t tw)
924 {
925         float cantake;
926         float take;
927         string s;
928
929         s = getWrappedLine_remaining;
930
931         if(w <= 0)
932         {
933                 getWrappedLine_remaining = string_null;
934                 return s; // the line has no size ANYWAY, nothing would be displayed.
935         }
936
937         cantake = textLengthUpToWidth(s, w, theFontSize, tw);
938         if(cantake > 0 && cantake < strlen(s))
939         {
940                 take = cantake - 1;
941                 while(take > 0 && substring(s, take, 1) != " ")
942                         --take;
943                 if(take == 0)
944                 {
945                         getWrappedLine_remaining = substring(s, cantake, strlen(s) - cantake);
946                         if(getWrappedLine_remaining == "")
947                                 getWrappedLine_remaining = string_null;
948                         else if (tw("^7", theFontSize) == 0)
949                                 getWrappedLine_remaining = strcat(find_last_color_code(substring(s, 0, cantake)), getWrappedLine_remaining);
950                         return substring(s, 0, cantake);
951                 }
952                 else
953                 {
954                         getWrappedLine_remaining = substring(s, take + 1, strlen(s) - take);
955                         if(getWrappedLine_remaining == "")
956                                 getWrappedLine_remaining = string_null;
957                         else if (tw("^7", theFontSize) == 0)
958                                 getWrappedLine_remaining = strcat(find_last_color_code(substring(s, 0, take)), getWrappedLine_remaining);
959                         return substring(s, 0, take);
960                 }
961         }
962         else
963         {
964                 getWrappedLine_remaining = string_null;
965                 return s;
966         }
967 }
968
969 string getWrappedLineLen(float w, textLengthUpToLength_lenFunction_t tw)
970 {
971         float cantake;
972         float take;
973         string s;
974
975         s = getWrappedLine_remaining;
976
977         if(w <= 0)
978         {
979                 getWrappedLine_remaining = string_null;
980                 return s; // the line has no size ANYWAY, nothing would be displayed.
981         }
982
983         cantake = textLengthUpToLength(s, w, tw);
984         if(cantake > 0 && cantake < strlen(s))
985         {
986                 take = cantake - 1;
987                 while(take > 0 && substring(s, take, 1) != " ")
988                         --take;
989                 if(take == 0)
990                 {
991                         getWrappedLine_remaining = substring(s, cantake, strlen(s) - cantake);
992                         if(getWrappedLine_remaining == "")
993                                 getWrappedLine_remaining = string_null;
994                         else if (tw("^7") == 0)
995                                 getWrappedLine_remaining = strcat(find_last_color_code(substring(s, 0, cantake)), getWrappedLine_remaining);
996                         return substring(s, 0, cantake);
997                 }
998                 else
999                 {
1000                         getWrappedLine_remaining = substring(s, take + 1, strlen(s) - take);
1001                         if(getWrappedLine_remaining == "")
1002                                 getWrappedLine_remaining = string_null;
1003                         else if (tw("^7") == 0)
1004                                 getWrappedLine_remaining = strcat(find_last_color_code(substring(s, 0, take)), getWrappedLine_remaining);
1005                         return substring(s, 0, take);
1006                 }
1007         }
1008         else
1009         {
1010                 getWrappedLine_remaining = string_null;
1011                 return s;
1012         }
1013 }
1014
1015 string textShortenToWidth(string theText, float maxWidth, vector theFontSize, textLengthUpToWidth_widthFunction_t tw)
1016 {
1017         if(tw(theText, theFontSize) <= maxWidth)
1018                 return theText;
1019         else
1020                 return strcat(substring(theText, 0, textLengthUpToWidth(theText, maxWidth - tw("...", theFontSize), theFontSize, tw)), "...");
1021 }
1022
1023 string textShortenToLength(string theText, float maxWidth, textLengthUpToLength_lenFunction_t tw)
1024 {
1025         if(tw(theText) <= maxWidth)
1026                 return theText;
1027         else
1028                 return strcat(substring(theText, 0, textLengthUpToLength(theText, maxWidth - tw("..."), tw)), "...");
1029 }
1030
1031 float isGametypeInFilter(Gametype gt, float tp, float ts, string pattern)
1032 {
1033         string subpattern, subpattern2, subpattern3, subpattern4;
1034         subpattern = strcat(",", MapInfo_Type_ToString(gt), ",");
1035         if(tp)
1036                 subpattern2 = ",teams,";
1037         else
1038                 subpattern2 = ",noteams,";
1039         if(ts)
1040                 subpattern3 = ",teamspawns,";
1041         else
1042                 subpattern3 = ",noteamspawns,";
1043         if(gt == MAPINFO_TYPE_RACE || gt == MAPINFO_TYPE_CTS)
1044                 subpattern4 = ",race,";
1045         else
1046                 subpattern4 = string_null;
1047
1048         if(substring(pattern, 0, 1) == "-")
1049         {
1050                 pattern = substring(pattern, 1, strlen(pattern) - 1);
1051                 if(strstrofs(strcat(",", pattern, ","), subpattern, 0) >= 0)
1052                         return 0;
1053                 if(strstrofs(strcat(",", pattern, ","), subpattern2, 0) >= 0)
1054                         return 0;
1055                 if(strstrofs(strcat(",", pattern, ","), subpattern3, 0) >= 0)
1056                         return 0;
1057                 if(subpattern4 && strstrofs(strcat(",", pattern, ","), subpattern4, 0) >= 0)
1058                         return 0;
1059         }
1060         else
1061         {
1062                 if(substring(pattern, 0, 1) == "+")
1063                         pattern = substring(pattern, 1, strlen(pattern) - 1);
1064                 if(strstrofs(strcat(",", pattern, ","), subpattern, 0) < 0)
1065                 if(strstrofs(strcat(",", pattern, ","), subpattern2, 0) < 0)
1066                 if(strstrofs(strcat(",", pattern, ","), subpattern3, 0) < 0)
1067                 {
1068                         if (!subpattern4)
1069                                 return 0;
1070                         if(strstrofs(strcat(",", pattern, ","), subpattern4, 0) < 0)
1071                                 return 0;
1072                 }
1073         }
1074         return 1;
1075 }
1076
1077 vector solve_shotdirection(vector myorg, vector myvel, vector eorg, vector evel, float spd, float newton_style)
1078 {
1079         vector ret;
1080
1081         // make origin and speed relative
1082         eorg -= myorg;
1083         if(newton_style)
1084                 evel -= myvel;
1085
1086         // now solve for ret, ret normalized:
1087         //   eorg + t * evel == t * ret * spd
1088         // or, rather, solve for t:
1089         //   |eorg + t * evel| == t * spd
1090         //   eorg^2 + t^2 * evel^2 + 2 * t * (eorg * evel) == t^2 * spd^2
1091         //   t^2 * (evel^2 - spd^2) + t * (2 * (eorg * evel)) + eorg^2 == 0
1092         vector solution = solve_quadratic(evel * evel - spd * spd, 2 * (eorg * evel), eorg * eorg);
1093         // p = 2 * (eorg * evel) / (evel * evel - spd * spd)
1094         // q = (eorg * eorg) / (evel * evel - spd * spd)
1095         if(!solution.z) // no real solution
1096         {
1097                 // happens if D < 0
1098                 // (eorg * evel)^2 < (evel^2 - spd^2) * eorg^2
1099                 // (eorg * evel)^2 / eorg^2 < evel^2 - spd^2
1100                 // spd^2 < ((evel^2 * eorg^2) - (eorg * evel)^2) / eorg^2
1101                 // spd^2 < evel^2 * (1 - cos^2 angle(evel, eorg))
1102                 // spd^2 < evel^2 * sin^2 angle(evel, eorg)
1103                 // spd < |evel| * sin angle(evel, eorg)
1104                 return '0 0 0';
1105         }
1106         else if(solution.x > 0)
1107         {
1108                 // both solutions > 0: take the smaller one
1109                 // happens if p < 0 and q > 0
1110                 ret = normalize(eorg + solution.x * evel);
1111         }
1112         else if(solution.y > 0)
1113         {
1114                 // one solution > 0: take the larger one
1115                 // happens if q < 0 or q == 0 and p < 0
1116                 ret = normalize(eorg + solution.y * evel);
1117         }
1118         else
1119         {
1120                 // no solution > 0: reject
1121                 // happens if p > 0 and q >= 0
1122                 // 2 * (eorg * evel) / (evel * evel - spd * spd) > 0
1123                 // (eorg * eorg) / (evel * evel - spd * spd) >= 0
1124                 //
1125                 // |evel| >= spd
1126                 // eorg * evel > 0
1127                 //
1128                 // "Enemy is moving away from me at more than spd"
1129                 return '0 0 0';
1130         }
1131
1132         // NOTE: we always got a solution if spd > |evel|
1133
1134         if(newton_style == 2)
1135                 ret = normalize(ret * spd + myvel);
1136
1137         return ret;
1138 }
1139
1140 vector get_shotvelocity(vector myvel, vector mydir, float spd, float newton_style, float mi, float ma)
1141 {
1142         if(!newton_style)
1143                 return spd * mydir;
1144
1145         if(newton_style == 2)
1146         {
1147                 // true Newtonian projectiles with automatic aim adjustment
1148                 //
1149                 // solve: |outspeed * mydir - myvel| = spd
1150                 // outspeed^2 - 2 * outspeed * (mydir * myvel) + myvel^2 - spd^2 = 0
1151                 // outspeed = (mydir * myvel) +- sqrt((mydir * myvel)^2 - myvel^2 + spd^2)
1152                 // PLUS SIGN!
1153                 // not defined?
1154                 // then...
1155                 // myvel^2 - (mydir * myvel)^2 > spd^2
1156                 // velocity without mydir component > spd
1157                 // fire at smallest possible spd that works?
1158                 // |(mydir * myvel) * myvel - myvel| = spd
1159
1160                 vector solution = solve_quadratic(1, -2 * (mydir * myvel), myvel * myvel - spd * spd);
1161
1162                 float outspeed;
1163                 if(solution.z)
1164                         outspeed = solution.y; // the larger one
1165                 else
1166                 {
1167                         //outspeed = 0; // slowest possible shot
1168                         outspeed = solution.x; // the real part (that is, the average!)
1169                         //dprint("impossible shot, adjusting\n");
1170                 }
1171
1172                 outspeed = bound(spd * mi, outspeed, spd * ma);
1173                 return mydir * outspeed;
1174         }
1175
1176         // real Newtonian
1177         return myvel + spd * mydir;
1178 }
1179
1180 float compressShotOrigin(vector v)
1181 {
1182         float rx = rint(v.x * 2);
1183         float ry = rint(v.y * 4) + 128;
1184         float rz = rint(v.z * 4) + 128;
1185         if(rx > 255 || rx < 0)
1186         {
1187                 LOG_DEBUG("shot origin ", vtos(v), " x out of bounds\n");
1188                 rx = bound(0, rx, 255);
1189         }
1190         if(ry > 255 || ry < 0)
1191         {
1192                 LOG_DEBUG("shot origin ", vtos(v), " y out of bounds\n");
1193                 ry = bound(0, ry, 255);
1194         }
1195         if(rz > 255 || rz < 0)
1196         {
1197                 LOG_DEBUG("shot origin ", vtos(v), " z out of bounds\n");
1198                 rz = bound(0, rz, 255);
1199         }
1200         return rx * 0x10000 + ry * 0x100 + rz;
1201 }
1202 vector decompressShotOrigin(int f)
1203 {
1204         vector v;
1205         v.x = ((f & 0xFF0000) / 0x10000) / 2;
1206         v.y = ((f & 0xFF00) / 0x100 - 128) / 4;
1207         v.z = ((f & 0xFF) - 128) / 4;
1208         return v;
1209 }
1210
1211 #ifdef GAMEQC
1212 vector healtharmor_maxdamage(float h, float a, float armorblock, int deathtype)
1213 {
1214         // NOTE: we'll always choose the SMALLER value...
1215         float healthdamage, armordamage, armorideal;
1216         if (DEATH_IS(deathtype, DEATH_DROWN))  // Why should armor help here...
1217                 armorblock = 0;
1218         vector v;
1219         healthdamage = (h - 1) / (1 - armorblock); // damage we can take if we could use more health
1220         armordamage = a + (h - 1); // damage we can take if we could use more armor
1221         armorideal = healthdamage * armorblock;
1222         v.y = armorideal;
1223         if(armordamage < healthdamage)
1224         {
1225                 v.x = armordamage;
1226                 v.z = 1;
1227         }
1228         else
1229         {
1230                 v.x = healthdamage;
1231                 v.z = 0;
1232         }
1233         return v;
1234 }
1235
1236 vector healtharmor_applydamage(float a, float armorblock, int deathtype, float damage)
1237 {
1238         vector v;
1239         if (DEATH_IS(deathtype, DEATH_DROWN))  // Why should armor help here...
1240                 armorblock = 0;
1241         if (deathtype & HITTYPE_ARMORPIERCE)
1242                 armorblock = 0;
1243         v.y = bound(0, damage * armorblock, a); // save
1244         v.x = bound(0, damage - v.y, damage); // take
1245         v.z = 0;
1246         return v;
1247 }
1248 #endif
1249
1250 string getcurrentmod()
1251 {
1252         float n;
1253         string m;
1254         m = cvar_string("fs_gamedir");
1255         n = tokenize_console(m);
1256         if(n == 0)
1257                 return "data";
1258         else
1259                 return argv(n - 1);
1260 }
1261
1262 float matchacl(string acl, string str)
1263 {
1264         string t, s;
1265         float r, d;
1266         r = 0;
1267         while(acl)
1268         {
1269                 t = car(acl); acl = cdr(acl);
1270
1271                 d = 1;
1272                 if(substring(t, 0, 1) == "-")
1273                 {
1274                         d = -1;
1275                         t = substring(t, 1, strlen(t) - 1);
1276                 }
1277                 else if(substring(t, 0, 1) == "+")
1278                         t = substring(t, 1, strlen(t) - 1);
1279
1280                 if(substring(t, -1, 1) == "*")
1281                 {
1282                         t = substring(t, 0, strlen(t) - 1);
1283                         s = substring(str, 0, strlen(t));
1284                 }
1285                 else
1286                         s = str;
1287
1288                 if(s == t)
1289                 {
1290                         r = d;
1291                         break; // if we found a killing case, apply it! other settings may be allowed in the future, but this one is caught
1292                 }
1293         }
1294         return r;
1295 }
1296
1297 ERASEABLE
1298 void write_String_To_File(int fh, string str, bool alsoprint)
1299 {
1300         fputs(fh, str);
1301         if (alsoprint) LOG_INFO(str);
1302 }
1303
1304 string get_model_datafilename(string m, float sk, string fil)
1305 {
1306         if(m)
1307                 m = strcat(m, "_");
1308         else
1309                 m = "models/player/*_";
1310         if(sk >= 0)
1311                 m = strcat(m, ftos(sk));
1312         else
1313                 m = strcat(m, "*");
1314         return strcat(m, ".", fil);
1315 }
1316
1317 float get_model_parameters(string m, float sk)
1318 {
1319         get_model_parameters_modelname = string_null;
1320         get_model_parameters_modelskin = -1;
1321         get_model_parameters_name = string_null;
1322         get_model_parameters_species = -1;
1323         get_model_parameters_sex = string_null;
1324         get_model_parameters_weight = -1;
1325         get_model_parameters_age = -1;
1326         get_model_parameters_desc = string_null;
1327         get_model_parameters_bone_upperbody = string_null;
1328         get_model_parameters_bone_weapon = string_null;
1329         for(int i = 0; i < MAX_AIM_BONES; ++i)
1330         {
1331                 get_model_parameters_bone_aim[i] = string_null;
1332                 get_model_parameters_bone_aimweight[i] = 0;
1333         }
1334         get_model_parameters_fixbone = 0;
1335         get_model_parameters_hidden = false;
1336
1337 #ifdef GAMEQC
1338         MUTATOR_CALLHOOK(ClearModelParams);
1339 #endif
1340
1341         if (!m)
1342                 return 1;
1343
1344         if(substring(m, -9, 5) == "_lod1" || substring(m, -9, 5) == "_lod2")
1345                 m = strcat(substring(m, 0, -10), substring(m, -4, -1));
1346
1347         if(sk < 0)
1348         {
1349                 if(substring(m, -4, -1) != ".txt")
1350                         return 0;
1351                 if(substring(m, -6, 1) != "_")
1352                         return 0;
1353                 sk = stof(substring(m, -5, 1));
1354                 m = substring(m, 0, -7);
1355         }
1356
1357         string fn = get_model_datafilename(m, sk, "txt");
1358         int fh = fopen(fn, FILE_READ);
1359         if(fh < 0)
1360         {
1361                 sk = 0;
1362                 fn = get_model_datafilename(m, sk, "txt");
1363                 fh = fopen(fn, FILE_READ);
1364                 if(fh < 0)
1365                         return 0;
1366         }
1367
1368         get_model_parameters_modelname = m;
1369         get_model_parameters_modelskin = sk;
1370         string s, c;
1371         while((s = fgets(fh)))
1372         {
1373                 if(s == "")
1374                         break; // next lines will be description
1375                 c = car(s);
1376                 s = cdr(s);
1377                 if(c == "name")
1378                         get_model_parameters_name = s;
1379                 if(c == "species")
1380                         switch(s)
1381                         {
1382                                 case "human":       get_model_parameters_species = SPECIES_HUMAN;       break;
1383                                 case "alien":       get_model_parameters_species = SPECIES_ALIEN;       break;
1384                                 case "robot_shiny": get_model_parameters_species = SPECIES_ROBOT_SHINY; break;
1385                                 case "robot_rusty": get_model_parameters_species = SPECIES_ROBOT_RUSTY; break;
1386                                 case "robot_solid": get_model_parameters_species = SPECIES_ROBOT_SOLID; break;
1387                                 case "animal":      get_model_parameters_species = SPECIES_ANIMAL;      break;
1388                                 case "reserved":    get_model_parameters_species = SPECIES_RESERVED;    break;
1389                         }
1390                 if(c == "sex")
1391                 {
1392                         if (s == "Male")                                s = _("Male");
1393                         else if (s == "Female")                 s = _("Female");
1394                         else if (s == "Undisclosed")    s = _("Undisclosed");
1395                         get_model_parameters_sex = s;
1396                 }
1397                 if(c == "weight")
1398                         get_model_parameters_weight = stof(s);
1399                 if(c == "age")
1400                         get_model_parameters_age = stof(s);
1401                 if(c == "description")
1402                         get_model_parameters_description = s;
1403                 if(c == "bone_upperbody")
1404                         get_model_parameters_bone_upperbody = s;
1405                 if(c == "bone_weapon")
1406                         get_model_parameters_bone_weapon = s;
1407         #ifdef GAMEQC
1408                 MUTATOR_CALLHOOK(GetModelParams, c, s);
1409         #endif
1410                 for(int i = 0; i < MAX_AIM_BONES; ++i)
1411                         if(c == strcat("bone_aim", ftos(i)))
1412                         {
1413                                 get_model_parameters_bone_aimweight[i] = stof(car(s));
1414                                 get_model_parameters_bone_aim[i] = cdr(s);
1415                         }
1416                 if(c == "fixbone")
1417                         get_model_parameters_fixbone = stof(s);
1418                 if(c == "hidden")
1419                         get_model_parameters_hidden = stob(s);
1420         }
1421
1422         while((s = fgets(fh)))
1423         {
1424                 if(get_model_parameters_desc)
1425                         get_model_parameters_desc = strcat(get_model_parameters_desc, "\n");
1426                 if(s != "")
1427                         get_model_parameters_desc = strcat(get_model_parameters_desc, s);
1428         }
1429
1430         fclose(fh);
1431
1432         return 1;
1433 }
1434
1435 string translate_key(string key)
1436 {
1437         if (prvm_language == "en") return key;
1438
1439         if (substring(key, 0, 1) == "<")
1440         {
1441                 if (key == "<KEY NOT FOUND>") return _("<KEY NOT FOUND>");
1442                 if (key == "<UNKNOWN KEYNUM>") return _("<UNKNOWN KEYNUM>");
1443         }
1444
1445         switch(key)
1446         {
1447                 case "TAB":                             return _("TAB");
1448                 case "ENTER":                   return _("ENTER");
1449                 case "ESCAPE":                  return _("ESCAPE");
1450                 case "SPACE":                   return _("SPACE");
1451
1452                 case "BACKSPACE":               return _("BACKSPACE");
1453                 case "UPARROW":                 return _("UPARROW");
1454                 case "DOWNARROW":               return _("DOWNARROW");
1455                 case "LEFTARROW":               return _("LEFTARROW");
1456                 case "RIGHTARROW":              return _("RIGHTARROW");
1457
1458                 case "ALT":                             return _("ALT");
1459                 case "CTRL":                    return _("CTRL");
1460                 case "SHIFT":                   return _("SHIFT");
1461
1462                 case "INS":                             return _("INS");
1463                 case "DEL":                             return _("DEL");
1464                 case "PGDN":                    return _("PGDN");
1465                 case "PGUP":                    return _("PGUP");
1466                 case "HOME":                    return _("HOME");
1467                 case "END":                             return _("END");
1468
1469                 case "PAUSE":                   return _("PAUSE");
1470
1471                 case "NUMLOCK":                 return _("NUMLOCK");
1472                 case "CAPSLOCK":                return _("CAPSLOCK");
1473                 case "SCROLLOCK":               return _("SCROLLOCK");
1474
1475                 case "SEMICOLON":               return _("SEMICOLON");
1476                 case "TILDE":                   return _("TILDE");
1477                 case "BACKQUOTE":               return _("BACKQUOTE");
1478                 case "QUOTE":                   return _("QUOTE");
1479                 case "APOSTROPHE":              return _("APOSTROPHE");
1480                 case "BACKSLASH":               return _("BACKSLASH");
1481         }
1482
1483         if (substring(key, 0, 1) == "F")
1484         {
1485                 string subkey = substring(key, 1, -1);
1486                 if (IS_DIGIT(substring(key, 3, 1))) // check only first digit
1487                 {
1488                         return sprintf(_("F%d"), stof(subkey));
1489                 }
1490                 // continue in case there is another key name starting with F
1491         }
1492
1493         if (substring(key, 0, 3) == "KP_")
1494         {
1495                 string subkey = substring(key, 3, -1);
1496                 if (IS_DIGIT(substring(key, 3, 1))) // check only first digit
1497                 {
1498                         return sprintf(_("KP_%d"), stof(subkey));
1499                 }
1500
1501                 switch(subkey)
1502                 {
1503                         case "INS":                             return sprintf(_("KP_%s"), _("INS"));
1504                         case "END":                             return sprintf(_("KP_%s"), _("END"));
1505                         case "DOWNARROW":               return sprintf(_("KP_%s"), _("DOWNARROW"));
1506                         case "PGDN":                    return sprintf(_("KP_%s"), _("PGDN"));
1507                         case "LEFTARROW":               return sprintf(_("KP_%s"), _("LEFTARROW"));
1508                         case "RIGHTARROW":              return sprintf(_("KP_%s"), _("RIGHTARROW"));
1509                         case "HOME":                    return sprintf(_("KP_%s"), _("HOME"));
1510                         case "UPARROW":                 return sprintf(_("KP_%s"), _("UPARROW"));
1511                         case "PGUP":                    return sprintf(_("KP_%s"), _("PGUP"));
1512                         case "PERIOD":                  return sprintf(_("KP_%s"), _("PERIOD"));
1513                         case "DEL":                             return sprintf(_("KP_%s"), _("DEL"));
1514                         case "DIVIDE":                  return sprintf(_("KP_%s"), _("DIVIDE"));
1515                         case "SLASH":                   return sprintf(_("KP_%s"), _("SLASH"));
1516                         case "MULTIPLY":                return sprintf(_("KP_%s"), _("MULTIPLY"));
1517                         case "MINUS":                   return sprintf(_("KP_%s"), _("MINUS"));
1518                         case "PLUS":                    return sprintf(_("KP_%s"), _("PLUS"));
1519                         case "ENTER":                   return sprintf(_("KP_%s"), _("ENTER"));
1520                         case "EQUALS":                  return sprintf(_("KP_%s"), _("EQUALS"));
1521                         default:                                return key;
1522                 }
1523         }
1524
1525         if (key == "PRINTSCREEN") return _("PRINTSCREEN");
1526
1527         if (substring(key, 0, 5) == "MOUSE")
1528                 return sprintf(_("MOUSE%d"), stof(substring(key, 5, -1)));
1529
1530         if (key == "MWHEELUP") return _("MWHEELUP");
1531         if (key == "MWHEELDOWN") return _("MWHEELDOWN");
1532
1533         if (substring(key, 0,3) == "JOY")
1534                 return sprintf(_("JOY%d"), stof(substring(key, 3, -1)));
1535
1536         if (substring(key, 0,3) == "AUX")
1537                 return sprintf(_("AUX%d"), stof(substring(key, 3, -1)));
1538
1539         if (substring(key, 0, 4) == "X360_")
1540         {
1541                 string subkey = substring(key, 4, -1);
1542                 switch(subkey)
1543                 {
1544                         case "DPAD_UP":                                 return sprintf(_("X360_%s"), _("DPAD_UP"));
1545                         case "DPAD_DOWN":                               return sprintf(_("X360_%s"), _("DPAD_DOWN"));
1546                         case "DPAD_LEFT":                               return sprintf(_("X360_%s"), _("DPAD_LEFT"));
1547                         case "DPAD_RIGHT":                              return sprintf(_("X360_%s"), _("DPAD_RIGHT"));
1548                         case "START":                                   return sprintf(_("X360_%s"), _("START"));
1549                         case "BACK":                                    return sprintf(_("X360_%s"), _("BACK"));
1550                         case "LEFT_THUMB":                              return sprintf(_("X360_%s"), _("LEFT_THUMB"));
1551                         case "RIGHT_THUMB":                             return sprintf(_("X360_%s"), _("RIGHT_THUMB"));
1552                         case "LEFT_SHOULDER":                   return sprintf(_("X360_%s"), _("LEFT_SHOULDER"));
1553                         case "RIGHT_SHOULDER":                  return sprintf(_("X360_%s"), _("RIGHT_SHOULDER"));
1554                         case "LEFT_TRIGGER":                    return sprintf(_("X360_%s"), _("LEFT_TRIGGER"));
1555                         case "RIGHT_TRIGGER":                   return sprintf(_("X360_%s"), _("RIGHT_TRIGGER"));
1556                         case "LEFT_THUMB_UP":                   return sprintf(_("X360_%s"), _("LEFT_THUMB_UP"));
1557                         case "LEFT_THUMB_DOWN":                 return sprintf(_("X360_%s"), _("LEFT_THUMB_DOWN"));
1558                         case "LEFT_THUMB_LEFT":                 return sprintf(_("X360_%s"), _("LEFT_THUMB_LEFT"));
1559                         case "LEFT_THUMB_RIGHT":                return sprintf(_("X360_%s"), _("LEFT_THUMB_RIGHT"));
1560                         case "RIGHT_THUMB_UP":                  return sprintf(_("X360_%s"), _("RIGHT_THUMB_UP"));
1561                         case "RIGHT_THUMB_DOWN":                return sprintf(_("X360_%s"), _("RIGHT_THUMB_DOWN"));
1562                         case "RIGHT_THUMB_LEFT":                return sprintf(_("X360_%s"), _("RIGHT_THUMB_LEFT"));
1563                         case "RIGHT_THUMB_RIGHT":               return sprintf(_("X360_%s"), _("RIGHT_THUMB_RIGHT"));
1564                         default:                                                return key;
1565                 }
1566         }
1567
1568         if (substring(key, 0, 4) == "JOY_")
1569         {
1570                 string subkey = substring(key, 4, -1);
1571                 switch(subkey)
1572                 {
1573                         case "UP":                      return sprintf(_("JOY_%s"), _("UP"));
1574                         case "DOWN":            return sprintf(_("JOY_%s"), _("DOWN"));
1575                         case "LEFT":            return sprintf(_("JOY_%s"), _("LEFT"));
1576                         case "RIGHT":           return sprintf(_("JOY_%s"), _("RIGHT"));
1577                         default:                        return key;
1578                 }
1579         }
1580
1581         if (substring(key, 0, 8) == "MIDINOTE")
1582                 return sprintf(_("MIDINOTE%d"), stof(substring(key, 8, -1)));
1583
1584         return key;
1585 }
1586
1587 // x-encoding (encoding as zero length invisible string)
1588 const string XENCODE_2  = "xX";
1589 const string XENCODE_22 = "0123456789abcdefABCDEF";
1590 string xencode(int f)
1591 {
1592         float a, b, c, d;
1593         d = f % 22; f = floor(f / 22);
1594         c = f % 22; f = floor(f / 22);
1595         b = f % 22; f = floor(f / 22);
1596         a = f %  2; // f = floor(f /  2);
1597         return strcat(
1598                 "^",
1599                 substring(XENCODE_2,  a, 1),
1600                 substring(XENCODE_22, b, 1),
1601                 substring(XENCODE_22, c, 1),
1602                 substring(XENCODE_22, d, 1)
1603         );
1604 }
1605 float xdecode(string s)
1606 {
1607         float a, b, c, d;
1608         if(substring(s, 0, 1) != "^")
1609                 return -1;
1610         if(strlen(s) < 5)
1611                 return -1;
1612         a = strstrofs(XENCODE_2,  substring(s, 1, 1), 0);
1613         b = strstrofs(XENCODE_22, substring(s, 2, 1), 0);
1614         c = strstrofs(XENCODE_22, substring(s, 3, 1), 0);
1615         d = strstrofs(XENCODE_22, substring(s, 4, 1), 0);
1616         if(a < 0 || b < 0 || c < 0 || d < 0)
1617                 return -1;
1618         return ((a * 22 + b) * 22 + c) * 22 + d;
1619 }
1620
1621 /*
1622 string strlimitedlen(string input, string truncation, float strip_colors, float limit)
1623 {
1624         if(strlen((strip_colors ? strdecolorize(input) : input)) <= limit)
1625                 return input;
1626         else
1627                 return strcat(substring(input, 0, (strlen(input) - strlen(truncation))), truncation);
1628 }*/
1629
1630 float shutdown_running;
1631 #ifdef SVQC
1632 void SV_Shutdown()
1633 #endif
1634 #ifdef CSQC
1635 void CSQC_Shutdown()
1636 #endif
1637 #ifdef MENUQC
1638 void m_shutdown()
1639 #endif
1640 {
1641         if(shutdown_running)
1642         {
1643                 LOG_INFO("Recursive shutdown detected! Only restoring cvars...");
1644         }
1645         else
1646         {
1647                 shutdown_running = 1;
1648                 Shutdown();
1649                 shutdownhooks();
1650         }
1651         cvar_settemp_restore(); // this must be done LAST, but in any case
1652 }
1653
1654 #ifdef GAMEQC
1655 .float skeleton_bones_index;
1656 void Skeleton_SetBones(entity e)
1657 {
1658         // set skeleton_bones to the total number of bones on the model
1659         if(e.skeleton_bones_index == e.modelindex)
1660                 return; // same model, nothing to update
1661
1662         float skelindex;
1663         skelindex = skel_create(e.modelindex);
1664         e.skeleton_bones = skel_get_numbones(skelindex);
1665         skel_delete(skelindex);
1666         e.skeleton_bones_index = e.modelindex;
1667 }
1668 #endif
1669
1670 string to_execute_next_frame;
1671 void execute_next_frame()
1672 {
1673         if(to_execute_next_frame)
1674         {
1675                 localcmd("\n", to_execute_next_frame, "\n");
1676                 strfree(to_execute_next_frame);
1677         }
1678 }
1679 void queue_to_execute_next_frame(string s)
1680 {
1681         if(to_execute_next_frame)
1682         {
1683                 s = strcat(s, "\n", to_execute_next_frame);
1684         }
1685         strcpy(to_execute_next_frame, s);
1686 }
1687
1688 .float FindConnectedComponent_processing;
1689 void FindConnectedComponent(entity e, .entity fld, findNextEntityNearFunction_t nxt, isConnectedFunction_t iscon, entity pass)
1690 {
1691         entity queue_start, queue_end;
1692
1693         // we build a queue of to-be-processed entities.
1694         // queue_start is the next entity to be checked for neighbors
1695         // queue_end is the last entity added
1696
1697         if(e.FindConnectedComponent_processing)
1698                 error("recursion or broken cleanup");
1699
1700         // start with a 1-element queue
1701         queue_start = queue_end = e;
1702         queue_end.(fld) = NULL;
1703         queue_end.FindConnectedComponent_processing = 1;
1704
1705         // for each queued item:
1706         for (; queue_start; queue_start = queue_start.(fld))
1707         {
1708                 // find all neighbors of queue_start
1709                 entity t;
1710                 for(t = NULL; (t = nxt(t, queue_start, pass)); )
1711                 {
1712                         if(t.FindConnectedComponent_processing)
1713                                 continue;
1714                         if(iscon(t, queue_start, pass))
1715                         {
1716                                 // it is connected? ADD IT. It will look for neighbors soon too.
1717                                 queue_end.(fld) = t;
1718                                 queue_end = t;
1719                                 queue_end.(fld) = NULL;
1720                                 queue_end.FindConnectedComponent_processing = 1;
1721                         }
1722                 }
1723         }
1724
1725         // unmark
1726         for (queue_start = e; queue_start; queue_start = queue_start.(fld))
1727                 queue_start.FindConnectedComponent_processing = 0;
1728 }
1729
1730 #ifdef GAMEQC
1731 vector animfixfps(entity e, vector a, vector b)
1732 {
1733         // multi-frame anim: keep as-is
1734         if(a.y == 1)
1735         {
1736                 float dur = frameduration(e.modelindex, a.x);
1737                 if (dur <= 0 && b.y)
1738                 {
1739                         a = b;
1740                         dur = frameduration(e.modelindex, a.x);
1741                 }
1742                 if (dur > 0)
1743                         a.z = 1.0 / dur;
1744         }
1745         return a;
1746 }
1747 #endif
1748
1749 #ifdef GAMEQC
1750 Notification Announcer_PickNumber(int type, int num)
1751 {
1752     return = NULL;
1753         switch (type)
1754         {
1755                 case CNT_GAMESTART:
1756                 {
1757                         switch(num)
1758                         {
1759                                 case 10: return ANNCE_NUM_GAMESTART_10;
1760                                 case 9:  return ANNCE_NUM_GAMESTART_9;
1761                                 case 8:  return ANNCE_NUM_GAMESTART_8;
1762                                 case 7:  return ANNCE_NUM_GAMESTART_7;
1763                                 case 6:  return ANNCE_NUM_GAMESTART_6;
1764                                 case 5:  return ANNCE_NUM_GAMESTART_5;
1765                                 case 4:  return ANNCE_NUM_GAMESTART_4;
1766                                 case 3:  return ANNCE_NUM_GAMESTART_3;
1767                                 case 2:  return ANNCE_NUM_GAMESTART_2;
1768                                 case 1:  return ANNCE_NUM_GAMESTART_1;
1769                         }
1770                         break;
1771                 }
1772                 case CNT_IDLE:
1773                 {
1774                         switch(num)
1775                         {
1776                                 case 10: return ANNCE_NUM_IDLE_10;
1777                                 case 9:  return ANNCE_NUM_IDLE_9;
1778                                 case 8:  return ANNCE_NUM_IDLE_8;
1779                                 case 7:  return ANNCE_NUM_IDLE_7;
1780                                 case 6:  return ANNCE_NUM_IDLE_6;
1781                                 case 5:  return ANNCE_NUM_IDLE_5;
1782                                 case 4:  return ANNCE_NUM_IDLE_4;
1783                                 case 3:  return ANNCE_NUM_IDLE_3;
1784                                 case 2:  return ANNCE_NUM_IDLE_2;
1785                                 case 1:  return ANNCE_NUM_IDLE_1;
1786                         }
1787                         break;
1788                 }
1789                 case CNT_KILL:
1790                 {
1791                         switch(num)
1792                         {
1793                                 case 10: return ANNCE_NUM_KILL_10;
1794                                 case 9:  return ANNCE_NUM_KILL_9;
1795                                 case 8:  return ANNCE_NUM_KILL_8;
1796                                 case 7:  return ANNCE_NUM_KILL_7;
1797                                 case 6:  return ANNCE_NUM_KILL_6;
1798                                 case 5:  return ANNCE_NUM_KILL_5;
1799                                 case 4:  return ANNCE_NUM_KILL_4;
1800                                 case 3:  return ANNCE_NUM_KILL_3;
1801                                 case 2:  return ANNCE_NUM_KILL_2;
1802                                 case 1:  return ANNCE_NUM_KILL_1;
1803                         }
1804                         break;
1805                 }
1806                 case CNT_RESPAWN:
1807                 {
1808                         switch(num)
1809                         {
1810                                 case 10: return ANNCE_NUM_RESPAWN_10;
1811                                 case 9:  return ANNCE_NUM_RESPAWN_9;
1812                                 case 8:  return ANNCE_NUM_RESPAWN_8;
1813                                 case 7:  return ANNCE_NUM_RESPAWN_7;
1814                                 case 6:  return ANNCE_NUM_RESPAWN_6;
1815                                 case 5:  return ANNCE_NUM_RESPAWN_5;
1816                                 case 4:  return ANNCE_NUM_RESPAWN_4;
1817                                 case 3:  return ANNCE_NUM_RESPAWN_3;
1818                                 case 2:  return ANNCE_NUM_RESPAWN_2;
1819                                 case 1:  return ANNCE_NUM_RESPAWN_1;
1820                         }
1821                         break;
1822                 }
1823                 case CNT_ROUNDSTART:
1824                 {
1825                         switch(num)
1826                         {
1827                                 case 10: return ANNCE_NUM_ROUNDSTART_10;
1828                                 case 9:  return ANNCE_NUM_ROUNDSTART_9;
1829                                 case 8:  return ANNCE_NUM_ROUNDSTART_8;
1830                                 case 7:  return ANNCE_NUM_ROUNDSTART_7;
1831                                 case 6:  return ANNCE_NUM_ROUNDSTART_6;
1832                                 case 5:  return ANNCE_NUM_ROUNDSTART_5;
1833                                 case 4:  return ANNCE_NUM_ROUNDSTART_4;
1834                                 case 3:  return ANNCE_NUM_ROUNDSTART_3;
1835                                 case 2:  return ANNCE_NUM_ROUNDSTART_2;
1836                                 case 1:  return ANNCE_NUM_ROUNDSTART_1;
1837                         }
1838                         break;
1839                 }
1840                 default:
1841                 {
1842                         switch(num)
1843                         {
1844                                 case 10: return ANNCE_NUM_10;
1845                                 case 9:  return ANNCE_NUM_9;
1846                                 case 8:  return ANNCE_NUM_8;
1847                                 case 7:  return ANNCE_NUM_7;
1848                                 case 6:  return ANNCE_NUM_6;
1849                                 case 5:  return ANNCE_NUM_5;
1850                                 case 4:  return ANNCE_NUM_4;
1851                                 case 3:  return ANNCE_NUM_3;
1852                                 case 2:  return ANNCE_NUM_2;
1853                                 case 1:  return ANNCE_NUM_1;
1854                         }
1855                         break;
1856                 }
1857         }
1858 }
1859 #endif
1860
1861 #ifdef GAMEQC
1862 int Mod_Q1BSP_SuperContentsFromNativeContents(int nativecontents)
1863 {
1864         switch(nativecontents)
1865         {
1866                 case CONTENT_EMPTY:
1867                         return 0;
1868                 case CONTENT_SOLID:
1869                         return DPCONTENTS_SOLID | DPCONTENTS_OPAQUE;
1870                 case CONTENT_WATER:
1871                         return DPCONTENTS_WATER;
1872                 case CONTENT_SLIME:
1873                         return DPCONTENTS_SLIME;
1874                 case CONTENT_LAVA:
1875                         return DPCONTENTS_LAVA | DPCONTENTS_NODROP;
1876                 case CONTENT_SKY:
1877                         return DPCONTENTS_SKY | DPCONTENTS_NODROP | DPCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
1878         }
1879         return 0;
1880 }
1881
1882 int Mod_Q1BSP_NativeContentsFromSuperContents(int supercontents)
1883 {
1884         if(supercontents & (DPCONTENTS_SOLID | DPCONTENTS_BODY))
1885                 return CONTENT_SOLID;
1886         if(supercontents & DPCONTENTS_SKY)
1887                 return CONTENT_SKY;
1888         if(supercontents & DPCONTENTS_LAVA)
1889                 return CONTENT_LAVA;
1890         if(supercontents & DPCONTENTS_SLIME)
1891                 return CONTENT_SLIME;
1892         if(supercontents & DPCONTENTS_WATER)
1893                 return CONTENT_WATER;
1894         return CONTENT_EMPTY;
1895 }
1896 #endif
1897
1898 #ifdef SVQC
1899 void attach_sameorigin(entity e, entity to, string tag)
1900 {
1901     vector org, t_forward, t_left, t_up, e_forward, e_up;
1902     float tagscale;
1903
1904     org = e.origin - gettaginfo(to, gettagindex(to, tag));
1905     tagscale = (vlen(v_forward) ** -2); // undo a scale on the tag
1906     t_forward = v_forward * tagscale;
1907     t_left = v_right * -tagscale;
1908     t_up = v_up * tagscale;
1909
1910     e.origin_x = org * t_forward;
1911     e.origin_y = org * t_left;
1912     e.origin_z = org * t_up;
1913
1914     // current forward and up directions
1915     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1916                 e.angles = AnglesTransform_FromVAngles(e.angles);
1917         else
1918                 e.angles = AnglesTransform_FromAngles(e.angles);
1919     fixedmakevectors(e.angles);
1920
1921     // untransform forward, up!
1922     e_forward.x = v_forward * t_forward;
1923     e_forward.y = v_forward * t_left;
1924     e_forward.z = v_forward * t_up;
1925     e_up.x = v_up * t_forward;
1926     e_up.y = v_up * t_left;
1927     e_up.z = v_up * t_up;
1928
1929     e.angles = fixedvectoangles2(e_forward, e_up);
1930     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1931                 e.angles = AnglesTransform_ToVAngles(e.angles);
1932         else
1933                 e.angles = AnglesTransform_ToAngles(e.angles);
1934
1935     setattachment(e, to, tag);
1936     setorigin(e, e.origin);
1937 }
1938
1939 void detach_sameorigin(entity e)
1940 {
1941     vector org;
1942     org = gettaginfo(e, 0);
1943     e.angles = fixedvectoangles2(v_forward, v_up);
1944     if (substring(e.model, 0, 1) == "*") // bmodels have their own rules
1945                 e.angles = AnglesTransform_ToVAngles(e.angles);
1946         else
1947                 e.angles = AnglesTransform_ToAngles(e.angles);
1948     setorigin(e, org);
1949     setattachment(e, NULL, "");
1950     setorigin(e, e.origin);
1951 }
1952
1953 void follow_sameorigin(entity e, entity to)
1954 {
1955     set_movetype(e, MOVETYPE_FOLLOW); // make the hole follow
1956     e.aiment = to; // make the hole follow bmodel
1957     e.punchangle = to.angles; // the original angles of bmodel
1958     e.view_ofs = e.origin - to.origin; // relative origin
1959     e.v_angle = e.angles - to.angles; // relative angles
1960 }
1961
1962 #if 0
1963 // TODO: unused, likely for a reason, possibly needs extensions (allow setting the new movetype as a parameter?)
1964 void unfollow_sameorigin(entity e)
1965 {
1966     set_movetype(e, MOVETYPE_NONE);
1967 }
1968 #endif
1969
1970 .string aiment_classname;
1971 .float aiment_deadflag;
1972 void SetMovetypeFollow(entity ent, entity e)
1973 {
1974         // FIXME this may not be warpzone aware
1975         set_movetype(ent, MOVETYPE_FOLLOW); // make the hole follow
1976         ent.solid = SOLID_NOT; // MOVETYPE_FOLLOW is always non-solid - this means this cannot be teleported by warpzones any more! Instead, we must notice when our owner gets teleported.
1977         ent.aiment = e; // make the hole follow bmodel
1978         ent.punchangle = e.angles; // the original angles of bmodel
1979         ent.view_ofs = ent.origin - e.origin; // relative origin
1980         ent.v_angle = ent.angles - e.angles; // relative angles
1981         ent.aiment_classname = strzone(e.classname);
1982         ent.aiment_deadflag = e.deadflag;
1983 }
1984 void UnsetMovetypeFollow(entity ent)
1985 {
1986         set_movetype(ent, MOVETYPE_FLY);
1987         PROJECTILE_MAKETRIGGER(ent);
1988         ent.aiment = NULL;
1989 }
1990 float LostMovetypeFollow(entity ent)
1991 {
1992 /*
1993         if(ent.move_movetype != MOVETYPE_FOLLOW)
1994                 if(ent.aiment)
1995                         error("???");
1996 */
1997         if(ent.aiment)
1998         {
1999                 if(ent.aiment.classname != ent.aiment_classname)
2000                         return 1;
2001                 if(ent.aiment.deadflag != ent.aiment_deadflag)
2002                         return 1;
2003         }
2004         return 0;
2005 }
2006 #endif
2007
2008 #ifdef GAMEQC
2009 // decolorizes and team colors the player name when needed
2010 string playername(string thename, int teamid, bool team_colorize)
2011 {
2012         TC(int, teamid);
2013         bool do_colorize = (teamplay && team_colorize);
2014 #ifdef SVQC
2015         if(do_colorize && !intermission_running)
2016 #else
2017         if(do_colorize)
2018 #endif
2019     {
2020         string t = Team_ColorCode(teamid);
2021         return strcat(t, strdecolorize(thename));
2022     }
2023     else
2024         return thename;
2025 }
2026
2027 float trace_hits_box_a0, trace_hits_box_a1;
2028
2029 float trace_hits_box_1d(float end, float thmi, float thma)
2030 {
2031     if (end == 0)
2032     {
2033         // just check if x is in range
2034         if (0 < thmi)
2035             return false;
2036         if (0 > thma)
2037             return false;
2038     }
2039     else
2040     {
2041         // do the trace with respect to x
2042         // 0 -> end has to stay in thmi -> thma
2043         trace_hits_box_a0 = max(trace_hits_box_a0, min(thmi / end, thma / end));
2044         trace_hits_box_a1 = min(trace_hits_box_a1, max(thmi / end, thma / end));
2045         if (trace_hits_box_a0 > trace_hits_box_a1)
2046             return false;
2047     }
2048     return true;
2049 }
2050
2051 float trace_hits_box(vector start, vector end, vector thmi, vector thma)
2052 {
2053     end -= start;
2054     thmi -= start;
2055     thma -= start;
2056     // now it is a trace from 0 to end
2057
2058     trace_hits_box_a0 = 0;
2059     trace_hits_box_a1 = 1;
2060
2061     if (!trace_hits_box_1d(end.x, thmi.x, thma.x))
2062         return false;
2063     if (!trace_hits_box_1d(end.y, thmi.y, thma.y))
2064         return false;
2065     if (!trace_hits_box_1d(end.z, thmi.z, thma.z))
2066         return false;
2067
2068     return true;
2069 }
2070
2071 float tracebox_hits_box(vector start, vector mi, vector ma, vector end, vector thmi, vector thma)
2072 {
2073     return trace_hits_box(start, end, thmi - ma, thma - mi);
2074 }
2075 #endif
2076
2077 ERASEABLE
2078 float cvar_or(string cv, float v)
2079 {
2080         string s = cvar_string(cv);
2081         if(s == "")
2082                 return v;
2083         else
2084                 return stof(s);
2085 }
2086
2087 // NOTE base is the central value
2088 // freq: circle frequency, = 2*pi*frequency in hertz
2089 // start_pos:
2090 //  -1 start from the lower value
2091 //   0 start from the base value
2092 //   1 start from the higher value
2093 ERASEABLE
2094 float blink_synced(float base, float range, float freq, float start_time, int start_pos)
2095 {
2096         // note:
2097         //   RMS = sqrt(base^2 + 0.5 * range^2)
2098         // thus
2099         //   base = sqrt(RMS^2 - 0.5 * range^2)
2100         // ensure RMS == 1
2101
2102         return base + range * sin((time - start_time - (M_PI / 2) * start_pos) * freq);
2103 }
2104
2105 ERASEABLE
2106 float blink(float base, float range, float freq)
2107 {
2108         return blink_synced(base, range, freq, 0, 0);
2109 }