]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/common/util.qh
Merge branch 'master' into samual/combined_updates
[xonotic/xonotic-data.pk3dir.git] / qcsrc / common / util.qh
1 #define WANT_CONST
2 // commonly used, but better make them macros
3 #define TRUE 1
4 #define FALSE 0
5
6 // a dummy macro that prevents the "hanging ;" warning
7 #define ENDS_WITH_CURLY_BRACE
8
9 #ifdef GMQCC
10 # define ACCUMULATE_FUNCTION(func,otherfunc) \
11         [[accumulate]] void func() { otherfunc(); }
12 # define CALL_ACCUMULATED_FUNCTION(func) \
13         func()
14 #else
15 #ifdef HAVE_YO_DAWG_CPP
16 // TODO make ascii art pic of xzibit
17 // YO DAWG!
18 // I HERD YO LIEK MACROS
19 // SO I PUT A MACRO DEFINITION IN YO MACRO DEFINITION
20 // SO YO CAN EXPAND MACROS WHILE YO EXPAND MACROS
21 # define ACCUMULATE_FUNCTION(func,otherfunc) \
22         #ifdef func \
23         void __merge__##otherfunc() { func(); otherfunc(); } \
24         #undef func \
25         #define func __merge__##otherfunc \
26         #else \
27         #define func otherfunc \
28         #endif
29 # define CALL_ACCUMULATED_FUNCTION(func) \
30         func()
31 #else
32 # define ACCUMULATE_FUNCTION(func,otherfunc) \
33         .float _ACCUMULATE_##func##__##otherfunc
34 void ACCUMULATE_call(string func)
35 {
36         float i;
37         float n = numentityfields();
38         string funcprefix = strcat("_ACCUMULATE_", func, "__");
39         float funcprefixlen = strlen(funcprefix);
40         for(i = 0; i < n; ++i)
41         {
42                 string name = entityfieldname(i);
43                 if(substring(name, 0, funcprefixlen) == funcprefix)
44                         callfunction(substring(name, funcprefixlen, -1));
45         }
46 }
47 # define CALL_ACCUMULATED_FUNCTION(func) \
48         ACCUMULATE_call(#func)
49 #endif
50 #endif
51
52 // used for simplifying ACCUMULATE_FUNCTIONs
53 #define SET_FIRST_OR_LAST(input,first,count) if(!input) { input = (first + count); }
54 #define SET_FIELD_COUNT(field,first,count) if(!field) { field = (first + count); ++count; }
55 #define CHECK_MAX_COUNT(name,max,count,type) if(count > max) { error(strcat("Maximum ", type, " hit: ", #name, ": ", ftos(count), ".\n")); }
56
57 // this returns a tempstring containing a copy of s with additional \n newlines added, it also replaces \n in the text with a real newline
58 // NOTE: s IS allowed to be a tempstring
59 string wordwrap(string s, float l);
60 #ifndef MENUQC
61 #ifndef CSQC
62 void wordwrap_sprint(string s, float l);
63 #endif
64 #endif
65 void wordwrap_cb(string s, float l, void(string) callback);
66
67 #ifndef SVQC
68 string draw_currentSkin;
69 string draw_UseSkinFor(string pic);
70 #endif
71
72 // iterative depth-first search, with fields that go "up", "down left" and "right" in a tree
73 // for each element, funcPre is called first, then funcPre and funcPost for all its children, and funcPost last
74 void depthfirst(entity start, .entity up, .entity downleft, .entity right, void(entity, entity) funcPre, void(entity, entity) funcPost, entity pass);
75
76 float median(float a, float b, float c);
77
78 // converts a number to a string with the indicated number of decimals
79 // works for up to 10 decimals!
80 string ftos_decimals(float number, float decimals);
81
82 float fexists(string f);
83
84 vector colormapPaletteColor(float c, float isPants);
85
86 // unzone the string, and return it as tempstring. Safe to be called on string_null
87 string fstrunzone(string s);
88
89 // database (NOTE: keys are case sensitive)
90 void db_save(float db, string filename);
91 void db_dump(float db, string pFilename);
92 float db_create();
93 float db_load(string filename);
94 void db_close(float db);
95 string db_get(float db, string key);
96 void db_put(float db, string key, string value);
97
98 // stringbuffer loading/saving
99 float buf_load(string filename);
100 void buf_save(float buf, string filename);
101
102 // modulo function
103 #ifndef MENUQC
104 float mod(float a, float b) { return a - (floor(a / b) * b); }
105 #endif
106
107 #define TIME_TO_NTHS(t,n) floor((t) * (n) + 0.4)
108 string format_time(float seconds);
109 string mmsss(float t);
110 string mmssss(float t);
111
112 #define TIME_DECIMALS 2
113 #define TIME_FACTOR 100
114 #define TIME_ENCODED_TOSTRING(n) mmssss(n)
115 #define RACE_RECORD "/race100record/"
116 #define CTS_RECORD "/cts100record/"
117 #define TIME_ENCODE(t) TIME_TO_NTHS(t, TIME_FACTOR)
118 #define TIME_DECODE(n) ((n) / TIME_FACTOR)
119
120 string ScoreString(float vflags, float value);
121
122 float dotproduct(vector a, vector b);
123 vector cross(vector a, vector b);
124
125 void compressShortVector_init();
126 vector decompressShortVector(float data);
127 float compressShortVector(vector vec);
128
129 #ifndef MENUQC
130 float CheckWireframeBox(entity forent, vector v0, vector dvx, vector dvy, vector dvz);
131 #endif
132
133 string fixPriorityList(string pl, float from, float to, float subtract, float complete);
134 string mapPriorityList(string order, string(string) mapfunc);
135 string swapInPriorityList(string order, float i, float j);
136
137 float cvar_value_issafe(string s);
138
139 float cvar_settemp(string pKey, string pValue);
140 float cvar_settemp_restore();
141
142 #ifndef MENUQC
143 // modes: 0 = trust q3map2 (_mini images)
144 //        1 = trust tracebox (_radar images)
145 // in both modes, mapinfo's "size" overrides
146
147 string mi_shortname;
148 vector mi_min;
149 vector mi_max;
150 void get_mi_min_max(float mode);
151
152 vector mi_picmin; // adjusted mins that map to the picture (square)
153 vector mi_picmax; // adjusted maxs that map to the picture (square)
154 vector mi_pictexcoord0; // texcoords of the image corners (after transforming, these are 2D coords too)
155 vector mi_pictexcoord1; // texcoords of the image corners (after transforming, these are 2D coords too)
156 vector mi_pictexcoord2; // texcoords of the image corners (after transforming, these are 2D coords too)
157 vector mi_pictexcoord3; // texcoords of the image corners (after transforming, these are 2D coords too)
158 void get_mi_min_max_texcoords(float mode);
159 #endif
160
161 float almost_equals(float a, float b);
162 float almost_in_bounds(float a, float b, float c);
163
164 float power2of(float e);
165 float log2of(float x);
166
167 const string HEXDIGITS = "0123456789ABCDEF0123456789abcdef";
168 #define HEXDIGIT_TO_DEC_RAW(d) (strstrofs(HEXDIGITS, (d), 0))
169 #define HEXDIGIT_TO_DEC(d) ((HEXDIGIT_TO_DEC_RAW(d) | 0x10) - 0x10)
170 #define DEC_TO_HEXDIGIT(d) (substring(HEXDIGITS, (d), 1))
171
172 vector rgb_to_hsl(vector rgb);
173 vector hsl_to_rgb(vector hsl);
174 vector rgb_to_hsv(vector rgb);
175 vector hsv_to_rgb(vector hsv);
176 string rgb_to_hexcolor(vector rgb);
177
178 float boxesoverlap(vector m1, vector m2, vector m3, vector m4);
179 float boxinsidebox(vector smins, vector smaxs, vector bmins, vector bmaxs);
180
181 typedef float(string s, vector size) textLengthUpToWidth_widthFunction_t;
182 typedef float(string s) textLengthUpToLength_lenFunction_t;
183 float textLengthUpToWidth(string theText, float maxWidth, vector size, textLengthUpToWidth_widthFunction_t tw);
184 string textShortenToWidth(string theText, float maxWidth, vector size, textLengthUpToWidth_widthFunction_t tw);
185 float textLengthUpToLength(string theText, float maxWidth, textLengthUpToLength_lenFunction_t tw);
186 string textShortenToLength(string theText, float maxWidth, textLengthUpToLength_lenFunction_t tw);
187
188 string getWrappedLine_remaining;
189 string getWrappedLine(float w, vector size, textLengthUpToWidth_widthFunction_t tw);
190 string getWrappedLineLen(float w, textLengthUpToLength_lenFunction_t tw);
191
192 float isGametypeInFilter(float gt, float tp, float ts, string pattern);
193
194 typedef void(float i1, float i2, entity pass) swapfunc_t; // is only ever called for i1 < i2
195 typedef float(float i1, float i2, entity pass) comparefunc_t; // <0 for <, ==0 for ==, >0 for > (like strcmp)
196 void shuffle(float n, swapfunc_t swap, entity pass);
197 void heapsort(float n, swapfunc_t swap, comparefunc_t cmp, entity pass);
198
199 string swapwords(string str, float i, float j);
200 string shufflewords(string str);
201
202 string substring_range(string s, float b, float e);
203
204 vector solve_quadratic(float a, float b, float c);
205 // solution 1 -> x
206 // solution 2 -> y
207 // z = 1 if a real solution exists, 0 if not
208 // if no real solution exists, x contains the real part and y the imaginary part of the complex solutions x+iy and x-iy
209
210 vector solve_shotdirection(vector myorg, vector myvel, vector eorg, vector evel, float spd, float newton_style);
211 vector get_shotvelocity(vector myvel, vector mydir, float spd, float newton_style, float mi, float ma);
212
213 void check_unacceptable_compiler_bugs();
214
215 float compressShotOrigin(vector v);
216 vector decompressShotOrigin(float f);
217
218 #ifdef SVQC
219 string rankings_reply, ladder_reply, lsmaps_reply, maplist_reply, monsterlist_reply; // cached replies
220 string records_reply[10];
221 #endif
222
223 float RandomSelection_totalweight;
224 float RandomSelection_best_priority;
225 entity RandomSelection_chosen_ent;
226 float RandomSelection_chosen_float;
227 string RandomSelection_chosen_string;
228 void RandomSelection_Init();
229 void RandomSelection_Add(entity e, float f, string s, float weight, float priority);
230
231 #ifndef MENUQC
232 vector healtharmor_maxdamage(float h, float a, float armorblock, float deathtype); // returns vector: maxdamage, armorideal, 1 if fully armored
233 vector healtharmor_applydamage(float a, float armorblock, float deathtype, float damage); // returns vector: take, save, 0
234 #endif
235
236 string getcurrentmod();
237
238 #ifndef MENUQC
239 #ifdef CSQC
240 float ReadInt24_t();
241 vector ReadInt48_t();
242 vector ReadInt72_t();
243 #else
244 void WriteInt24_t(float dest, float val);
245 void WriteInt48_t(float dest, vector val);
246 void WriteInt72_t(float dest, vector val);
247 #endif
248 #endif
249
250 // the NULL function
251 #ifdef GMQCC
252 #define func_null nil
253 #define string_null nil
254 #else
255 var void func_null(void);
256 var string string_null;
257 #endif
258 float float2range11(float f);
259 float float2range01(float f);
260
261 float gsl_ran_gaussian(float sigma);
262
263 string car(string s); // returns first word
264 string cdr(string s); // returns all but first word
265 float matchacl(string acl, string str); // matches str against ACL acl (with entries +foo*, +foo, +*foo, +*foo*, and same with - for forbidding)
266 float startsWith(string haystack, string needle);
267 float startsWithNocase(string haystack, string needle);
268
269 string get_model_datafilename(string mod, float skn, string fil); // skin -1 will return wildcard, mod string_null will also put wildcard there
270 string get_model_parameters_modelname;
271 float get_model_parameters_modelskin;
272 string get_model_parameters_name;
273 float get_model_parameters_species;
274 string get_model_parameters_sex;
275 float get_model_parameters_weight;
276 float get_model_parameters_age;
277 string get_model_parameters_description;
278 string get_model_parameters_bone_upperbody;
279 string get_model_parameters_bone_weapon;
280 #define MAX_AIM_BONES 4
281 string get_model_parameters_bone_aim[MAX_AIM_BONES];
282 float get_model_parameters_bone_aimweight[MAX_AIM_BONES];
283 float get_model_parameters_fixbone;
284 string get_model_parameters_desc;
285 float get_model_parameters(string mod, float skn); // call with string_null to clear; skin -1 means mod is the filename of the txt file and is to be split
286
287 vector vec2(vector v);
288
289 #ifndef MENUQC
290 vector NearestPointOnBox(entity box, vector org);
291 #endif
292
293 float vercmp(string v1, string v2);
294
295 float u8_strsize(string s);
296
297 // translation helpers
298 string prvm_language;
299 string language_filename(string s);
300 string CTX(string s);
301 #define ZCTX(s) strzone(CTX(s))
302
303 // x-encoding (encoding as zero length invisible string)
304 // encodes approx. 14 bits into 5 bytes of color code string
305 const float XENCODE_MAX = 21295; // 2*22*22*22-1
306 const float XENCODE_LEN = 5;
307 string xencode(float f);
308 float xdecode(string s);
309
310 // Play all sounds via sound7, for access to the extra channels.
311 // Otherwise, channels 8 to 15 would be blocked for a weird QW feature.
312 #define sound(e,c,s,v,a) sound7(e,c,s,v,a,0,0)
313
314 float lowestbit(float f);
315
316 #ifdef CSQC
317 entity ReadCSQCEntity();
318 #endif
319
320 #ifndef MENUQC
321 string strtolower(string s);
322 #endif
323
324 string MakeConsoleSafe(string input);
325
326 #ifndef MENUQC
327 float InterpretBoolean(string input);
328 #endif
329
330 // generic shutdown handler
331 void Shutdown();
332
333 #ifndef MENUQC
334 .float skeleton_bones;
335 void Skeleton_SetBones(entity e);
336 // loops through the tags of model v using counter tagnum
337 #define FOR_EACH_TAG(v) float tagnum; Skeleton_SetBones(v); for(tagnum = 0; tagnum < v.skeleton_bones; tagnum++, gettaginfo(v, tagnum))
338 #endif
339 #ifdef SVQC
340 void WriteApproxPastTime(float dst, float t);
341 #endif
342 #ifdef CSQC
343 float ReadApproxPastTime();
344 #endif
345
346 // execute-stuff-next-frame subsystem
347 void execute_next_frame();
348 void queue_to_execute_next_frame(string s);
349
350 // for marking written-to values as unused where it's a good idea to do this
351 noref float unused_float;
352
353 // a function f with:
354 // f(0) = 0
355 // f(1) = 1
356 // f'(0) = startspeedfactor
357 // f'(1) = endspeedfactor
358 float cubic_speedfunc(float startspeedfactor, float endspeedfactor, float x);
359
360 // checks whether f'(x) = 0 anywhere from 0 to 1
361 // because if this is the case, the function is not usable for platforms
362 // as it may exceed 0..1 bounds, or go in reverse
363 float cubic_speedfunc_is_sane(float startspeedfactor, float endspeedfactor);
364
365 typedef entity(entity cur, entity near, entity pass) findNextEntityNearFunction_t;
366 typedef float(entity a, entity b, entity pass) isConnectedFunction_t;
367 void FindConnectedComponent(entity e, .entity fld, findNextEntityNearFunction_t nxt, isConnectedFunction_t iscon, entity pass);
368
369 // expand multiple arguments into one argument by stripping parenthesis
370 #define XPD(...) __VA_ARGS__
371
372 // Some common varargs functions. Lowercase as they match C.
373 #define printf(...) print(sprintf(__VA_ARGS__))
374 #define dprintf(...) dprint(sprintf(__VA_ARGS__))
375 #define fprintf(file, ...) fputs(file, sprintf(__VA_ARGS__))
376 #define bprintf(...) bprint(sprintf(__VA_ARGS__))
377
378 //#ifndef MENUQC
379 void backtrace(string msg);
380 //#endif
381
382 // color code replace, place inside of sprintf and parse the string... defaults described as constants
383 // foreground/normal colors
384 var string autocvar_hud_colorset_foreground_1 = "2"; // F1 - Green  // primary priority (important names, etc)
385 var string autocvar_hud_colorset_foreground_2 = "3"; // F2 - Yellow // secondary priority (items, locations, numbers, etc)
386 var string autocvar_hud_colorset_foreground_3 = "4"; // F3 - Blue   // tertiary priority or relatively inconsequential text
387 var string autocvar_hud_colorset_foreground_4 = "1"; // F4 - Red    // notice/attention grabbing texting
388 // "kill" colors
389 var string autocvar_hud_colorset_kill_1 = "1"; // K1 - Red    // "bad" or "dangerous" text (death messages against you, kill notifications, etc)
390 var string autocvar_hud_colorset_kill_2 = "3"; // K2 - Yellow // similar to above, but less important... OR, a highlight out of above message type
391 var string autocvar_hud_colorset_kill_3 = "4"; // K3 - Blue   // "good" or "beneficial" text (you fragging someone, etc)
392 // background color
393 var string autocvar_hud_colorset_background = "7"; // BG - White // neutral/unimportant text
394
395 string CCR(string input);
396
397 #ifndef MENUQC
398 #ifdef CSQC
399 #define GENTLE (autocvar_cl_gentle || autocvar_cl_gentle_messages)
400 #else
401 #define GENTLE autocvar_sv_gentle
402 #endif
403 #define normal_or_gentle(normal,gentle) (GENTLE ? ((gentle != "") ? gentle : normal) : normal)
404 #endif
405
406 // allow writing to also pass through to spectators (like so spectators see the same centerprints as players for example)
407 #define WRITESPECTATABLE_MSG_ONE_VARNAME(varname,statement) entity varname; varname = msg_entity; FOR_EACH_REALCLIENT(msg_entity) if(msg_entity == varname || (msg_entity.classname == STR_SPECTATOR && msg_entity.enemy == varname)) statement msg_entity = varname
408 #define WRITESPECTATABLE_MSG_ONE(statement) WRITESPECTATABLE_MSG_ONE_VARNAME(oldmsg_entity, statement)
409 #define WRITESPECTATABLE(msg,statement) if(msg == MSG_ONE) { WRITESPECTATABLE_MSG_ONE(statement); } else statement float WRITESPECTATABLE_workaround = 0
410
411 vector vec3(float x, float y, float z);
412
413 #ifndef MENUQC
414 vector animfixfps(entity e, vector a, vector b);
415 #endif
416
417 #ifdef SVQC
418 void dedicated_print(string input);
419 #endif
420
421 // todo: better way to do this?
422 #ifdef MENUQC
423 #define PROGNAME "MENUQC"
424 #else
425 #ifdef SVQC
426 #define PROGNAME "SVQC"
427 #else
428 #define PROGNAME "CSQC"
429 #endif
430 #endif
431
432 #ifndef MENUQC
433 #define CNT_NORMAL 1
434 #define CNT_GAMESTART 2
435 #define CNT_IDLE 3
436 #define CNT_KILL 4
437 #define CNT_RESPAWN 5
438 #define CNT_ROUNDSTART 6
439 float Announcer_PickNumber(float type, float num);
440 #endif
441
442 #ifndef MENUQC
443 float Mod_Q1BSP_SuperContentsFromNativeContents(float nativecontents);
444 float Mod_Q1BSP_NativeContentsFromSuperContents(float supercontents);
445 #endif
446
447 // Quadratic splines (bezier)
448 vector bezier_quadratic_getpoint(vector a, vector p, vector b, float t);
449 vector bezier_quadratic_getderivative(vector a, vector p, vector b, float t);