]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/common/util.qc
e5eadc4525bf77e1f7d201abbfdb303dcfd749ef
[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 #ifndef SVQC
43 string draw_UseSkinFor(string pic)
44 {
45         if(substring(pic, 0, 1) == "/")
46                 return substring(pic, 1, strlen(pic)-1);
47         else
48                 return strcat(draw_currentSkin, "/", pic);
49 }
50 #endif
51
52 string unescape(string in)
53 {
54         float i, len;
55         string str, s;
56
57         // but it doesn't seem to be necessary in my tests at least
58         in = strzone(in);
59
60         len = strlen(in);
61         str = "";
62         for(i = 0; i < len; ++i)
63         {
64                 s = substring(in, i, 1);
65                 if(s == "\\")
66                 {
67                         s = substring(in, i+1, 1);
68                         if(s == "n")
69                                 str = strcat(str, "\n");
70                         else if(s == "\\")
71                                 str = strcat(str, "\\");
72                         else
73                                 str = strcat(str, substring(in, i, 2));
74                         ++i;
75                 } else
76                         str = strcat(str, s);
77         }
78
79         strunzone(in);
80         return str;
81 }
82
83 void wordwrap_cb(string s, float l, void(string) callback)
84 {
85         string c;
86         float lleft, i, j, wlen;
87
88         s = strzone(s);
89         lleft = l;
90         for (i = 0;i < strlen(s);++i)
91         {
92                 if (substring(s, i, 2) == "\\n")
93                 {
94                         callback("\n");
95                         lleft = l;
96                         ++i;
97                 }
98                 else if (substring(s, i, 1) == "\n")
99                 {
100                         callback("\n");
101                         lleft = l;
102                 }
103                 else if (substring(s, i, 1) == " ")
104                 {
105                         if (lleft > 0)
106                         {
107                                 callback(" ");
108                                 lleft = lleft - 1;
109                         }
110                 }
111                 else
112                 {
113                         for (j = i+1;j < strlen(s);++j)
114                                 //    ^^ this skips over the first character of a word, which
115                                 //       is ALWAYS part of the word
116                                 //       this is safe since if i+1 == strlen(s), i will become
117                                 //       strlen(s)-1 at the end of this block and the function
118                                 //       will terminate. A space can't be the first character we
119                                 //       read here, and neither can a \n be the start, since these
120                                 //       two cases have been handled above.
121                         {
122                                 c = substring(s, j, 1);
123                                 if (c == " ")
124                                         break;
125                                 if (c == "\\")
126                                         break;
127                                 if (c == "\n")
128                                         break;
129                                 // we need to keep this tempstring alive even if substring is
130                                 // called repeatedly, so call strcat even though we're not
131                                 // doing anything
132                                 callback("");
133                         }
134                         wlen = j - i;
135                         if (lleft < wlen)
136                         {
137                                 callback("\n");
138                                 lleft = l;
139                         }
140                         callback(substring(s, i, wlen));
141                         lleft = lleft - wlen;
142                         i = j - 1;
143                 }
144         }
145         strunzone(s);
146 }
147
148 float dist_point_line(vector p, vector l0, vector ldir)
149 {
150         ldir = normalize(ldir);
151
152         // remove the component in line direction
153         p = p - (p * ldir) * ldir;
154
155         // vlen of the remaining vector
156         return vlen(p);
157 }
158
159 void depthfirst(entity start, .entity up, .entity downleft, .entity right, void(entity, entity) funcPre, void(entity, entity) funcPost, entity pass)
160 {
161         entity e;
162         e = start;
163         funcPre(pass, e);
164         while(e.downleft)
165         {
166                 e = e.downleft;
167                 funcPre(pass, e);
168         }
169         funcPost(pass, e);
170         while(e != start)
171         {
172                 if(e.right)
173                 {
174                         e = e.right;
175                         funcPre(pass, e);
176                         while(e.downleft)
177                         {
178                                 e = e.downleft;
179                                 funcPre(pass, e);
180                         }
181                 }
182                 else
183                         e = e.up;
184                 funcPost(pass, e);
185         }
186 }
187
188 float median(float a, float b, float c)
189 {
190         if(a < c)
191                 return bound(a, b, c);
192         return bound(c, b, a);
193 }
194
195 // converts a number to a string with the indicated number of decimals
196 // works for up to 10 decimals!
197 string ftos_decimals(float number, float decimals)
198 {
199         // inhibit stupid negative zero
200         if(number == 0)
201                 number = 0;
202         // we have sprintf...
203         return sprintf("%.*f", decimals, number);
204 }
205
206 vector colormapPaletteColor(float c, float isPants)
207 {
208         switch(c)
209         {
210                 case  0: return '1.000000 1.000000 1.000000';
211                 case  1: return '1.000000 0.333333 0.000000';
212                 case  2: return '0.000000 1.000000 0.501961';
213                 case  3: return '0.000000 1.000000 0.000000';
214                 case  4: return '1.000000 0.000000 0.000000';
215                 case  5: return '0.000000 0.666667 1.000000';
216                 case  6: return '0.000000 1.000000 1.000000';
217                 case  7: return '0.501961 1.000000 0.000000';
218                 case  8: return '0.501961 0.000000 1.000000';
219                 case  9: return '1.000000 0.000000 1.000000';
220                 case 10: return '1.000000 0.000000 0.501961';
221                 case 11: return '0.000000 0.000000 1.000000';
222                 case 12: return '1.000000 1.000000 0.000000';
223                 case 13: return '0.000000 0.333333 1.000000';
224                 case 14: return '1.000000 0.666667 0.000000';
225                 case 15:
226                         if(isPants)
227                                 return
228                                           '1 0 0' * (0.502 + 0.498 * sin(time / 2.7182818285 + 0.0000000000))
229                                         + '0 1 0' * (0.502 + 0.498 * sin(time / 2.7182818285 + 2.0943951024))
230                                         + '0 0 1' * (0.502 + 0.498 * sin(time / 2.7182818285 + 4.1887902048));
231                         else
232                                 return
233                                           '1 0 0' * (0.502 + 0.498 * sin(time / 3.1415926536 + 5.2359877560))
234                                         + '0 1 0' * (0.502 + 0.498 * sin(time / 3.1415926536 + 3.1415926536))
235                                         + '0 0 1' * (0.502 + 0.498 * sin(time / 3.1415926536 + 1.0471975512));
236                 default: return '0.000 0.000 0.000';
237         }
238 }
239
240 // unzone the string, and return it as tempstring. Safe to be called on string_null
241 string fstrunzone(string s)
242 {
243         string sc;
244         if (!s)
245                 return s;
246         sc = strcat(s, "");
247         strunzone(s);
248         return sc;
249 }
250
251 float fexists(string f)
252 {
253     float fh;
254     fh = fopen(f, FILE_READ);
255     if (fh < 0)
256         return FALSE;
257     fclose(fh);
258     return TRUE;
259 }
260
261 // Databases (hash tables)
262 const float DB_BUCKETS = 8192;
263 void db_save(float db, string pFilename)
264 {
265         float fh, i, n;
266         fh = fopen(pFilename, FILE_WRITE);
267         if(fh < 0)
268         {
269                 print(strcat("^1Can't write DB to ", pFilename));
270                 return;
271         }
272         n = buf_getsize(db);
273         fputs(fh, strcat(ftos(DB_BUCKETS), "\n"));
274         for(i = 0; i < n; ++i)
275                 fputs(fh, strcat(bufstr_get(db, i), "\n"));
276         fclose(fh);
277 }
278
279 float db_create()
280 {
281         return buf_create();
282 }
283
284 float db_load(string pFilename)
285 {
286         float db, fh, i, j, n;
287         string l;
288         db = buf_create();
289         if(db < 0)
290                 return -1;
291         fh = fopen(pFilename, FILE_READ);
292         if(fh < 0)
293                 return db;
294         l = fgets(fh);
295         if(stof(l) == DB_BUCKETS)
296         {
297                 i = 0;
298                 while((l = fgets(fh)))
299                 {
300                         if(l != "")
301                                 bufstr_set(db, i, l);
302                         ++i;
303                 }
304         }
305         else
306         {
307                 // different count of buckets, or a dump?
308                 // need to reorganize the database then (SLOW)
309                 //
310                 // note: we also parse the first line (l) in case the DB file is
311                 // missing the bucket count
312                 do
313                 {
314                         n = tokenizebyseparator(l, "\\");
315                         for(j = 2; j < n; j += 2)
316                                 db_put(db, argv(j-1), uri_unescape(argv(j)));
317                 }
318                 while((l = fgets(fh)));
319         }
320         fclose(fh);
321         return db;
322 }
323
324 void db_dump(float db, string pFilename)
325 {
326         float fh, i, j, n, m;
327         fh = fopen(pFilename, FILE_WRITE);
328         if(fh < 0)
329                 error(strcat("Can't dump DB to ", pFilename));
330         n = buf_getsize(db);
331         fputs(fh, "0\n");
332         for(i = 0; i < n; ++i)
333         {
334                 m = tokenizebyseparator(bufstr_get(db, i), "\\");
335                 for(j = 2; j < m; j += 2)
336                         fputs(fh, strcat("\\", argv(j-1), "\\", argv(j), "\n"));
337         }
338         fclose(fh);
339 }
340
341 void db_close(float db)
342 {
343         buf_del(db);
344 }
345
346 string db_get(float db, string pKey)
347 {
348         float h;
349         h = crc16(FALSE, pKey) % DB_BUCKETS;
350         return uri_unescape(infoget(bufstr_get(db, h), pKey));
351 }
352
353 void db_put(float db, string pKey, string pValue)
354 {
355         float h;
356         h = crc16(FALSE, pKey) % DB_BUCKETS;
357         bufstr_set(db, h, infoadd(bufstr_get(db, h), pKey, uri_escape(pValue)));
358 }
359
360 void db_test()
361 {
362         float db, i;
363         print("LOAD...\n");
364         db = db_load("foo.db");
365         print("LOADED. FILL...\n");
366         for(i = 0; i < DB_BUCKETS; ++i)
367                 db_put(db, ftos(random()), "X");
368         print("FILLED. SAVE...\n");
369         db_save(db, "foo.db");
370         print("SAVED. CLOSE...\n");
371         db_close(db);
372         print("CLOSED.\n");
373 }
374
375 // Multiline text file buffers
376 float buf_load(string pFilename)
377 {
378         float buf, fh, i;
379         string l;
380         buf = buf_create();
381         if(buf < 0)
382                 return -1;
383         fh = fopen(pFilename, FILE_READ);
384         if(fh < 0)
385         {
386                 buf_del(buf);
387                 return -1;
388         }
389         i = 0;
390         while((l = fgets(fh)))
391         {
392                 bufstr_set(buf, i, l);
393                 ++i;
394         }
395         fclose(fh);
396         return buf;
397 }
398
399 void buf_save(float buf, string pFilename)
400 {
401         float fh, i, n;
402         fh = fopen(pFilename, FILE_WRITE);
403         if(fh < 0)
404                 error(strcat("Can't write buf to ", pFilename));
405         n = buf_getsize(buf);
406         for(i = 0; i < n; ++i)
407                 fputs(fh, strcat(bufstr_get(buf, i), "\n"));
408         fclose(fh);
409 }
410
411 string format_time(float seconds)
412 {
413         float days, hours, minutes;
414         seconds = floor(seconds + 0.5);
415         days = floor(seconds / 864000);
416         seconds -= days * 864000;
417         hours = floor(seconds / 36000);
418         seconds -= hours * 36000;
419         minutes = floor(seconds / 600);
420         seconds -= minutes * 600;
421         if (days > 0)
422                 return sprintf(_("%d days, %02d:%02d:%02d"), days, hours, minutes, seconds);
423         else
424                 return sprintf(_("%02d:%02d:%02d"), hours, minutes, seconds);
425 }
426
427 string mmsss(float tenths)
428 {
429         float minutes;
430         string s;
431         tenths = floor(tenths + 0.5);
432         minutes = floor(tenths / 600);
433         tenths -= minutes * 600;
434         s = ftos(1000 + tenths);
435         return strcat(ftos(minutes), ":", substring(s, 1, 2), ".", substring(s, 3, 1));
436 }
437
438 string mmssss(float hundredths)
439 {
440         float minutes;
441         string s;
442         hundredths = floor(hundredths + 0.5);
443         minutes = floor(hundredths / 6000);
444         hundredths -= minutes * 6000;
445         s = ftos(10000 + hundredths);
446         return strcat(ftos(minutes), ":", substring(s, 1, 2), ".", substring(s, 3, 2));
447 }
448
449 string ScoreString(int pFlags, float pValue)
450 {
451         string valstr;
452         float l;
453
454         pValue = floor(pValue + 0.5); // round
455
456         if((pValue == 0) && (pFlags & (SFL_HIDE_ZERO | SFL_RANK | SFL_TIME)))
457                 valstr = "";
458         else if(pFlags & SFL_RANK)
459         {
460                 valstr = ftos(pValue);
461                 l = strlen(valstr);
462                 if((l >= 2) && (substring(valstr, l - 2, 1) == "1"))
463                         valstr = strcat(valstr, "th");
464                 else if(substring(valstr, l - 1, 1) == "1")
465                         valstr = strcat(valstr, "st");
466                 else if(substring(valstr, l - 1, 1) == "2")
467                         valstr = strcat(valstr, "nd");
468                 else if(substring(valstr, l - 1, 1) == "3")
469                         valstr = strcat(valstr, "rd");
470                 else
471                         valstr = strcat(valstr, "th");
472         }
473         else if(pFlags & SFL_TIME)
474                 valstr = TIME_ENCODED_TOSTRING(pValue);
475         else
476                 valstr = ftos(pValue);
477
478         return valstr;
479 }
480
481 float dotproduct(vector a, vector b)
482 {
483         return a_x * b_x + a_y * b_y + a_z * b_z;
484 }
485
486 vector cross(vector a, vector b)
487 {
488         return
489                 '1 0 0' * (a_y * b_z - a_z * b_y)
490         +       '0 1 0' * (a_z * b_x - a_x * b_z)
491         +       '0 0 1' * (a_x * b_y - a_y * b_x);
492 }
493
494 // compressed vector format:
495 // like MD3, just even shorter
496 //   4 bit pitch (16 angles), 0 is -90, 8 is 0, 16 would be 90
497 //   5 bit yaw (32 angles), 0=0, 8=90, 16=180, 24=270
498 //   7 bit length (logarithmic encoding), 1/8 .. about 7844
499 //     length = 2^(length_encoded/8) / 8
500 // if pitch is 90, yaw does nothing and therefore indicates the sign (yaw is then either 11111 or 11110); 11111 is pointing DOWN
501 // thus, valid values are from 0000.11110.0000000 to 1111.11111.1111111
502 // the special value 0 indicates the zero vector
503
504 float lengthLogTable[128];
505
506 float invertLengthLog(float x)
507 {
508         int l, r, m;
509
510         if(x >= lengthLogTable[127])
511                 return 127;
512         if(x <= lengthLogTable[0])
513                 return 0;
514
515         l = 0;
516         r = 127;
517
518         while(r - l > 1)
519         {
520                 m = floor((l + r) / 2);
521                 if(lengthLogTable[m] < x)
522                         l = m;
523                 else
524                         r = m;
525         }
526
527         // now: r is >=, l is <
528         float lerr = (x - lengthLogTable[l]);
529         float rerr = (lengthLogTable[r] - x);
530         if(lerr < rerr)
531                 return l;
532         return r;
533 }
534
535 vector decompressShortVector(int data)
536 {
537         vector out;
538         if(data == 0)
539                 return '0 0 0';
540         float p = (data & 0xF000) / 0x1000;
541         float y = (data & 0x0F80) / 0x80;
542         int len = (data & 0x007F);
543
544         //print("\ndecompress: p ", ftos(p)); print("y ", ftos(y)); print("len ", ftos(len), "\n");
545
546         if(p == 0)
547         {
548                 out_x = 0;
549                 out_y = 0;
550                 if(y == 31)
551                         out_z = -1;
552                 else
553                         out_z = +1;
554         }
555         else
556         {
557                 y   = .19634954084936207740 * y;
558                 p = .19634954084936207740 * p - 1.57079632679489661922;
559                 out_x = cos(y) *  cos(p);
560                 out_y = sin(y) *  cos(p);
561                 out_z =          -sin(p);
562         }
563
564         //print("decompressed: ", vtos(out), "\n");
565
566         return out * lengthLogTable[len];
567 }
568
569 float compressShortVector(vector vec)
570 {
571         vector ang;
572         float p, y, len;
573         if(vlen(vec) == 0)
574                 return 0;
575         //print("compress: ", vtos(vec), "\n");
576         ang = vectoangles(vec);
577         ang_x = -ang_x;
578         if(ang_x < -90)
579                 ang_x += 360;
580         if(ang_x < -90 && ang_x > +90)
581                 error("BOGUS vectoangles");
582         //print("angles: ", vtos(ang), "\n");
583
584         p = floor(0.5 + (ang_x + 90) * 16 / 180) & 15; // -90..90 to 0..14
585         if(p == 0)
586         {
587                 if(vec_z < 0)
588                         y = 31;
589                 else
590                         y = 30;
591         }
592         else
593                 y = floor(0.5 + ang_y * 32 / 360)          & 31; // 0..360 to 0..32
594         len = invertLengthLog(vlen(vec));
595
596         //print("compressed: p ", ftos(p)); print("y ", ftos(y)); print("len ", ftos(len), "\n");
597
598         return (p * 0x1000) + (y * 0x80) + len;
599 }
600
601 void compressShortVector_init()
602 {
603         float l = 1;
604         float f = pow(2, 1/8);
605         int i;
606         for(i = 0; i < 128; ++i)
607         {
608                 lengthLogTable[i] = l;
609                 l *= f;
610         }
611
612         if(cvar("developer"))
613         {
614                 print("Verifying vector compression table...\n");
615                 for(i = 0x0F00; i < 0xFFFF; ++i)
616                         if(i != compressShortVector(decompressShortVector(i)))
617                         {
618                                 print("BROKEN vector compression: ", ftos(i));
619                                 print(" -> ", vtos(decompressShortVector(i)));
620                                 print(" -> ", ftos(compressShortVector(decompressShortVector(i))));
621                                 print("\n");
622                                 error("b0rk");
623                         }
624                 print("Done.\n");
625         }
626 }
627
628 #ifndef MENUQC
629 float CheckWireframeBox(entity forent, vector v0, vector dvx, vector dvy, vector dvz)
630 {
631         traceline(v0, v0 + dvx, TRUE, forent); if(trace_fraction < 1) return 0;
632         traceline(v0, v0 + dvy, TRUE, forent); if(trace_fraction < 1) return 0;
633         traceline(v0, v0 + dvz, TRUE, forent); if(trace_fraction < 1) return 0;
634         traceline(v0 + dvx, v0 + dvx + dvy, TRUE, forent); if(trace_fraction < 1) return 0;
635         traceline(v0 + dvx, v0 + dvx + dvz, TRUE, forent); if(trace_fraction < 1) return 0;
636         traceline(v0 + dvy, v0 + dvy + dvx, TRUE, forent); if(trace_fraction < 1) return 0;
637         traceline(v0 + dvy, v0 + dvy + dvz, TRUE, forent); if(trace_fraction < 1) return 0;
638         traceline(v0 + dvz, v0 + dvz + dvx, TRUE, forent); if(trace_fraction < 1) return 0;
639         traceline(v0 + dvz, v0 + dvz + dvy, TRUE, forent); if(trace_fraction < 1) return 0;
640         traceline(v0 + dvx + dvy, v0 + dvx + dvy + dvz, TRUE, forent); if(trace_fraction < 1) return 0;
641         traceline(v0 + dvx + dvz, v0 + dvx + dvy + dvz, TRUE, forent); if(trace_fraction < 1) return 0;
642         traceline(v0 + dvy + dvz, v0 + dvx + dvy + dvz, TRUE, forent); if(trace_fraction < 1) return 0;
643         return 1;
644 }
645 #endif
646
647 string fixPriorityList(string order, float from, float to, float subtract, float complete)
648 {
649         string neworder;
650         float i, n, w;
651
652         n = tokenize_console(order);
653         neworder = "";
654         for(i = 0; i < n; ++i)
655         {
656                 w = stof(argv(i));
657                 if(w == floor(w))
658                 {
659                         if(w >= from && w <= to)
660                                 neworder = strcat(neworder, ftos(w), " ");
661                         else
662                         {
663                                 w -= subtract;
664                                 if(w >= from && w <= to)
665                                         neworder = strcat(neworder, ftos(w), " ");
666                         }
667                 }
668         }
669
670         if(complete)
671         {
672                 n = tokenize_console(neworder);
673                 for(w = to; w >= from; --w)
674                 {
675                         for(i = 0; i < n; ++i)
676                                 if(stof(argv(i)) == w)
677                                         break;
678                         if(i == n) // not found
679                                 neworder = strcat(neworder, ftos(w), " ");
680                 }
681         }
682
683         return substring(neworder, 0, strlen(neworder) - 1);
684 }
685
686 string mapPriorityList(string order, string(string) mapfunc)
687 {
688         string neworder;
689         float i, n;
690
691         n = tokenize_console(order);
692         neworder = "";
693         for(i = 0; i < n; ++i)
694                 neworder = strcat(neworder, mapfunc(argv(i)), " ");
695
696         return substring(neworder, 0, strlen(neworder) - 1);
697 }
698
699 string swapInPriorityList(string order, float i, float j)
700 {
701         string s;
702         float w, n;
703
704         n = tokenize_console(order);
705
706         if(i >= 0 && i < n && j >= 0 && j < n && i != j)
707         {
708                 s = "";
709                 for(w = 0; w < n; ++w)
710                 {
711                         if(w == i)
712                                 s = strcat(s, argv(j), " ");
713                         else if(w == j)
714                                 s = strcat(s, argv(i), " ");
715                         else
716                                 s = strcat(s, argv(w), " ");
717                 }
718                 return substring(s, 0, strlen(s) - 1);
719         }
720
721         return order;
722 }
723
724 float cvar_value_issafe(string s)
725 {
726         if(strstrofs(s, "\"", 0) >= 0)
727                 return 0;
728         if(strstrofs(s, "\\", 0) >= 0)
729                 return 0;
730         if(strstrofs(s, ";", 0) >= 0)
731                 return 0;
732         if(strstrofs(s, "$", 0) >= 0)
733                 return 0;
734         if(strstrofs(s, "\r", 0) >= 0)
735                 return 0;
736         if(strstrofs(s, "\n", 0) >= 0)
737                 return 0;
738         return 1;
739 }
740
741 #ifndef MENUQC
742 void get_mi_min_max(float mode)
743 {
744         vector mi, ma;
745
746         if(mi_shortname)
747                 strunzone(mi_shortname);
748         mi_shortname = mapname;
749         if(!strcasecmp(substring(mi_shortname, 0, 5), "maps/"))
750                 mi_shortname = substring(mi_shortname, 5, strlen(mi_shortname) - 5);
751         if(!strcasecmp(substring(mi_shortname, strlen(mi_shortname) - 4, 4), ".bsp"))
752                 mi_shortname = substring(mi_shortname, 0, strlen(mi_shortname) - 4);
753         mi_shortname = strzone(mi_shortname);
754
755 #ifdef CSQC
756         mi = world.mins;
757         ma = world.maxs;
758 #else
759         mi = world.absmin;
760         ma = world.absmax;
761 #endif
762
763         mi_min = mi;
764         mi_max = ma;
765         MapInfo_Get_ByName(mi_shortname, 0, 0);
766         if(MapInfo_Map_mins_x < MapInfo_Map_maxs_x)
767         {
768                 mi_min = MapInfo_Map_mins;
769                 mi_max = MapInfo_Map_maxs;
770         }
771         else
772         {
773                 // not specified
774                 if(mode)
775                 {
776                         // be clever
777                         tracebox('1 0 0' * mi_x,
778                                          '0 1 0' * mi_y + '0 0 1' * mi_z,
779                                          '0 1 0' * ma_y + '0 0 1' * ma_z,
780                                          '1 0 0' * ma_x,
781                                          MOVE_WORLDONLY,
782                                          world);
783                         if(!trace_startsolid)
784                                 mi_min_x = trace_endpos_x;
785
786                         tracebox('0 1 0' * mi_y,
787                                          '1 0 0' * mi_x + '0 0 1' * mi_z,
788                                          '1 0 0' * ma_x + '0 0 1' * ma_z,
789                                          '0 1 0' * ma_y,
790                                          MOVE_WORLDONLY,
791                                          world);
792                         if(!trace_startsolid)
793                                 mi_min_y = trace_endpos_y;
794
795                         tracebox('0 0 1' * mi_z,
796                                          '1 0 0' * mi_x + '0 1 0' * mi_y,
797                                          '1 0 0' * ma_x + '0 1 0' * ma_y,
798                                          '0 0 1' * ma_z,
799                                          MOVE_WORLDONLY,
800                                          world);
801                         if(!trace_startsolid)
802                                 mi_min_z = trace_endpos_z;
803
804                         tracebox('1 0 0' * ma_x,
805                                          '0 1 0' * mi_y + '0 0 1' * mi_z,
806                                          '0 1 0' * ma_y + '0 0 1' * ma_z,
807                                          '1 0 0' * mi_x,
808                                          MOVE_WORLDONLY,
809                                          world);
810                         if(!trace_startsolid)
811                                 mi_max_x = trace_endpos_x;
812
813                         tracebox('0 1 0' * ma_y,
814                                          '1 0 0' * mi_x + '0 0 1' * mi_z,
815                                          '1 0 0' * ma_x + '0 0 1' * ma_z,
816                                          '0 1 0' * mi_y,
817                                          MOVE_WORLDONLY,
818                                          world);
819                         if(!trace_startsolid)
820                                 mi_max_y = trace_endpos_y;
821
822                         tracebox('0 0 1' * ma_z,
823                                          '1 0 0' * mi_x + '0 1 0' * mi_y,
824                                          '1 0 0' * ma_x + '0 1 0' * ma_y,
825                                          '0 0 1' * mi_z,
826                                          MOVE_WORLDONLY,
827                                          world);
828                         if(!trace_startsolid)
829                                 mi_max_z = trace_endpos_z;
830                 }
831         }
832 }
833
834 void get_mi_min_max_texcoords(float mode)
835 {
836         vector extend;
837
838         get_mi_min_max(mode);
839
840         mi_picmin = mi_min;
841         mi_picmax = mi_max;
842
843         // extend mi_picmax to get a square aspect ratio
844         // center the map in that area
845         extend = mi_picmax - mi_picmin;
846         if(extend_y > extend_x)
847         {
848                 mi_picmin_x -= (extend_y - extend_x) * 0.5;
849                 mi_picmax_x += (extend_y - extend_x) * 0.5;
850         }
851         else
852         {
853                 mi_picmin_y -= (extend_x - extend_y) * 0.5;
854                 mi_picmax_y += (extend_x - extend_y) * 0.5;
855         }
856
857         // add another some percent
858         extend = (mi_picmax - mi_picmin) * (1 / 64.0);
859         mi_picmin -= extend;
860         mi_picmax += extend;
861
862         // calculate the texcoords
863         mi_pictexcoord0 = mi_pictexcoord1 = mi_pictexcoord2 = mi_pictexcoord3 = '0 0 0';
864         // first the two corners of the origin
865         mi_pictexcoord0_x = (mi_min_x - mi_picmin_x) / (mi_picmax_x - mi_picmin_x);
866         mi_pictexcoord0_y = (mi_min_y - mi_picmin_y) / (mi_picmax_y - mi_picmin_y);
867         mi_pictexcoord2_x = (mi_max_x - mi_picmin_x) / (mi_picmax_x - mi_picmin_x);
868         mi_pictexcoord2_y = (mi_max_y - mi_picmin_y) / (mi_picmax_y - mi_picmin_y);
869         // then the other corners
870         mi_pictexcoord1_x = mi_pictexcoord0_x;
871         mi_pictexcoord1_y = mi_pictexcoord2_y;
872         mi_pictexcoord3_x = mi_pictexcoord2_x;
873         mi_pictexcoord3_y = mi_pictexcoord0_y;
874 }
875 #endif
876
877 float cvar_settemp(string tmp_cvar, string tmp_value)
878 {
879         float created_saved_value;
880         entity e;
881
882         created_saved_value = 0;
883
884         if (!(tmp_cvar || tmp_value))
885         {
886                 dprint("Error: Invalid usage of cvar_settemp(string, string); !\n");
887                 return 0;
888         }
889
890         if(!cvar_type(tmp_cvar))
891         {
892                 printf("Error: cvar %s doesn't exist!\n", tmp_cvar);
893                 return 0;
894         }
895
896         for(e = world; (e = find(e, classname, "saved_cvar_value")); )
897                 if(e.netname == tmp_cvar)
898                         created_saved_value = -1; // skip creation
899
900         if(created_saved_value != -1)
901         {
902                 // creating a new entity to keep track of this cvar
903                 e = spawn();
904                 e.classname = "saved_cvar_value";
905                 e.netname = strzone(tmp_cvar);
906                 e.message = strzone(cvar_string(tmp_cvar));
907                 created_saved_value = 1;
908         }
909
910         // update the cvar to the value given
911         cvar_set(tmp_cvar, tmp_value);
912
913         return created_saved_value;
914 }
915
916 float cvar_settemp_restore()
917 {
918         float i = 0;
919         entity e = world;
920         while((e = find(e, classname, "saved_cvar_value")))
921         {
922                 if(cvar_type(e.netname))
923                 {
924                         cvar_set(e.netname, e.message);
925                         remove(e);
926                         ++i;
927                 }
928                 else
929                         printf("Error: cvar %s doesn't exist anymore! It can still be restored once it's manually recreated.\n", e.netname);
930         }
931
932         return i;
933 }
934
935 float almost_equals(float a, float b)
936 {
937         float eps;
938         eps = (max(a, -a) + max(b, -b)) * 0.001;
939         if(a - b < eps && b - a < eps)
940                 return TRUE;
941         return FALSE;
942 }
943
944 float almost_in_bounds(float a, float b, float c)
945 {
946         float eps;
947         eps = (max(a, -a) + max(c, -c)) * 0.001;
948         if(a > c)
949                 eps = -eps;
950         return b == median(a - eps, b, c + eps);
951 }
952
953 float power2of(float e)
954 {
955         return pow(2, e);
956 }
957 float log2of(float x)
958 {
959         // NOTE: generated code
960         if(x > 2048)
961                 if(x > 131072)
962                         if(x > 1048576)
963                                 if(x > 4194304)
964                                         return 23;
965                                 else
966                                         if(x > 2097152)
967                                                 return 22;
968                                         else
969                                                 return 21;
970                         else
971                                 if(x > 524288)
972                                         return 20;
973                                 else
974                                         if(x > 262144)
975                                                 return 19;
976                                         else
977                                                 return 18;
978                 else
979                         if(x > 16384)
980                                 if(x > 65536)
981                                         return 17;
982                                 else
983                                         if(x > 32768)
984                                                 return 16;
985                                         else
986                                                 return 15;
987                         else
988                                 if(x > 8192)
989                                         return 14;
990                                 else
991                                         if(x > 4096)
992                                                 return 13;
993                                         else
994                                                 return 12;
995         else
996                 if(x > 32)
997                         if(x > 256)
998                                 if(x > 1024)
999                                         return 11;
1000                                 else
1001                                         if(x > 512)
1002                                                 return 10;
1003                                         else
1004                                                 return 9;
1005                         else
1006                                 if(x > 128)
1007                                         return 8;
1008                                 else
1009                                         if(x > 64)
1010                                                 return 7;
1011                                         else
1012                                                 return 6;
1013                 else
1014                         if(x > 4)
1015                                 if(x > 16)
1016                                         return 5;
1017                                 else
1018                                         if(x > 8)
1019                                                 return 4;
1020                                         else
1021                                                 return 3;
1022                         else
1023                                 if(x > 2)
1024                                         return 2;
1025                                 else
1026                                         if(x > 1)
1027                                                 return 1;
1028                                         else
1029                                                 return 0;
1030 }
1031
1032 float rgb_mi_ma_to_hue(vector rgb, float mi, float ma)
1033 {
1034         if(mi == ma)
1035                 return 0;
1036         else if(ma == rgb_x)
1037         {
1038                 if(rgb_y >= rgb_z)
1039                         return (rgb_y - rgb_z) / (ma - mi);
1040                 else
1041                         return (rgb_y - rgb_z) / (ma - mi) + 6;
1042         }
1043         else if(ma == rgb_y)
1044                 return (rgb_z - rgb_x) / (ma - mi) + 2;
1045         else // if(ma == rgb_z)
1046                 return (rgb_x - rgb_y) / (ma - mi) + 4;
1047 }
1048
1049 vector hue_mi_ma_to_rgb(float hue, float mi, float ma)
1050 {
1051         vector rgb;
1052
1053         hue -= 6 * floor(hue / 6);
1054
1055         //else if(ma == rgb_x)
1056         //      hue = 60 * (rgb_y - rgb_z) / (ma - mi);
1057         if(hue <= 1)
1058         {
1059                 rgb_x = ma;
1060                 rgb_y = hue * (ma - mi) + mi;
1061                 rgb_z = mi;
1062         }
1063         //else if(ma == rgb_y)
1064         //      hue = 60 * (rgb_z - rgb_x) / (ma - mi) + 120;
1065         else if(hue <= 2)
1066         {
1067                 rgb_x = (2 - hue) * (ma - mi) + mi;
1068                 rgb_y = ma;
1069                 rgb_z = mi;
1070         }
1071         else if(hue <= 3)
1072         {
1073                 rgb_x = mi;
1074                 rgb_y = ma;
1075                 rgb_z = (hue - 2) * (ma - mi) + mi;
1076         }
1077         //else // if(ma == rgb_z)
1078         //      hue = 60 * (rgb_x - rgb_y) / (ma - mi) + 240;
1079         else if(hue <= 4)
1080         {
1081                 rgb_x = mi;
1082                 rgb_y = (4 - hue) * (ma - mi) + mi;
1083                 rgb_z = ma;
1084         }
1085         else if(hue <= 5)
1086         {
1087                 rgb_x = (hue - 4) * (ma - mi) + mi;
1088                 rgb_y = mi;
1089                 rgb_z = ma;
1090         }
1091         //else if(ma == rgb_x)
1092         //      hue = 60 * (rgb_y - rgb_z) / (ma - mi);
1093         else // if(hue <= 6)
1094         {
1095                 rgb_x = ma;
1096                 rgb_y = mi;
1097                 rgb_z = (6 - hue) * (ma - mi) + mi;
1098         }
1099
1100         return rgb;
1101 }
1102
1103 vector rgb_to_hsv(vector rgb)
1104 {
1105         float mi, ma;
1106         vector hsv;
1107
1108         mi = min(rgb_x, rgb_y, rgb_z);
1109         ma = max(rgb_x, rgb_y, rgb_z);
1110
1111         hsv_x = rgb_mi_ma_to_hue(rgb, mi, ma);
1112         hsv_z = ma;
1113
1114         if(ma == 0)
1115                 hsv_y = 0;
1116         else
1117                 hsv_y = 1 - mi/ma;
1118
1119         return hsv;
1120 }
1121
1122 vector hsv_to_rgb(vector hsv)
1123 {
1124         return hue_mi_ma_to_rgb(hsv_x, hsv_z * (1 - hsv_y), hsv_z);
1125 }
1126
1127 vector rgb_to_hsl(vector rgb)
1128 {
1129         float mi, ma;
1130         vector hsl;
1131
1132         mi = min(rgb_x, rgb_y, rgb_z);
1133         ma = max(rgb_x, rgb_y, rgb_z);
1134
1135         hsl_x = rgb_mi_ma_to_hue(rgb, mi, ma);
1136
1137         hsl_z = 0.5 * (mi + ma);
1138         if(mi == ma)
1139                 hsl_y = 0;
1140         else if(hsl_z <= 0.5)
1141                 hsl_y = (ma - mi) / (2*hsl_z);
1142         else // if(hsl_z > 0.5)
1143                 hsl_y = (ma - mi) / (2 - 2*hsl_z);
1144
1145         return hsl;
1146 }
1147
1148 vector hsl_to_rgb(vector hsl)
1149 {
1150         float mi, ma, maminusmi;
1151
1152         if(hsl_z <= 0.5)
1153                 maminusmi = hsl_y * 2 * hsl_z;
1154         else
1155                 maminusmi = hsl_y * (2 - 2 * hsl_z);
1156
1157         // hsl_z     = 0.5 * mi + 0.5 * ma
1158         // maminusmi =     - mi +       ma
1159         mi = hsl_z - 0.5 * maminusmi;
1160         ma = hsl_z + 0.5 * maminusmi;
1161
1162         return hue_mi_ma_to_rgb(hsl_x, mi, ma);
1163 }
1164
1165 string rgb_to_hexcolor(vector rgb)
1166 {
1167         return
1168                 strcat(
1169                         "^x",
1170                         DEC_TO_HEXDIGIT(floor(rgb_x * 15 + 0.5)),
1171                         DEC_TO_HEXDIGIT(floor(rgb_y * 15 + 0.5)),
1172                         DEC_TO_HEXDIGIT(floor(rgb_z * 15 + 0.5))
1173                 );
1174 }
1175
1176 // requires that m2>m1 in all coordinates, and that m4>m3
1177 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;}
1178
1179 // requires the same, but is a stronger condition
1180 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;}
1181
1182 #ifndef MENUQC
1183 #endif
1184
1185 float textLengthUpToWidth(string theText, float maxWidth, vector theSize, textLengthUpToWidth_widthFunction_t w)
1186 {
1187         // STOP.
1188         // The following function is SLOW.
1189         // For your safety and for the protection of those around you...
1190         // DO NOT CALL THIS AT HOME.
1191         // No really, don't.
1192         if(w(theText, theSize) <= maxWidth)
1193                 return strlen(theText); // yeah!
1194
1195         // binary search for right place to cut string
1196         float ch;
1197         float left, right, middle; // this always works
1198         left = 0;
1199         right = strlen(theText); // this always fails
1200         do
1201         {
1202                 middle = floor((left + right) / 2);
1203                 if(w(substring(theText, 0, middle), theSize) <= maxWidth)
1204                         left = middle;
1205                 else
1206                         right = middle;
1207         }
1208         while(left < right - 1);
1209
1210         if(w("^7", theSize) == 0) // detect color codes support in the width function
1211         {
1212                 // NOTE: when color codes are involved, this binary search is,
1213                 // mathematically, BROKEN. However, it is obviously guaranteed to
1214                 // terminate, as the range still halves each time - but nevertheless, it is
1215                 // guaranteed that it finds ONE valid cutoff place (where "left" is in
1216                 // range, and "right" is outside).
1217
1218                 // terencehill: the following code detects truncated ^xrgb tags (e.g. ^x or ^x4)
1219                 // and decrease left on the basis of the chars detected of the truncated tag
1220                 // Even if the ^xrgb tag is not complete/correct, left is decreased
1221                 // (sometimes too much but with a correct result)
1222                 // it fixes also ^[0-9]
1223                 while(left >= 1 && substring(theText, left-1, 1) == "^")
1224                         left-=1;
1225
1226                 if (left >= 2 && substring(theText, left-2, 2) == "^x") // ^x/
1227                         left-=2;
1228                 else if (left >= 3 && substring(theText, left-3, 2) == "^x")
1229                         {
1230                                 ch = str2chr(theText, left-1);
1231                                 if( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') ) // ^xr/
1232                                         left-=3;
1233                         }
1234                 else if (left >= 4 && substring(theText, left-4, 2) == "^x")
1235                         {
1236                                 ch = str2chr(theText, left-2);
1237                                 if ( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') )
1238                                 {
1239                                         ch = str2chr(theText, left-1);
1240                                         if ( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') ) // ^xrg/
1241                                                 left-=4;
1242                                 }
1243                         }
1244         }
1245
1246         return left;
1247 }
1248
1249 float textLengthUpToLength(string theText, float maxWidth, textLengthUpToLength_lenFunction_t w)
1250 {
1251         // STOP.
1252         // The following function is SLOW.
1253         // For your safety and for the protection of those around you...
1254         // DO NOT CALL THIS AT HOME.
1255         // No really, don't.
1256         if(w(theText) <= maxWidth)
1257                 return strlen(theText); // yeah!
1258
1259         // binary search for right place to cut string
1260         float ch;
1261         float left, right, middle; // this always works
1262         left = 0;
1263         right = strlen(theText); // this always fails
1264         do
1265         {
1266                 middle = floor((left + right) / 2);
1267                 if(w(substring(theText, 0, middle)) <= maxWidth)
1268                         left = middle;
1269                 else
1270                         right = middle;
1271         }
1272         while(left < right - 1);
1273
1274         if(w("^7") == 0) // detect color codes support in the width function
1275         {
1276                 // NOTE: when color codes are involved, this binary search is,
1277                 // mathematically, BROKEN. However, it is obviously guaranteed to
1278                 // terminate, as the range still halves each time - but nevertheless, it is
1279                 // guaranteed that it finds ONE valid cutoff place (where "left" is in
1280                 // range, and "right" is outside).
1281
1282                 // terencehill: the following code detects truncated ^xrgb tags (e.g. ^x or ^x4)
1283                 // and decrease left on the basis of the chars detected of the truncated tag
1284                 // Even if the ^xrgb tag is not complete/correct, left is decreased
1285                 // (sometimes too much but with a correct result)
1286                 // it fixes also ^[0-9]
1287                 while(left >= 1 && substring(theText, left-1, 1) == "^")
1288                         left-=1;
1289
1290                 if (left >= 2 && substring(theText, left-2, 2) == "^x") // ^x/
1291                         left-=2;
1292                 else if (left >= 3 && substring(theText, left-3, 2) == "^x")
1293                         {
1294                                 ch = str2chr(theText, left-1);
1295                                 if( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') ) // ^xr/
1296                                         left-=3;
1297                         }
1298                 else if (left >= 4 && substring(theText, left-4, 2) == "^x")
1299                         {
1300                                 ch = str2chr(theText, left-2);
1301                                 if ( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') )
1302                                 {
1303                                         ch = str2chr(theText, left-1);
1304                                         if ( (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F') ) // ^xrg/
1305                                                 left-=4;
1306                                 }
1307                         }
1308         }
1309
1310         return left;
1311 }
1312
1313 string find_last_color_code(string s)
1314 {
1315         int start = strstrofs(s, "^", 0);
1316         if (start == -1) // no caret found
1317                 return "";
1318         int len = strlen(s)-1;
1319         int i;
1320         for(i = len; i >= start; --i)
1321         {
1322                 if(substring(s, i, 1) != "^")
1323                         continue;
1324
1325                 int carets = 1;
1326                 while (i-carets >= start && substring(s, i-carets, 1) == "^")
1327                         ++carets;
1328
1329                 // check if carets aren't all escaped
1330                 if (carets & 1)
1331                 {
1332                         if(i+1 <= len)
1333                         if(strstrofs("0123456789", substring(s, i+1, 1), 0) >= 0)
1334                                 return substring(s, i, 2);
1335
1336                         if(i+4 <= len)
1337                         if(substring(s, i+1, 1) == "x")
1338                         if(strstrofs("0123456789abcdefABCDEF", substring(s, i+2, 1), 0) >= 0)
1339                         if(strstrofs("0123456789abcdefABCDEF", substring(s, i+3, 1), 0) >= 0)
1340                         if(strstrofs("0123456789abcdefABCDEF", substring(s, i+4, 1), 0) >= 0)
1341                                 return substring(s, i, 5);
1342                 }
1343                 i -= carets; // this also skips one char before the carets
1344         }
1345
1346         return "";
1347 }
1348
1349 string getWrappedLine(float w, vector theFontSize, textLengthUpToWidth_widthFunction_t tw)
1350 {
1351         float cantake;
1352         float take;
1353         string s;
1354
1355         s = getWrappedLine_remaining;
1356
1357         if(w <= 0)
1358         {
1359                 getWrappedLine_remaining = string_null;
1360                 return s; // the line has no size ANYWAY, nothing would be displayed.
1361         }
1362
1363         cantake = textLengthUpToWidth(s, w, theFontSize, tw);
1364         if(cantake > 0 && cantake < strlen(s))
1365         {
1366                 take = cantake - 1;
1367                 while(take > 0 && substring(s, take, 1) != " ")
1368                         --take;
1369                 if(take == 0)
1370                 {
1371                         getWrappedLine_remaining = substring(s, cantake, strlen(s) - cantake);
1372                         if(getWrappedLine_remaining == "")
1373                                 getWrappedLine_remaining = string_null;
1374                         else if (tw("^7", theFontSize) == 0)
1375                                 getWrappedLine_remaining = strcat(find_last_color_code(substring(s, 0, cantake)), getWrappedLine_remaining);
1376                         return substring(s, 0, cantake);
1377                 }
1378                 else
1379                 {
1380                         getWrappedLine_remaining = substring(s, take + 1, strlen(s) - take);
1381                         if(getWrappedLine_remaining == "")
1382                                 getWrappedLine_remaining = string_null;
1383                         else if (tw("^7", theFontSize) == 0)
1384                                 getWrappedLine_remaining = strcat(find_last_color_code(substring(s, 0, take)), getWrappedLine_remaining);
1385                         return substring(s, 0, take);
1386                 }
1387         }
1388         else
1389         {
1390                 getWrappedLine_remaining = string_null;
1391                 return s;
1392         }
1393 }
1394
1395 string getWrappedLineLen(float w, textLengthUpToLength_lenFunction_t tw)
1396 {
1397         float cantake;
1398         float take;
1399         string s;
1400
1401         s = getWrappedLine_remaining;
1402
1403         if(w <= 0)
1404         {
1405                 getWrappedLine_remaining = string_null;
1406                 return s; // the line has no size ANYWAY, nothing would be displayed.
1407         }
1408
1409         cantake = textLengthUpToLength(s, w, tw);
1410         if(cantake > 0 && cantake < strlen(s))
1411         {
1412                 take = cantake - 1;
1413                 while(take > 0 && substring(s, take, 1) != " ")
1414                         --take;
1415                 if(take == 0)
1416                 {
1417                         getWrappedLine_remaining = substring(s, cantake, strlen(s) - cantake);
1418                         if(getWrappedLine_remaining == "")
1419                                 getWrappedLine_remaining = string_null;
1420                         else if (tw("^7") == 0)
1421                                 getWrappedLine_remaining = strcat(find_last_color_code(substring(s, 0, cantake)), getWrappedLine_remaining);
1422                         return substring(s, 0, cantake);
1423                 }
1424                 else
1425                 {
1426                         getWrappedLine_remaining = substring(s, take + 1, strlen(s) - take);
1427                         if(getWrappedLine_remaining == "")
1428                                 getWrappedLine_remaining = string_null;
1429                         else if (tw("^7") == 0)
1430                                 getWrappedLine_remaining = strcat(find_last_color_code(substring(s, 0, take)), getWrappedLine_remaining);
1431                         return substring(s, 0, take);
1432                 }
1433         }
1434         else
1435         {
1436                 getWrappedLine_remaining = string_null;
1437                 return s;
1438         }
1439 }
1440
1441 string textShortenToWidth(string theText, float maxWidth, vector theFontSize, textLengthUpToWidth_widthFunction_t tw)
1442 {
1443         if(tw(theText, theFontSize) <= maxWidth)
1444                 return theText;
1445         else
1446                 return strcat(substring(theText, 0, textLengthUpToWidth(theText, maxWidth - tw("...", theFontSize), theFontSize, tw)), "...");
1447 }
1448
1449 string textShortenToLength(string theText, float maxWidth, textLengthUpToLength_lenFunction_t tw)
1450 {
1451         if(tw(theText) <= maxWidth)
1452                 return theText;
1453         else
1454                 return strcat(substring(theText, 0, textLengthUpToLength(theText, maxWidth - tw("..."), tw)), "...");
1455 }
1456
1457 float isGametypeInFilter(float gt, float tp, float ts, string pattern)
1458 {
1459         string subpattern, subpattern2, subpattern3, subpattern4;
1460         subpattern = strcat(",", MapInfo_Type_ToString(gt), ",");
1461         if(tp)
1462                 subpattern2 = ",teams,";
1463         else
1464                 subpattern2 = ",noteams,";
1465         if(ts)
1466                 subpattern3 = ",teamspawns,";
1467         else
1468                 subpattern3 = ",noteamspawns,";
1469         if(gt == MAPINFO_TYPE_RACE || gt == MAPINFO_TYPE_CTS)
1470                 subpattern4 = ",race,";
1471         else
1472                 subpattern4 = string_null;
1473
1474         if(substring(pattern, 0, 1) == "-")
1475         {
1476                 pattern = substring(pattern, 1, strlen(pattern) - 1);
1477                 if(strstrofs(strcat(",", pattern, ","), subpattern, 0) >= 0)
1478                         return 0;
1479                 if(strstrofs(strcat(",", pattern, ","), subpattern2, 0) >= 0)
1480                         return 0;
1481                 if(strstrofs(strcat(",", pattern, ","), subpattern3, 0) >= 0)
1482                         return 0;
1483                 if(subpattern4 && strstrofs(strcat(",", pattern, ","), subpattern4, 0) >= 0)
1484                         return 0;
1485         }
1486         else
1487         {
1488                 if(substring(pattern, 0, 1) == "+")
1489                         pattern = substring(pattern, 1, strlen(pattern) - 1);
1490                 if(strstrofs(strcat(",", pattern, ","), subpattern, 0) < 0)
1491                 if(strstrofs(strcat(",", pattern, ","), subpattern2, 0) < 0)
1492                 if(strstrofs(strcat(",", pattern, ","), subpattern3, 0) < 0)
1493                 {
1494                         if (!subpattern4)
1495                                 return 0;
1496                         if(strstrofs(strcat(",", pattern, ","), subpattern4, 0) < 0)
1497                                 return 0;
1498                 }
1499         }
1500         return 1;
1501 }
1502
1503 void shuffle(float n, swapfunc_t swap, entity pass)
1504 {
1505         float i, j;
1506         for(i = 1; i < n; ++i)
1507         {
1508                 // swap i-th item at a random position from 0 to i
1509                 // proof for even distribution:
1510                 //   n = 1: obvious
1511                 //   n -> n+1:
1512                 //     item n+1 gets at any position with chance 1/(n+1)
1513                 //     all others will get their 1/n chance reduced by factor n/(n+1)
1514                 //     to be on place n+1, their chance will be 1/(n+1)
1515                 //     1/n * n/(n+1) = 1/(n+1)
1516                 //     q.e.d.
1517                 j = floor(random() * (i + 1));
1518                 if(j != i)
1519                         swap(j, i, pass);
1520         }
1521 }
1522
1523 string substring_range(string s, float b, float e)
1524 {
1525         return substring(s, b, e - b);
1526 }
1527
1528 string swapwords(string str, float i, float j)
1529 {
1530         float n;
1531         string s1, s2, s3, s4, s5;
1532         float si, ei, sj, ej, s0, en;
1533         n = tokenizebyseparator(str, " "); // must match g_maplist processing in ShuffleMaplist and "shuffle"
1534         si = argv_start_index(i);
1535         sj = argv_start_index(j);
1536         ei = argv_end_index(i);
1537         ej = argv_end_index(j);
1538         s0 = argv_start_index(0);
1539         en = argv_end_index(n-1);
1540         s1 = substring_range(str, s0, si);
1541         s2 = substring_range(str, si, ei);
1542         s3 = substring_range(str, ei, sj);
1543         s4 = substring_range(str, sj, ej);
1544         s5 = substring_range(str, ej, en);
1545         return strcat(s1, s4, s3, s2, s5);
1546 }
1547
1548 string _shufflewords_str;
1549 void _shufflewords_swapfunc(float i, float j, entity pass)
1550 {
1551         _shufflewords_str = swapwords(_shufflewords_str, i, j);
1552 }
1553 string shufflewords(string str)
1554 {
1555         float n;
1556         _shufflewords_str = str;
1557         n = tokenizebyseparator(str, " ");
1558         shuffle(n, _shufflewords_swapfunc, world);
1559         str = _shufflewords_str;
1560         _shufflewords_str = string_null;
1561         return str;
1562 }
1563
1564 vector solve_quadratic(float a, float b, float c) // ax^2 + bx + c = 0
1565 {
1566         vector v;
1567         float D;
1568         v = '0 0 0';
1569         if(a == 0)
1570         {
1571                 if(b != 0)
1572                 {
1573                         v_x = v_y = -c / b;
1574                         v_z = 1;
1575                 }
1576                 else
1577                 {
1578                         if(c == 0)
1579                         {
1580                                 // actually, every number solves the equation!
1581                                 v_z = 1;
1582                         }
1583                 }
1584         }
1585         else
1586         {
1587                 D = b*b - 4*a*c;
1588                 if(D >= 0)
1589                 {
1590                         D = sqrt(D);
1591                         if(a > 0) // put the smaller solution first
1592                         {
1593                                 v_x = ((-b)-D) / (2*a);
1594                                 v_y = ((-b)+D) / (2*a);
1595                         }
1596                         else
1597                         {
1598                                 v_x = (-b+D) / (2*a);
1599                                 v_y = (-b-D) / (2*a);
1600                         }
1601                         v_z = 1;
1602                 }
1603                 else
1604                 {
1605                         // complex solutions!
1606                         D = sqrt(-D);
1607                         v_x = -b / (2*a);
1608                         if(a > 0)
1609                                 v_y =  D / (2*a);
1610                         else
1611                                 v_y = -D / (2*a);
1612                         v_z = 0;
1613                 }
1614         }
1615         return v;
1616 }
1617
1618 vector solve_shotdirection(vector myorg, vector myvel, vector eorg, vector evel, float spd, float newton_style)
1619 {
1620         vector ret;
1621
1622         // make origin and speed relative
1623         eorg -= myorg;
1624         if(newton_style)
1625                 evel -= myvel;
1626
1627         // now solve for ret, ret normalized:
1628         //   eorg + t * evel == t * ret * spd
1629         // or, rather, solve for t:
1630         //   |eorg + t * evel| == t * spd
1631         //   eorg^2 + t^2 * evel^2 + 2 * t * (eorg * evel) == t^2 * spd^2
1632         //   t^2 * (evel^2 - spd^2) + t * (2 * (eorg * evel)) + eorg^2 == 0
1633         vector solution = solve_quadratic(evel * evel - spd * spd, 2 * (eorg * evel), eorg * eorg);
1634         // p = 2 * (eorg * evel) / (evel * evel - spd * spd)
1635         // q = (eorg * eorg) / (evel * evel - spd * spd)
1636         if(!solution_z) // no real solution
1637         {
1638                 // happens if D < 0
1639                 // (eorg * evel)^2 < (evel^2 - spd^2) * eorg^2
1640                 // (eorg * evel)^2 / eorg^2 < evel^2 - spd^2
1641                 // spd^2 < ((evel^2 * eorg^2) - (eorg * evel)^2) / eorg^2
1642                 // spd^2 < evel^2 * (1 - cos^2 angle(evel, eorg))
1643                 // spd^2 < evel^2 * sin^2 angle(evel, eorg)
1644                 // spd < |evel| * sin angle(evel, eorg)
1645                 return '0 0 0';
1646         }
1647         else if(solution_x > 0)
1648         {
1649                 // both solutions > 0: take the smaller one
1650                 // happens if p < 0 and q > 0
1651                 ret = normalize(eorg + solution_x * evel);
1652         }
1653         else if(solution_y > 0)
1654         {
1655                 // one solution > 0: take the larger one
1656                 // happens if q < 0 or q == 0 and p < 0
1657                 ret = normalize(eorg + solution_y * evel);
1658         }
1659         else
1660         {
1661                 // no solution > 0: reject
1662                 // happens if p > 0 and q >= 0
1663                 // 2 * (eorg * evel) / (evel * evel - spd * spd) > 0
1664                 // (eorg * eorg) / (evel * evel - spd * spd) >= 0
1665                 //
1666                 // |evel| >= spd
1667                 // eorg * evel > 0
1668                 //
1669                 // "Enemy is moving away from me at more than spd"
1670                 return '0 0 0';
1671         }
1672
1673         // NOTE: we always got a solution if spd > |evel|
1674
1675         if(newton_style == 2)
1676                 ret = normalize(ret * spd + myvel);
1677
1678         return ret;
1679 }
1680
1681 vector get_shotvelocity(vector myvel, vector mydir, float spd, float newton_style, float mi, float ma)
1682 {
1683         if(!newton_style)
1684                 return spd * mydir;
1685
1686         if(newton_style == 2)
1687         {
1688                 // true Newtonian projectiles with automatic aim adjustment
1689                 //
1690                 // solve: |outspeed * mydir - myvel| = spd
1691                 // outspeed^2 - 2 * outspeed * (mydir * myvel) + myvel^2 - spd^2 = 0
1692                 // outspeed = (mydir * myvel) +- sqrt((mydir * myvel)^2 - myvel^2 + spd^2)
1693                 // PLUS SIGN!
1694                 // not defined?
1695                 // then...
1696                 // myvel^2 - (mydir * myvel)^2 > spd^2
1697                 // velocity without mydir component > spd
1698                 // fire at smallest possible spd that works?
1699                 // |(mydir * myvel) * myvel - myvel| = spd
1700
1701                 vector solution = solve_quadratic(1, -2 * (mydir * myvel), myvel * myvel - spd * spd);
1702
1703                 float outspeed;
1704                 if(solution_z)
1705                         outspeed = solution_y; // the larger one
1706                 else
1707                 {
1708                         //outspeed = 0; // slowest possible shot
1709                         outspeed = solution_x; // the real part (that is, the average!)
1710                         //dprint("impossible shot, adjusting\n");
1711                 }
1712
1713                 outspeed = bound(spd * mi, outspeed, spd * ma);
1714                 return mydir * outspeed;
1715         }
1716
1717         // real Newtonian
1718         return myvel + spd * mydir;
1719 }
1720
1721 float compressShotOrigin(vector v)
1722 {
1723         float x, y, z;
1724         x = rint(v_x * 2);
1725         y = rint(v_y * 4) + 128;
1726         z = rint(v_z * 4) + 128;
1727         if(x > 255 || x < 0)
1728         {
1729                 print("shot origin ", vtos(v), " x out of bounds\n");
1730                 x = bound(0, x, 255);
1731         }
1732         if(y > 255 || y < 0)
1733         {
1734                 print("shot origin ", vtos(v), " y out of bounds\n");
1735                 y = bound(0, y, 255);
1736         }
1737         if(z > 255 || z < 0)
1738         {
1739                 print("shot origin ", vtos(v), " z out of bounds\n");
1740                 z = bound(0, z, 255);
1741         }
1742         return x * 0x10000 + y * 0x100 + z;
1743 }
1744 vector decompressShotOrigin(int f)
1745 {
1746         vector v;
1747         v_x = ((f & 0xFF0000) / 0x10000) / 2;
1748         v_y = ((f & 0xFF00) / 0x100 - 128) / 4;
1749         v_z = ((f & 0xFF) - 128) / 4;
1750         return v;
1751 }
1752
1753 void heapsort(float n, swapfunc_t swap, comparefunc_t cmp, entity pass)
1754 {
1755         float start, end, root, child;
1756
1757         // heapify
1758         start = floor((n - 2) / 2);
1759         while(start >= 0)
1760         {
1761                 // siftdown(start, count-1);
1762                 root = start;
1763                 while(root * 2 + 1 <= n-1)
1764                 {
1765                         child = root * 2 + 1;
1766                         if(child < n-1)
1767                                 if(cmp(child, child+1, pass) < 0)
1768                                         ++child;
1769                         if(cmp(root, child, pass) < 0)
1770                         {
1771                                 swap(root, child, pass);
1772                                 root = child;
1773                         }
1774                         else
1775                                 break;
1776                 }
1777                 // end of siftdown
1778                 --start;
1779         }
1780
1781         // extract
1782         end = n - 1;
1783         while(end > 0)
1784         {
1785                 swap(0, end, pass);
1786                 --end;
1787                 // siftdown(0, end);
1788                 root = 0;
1789                 while(root * 2 + 1 <= end)
1790                 {
1791                         child = root * 2 + 1;
1792                         if(child < end && cmp(child, child+1, pass) < 0)
1793                                 ++child;
1794                         if(cmp(root, child, pass) < 0)
1795                         {
1796                                 swap(root, child, pass);
1797                                 root = child;
1798                         }
1799                         else
1800                                 break;
1801                 }
1802                 // end of siftdown
1803         }
1804 }
1805
1806 void RandomSelection_Init()
1807 {
1808         RandomSelection_totalweight = 0;
1809         RandomSelection_chosen_ent = world;
1810         RandomSelection_chosen_float = 0;
1811         RandomSelection_chosen_string = string_null;
1812         RandomSelection_best_priority = -1;
1813 }
1814 void RandomSelection_Add(entity e, float f, string s, float weight, float priority)
1815 {
1816         if(priority > RandomSelection_best_priority)
1817         {
1818                 RandomSelection_best_priority = priority;
1819                 RandomSelection_chosen_ent = e;
1820                 RandomSelection_chosen_float = f;
1821                 RandomSelection_chosen_string = s;
1822                 RandomSelection_totalweight = weight;
1823         }
1824         else if(priority == RandomSelection_best_priority)
1825         {
1826                 RandomSelection_totalweight += weight;
1827                 if(random() * RandomSelection_totalweight <= weight)
1828                 {
1829                         RandomSelection_chosen_ent = e;
1830                         RandomSelection_chosen_float = f;
1831                         RandomSelection_chosen_string = s;
1832                 }
1833         }
1834 }
1835
1836 #ifndef MENUQC
1837 vector healtharmor_maxdamage(float h, float a, float armorblock, float deathtype)
1838 {
1839         // NOTE: we'll always choose the SMALLER value...
1840         float healthdamage, armordamage, armorideal;
1841         if (deathtype == DEATH_DROWN)  // Why should armor help here...
1842                 armorblock = 0;
1843         vector v;
1844         healthdamage = (h - 1) / (1 - armorblock); // damage we can take if we could use more health
1845         armordamage = a + (h - 1); // damage we can take if we could use more armor
1846         armorideal = healthdamage * armorblock;
1847         v_y = armorideal;
1848         if(armordamage < healthdamage)
1849         {
1850                 v_x = armordamage;
1851                 v_z = 1;
1852         }
1853         else
1854         {
1855                 v_x = healthdamage;
1856                 v_z = 0;
1857         }
1858         return v;
1859 }
1860
1861 vector healtharmor_applydamage(float a, float armorblock, float deathtype, float damage)
1862 {
1863         vector v;
1864         if (deathtype == DEATH_DROWN)  // Why should armor help here...
1865                 armorblock = 0;
1866         v_y = bound(0, damage * armorblock, a); // save
1867         v_x = bound(0, damage - v_y, damage); // take
1868         v_z = 0;
1869         return v;
1870 }
1871 #endif
1872
1873 string getcurrentmod()
1874 {
1875         float n;
1876         string m;
1877         m = cvar_string("fs_gamedir");
1878         n = tokenize_console(m);
1879         if(n == 0)
1880                 return "data";
1881         else
1882                 return argv(n - 1);
1883 }
1884
1885 #ifndef MENUQC
1886 #ifdef CSQC
1887 float ReadInt24_t()
1888 {
1889         float v;
1890         v = ReadShort() * 256; // note: this is signed
1891         v += ReadByte(); // note: this is unsigned
1892         return v;
1893 }
1894 vector ReadInt48_t()
1895 {
1896         vector v;
1897         v_x = ReadInt24_t();
1898         v_y = ReadInt24_t();
1899         v_z = 0;
1900         return v;
1901 }
1902 vector ReadInt72_t()
1903 {
1904         vector v;
1905         v_x = ReadInt24_t();
1906         v_y = ReadInt24_t();
1907         v_z = ReadInt24_t();
1908         return v;
1909 }
1910 #else
1911 void WriteInt24_t(float dst, float val)
1912 {
1913         float v;
1914         WriteShort(dst, (v = floor(val / 256)));
1915         WriteByte(dst, val - v * 256); // 0..255
1916 }
1917 void WriteInt48_t(float dst, vector val)
1918 {
1919         WriteInt24_t(dst, val_x);
1920         WriteInt24_t(dst, val_y);
1921 }
1922 void WriteInt72_t(float dst, vector val)
1923 {
1924         WriteInt24_t(dst, val_x);
1925         WriteInt24_t(dst, val_y);
1926         WriteInt24_t(dst, val_z);
1927 }
1928 #endif
1929 #endif
1930
1931 float float2range11(float f)
1932 {
1933         // continuous function mapping all reals into -1..1
1934         return f / (fabs(f) + 1);
1935 }
1936
1937 float float2range01(float f)
1938 {
1939         // continuous function mapping all reals into 0..1
1940         return 0.5 + 0.5 * float2range11(f);
1941 }
1942
1943 // from the GNU Scientific Library
1944 float gsl_ran_gaussian_lastvalue;
1945 float gsl_ran_gaussian_lastvalue_set;
1946 float gsl_ran_gaussian(float sigma)
1947 {
1948         float a, b;
1949         if(gsl_ran_gaussian_lastvalue_set)
1950         {
1951                 gsl_ran_gaussian_lastvalue_set = 0;
1952                 return sigma * gsl_ran_gaussian_lastvalue;
1953         }
1954         else
1955         {
1956                 a = random() * 2 * M_PI;
1957                 b = sqrt(-2 * log(random()));
1958                 gsl_ran_gaussian_lastvalue = cos(a) * b;
1959                 gsl_ran_gaussian_lastvalue_set = 1;
1960                 return sigma * sin(a) * b;
1961         }
1962 }
1963
1964 string car(string s)
1965 {
1966         float o;
1967         o = strstrofs(s, " ", 0);
1968         if(o < 0)
1969                 return s;
1970         return substring(s, 0, o);
1971 }
1972 string cdr(string s)
1973 {
1974         float o;
1975         o = strstrofs(s, " ", 0);
1976         if(o < 0)
1977                 return string_null;
1978         return substring(s, o + 1, strlen(s) - (o + 1));
1979 }
1980 float matchacl(string acl, string str)
1981 {
1982         string t, s;
1983         float r, d;
1984         r = 0;
1985         while(acl)
1986         {
1987                 t = car(acl); acl = cdr(acl);
1988
1989                 d = 1;
1990                 if(substring(t, 0, 1) == "-")
1991                 {
1992                         d = -1;
1993                         t = substring(t, 1, strlen(t) - 1);
1994                 }
1995                 else if(substring(t, 0, 1) == "+")
1996                         t = substring(t, 1, strlen(t) - 1);
1997
1998                 if(substring(t, -1, 1) == "*")
1999                 {
2000                         t = substring(t, 0, strlen(t) - 1);
2001                         s = substring(str, 0, strlen(t));
2002                 }
2003                 else
2004                         s = str;
2005
2006                 if(s == t)
2007                 {
2008                         r = d;
2009                 }
2010         }
2011         return r;
2012 }
2013 float startsWith(string haystack, string needle)
2014 {
2015         return substring(haystack, 0, strlen(needle)) == needle;
2016 }
2017 float startsWithNocase(string haystack, string needle)
2018 {
2019         return strcasecmp(substring(haystack, 0, strlen(needle)), needle) == 0;
2020 }
2021
2022 string get_model_datafilename(string m, float sk, string fil)
2023 {
2024         if(m)
2025                 m = strcat(m, "_");
2026         else
2027                 m = "models/player/*_";
2028         if(sk >= 0)
2029                 m = strcat(m, ftos(sk));
2030         else
2031                 m = strcat(m, "*");
2032         return strcat(m, ".", fil);
2033 }
2034
2035 float get_model_parameters(string m, float sk)
2036 {
2037         string fn, s, c;
2038         float fh, i;
2039
2040         get_model_parameters_modelname = string_null;
2041         get_model_parameters_modelskin = -1;
2042         get_model_parameters_name = string_null;
2043         get_model_parameters_species = -1;
2044         get_model_parameters_sex = string_null;
2045         get_model_parameters_weight = -1;
2046         get_model_parameters_age = -1;
2047         get_model_parameters_desc = string_null;
2048         get_model_parameters_bone_upperbody = string_null;
2049         get_model_parameters_bone_weapon = string_null;
2050         for(i = 0; i < MAX_AIM_BONES; ++i)
2051         {
2052                 get_model_parameters_bone_aim[i] = string_null;
2053                 get_model_parameters_bone_aimweight[i] = 0;
2054         }
2055         get_model_parameters_fixbone = 0;
2056
2057         if (!m)
2058                 return 1;
2059
2060         if(substring(m, -9, 5) == "_lod1" || substring(m, -9, 5) == "_lod2")
2061                 m = strcat(substring(m, 0, -10), substring(m, -4, -1));
2062
2063         if(sk < 0)
2064         {
2065                 if(substring(m, -4, -1) != ".txt")
2066                         return 0;
2067                 if(substring(m, -6, 1) != "_")
2068                         return 0;
2069                 sk = stof(substring(m, -5, 1));
2070                 m = substring(m, 0, -7);
2071         }
2072
2073         fn = get_model_datafilename(m, sk, "txt");
2074         fh = fopen(fn, FILE_READ);
2075         if(fh < 0)
2076         {
2077                 sk = 0;
2078                 fn = get_model_datafilename(m, sk, "txt");
2079                 fh = fopen(fn, FILE_READ);
2080                 if(fh < 0)
2081                         return 0;
2082         }
2083
2084         get_model_parameters_modelname = m;
2085         get_model_parameters_modelskin = sk;
2086         while((s = fgets(fh)))
2087         {
2088                 if(s == "")
2089                         break; // next lines will be description
2090                 c = car(s);
2091                 s = cdr(s);
2092                 if(c == "name")
2093                         get_model_parameters_name = s;
2094                 if(c == "species")
2095                         switch(s)
2096                         {
2097                                 case "human":       get_model_parameters_species = SPECIES_HUMAN;       break;
2098                                 case "alien":       get_model_parameters_species = SPECIES_ALIEN;       break;
2099                                 case "robot_shiny": get_model_parameters_species = SPECIES_ROBOT_SHINY; break;
2100                                 case "robot_rusty": get_model_parameters_species = SPECIES_ROBOT_RUSTY; break;
2101                                 case "robot_solid": get_model_parameters_species = SPECIES_ROBOT_SOLID; break;
2102                                 case "animal":      get_model_parameters_species = SPECIES_ANIMAL;      break;
2103                                 case "reserved":    get_model_parameters_species = SPECIES_RESERVED;    break;
2104                         }
2105                 if(c == "sex")
2106                         get_model_parameters_sex = s;
2107                 if(c == "weight")
2108                         get_model_parameters_weight = stof(s);
2109                 if(c == "age")
2110                         get_model_parameters_age = stof(s);
2111                 if(c == "description")
2112                         get_model_parameters_description = s;
2113                 if(c == "bone_upperbody")
2114                         get_model_parameters_bone_upperbody = s;
2115                 if(c == "bone_weapon")
2116                         get_model_parameters_bone_weapon = s;
2117                 for(i = 0; i < MAX_AIM_BONES; ++i)
2118                         if(c == strcat("bone_aim", ftos(i)))
2119                         {
2120                                 get_model_parameters_bone_aimweight[i] = stof(car(s));
2121                                 get_model_parameters_bone_aim[i] = cdr(s);
2122                         }
2123                 if(c == "fixbone")
2124                         get_model_parameters_fixbone = stof(s);
2125         }
2126
2127         while((s = fgets(fh)))
2128         {
2129                 if(get_model_parameters_desc)
2130                         get_model_parameters_desc = strcat(get_model_parameters_desc, "\n");
2131                 if(s != "")
2132                         get_model_parameters_desc = strcat(get_model_parameters_desc, s);
2133         }
2134
2135         fclose(fh);
2136
2137         return 1;
2138 }
2139
2140 vector vec2(vector v)
2141 {
2142         v_z = 0;
2143         return v;
2144 }
2145
2146 #ifndef MENUQC
2147 vector NearestPointOnBox(entity box, vector org)
2148 {
2149         vector m1, m2, nearest;
2150
2151         m1 = box.mins + box.origin;
2152         m2 = box.maxs + box.origin;
2153
2154         nearest_x = bound(m1_x, org_x, m2_x);
2155         nearest_y = bound(m1_y, org_y, m2_y);
2156         nearest_z = bound(m1_z, org_z, m2_z);
2157
2158         return nearest;
2159 }
2160 #endif
2161
2162 float vercmp_recursive(string v1, string v2)
2163 {
2164         float dot1, dot2;
2165         string s1, s2;
2166         float r;
2167
2168         dot1 = strstrofs(v1, ".", 0);
2169         dot2 = strstrofs(v2, ".", 0);
2170         if(dot1 == -1)
2171                 s1 = v1;
2172         else
2173                 s1 = substring(v1, 0, dot1);
2174         if(dot2 == -1)
2175                 s2 = v2;
2176         else
2177                 s2 = substring(v2, 0, dot2);
2178
2179         r = stof(s1) - stof(s2);
2180         if(r != 0)
2181                 return r;
2182
2183         r = strcasecmp(s1, s2);
2184         if(r != 0)
2185                 return r;
2186
2187         if(dot1 == -1)
2188                 if(dot2 == -1)
2189                         return 0;
2190                 else
2191                         return -1;
2192         else
2193                 if(dot2 == -1)
2194                         return 1;
2195                 else
2196                         return vercmp_recursive(substring(v1, dot1 + 1, 999), substring(v2, dot2 + 1, 999));
2197 }
2198
2199 float vercmp(string v1, string v2)
2200 {
2201         if(strcasecmp(v1, v2) == 0) // early out check
2202                 return 0;
2203
2204         // "git" beats all
2205         if(v1 == "git")
2206                 return 1;
2207         if(v2 == "git")
2208                 return -1;
2209
2210         return vercmp_recursive(v1, v2);
2211 }
2212
2213 float u8_strsize(string s)
2214 {
2215         float l, i, c;
2216         l = 0;
2217         for(i = 0; ; ++i)
2218         {
2219                 c = str2chr(s, i);
2220                 if(c <= 0)
2221                         break;
2222                 ++l;
2223                 if(c >= 0x80)
2224                         ++l;
2225                 if(c >= 0x800)
2226                         ++l;
2227                 if(c >= 0x10000)
2228                         ++l;
2229         }
2230         return l;
2231 }
2232
2233 // translation helpers
2234 string language_filename(string s)
2235 {
2236         string fn;
2237         float fh;
2238         fn = prvm_language;
2239         if(fn == "" || fn == "dump")
2240                 return s;
2241         fn = strcat(s, ".", fn);
2242         if((fh = fopen(fn, FILE_READ)) >= 0)
2243         {
2244                 fclose(fh);
2245                 return fn;
2246         }
2247         return s;
2248 }
2249 string CTX(string s)
2250 {
2251         float p = strstrofs(s, "^", 0);
2252         if(p < 0)
2253                 return s;
2254         return substring(s, p+1, -1);
2255 }
2256
2257 // x-encoding (encoding as zero length invisible string)
2258 const string XENCODE_2  = "xX";
2259 const string XENCODE_22 = "0123456789abcdefABCDEF";
2260 string xencode(int f)
2261 {
2262         float a, b, c, d;
2263         d = f % 22; f = floor(f / 22);
2264         c = f % 22; f = floor(f / 22);
2265         b = f % 22; f = floor(f / 22);
2266         a = f %  2; // f = floor(f /  2);
2267         return strcat(
2268                 "^",
2269                 substring(XENCODE_2,  a, 1),
2270                 substring(XENCODE_22, b, 1),
2271                 substring(XENCODE_22, c, 1),
2272                 substring(XENCODE_22, d, 1)
2273         );
2274 }
2275 float xdecode(string s)
2276 {
2277         float a, b, c, d;
2278         if(substring(s, 0, 1) != "^")
2279                 return -1;
2280         if(strlen(s) < 5)
2281                 return -1;
2282         a = strstrofs(XENCODE_2,  substring(s, 1, 1), 0);
2283         b = strstrofs(XENCODE_22, substring(s, 2, 1), 0);
2284         c = strstrofs(XENCODE_22, substring(s, 3, 1), 0);
2285         d = strstrofs(XENCODE_22, substring(s, 4, 1), 0);
2286         if(a < 0 || b < 0 || c < 0 || d < 0)
2287                 return -1;
2288         return ((a * 22 + b) * 22 + c) * 22 + d;
2289 }
2290
2291 float lowestbit(int f)
2292 {
2293         f &= ~(f * 2);
2294         f &= ~(f * 4);
2295         f &= ~(f * 16);
2296         f &= ~(f * 256);
2297         f &= ~(f * 65536);
2298         return f;
2299 }
2300
2301 /*
2302 string strlimitedlen(string input, string truncation, float strip_colors, float limit)
2303 {
2304         if(strlen((strip_colors ? strdecolorize(input) : input)) <= limit)
2305                 return input;
2306         else
2307                 return strcat(substring(input, 0, (strlen(input) - strlen(truncation))), truncation);
2308 }*/
2309
2310 // escape the string to make it safe for consoles
2311 string MakeConsoleSafe(string input)
2312 {
2313         input = strreplace("\n", "", input);
2314         input = strreplace("\\", "\\\\", input);
2315         input = strreplace("$", "$$", input);
2316         input = strreplace("\"", "\\\"", input);
2317         return input;
2318 }
2319
2320 #ifndef MENUQC
2321 // get true/false value of a string with multiple different inputs
2322 float InterpretBoolean(string input)
2323 {
2324         switch(strtolower(input))
2325         {
2326                 case "yes":
2327                 case "true":
2328                 case "on":
2329                         return TRUE;
2330
2331                 case "no":
2332                 case "false":
2333                 case "off":
2334                         return FALSE;
2335
2336                 default: return stof(input);
2337         }
2338 }
2339 #endif
2340
2341 #ifdef CSQC
2342 entity ReadCSQCEntity()
2343 {
2344         float f;
2345         f = ReadShort();
2346         if(f == 0)
2347                 return world;
2348         return findfloat(world, entnum, f);
2349 }
2350 #endif
2351
2352 float shutdown_running;
2353 #ifdef SVQC
2354 void SV_Shutdown()
2355 #endif
2356 #ifdef CSQC
2357 void CSQC_Shutdown()
2358 #endif
2359 #ifdef MENUQC
2360 void m_shutdown()
2361 #endif
2362 {
2363         if(shutdown_running)
2364         {
2365                 print("Recursive shutdown detected! Only restoring cvars...\n");
2366         }
2367         else
2368         {
2369                 shutdown_running = 1;
2370                 Shutdown();
2371         }
2372         cvar_settemp_restore(); // this must be done LAST, but in any case
2373 }
2374
2375 const float APPROXPASTTIME_ACCURACY_REQUIREMENT = 0.05;
2376 #define APPROXPASTTIME_MAX (16384 * APPROXPASTTIME_ACCURACY_REQUIREMENT)
2377 #define APPROXPASTTIME_RANGE (64 * APPROXPASTTIME_ACCURACY_REQUIREMENT)
2378 // this will use the value:
2379 //   128
2380 // accuracy near zero is APPROXPASTTIME_MAX/(256*255)
2381 // accuracy at x is 1/derivative, i.e.
2382 //   APPROXPASTTIME_MAX * (1 + 256 * (dt / APPROXPASTTIME_MAX))^2 / 65536
2383 #ifdef SVQC
2384 void WriteApproxPastTime(float dst, float t)
2385 {
2386         float dt = time - t;
2387
2388         // warning: this is approximate; do not resend when you don't have to!
2389         // be careful with sendflags here!
2390         // we want: 0 -> 0.05, 1 -> 0.1, ..., 255 -> 12.75
2391
2392         // map to range...
2393         dt = 256 * (dt / ((APPROXPASTTIME_MAX / 256) + dt));
2394
2395         // round...
2396         dt = rint(bound(0, dt, 255));
2397
2398         WriteByte(dst, dt);
2399 }
2400 #endif
2401 #ifdef CSQC
2402 float ReadApproxPastTime()
2403 {
2404         float dt = ReadByte();
2405
2406         // map from range...PPROXPASTTIME_MAX / 256
2407         dt = (APPROXPASTTIME_MAX / 256) * (dt / (256 - dt));
2408
2409         return servertime - dt;
2410 }
2411 #endif
2412
2413 #ifndef MENUQC
2414 .float skeleton_bones_index;
2415 void Skeleton_SetBones(entity e)
2416 {
2417         // set skeleton_bones to the total number of bones on the model
2418         if(e.skeleton_bones_index == e.modelindex)
2419                 return; // same model, nothing to update
2420
2421         float skelindex;
2422         skelindex = skel_create(e.modelindex);
2423         e.skeleton_bones = skel_get_numbones(skelindex);
2424         skel_delete(skelindex);
2425         e.skeleton_bones_index = e.modelindex;
2426 }
2427 #endif
2428
2429 string to_execute_next_frame;
2430 void execute_next_frame()
2431 {
2432         if(to_execute_next_frame)
2433         {
2434                 localcmd("\n", to_execute_next_frame, "\n");
2435                 strunzone(to_execute_next_frame);
2436                 to_execute_next_frame = string_null;
2437         }
2438 }
2439 void queue_to_execute_next_frame(string s)
2440 {
2441         if(to_execute_next_frame)
2442         {
2443                 s = strcat(s, "\n", to_execute_next_frame);
2444                 strunzone(to_execute_next_frame);
2445         }
2446         to_execute_next_frame = strzone(s);
2447 }
2448
2449 float cubic_speedfunc(float startspeedfactor, float endspeedfactor, float x)
2450 {
2451         return
2452                 (((     startspeedfactor + endspeedfactor - 2
2453                 ) * x - 2 * startspeedfactor - endspeedfactor + 3
2454                 ) * x + startspeedfactor
2455                 ) * x;
2456 }
2457
2458 float cubic_speedfunc_is_sane(float startspeedfactor, float endspeedfactor)
2459 {
2460         if(startspeedfactor < 0 || endspeedfactor < 0)
2461                 return FALSE;
2462
2463         /*
2464         // if this is the case, the possible zeros of the first derivative are outside
2465         // 0..1
2466         We can calculate this condition as condition
2467         if(se <= 3)
2468                 return TRUE;
2469         */
2470
2471         // better, see below:
2472         if(startspeedfactor <= 3 && endspeedfactor <= 3)
2473                 return TRUE;
2474
2475         // if this is the case, the first derivative has no zeros at all
2476         float se = startspeedfactor + endspeedfactor;
2477         float s_e = startspeedfactor - endspeedfactor;
2478         if(3 * (se - 4) * (se - 4) + s_e * s_e <= 12) // an ellipse
2479                 return TRUE;
2480
2481         // Now let s <= 3, s <= 3, s+e >= 3 (triangle) then we get se <= 6 (top right corner).
2482         // we also get s_e <= 6 - se
2483         // 3 * (se - 4)^2 + (6 - se)^2
2484         // is quadratic, has value 12 at 3 and 6, and value < 12 in between.
2485         // Therefore, above "better" check works!
2486
2487         return FALSE;
2488
2489         // known good cases:
2490         // (0, [0..3])
2491         // (0.5, [0..3.8])
2492         // (1, [0..4])
2493         // (1.5, [0..3.9])
2494         // (2, [0..3.7])
2495         // (2.5, [0..3.4])
2496         // (3, [0..3])
2497         // (3.5, [0.2..2.3])
2498         // (4, 1)
2499
2500         /*
2501            On another note:
2502            inflection point is always at (2s + e - 3) / (3s + 3e - 6).
2503
2504            s + e - 2 == 0: no inflection
2505
2506            s + e > 2:
2507            0 < inflection < 1 if:
2508            0 < 2s + e - 3 < 3s + 3e - 6
2509            2s + e > 3 and 2e + s > 3
2510
2511            s + e < 2:
2512            0 < inflection < 1 if:
2513            0 > 2s + e - 3 > 3s + 3e - 6
2514            2s + e < 3 and 2e + s < 3
2515
2516            Therefore: there is an inflection point iff:
2517            e outside (3 - s)/2 .. 3 - s*2
2518
2519            in other words, if (s,e) in triangle (1,1)(0,3)(0,1.5) or in triangle (1,1)(3,0)(1.5,0)
2520         */
2521 }
2522
2523 .float FindConnectedComponent_processing;
2524 void FindConnectedComponent(entity e, .entity fld, findNextEntityNearFunction_t nxt, isConnectedFunction_t iscon, entity pass)
2525 {
2526         entity queue_start, queue_end;
2527
2528         // we build a queue of to-be-processed entities.
2529         // queue_start is the next entity to be checked for neighbors
2530         // queue_end is the last entity added
2531
2532         if(e.FindConnectedComponent_processing)
2533                 error("recursion or broken cleanup");
2534
2535         // start with a 1-element queue
2536         queue_start = queue_end = e;
2537         queue_end.fld = world;
2538         queue_end.FindConnectedComponent_processing = 1;
2539
2540         // for each queued item:
2541         for(; queue_start; queue_start = queue_start.fld)
2542         {
2543                 // find all neighbors of queue_start
2544                 entity t;
2545                 for(t = world; (t = nxt(t, queue_start, pass)); )
2546                 {
2547                         if(t.FindConnectedComponent_processing)
2548                                 continue;
2549                         if(iscon(t, queue_start, pass))
2550                         {
2551                                 // it is connected? ADD IT. It will look for neighbors soon too.
2552                                 queue_end.fld = t;
2553                                 queue_end = t;
2554                                 queue_end.fld = world;
2555                                 queue_end.FindConnectedComponent_processing = 1;
2556                         }
2557                 }
2558         }
2559
2560         // unmark
2561         for(queue_start = e; queue_start; queue_start = queue_start.fld)
2562                 queue_start.FindConnectedComponent_processing = 0;
2563 }
2564
2565 #ifdef SVQC
2566 vector combine_to_vector(float x, float y, float z)
2567 {
2568         vector result; result_x = x; result_y = y; result_z = z;
2569         return result;
2570 }
2571
2572 vector get_corner_position(entity box, float corner)
2573 {
2574         switch(corner)
2575         {
2576                 case 1: return combine_to_vector(box.absmin_x, box.absmin_y, box.absmin_z);
2577                 case 2: return combine_to_vector(box.absmax_x, box.absmin_y, box.absmin_z);
2578                 case 3: return combine_to_vector(box.absmin_x, box.absmax_y, box.absmin_z);
2579                 case 4: return combine_to_vector(box.absmin_x, box.absmin_y, box.absmax_z);
2580                 case 5: return combine_to_vector(box.absmax_x, box.absmax_y, box.absmin_z);
2581                 case 6: return combine_to_vector(box.absmin_x, box.absmax_y, box.absmax_z);
2582                 case 7: return combine_to_vector(box.absmax_x, box.absmin_y, box.absmax_z);
2583                 case 8: return combine_to_vector(box.absmax_x, box.absmax_y, box.absmax_z);
2584                 default: return '0 0 0';
2585         }
2586 }
2587 #endif
2588
2589 // todo: this sucks, lets find a better way to do backtraces?
2590 void backtrace(string msg)
2591 {
2592         float dev, war;
2593         #ifdef SVQC
2594         dev = autocvar_developer;
2595         war = autocvar_prvm_backtraceforwarnings;
2596         #else
2597         dev = cvar("developer");
2598         war = cvar("prvm_backtraceforwarnings");
2599         #endif
2600         cvar_set("developer", "1");
2601         cvar_set("prvm_backtraceforwarnings", "1");
2602         print("\n");
2603         print("--- CUT HERE ---\nWARNING: ");
2604         print(msg);
2605         print("\n");
2606         remove(world); // isn't there any better way to cause a backtrace?
2607         print("\n--- CUT UNTIL HERE ---\n");
2608         cvar_set("developer", ftos(dev));
2609         cvar_set("prvm_backtraceforwarnings", ftos(war));
2610 }
2611
2612 // color code replace, place inside of sprintf and parse the string
2613 string CCR(string input)
2614 {
2615         // See the autocvar declarations in util.qh for default values
2616
2617         // foreground/normal colors
2618         input = strreplace("^F1", strcat("^", autocvar_hud_colorset_foreground_1), input);
2619         input = strreplace("^F2", strcat("^", autocvar_hud_colorset_foreground_2), input);
2620         input = strreplace("^F3", strcat("^", autocvar_hud_colorset_foreground_3), input);
2621         input = strreplace("^F4", strcat("^", autocvar_hud_colorset_foreground_4), input);
2622
2623         // "kill" colors
2624         input = strreplace("^K1", strcat("^", autocvar_hud_colorset_kill_1), input);
2625         input = strreplace("^K2", strcat("^", autocvar_hud_colorset_kill_2), input);
2626         input = strreplace("^K3", strcat("^", autocvar_hud_colorset_kill_3), input);
2627
2628         // background colors
2629         input = strreplace("^BG", strcat("^", autocvar_hud_colorset_background), input);
2630         input = strreplace("^N", "^7", input); // "none"-- reset to white...
2631         return input;
2632 }
2633
2634 vector vec3(float x, float y, float z)
2635 {
2636         vector v;
2637         v_x = x;
2638         v_y = y;
2639         v_z = z;
2640         return v;
2641 }
2642
2643 #ifndef MENUQC
2644 vector animfixfps(entity e, vector a, vector b)
2645 {
2646         // multi-frame anim: keep as-is
2647         if(a_y == 1)
2648         {
2649                 float dur;
2650                 dur = frameduration(e.modelindex, a_x);
2651                 if(dur <= 0 && b_y)
2652                 {
2653                         a = b;
2654                         dur = frameduration(e.modelindex, a_x);
2655                 }
2656                 if(dur > 0)
2657                         a_z = 1.0 / dur;
2658         }
2659         return a;
2660 }
2661 #endif
2662
2663 #ifdef SVQC
2664 void dedicated_print(string input) // print(), but only print if the server is not local
2665 {
2666         if(server_is_dedicated) { print(input); }
2667 }
2668 #endif
2669
2670 #ifndef MENUQC
2671 float Announcer_PickNumber(float type, float num)
2672 {
2673         switch(type)
2674         {
2675                 case CNT_GAMESTART:
2676                 {
2677                         switch(num)
2678                         {
2679                                 case 10: return ANNCE_NUM_GAMESTART_10;
2680                                 case 9:  return ANNCE_NUM_GAMESTART_9;
2681                                 case 8:  return ANNCE_NUM_GAMESTART_8;
2682                                 case 7:  return ANNCE_NUM_GAMESTART_7;
2683                                 case 6:  return ANNCE_NUM_GAMESTART_6;
2684                                 case 5:  return ANNCE_NUM_GAMESTART_5;
2685                                 case 4:  return ANNCE_NUM_GAMESTART_4;
2686                                 case 3:  return ANNCE_NUM_GAMESTART_3;
2687                                 case 2:  return ANNCE_NUM_GAMESTART_2;
2688                                 case 1:  return ANNCE_NUM_GAMESTART_1;
2689                         }
2690                         break;
2691                 }
2692                 case CNT_IDLE:
2693                 {
2694                         switch(num)
2695                         {
2696                                 case 10: return ANNCE_NUM_IDLE_10;
2697                                 case 9:  return ANNCE_NUM_IDLE_9;
2698                                 case 8:  return ANNCE_NUM_IDLE_8;
2699                                 case 7:  return ANNCE_NUM_IDLE_7;
2700                                 case 6:  return ANNCE_NUM_IDLE_6;
2701                                 case 5:  return ANNCE_NUM_IDLE_5;
2702                                 case 4:  return ANNCE_NUM_IDLE_4;
2703                                 case 3:  return ANNCE_NUM_IDLE_3;
2704                                 case 2:  return ANNCE_NUM_IDLE_2;
2705                                 case 1:  return ANNCE_NUM_IDLE_1;
2706                         }
2707                         break;
2708                 }
2709                 case CNT_KILL:
2710                 {
2711                         switch(num)
2712                         {
2713                                 case 10: return ANNCE_NUM_KILL_10;
2714                                 case 9:  return ANNCE_NUM_KILL_9;
2715                                 case 8:  return ANNCE_NUM_KILL_8;
2716                                 case 7:  return ANNCE_NUM_KILL_7;
2717                                 case 6:  return ANNCE_NUM_KILL_6;
2718                                 case 5:  return ANNCE_NUM_KILL_5;
2719                                 case 4:  return ANNCE_NUM_KILL_4;
2720                                 case 3:  return ANNCE_NUM_KILL_3;
2721                                 case 2:  return ANNCE_NUM_KILL_2;
2722                                 case 1:  return ANNCE_NUM_KILL_1;
2723                         }
2724                         break;
2725                 }
2726                 case CNT_RESPAWN:
2727                 {
2728                         switch(num)
2729                         {
2730                                 case 10: return ANNCE_NUM_RESPAWN_10;
2731                                 case 9:  return ANNCE_NUM_RESPAWN_9;
2732                                 case 8:  return ANNCE_NUM_RESPAWN_8;
2733                                 case 7:  return ANNCE_NUM_RESPAWN_7;
2734                                 case 6:  return ANNCE_NUM_RESPAWN_6;
2735                                 case 5:  return ANNCE_NUM_RESPAWN_5;
2736                                 case 4:  return ANNCE_NUM_RESPAWN_4;
2737                                 case 3:  return ANNCE_NUM_RESPAWN_3;
2738                                 case 2:  return ANNCE_NUM_RESPAWN_2;
2739                                 case 1:  return ANNCE_NUM_RESPAWN_1;
2740                         }
2741                         break;
2742                 }
2743                 case CNT_ROUNDSTART:
2744                 {
2745                         switch(num)
2746                         {
2747                                 case 10: return ANNCE_NUM_ROUNDSTART_10;
2748                                 case 9:  return ANNCE_NUM_ROUNDSTART_9;
2749                                 case 8:  return ANNCE_NUM_ROUNDSTART_8;
2750                                 case 7:  return ANNCE_NUM_ROUNDSTART_7;
2751                                 case 6:  return ANNCE_NUM_ROUNDSTART_6;
2752                                 case 5:  return ANNCE_NUM_ROUNDSTART_5;
2753                                 case 4:  return ANNCE_NUM_ROUNDSTART_4;
2754                                 case 3:  return ANNCE_NUM_ROUNDSTART_3;
2755                                 case 2:  return ANNCE_NUM_ROUNDSTART_2;
2756                                 case 1:  return ANNCE_NUM_ROUNDSTART_1;
2757                         }
2758                         break;
2759                 }
2760                 default:
2761                 {
2762                         switch(num)
2763                         {
2764                                 case 10: return ANNCE_NUM_10;
2765                                 case 9:  return ANNCE_NUM_9;
2766                                 case 8:  return ANNCE_NUM_8;
2767                                 case 7:  return ANNCE_NUM_7;
2768                                 case 6:  return ANNCE_NUM_6;
2769                                 case 5:  return ANNCE_NUM_5;
2770                                 case 4:  return ANNCE_NUM_4;
2771                                 case 3:  return ANNCE_NUM_3;
2772                                 case 2:  return ANNCE_NUM_2;
2773                                 case 1:  return ANNCE_NUM_1;
2774                         }
2775                         break;
2776                 }
2777         }
2778         return NOTIF_ABORT; // abort sending if none of these numbers were right
2779 }
2780 #endif
2781
2782 #ifndef MENUQC
2783 float Mod_Q1BSP_SuperContentsFromNativeContents(float nativecontents)
2784 {
2785         switch(nativecontents)
2786         {
2787                 case CONTENT_EMPTY:
2788                         return 0;
2789                 case CONTENT_SOLID:
2790                         return DPCONTENTS_SOLID | DPCONTENTS_OPAQUE;
2791                 case CONTENT_WATER:
2792                         return DPCONTENTS_WATER;
2793                 case CONTENT_SLIME:
2794                         return DPCONTENTS_SLIME;
2795                 case CONTENT_LAVA:
2796                         return DPCONTENTS_LAVA | DPCONTENTS_NODROP;
2797                 case CONTENT_SKY:
2798                         return DPCONTENTS_SKY | DPCONTENTS_NODROP | DPCONTENTS_OPAQUE; // to match behaviour of Q3 maps, let sky count as opaque
2799         }
2800         return 0;
2801 }
2802
2803 float Mod_Q1BSP_NativeContentsFromSuperContents(int supercontents)
2804 {
2805         if(supercontents & (DPCONTENTS_SOLID | DPCONTENTS_BODY))
2806                 return CONTENT_SOLID;
2807         if(supercontents & DPCONTENTS_SKY)
2808                 return CONTENT_SKY;
2809         if(supercontents & DPCONTENTS_LAVA)
2810                 return CONTENT_LAVA;
2811         if(supercontents & DPCONTENTS_SLIME)
2812                 return CONTENT_SLIME;
2813         if(supercontents & DPCONTENTS_WATER)
2814                 return CONTENT_WATER;
2815         return CONTENT_EMPTY;
2816 }
2817 #endif
2818
2819 vector bezier_quadratic_getpoint(vector a, vector b, vector c, float t)
2820 {
2821         return
2822                 (c - 2 * b + a) * (t * t) +
2823                 (b - a) * (2 * t) +
2824                 a;
2825 }
2826
2827 vector bezier_quadratic_getderivative(vector a, vector b, vector c, float t)
2828 {
2829         return
2830                 (c - 2 * b + a) * (2 * t) +
2831                 (b - a) * 2;
2832 }