]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/common/util.qc
Merge branch 'master' into terencehill/arena_and_ca_fixes
[xonotic/xonotic-data.pk3dir.git] / qcsrc / common / util.qc
1 string wordwrap_buffer;
2
3 void wordwrap_buffer_put(string s)
4 {
5         wordwrap_buffer = strcat(wordwrap_buffer, s);
6 }
7
8 string wordwrap(string s, float l)
9 {
10         string r;
11         wordwrap_buffer = "";
12         wordwrap_cb(s, l, wordwrap_buffer_put);
13         r = wordwrap_buffer;
14         wordwrap_buffer = "";
15         return r;
16 }
17
18 #ifndef MENUQC
19 #ifndef CSQC
20 void wordwrap_buffer_sprint(string s)
21 {
22         wordwrap_buffer = strcat(wordwrap_buffer, s);
23         if(s == "\n")
24         {
25                 sprint(self, wordwrap_buffer);
26                 wordwrap_buffer = "";
27         }
28 }
29
30 void wordwrap_sprint(string s, float l)
31 {
32         wordwrap_buffer = "";
33         wordwrap_cb(s, l, wordwrap_buffer_sprint);
34         if(wordwrap_buffer != "")
35                 sprint(self, strcat(wordwrap_buffer, "\n"));
36         wordwrap_buffer = "";
37         return;
38 }
39 #endif
40 #endif
41
42 string unescape(string in)
43 {
44         float i, len;
45         string str, s;
46
47         // but it doesn't seem to be necessary in my tests at least
48         in = strzone(in);
49
50         len = strlen(in);
51         str = "";
52         for(i = 0; i < len; ++i)
53         {
54                 s = substring(in, i, 1);
55                 if(s == "\\")
56                 {
57                         s = substring(in, i+1, 1);
58                         if(s == "n")
59                                 str = strcat(str, "\n");
60                         else if(s == "\\")
61                                 str = strcat(str, "\\");
62                         else
63                                 str = strcat(str, substring(in, i, 2));
64                         ++i;
65                 } else
66                         str = strcat(str, s);
67         }
68
69         strunzone(in);
70         return str;
71 }
72
73 void wordwrap_cb(string s, float l, void(string) callback)
74 {
75         string c;
76         float lleft, i, j, wlen;
77
78         s = strzone(s);
79         lleft = l;
80         for (i = 0;i < strlen(s);++i)
81         {
82                 if (substring(s, i, 2) == "\\n")
83                 {
84                         callback("\n");
85                         lleft = l;
86                         ++i;
87                 }
88                 else if (substring(s, i, 1) == "\n")
89                 {
90                         callback("\n");
91                         lleft = l;
92                 }
93                 else if (substring(s, i, 1) == " ")
94                 {
95                         if (lleft > 0)
96                         {
97                                 callback(" ");
98                                 lleft = lleft - 1;
99                         }
100                 }
101                 else
102                 {
103                         for (j = i+1;j < strlen(s);++j)
104                                 //    ^^ this skips over the first character of a word, which
105                                 //       is ALWAYS part of the word
106                                 //       this is safe since if i+1 == strlen(s), i will become
107                                 //       strlen(s)-1 at the end of this block and the function
108                                 //       will terminate. A space can't be the first character we
109                                 //       read here, and neither can a \n be the start, since these
110                                 //       two cases have been handled above.
111                         {
112                                 c = substring(s, j, 1);
113                                 if (c == " ")
114                                         break;
115                                 if (c == "\\")
116                                         break;
117                                 if (c == "\n")
118                                         break;
119                                 // we need to keep this tempstring alive even if substring is
120                                 // called repeatedly, so call strcat even though we're not
121                                 // doing anything
122                                 callback("");
123                         }
124                         wlen = j - i;
125                         if (lleft < wlen)
126                         {
127                                 callback("\n");
128                                 lleft = l;
129                         }
130                         callback(substring(s, i, wlen));
131                         lleft = lleft - wlen;
132                         i = j - 1;
133                 }
134         }
135         strunzone(s);
136 }
137
138 float dist_point_line(vector p, vector l0, vector ldir)
139 {
140         ldir = normalize(ldir);
141         
142         // remove the component in line direction
143         p = p - (p * ldir) * ldir;
144
145         // vlen of the remaining vector
146         return vlen(p);
147 }
148
149 void depthfirst(entity start, .entity up, .entity downleft, .entity right, void(entity, entity) funcPre, void(entity, entity) funcPost, entity pass)
150 {
151         entity e;
152         e = start;
153         funcPre(pass, e);
154         while(e.downleft)
155         {
156                 e = e.downleft;
157                 funcPre(pass, e);
158         }
159         funcPost(pass, e);
160         while(e != start)
161         {
162                 if(e.right)
163                 {
164                         e = e.right;
165                         funcPre(pass, e);
166                         while(e.downleft)
167                         {
168                                 e = e.downleft;
169                                 funcPre(pass, e);
170                         }
171                 }
172                 else
173                         e = e.up;
174                 funcPost(pass, e);
175         }
176 }
177
178 float median(float a, float b, float c)
179 {
180         if(a < c)
181                 return bound(a, b, c);
182         return bound(c, b, a);
183 }
184
185 // converts a number to a string with the indicated number of decimals
186 // works for up to 10 decimals!
187 string ftos_decimals(float number, float decimals)
188 {
189         // we have sprintf...
190         return sprintf("%.*f", decimals, number);
191 }
192
193 float time;
194 vector colormapPaletteColor(float c, float isPants)
195 {
196         switch(c)
197         {
198                 case  0: return '1.000000 1.000000 1.000000';
199                 case  1: return '1.000000 0.333333 0.000000';
200                 case  2: return '0.000000 1.000000 0.501961';
201                 case  3: return '0.000000 1.000000 0.000000';
202                 case  4: return '1.000000 0.000000 0.000000';
203                 case  5: return '0.000000 0.666667 1.000000';
204                 case  6: return '0.000000 1.000000 1.000000';
205                 case  7: return '0.501961 1.000000 0.000000';
206                 case  8: return '0.501961 0.000000 1.000000';
207                 case  9: return '1.000000 0.000000 1.000000';
208                 case 10: return '1.000000 0.000000 0.501961';
209                 case 11: return '0.000000 0.000000 1.000000';
210                 case 12: return '1.000000 1.000000 0.000000';
211                 case 13: return '0.000000 0.333333 1.000000';
212                 case 14: return '1.000000 0.666667 0.000000';
213                 case 15:
214                         if(isPants)
215                                 return
216                                           '1 0 0' * (0.502 + 0.498 * sin(time / 2.7182818285 + 0.0000000000))
217                                         + '0 1 0' * (0.502 + 0.498 * sin(time / 2.7182818285 + 2.0943951024))
218                                         + '0 0 1' * (0.502 + 0.498 * sin(time / 2.7182818285 + 4.1887902048));
219                         else
220                                 return
221                                           '1 0 0' * (0.502 + 0.498 * sin(time / 3.1415926536 + 5.2359877560))
222                                         + '0 1 0' * (0.502 + 0.498 * sin(time / 3.1415926536 + 3.1415926536))
223                                         + '0 0 1' * (0.502 + 0.498 * sin(time / 3.1415926536 + 1.0471975512));
224                 default: return '0.000 0.000 0.000';
225         }
226 }
227
228 // unzone the string, and return it as tempstring. Safe to be called on string_null
229 string fstrunzone(string s)
230 {
231         string sc;
232         if not(s)
233                 return s;
234         sc = strcat(s, "");
235         strunzone(s);
236         return sc;
237 }
238
239 float fexists(string f)
240 {
241     float fh;
242     fh = fopen(f, FILE_READ);
243     if (fh < 0)
244         return FALSE;
245     fclose(fh);
246     return TRUE;
247 }
248
249 // Databases (hash tables)
250 #define DB_BUCKETS 8192
251 void db_save(float db, string pFilename)
252 {
253         float fh, i, n;
254         fh = fopen(pFilename, FILE_WRITE);
255         if(fh < 0) 
256         {
257                 print(strcat("^1Can't write DB to ", pFilename));
258                 return;
259         }
260         n = buf_getsize(db);
261         fputs(fh, strcat(ftos(DB_BUCKETS), "\n"));
262         for(i = 0; i < n; ++i)
263                 fputs(fh, strcat(bufstr_get(db, i), "\n"));
264         fclose(fh);
265 }
266
267 float db_create()
268 {
269         return buf_create();
270 }
271
272 float db_load(string pFilename)
273 {
274         float db, fh, i, j, n;
275         string l;
276         db = buf_create();
277         if(db < 0)
278                 return -1;
279         fh = fopen(pFilename, FILE_READ);
280         if(fh < 0)
281                 return db;
282         l = fgets(fh);
283         if(stof(l) == DB_BUCKETS)
284         {
285                 i = 0;
286                 while((l = fgets(fh)))
287                 {
288                         if(l != "")
289                                 bufstr_set(db, i, l);
290                         ++i;
291                 }
292         }
293         else
294         {
295                 // different count of buckets, or a dump?
296                 // need to reorganize the database then (SLOW)
297                 //
298                 // note: we also parse the first line (l) in case the DB file is
299                 // missing the bucket count
300                 do
301                 {
302                         n = tokenizebyseparator(l, "\\");
303                         for(j = 2; j < n; j += 2)
304                                 db_put(db, argv(j-1), uri_unescape(argv(j)));
305                 }
306                 while((l = fgets(fh)));
307         }
308         fclose(fh);
309         return db;
310 }
311
312 void db_dump(float db, string pFilename)
313 {
314         float fh, i, j, n, m;
315         fh = fopen(pFilename, FILE_WRITE);
316         if(fh < 0)
317                 error(strcat("Can't dump DB to ", pFilename));
318         n = buf_getsize(db);
319         fputs(fh, "0\n");
320         for(i = 0; i < n; ++i)
321         {
322                 m = tokenizebyseparator(bufstr_get(db, i), "\\");
323                 for(j = 2; j < m; j += 2)
324                         fputs(fh, strcat("\\", argv(j-1), "\\", argv(j), "\n"));
325         }
326         fclose(fh);
327 }
328
329 void db_close(float db)
330 {
331         buf_del(db);
332 }
333
334 string db_get(float db, string pKey)
335 {
336         float h;
337         h = mod(crc16(FALSE, pKey), DB_BUCKETS);
338         return uri_unescape(infoget(bufstr_get(db, h), pKey));
339 }
340
341 void db_put(float db, string pKey, string pValue)
342 {
343         float h;
344         h = mod(crc16(FALSE, pKey), DB_BUCKETS);
345         bufstr_set(db, h, infoadd(bufstr_get(db, h), pKey, uri_escape(pValue)));
346 }
347
348 void db_test()
349 {
350         float db, i;
351         print("LOAD...\n");
352         db = db_load("foo.db");
353         print("LOADED. FILL...\n");
354         for(i = 0; i < DB_BUCKETS; ++i)
355                 db_put(db, ftos(random()), "X");
356         print("FILLED. SAVE...\n");
357         db_save(db, "foo.db");
358         print("SAVED. CLOSE...\n");
359         db_close(db);
360         print("CLOSED.\n");
361 }
362
363 // Multiline text file buffers
364 float buf_load(string pFilename)
365 {
366         float buf, fh, i;
367         string l;
368         buf = buf_create();
369         if(buf < 0)
370                 return -1;
371         fh = fopen(pFilename, FILE_READ);
372         if(fh < 0)
373         {
374                 buf_del(buf);
375                 return -1;
376         }
377         i = 0;
378         while((l = fgets(fh)))
379         {
380                 bufstr_set(buf, i, l);
381                 ++i;
382         }
383         fclose(fh);
384         return buf;
385 }
386
387 void buf_save(float buf, string pFilename)
388 {
389         float fh, i, n;
390         fh = fopen(pFilename, FILE_WRITE);
391         if(fh < 0)
392                 error(strcat("Can't write buf to ", pFilename));
393         n = buf_getsize(buf);
394         for(i = 0; i < n; ++i)
395                 fputs(fh, strcat(bufstr_get(buf, i), "\n"));
396         fclose(fh);
397 }
398
399 string mmsss(float tenths)
400 {
401         float minutes;
402         string s;
403         tenths = floor(tenths + 0.5);
404         minutes = floor(tenths / 600);
405         tenths -= minutes * 600;
406         s = ftos(1000 + tenths);
407         return strcat(ftos(minutes), ":", substring(s, 1, 2), ".", substring(s, 3, 1));
408 }
409
410 string mmssss(float hundredths)
411 {
412         float minutes;
413         string s;
414         hundredths = floor(hundredths + 0.5);
415         minutes = floor(hundredths / 6000);
416         hundredths -= minutes * 6000;
417         s = ftos(10000 + hundredths);
418         return strcat(ftos(minutes), ":", substring(s, 1, 2), ".", substring(s, 3, 2));
419 }
420
421 string ScoreString(float pFlags, float pValue)
422 {
423         string valstr;
424         float l;
425
426         pValue = floor(pValue + 0.5); // round
427
428         if((pValue == 0) && (pFlags & (SFL_HIDE_ZERO | SFL_RANK | SFL_TIME)))
429                 valstr = "";
430         else if(pFlags & SFL_RANK)
431         {
432                 valstr = ftos(pValue);
433                 l = strlen(valstr);
434                 if((l >= 2) && (substring(valstr, l - 2, 1) == "1"))
435                         valstr = strcat(valstr, "th");
436                 else if(substring(valstr, l - 1, 1) == "1")
437                         valstr = strcat(valstr, "st");
438                 else if(substring(valstr, l - 1, 1) == "2")
439                         valstr = strcat(valstr, "nd");
440                 else if(substring(valstr, l - 1, 1) == "3")
441                         valstr = strcat(valstr, "rd");
442                 else
443                         valstr = strcat(valstr, "th");
444         }
445         else if(pFlags & SFL_TIME)
446                 valstr = TIME_ENCODED_TOSTRING(pValue);
447         else
448                 valstr = ftos(pValue);
449         
450         return valstr;
451 }
452
453 vector cross(vector a, vector b)
454 {
455         return
456                 '1 0 0' * (a_y * b_z - a_z * b_y)
457         +       '0 1 0' * (a_z * b_x - a_x * b_z)
458         +       '0 0 1' * (a_x * b_y - a_y * b_x);
459 }
460
461 // compressed vector format:
462 // like MD3, just even shorter
463 //   4 bit pitch (16 angles), 0 is -90, 8 is 0, 16 would be 90
464 //   5 bit yaw (32 angles), 0=0, 8=90, 16=180, 24=270
465 //   7 bit length (logarithmic encoding), 1/8 .. about 7844
466 //     length = 2^(length_encoded/8) / 8
467 // if pitch is 90, yaw does nothing and therefore indicates the sign (yaw is then either 11111 or 11110); 11111 is pointing DOWN
468 // thus, valid values are from 0000.11110.0000000 to 1111.11111.1111111
469 // the special value 0 indicates the zero vector
470
471 float lengthLogTable[128];
472
473 float invertLengthLog(float x)
474 {
475         float l, r, m, lerr, rerr;
476
477         if(x >= lengthLogTable[127])
478                 return 127;
479         if(x <= lengthLogTable[0])
480                 return 0;
481
482         l = 0;
483         r = 127;
484
485         while(r - l > 1)
486         {
487                 m = floor((l + r) / 2);
488                 if(lengthLogTable[m] < x)
489                         l = m;
490                 else
491                         r = m;
492         }
493
494         // now: r is >=, l is <
495         lerr = (x - lengthLogTable[l]);
496         rerr = (lengthLogTable[r] - x);
497         if(lerr < rerr)
498                 return l;
499         return r;
500 }
501
502 vector decompressShortVector(float data)
503 {
504         vector out;
505         float p, y, len;
506         if(data == 0)
507                 return '0 0 0';
508         p   = (data & 0xF000) / 0x1000;
509         y   = (data & 0x0F80) / 0x80;
510         len = (data & 0x007F);
511
512         //print("\ndecompress: p ", ftos(p)); print("y ", ftos(y)); print("len ", ftos(len), "\n");
513
514         if(p == 0)
515         {
516                 out_x = 0;
517                 out_y = 0;
518                 if(y == 31)
519                         out_z = -1;
520                 else
521                         out_z = +1;
522         }
523         else
524         {
525                 y   = .19634954084936207740 * y;
526                 p = .19634954084936207740 * p - 1.57079632679489661922;
527                 out_x = cos(y) *  cos(p);
528                 out_y = sin(y) *  cos(p);
529                 out_z =          -sin(p);
530         }
531
532         //print("decompressed: ", vtos(out), "\n");
533
534         return out * lengthLogTable[len];
535 }
536
537 float compressShortVector(vector vec)
538 {
539         vector ang;
540         float p, y, len;
541         if(vlen(vec) == 0)
542                 return 0;
543         //print("compress: ", vtos(vec), "\n");
544         ang = vectoangles(vec);
545         ang_x = -ang_x;
546         if(ang_x < -90)
547                 ang_x += 360;
548         if(ang_x < -90 && ang_x > +90)
549                 error("BOGUS vectoangles");
550         //print("angles: ", vtos(ang), "\n");
551
552         p = floor(0.5 + (ang_x + 90) * 16 / 180) & 15; // -90..90 to 0..14
553         if(p == 0)
554         {
555                 if(vec_z < 0)
556                         y = 31;
557                 else
558                         y = 30;
559         }
560         else
561                 y = floor(0.5 + ang_y * 32 / 360)          & 31; // 0..360 to 0..32
562         len = invertLengthLog(vlen(vec));
563
564         //print("compressed: p ", ftos(p)); print("y ", ftos(y)); print("len ", ftos(len), "\n");
565
566         return (p * 0x1000) + (y * 0x80) + len;
567 }
568
569 void compressShortVector_init()
570 {
571         float l, f, i;
572         l = 1;
573         f = pow(2, 1/8);
574         for(i = 0; i < 128; ++i)
575         {
576                 lengthLogTable[i] = l;
577                 l *= f;
578         }
579
580         if(cvar("developer"))
581         {
582                 print("Verifying vector compression table...\n");
583                 for(i = 0x0F00; i < 0xFFFF; ++i)
584                         if(i != compressShortVector(decompressShortVector(i)))
585                         {
586                                 print("BROKEN vector compression: ", ftos(i));
587                                 print(" -> ", vtos(decompressShortVector(i)));
588                                 print(" -> ", ftos(compressShortVector(decompressShortVector(i))));
589                                 print("\n");
590                                 error("b0rk");
591                         }
592                 print("Done.\n");
593         }
594 }
595
596 #ifndef MENUQC
597 float CheckWireframeBox(entity forent, vector v0, vector dvx, vector dvy, vector dvz)
598 {
599         traceline(v0, v0 + dvx, TRUE, forent); if(trace_fraction < 1) return 0;
600         traceline(v0, v0 + dvy, TRUE, forent); if(trace_fraction < 1) return 0;
601         traceline(v0, v0 + dvz, TRUE, forent); if(trace_fraction < 1) return 0;
602         traceline(v0 + dvx, v0 + dvx + dvy, TRUE, forent); if(trace_fraction < 1) return 0;
603         traceline(v0 + dvx, v0 + dvx + dvz, TRUE, forent); if(trace_fraction < 1) return 0;
604         traceline(v0 + dvy, v0 + dvy + dvx, TRUE, forent); if(trace_fraction < 1) return 0;
605         traceline(v0 + dvy, v0 + dvy + dvz, TRUE, forent); if(trace_fraction < 1) return 0;
606         traceline(v0 + dvz, v0 + dvz + dvx, TRUE, forent); if(trace_fraction < 1) return 0;
607         traceline(v0 + dvz, v0 + dvz + dvy, TRUE, forent); if(trace_fraction < 1) return 0;
608         traceline(v0 + dvx + dvy, v0 + dvx + dvy + dvz, TRUE, forent); if(trace_fraction < 1) return 0;
609         traceline(v0 + dvx + dvz, v0 + dvx + dvy + dvz, TRUE, forent); if(trace_fraction < 1) return 0;
610         traceline(v0 + dvy + dvz, v0 + dvx + dvy + dvz, TRUE, forent); if(trace_fraction < 1) return 0;
611         return 1;
612 }
613 #endif
614
615 string fixPriorityList(string order, float from, float to, float subtract, float complete)
616 {
617         string neworder;
618         float i, n, w;
619
620         n = tokenize_console(order);
621         neworder = "";
622         for(i = 0; i < n; ++i)
623         {
624                 w = stof(argv(i));
625                 if(w == floor(w))
626                 {
627                         if(w >= from && w <= to)
628                                 neworder = strcat(neworder, ftos(w), " ");
629                         else
630                         {
631                                 w -= subtract;
632                                 if(w >= from && w <= to)
633                                         neworder = strcat(neworder, ftos(w), " ");
634                         }
635                 }
636         }
637
638         if(complete)
639         {
640                 n = tokenize_console(neworder);
641                 for(w = to; w >= from; --w)
642                 {
643                         for(i = 0; i < n; ++i)
644                                 if(stof(argv(i)) == w)
645                                         break;
646                         if(i == n) // not found
647                                 neworder = strcat(neworder, ftos(w), " ");
648                 }
649         }
650         
651         return substring(neworder, 0, strlen(neworder) - 1);
652 }
653
654 string mapPriorityList(string order, string(string) mapfunc)
655 {
656         string neworder;
657         float i, n;
658
659         n = tokenize_console(order);
660         neworder = "";
661         for(i = 0; i < n; ++i)
662                 neworder = strcat(neworder, mapfunc(argv(i)), " ");
663         
664         return substring(neworder, 0, strlen(neworder) - 1);
665 }
666
667 string swapInPriorityList(string order, float i, float j)
668 {
669         string s;
670         float w, n;
671
672         n = tokenize_console(order);
673
674         if(i >= 0 && i < n && j >= 0 && j < n && i != j)
675         {
676                 s = "";
677                 for(w = 0; w < n; ++w)
678                 {
679                         if(w == i)
680                                 s = strcat(s, argv(j), " ");
681                         else if(w == j)
682                                 s = strcat(s, argv(i), " ");
683                         else
684                                 s = strcat(s, argv(w), " ");
685                 }
686                 return substring(s, 0, strlen(s) - 1);
687         }
688         
689         return order;
690 }
691
692 float cvar_value_issafe(string s)
693 {
694         if(strstrofs(s, "\"", 0) >= 0)
695                 return 0;
696         if(strstrofs(s, "\\", 0) >= 0)
697                 return 0;
698         if(strstrofs(s, ";", 0) >= 0)
699                 return 0;
700         if(strstrofs(s, "$", 0) >= 0)
701                 return 0;
702         if(strstrofs(s, "\r", 0) >= 0)
703                 return 0;
704         if(strstrofs(s, "\n", 0) >= 0)
705                 return 0;
706         return 1;
707 }
708
709 #ifndef MENUQC
710 void get_mi_min_max(float mode)
711 {
712         vector mi, ma;
713
714         if(mi_shortname)
715                 strunzone(mi_shortname);
716         mi_shortname = mapname;
717         if(!strcasecmp(substring(mi_shortname, 0, 5), "maps/"))
718                 mi_shortname = substring(mi_shortname, 5, strlen(mi_shortname) - 5);
719         if(!strcasecmp(substring(mi_shortname, strlen(mi_shortname) - 4, 4), ".bsp"))
720                 mi_shortname = substring(mi_shortname, 0, strlen(mi_shortname) - 4);
721         mi_shortname = strzone(mi_shortname);
722
723 #ifdef CSQC
724         mi = world.mins;
725         ma = world.maxs;
726 #else
727         mi = world.absmin;
728         ma = world.absmax;
729 #endif
730
731         mi_min = mi;
732         mi_max = ma;
733         MapInfo_Get_ByName(mi_shortname, 0, 0);
734         if(MapInfo_Map_mins_x < MapInfo_Map_maxs_x)
735         {
736                 mi_min = MapInfo_Map_mins;
737                 mi_max = MapInfo_Map_maxs;
738         }
739         else
740         {
741                 // not specified
742                 if(mode)
743                 {
744                         // be clever
745                         tracebox('1 0 0' * mi_x,
746                                          '0 1 0' * mi_y + '0 0 1' * mi_z,
747                                          '0 1 0' * ma_y + '0 0 1' * ma_z,
748                                          '1 0 0' * ma_x,
749                                          MOVE_WORLDONLY,
750                                          world);
751                         if(!trace_startsolid)
752                                 mi_min_x = trace_endpos_x;
753
754                         tracebox('0 1 0' * mi_y,
755                                          '1 0 0' * mi_x + '0 0 1' * mi_z,
756                                          '1 0 0' * ma_x + '0 0 1' * ma_z,
757                                          '0 1 0' * ma_y,
758                                          MOVE_WORLDONLY,
759                                          world);
760                         if(!trace_startsolid)
761                                 mi_min_y = trace_endpos_y;
762
763                         tracebox('0 0 1' * mi_z,
764                                          '1 0 0' * mi_x + '0 1 0' * mi_y,
765                                          '1 0 0' * ma_x + '0 1 0' * ma_y,
766                                          '0 0 1' * ma_z,
767                                          MOVE_WORLDONLY,
768                                          world);
769                         if(!trace_startsolid)
770                                 mi_min_z = trace_endpos_z;
771
772                         tracebox('1 0 0' * ma_x,
773                                          '0 1 0' * mi_y + '0 0 1' * mi_z,
774                                          '0 1 0' * ma_y + '0 0 1' * ma_z,
775                                          '1 0 0' * mi_x,
776                                          MOVE_WORLDONLY,
777                                          world);
778                         if(!trace_startsolid)
779                                 mi_max_x = trace_endpos_x;
780
781                         tracebox('0 1 0' * ma_y,
782                                          '1 0 0' * mi_x + '0 0 1' * mi_z,
783                                          '1 0 0' * ma_x + '0 0 1' * ma_z,
784                                          '0 1 0' * mi_y,
785                                          MOVE_WORLDONLY,
786                                          world);
787                         if(!trace_startsolid)
788                                 mi_max_y = trace_endpos_y;
789
790                         tracebox('0 0 1' * ma_z,
791                                          '1 0 0' * mi_x + '0 1 0' * mi_y,
792                                          '1 0 0' * ma_x + '0 1 0' * ma_y,
793                                          '0 0 1' * mi_z,
794                                          MOVE_WORLDONLY,
795                                          world);
796                         if(!trace_startsolid)
797                                 mi_max_z = trace_endpos_z;
798                 }
799         }
800 }
801
802 void get_mi_min_max_texcoords(float mode)
803 {
804         vector extend;
805
806         get_mi_min_max(mode);
807
808         mi_picmin = mi_min;
809         mi_picmax = mi_max;
810
811         // extend mi_picmax to get a square aspect ratio
812         // center the map in that area
813         extend = mi_picmax - mi_picmin;
814         if(extend_y > extend_x)
815         {
816                 mi_picmin_x -= (extend_y - extend_x) * 0.5;
817                 mi_picmax_x += (extend_y - extend_x) * 0.5;
818         }
819         else
820         {
821                 mi_picmin_y -= (extend_x - extend_y) * 0.5;
822                 mi_picmax_y += (extend_x - extend_y) * 0.5;
823         }
824
825         // add another some percent
826         extend = (mi_picmax - mi_picmin) * (1 / 64.0);
827         mi_picmin -= extend;
828         mi_picmax += extend;
829
830         // calculate the texcoords
831         mi_pictexcoord0 = mi_pictexcoord1 = mi_pictexcoord2 = mi_pictexcoord3 = '0 0 0';
832         // first the two corners of the origin
833         mi_pictexcoord0_x = (mi_min_x - mi_picmin_x) / (mi_picmax_x - mi_picmin_x);
834         mi_pictexcoord0_y = (mi_min_y - mi_picmin_y) / (mi_picmax_y - mi_picmin_y);
835         mi_pictexcoord2_x = (mi_max_x - mi_picmin_x) / (mi_picmax_x - mi_picmin_x);
836         mi_pictexcoord2_y = (mi_max_y - mi_picmin_y) / (mi_picmax_y - mi_picmin_y);
837         // then the other corners
838         mi_pictexcoord1_x = mi_pictexcoord0_x;
839         mi_pictexcoord1_y = mi_pictexcoord2_y;
840         mi_pictexcoord3_x = mi_pictexcoord2_x;
841         mi_pictexcoord3_y = mi_pictexcoord0_y;
842 }
843 #endif
844
845 float cvar_settemp(string tmp_cvar, string tmp_value)
846 {
847         float created_saved_value;
848         entity e;
849         
850         if not(tmp_cvar || tmp_value)
851         {
852                 dprint("Error: Invalid usage of cvar_settemp(string, string); !\n");
853                 return FALSE;
854         }
855         
856         for(e = world; (e = find(e, classname, "saved_cvar_value")); )
857                 if(e.netname == tmp_cvar)
858                         goto saved; // skip creation
859                         
860         // creating a new entity to keep track of this cvar
861         e = spawn();
862         e.classname = "saved_cvar_value";
863         e.netname = strzone(tmp_cvar);
864         e.message = strzone(cvar_string(tmp_cvar));
865         created_saved_value = TRUE;
866         
867         // an entity for this cvar already exists
868         :saved
869         
870         // update the cvar to the value given
871         cvar_set(tmp_cvar, tmp_value);
872         
873         return created_saved_value;
874 }
875
876 float cvar_settemp_restore()
877 {
878         float i;
879         entity e;
880         while((e = find(world, classname, "saved_cvar_value")))
881         {
882                 cvar_set(e.netname, e.message);
883                 remove(e);
884         }
885         
886         return i;
887 }
888
889 float almost_equals(float a, float b)
890 {
891         float eps;
892         eps = (max(a, -a) + max(b, -b)) * 0.001;
893         if(a - b < eps && b - a < eps)
894                 return TRUE;
895         return FALSE;
896 }
897
898 float almost_in_bounds(float a, float b, float c)
899 {
900         float eps;
901         eps = (max(a, -a) + max(c, -c)) * 0.001;
902         return b == median(a - eps, b, c + eps);
903 }
904
905 float power2of(float e)
906 {
907         return pow(2, e);
908 }
909 float log2of(float x)
910 {
911         // NOTE: generated code
912         if(x > 2048)
913                 if(x > 131072)
914                         if(x > 1048576)
915                                 if(x > 4194304)
916                                         return 23;
917                                 else
918                                         if(x > 2097152)
919                                                 return 22;
920                                         else
921                                                 return 21;
922                         else
923                                 if(x > 524288)
924                                         return 20;
925                                 else
926                                         if(x > 262144)
927                                                 return 19;
928                                         else
929                                                 return 18;
930                 else
931                         if(x > 16384)
932                                 if(x > 65536)
933                                         return 17;
934                                 else
935                                         if(x > 32768)
936                                                 return 16;
937                                         else
938                                                 return 15;
939                         else
940                                 if(x > 8192)
941                                         return 14;
942                                 else
943                                         if(x > 4096)
944                                                 return 13;
945                                         else
946                                                 return 12;
947         else
948                 if(x > 32)
949                         if(x > 256)
950                                 if(x > 1024)
951                                         return 11;
952                                 else
953                                         if(x > 512)
954                                                 return 10;
955                                         else
956                                                 return 9;
957                         else
958                                 if(x > 128)
959                                         return 8;
960                                 else
961                                         if(x > 64)
962                                                 return 7;
963                                         else
964                                                 return 6;
965                 else
966                         if(x > 4)
967                                 if(x > 16)
968                                         return 5;
969                                 else
970                                         if(x > 8)
971                                                 return 4;
972                                         else
973                                                 return 3;
974                         else
975                                 if(x > 2)
976                                         return 2;
977                                 else
978                                         if(x > 1)
979                                                 return 1;
980                                         else
981                                                 return 0;
982 }
983
984 float rgb_mi_ma_to_hue(vector rgb, float mi, float ma)
985 {
986         if(mi == ma)
987                 return 0;
988         else if(ma == rgb_x)
989         {
990                 if(rgb_y >= rgb_z)
991                         return (rgb_y - rgb_z) / (ma - mi);
992                 else
993                         return (rgb_y - rgb_z) / (ma - mi) + 6;
994         }
995         else if(ma == rgb_y)
996                 return (rgb_z - rgb_x) / (ma - mi) + 2;
997         else // if(ma == rgb_z)
998                 return (rgb_x - rgb_y) / (ma - mi) + 4;
999 }
1000
1001 vector hue_mi_ma_to_rgb(float hue, float mi, float ma)
1002 {
1003         vector rgb;
1004
1005         hue -= 6 * floor(hue / 6);
1006
1007         //else if(ma == rgb_x)
1008         //      hue = 60 * (rgb_y - rgb_z) / (ma - mi);
1009         if(hue <= 1)
1010         {
1011                 rgb_x = ma;
1012                 rgb_y = hue * (ma - mi) + mi;
1013                 rgb_z = mi;
1014         }
1015         //else if(ma == rgb_y)
1016         //      hue = 60 * (rgb_z - rgb_x) / (ma - mi) + 120;
1017         else if(hue <= 2)
1018         {
1019                 rgb_x = (2 - hue) * (ma - mi) + mi;
1020                 rgb_y = ma;
1021                 rgb_z = mi;
1022         }
1023         else if(hue <= 3)
1024         {
1025                 rgb_x = mi;
1026                 rgb_y = ma;
1027                 rgb_z = (hue - 2) * (ma - mi) + mi;
1028         }
1029         //else // if(ma == rgb_z)
1030         //      hue = 60 * (rgb_x - rgb_y) / (ma - mi) + 240;
1031         else if(hue <= 4)
1032         {
1033                 rgb_x = mi;
1034                 rgb_y = (4 - hue) * (ma - mi) + mi;
1035                 rgb_z = ma;
1036         }
1037         else if(hue <= 5)
1038         {
1039                 rgb_x = (hue - 4) * (ma - mi) + mi;
1040                 rgb_y = mi;
1041                 rgb_z = ma;
1042         }
1043         //else if(ma == rgb_x)
1044         //      hue = 60 * (rgb_y - rgb_z) / (ma - mi);
1045         else // if(hue <= 6)
1046         {
1047                 rgb_x = ma;
1048                 rgb_y = mi;
1049                 rgb_z = (6 - hue) * (ma - mi) + mi;
1050         }
1051
1052         return rgb;
1053 }
1054
1055 vector rgb_to_hsv(vector rgb)
1056 {
1057         float mi, ma;
1058         vector hsv;
1059
1060         mi = min(rgb_x, rgb_y, rgb_z);
1061         ma = max(rgb_x, rgb_y, rgb_z);
1062
1063         hsv_x = rgb_mi_ma_to_hue(rgb, mi, ma);
1064         hsv_z = ma;
1065
1066         if(ma == 0)
1067                 hsv_y = 0;
1068         else
1069                 hsv_y = 1 - mi/ma;
1070         
1071         return hsv;
1072 }
1073
1074 vector hsv_to_rgb(vector hsv)
1075 {
1076         return hue_mi_ma_to_rgb(hsv_x, hsv_z * (1 - hsv_y), hsv_z);
1077 }
1078
1079 vector rgb_to_hsl(vector rgb)
1080 {
1081         float mi, ma;
1082         vector hsl;
1083
1084         mi = min(rgb_x, rgb_y, rgb_z);
1085         ma = max(rgb_x, rgb_y, rgb_z);
1086
1087         hsl_x = rgb_mi_ma_to_hue(rgb, mi, ma);
1088         
1089         hsl_z = 0.5 * (mi + ma);
1090         if(mi == ma)
1091                 hsl_y = 0;
1092         else if(hsl_z <= 0.5)
1093                 hsl_y = (ma - mi) / (2*hsl_z);
1094         else // if(hsl_z > 0.5)
1095                 hsl_y = (ma - mi) / (2 - 2*hsl_z);
1096         
1097         return hsl;
1098 }
1099
1100 vector hsl_to_rgb(vector hsl)
1101 {
1102         float mi, ma, maminusmi;
1103
1104         if(hsl_z <= 0.5)
1105                 maminusmi = hsl_y * 2 * hsl_z;
1106         else
1107                 maminusmi = hsl_y * (2 - 2 * hsl_z);
1108         
1109         // hsl_z     = 0.5 * mi + 0.5 * ma
1110         // maminusmi =     - mi +       ma
1111         mi = hsl_z - 0.5 * maminusmi;
1112         ma = hsl_z + 0.5 * maminusmi;
1113
1114         return hue_mi_ma_to_rgb(hsl_x, mi, ma);
1115 }
1116
1117 string rgb_to_hexcolor(vector rgb)
1118 {
1119         return
1120                 strcat(
1121                         "^x",
1122                         DEC_TO_HEXDIGIT(floor(rgb_x * 15 + 0.5)),
1123                         DEC_TO_HEXDIGIT(floor(rgb_y * 15 + 0.5)),
1124                         DEC_TO_HEXDIGIT(floor(rgb_z * 15 + 0.5))
1125                 );
1126 }
1127
1128 // requires that m2>m1 in all coordinates, and that m4>m3
1129 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;}
1130
1131 // requires the same, but is a stronger condition
1132 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;}
1133
1134 #ifndef MENUQC
1135 #endif
1136
1137 float textLengthUpToWidth(string theText, float maxWidth, vector theSize, textLengthUpToWidth_widthFunction_t w)
1138 {
1139         // STOP.
1140         // The following function is SLOW.
1141         // For your safety and for the protection of those around you...
1142         // DO NOT CALL THIS AT HOME.
1143         // No really, don't.
1144         if(w(theText, theSize) <= maxWidth)
1145                 return strlen(theText); // yeah!
1146
1147         // binary search for right place to cut string
1148         float ch;
1149         float left, right, middle; // this always works
1150         left = 0;
1151         right = strlen(theText); // this always fails
1152         do
1153         {
1154                 middle = floor((left + right) / 2);
1155                 if(w(substring(theText, 0, middle), theSize) <= maxWidth)
1156                         left = middle;
1157                 else
1158                         right = middle;
1159         }
1160         while(left < right - 1);
1161
1162         if(w("^7", theSize) == 0) // detect color codes support in the width function
1163         {
1164                 // NOTE: when color codes are involved, this binary search is,
1165                 // mathematically, BROKEN. However, it is obviously guaranteed to
1166                 // terminate, as the range still halves each time - but nevertheless, it is
1167                 // guaranteed that it finds ONE valid cutoff place (where "left" is in
1168                 // range, and "right" is outside).
1169                 
1170                 // terencehill: the following code detects truncated ^xrgb tags (e.g. ^x or ^x4)
1171                 // and decrease left on the basis of the chars detected of the truncated tag
1172                 // Even if the ^xrgb tag is not complete/correct, left is decreased
1173                 // (sometimes too much but with a correct result)
1174                 // it fixes also ^[0-9]
1175                 while(left >= 1 && substring(theText, left-1, 1) == "^")
1176                         left-=1;
1177
1178                 if (left >= 2 && substring(theText, left-2, 2) == "^x") // ^x/
1179                         left-=2;
1180                 else if (left >= 3 && substring(theText, left-3, 2) == "^x")
1181                         {
1182                                 ch = str2chr(theText, left-1);
1183                                 if( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') ) // ^xr/
1184                                         left-=3;
1185                         }
1186                 else if (left >= 4 && substring(theText, left-4, 2) == "^x")
1187                         {
1188                                 ch = str2chr(theText, left-2);
1189                                 if ( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') )
1190                                 {
1191                                         ch = str2chr(theText, left-1);
1192                                         if ( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') ) // ^xrg/
1193                                                 left-=4;
1194                                 }
1195                         }
1196         }
1197         
1198         return left;
1199 }
1200
1201 float textLengthUpToLength(string theText, float maxWidth, textLengthUpToLength_lenFunction_t w)
1202 {
1203         // STOP.
1204         // The following function is SLOW.
1205         // For your safety and for the protection of those around you...
1206         // DO NOT CALL THIS AT HOME.
1207         // No really, don't.
1208         if(w(theText) <= maxWidth)
1209                 return strlen(theText); // yeah!
1210
1211         // binary search for right place to cut string
1212         float ch;
1213         float left, right, middle; // this always works
1214         left = 0;
1215         right = strlen(theText); // this always fails
1216         do
1217         {
1218                 middle = floor((left + right) / 2);
1219                 if(w(substring(theText, 0, middle)) <= maxWidth)
1220                         left = middle;
1221                 else
1222                         right = middle;
1223         }
1224         while(left < right - 1);
1225
1226         if(w("^7") == 0) // detect color codes support in the width function
1227         {
1228                 // NOTE: when color codes are involved, this binary search is,
1229                 // mathematically, BROKEN. However, it is obviously guaranteed to
1230                 // terminate, as the range still halves each time - but nevertheless, it is
1231                 // guaranteed that it finds ONE valid cutoff place (where "left" is in
1232                 // range, and "right" is outside).
1233                 
1234                 // terencehill: the following code detects truncated ^xrgb tags (e.g. ^x or ^x4)
1235                 // and decrease left on the basis of the chars detected of the truncated tag
1236                 // Even if the ^xrgb tag is not complete/correct, left is decreased
1237                 // (sometimes too much but with a correct result)
1238                 // it fixes also ^[0-9]
1239                 while(left >= 1 && substring(theText, left-1, 1) == "^")
1240                         left-=1;
1241
1242                 if (left >= 2 && substring(theText, left-2, 2) == "^x") // ^x/
1243                         left-=2;
1244                 else if (left >= 3 && substring(theText, left-3, 2) == "^x")
1245                         {
1246                                 ch = str2chr(theText, left-1);
1247                                 if( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') ) // ^xr/
1248                                         left-=3;
1249                         }
1250                 else if (left >= 4 && substring(theText, left-4, 2) == "^x")
1251                         {
1252                                 ch = str2chr(theText, left-2);
1253                                 if ( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') )
1254                                 {
1255                                         ch = str2chr(theText, left-1);
1256                                         if ( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') ) // ^xrg/
1257                                                 left-=4;
1258                                 }
1259                         }
1260         }
1261         
1262         return left;
1263 }
1264
1265 string find_last_color_code(string s)
1266 {
1267         float start, len, i, carets;
1268         start = strstrofs(s, "^", 0);
1269         if (start == -1) // no caret found
1270                 return "";
1271         len = strlen(s)-1;
1272         for(i = len; i >= start; --i)
1273         {
1274                 if(substring(s, i, 1) != "^")
1275                         continue;
1276
1277                 carets = 1;
1278                 while (i-carets >= start && substring(s, i-carets, 1) == "^")
1279                         ++carets;
1280
1281                 // check if carets aren't all escaped
1282                 if (carets == 1 || mod(carets, 2) == 1) // first check is just an optimization
1283                 {
1284                         if(i+1 <= len)
1285                         if(strstrofs("0123456789", substring(s, i+1, 1), 0) >= 0)
1286                                 return substring(s, i, 2);
1287
1288                         if(i+4 <= len)
1289                         if(substring(s, i+1, 1) == "x")
1290                         if(strstrofs("0123456789abcdefABCDEF", substring(s, i+2, 1), 0) >= 0)
1291                         if(strstrofs("0123456789abcdefABCDEF", substring(s, i+3, 1), 0) >= 0)
1292                         if(strstrofs("0123456789abcdefABCDEF", substring(s, i+4, 1), 0) >= 0)
1293                                 return substring(s, i, 5);
1294                 }
1295                 i -= carets; // this also skips one char before the carets
1296         }
1297
1298         return "";
1299 }
1300
1301 string getWrappedLine(float w, vector theFontSize, textLengthUpToWidth_widthFunction_t tw)
1302 {
1303         float cantake;
1304         float take;
1305         string s;
1306
1307         s = getWrappedLine_remaining;
1308         
1309         if(w <= 0)
1310         {
1311                 getWrappedLine_remaining = string_null;
1312                 return s; // the line has no size ANYWAY, nothing would be displayed.
1313         }
1314
1315         cantake = textLengthUpToWidth(s, w, theFontSize, tw);
1316         if(cantake > 0 && cantake < strlen(s))
1317         {
1318                 take = cantake - 1;
1319                 while(take > 0 && substring(s, take, 1) != " ")
1320                         --take;
1321                 if(take == 0)
1322                 {
1323                         getWrappedLine_remaining = substring(s, cantake, strlen(s) - cantake);
1324                         if(getWrappedLine_remaining == "")
1325                                 getWrappedLine_remaining = string_null;
1326                         else if (tw("^7", theFontSize) == 0)
1327                                 getWrappedLine_remaining = strcat(find_last_color_code(substring(s, 0, cantake)), getWrappedLine_remaining);
1328                         return substring(s, 0, cantake);
1329                 }
1330                 else
1331                 {
1332                         getWrappedLine_remaining = substring(s, take + 1, strlen(s) - take);
1333                         if(getWrappedLine_remaining == "")
1334                                 getWrappedLine_remaining = string_null;
1335                         else if (tw("^7", theFontSize) == 0)
1336                                 getWrappedLine_remaining = strcat(find_last_color_code(substring(s, 0, take)), getWrappedLine_remaining);
1337                         return substring(s, 0, take);
1338                 }
1339         }
1340         else
1341         {
1342                 getWrappedLine_remaining = string_null;
1343                 return s;
1344         }
1345 }
1346
1347 string getWrappedLineLen(float w, textLengthUpToLength_lenFunction_t tw)
1348 {
1349         float cantake;
1350         float take;
1351         string s;
1352
1353         s = getWrappedLine_remaining;
1354         
1355         if(w <= 0)
1356         {
1357                 getWrappedLine_remaining = string_null;
1358                 return s; // the line has no size ANYWAY, nothing would be displayed.
1359         }
1360
1361         cantake = textLengthUpToLength(s, w, tw);
1362         if(cantake > 0 && cantake < strlen(s))
1363         {
1364                 take = cantake - 1;
1365                 while(take > 0 && substring(s, take, 1) != " ")
1366                         --take;
1367                 if(take == 0)
1368                 {
1369                         getWrappedLine_remaining = substring(s, cantake, strlen(s) - cantake);
1370                         if(getWrappedLine_remaining == "")
1371                                 getWrappedLine_remaining = string_null;
1372                         else if (tw("^7") == 0)
1373                                 getWrappedLine_remaining = strcat(find_last_color_code(substring(s, 0, cantake)), getWrappedLine_remaining);
1374                         return substring(s, 0, cantake);
1375                 }
1376                 else
1377                 {
1378                         getWrappedLine_remaining = substring(s, take + 1, strlen(s) - take);
1379                         if(getWrappedLine_remaining == "")
1380                                 getWrappedLine_remaining = string_null;
1381                         else if (tw("^7") == 0)
1382                                 getWrappedLine_remaining = strcat(find_last_color_code(substring(s, 0, take)), getWrappedLine_remaining);
1383                         return substring(s, 0, take);
1384                 }
1385         }
1386         else
1387         {
1388                 getWrappedLine_remaining = string_null;
1389                 return s;
1390         }
1391 }
1392
1393 string textShortenToWidth(string theText, float maxWidth, vector theFontSize, textLengthUpToWidth_widthFunction_t tw)
1394 {
1395         if(tw(theText, theFontSize) <= maxWidth)
1396                 return theText;
1397         else
1398                 return strcat(substring(theText, 0, textLengthUpToWidth(theText, maxWidth - tw("...", theFontSize), theFontSize, tw)), "...");
1399 }
1400
1401 string textShortenToLength(string theText, float maxWidth, textLengthUpToLength_lenFunction_t tw)
1402 {
1403         if(tw(theText) <= maxWidth)
1404                 return theText;
1405         else
1406                 return strcat(substring(theText, 0, textLengthUpToLength(theText, maxWidth - tw("..."), tw)), "...");
1407 }
1408
1409 float isGametypeInFilter(float gt, float tp, float ts, string pattern)
1410 {
1411         string subpattern, subpattern2, subpattern3, subpattern4;
1412         subpattern = strcat(",", MapInfo_Type_ToString(gt), ",");
1413         if(tp)
1414                 subpattern2 = ",teams,";
1415         else
1416                 subpattern2 = ",noteams,";
1417         if(ts)
1418                 subpattern3 = ",teamspawns,";
1419         else
1420                 subpattern3 = ",noteamspawns,";
1421         if(gt == MAPINFO_TYPE_RACE || gt == MAPINFO_TYPE_CTS)
1422                 subpattern4 = ",race,";
1423         else
1424                 subpattern4 = string_null;
1425
1426         if(substring(pattern, 0, 1) == "-")
1427         {
1428                 pattern = substring(pattern, 1, strlen(pattern) - 1);
1429                 if(strstrofs(strcat(",", pattern, ","), subpattern, 0) >= 0)
1430                         return 0;
1431                 if(strstrofs(strcat(",", pattern, ","), subpattern2, 0) >= 0)
1432                         return 0;
1433                 if(strstrofs(strcat(",", pattern, ","), subpattern3, 0) >= 0)
1434                         return 0;
1435                 if(subpattern4 && strstrofs(strcat(",", pattern, ","), subpattern4, 0) >= 0)
1436                         return 0;
1437         }
1438         else
1439         {
1440                 if(substring(pattern, 0, 1) == "+")
1441                         pattern = substring(pattern, 1, strlen(pattern) - 1);
1442                 if(strstrofs(strcat(",", pattern, ","), subpattern, 0) < 0)
1443                 if(strstrofs(strcat(",", pattern, ","), subpattern2, 0) < 0)
1444                 if(strstrofs(strcat(",", pattern, ","), subpattern3, 0) < 0)
1445                 if((!subpattern4) || strstrofs(strcat(",", pattern, ","), subpattern4, 0) < 0)
1446                         return 0;
1447         }
1448         return 1;
1449 }
1450
1451 void shuffle(float n, swapfunc_t swap, entity pass)
1452 {
1453         float i, j;
1454         for(i = 1; i < n; ++i)
1455         {
1456                 // swap i-th item at a random position from 0 to i
1457                 // proof for even distribution:
1458                 //   n = 1: obvious
1459                 //   n -> n+1:
1460                 //     item n+1 gets at any position with chance 1/(n+1)
1461                 //     all others will get their 1/n chance reduced by factor n/(n+1)
1462                 //     to be on place n+1, their chance will be 1/(n+1)
1463                 //     1/n * n/(n+1) = 1/(n+1)
1464                 //     q.e.d.
1465                 j = floor(random() * (i + 1));
1466                 if(j != i)
1467                         swap(j, i, pass);
1468         }
1469 }
1470
1471 string substring_range(string s, float b, float e)
1472 {
1473         return substring(s, b, e - b);
1474 }
1475
1476 string swapwords(string str, float i, float j)
1477 {
1478         float n;
1479         string s1, s2, s3, s4, s5;
1480         float si, ei, sj, ej, s0, en;
1481         n = tokenizebyseparator(str, " "); // must match g_maplist processing in ShuffleMaplist and "shuffle"
1482         si = argv_start_index(i);
1483         sj = argv_start_index(j);
1484         ei = argv_end_index(i);
1485         ej = argv_end_index(j);
1486         s0 = argv_start_index(0);
1487         en = argv_end_index(n-1);
1488         s1 = substring_range(str, s0, si);
1489         s2 = substring_range(str, si, ei);
1490         s3 = substring_range(str, ei, sj);
1491         s4 = substring_range(str, sj, ej);
1492         s5 = substring_range(str, ej, en);
1493         return strcat(s1, s4, s3, s2, s5);
1494 }
1495
1496 string _shufflewords_str;
1497 void _shufflewords_swapfunc(float i, float j, entity pass)
1498 {
1499         _shufflewords_str = swapwords(_shufflewords_str, i, j);
1500 }
1501 string shufflewords(string str)
1502 {
1503         float n;
1504         _shufflewords_str = str;
1505         n = tokenizebyseparator(str, " ");
1506         shuffle(n, _shufflewords_swapfunc, world);
1507         str = _shufflewords_str;
1508         _shufflewords_str = string_null;
1509         return str;
1510 }
1511
1512 vector solve_quadratic(float a, float b, float c) // ax^2 + bx + c = 0
1513 {
1514         vector v;
1515         float D;
1516         v = '0 0 0';
1517         if(a == 0)
1518         {
1519                 if(b != 0)
1520                 {
1521                         v_x = v_y = -c / b;
1522                         v_z = 1;
1523                 }
1524                 else
1525                 {
1526                         if(c == 0)
1527                         {
1528                                 // actually, every number solves the equation!
1529                                 v_z = 1;
1530                         }
1531                 }
1532         }
1533         else
1534         {
1535                 D = b*b - 4*a*c;
1536                 if(D >= 0)
1537                 {
1538                         D = sqrt(D);
1539                         if(a > 0) // put the smaller solution first
1540                         {
1541                                 v_x = ((-b)-D) / (2*a);
1542                                 v_y = ((-b)+D) / (2*a);
1543                         }
1544                         else
1545                         {
1546                                 v_x = (-b+D) / (2*a);
1547                                 v_y = (-b-D) / (2*a);
1548                         }
1549                         v_z = 1;
1550                 }
1551                 else
1552                 {
1553                         // complex solutions!
1554                         D = sqrt(-D);
1555                         v_x = -b / (2*a);
1556                         if(a > 0)
1557                                 v_y =  D / (2*a);
1558                         else
1559                                 v_y = -D / (2*a);
1560                         v_z = 0;
1561                 }
1562         }
1563         return v;
1564 }
1565
1566 void check_unacceptable_compiler_bugs()
1567 {
1568         if(cvar("_allow_unacceptable_compiler_bugs"))
1569                 return;
1570         tokenize_console("foo bar");
1571         if(strcat(argv(0), substring("foo bar", 4, 7 - argv_start_index(1))) == "barbar")
1572                 error("fteqcc bug introduced with revision 3178 detected. Please upgrade fteqcc to a later revision, downgrade fteqcc to revision 3177, or pester Spike until he fixes it. You can set _allow_unacceptable_compiler_bugs 1 to skip this check, but expect stuff to be horribly broken then.");
1573 }
1574
1575 float compressShotOrigin(vector v)
1576 {
1577         float x, y, z;
1578         x = rint(v_x * 2);
1579         y = rint(v_y * 4) + 128;
1580         z = rint(v_z * 4) + 128;
1581         if(x > 255 || x < 0)
1582         {
1583                 print("shot origin ", vtos(v), " x out of bounds\n");
1584                 x = bound(0, x, 255);
1585         }
1586         if(y > 255 || y < 0)
1587         {
1588                 print("shot origin ", vtos(v), " y out of bounds\n");
1589                 y = bound(0, y, 255);
1590         }
1591         if(z > 255 || z < 0)
1592         {
1593                 print("shot origin ", vtos(v), " z out of bounds\n");
1594                 z = bound(0, z, 255);
1595         }
1596         return x * 0x10000 + y * 0x100 + z;
1597 }
1598 vector decompressShotOrigin(float f)
1599 {
1600         vector v;
1601         v_x = ((f & 0xFF0000) / 0x10000) / 2;
1602         v_y = ((f & 0xFF00) / 0x100 - 128) / 4;
1603         v_z = ((f & 0xFF) - 128) / 4;
1604         return v;
1605 }
1606
1607 void heapsort(float n, swapfunc_t swap, comparefunc_t cmp, entity pass)
1608 {
1609         float start, end, root, child;
1610
1611         // heapify
1612         start = floor((n - 2) / 2);
1613         while(start >= 0)
1614         {
1615                 // siftdown(start, count-1);
1616                 root = start;
1617                 while(root * 2 + 1 <= n-1)
1618                 {
1619                         child = root * 2 + 1;
1620                         if(child < n-1)
1621                                 if(cmp(child, child+1, pass) < 0)
1622                                         ++child;
1623                         if(cmp(root, child, pass) < 0)
1624                         {
1625                                 swap(root, child, pass);
1626                                 root = child;
1627                         }
1628                         else
1629                                 break;
1630                 }
1631                 // end of siftdown
1632                 --start;
1633         }
1634
1635         // extract
1636         end = n - 1;
1637         while(end > 0)
1638         {
1639                 swap(0, end, pass);
1640                 --end;
1641                 // siftdown(0, end);
1642                 root = 0;
1643                 while(root * 2 + 1 <= end)
1644                 {
1645                         child = root * 2 + 1;
1646                         if(child < end && cmp(child, child+1, pass) < 0)
1647                                 ++child;
1648                         if(cmp(root, child, pass) < 0)
1649                         {
1650                                 swap(root, child, pass);
1651                                 root = child;
1652                         }
1653                         else
1654                                 break;
1655                 }
1656                 // end of siftdown
1657         }
1658 }
1659
1660 void RandomSelection_Init()
1661 {
1662         RandomSelection_totalweight = 0;
1663         RandomSelection_chosen_ent = world;
1664         RandomSelection_chosen_float = 0;
1665         RandomSelection_chosen_string = string_null;
1666         RandomSelection_best_priority = -1;
1667 }
1668 void RandomSelection_Add(entity e, float f, string s, float weight, float priority)
1669 {
1670         if(priority > RandomSelection_best_priority)
1671         {
1672                 RandomSelection_best_priority = priority;
1673                 RandomSelection_chosen_ent = e;
1674                 RandomSelection_chosen_float = f;
1675                 RandomSelection_chosen_string = s;
1676                 RandomSelection_totalweight = weight;
1677         }
1678         else if(priority == RandomSelection_best_priority)
1679         {
1680                 RandomSelection_totalweight += weight;
1681                 if(random() * RandomSelection_totalweight <= weight)
1682                 {
1683                         RandomSelection_chosen_ent = e;
1684                         RandomSelection_chosen_float = f;
1685                         RandomSelection_chosen_string = s;
1686                 }
1687         }
1688 }
1689
1690 vector healtharmor_maxdamage(float h, float a, float armorblock)
1691 {
1692         // NOTE: we'll always choose the SMALLER value...
1693         float healthdamage, armordamage, armorideal;
1694         vector v;
1695         healthdamage = (h - 1) / (1 - armorblock); // damage we can take if we could use more health
1696         armordamage = a + (h - 1); // damage we can take if we could use more armor
1697         armorideal = healthdamage * armorblock;
1698         v_y = armorideal;
1699         if(armordamage < healthdamage)
1700         {
1701                 v_x = armordamage;
1702                 v_z = 1;
1703         }
1704         else
1705         {
1706                 v_x = healthdamage;
1707                 v_z = 0;
1708         }
1709         return v;
1710 }
1711
1712 vector healtharmor_applydamage(float a, float armorblock, float damage)
1713 {
1714         vector v;
1715         v_y = bound(0, damage * armorblock, a); // save
1716         v_x = bound(0, damage - v_y, damage); // take
1717         v_z = 0;
1718         return v;
1719 }
1720
1721 string getcurrentmod()
1722 {
1723         float n;
1724         string m;
1725         m = cvar_string("fs_gamedir");
1726         n = tokenize_console(m);
1727         if(n == 0)
1728                 return "data";
1729         else
1730                 return argv(n - 1);
1731 }
1732
1733 #ifndef MENUQC
1734 #ifdef CSQC
1735 float ReadInt24_t()
1736 {
1737         float v;
1738         v = ReadShort() * 256; // note: this is signed
1739         v += ReadByte(); // note: this is unsigned
1740         return v;
1741 }
1742 #else
1743 void WriteInt24_t(float dst, float val)
1744 {
1745         float v;
1746         WriteShort(dst, (v = floor(val / 256)));
1747         WriteByte(dst, val - v * 256); // 0..255
1748 }
1749 #endif
1750 #endif
1751
1752 float float2range11(float f)
1753 {
1754         // continuous function mapping all reals into -1..1
1755         return f / (fabs(f) + 1);
1756 }
1757
1758 float float2range01(float f)
1759 {
1760         // continuous function mapping all reals into 0..1
1761         return 0.5 + 0.5 * float2range11(f);
1762 }
1763
1764 // from the GNU Scientific Library
1765 float gsl_ran_gaussian_lastvalue;
1766 float gsl_ran_gaussian_lastvalue_set;
1767 float gsl_ran_gaussian(float sigma)
1768 {
1769         float a, b;
1770         if(gsl_ran_gaussian_lastvalue_set)
1771         {
1772                 gsl_ran_gaussian_lastvalue_set = 0;
1773                 return sigma * gsl_ran_gaussian_lastvalue;
1774         }
1775         else
1776         {
1777                 a = random() * 2 * M_PI;
1778                 b = sqrt(-2 * log(random()));
1779                 gsl_ran_gaussian_lastvalue = cos(a) * b;
1780                 gsl_ran_gaussian_lastvalue_set = 1;
1781                 return sigma * sin(a) * b;
1782         }
1783 }
1784
1785 string car(string s)
1786 {
1787         float o;
1788         o = strstrofs(s, " ", 0);
1789         if(o < 0)
1790                 return s;
1791         return substring(s, 0, o);
1792 }
1793 string cdr(string s)
1794 {
1795         float o;
1796         o = strstrofs(s, " ", 0);
1797         if(o < 0)
1798                 return string_null;
1799         return substring(s, o + 1, strlen(s) - (o + 1));
1800 }
1801 float matchacl(string acl, string str)
1802 {
1803         string t, s;
1804         float r, d;
1805         r = 0;
1806         while(acl)
1807         {
1808                 t = car(acl); acl = cdr(acl);
1809                 d = 1;
1810                 if(substring(t, 0, 1) == "-")
1811                 {
1812                         d = -1;
1813                         t = substring(t, 1, strlen(t) - 1);
1814                 }
1815                 else if(substring(t, 0, 1) == "+")
1816                         t = substring(t, 1, strlen(t) - 1);
1817                 if(substring(t, -1, 1) == "*")
1818                 {
1819                         t = substring(t, 0, strlen(t) - 1);
1820                         s = substring(s, 0, strlen(t));
1821                 }
1822                 else
1823                         s = str;
1824
1825                 if(s == t)
1826                 {
1827                         r = d;
1828                 }
1829         }
1830         return r;
1831 }
1832 float startsWith(string haystack, string needle)
1833 {
1834         return substring(haystack, 0, strlen(needle)) == needle;
1835 }
1836 float startsWithNocase(string haystack, string needle)
1837 {
1838         return strcasecmp(substring(haystack, 0, strlen(needle)), needle) == 0;
1839 }
1840
1841 string get_model_datafilename(string m, float sk, string fil)
1842 {
1843         if(m)
1844                 m = strcat(m, "_");
1845         else
1846                 m = "models/player/*_";
1847         if(sk >= 0)
1848                 m = strcat(m, ftos(sk));
1849         else
1850                 m = strcat(m, "*");
1851         return strcat(m, ".", fil);
1852 }
1853
1854 float get_model_parameters(string m, float sk)
1855 {
1856         string fn, s, c;
1857         float fh;
1858
1859         get_model_parameters_modelname = string_null;
1860         get_model_parameters_modelskin = -1;
1861         get_model_parameters_name = string_null;
1862         get_model_parameters_species = -1;
1863         get_model_parameters_sex = string_null;
1864         get_model_parameters_weight = -1;
1865         get_model_parameters_age = -1;
1866         get_model_parameters_desc = string_null;
1867
1868         if not(m)
1869                 return 1;
1870         if(sk < 0)
1871         {
1872                 if(substring(m, -4, -1) != ".txt")
1873                         return 0;
1874                 if(substring(m, -6, 1) != "_")
1875                         return 0;
1876                 sk = stof(substring(m, -5, 1));
1877                 m = substring(m, 0, -7);
1878         }
1879
1880         fn = get_model_datafilename(m, sk, "txt");
1881         fh = fopen(fn, FILE_READ);
1882         if(fh < 0)
1883         {
1884                 sk = 0;
1885                 fn = get_model_datafilename(m, sk, "txt");
1886                 fh = fopen(fn, FILE_READ);
1887                 if(fh < 0)
1888                         return 0;
1889         }
1890
1891         get_model_parameters_modelname = m;
1892         get_model_parameters_modelskin = sk;
1893         while((s = fgets(fh)))
1894         {
1895                 if(s == "")
1896                         break; // next lines will be description
1897                 c = car(s);
1898                 s = cdr(s);
1899                 if(c == "name")
1900                         get_model_parameters_name = s;
1901                 if(c == "species")
1902                         switch(s)
1903                         {
1904                                 case "human":       get_model_parameters_species = SPECIES_HUMAN;       break;
1905                                 case "alien":       get_model_parameters_species = SPECIES_ALIEN;       break;
1906                                 case "robot_shiny": get_model_parameters_species = SPECIES_ROBOT_SHINY; break;
1907                                 case "robot_rusty": get_model_parameters_species = SPECIES_ROBOT_RUSTY; break;
1908                                 case "robot_solid": get_model_parameters_species = SPECIES_ROBOT_SOLID; break;
1909                                 case "animal":      get_model_parameters_species = SPECIES_ANIMAL;      break;
1910                                 case "reserved":    get_model_parameters_species = SPECIES_RESERVED;    break;
1911                         }
1912                 if(c == "sex")
1913                         get_model_parameters_sex = s;
1914                 if(c == "weight")
1915                         get_model_parameters_weight = stof(s);
1916                 if(c == "age")
1917                         get_model_parameters_age = stof(s);
1918         }
1919
1920         while((s = fgets(fh)))
1921         {
1922                 if(get_model_parameters_desc)
1923                         get_model_parameters_desc = strcat(get_model_parameters_desc, "\n");
1924                 if(s != "")
1925                         get_model_parameters_desc = strcat(get_model_parameters_desc, s);
1926         }
1927
1928         fclose(fh);
1929
1930         return 1;
1931 }
1932
1933 vector vec2(vector v)
1934 {
1935         v_z = 0;
1936         return v;
1937 }
1938
1939 #ifndef MENUQC
1940 vector NearestPointOnBox(entity box, vector org)
1941 {
1942         vector m1, m2, nearest;
1943
1944         m1 = box.mins + box.origin;
1945         m2 = box.maxs + box.origin;
1946
1947         nearest_x = bound(m1_x, org_x, m2_x);
1948         nearest_y = bound(m1_y, org_y, m2_y);
1949         nearest_z = bound(m1_z, org_z, m2_z);
1950
1951         return nearest;
1952 }
1953 #endif
1954
1955 float vercmp_recursive(string v1, string v2)
1956 {
1957         float dot1, dot2;
1958         string s1, s2;
1959         float r;
1960
1961         dot1 = strstrofs(v1, ".", 0);
1962         dot2 = strstrofs(v2, ".", 0);
1963         if(dot1 == -1)
1964                 s1 = v1;
1965         else
1966                 s1 = substring(v1, 0, dot1);
1967         if(dot2 == -1)
1968                 s2 = v2;
1969         else
1970                 s2 = substring(v2, 0, dot2);
1971
1972         r = stof(s1) - stof(s2);
1973         if(r != 0)
1974                 return r;
1975
1976         r = strcasecmp(s1, s2);
1977         if(r != 0)
1978                 return r;
1979
1980         if(dot1 == -1)
1981                 if(dot2 == -1)
1982                         return 0;
1983                 else
1984                         return -1;
1985         else
1986                 if(dot2 == -1)
1987                         return 1;
1988                 else
1989                         return vercmp_recursive(substring(v1, dot1 + 1, 999), substring(v2, dot2 + 1, 999));
1990 }
1991
1992 float vercmp(string v1, string v2)
1993 {
1994         if(strcasecmp(v1, v2) == 0) // early out check
1995                 return 0;
1996
1997         // "git" beats all
1998         if(v1 == "git")
1999                 return 1;
2000         if(v2 == "git")
2001                 return -1;
2002
2003         return vercmp_recursive(v1, v2);
2004 }
2005
2006 float u8_strsize(string s)
2007 {
2008         float l, i, c;
2009         l = 0;
2010         for(i = 0; ; ++i)
2011         {
2012                 c = str2chr(s, i);
2013                 if(c <= 0)
2014                         break;
2015                 ++l;
2016                 if(c >= 0x80)
2017                         ++l;
2018                 if(c >= 0x800)
2019                         ++l;
2020                 if(c >= 0x10000)
2021                         ++l;
2022         }
2023         return l;
2024 }
2025
2026 // translation helpers
2027 string language_filename(string s)
2028 {
2029         string fn;
2030         float fh;
2031         fn = prvm_language;
2032         if(fn == "" || fn == "dump")
2033                 return s;
2034         fn = strcat(s, ".", fn);
2035         if((fh = fopen(fn, FILE_READ)) >= 0)
2036         {
2037                 fclose(fh);
2038                 return fn;
2039         }
2040         return s;
2041 }
2042 string CTX(string s)
2043 {
2044         float p = strstrofs(s, "^", 0);
2045         if(p < 0)
2046                 return s;
2047         return substring(s, p+1, -1);
2048 }
2049
2050 // x-encoding (encoding as zero length invisible string)
2051 const string XENCODE_2  = "xX";
2052 const string XENCODE_22 = "0123456789abcdefABCDEF";
2053 string xencode(float f)
2054 {
2055         float a, b, c, d;
2056         d = mod(f, 22); f = floor(f / 22);
2057         c = mod(f, 22); f = floor(f / 22);
2058         b = mod(f, 22); f = floor(f / 22);
2059         a = mod(f,  2); // f = floor(f /  2);
2060         return strcat(
2061                 "^",
2062                 substring(XENCODE_2,  a, 1),
2063                 substring(XENCODE_22, b, 1),
2064                 substring(XENCODE_22, c, 1),
2065                 substring(XENCODE_22, d, 1)
2066         );
2067 }
2068 float xdecode(string s)
2069 {
2070         float a, b, c, d;
2071         if(substring(s, 0, 1) != "^")
2072                 return -1;
2073         if(strlen(s) < 5)
2074                 return -1;
2075         a = strstrofs(XENCODE_2,  substring(s, 1, 1), 0);
2076         b = strstrofs(XENCODE_22, substring(s, 2, 1), 0);
2077         c = strstrofs(XENCODE_22, substring(s, 3, 1), 0);
2078         d = strstrofs(XENCODE_22, substring(s, 4, 1), 0);
2079         if(a < 0 || b < 0 || c < 0 || d < 0)
2080                 return -1;
2081         return ((a * 22 + b) * 22 + c) * 22 + d;
2082 }
2083
2084 float lowestbit(float f)
2085 {
2086         f &~= f * 2;
2087         f &~= f * 4;
2088         f &~= f * 16;
2089         f &~= f * 256;
2090         f &~= f * 65536;
2091         return f;
2092 }
2093
2094 /*
2095 string strlimitedlen(string input, string truncation, float strip_colors, float limit)
2096 {
2097         if(strlen((strip_colors ? strdecolorize(input) : input)) <= limit)
2098                 return input;
2099         else
2100                 return strcat(substring(input, 0, (strlen(input) - strlen(truncation))), truncation);
2101 }*/
2102
2103 // escape the string to make it safe for consoles
2104 string MakeConsoleSafe(string input)
2105 {
2106         input = strreplace("\n", "", input);
2107         input = strreplace("\\", "\\\\", input);
2108         input = strreplace("$", "$$", input);
2109         input = strreplace("\"", "\\\"", input);
2110         return input;
2111 }
2112
2113 #ifndef MENUQC
2114 // get true/false value of a string with multiple different inputs
2115 float InterpretBoolean(string input)
2116 {
2117         switch(strtolower(input))
2118         {
2119                 case "yes":
2120                 case "true":
2121                 case "on":
2122                         return TRUE;
2123                 
2124                 case "no":
2125                 case "false":
2126                 case "off":
2127                         return FALSE;
2128                 
2129                 default: return stof(input);
2130         }
2131 }
2132 #endif
2133
2134 #ifdef CSQC
2135 entity ReadCSQCEntity()
2136 {
2137         float f;
2138         f = ReadShort();
2139         if(f == 0)
2140                 return world;
2141         return findfloat(world, entnum, f);
2142 }
2143 #endif
2144
2145 float shutdown_running;
2146 #ifdef SVQC
2147 void SV_Shutdown()
2148 #endif
2149 #ifdef CSQC
2150 void CSQC_Shutdown()
2151 #endif
2152 #ifdef MENUQC
2153 void m_shutdown()
2154 #endif
2155 {
2156         if(shutdown_running)
2157         {
2158                 print("Recursive shutdown detected! Only restoring cvars...\n");
2159         }
2160         else
2161         {
2162                 shutdown_running = 1;
2163                 Shutdown();
2164         }
2165         cvar_settemp_restore(); // this must be done LAST, but in any case
2166 }