]> git.xonotic.org Git - xonotic/darkplaces.git/blob - prvm_cmds.c
physics: fix and refactor unsticking
[xonotic/darkplaces.git] / prvm_cmds.c
1 // AK
2 // Basically every vm builtin cmd should be in here.
3 // All 3 builtin and extension lists can be found here
4 // cause large (I think they will) parts are from pr_cmds the same copyright like in pr_cmds
5 // also applies here
6
7 #include "quakedef.h"
8
9 #include "prvm_cmds.h"
10 #include "libcurl.h"
11 #include <time.h>
12
13 #include "cl_collision.h"
14 #include "clvm_cmds.h"
15 #include "csprogs.h"
16 #include "ft2.h"
17 #include "mdfour.h"
18
19 extern cvar_t prvm_backtraceforwarnings;
20 #ifdef USEODE
21 extern dllhandle_t ode_dll;
22 #endif
23
24 // LadyHavoc: changed this to NOT use a return statement, so that it can be used in functions that must return a value
25 void VM_Warning(prvm_prog_t *prog, const char *fmt, ...)
26 {
27         va_list argptr;
28         char msg[MAX_INPUTLINE];
29         static double recursive = -1;
30         int outfd = sys.outfd;
31
32         // set output to stderr
33         sys.outfd = fileno(stderr);
34
35         va_start(argptr,fmt);
36         dpvsnprintf(msg,sizeof(msg),fmt,argptr);
37         va_end(argptr);
38
39         Con_Printf(CON_WARN "%s VM warning: %s", prog->name, msg);
40
41         // TODO: either add a cvar/cmd to control the state dumping or replace some of the calls with Con_Printf [9/13/2006 Black]
42         if(prvm_backtraceforwarnings.integer && recursive != host.realtime) // NOTE: this compares to the time, just in case if PRVM_PrintState causes a Host_Error and keeps recursive set
43         {
44                 recursive = host.realtime;
45                 PRVM_PrintState(prog, 0);
46                 recursive = -1;
47         }
48
49         // restore configured outfd
50         sys.outfd = outfd;
51 }
52
53
54 //============================================================================
55 // Common
56
57 // TODO DONE: move vm_files and vm_fssearchlist to prvm_prog_t struct
58 // TODO: move vm_files and vm_fssearchlist back [9/13/2006 Black]
59 // TODO: (move vm_files and vm_fssearchlist to prvm_prog_t struct again) [2007-01-23 LadyHavoc]
60 // TODO: will this war ever end? [2007-01-23 LadyHavoc]
61
62 void VM_CheckEmptyString(prvm_prog_t *prog, const char *s)
63 {
64         if (ISWHITESPACE(s[0]))
65                 prog->error_cmd("%s: Bad string", prog->name);
66 }
67
68 qbool PRVM_ConsoleCommand(prvm_prog_t *prog, const char *text, size_t textlen, int *func, qbool preserve_self, int curself, double ptime, const char *error_message)
69 {
70         int restorevm_tempstringsbuf_cursize;
71         int save_self = 0; // hush compiler warning
72         qbool r = false;
73
74         if(!prog->loaded)
75                 return false;
76
77         if(func)
78         {
79                 if(preserve_self)
80                         save_self = PRVM_gameglobaledict(self);
81                 if(ptime)
82                         PRVM_gameglobalfloat(time) = ptime;
83                 PRVM_gameglobaledict(self) = curself;
84                 restorevm_tempstringsbuf_cursize = prog->tempstringsbuf.cursize;
85                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(prog, text, textlen);
86                 prog->ExecuteProgram(prog, *func, error_message);
87                 prog->tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
88                 if(preserve_self)
89                         PRVM_gameglobaledict(self) = save_self;
90                 r = (int) PRVM_G_FLOAT(OFS_RETURN) != 0;
91         }
92
93         return r;
94 }
95
96 void VM_GenerateFrameGroupBlend(prvm_prog_t *prog, framegroupblend_t *framegroupblend, const prvm_edict_t *ed)
97 {
98         // self.frame is the interpolation target (new frame)
99         // self.frame1time is the animation base time for the interpolation target
100         // self.frame2 is the interpolation start (previous frame)
101         // self.frame2time is the animation base time for the interpolation start
102         // self.lerpfrac is the interpolation strength for self.frame2
103         // self.lerpfrac3 is the interpolation strength for self.frame3
104         // self.lerpfrac4 is the interpolation strength for self.frame4
105         // pitch angle on a player model where the animator set up 5 sets of
106         // animations and the csqc simply lerps between sets)
107         framegroupblend[0].frame = (int) PRVM_gameedictfloat(ed, frame     );
108         framegroupblend[1].frame = (int) PRVM_gameedictfloat(ed, frame2    );
109         framegroupblend[2].frame = (int) PRVM_gameedictfloat(ed, frame3    );
110         framegroupblend[3].frame = (int) PRVM_gameedictfloat(ed, frame4    );
111         framegroupblend[0].start =       PRVM_gameedictfloat(ed, frame1time);
112         framegroupblend[1].start =       PRVM_gameedictfloat(ed, frame2time);
113         framegroupblend[2].start =       PRVM_gameedictfloat(ed, frame3time);
114         framegroupblend[3].start =       PRVM_gameedictfloat(ed, frame4time);
115         framegroupblend[1].lerp  =       PRVM_gameedictfloat(ed, lerpfrac  );
116         framegroupblend[2].lerp  =       PRVM_gameedictfloat(ed, lerpfrac3 );
117         framegroupblend[3].lerp  =       PRVM_gameedictfloat(ed, lerpfrac4 );
118         // assume that the (missing) lerpfrac1 is whatever remains after lerpfrac2+lerpfrac3+lerpfrac4 are summed
119         framegroupblend[0].lerp = 1 - framegroupblend[1].lerp - framegroupblend[2].lerp - framegroupblend[3].lerp;
120 }
121
122 // LadyHavoc: quite tempting to break apart this function to reuse the
123 //            duplicated code, but I suspect it is better for performance
124 //            this way
125 void VM_FrameBlendFromFrameGroupBlend(frameblend_t *frameblend, const framegroupblend_t *framegroupblend, const model_t *model, double curtime)
126 {
127         int sub2, numframes, f, i, k;
128         int isfirstframegroup = true;
129         int nolerp;
130         double sublerp, lerp, d;
131         const animscene_t *scene;
132         const framegroupblend_t *g;
133         frameblend_t *blend = frameblend;
134
135         memset(blend, 0, MAX_FRAMEBLENDS * sizeof(*blend));
136
137         // rpolzer: Not testing isanimated here - a model might have
138         // "animations" that move no vertices (but only bones), thus rendering
139         // may assume it's not animated while processing can't.
140         if (!model)
141         {
142                 blend[0].lerp = 1;
143                 return;
144         }
145
146         nolerp = ((model->type == mod_sprite) ? !r_lerpsprites.integer : !r_lerpmodels.integer) || (model->nolerp == true);
147         numframes = model->numframes;
148         for (k = 0, g = framegroupblend;k < MAX_FRAMEGROUPBLENDS;k++, g++)
149         {
150                 f = g->frame;
151                 if ((unsigned int)f >= (unsigned int)numframes)
152                 {
153                         if (developer_extra.integer)
154                                 Con_DPrintf("VM_FrameBlendFromFrameGroupBlend: no such frame %d in model %s\n", f, model->name);
155                         f = 0;
156                 }
157                 d = lerp = g->lerp;
158                 if (lerp <= 0)
159                         continue;
160                 if (nolerp)
161                 {
162                         if (isfirstframegroup)
163                         {
164                                 d = lerp = 1;
165                                 isfirstframegroup = false;
166                         }
167                         else
168                                 continue;
169                 }
170                 if (model->animscenes)
171                 {
172                         scene = model->animscenes + f;
173                         f = scene->firstframe;
174                         if (scene->framecount > 1)
175                         {
176                                 // this code path is only used on .zym models and torches
177                                 sublerp = scene->framerate * (curtime - g->start);
178                                 f = (int) floor(sublerp);
179                                 sublerp -= f;
180                                 sub2 = f + 1;
181                                 if (sublerp < (1.0 / 65536.0f))
182                                         sublerp = 0;
183                                 if (sublerp > (65535.0f / 65536.0f))
184                                         sublerp = 1;
185                                 if (nolerp)
186                                         sublerp = 0;
187                                 if (scene->loop)
188                                 {
189                                         f = (f % scene->framecount);
190                                         sub2 = (sub2 % scene->framecount);
191                                 }
192                                 f = bound(0, f, (scene->framecount - 1)) + scene->firstframe;
193                                 sub2 = bound(0, sub2, (scene->framecount - 1)) + scene->firstframe;
194                                 d = sublerp * lerp;
195                                 // two framelerps produced from one animation
196                                 if (d > 0)
197                                 {
198                                         for (i = 0;i < MAX_FRAMEBLENDS;i++)
199                                         {
200                                                 if (blend[i].lerp <= 0 || blend[i].subframe == sub2)
201                                                 {
202                                                         blend[i].subframe = sub2;
203                                                         blend[i].lerp += d;
204                                                         break;
205                                                 }
206                                         }
207                                 }
208                                 d = (1 - sublerp) * lerp;
209                         }
210                 }
211                 if (d > 0)
212                 {
213                         for (i = 0;i < MAX_FRAMEBLENDS;i++)
214                         {
215                                 if (blend[i].lerp <= 0 || blend[i].subframe == f)
216                                 {
217                                         blend[i].subframe = f;
218                                         blend[i].lerp += d;
219                                         break;
220                                 }
221                         }
222                 }
223         }
224 }
225
226 void VM_UpdateEdictSkeleton(prvm_prog_t *prog, prvm_edict_t *ed, const model_t *edmodel, const frameblend_t *frameblend)
227 {
228         if (ed->priv.server->skeleton.model != edmodel)
229         {
230                 VM_RemoveEdictSkeleton(prog, ed);
231                 ed->priv.server->skeleton.model = edmodel;
232         }
233         if (!ed->priv.server->skeleton.model || !ed->priv.server->skeleton.model->num_bones)
234         {
235                 if(ed->priv.server->skeleton.relativetransforms)
236                         Mem_Free(ed->priv.server->skeleton.relativetransforms);
237                 ed->priv.server->skeleton.relativetransforms = NULL;
238                 return;
239         }
240
241         {
242                 int skeletonindex = -1;
243                 skeleton_t *skeleton;
244                 skeletonindex = (int)PRVM_gameedictfloat(ed, skeletonindex) - 1;
245                 if (skeletonindex >= 0 && skeletonindex < MAX_EDICTS && (skeleton = prog->skeletons[skeletonindex]) && skeleton->model->num_bones == ed->priv.server->skeleton.model->num_bones)
246                 {
247                         // custom skeleton controlled by the game (FTE_CSQC_SKELETONOBJECTS)
248                         if (!ed->priv.server->skeleton.relativetransforms)
249                                 ed->priv.server->skeleton.relativetransforms = (matrix4x4_t *)Mem_Alloc(prog->progs_mempool, ed->priv.server->skeleton.model->num_bones * sizeof(matrix4x4_t));
250                         memcpy(ed->priv.server->skeleton.relativetransforms, skeleton->relativetransforms, ed->priv.server->skeleton.model->num_bones * sizeof(matrix4x4_t));
251                 }
252                 else
253                 {
254                         if(ed->priv.server->skeleton.relativetransforms)
255                                 Mem_Free(ed->priv.server->skeleton.relativetransforms);
256                         ed->priv.server->skeleton.relativetransforms = NULL;
257                 }
258         }
259 }
260
261 void VM_RemoveEdictSkeleton(prvm_prog_t *prog, prvm_edict_t *ed)
262 {
263         if (ed->priv.server->skeleton.relativetransforms)
264                 Mem_Free(ed->priv.server->skeleton.relativetransforms);
265         memset(&ed->priv.server->skeleton, 0, sizeof(ed->priv.server->skeleton));
266 }
267
268
269
270
271 //============================================================================
272 //BUILT-IN FUNCTIONS
273
274 #ifdef WIN32
275         // memccpy() is standard in POSIX.1-2001, POSIX.1-2008, SVr4, 4.3BSD, C23.
276         // Microsoft supports it, but apparently complains if we use it.
277         #undef memccpy
278         #define memccpy _memccpy
279 #endif
280 size_t VM_VarString(prvm_prog_t *prog, int first, char *out, size_t outsize)
281 {
282         int i;
283         const char *s;
284         char *p;
285         char *outend = out + outsize - 1;
286
287         // bones_was_here: && out < outend improves perf significantly in some tests that don't trigger the warning,
288         // which seems odd, surely it would only help when the warning is printed?
289         for (i = first;i < prog->argc && out < outend;i++)
290         {
291                 s = PRVM_G_STRING((OFS_PARM0+i*3));
292                 if (*s)
293                 {
294                         // like dp_stpecpy but with a VM_Warning for use with `prvm_backtraceforwarnings 1`
295                         p = (char *)memccpy(out, s, '\0', (outend + 1) - out);
296                         if (p)
297                                 out = p - 1;
298                         else
299                         {
300                                 VM_Warning(prog, "%lu of %lu bytes available, will truncate %lu byte string \"%s\"\n", (unsigned long)(outend - out), (unsigned long)outsize - 1, (unsigned long)strlen(s), s);
301                                 out = outend;
302                                 *out = '\0';
303                         }
304                 }
305                 else
306                         *out = '\0';
307         }
308
309         return outsize - ((outend + 1) - out);
310 }
311
312 /*
313 =================
314 VM_checkextension
315
316 returns true if the extension is supported by the server
317
318 checkextension(extensionname)
319 =================
320 */
321
322 // kind of helper function
323 static qbool checkextension(prvm_prog_t *prog, const char *name)
324 {
325         const char **e;
326
327         for (e = prog->extensionstring;*e;e++)
328         {
329                 if(!strcasecmp(*e, name))
330                 {
331 #ifdef USEODE
332                         // special sheck for ODE
333                         if (!strncasecmp("DP_PHYSICS_ODE", name, 14))
334                         {
335 #ifndef LINK_TO_LIBODE
336                                 return ode_dll ? true : false;
337 #else
338 #ifdef LINK_TO_LIBODE
339                                 return true;
340 #else
341                                 return false;
342 #endif
343 #endif
344                         }
345 #endif
346
347                         // special sheck for d0_blind_id
348                         if (!strcasecmp("DP_CRYPTO", name))
349                                 return Crypto_Available();
350                         if (!strcasecmp("DP_QC_DIGEST_SHA256", name))
351                                 return Crypto_Available();
352
353                         // special shreck for libcurl
354                         if (!strcasecmp("DP_QC_URI_GET", name) || !strcasecmp("DP_QC_URI_POST", name))
355                                 return Curl_Available();
356
357                         return true;
358                 }
359         }
360         return false;
361 }
362
363 void VM_checkextension(prvm_prog_t *prog)
364 {
365         VM_SAFEPARMCOUNT(1,VM_checkextension);
366
367         PRVM_G_FLOAT(OFS_RETURN) = checkextension(prog, PRVM_G_STRING(OFS_PARM0));
368 }
369
370 /*
371 =================
372 VM_error
373
374 This is a TERMINAL error, which will kill off the entire prog.
375 Dumps self.
376
377 error(value)
378 =================
379 */
380 void VM_error(prvm_prog_t *prog)
381 {
382         prvm_edict_t    *ed;
383         char string[VM_TEMPSTRING_MAXSIZE];
384
385         VM_VarString(prog, 0, string, sizeof(string));
386         Con_Printf(CON_ERROR "======%s ERROR in %s:\n%s\n", prog->name, PRVM_GetString(prog, prog->xfunction->s_name), string);
387         ed = PRVM_PROG_TO_EDICT(PRVM_allglobaledict(self));
388         PRVM_ED_Print(prog, ed, NULL);
389
390         prog->error_cmd("%s: Program error in function %s:\n%s\nTip: read above for entity information\n", prog->name, PRVM_GetString(prog, prog->xfunction->s_name), string);
391 }
392
393 /*
394 =================
395 VM_objerror
396
397 Dumps out self, then an error message.  The program is aborted and self is
398 removed, but the level can continue.
399
400 objerror(value)
401 =================
402 */
403 void VM_objerror(prvm_prog_t *prog)
404 {
405         prvm_edict_t    *ed;
406         char string[VM_TEMPSTRING_MAXSIZE];
407
408         VM_VarString(prog, 0, string, sizeof(string));
409         Con_Printf(CON_ERROR "======OBJECT ERROR======\n"); // , prog->name, PRVM_GetString(prog->xfunction->s_name), string); // or include them? FIXME
410         ed = PRVM_PROG_TO_EDICT(PRVM_allglobaledict(self));
411         PRVM_ED_Print(prog, ed, NULL);
412         PRVM_ED_Free (prog, ed);
413         Con_Printf(CON_ERROR "%s OBJECT ERROR in %s:\n%s\nTip: read above for entity information\n", prog->name, PRVM_GetString(prog, prog->xfunction->s_name), string);
414 }
415
416 /*
417 =================
418 VM_print
419
420 print to console
421
422 print(...[string])
423 =================
424 */
425 void VM_print(prvm_prog_t *prog)
426 {
427         char string[VM_TEMPSTRING_MAXSIZE];
428
429         VM_VarString(prog, 0, string, sizeof(string));
430         Con_Print(string);
431 }
432
433 /*
434 =================
435 VM_bprint
436
437 broadcast print to everyone on server
438
439 bprint(...[string])
440 =================
441 */
442 void VM_bprint(prvm_prog_t *prog)
443 {
444         char string[VM_TEMPSTRING_MAXSIZE];
445
446         if(!sv.active)
447         {
448                 VM_Warning(prog, "VM_bprint: game is not server(%s) !\n", prog->name);
449                 return;
450         }
451
452         VM_VarString(prog, 0, string, sizeof(string));
453         SV_BroadcastPrint(string);
454 }
455
456 /*
457 =================
458 VM_sprint (menu & client but only if server.active == true)
459
460 single print to a specific client
461
462 sprint(float clientnum,...[string])
463 =================
464 */
465 void VM_sprint(prvm_prog_t *prog)
466 {
467         client_t        *client;
468         int                     clientnum;
469         char string[VM_TEMPSTRING_MAXSIZE];
470
471         VM_SAFEPARMCOUNTRANGE(1, 8, VM_sprint);
472
473         //find client for this entity
474         clientnum = (int)PRVM_G_FLOAT(OFS_PARM0);
475         if (!sv.active  || clientnum < 0 || clientnum >= svs.maxclients || !svs.clients[clientnum].active)
476         {
477                 VM_Warning(prog, "VM_sprint: %s: invalid client or server is not active !\n", prog->name);
478                 return;
479         }
480
481         client = svs.clients + clientnum;
482         if (!client->netconnection)
483                 return;
484
485         VM_VarString(prog, 1, string, sizeof(string));
486         MSG_WriteChar(&client->netconnection->message,svc_print);
487         MSG_WriteString(&client->netconnection->message, string);
488 }
489
490 /*
491 =================
492 VM_centerprint
493
494 single print to the screen
495
496 centerprint(value)
497 =================
498 */
499 void VM_centerprint(prvm_prog_t *prog)
500 {
501         char string[VM_TEMPSTRING_MAXSIZE];
502
503         VM_SAFEPARMCOUNTRANGE(1, 8, VM_centerprint);
504         VM_VarString(prog, 0, string, sizeof(string));
505         SCR_CenterPrint(string);
506 }
507
508 /*
509 =================
510 VM_normalize
511
512 vector normalize(vector)
513 =================
514 */
515 void VM_normalize(prvm_prog_t *prog)
516 {
517         prvm_vec_t      *value1;
518         vec3_t  newvalue;
519         double  f;
520
521         VM_SAFEPARMCOUNT(1,VM_normalize);
522
523         value1 = PRVM_G_VECTOR(OFS_PARM0);
524
525         f = VectorLength2(value1);
526         if (f)
527         {
528                 f = 1.0 / sqrt(f);
529                 VectorScale(value1, f, newvalue);
530         }
531         else
532                 VectorClear(newvalue);
533
534         VectorCopy (newvalue, PRVM_G_VECTOR(OFS_RETURN));
535 }
536
537 /*
538 =================
539 VM_vlen
540
541 scalar vlen(vector)
542 =================
543 */
544 void VM_vlen(prvm_prog_t *prog)
545 {
546         VM_SAFEPARMCOUNT(1,VM_vlen);
547         PRVM_G_FLOAT(OFS_RETURN) = VectorLength(PRVM_G_VECTOR(OFS_PARM0));
548 }
549
550 /*
551 =================
552 VM_vectoyaw
553
554 float vectoyaw(vector)
555 =================
556 */
557 void VM_vectoyaw(prvm_prog_t *prog)
558 {
559         prvm_vec_t      *value1;
560         prvm_vec_t      yaw;
561
562         VM_SAFEPARMCOUNT(1,VM_vectoyaw);
563
564         value1 = PRVM_G_VECTOR(OFS_PARM0);
565
566         if (value1[1] == 0 && value1[0] == 0)
567                 yaw = 0;
568         else
569         {
570                 yaw = (int) (atan2(value1[1], value1[0]) * 180 / M_PI);
571                 if (yaw < 0)
572                         yaw += 360;
573         }
574
575         PRVM_G_FLOAT(OFS_RETURN) = yaw;
576 }
577
578
579 /*
580 =================
581 VM_vectoangles
582
583 vector vectoangles(vector[, vector])
584 =================
585 */
586 void VM_vectoangles(prvm_prog_t *prog)
587 {
588         vec3_t result, forward, up;
589         VM_SAFEPARMCOUNTRANGE(1, 2,VM_vectoangles);
590
591         VectorCopy(PRVM_G_VECTOR(OFS_PARM0), forward);
592         if (prog->argc >= 2)
593         {
594                 VectorCopy(PRVM_G_VECTOR(OFS_PARM1), up);
595                 AnglesFromVectors(result, forward, up, true);
596         }
597         else
598                 AnglesFromVectors(result, forward, NULL, true);
599         VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
600 }
601
602 /*
603 =================
604 VM_random
605
606 Returns a random number > 0 and < 1
607
608 float random()
609 =================
610 */
611 void VM_random(prvm_prog_t *prog)
612 {
613         VM_SAFEPARMCOUNT(0,VM_random);
614
615         PRVM_G_FLOAT(OFS_RETURN) = lhrandom(0, 1);
616 }
617
618 /*
619 =========
620 VM_localsound
621
622 localsound(string sample, float chan, float vol)
623 =========
624 */
625 void VM_localsound(prvm_prog_t *prog)
626 {
627         const char *s;
628         float chan, vol;
629
630         VM_SAFEPARMCOUNTRANGE(1, 3,VM_localsound);
631
632         s = PRVM_G_STRING(OFS_PARM0);
633         if(prog->argc == 3)
634         {
635                 chan = PRVM_G_FLOAT(OFS_PARM1);
636                 vol = PRVM_G_FLOAT(OFS_PARM2) == 0 ? 1 : PRVM_G_FLOAT(OFS_PARM2);
637                 if(!S_LocalSoundEx(s, chan, vol))
638                 {
639                         PRVM_G_FLOAT(OFS_RETURN) = -4;
640                         VM_Warning(prog, "VM_localsound: Failed to play %s for %s !\n", s, prog->name);
641                         return;
642                 }
643         }
644         else if(!S_LocalSound (s))
645         {
646                 PRVM_G_FLOAT(OFS_RETURN) = -4;
647                 VM_Warning(prog, "VM_localsound: Failed to play %s for %s !\n", s, prog->name);
648                 return;
649         }
650
651         PRVM_G_FLOAT(OFS_RETURN) = 1;
652 }
653
654 /*
655 =================
656 VM_break
657
658 break()
659 =================
660 */
661 void VM_break(prvm_prog_t *prog)
662 {
663         prog->error_cmd("%s: break statement", prog->name);
664 }
665
666 //============================================================================
667
668 /*
669 =================
670 VM_localcmd_local
671
672 Sends text over to the client's execution buffer
673
674 [localcmd (string, ...) or]
675 cmd (string, ...)
676 =================
677 */
678 void VM_localcmd_local(prvm_prog_t *prog)
679 {
680         char string[VM_TEMPSTRING_MAXSIZE];
681         VM_SAFEPARMCOUNTRANGE(1, 8, VM_localcmd_local);
682         VM_VarString(prog, 0, string, sizeof(string));
683         Cbuf_AddText(cmd_local, string);
684 }
685
686 /*
687 =================
688 VM_localcmd_server
689
690 Sends text over to the server's execution buffer
691
692 [localcmd (string, ...) or]
693 cmd (string, ...)
694 =================
695 */
696 void VM_localcmd_server(prvm_prog_t *prog)
697 {
698         char string[VM_TEMPSTRING_MAXSIZE];
699         VM_SAFEPARMCOUNTRANGE(1, 8, VM_localcmd_server);
700         VM_VarString(prog, 0, string, sizeof(string));
701         Cbuf_AddText(cmd_local, string);
702 }
703
704 static qbool PRVM_Cvar_ReadOk(prvm_prog_t *prog, const char *string)
705 {
706         cvar_t *cvar;
707         cvar = Cvar_FindVar(prog->console_cmd->cvars, string, prog->console_cmd->cvars_flagsmask);
708         return ((cvar) && ((cvar->flags & CF_PRIVATE) == 0));
709 }
710
711 /*
712 =================
713 VM_cvar
714
715 float cvar (string)
716 =================
717 */
718 void VM_cvar(prvm_prog_t *prog)
719 {
720         char string[VM_TEMPSTRING_MAXSIZE];
721         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar);
722         VM_VarString(prog, 0, string, sizeof(string));
723         VM_CheckEmptyString(prog, string);
724         PRVM_G_FLOAT(OFS_RETURN) = PRVM_Cvar_ReadOk(prog, string) ? Cvar_VariableValue(prog->console_cmd->cvars, string, prog->console_cmd->cvars_flagsmask) : 0;
725 }
726
727 /*
728 =================
729 VM_cvar
730
731 float cvar_type (string)
732 float CVAR_TYPEFLAG_EXISTS = 1;
733 float CVAR_TYPEFLAG_SAVED = 2;
734 float CVAR_TYPEFLAG_PRIVATE = 4;
735 float CVAR_TYPEFLAG_ENGINE = 8;
736 float CVAR_TYPEFLAG_HASDESCRIPTION = 16;
737 float CVAR_TYPEFLAG_READONLY = 32;
738 =================
739 */
740 void VM_cvar_type(prvm_prog_t *prog)
741 {
742         char string[VM_TEMPSTRING_MAXSIZE];
743         cvar_t *cvar;
744         int ret;
745
746         VM_SAFEPARMCOUNTRANGE(1, 8, VM_cvar_type);
747         VM_VarString(prog, 0, string, sizeof(string));
748         VM_CheckEmptyString(prog, string);
749         cvar = Cvar_FindVar(prog->console_cmd->cvars, string, prog->console_cmd->cvars_flagsmask);
750
751
752         if(!cvar)
753         {
754                 PRVM_G_FLOAT(OFS_RETURN) = 0;
755                 return; // CVAR_TYPE_NONE
756         }
757
758         ret = 1; // CVAR_EXISTS
759         if(cvar->flags & CF_ARCHIVE)
760                 ret |= 2; // CVAR_TYPE_SAVED
761         if(cvar->flags & CF_PRIVATE)
762                 ret |= 4; // CVAR_TYPE_PRIVATE
763         if(!(cvar->flags & CF_ALLOCATED))
764                 ret |= 8; // CVAR_TYPE_ENGINE
765         if(cvar->description != cvar_dummy_description)
766                 ret |= 16; // CVAR_TYPE_HASDESCRIPTION
767         if(cvar->flags & CF_READONLY)
768                 ret |= 32; // CVAR_TYPE_READONLY
769         
770         PRVM_G_FLOAT(OFS_RETURN) = ret;
771 }
772
773 /*
774 =================
775 VM_cvar_string
776
777 const string    VM_cvar_string (string, ...)
778 =================
779 */
780 void VM_cvar_string(prvm_prog_t *prog)
781 {
782         char cvar_name[VM_TEMPSTRING_MAXSIZE];
783
784         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_string);
785         VM_VarString(prog, 0, cvar_name, sizeof(cvar_name));
786         VM_CheckEmptyString(prog, cvar_name);
787         if (PRVM_Cvar_ReadOk(prog, cvar_name))
788         {
789                 const char *cvar_string = Cvar_VariableString(prog->console_cmd->cvars, cvar_name, prog->console_cmd->cvars_flagsmask);
790                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, cvar_string, strlen(cvar_string));
791         }
792         else
793                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
794 }
795
796
797 /*
798 ========================
799 VM_cvar_defstring
800
801 const string    VM_cvar_defstring (string, ...)
802 ========================
803 */
804 void VM_cvar_defstring(prvm_prog_t *prog)
805 {
806         char cvar_name[VM_TEMPSTRING_MAXSIZE];
807         const char *cvar_defstring;
808
809         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_defstring);
810         VM_VarString(prog, 0, cvar_name, sizeof(cvar_name));
811         VM_CheckEmptyString(prog, cvar_name);
812         cvar_defstring = Cvar_VariableDefString(prog->console_cmd->cvars, cvar_name, prog->console_cmd->cvars_flagsmask);
813         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, cvar_defstring, strlen(cvar_defstring));
814 }
815
816 /*
817 ========================
818 VM_cvar_defstring
819
820 const string    VM_cvar_description (string, ...)
821 ========================
822 */
823 void VM_cvar_description(prvm_prog_t *prog)
824 {
825         char cvar_name[VM_TEMPSTRING_MAXSIZE];
826         const char *cvar_desc;
827
828         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_description);
829         VM_VarString(prog, 0, cvar_name, sizeof(cvar_name));
830         VM_CheckEmptyString(prog, cvar_name);
831         cvar_desc = Cvar_VariableDescription(prog->console_cmd->cvars, cvar_name, prog->console_cmd->cvars_flagsmask);
832         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, cvar_desc, strlen(cvar_desc));
833 }
834 /*
835 =================
836 VM_cvar_set
837
838 void cvar_set (string,string, ...)
839 =================
840 */
841 void VM_cvar_set(prvm_prog_t *prog)
842 {
843         const char *name;
844         char value[VM_TEMPSTRING_MAXSIZE];
845         cvar_t *cvar;
846
847         VM_SAFEPARMCOUNTRANGE(2,8,VM_cvar_set);
848         name = PRVM_G_STRING(OFS_PARM0);
849         VM_CheckEmptyString(prog, name);
850         cvar = Cvar_FindVar(prog->console_cmd->cvars, name, prog->console_cmd->cvars_flagsmask);
851         if (!cvar)
852         {
853                 VM_Warning(prog, "VM_cvar_set: variable %s not found\n", name);
854                 return;
855         }
856         if (cvar->flags & CF_READONLY)
857         {
858                 VM_Warning(prog, "VM_cvar_set: variable %s is read-only\n", cvar->name);
859                 return;
860         }
861         VM_VarString(prog, 1, value, sizeof(value));
862         Cvar_SetQuick(cvar, value);
863 }
864
865 /*
866 =========
867 VM_dprint
868
869 dprint(...[string])
870 =========
871 */
872 void VM_dprint(prvm_prog_t *prog)
873 {
874         char string[VM_TEMPSTRING_MAXSIZE];
875         VM_SAFEPARMCOUNTRANGE(1, 8, VM_dprint);
876         VM_VarString(prog, 0, string, sizeof(string));
877 #if 1
878         Con_DPrintf("%s", string);
879 #else
880         Con_DPrintf("%s: %s", prog->name, string);
881 #endif
882 }
883
884 /*
885 =========
886 VM_ftos
887
888 string  ftos(float)
889 =========
890 */
891
892 void VM_ftos(prvm_prog_t *prog)
893 {
894         prvm_vec_t v;
895         char s[128];
896         size_t slen;
897
898         VM_SAFEPARMCOUNT(1, VM_ftos);
899
900         v = PRVM_G_FLOAT(OFS_PARM0);
901
902         if ((prvm_vec_t)((prvm_int_t)v) == v)
903                 slen = dpsnprintf(s, sizeof(s), "%.0f", v);
904         else
905                 slen = dpsnprintf(s, sizeof(s), "%f", v);
906         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s, slen);
907 }
908
909 /*
910 =========
911 VM_fabs
912
913 float   fabs(float)
914 =========
915 */
916
917 void VM_fabs(prvm_prog_t *prog)
918 {
919         prvm_vec_t v;
920
921         VM_SAFEPARMCOUNT(1,VM_fabs);
922
923         v = PRVM_G_FLOAT(OFS_PARM0);
924         PRVM_G_FLOAT(OFS_RETURN) = fabs(v);
925 }
926
927 /*
928 =========
929 VM_vtos
930
931 string  vtos(vector)
932 =========
933 */
934
935 void VM_vtos(prvm_prog_t *prog)
936 {
937         char s[512];
938         size_t slen;
939
940         VM_SAFEPARMCOUNT(1,VM_vtos);
941
942         slen = dpsnprintf(s, sizeof(s), "'%5.1f %5.1f %5.1f'", PRVM_G_VECTOR(OFS_PARM0)[0], PRVM_G_VECTOR(OFS_PARM0)[1], PRVM_G_VECTOR(OFS_PARM0)[2]);
943         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s, slen);
944 }
945
946 /*
947 =========
948 VM_etos
949
950 string  etos(entity)
951 =========
952 */
953
954 void VM_etos(prvm_prog_t *prog)
955 {
956         char s[128];
957         size_t slen;
958
959         VM_SAFEPARMCOUNT(1, VM_etos);
960
961         slen = dpsnprintf(s, sizeof(s), "entity %i", PRVM_G_EDICTNUM(OFS_PARM0));
962         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s, slen);
963 }
964
965 /*
966 =========
967 VM_stof
968
969 float stof(...[string])
970 =========
971 */
972 void VM_stof(prvm_prog_t *prog)
973 {
974         char string[VM_TEMPSTRING_MAXSIZE];
975         VM_SAFEPARMCOUNTRANGE(1, 8, VM_stof);
976         VM_VarString(prog, 0, string, sizeof(string));
977         PRVM_G_FLOAT(OFS_RETURN) = atof(string);
978 }
979
980 /*
981 ========================
982 VM_itof
983
984 float itof(int ent)
985 ========================
986 */
987 void VM_itof(prvm_prog_t *prog)
988 {
989         VM_SAFEPARMCOUNT(1, VM_itof);
990         PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
991 }
992
993 /*
994 ========================
995 VM_ftoe
996
997 entity ftoe(float num)
998 ========================
999 */
1000 void VM_ftoe(prvm_prog_t *prog)
1001 {
1002         prvm_int_t ent;
1003         VM_SAFEPARMCOUNT(1, VM_ftoe);
1004
1005         ent = (prvm_int_t)PRVM_G_FLOAT(OFS_PARM0);
1006         if (ent < 0 || ent >= prog->max_edicts || PRVM_PROG_TO_EDICT(ent)->free)
1007                 ent = 0; // return world instead of a free or invalid entity
1008
1009         PRVM_G_INT(OFS_RETURN) = ent;
1010 }
1011
1012 /*
1013 ========================
1014 VM_etof
1015
1016 float etof(entity ent)
1017 ========================
1018 */
1019 void VM_etof(prvm_prog_t *prog)
1020 {
1021         VM_SAFEPARMCOUNT(1, VM_etof);
1022         PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_EDICTNUM(OFS_PARM0);
1023 }
1024
1025 /*
1026 =========
1027 VM_strftime
1028
1029 string strftime(float uselocaltime, string[, string ...])
1030 =========
1031 */
1032 void VM_strftime(prvm_prog_t *prog)
1033 {
1034         time_t t;
1035 #if _MSC_VER >= 1400
1036         struct tm tm;
1037         int tmresult;
1038 #else
1039         struct tm *tm;
1040 #endif
1041         char fmt[VM_TEMPSTRING_MAXSIZE];
1042         char result[VM_TEMPSTRING_MAXSIZE];
1043         size_t result_len;
1044
1045         VM_SAFEPARMCOUNTRANGE(2, 8, VM_strftime);
1046         VM_VarString(prog, 1, fmt, sizeof(fmt));
1047         t = time(NULL);
1048 #if _MSC_VER >= 1400
1049         if (PRVM_G_FLOAT(OFS_PARM0))
1050                 tmresult = localtime_s(&tm, &t);
1051         else
1052                 tmresult = gmtime_s(&tm, &t);
1053         if (!tmresult)
1054 #else
1055         if (PRVM_G_FLOAT(OFS_PARM0))
1056                 tm = localtime(&t);
1057         else
1058                 tm = gmtime(&t);
1059         if (!tm)
1060 #endif
1061         {
1062                 PRVM_G_INT(OFS_RETURN) = 0;
1063                 return;
1064         }
1065 #if _MSC_VER >= 1400
1066         result_len = strftime(result, sizeof(result), fmt, &tm);
1067 #else
1068         result_len = strftime(result, sizeof(result), fmt, tm);
1069 #endif
1070         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, result, result_len);
1071 }
1072
1073 /*
1074 =========
1075 VM_spawn
1076
1077 entity spawn()
1078 =========
1079 */
1080
1081 void VM_spawn(prvm_prog_t *prog)
1082 {
1083         prvm_edict_t    *ed;
1084         VM_SAFEPARMCOUNT(0, VM_spawn);
1085         prog->xfunction->builtinsprofile += 20;
1086         ed = PRVM_ED_Alloc(prog);
1087         VM_RETURN_EDICT(ed);
1088 }
1089
1090 /*
1091 =========
1092 VM_remove
1093
1094 remove(entity e)
1095 =========
1096 */
1097
1098 void VM_remove(prvm_prog_t *prog)
1099 {
1100         prvm_edict_t    *ed;
1101         prog->xfunction->builtinsprofile += 20;
1102
1103         VM_SAFEPARMCOUNT(1, VM_remove);
1104
1105         ed = PRVM_G_EDICT(OFS_PARM0);
1106         if( PRVM_NUM_FOR_EDICT(ed) <= prog->reserved_edicts )
1107         {
1108                 if (developer.integer > 0)
1109                         VM_Warning(prog, "VM_remove: tried to remove the null entity or a reserved entity!\n" );
1110         }
1111         else if( ed->free )
1112         {
1113                 if (developer.integer > 0)
1114                         VM_Warning(prog, "VM_remove: tried to remove an already freed entity!\n" );
1115         }
1116         else
1117                 PRVM_ED_Free (prog, ed);
1118 }
1119
1120 /*
1121 =========
1122 VM_find
1123
1124 entity  find(entity start, .string field, string match)
1125 =========
1126 */
1127
1128 void VM_find(prvm_prog_t *prog)
1129 {
1130         int             e;
1131         int             f;
1132         const char      *s, *t;
1133         prvm_edict_t    *ed;
1134
1135         VM_SAFEPARMCOUNT(3,VM_find);
1136
1137         e = PRVM_G_EDICTNUM(OFS_PARM0);
1138         f = PRVM_G_INT(OFS_PARM1);
1139         s = PRVM_G_STRING(OFS_PARM2);
1140
1141         // LadyHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
1142         // expects it to find all the monsters, so we must be careful to support
1143         // searching for ""
1144
1145         for (e++ ; e < prog->num_edicts ; e++)
1146         {
1147                 prog->xfunction->builtinsprofile++;
1148                 ed = PRVM_EDICT_NUM(e);
1149                 if (ed->free)
1150                         continue;
1151                 t = PRVM_E_STRING(ed,f);
1152                 if (!t)
1153                         t = "";
1154                 if (!strcmp(t,s))
1155                 {
1156                         VM_RETURN_EDICT(ed);
1157                         return;
1158                 }
1159         }
1160
1161         VM_RETURN_EDICT(prog->edicts);
1162 }
1163
1164 /*
1165 =========
1166 VM_findfloat
1167
1168   entity        findfloat(entity start, .float field, float match)
1169   entity        findentity(entity start, .entity field, entity match)
1170 =========
1171 */
1172 // LadyHavoc: added this for searching float, int, and entity reference fields
1173 void VM_findfloat(prvm_prog_t *prog)
1174 {
1175         int             e;
1176         int             f;
1177         prvm_vec_t      s;
1178         prvm_edict_t    *ed;
1179
1180         VM_SAFEPARMCOUNT(3,VM_findfloat);
1181
1182         e = PRVM_G_EDICTNUM(OFS_PARM0);
1183         f = PRVM_G_INT(OFS_PARM1);
1184         s = PRVM_G_FLOAT(OFS_PARM2);
1185
1186         for (e++ ; e < prog->num_edicts ; e++)
1187         {
1188                 prog->xfunction->builtinsprofile++;
1189                 ed = PRVM_EDICT_NUM(e);
1190                 if (ed->free)
1191                         continue;
1192                 if (PRVM_E_FLOAT(ed,f) == s)
1193                 {
1194                         VM_RETURN_EDICT(ed);
1195                         return;
1196                 }
1197         }
1198
1199         VM_RETURN_EDICT(prog->edicts);
1200 }
1201
1202 /*
1203 =========
1204 VM_findchain
1205
1206 entity  findchain(.string field, string match)
1207 =========
1208 */
1209 // chained search for strings in entity fields
1210 // entity(.string field, string match) findchain = #402;
1211 void VM_findchain(prvm_prog_t *prog)
1212 {
1213         int             i;
1214         int             f;
1215         const char      *s, *t;
1216         prvm_edict_t    *ent, *chain;
1217         int chainfield;
1218
1219         VM_SAFEPARMCOUNTRANGE(2,3,VM_findchain);
1220
1221         if(prog->argc == 3)
1222                 chainfield = PRVM_G_INT(OFS_PARM2);
1223         else
1224                 chainfield = prog->fieldoffsets.chain;
1225         if (chainfield < 0)
1226                 prog->error_cmd("VM_findchain: %s doesnt have the specified chain field !", prog->name);
1227
1228         chain = prog->edicts;
1229
1230         f = PRVM_G_INT(OFS_PARM0);
1231         s = PRVM_G_STRING(OFS_PARM1);
1232
1233         // LadyHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
1234         // expects it to find all the monsters, so we must be careful to support
1235         // searching for ""
1236
1237         ent = PRVM_NEXT_EDICT(prog->edicts);
1238         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1239         {
1240                 prog->xfunction->builtinsprofile++;
1241                 if (ent->free)
1242                         continue;
1243                 t = PRVM_E_STRING(ent,f);
1244                 if (!t)
1245                         t = "";
1246                 if (strcmp(t,s))
1247                         continue;
1248
1249                 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_NUM_FOR_EDICT(chain);
1250                 chain = ent;
1251         }
1252
1253         VM_RETURN_EDICT(chain);
1254 }
1255
1256 /*
1257 =========
1258 VM_findchainfloat
1259
1260 entity  findchainfloat(.string field, float match)
1261 entity  findchainentity(.string field, entity match)
1262 =========
1263 */
1264 // LadyHavoc: chained search for float, int, and entity reference fields
1265 // entity(.string field, float match) findchainfloat = #403;
1266 void VM_findchainfloat(prvm_prog_t *prog)
1267 {
1268         int             i;
1269         int             f;
1270         prvm_vec_t      s;
1271         prvm_edict_t    *ent, *chain;
1272         int chainfield;
1273
1274         VM_SAFEPARMCOUNTRANGE(2, 3, VM_findchainfloat);
1275
1276         if(prog->argc == 3)
1277                 chainfield = PRVM_G_INT(OFS_PARM2);
1278         else
1279                 chainfield = prog->fieldoffsets.chain;
1280         if (chainfield < 0)
1281                 prog->error_cmd("VM_findchainfloat: %s doesnt have the specified chain field !", prog->name);
1282
1283         chain = (prvm_edict_t *)prog->edicts;
1284
1285         f = PRVM_G_INT(OFS_PARM0);
1286         s = PRVM_G_FLOAT(OFS_PARM1);
1287
1288         ent = PRVM_NEXT_EDICT(prog->edicts);
1289         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1290         {
1291                 prog->xfunction->builtinsprofile++;
1292                 if (ent->free)
1293                         continue;
1294                 if (PRVM_E_FLOAT(ent,f) != s)
1295                         continue;
1296
1297                 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_EDICT_TO_PROG(chain);
1298                 chain = ent;
1299         }
1300
1301         VM_RETURN_EDICT(chain);
1302 }
1303
1304 /*
1305 ========================
1306 VM_findflags
1307
1308 entity  findflags(entity start, .float field, float match)
1309 ========================
1310 */
1311 // LadyHavoc: search for flags in float fields
1312 void VM_findflags(prvm_prog_t *prog)
1313 {
1314         prvm_int_t      e;
1315         prvm_int_t      f;
1316         prvm_int_t      s;
1317         prvm_edict_t    *ed;
1318
1319         VM_SAFEPARMCOUNT(3, VM_findflags);
1320
1321
1322         e = PRVM_G_EDICTNUM(OFS_PARM0);
1323         f = PRVM_G_INT(OFS_PARM1);
1324         s = (prvm_int_t)PRVM_G_FLOAT(OFS_PARM2);
1325
1326         for (e++ ; e < prog->num_edicts ; e++)
1327         {
1328                 prog->xfunction->builtinsprofile++;
1329                 ed = PRVM_EDICT_NUM(e);
1330                 if (ed->free)
1331                         continue;
1332                 if (!PRVM_E_FLOAT(ed,f))
1333                         continue;
1334                 if ((prvm_int_t)PRVM_E_FLOAT(ed,f) & s)
1335                 {
1336                         VM_RETURN_EDICT(ed);
1337                         return;
1338                 }
1339         }
1340
1341         VM_RETURN_EDICT(prog->edicts);
1342 }
1343
1344 /*
1345 ========================
1346 VM_findchainflags
1347
1348 entity  findchainflags(.float field, float match)
1349 ========================
1350 */
1351 // LadyHavoc: chained search for flags in float fields
1352 void VM_findchainflags(prvm_prog_t *prog)
1353 {
1354         prvm_int_t              i;
1355         prvm_int_t              f;
1356         prvm_int_t              s;
1357         prvm_edict_t    *ent, *chain;
1358         int chainfield;
1359
1360         VM_SAFEPARMCOUNTRANGE(2, 3, VM_findchainflags);
1361
1362         if(prog->argc == 3)
1363                 chainfield = PRVM_G_INT(OFS_PARM2);
1364         else
1365                 chainfield = prog->fieldoffsets.chain;
1366         if (chainfield < 0)
1367                 prog->error_cmd("VM_findchainflags: %s doesnt have the specified chain field !", prog->name);
1368
1369         chain = (prvm_edict_t *)prog->edicts;
1370
1371         f = PRVM_G_INT(OFS_PARM0);
1372         s = (prvm_int_t)PRVM_G_FLOAT(OFS_PARM1);
1373
1374         ent = PRVM_NEXT_EDICT(prog->edicts);
1375         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1376         {
1377                 prog->xfunction->builtinsprofile++;
1378                 if (ent->free)
1379                         continue;
1380                 if (!PRVM_E_FLOAT(ent,f))
1381                         continue;
1382                 if (!((prvm_int_t)PRVM_E_FLOAT(ent,f) & s))
1383                         continue;
1384
1385                 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_EDICT_TO_PROG(chain);
1386                 chain = ent;
1387         }
1388
1389         VM_RETURN_EDICT(chain);
1390 }
1391
1392 /*
1393 =========
1394 VM_precache_sound
1395
1396 string  precache_sound (string sample)
1397 =========
1398 */
1399 void VM_precache_sound(prvm_prog_t *prog)
1400 {
1401         const char *s;
1402
1403         VM_SAFEPARMCOUNT(1, VM_precache_sound);
1404
1405         s = PRVM_G_STRING(OFS_PARM0);
1406         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
1407         //VM_CheckEmptyString(prog, s);
1408
1409         if(snd_initialized.integer && !S_PrecacheSound(s, true, true))
1410         {
1411                 VM_Warning(prog, "VM_precache_sound: Failed to load %s for %s\n", s, prog->name);
1412                 return;
1413         }
1414 }
1415
1416 /*
1417 =================
1418 VM_precache_file
1419
1420 returns the same string as output
1421
1422 does nothing, only used by qcc to build .pak archives
1423 =================
1424 */
1425 void VM_precache_file(prvm_prog_t *prog)
1426 {
1427         VM_SAFEPARMCOUNT(1,VM_precache_file);
1428         // precache_file is only used to copy files with qcc, it does nothing
1429         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
1430 }
1431
1432 /*
1433 =========
1434 VM_coredump
1435
1436 coredump()
1437 =========
1438 */
1439 void VM_coredump(prvm_prog_t *prog)
1440 {
1441         VM_SAFEPARMCOUNT(0,VM_coredump);
1442
1443         Cbuf_AddText(cmd_local, "prvm_edicts ");
1444         Cbuf_AddText(cmd_local, prog->name);
1445         Cbuf_AddText(cmd_local, "\n");
1446 }
1447
1448 /*
1449 =========
1450 VM_stackdump
1451
1452 stackdump()
1453 =========
1454 */
1455 void VM_stackdump(prvm_prog_t *prog)
1456 {
1457         VM_SAFEPARMCOUNT(0, VM_stackdump);
1458
1459         PRVM_StackTrace(prog);
1460 }
1461
1462 /*
1463 =========
1464 VM_crash
1465
1466 crash()
1467 =========
1468 */
1469
1470 void VM_crash(prvm_prog_t *prog)
1471 {
1472         VM_SAFEPARMCOUNT(0, VM_crash);
1473
1474         prog->error_cmd("Crash called by %s",prog->name);
1475 }
1476
1477 /*
1478 =========
1479 VM_traceon
1480
1481 traceon()
1482 =========
1483 */
1484 void VM_traceon(prvm_prog_t *prog)
1485 {
1486         VM_SAFEPARMCOUNT(0,VM_traceon);
1487
1488         prog->trace = true;
1489 }
1490
1491 /*
1492 =========
1493 VM_traceoff
1494
1495 traceoff()
1496 =========
1497 */
1498 void VM_traceoff(prvm_prog_t *prog)
1499 {
1500         VM_SAFEPARMCOUNT(0,VM_traceoff);
1501
1502         prog->trace = false;
1503 }
1504
1505 /*
1506 =========
1507 VM_eprint
1508
1509 eprint(entity e)
1510 =========
1511 */
1512 void VM_eprint(prvm_prog_t *prog)
1513 {
1514         VM_SAFEPARMCOUNT(1,VM_eprint);
1515
1516         PRVM_ED_PrintNum (prog, PRVM_G_EDICTNUM(OFS_PARM0), NULL);
1517 }
1518
1519 /*
1520 =========
1521 VM_rint
1522
1523 float   rint(float)
1524 =========
1525 */
1526 void VM_rint(prvm_prog_t *prog)
1527 {
1528         prvm_vec_t f;
1529         VM_SAFEPARMCOUNT(1,VM_rint);
1530
1531         f = PRVM_G_FLOAT(OFS_PARM0);
1532         if (f > 0)
1533                 PRVM_G_FLOAT(OFS_RETURN) = floor(f + 0.5);
1534         else
1535                 PRVM_G_FLOAT(OFS_RETURN) = ceil(f - 0.5);
1536 }
1537
1538 /*
1539 =========
1540 VM_floor
1541
1542 float   floor(float)
1543 =========
1544 */
1545 void VM_floor(prvm_prog_t *prog)
1546 {
1547         VM_SAFEPARMCOUNT(1,VM_floor);
1548
1549         PRVM_G_FLOAT(OFS_RETURN) = floor(PRVM_G_FLOAT(OFS_PARM0));
1550 }
1551
1552 /*
1553 =========
1554 VM_ceil
1555
1556 float   ceil(float)
1557 =========
1558 */
1559 void VM_ceil(prvm_prog_t *prog)
1560 {
1561         VM_SAFEPARMCOUNT(1,VM_ceil);
1562
1563         PRVM_G_FLOAT(OFS_RETURN) = ceil(PRVM_G_FLOAT(OFS_PARM0));
1564 }
1565
1566
1567 /*
1568 =============
1569 VM_nextent
1570
1571 entity  nextent(entity)
1572 =============
1573 */
1574 void VM_nextent(prvm_prog_t *prog)
1575 {
1576         int             i;
1577         prvm_edict_t    *ent;
1578
1579         VM_SAFEPARMCOUNT(1, VM_nextent);
1580
1581         i = PRVM_G_EDICTNUM(OFS_PARM0);
1582         while (1)
1583         {
1584                 prog->xfunction->builtinsprofile++;
1585                 i++;
1586                 if (i == prog->num_edicts)
1587                 {
1588                         VM_RETURN_EDICT(prog->edicts);
1589                         return;
1590                 }
1591                 ent = PRVM_EDICT_NUM(i);
1592                 if (!ent->free)
1593                 {
1594                         VM_RETURN_EDICT(ent);
1595                         return;
1596                 }
1597         }
1598 }
1599
1600 //=============================================================================
1601
1602 /*
1603 ==============
1604 VM_changelevel
1605 server and menu
1606
1607 changelevel(string map)
1608 ==============
1609 */
1610 void VM_changelevel(prvm_prog_t *prog)
1611 {
1612         char vabuf[1024];
1613         VM_SAFEPARMCOUNT(1, VM_changelevel);
1614
1615         if(!sv.active)
1616         {
1617                 VM_Warning(prog, "VM_changelevel: game is not server (%s)\n", prog->name);
1618                 return;
1619         }
1620
1621 // make sure we don't issue two changelevels
1622         if (svs.changelevel_issued)
1623                 return;
1624         svs.changelevel_issued = true;
1625
1626         Cbuf_AddText(cmd_local, va(vabuf, sizeof(vabuf), "changelevel %s\n", PRVM_G_STRING(OFS_PARM0)));
1627 }
1628
1629 /*
1630 =========
1631 VM_sin
1632
1633 float   sin(float)
1634 =========
1635 */
1636 void VM_sin(prvm_prog_t *prog)
1637 {
1638         VM_SAFEPARMCOUNT(1,VM_sin);
1639         PRVM_G_FLOAT(OFS_RETURN) = sin(PRVM_G_FLOAT(OFS_PARM0));
1640 }
1641
1642 /*
1643 =========
1644 VM_cos
1645 float   cos(float)
1646 =========
1647 */
1648 void VM_cos(prvm_prog_t *prog)
1649 {
1650         VM_SAFEPARMCOUNT(1,VM_cos);
1651         PRVM_G_FLOAT(OFS_RETURN) = cos(PRVM_G_FLOAT(OFS_PARM0));
1652 }
1653
1654 /*
1655 =========
1656 VM_sqrt
1657
1658 float   sqrt(float)
1659 =========
1660 */
1661 void VM_sqrt(prvm_prog_t *prog)
1662 {
1663         VM_SAFEPARMCOUNT(1,VM_sqrt);
1664         PRVM_G_FLOAT(OFS_RETURN) = sqrt(PRVM_G_FLOAT(OFS_PARM0));
1665 }
1666
1667 /*
1668 =========
1669 VM_asin
1670
1671 float   asin(float)
1672 =========
1673 */
1674 void VM_asin(prvm_prog_t *prog)
1675 {
1676         VM_SAFEPARMCOUNT(1,VM_asin);
1677         PRVM_G_FLOAT(OFS_RETURN) = asin(PRVM_G_FLOAT(OFS_PARM0));
1678 }
1679
1680 /*
1681 =========
1682 VM_acos
1683 float   acos(float)
1684 =========
1685 */
1686 void VM_acos(prvm_prog_t *prog)
1687 {
1688         VM_SAFEPARMCOUNT(1,VM_acos);
1689         PRVM_G_FLOAT(OFS_RETURN) = acos(PRVM_G_FLOAT(OFS_PARM0));
1690 }
1691
1692 /*
1693 =========
1694 VM_atan
1695 float   atan(float)
1696 =========
1697 */
1698 void VM_atan(prvm_prog_t *prog)
1699 {
1700         VM_SAFEPARMCOUNT(1,VM_atan);
1701         PRVM_G_FLOAT(OFS_RETURN) = atan(PRVM_G_FLOAT(OFS_PARM0));
1702 }
1703
1704 /*
1705 =========
1706 VM_atan2
1707 float   atan2(float,float)
1708 =========
1709 */
1710 void VM_atan2(prvm_prog_t *prog)
1711 {
1712         VM_SAFEPARMCOUNT(2,VM_atan2);
1713         PRVM_G_FLOAT(OFS_RETURN) = atan2(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1714 }
1715
1716 /*
1717 =========
1718 VM_tan
1719 float   tan(float)
1720 =========
1721 */
1722 void VM_tan(prvm_prog_t *prog)
1723 {
1724         VM_SAFEPARMCOUNT(1,VM_tan);
1725         PRVM_G_FLOAT(OFS_RETURN) = tan(PRVM_G_FLOAT(OFS_PARM0));
1726 }
1727
1728 /*
1729 =================
1730 VM_randomvec
1731
1732 Returns a vector of length < 1 and > 0
1733
1734 vector randomvec()
1735 =================
1736 */
1737 void VM_randomvec(prvm_prog_t *prog)
1738 {
1739         vec3_t temp;
1740         VM_SAFEPARMCOUNT(0, VM_randomvec);
1741         VectorRandom(temp);
1742         VectorCopy(temp, PRVM_G_VECTOR(OFS_RETURN));
1743 }
1744
1745 //=============================================================================
1746
1747 /*
1748 =========
1749 VM_registercvar
1750
1751 float   registercvar (string name, string value[, float flags])
1752 =========
1753 */
1754 void VM_registercvar(prvm_prog_t *prog)
1755 {
1756         const char *name, *value;
1757         unsigned flags;
1758
1759         VM_SAFEPARMCOUNTRANGE(2, 3, VM_registercvar);
1760
1761         name = PRVM_G_STRING(OFS_PARM0);
1762         value = PRVM_G_STRING(OFS_PARM1);
1763         flags = prog->argc >= 3 ? (int)PRVM_G_FLOAT(OFS_PARM2) : 0;
1764         PRVM_G_FLOAT(OFS_RETURN) = 0;
1765
1766         if(flags > CF_MAXFLAGSVAL)
1767                 return;
1768
1769 // first check to see if it has already been defined
1770         if (Cvar_FindVar (prog->console_cmd->cvars, name, prog->console_cmd->cvars_flagsmask))
1771                 return;
1772
1773 // check for overlap with a command
1774         if (Cmd_Exists(cmd_local, name))
1775         {
1776                 VM_Warning(prog, "VM_registercvar: %s is a command\n", name);
1777                 return;
1778         }
1779
1780         Cvar_Get(prog->console_cmd->cvars, name, value, prog->console_cmd->cvars_flagsmask | flags, NULL);
1781
1782         PRVM_G_FLOAT(OFS_RETURN) = 1; // success
1783 }
1784
1785
1786 /*
1787 =================
1788 VM_min
1789
1790 returns the minimum of two supplied floats
1791
1792 float min(float a, float b, ...[float])
1793 =================
1794 */
1795 void VM_min(prvm_prog_t *prog)
1796 {
1797         VM_SAFEPARMCOUNTRANGE(2, 8, VM_min);
1798         // LadyHavoc: 3+ argument enhancement suggested by FrikaC
1799         if (prog->argc >= 3)
1800         {
1801                 int i;
1802                 float f = PRVM_G_FLOAT(OFS_PARM0);
1803                 for (i = 1;i < prog->argc;i++)
1804                         if (f > PRVM_G_FLOAT((OFS_PARM0+i*3)))
1805                                 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1806                 PRVM_G_FLOAT(OFS_RETURN) = f;
1807         }
1808         else
1809                 PRVM_G_FLOAT(OFS_RETURN) = min(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1810 }
1811
1812 /*
1813 =================
1814 VM_max
1815
1816 returns the maximum of two supplied floats
1817
1818 float   max(float a, float b, ...[float])
1819 =================
1820 */
1821 void VM_max(prvm_prog_t *prog)
1822 {
1823         VM_SAFEPARMCOUNTRANGE(2, 8, VM_max);
1824         // LadyHavoc: 3+ argument enhancement suggested by FrikaC
1825         if (prog->argc >= 3)
1826         {
1827                 int i;
1828                 float f = PRVM_G_FLOAT(OFS_PARM0);
1829                 for (i = 1;i < prog->argc;i++)
1830                         if (f < PRVM_G_FLOAT((OFS_PARM0+i*3)))
1831                                 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1832                 PRVM_G_FLOAT(OFS_RETURN) = f;
1833         }
1834         else
1835                 PRVM_G_FLOAT(OFS_RETURN) = max(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1836 }
1837
1838 /*
1839 =================
1840 VM_bound
1841
1842 returns number bounded by supplied range
1843
1844 float   bound(float min, float value, float max)
1845 =================
1846 */
1847 void VM_bound(prvm_prog_t *prog)
1848 {
1849         VM_SAFEPARMCOUNT(3,VM_bound);
1850         PRVM_G_FLOAT(OFS_RETURN) = bound(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1), PRVM_G_FLOAT(OFS_PARM2));
1851 }
1852
1853 /*
1854 =================
1855 VM_pow
1856
1857 returns a raised to power b
1858
1859 float   pow(float a, float b)
1860 =================
1861 */
1862 void VM_pow(prvm_prog_t *prog)
1863 {
1864         VM_SAFEPARMCOUNT(2,VM_pow);
1865         PRVM_G_FLOAT(OFS_RETURN) = pow(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1866 }
1867
1868 void VM_log(prvm_prog_t *prog)
1869 {
1870         VM_SAFEPARMCOUNT(1,VM_log);
1871         PRVM_G_FLOAT(OFS_RETURN) = log(PRVM_G_FLOAT(OFS_PARM0));
1872 }
1873
1874 void VM_Files_Init(prvm_prog_t *prog)
1875 {
1876         int i;
1877         for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1878                 prog->openfiles[i] = NULL;
1879 }
1880
1881 void VM_Files_CloseAll(prvm_prog_t *prog)
1882 {
1883         int i;
1884         for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1885         {
1886                 if (prog->openfiles[i])
1887                         FS_Close(prog->openfiles[i]);
1888                 prog->openfiles[i] = NULL;
1889         }
1890 }
1891
1892 static qfile_t *VM_GetFileHandle(prvm_prog_t *prog, int index)
1893 {
1894         if (index < 0 || index >= PRVM_MAX_OPENFILES)
1895         {
1896                 Con_Printf("VM_GetFileHandle: invalid file handle %i used in %s\n", index, prog->name);
1897                 return NULL;
1898         }
1899         if (prog->openfiles[index] == NULL)
1900         {
1901                 Con_Printf("VM_GetFileHandle: no such file handle %i (or file has been closed) in %s\n", index, prog->name);
1902                 return NULL;
1903         }
1904         return prog->openfiles[index];
1905 }
1906
1907 /*
1908 =========
1909 VM_fopen
1910
1911 float   fopen(string filename, float mode)
1912 =========
1913 */
1914 // float(string filename, float mode) fopen = #110;
1915 // opens a file inside quake/gamedir/data/ (mode is FILE_READ, FILE_APPEND, or FILE_WRITE),
1916 // returns fhandle >= 0 if successful, or fhandle < 0 if unable to open file for any reason
1917 void VM_fopen(prvm_prog_t *prog)
1918 {
1919         int filenum, mode;
1920         const char *modestring, *filename;
1921         char vabuf[1024];
1922
1923         VM_SAFEPARMCOUNT(2,VM_fopen);
1924
1925         for (filenum = 0;filenum < PRVM_MAX_OPENFILES;filenum++)
1926                 if (prog->openfiles[filenum] == NULL)
1927                         break;
1928         if (filenum >= PRVM_MAX_OPENFILES)
1929         {
1930                 PRVM_G_FLOAT(OFS_RETURN) = -2;
1931                 VM_Warning(prog, "VM_fopen: %s ran out of file handles (%i)\n", prog->name, PRVM_MAX_OPENFILES);
1932                 return;
1933         }
1934         filename = PRVM_G_STRING(OFS_PARM0);
1935         mode = (int)PRVM_G_FLOAT(OFS_PARM1);
1936         switch(mode)
1937         {
1938         case 0: // FILE_READ
1939                 modestring = "rb";
1940                 prog->openfiles[filenum] = FS_OpenVirtualFile(va(vabuf, sizeof(vabuf), "data/%s", filename), false);
1941                 if (prog->openfiles[filenum] == NULL)
1942                         prog->openfiles[filenum] = FS_OpenVirtualFile(va(vabuf, sizeof(vabuf), "%s", filename), false);
1943                 break;
1944         case 1: // FILE_APPEND
1945                 modestring = "a";
1946                 prog->openfiles[filenum] = FS_OpenRealFile(va(vabuf, sizeof(vabuf), "data/%s", filename), modestring, false);
1947                 break;
1948         case 2: // FILE_WRITE
1949                 modestring = "w";
1950                 prog->openfiles[filenum] = FS_OpenRealFile(va(vabuf, sizeof(vabuf), "data/%s", filename), modestring, false);
1951                 break;
1952         default:
1953                 PRVM_G_FLOAT(OFS_RETURN) = -3;
1954                 VM_Warning(prog, "VM_fopen: %s: no such mode %i (valid: 0 = read, 1 = append, 2 = write)\n", prog->name, mode);
1955                 return;
1956         }
1957
1958         if (prog->openfiles[filenum] == NULL)
1959         {
1960                 PRVM_G_FLOAT(OFS_RETURN) = -1;
1961                 if (developer_extra.integer)
1962                         VM_Warning(prog, "VM_fopen: %s: %s mode %s failed\n", prog->name, filename, modestring);
1963         }
1964         else
1965         {
1966                 PRVM_G_FLOAT(OFS_RETURN) = filenum;
1967                 if (developer_extra.integer)
1968                         Con_DPrintf("VM_fopen: %s: %s mode %s opened as #%i\n", prog->name, filename, modestring, filenum);
1969                 prog->openfiles_origin[filenum] = PRVM_AllocationOrigin(prog);
1970         }
1971 }
1972
1973 /*
1974 =========
1975 VM_fclose
1976
1977 fclose(float fhandle)
1978 =========
1979 */
1980 //void(float fhandle) fclose = #111; // closes a file
1981 void VM_fclose(prvm_prog_t *prog)
1982 {
1983         int filenum;
1984
1985         VM_SAFEPARMCOUNT(1,VM_fclose);
1986
1987         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1988         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1989         {
1990                 VM_Warning(prog, "VM_fclose: invalid file handle %i used in %s\n", filenum, prog->name);
1991                 return;
1992         }
1993         if (prog->openfiles[filenum] == NULL)
1994         {
1995                 VM_Warning(prog, "VM_fclose: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
1996                 return;
1997         }
1998         FS_Close(prog->openfiles[filenum]);
1999         prog->openfiles[filenum] = NULL;
2000         if(prog->openfiles_origin[filenum])
2001                 PRVM_Free((char *)prog->openfiles_origin[filenum]);
2002         if (developer_extra.integer)
2003                 Con_DPrintf("VM_fclose: %s: #%i closed\n", prog->name, filenum);
2004 }
2005
2006 /*
2007 =========
2008 VM_fgets
2009
2010 string  fgets(float fhandle)
2011 =========
2012 */
2013 //string(float fhandle) fgets = #112; // reads a line of text from the file and returns as a tempstring
2014 void VM_fgets(prvm_prog_t *prog)
2015 {
2016         int c, end;
2017         char string[VM_TEMPSTRING_MAXSIZE];
2018         int filenum;
2019
2020         VM_SAFEPARMCOUNT(1,VM_fgets);
2021
2022         // set the return value regardless of any possible errors
2023         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
2024
2025         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
2026         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
2027         {
2028                 VM_Warning(prog, "VM_fgets: invalid file handle %i used in %s\n", filenum, prog->name);
2029                 return;
2030         }
2031         if (prog->openfiles[filenum] == NULL)
2032         {
2033                 VM_Warning(prog, "VM_fgets: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
2034                 return;
2035         }
2036         end = 0;
2037         for (;;)
2038         {
2039                 c = FS_Getc(prog->openfiles[filenum]);
2040                 if (c == '\r' || c == '\n' || c < 0)
2041                         break;
2042                 if (end < VM_TEMPSTRING_MAXSIZE - 1)
2043                         string[end++] = c;
2044         }
2045         string[end] = '\0';
2046         // remove \n following \r
2047         if (c == '\r')
2048         {
2049                 c = FS_Getc(prog->openfiles[filenum]);
2050                 if (c != '\n')
2051                         FS_UnGetc(prog->openfiles[filenum], (unsigned char)c);
2052         }
2053         if (developer_extra.integer)
2054                 Con_DPrintf("fgets: %s: %s\n", prog->name, string);
2055         if (c >= 0 || end)
2056                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string, end);
2057 }
2058
2059 /*
2060 =========
2061 VM_fputs
2062
2063 fputs(float fhandle, string s)
2064 =========
2065 */
2066 //void(float fhandle, string s) fputs = #113; // writes a line of text to the end of the file
2067 void VM_fputs(prvm_prog_t *prog)
2068 {
2069         size_t stringlength;
2070         char string[VM_TEMPSTRING_MAXSIZE];
2071         int filenum;
2072
2073         VM_SAFEPARMCOUNT(2,VM_fputs);
2074
2075         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
2076         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
2077         {
2078                 VM_Warning(prog, "VM_fputs: invalid file handle %i used in %s\n", filenum, prog->name);
2079                 return;
2080         }
2081         if (prog->openfiles[filenum] == NULL)
2082         {
2083                 VM_Warning(prog, "VM_fputs: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
2084                 return;
2085         }
2086         stringlength = VM_VarString(prog, 1, string, sizeof(string));
2087         if (stringlength)
2088                 FS_Write(prog->openfiles[filenum], string, stringlength);
2089         if (developer_extra.integer)
2090                 Con_DPrintf("fputs: %s: %s\n", prog->name, string);
2091 }
2092
2093 /*
2094 =========
2095 VM_writetofile
2096
2097         writetofile(float fhandle, entity ent)
2098 =========
2099 */
2100 void VM_writetofile(prvm_prog_t *prog)
2101 {
2102         prvm_edict_t * ent;
2103         qfile_t *file;
2104
2105         VM_SAFEPARMCOUNT(2, VM_writetofile);
2106
2107         file = VM_GetFileHandle(prog, (int)PRVM_G_FLOAT(OFS_PARM0));
2108         if( !file )
2109         {
2110                 VM_Warning(prog, "VM_writetofile: invalid or closed file handle\n");
2111                 return;
2112         }
2113
2114         ent = PRVM_G_EDICT(OFS_PARM1);
2115         if(ent->free)
2116         {
2117                 VM_Warning(prog, "VM_writetofile: %s: entity %i is free !\n", prog->name, PRVM_NUM_FOR_EDICT(ent));
2118                 return;
2119         }
2120
2121         PRVM_ED_Write (prog, file, ent);
2122 }
2123
2124 // KrimZon - DP_QC_ENTITYDATA
2125 /*
2126 =========
2127 VM_numentityfields
2128
2129 float() numentityfields
2130 Return the number of entity fields - NOT offsets
2131 =========
2132 */
2133 void VM_numentityfields(prvm_prog_t *prog)
2134 {
2135         PRVM_G_FLOAT(OFS_RETURN) = prog->numfielddefs;
2136 }
2137
2138 // KrimZon - DP_QC_ENTITYDATA
2139 /*
2140 =========
2141 VM_entityfieldname
2142
2143 string(float fieldnum) entityfieldname
2144 Return name of the specified field as a string, or empty if the field is invalid (warning)
2145 =========
2146 */
2147 void VM_entityfieldname(prvm_prog_t *prog)
2148 {
2149         mdef_t *d;
2150         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2151
2152         if (i < 0 || i >= prog->numfielddefs)
2153         {
2154                 VM_Warning(prog, "VM_entityfieldname: %s: field index out of bounds\n", prog->name);
2155                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
2156                 return;
2157         }
2158
2159         d = &prog->fielddefs[i];
2160         PRVM_G_INT(OFS_RETURN) = d->s_name; // presuming that s_name points to a string already
2161 }
2162
2163 // KrimZon - DP_QC_ENTITYDATA
2164 /*
2165 =========
2166 VM_entityfieldtype
2167
2168 float(float fieldnum) entityfieldtype
2169 =========
2170 */
2171 void VM_entityfieldtype(prvm_prog_t *prog)
2172 {
2173         mdef_t *d;
2174         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2175         
2176         if (i < 0 || i >= prog->numfielddefs)
2177         {
2178                 VM_Warning(prog, "VM_entityfieldtype: %s: field index out of bounds\n", prog->name);
2179                 PRVM_G_FLOAT(OFS_RETURN) = -1.0;
2180                 return;
2181         }
2182         
2183         d = &prog->fielddefs[i];
2184         PRVM_G_FLOAT(OFS_RETURN) = (prvm_vec_t)d->type;
2185 }
2186
2187 // KrimZon - DP_QC_ENTITYDATA
2188 /*
2189 =========
2190 VM_getentityfieldstring
2191
2192 string(float fieldnum, entity ent) getentityfieldstring
2193 =========
2194 */
2195 void VM_getentityfieldstring(prvm_prog_t *prog)
2196 {
2197         // put the data into a string
2198         mdef_t *d;
2199         int type, j;
2200         prvm_eval_t *val;
2201         prvm_edict_t * ent;
2202         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2203         char valuebuf[MAX_INPUTLINE];
2204         
2205         if (i < 0 || i >= prog->numfielddefs)
2206         {
2207                 VM_Warning(prog, "VM_entityfielddata: %s: field index out of bounds\n", prog->name);
2208                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
2209                 return;
2210         }
2211         
2212         d = &prog->fielddefs[i];
2213         
2214         // get the entity
2215         ent = PRVM_G_EDICT(OFS_PARM1);
2216         if(ent->free)
2217         {
2218                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
2219                 VM_Warning(prog, "VM_entityfielddata: %s: entity %i is free !\n", prog->name, PRVM_NUM_FOR_EDICT(ent));
2220                 return;
2221         }
2222         val = (prvm_eval_t *)(ent->fields.fp + d->ofs);
2223         
2224         // if it's 0 or blank, return an empty string
2225         type = d->type & ~DEF_SAVEGLOBAL;
2226         for (j=0 ; j<prvm_type_size[type] ; j++)
2227                 if (val->ivector[j])
2228                         break;
2229         if (j == prvm_type_size[type])
2230         {
2231                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
2232                 return;
2233         }
2234
2235         PRVM_UglyValueString(prog, (etype_t)d->type, val, valuebuf, sizeof(valuebuf));
2236         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, valuebuf, strlen(valuebuf));
2237 }
2238
2239 // KrimZon - DP_QC_ENTITYDATA
2240 /*
2241 =========
2242 VM_putentityfieldstring
2243
2244 float(float fieldnum, entity ent, string s) putentityfieldstring
2245 =========
2246 */
2247 void VM_putentityfieldstring(prvm_prog_t *prog)
2248 {
2249         mdef_t *d;
2250         prvm_edict_t * ent;
2251         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2252
2253         if (i < 0 || i >= prog->numfielddefs)
2254         {
2255         VM_Warning(prog, "VM_entityfielddata: %s: field index out of bounds\n", prog->name);
2256                 PRVM_G_FLOAT(OFS_RETURN) = 0.0f;
2257                 return;
2258         }
2259
2260         d = &prog->fielddefs[i];
2261
2262         // get the entity
2263         ent = PRVM_G_EDICT(OFS_PARM1);
2264         if(ent->free)
2265         {
2266                 VM_Warning(prog, "VM_entityfielddata: %s: entity %i is free !\n", prog->name, PRVM_NUM_FOR_EDICT(ent));
2267                 PRVM_G_FLOAT(OFS_RETURN) = 0.0f;
2268                 return;
2269         }
2270
2271         // parse the string into the value
2272         PRVM_G_FLOAT(OFS_RETURN) = ( PRVM_ED_ParseEpair(prog, ent, d, PRVM_G_STRING(OFS_PARM2), false) ) ? 1.0f : 0.0f;
2273 }
2274
2275 /*
2276 =========
2277 VM_strlen
2278
2279 float   strlen(string s)
2280 =========
2281 */
2282 //float(string s) strlen = #114; // returns how many characters are in a string
2283 void VM_strlen(prvm_prog_t *prog)
2284 {
2285         VM_SAFEPARMCOUNT(1,VM_strlen);
2286
2287         //PRVM_G_FLOAT(OFS_RETURN) = strlen(PRVM_G_STRING(OFS_PARM0));
2288         PRVM_G_FLOAT(OFS_RETURN) = u8_strlen(PRVM_G_STRING(OFS_PARM0));
2289 }
2290
2291 // DRESK - Decolorized String
2292 /*
2293 =========
2294 VM_strdecolorize
2295
2296 string  strdecolorize(string s)
2297 =========
2298 */
2299 // string (string s) strdecolorize = #472; // returns the passed in string with color codes stripped
2300 void VM_strdecolorize(prvm_prog_t *prog)
2301 {
2302         char szNewString[VM_TEMPSTRING_MAXSIZE];
2303         size_t szNewString_len;
2304         const char *szString;
2305
2306         // Prepare Strings
2307         VM_SAFEPARMCOUNT(1,VM_strdecolorize);
2308         szString = PRVM_G_STRING(OFS_PARM0);
2309         szNewString_len = COM_StringDecolorize(szString, 0, szNewString, sizeof(szNewString), true);
2310         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString, szNewString_len);
2311 }
2312
2313 // DRESK - String Length (not counting color codes)
2314 /*
2315 =========
2316 VM_strlennocol
2317
2318 float   strlennocol(string s)
2319 =========
2320 */
2321 // float(string s) strlennocol = #471; // returns how many characters are in a string not including color codes
2322 // For example, ^2Dresk returns a length of 5
2323 void VM_strlennocol(prvm_prog_t *prog)
2324 {
2325         const char *szString;
2326         int nCnt;
2327
2328         VM_SAFEPARMCOUNT(1,VM_strlennocol);
2329
2330         szString = PRVM_G_STRING(OFS_PARM0);
2331
2332         //nCnt = (int)COM_StringLengthNoColors(szString, 0, NULL);
2333         nCnt = (int)u8_COM_StringLengthNoColors(szString, 0, NULL);
2334
2335         PRVM_G_FLOAT(OFS_RETURN) = nCnt;
2336 }
2337
2338 // DRESK - String to Uppercase and Lowercase
2339 /*
2340 =========
2341 VM_strtolower
2342
2343 string  strtolower(string s)
2344 =========
2345 */
2346 // string (string s) strtolower = #480; // returns passed in string in lowercase form
2347 void VM_strtolower(prvm_prog_t *prog)
2348 {
2349         char szNewString[VM_TEMPSTRING_MAXSIZE];
2350         size_t szNewString_len;
2351         const char *szString;
2352
2353         // Prepare Strings
2354         VM_SAFEPARMCOUNT(1,VM_strtolower);
2355         szString = PRVM_G_STRING(OFS_PARM0);
2356
2357         szNewString_len = COM_ToLowerString(szString, szNewString, sizeof(szNewString) );
2358
2359         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString, szNewString_len);
2360 }
2361
2362 /*
2363 =========
2364 VM_strtoupper
2365
2366 string  strtoupper(string s)
2367 =========
2368 */
2369 // string (string s) strtoupper = #481; // returns passed in string in uppercase form
2370 void VM_strtoupper(prvm_prog_t *prog)
2371 {
2372         char szNewString[VM_TEMPSTRING_MAXSIZE];
2373         size_t szNewString_len;
2374         const char *szString;
2375
2376         // Prepare Strings
2377         VM_SAFEPARMCOUNT(1,VM_strtoupper);
2378         szString = PRVM_G_STRING(OFS_PARM0);
2379
2380         szNewString_len = COM_ToUpperString(szString, szNewString, sizeof(szNewString) );
2381
2382         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString, szNewString_len);
2383 }
2384
2385 /*
2386 =========
2387 VM_strcat
2388
2389 string strcat(string s, string...)
2390 =========
2391 */
2392 //string(string s, string...) strcat = #115;
2393 // concatenates strings (for example "abc", "def" would return "abcdef")
2394 // and returns as a tempstring
2395 void VM_strcat(prvm_prog_t *prog)
2396 {
2397         char s[VM_TEMPSTRING_MAXSIZE];
2398         size_t slen;
2399
2400         VM_SAFEPARMCOUNTRANGE(1, 8, VM_strcat);
2401
2402         slen = VM_VarString(prog, 0, s, sizeof(s));
2403         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s, slen);
2404 }
2405
2406 /*
2407 =========
2408 VM_substring
2409
2410 string  substring(string s, float start, float length)
2411 =========
2412 */
2413 // string(string s, float start, float length) substring = #116;
2414 // returns a section of a string as a tempstring
2415 void VM_substring(prvm_prog_t *prog)
2416 {
2417         int start, length;
2418         int u_slength = 0, u_start;
2419         size_t u_length;
2420         const char *s;
2421         char string[VM_TEMPSTRING_MAXSIZE];
2422
2423         VM_SAFEPARMCOUNT(3,VM_substring);
2424
2425         /*
2426         s = PRVM_G_STRING(OFS_PARM0);
2427         start = (int)PRVM_G_FLOAT(OFS_PARM1);
2428         length = (int)PRVM_G_FLOAT(OFS_PARM2);
2429         slength = strlen(s);
2430
2431         if (start < 0) // FTE_STRINGS feature
2432                 start += slength;
2433         start = bound(0, start, slength);
2434
2435         if (length < 0) // FTE_STRINGS feature
2436                 length += slength - start + 1;
2437         maxlen = min((int)sizeof(string) - 1, slength - start);
2438         length = bound(0, length, maxlen);
2439
2440         memcpy(string, s + start, length);
2441         string[length] = 0;
2442         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string);
2443         */
2444         
2445         s = PRVM_G_STRING(OFS_PARM0);
2446         start = (int)PRVM_G_FLOAT(OFS_PARM1);
2447         length = (int)PRVM_G_FLOAT(OFS_PARM2);
2448
2449         if (start < 0) // FTE_STRINGS feature
2450         {
2451                 u_slength = (int)u8_strlen(s);
2452                 start += u_slength;
2453                 start = bound(0, start, u_slength);
2454         }
2455
2456         if (length < 0) // FTE_STRINGS feature
2457         {
2458                 if (!u_slength) // it's not calculated when it's not needed above
2459                         u_slength = (int)u8_strlen(s);
2460                 length += u_slength - start + 1;
2461         }
2462                 
2463         // positive start, positive length
2464         u_start = u8_byteofs(s, start, NULL);
2465         if (u_start < 0)
2466         {
2467                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
2468                 return;
2469         }
2470         u_length = u8_bytelen(s + u_start, length);
2471         if (u_length >= sizeof(string)-1)
2472                 u_length = sizeof(string)-1;
2473         
2474         memcpy(string, s + u_start, u_length);
2475         string[u_length] = '\0';
2476         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string, u_length);
2477 }
2478
2479 /*
2480 =========
2481 VM_strreplace
2482
2483 string(string search, string replace, string subject) strreplace = #484;
2484 =========
2485 */
2486 // replaces all occurrences of search with replace in the string subject, and returns the result
2487 void VM_strreplace(prvm_prog_t *prog)
2488 {
2489         int i, j, si;
2490         const char *search, *replace, *subject;
2491         char string[VM_TEMPSTRING_MAXSIZE];
2492         int search_len, replace_len, subject_len;
2493
2494         VM_SAFEPARMCOUNT(3,VM_strreplace);
2495
2496         search = PRVM_G_STRING(OFS_PARM0);
2497         replace = PRVM_G_STRING(OFS_PARM1);
2498         subject = PRVM_G_STRING(OFS_PARM2);
2499
2500         search_len = (int)strlen(search);
2501         replace_len = (int)strlen(replace);
2502         subject_len = (int)strlen(subject);
2503
2504         si = 0;
2505         for (i = 0; i <= subject_len - search_len; i++)
2506         {
2507                 for (j = 0; j < search_len; j++) // thus, i+j < subject_len
2508                         if (subject[i+j] != search[j])
2509                                 break;
2510                 if (j == search_len)
2511                 {
2512                         // NOTE: if search_len == 0, we always hit THIS case, and never the other
2513                         // found it at offset 'i'
2514                         for (j = 0; j < replace_len && si < (int)sizeof(string) - 1; j++)
2515                                 string[si++] = replace[j];
2516                         if(search_len > 0)
2517                         {
2518                                 i += search_len - 1;
2519                         }
2520                         else
2521                         {
2522                                 // the above would subtract 1 from i... so we
2523                                 // don't do that, but instead output the next
2524                                 // char
2525                                 if (si < (int)sizeof(string) - 1)
2526                                         string[si++] = subject[i];
2527                         }
2528                 }
2529                 else
2530                 {
2531                         // in THIS case, we know search_len > 0, thus i < subject_len
2532                         // not found
2533                         if (si < (int)sizeof(string) - 1)
2534                                 string[si++] = subject[i];
2535                 }
2536         }
2537         // remaining chars (these cannot match)
2538         for (; i < subject_len; i++)
2539                 if (si < (int)sizeof(string) - 1)
2540                         string[si++] = subject[i];
2541         string[si] = '\0';
2542
2543         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string, si);
2544 }
2545
2546 /*
2547 =========
2548 VM_strireplace
2549
2550 string(string search, string replace, string subject) strireplace = #485;
2551 =========
2552 */
2553 // case-insensitive version of strreplace
2554 void VM_strireplace(prvm_prog_t *prog)
2555 {
2556         int i, j, si;
2557         const char *search, *replace, *subject;
2558         char string[VM_TEMPSTRING_MAXSIZE];
2559         int search_len, replace_len, subject_len;
2560
2561         VM_SAFEPARMCOUNT(3, VM_strireplace);
2562
2563         search = PRVM_G_STRING(OFS_PARM0);
2564         replace = PRVM_G_STRING(OFS_PARM1);
2565         subject = PRVM_G_STRING(OFS_PARM2);
2566
2567         search_len = (int)strlen(search);
2568         replace_len = (int)strlen(replace);
2569         subject_len = (int)strlen(subject);
2570
2571         si = 0;
2572         for (i = 0; i <= subject_len - search_len; i++)
2573         {
2574                 for (j = 0; j < search_len; j++) // thus, i+j < subject_len
2575                         if (tolower(subject[i+j]) != tolower(search[j]))
2576                                 break;
2577                 if (j == search_len)
2578                 {
2579                         // NOTE: if search_len == 0, we always hit THIS case, and never the other
2580                         // found it at offset 'i'
2581                         for (j = 0; j < replace_len && si < (int)sizeof(string) - 1; j++)
2582                                 string[si++] = replace[j];
2583                         if(search_len > 0)
2584                         {
2585                                 i += search_len - 1;
2586                         }
2587                         else
2588                         {
2589                                 // the above would subtract 1 from i... so we
2590                                 // don't do that, but instead output the next
2591                                 // char
2592                                 if (si < (int)sizeof(string) - 1)
2593                                         string[si++] = subject[i];
2594                         }
2595                 }
2596                 else
2597                 {
2598                         // in THIS case, we know search_len > 0, thus i < subject_len
2599                         // not found
2600                         if (si < (int)sizeof(string) - 1)
2601                                 string[si++] = subject[i];
2602                 }
2603         }
2604         // remaining chars (these cannot match)
2605         for (; i < subject_len; i++)
2606                 if (si < (int)sizeof(string) - 1)
2607                         string[si++] = subject[i];
2608         string[si] = '\0';
2609
2610         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string, si);
2611 }
2612
2613 /*
2614 =========
2615 VM_stov
2616
2617 vector  stov(string s)
2618 =========
2619 */
2620 //vector(string s) stov = #117; // returns vector value from a string
2621 void VM_stov(prvm_prog_t *prog)
2622 {
2623         char string[VM_TEMPSTRING_MAXSIZE];
2624
2625         VM_SAFEPARMCOUNT(1,VM_stov);
2626
2627         VM_VarString(prog, 0, string, sizeof(string));
2628         Math_atov(string, PRVM_G_VECTOR(OFS_RETURN));
2629 }
2630
2631 /*
2632 =========
2633 VM_strzone
2634
2635 string  strzone(string s)
2636 =========
2637 */
2638 //string(string s, ...) strzone = #118; // makes a copy of a string into the string zone and returns it, this is often used to keep around a tempstring for longer periods of time (tempstrings are replaced often)
2639 void VM_strzone(prvm_prog_t *prog)
2640 {
2641         char *out;
2642         char string[VM_TEMPSTRING_MAXSIZE];
2643         size_t alloclen;
2644
2645         VM_SAFEPARMCOUNT(1,VM_strzone);
2646
2647         alloclen = VM_VarString(prog, 0, string, sizeof(string)) + 1;
2648         PRVM_G_INT(OFS_RETURN) = PRVM_AllocString(prog, alloclen, &out);
2649         memcpy(out, string, alloclen);
2650 }
2651
2652 /*
2653 =========
2654 VM_strunzone
2655
2656 strunzone(string s)
2657 =========
2658 */
2659 //void(string s) strunzone = #119; // removes a copy of a string from the string zone (you can not use that string again or it may crash!!!)
2660 void VM_strunzone(prvm_prog_t *prog)
2661 {
2662         VM_SAFEPARMCOUNT(1,VM_strunzone);
2663         PRVM_FreeString(prog, PRVM_G_INT(OFS_PARM0));
2664 }
2665
2666 /*
2667 =========
2668 VM_tokenize
2669
2670 float tokenize(string s)
2671 =========
2672 */
2673 //float(string s) tokenize = #441; // takes apart a string into individal words (access them with argv), returns how many
2674 //this function originally written by KrimZon, made shorter by LadyHavoc
2675 //20040203: rewritten by LadyHavoc (no longer uses allocations)
2676 static int num_tokens = 0;
2677 static int tokens[VM_TEMPSTRING_MAXSIZE / 2];
2678 static int tokens_startpos[VM_TEMPSTRING_MAXSIZE / 2];
2679 static int tokens_endpos[VM_TEMPSTRING_MAXSIZE / 2];
2680 static char tokenize_string[VM_TEMPSTRING_MAXSIZE];
2681 void VM_tokenize (prvm_prog_t *prog)
2682 {
2683         const char *p;
2684
2685         VM_SAFEPARMCOUNT(1,VM_tokenize);
2686
2687         dp_strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2688         p = tokenize_string;
2689
2690         num_tokens = 0;
2691         for(;;)
2692         {
2693                 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
2694                         break;
2695
2696                 // skip whitespace here to find token start pos
2697                 while(*p && ISWHITESPACE(*p))
2698                         ++p;
2699
2700                 tokens_startpos[num_tokens] = p - tokenize_string;
2701                 if(!COM_ParseToken_VM_Tokenize(&p, false))
2702                         break;
2703                 tokens_endpos[num_tokens] = p - tokenize_string;
2704                 tokens[num_tokens] = PRVM_SetTempString(prog, com_token, com_token_len);
2705                 ++num_tokens;
2706         }
2707
2708         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2709 }
2710
2711 //float(string s) tokenize = #514; // takes apart a string into individal words (access them with argv), returns how many
2712 void VM_tokenize_console (prvm_prog_t *prog)
2713 {
2714         const char *p;
2715
2716         VM_SAFEPARMCOUNT(1, VM_tokenize_console);
2717
2718         dp_strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2719         p = tokenize_string;
2720
2721         num_tokens = 0;
2722         for(;;)
2723         {
2724                 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
2725                         break;
2726
2727                 // skip whitespace here to find token start pos
2728                 while(*p && ISWHITESPACE(*p))
2729                         ++p;
2730
2731                 tokens_startpos[num_tokens] = p - tokenize_string;
2732                 if(!COM_ParseToken_Console(&p))
2733                         break;
2734                 tokens_endpos[num_tokens] = p - tokenize_string;
2735                 tokens[num_tokens] = PRVM_SetTempString(prog, com_token, com_token_len);
2736                 ++num_tokens;
2737         }
2738
2739         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2740 }
2741
2742 /*
2743 =========
2744 VM_tokenizebyseparator
2745
2746 float tokenizebyseparator(string s, string separator1, ...)
2747 =========
2748 */
2749 //float(string s, string separator1, ...) tokenizebyseparator = #479; // takes apart a string into individal words (access them with argv), returns how many
2750 //this function returns the token preceding each instance of a separator (of
2751 //which there can be multiple), and the text following the last separator
2752 //useful for parsing certain kinds of data like IP addresses
2753 //example:
2754 //numnumbers = tokenizebyseparator("10.1.2.3", ".");
2755 //returns 4 and the tokens "10" "1" "2" "3".
2756 void VM_tokenizebyseparator (prvm_prog_t *prog)
2757 {
2758         int j, k;
2759         int numseparators;
2760         int separatorlen[7];
2761         const char *separators[7];
2762         const char *p, *p0;
2763         const char *token;
2764         char tokentext[MAX_INPUTLINE];
2765
2766         VM_SAFEPARMCOUNTRANGE(2, 8,VM_tokenizebyseparator);
2767
2768         dp_strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2769         p = tokenize_string;
2770
2771         numseparators = 0;
2772         for (j = 1;j < prog->argc;j++)
2773         {
2774                 // skip any blank separator strings
2775                 const char *s = PRVM_G_STRING(OFS_PARM0+j*3);
2776                 if (!s[0])
2777                         continue;
2778                 separators[numseparators] = s;
2779                 separatorlen[numseparators] = (int)strlen(s);
2780                 numseparators++;
2781         }
2782
2783         num_tokens = 0;
2784         j = 0;
2785
2786         while (num_tokens < (int)(sizeof(tokens)/sizeof(tokens[0])))
2787         {
2788                 token = tokentext + j;
2789                 tokens_startpos[num_tokens] = p - tokenize_string;
2790                 p0 = p;
2791                 while (*p)
2792                 {
2793                         for (k = 0;k < numseparators;k++)
2794                         {
2795                                 if (!strncmp(p, separators[k], separatorlen[k]))
2796                                 {
2797                                         p += separatorlen[k];
2798                                         break;
2799                                 }
2800                         }
2801                         if (k < numseparators)
2802                                 break;
2803                         if (j < (int)sizeof(tokentext)-1)
2804                                 tokentext[j++] = *p;
2805                         p++;
2806                         p0 = p;
2807                 }
2808                 tokens_endpos[num_tokens] = p0 - tokenize_string;
2809                 if (j >= (int)sizeof(tokentext))
2810                         break;
2811                 tokentext[j++] = '\0';
2812                 tokens[num_tokens++] = PRVM_SetTempString(prog, token, j - 1);
2813                 if (!*p)
2814                         break;
2815         }
2816
2817         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2818 }
2819
2820 //string(float n) argv = #442; // returns a word from the tokenized string (returns nothing for an invalid index)
2821 //this function originally written by KrimZon, made shorter by LadyHavoc
2822 void VM_argv (prvm_prog_t *prog)
2823 {
2824         int token_num;
2825
2826         VM_SAFEPARMCOUNT(1,VM_argv);
2827
2828         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2829
2830         if(token_num < 0)
2831                 token_num += num_tokens;
2832
2833         if (token_num >= 0 && token_num < num_tokens)
2834                 PRVM_G_INT(OFS_RETURN) = tokens[token_num];
2835         else
2836                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
2837 }
2838
2839 //float(float n) argv_start_index = #515; // returns the start index of a token
2840 void VM_argv_start_index (prvm_prog_t *prog)
2841 {
2842         int token_num;
2843
2844         VM_SAFEPARMCOUNT(1,VM_argv);
2845
2846         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2847
2848         if(token_num < 0)
2849                 token_num += num_tokens;
2850
2851         if (token_num >= 0 && token_num < num_tokens)
2852                 PRVM_G_FLOAT(OFS_RETURN) = tokens_startpos[token_num];
2853         else
2854                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2855 }
2856
2857 //float(float n) argv_end_index = #516; // returns the end index of a token
2858 void VM_argv_end_index (prvm_prog_t *prog)
2859 {
2860         int token_num;
2861
2862         VM_SAFEPARMCOUNT(1,VM_argv);
2863
2864         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2865
2866         if(token_num < 0)
2867                 token_num += num_tokens;
2868
2869         if (token_num >= 0 && token_num < num_tokens)
2870                 PRVM_G_FLOAT(OFS_RETURN) = tokens_endpos[token_num];
2871         else
2872                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2873 }
2874
2875 /*
2876 =========
2877 VM_isserver
2878
2879 float   isserver()
2880 =========
2881 */
2882 void VM_isserver(prvm_prog_t *prog)
2883 {
2884         VM_SAFEPARMCOUNT(0, VM_isserver);
2885
2886         PRVM_G_FLOAT(OFS_RETURN) = sv.active;
2887 }
2888
2889 /*
2890 =========
2891 VM_clientcount
2892
2893 float   clientcount()
2894 =========
2895 */
2896 void VM_clientcount(prvm_prog_t *prog)
2897 {
2898         VM_SAFEPARMCOUNT(0,VM_clientcount);
2899
2900         PRVM_G_FLOAT(OFS_RETURN) = svs.maxclients;
2901 }
2902
2903 /*
2904 =========
2905 VM_clientstate
2906
2907 float   clientstate()
2908 =========
2909 */
2910 void VM_clientstate(prvm_prog_t *prog)
2911 {
2912         VM_SAFEPARMCOUNT(0,VM_clientstate);
2913
2914
2915         switch( cls.state ) {
2916                 case ca_uninitialized:
2917                 case ca_dedicated:
2918                         PRVM_G_FLOAT(OFS_RETURN) = 0;
2919                         break;
2920                 case ca_disconnected:
2921                         PRVM_G_FLOAT(OFS_RETURN) = 1;
2922                         break;
2923                 case ca_connected:
2924                         PRVM_G_FLOAT(OFS_RETURN) = 2;
2925                         break;
2926                 default:
2927                         // should never be reached!
2928                         break;
2929         }
2930 }
2931
2932 /*
2933 =========
2934 VM_getostype
2935
2936 float   getostype(prvm_prog_t *prog)
2937 =========
2938 */ // not used at the moment -> not included in the common list
2939 void VM_getostype(prvm_prog_t *prog)
2940 {
2941         VM_SAFEPARMCOUNT(0,VM_getostype);
2942
2943         /*
2944         OS_WINDOWS
2945         OS_LINUX
2946         OS_MAC - not supported
2947         */
2948
2949 #ifdef WIN32
2950         PRVM_G_FLOAT(OFS_RETURN) = 0;
2951 #elif defined(MACOSX)
2952         PRVM_G_FLOAT(OFS_RETURN) = 2;
2953 #else
2954         PRVM_G_FLOAT(OFS_RETURN) = 1;
2955 #endif
2956 }
2957
2958 /*
2959 =========
2960 VM_gettime
2961
2962 float   gettime(prvm_prog_t *prog)
2963 =========
2964 */
2965 float CDAudio_GetPosition(void);
2966 void VM_gettime(prvm_prog_t *prog)
2967 {
2968         int timer_index;
2969
2970         VM_SAFEPARMCOUNTRANGE(0,1,VM_gettime);
2971
2972         if(prog->argc == 0)
2973         {
2974                 PRVM_G_FLOAT(OFS_RETURN) = (prvm_vec_t) host.realtime;
2975         }
2976         else
2977         {
2978                 timer_index = (int) PRVM_G_FLOAT(OFS_PARM0);
2979                 switch(timer_index)
2980                 {
2981                         case 0: // GETTIME_FRAMESTART
2982                                 PRVM_G_FLOAT(OFS_RETURN) = host.realtime;
2983                                 break;
2984                         case 1: // GETTIME_REALTIME
2985                                 PRVM_G_FLOAT(OFS_RETURN) = Sys_DirtyTime();
2986                                 break;
2987                         case 2: // GETTIME_HIRES
2988                                 PRVM_G_FLOAT(OFS_RETURN) = (Sys_DirtyTime() - host.dirtytime);
2989                                 break;
2990                         case 3: // GETTIME_UPTIME
2991                                 PRVM_G_FLOAT(OFS_RETURN) = host.realtime;
2992                                 break;
2993                         case 4: // GETTIME_CDTRACK
2994                                 PRVM_G_FLOAT(OFS_RETURN) = CDAudio_GetPosition();
2995                                 break;
2996                         default:
2997                                 VM_Warning(prog, "VM_gettime: %s: unsupported timer specified, returning realtime\n", prog->name);
2998                                 PRVM_G_FLOAT(OFS_RETURN) = host.realtime;
2999                                 break;
3000                 }
3001         }
3002 }
3003
3004 /*
3005 =========
3006 VM_getsoundtime
3007
3008 float   getsoundtime(prvm_prog_t *prog)
3009 =========
3010 */
3011
3012 void VM_getsoundtime (prvm_prog_t *prog)
3013 {
3014         int entnum, entchannel;
3015         VM_SAFEPARMCOUNT(2,VM_getsoundtime);
3016
3017         if (prog == SVVM_prog)
3018                 entnum = PRVM_NUM_FOR_EDICT(PRVM_G_EDICT(OFS_PARM0));
3019         else if (prog == CLVM_prog)
3020                 entnum = MAX_EDICTS + PRVM_NUM_FOR_EDICT(PRVM_G_EDICT(OFS_PARM0));
3021         else
3022         {
3023                 VM_Warning(prog, "VM_getsoundtime: %s: not supported on this progs\n", prog->name);
3024                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3025                 return;
3026         }
3027         entchannel = (int)PRVM_G_FLOAT(OFS_PARM1);
3028         entchannel = CHAN_USER2ENGINE(entchannel);
3029         if (!IS_CHAN(entchannel))
3030                 VM_Warning(prog, "VM_getsoundtime: %s: bad channel %i\n", prog->name, entchannel);
3031         PRVM_G_FLOAT(OFS_RETURN) = (prvm_vec_t)S_GetEntChannelPosition(entnum, entchannel);
3032 }
3033
3034 /*
3035 =========
3036 VM_GetSoundLen
3037
3038 string  soundlength (string sample)
3039 =========
3040 */
3041 void VM_soundlength (prvm_prog_t *prog)
3042 {
3043         const char *s;
3044
3045         VM_SAFEPARMCOUNT(1, VM_soundlength);
3046
3047         s = PRVM_G_STRING(OFS_PARM0);
3048         PRVM_G_FLOAT(OFS_RETURN) = S_SoundLength(s);
3049 }
3050
3051 /*
3052 =========
3053 VM_loadfromdata
3054
3055 loadfromdata(string data)
3056 =========
3057 */
3058 void VM_loadfromdata(prvm_prog_t *prog)
3059 {
3060         VM_SAFEPARMCOUNT(1, VM_loadfromdata);
3061
3062         PRVM_ED_LoadFromFile(prog, PRVM_G_STRING(OFS_PARM0));
3063 }
3064
3065 /*
3066 ========================
3067 VM_parseentitydata
3068
3069 parseentitydata(entity ent, string data)
3070 ========================
3071 */
3072 void VM_parseentitydata(prvm_prog_t *prog)
3073 {
3074         prvm_edict_t *ent;
3075         const char *data;
3076
3077         VM_SAFEPARMCOUNT(2, VM_parseentitydata);
3078
3079         // get edict and test it
3080         ent = PRVM_G_EDICT(OFS_PARM0);
3081         if (ent->free)
3082                 prog->error_cmd("VM_parseentitydata: %s: Can only set already spawned entities (entity %i is free)!", prog->name, PRVM_NUM_FOR_EDICT(ent));
3083
3084         data = PRVM_G_STRING(OFS_PARM1);
3085
3086         // parse the opening brace
3087         if (!COM_ParseToken_Simple(&data, false, false, true) || com_token[0] != '{' )
3088                 prog->error_cmd("VM_parseentitydata: %s: Couldn't parse entity data:\n%s", prog->name, data );
3089
3090         PRVM_ED_ParseEdict (prog, data, ent);
3091 }
3092
3093 /*
3094 =========
3095 VM_loadfromfile
3096
3097 loadfromfile(string file)
3098 =========
3099 */
3100 void VM_loadfromfile(prvm_prog_t *prog)
3101 {
3102         const char *filename;
3103         char *data;
3104
3105         VM_SAFEPARMCOUNT(1,VM_loadfromfile);
3106
3107         filename = PRVM_G_STRING(OFS_PARM0);
3108         if (FS_CheckNastyPath(filename, false))
3109         {
3110                 PRVM_G_FLOAT(OFS_RETURN) = -4;
3111                 VM_Warning(prog, "VM_loadfromfile: %s dangerous or non-portable filename \"%s\" not allowed. (contains : or \\ or begins with .. or /)\n", prog->name, filename);
3112                 return;
3113         }
3114
3115         // not conform with VM_fopen
3116         data = (char *)FS_LoadFile(filename, tempmempool, false, NULL);
3117         if (data == NULL)
3118                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3119
3120         PRVM_ED_LoadFromFile(prog, data);
3121
3122         if(data)
3123                 Mem_Free(data);
3124 }
3125
3126
3127 /*
3128 =========
3129 VM_modulo
3130
3131 float   mod(float val, float m)
3132 =========
3133 */
3134 void VM_modulo(prvm_prog_t *prog)
3135 {
3136         vec_t val, m;
3137
3138         VM_SAFEPARMCOUNT(2, VM_modulo);
3139
3140         val = PRVM_G_FLOAT(OFS_PARM0);
3141         m   = PRVM_G_FLOAT(OFS_PARM1);
3142
3143         // matches how gmqcc implements % when mod() builtin isn't defined, and FTEQW mod()
3144         if (m)
3145                 PRVM_G_FLOAT(OFS_RETURN) = val - m * (prvm_int_t)(val / m);
3146         else
3147         {
3148                 VM_Warning(prog, "Attempted modulo of %f by zero\n", val);
3149                 PRVM_G_FLOAT(OFS_RETURN) = 0;
3150         }
3151 }
3152
3153 static void VM_Search_Init(prvm_prog_t *prog)
3154 {
3155         int i;
3156         for (i = 0;i < PRVM_MAX_OPENSEARCHES;i++)
3157                 prog->opensearches[i] = NULL;
3158 }
3159
3160 static void VM_Search_Reset(prvm_prog_t *prog)
3161 {
3162         int i;
3163         // reset the fssearch list
3164         for(i = 0; i < PRVM_MAX_OPENSEARCHES; i++)
3165         {
3166                 if(prog->opensearches[i])
3167                         FS_FreeSearch(prog->opensearches[i]);
3168                 prog->opensearches[i] = NULL;
3169         }
3170 }
3171
3172 /*
3173 =========
3174 VM_search_begin
3175
3176 float search_begin(string pattern, float caseinsensitive, float quiet[, string packfile])
3177 =========
3178 */
3179 void VM_search_begin(prvm_prog_t *prog)
3180 {
3181         int handle;
3182         const char *packfile = NULL, *pattern;
3183         int caseinsens, quiet;
3184
3185         VM_SAFEPARMCOUNTRANGE(3, 4, VM_search_begin);
3186
3187         pattern = PRVM_G_STRING(OFS_PARM0);
3188
3189         VM_CheckEmptyString(prog, pattern);
3190
3191         caseinsens = (int)PRVM_G_FLOAT(OFS_PARM1);
3192         quiet = (int)PRVM_G_FLOAT(OFS_PARM2);
3193
3194         // optional packfile parameter (DP_QC_FS_SEARCH_PACKFILE)
3195         if(prog->argc >= 4)
3196                 packfile = PRVM_G_STRING(OFS_PARM3);
3197
3198         for(handle = 0; handle < PRVM_MAX_OPENSEARCHES; handle++)
3199                 if(!prog->opensearches[handle])
3200                         break;
3201
3202         if(handle >= PRVM_MAX_OPENSEARCHES)
3203         {
3204                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3205                 VM_Warning(prog, "VM_search_begin: %s ran out of search handles (%i)\n", prog->name, PRVM_MAX_OPENSEARCHES);
3206                 return;
3207         }
3208
3209         if(!(prog->opensearches[handle] = FS_Search(pattern,caseinsens, quiet, packfile)))
3210                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3211         else
3212         {
3213                 prog->opensearches_origin[handle] = PRVM_AllocationOrigin(prog);
3214                 PRVM_G_FLOAT(OFS_RETURN) = handle;
3215         }
3216 }
3217
3218 /*
3219 =========
3220 VM_search_end
3221
3222 void    search_end(float handle)
3223 =========
3224 */
3225 void VM_search_end(prvm_prog_t *prog)
3226 {
3227         int handle;
3228         VM_SAFEPARMCOUNT(1, VM_search_end);
3229
3230         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3231
3232         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3233         {
3234                 VM_Warning(prog, "VM_search_end: invalid handle %i used in %s\n", handle, prog->name);
3235                 return;
3236         }
3237         if(prog->opensearches[handle] == NULL)
3238         {
3239                 VM_Warning(prog, "VM_search_end: no such handle %i in %s\n", handle, prog->name);
3240                 return;
3241         }
3242
3243         FS_FreeSearch(prog->opensearches[handle]);
3244         prog->opensearches[handle] = NULL;
3245         if(prog->opensearches_origin[handle])
3246                 PRVM_Free((char *)prog->opensearches_origin[handle]);
3247 }
3248
3249 /*
3250 =========
3251 VM_search_getsize
3252
3253 float   search_getsize(float handle)
3254 =========
3255 */
3256 void VM_search_getsize(prvm_prog_t *prog)
3257 {
3258         int handle;
3259         VM_SAFEPARMCOUNT(1, VM_search_getsize);
3260
3261         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3262
3263         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3264         {
3265                 VM_Warning(prog, "VM_search_getsize: invalid handle %i used in %s\n", handle, prog->name);
3266                 return;
3267         }
3268         if(prog->opensearches[handle] == NULL)
3269         {
3270                 VM_Warning(prog, "VM_search_getsize: no such handle %i in %s\n", handle, prog->name);
3271                 return;
3272         }
3273
3274         PRVM_G_FLOAT(OFS_RETURN) = prog->opensearches[handle]->numfilenames;
3275 }
3276
3277 /*
3278 =========
3279 VM_search_getfilename
3280
3281 string  search_getfilename(float handle, float num)
3282 =========
3283 */
3284 void VM_search_getfilename(prvm_prog_t *prog)
3285 {
3286         int handle, filenum;
3287
3288         VM_SAFEPARMCOUNT(2, VM_search_getfilename);
3289
3290         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3291         filenum = (int)PRVM_G_FLOAT(OFS_PARM1);
3292
3293         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3294         {
3295                 VM_Warning(prog, "VM_search_getfilename: invalid handle %i used in %s\n", handle, prog->name);
3296                 return;
3297         }
3298         if(prog->opensearches[handle] == NULL)
3299         {
3300                 VM_Warning(prog, "VM_search_getfilename: no such handle %i in %s\n", handle, prog->name);
3301                 return;
3302         }
3303         if(filenum < 0 || filenum >= prog->opensearches[handle]->numfilenames)
3304         {
3305                 VM_Warning(prog, "VM_search_getfilename: invalid filenum %i in %s\n", filenum, prog->name);
3306                 return;
3307         }
3308
3309         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog,
3310                                                     prog->opensearches[handle]->filenames[filenum],
3311                                                     strlen(prog->opensearches[handle]->filenames[filenum]));
3312 }
3313
3314 /*
3315 =========
3316 VM_chr
3317
3318 string  chr(float ascii)
3319 =========
3320 */
3321 void VM_chr(prvm_prog_t *prog)
3322 {
3323         /*
3324         char tmp[2];
3325         VM_SAFEPARMCOUNT(1, VM_chr);
3326
3327         tmp[0] = (unsigned char) PRVM_G_FLOAT(OFS_PARM0);
3328         tmp[1] = 0;
3329
3330         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, tmp);
3331         */
3332         
3333         char tmp[8];
3334         int len;
3335
3336         VM_SAFEPARMCOUNT(1, VM_chr);
3337         len = u8_fromchar((Uchar)PRVM_G_FLOAT(OFS_PARM0), tmp, sizeof(tmp));
3338         tmp[len] = '\0';
3339         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, tmp, len);
3340 }
3341
3342 /*
3343 =========
3344 VM_keynumtostring
3345
3346 string keynumtostring(float keynum)
3347 =========
3348 */
3349 void VM_keynumtostring (prvm_prog_t *prog)
3350 {
3351         char tinystr[TINYSTR_LEN];
3352         const char *str; // Key_KeynumToString doesn't always return tinystr
3353
3354         VM_SAFEPARMCOUNT(1, VM_keynumtostring);
3355         str = Key_KeynumToString((int)PRVM_G_FLOAT(OFS_PARM0), tinystr, sizeof(tinystr));
3356         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, str, strlen(str));
3357 }
3358
3359 /*
3360 =========
3361 VM_findkeysforcommand
3362
3363 string  findkeysforcommand(string command, float bindmap)
3364
3365 the returned string is an altstring
3366 =========
3367 */
3368 #define FKFC_NUMKEYS 5
3369 void M_FindKeysForCommand(const char *command, int *keys);
3370 void VM_findkeysforcommand(prvm_prog_t *prog)
3371 {
3372         const char *cmd;
3373         char ret[VM_TEMPSTRING_MAXSIZE];
3374         size_t ret_len;
3375         int keys[FKFC_NUMKEYS];
3376         int i;
3377         int bindmap;
3378         char vabuf[1024];
3379
3380         VM_SAFEPARMCOUNTRANGE(1, 2, VM_findkeysforcommand);
3381
3382         cmd = PRVM_G_STRING(OFS_PARM0);
3383         if(prog->argc == 2)
3384                 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM1), MAX_BINDMAPS-1);
3385         else
3386                 bindmap = 0; // consistent to "bind"
3387
3388         VM_CheckEmptyString(prog, cmd);
3389
3390         Key_FindKeysForCommand(cmd, keys, FKFC_NUMKEYS, bindmap);
3391
3392         ret[0] = 0;
3393         for(i = 0; i < FKFC_NUMKEYS; i++)
3394                 ret_len = dp_strlcat(ret, va(vabuf, sizeof(vabuf), " \'%i\'", keys[i]), sizeof(ret));
3395
3396         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, ret, ret_len);
3397 }
3398
3399 /*
3400 =========
3401 VM_stringtokeynum
3402
3403 float stringtokeynum(string key)
3404 =========
3405 */
3406 void VM_stringtokeynum (prvm_prog_t *prog)
3407 {
3408         VM_SAFEPARMCOUNT( 1, VM_stringtokeynum );
3409
3410         PRVM_G_FLOAT(OFS_RETURN) = Key_StringToKeynum(PRVM_G_STRING(OFS_PARM0));
3411 }
3412
3413 /*
3414 =========
3415 VM_getkeybind
3416
3417 string getkeybind(float key, float bindmap)
3418 =========
3419 */
3420 void VM_getkeybind (prvm_prog_t *prog)
3421 {
3422         int bindmap;
3423         const char *bind;
3424
3425         VM_SAFEPARMCOUNTRANGE(1, 2, VM_getkeybind);
3426         if(prog->argc == 2)
3427                 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM1), MAX_BINDMAPS-1);
3428         else
3429                 bindmap = 0; // consistent to "bind"
3430         bind = Key_GetBind((int)PRVM_G_FLOAT(OFS_PARM0), bindmap);
3431         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, bind, strlen(bind));
3432 }
3433
3434 /*
3435 =========
3436 VM_setkeybind
3437
3438 float setkeybind(float key, string cmd, float bindmap)
3439 =========
3440 */
3441 void VM_setkeybind (prvm_prog_t *prog)
3442 {
3443         int bindmap;
3444         VM_SAFEPARMCOUNTRANGE(2, 3, VM_setkeybind);
3445         if(prog->argc == 3)
3446                 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM2), MAX_BINDMAPS-1);
3447         else
3448                 bindmap = 0; // consistent to "bind"
3449
3450         PRVM_G_FLOAT(OFS_RETURN) = 0;
3451         if(Key_SetBinding((int)PRVM_G_FLOAT(OFS_PARM0), bindmap, PRVM_G_STRING(OFS_PARM1)))
3452                 PRVM_G_FLOAT(OFS_RETURN) = 1;
3453 }
3454
3455 /*
3456 =========
3457 VM_getbindmap
3458
3459 vector getbindmaps()
3460 =========
3461 */
3462 void VM_getbindmaps (prvm_prog_t *prog)
3463 {
3464         int fg, bg;
3465         VM_SAFEPARMCOUNT(0, VM_getbindmaps);
3466         Key_GetBindMap(&fg, &bg);
3467         PRVM_G_VECTOR(OFS_RETURN)[0] = fg;
3468         PRVM_G_VECTOR(OFS_RETURN)[1] = bg;
3469         PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
3470 }
3471
3472 /*
3473 =========
3474 VM_setbindmap
3475
3476 float setbindmaps(vector bindmap)
3477 =========
3478 */
3479 void VM_setbindmaps (prvm_prog_t *prog)
3480 {
3481         VM_SAFEPARMCOUNT(1, VM_setbindmaps);
3482         PRVM_G_FLOAT(OFS_RETURN) = 0;
3483         if(PRVM_G_VECTOR(OFS_PARM0)[2] == 0)
3484                 if(Key_SetBindMap((int)PRVM_G_VECTOR(OFS_PARM0)[0], (int)PRVM_G_VECTOR(OFS_PARM0)[1]))
3485                         PRVM_G_FLOAT(OFS_RETURN) = 1;
3486 }
3487
3488 /*
3489 ========================
3490 VM_gecko_create
3491
3492 float[bool] gecko_create( string name )
3493 ========================
3494 */
3495 void VM_gecko_create(prvm_prog_t *prog) {
3496         // REMOVED
3497         PRVM_G_FLOAT( OFS_RETURN ) = 0;
3498 }
3499
3500 /*
3501 ========================
3502 VM_gecko_destroy
3503
3504 void gecko_destroy( string name )
3505 ========================
3506 */
3507 void VM_gecko_destroy(prvm_prog_t *prog) {
3508         // REMOVED
3509 }
3510
3511 /*
3512 ========================
3513 VM_gecko_navigate
3514
3515 void gecko_navigate( string name, string URI )
3516 ========================
3517 */
3518 void VM_gecko_navigate(prvm_prog_t *prog) {
3519         // REMOVED
3520 }
3521
3522 /*
3523 ========================
3524 VM_gecko_keyevent
3525
3526 float[bool] gecko_keyevent( string name, float key, float eventtype ) 
3527 ========================
3528 */
3529 void VM_gecko_keyevent(prvm_prog_t *prog) {
3530         // REMOVED
3531         PRVM_G_FLOAT( OFS_RETURN ) = 0;
3532 }
3533
3534 /*
3535 ========================
3536 VM_gecko_movemouse
3537
3538 void gecko_mousemove( string name, float x, float y )
3539 ========================
3540 */
3541 void VM_gecko_movemouse(prvm_prog_t *prog) {
3542         // REMOVED
3543 }
3544
3545
3546 /*
3547 ========================
3548 VM_gecko_resize
3549
3550 void gecko_resize( string name, float w, float h )
3551 ========================
3552 */
3553 void VM_gecko_resize(prvm_prog_t *prog) {
3554         // REMOVED
3555 }
3556
3557
3558 /*
3559 ========================
3560 VM_gecko_get_texture_extent
3561
3562 vector gecko_get_texture_extent( string name )
3563 ========================
3564 */
3565 void VM_gecko_get_texture_extent(prvm_prog_t *prog) {
3566         // REMOVED
3567         PRVM_G_VECTOR(OFS_RETURN)[0] = 0;
3568         PRVM_G_VECTOR(OFS_RETURN)[1] = 0;
3569 }
3570
3571
3572
3573 /*
3574 ==============
3575 VM_makevectors
3576
3577 Writes new values for v_forward, v_up, and v_right based on angles
3578 void makevectors(vector angle)
3579 ==============
3580 */
3581 void VM_makevectors (prvm_prog_t *prog)
3582 {
3583         vec3_t angles, forward, right, up;
3584         VM_SAFEPARMCOUNT(1, VM_makevectors);
3585         VectorCopy(PRVM_G_VECTOR(OFS_PARM0), angles);
3586         AngleVectors(angles, forward, right, up);
3587         VectorCopy(forward, PRVM_gameglobalvector(v_forward));
3588         VectorCopy(right, PRVM_gameglobalvector(v_right));
3589         VectorCopy(up, PRVM_gameglobalvector(v_up));
3590 }
3591
3592 /*
3593 ==============
3594 VM_vectorvectors
3595
3596 Writes new values for v_forward, v_up, and v_right based on the given forward vector
3597 vectorvectors(vector)
3598 ==============
3599 */
3600 void VM_vectorvectors (prvm_prog_t *prog)
3601 {
3602         vec3_t forward, right, up;
3603         VM_SAFEPARMCOUNT(1, VM_vectorvectors);
3604         VectorNormalize2(PRVM_G_VECTOR(OFS_PARM0), forward);
3605         VectorVectors(forward, right, up);
3606         VectorCopy(forward, PRVM_gameglobalvector(v_forward));
3607         VectorCopy(right, PRVM_gameglobalvector(v_right));
3608         VectorCopy(up, PRVM_gameglobalvector(v_up));
3609 }
3610
3611 // float(float number, float quantity) bitshift (EXT_BITSHIFT)
3612 void VM_bitshift (prvm_prog_t *prog)
3613 {
3614         prvm_int_t n1, n2;
3615         VM_SAFEPARMCOUNT(2, VM_bitshift);
3616
3617         n1 = (prvm_int_t)fabs((prvm_vec_t)((prvm_int_t)PRVM_G_FLOAT(OFS_PARM0)));
3618         n2 = (prvm_int_t)PRVM_G_FLOAT(OFS_PARM1);
3619         if(!n1)
3620                 PRVM_G_FLOAT(OFS_RETURN) = n1;
3621         else
3622         if(n2 < 0)
3623                 PRVM_G_FLOAT(OFS_RETURN) = (n1 >> -n2);
3624         else
3625                 PRVM_G_FLOAT(OFS_RETURN) = (n1 << n2);
3626 }
3627
3628 ////////////////////////////////////////
3629 // AltString functions
3630 ////////////////////////////////////////
3631
3632 /*
3633 ========================
3634 VM_altstr_count
3635
3636 float altstr_count(string)
3637 ========================
3638 */
3639 void VM_altstr_count(prvm_prog_t *prog)
3640 {
3641         const char *altstr, *pos;
3642         int     count;
3643
3644         VM_SAFEPARMCOUNT( 1, VM_altstr_count );
3645
3646         altstr = PRVM_G_STRING( OFS_PARM0 );
3647         //VM_CheckEmptyString(prog,  altstr );
3648
3649         for( count = 0, pos = altstr ; *pos ; pos++ ) {
3650                 if( *pos == '\\' ) {
3651                         if( !*++pos ) {
3652                                 break;
3653                         }
3654                 } else if( *pos == '\'' ) {
3655                         count++;
3656                 }
3657         }
3658
3659         PRVM_G_FLOAT( OFS_RETURN ) = (prvm_vec_t) (count / 2);
3660 }
3661
3662 /*
3663 ========================
3664 VM_altstr_prepare
3665
3666 string altstr_prepare(string)
3667 ========================
3668 */
3669 void VM_altstr_prepare(prvm_prog_t *prog)
3670 {
3671         const char *instr, *in;
3672         char outstr[VM_TEMPSTRING_MAXSIZE];
3673         size_t outpos;
3674
3675         VM_SAFEPARMCOUNT( 1, VM_altstr_prepare );
3676
3677         instr = PRVM_G_STRING( OFS_PARM0 );
3678
3679         for (in = instr, outpos = 0; *in && outpos < sizeof(outstr) - 1; ++in)
3680         {
3681                 if (*in == '\'' && outpos < sizeof(outstr) - 2)
3682                 {
3683                         outstr[outpos++] = '\\';
3684                         outstr[outpos++] = '\'';
3685                 }
3686                 else
3687                         outstr[outpos++] = *in;
3688         }
3689
3690         outstr[outpos] = '\0';
3691         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outstr, outpos);
3692 }
3693
3694 /*
3695 ========================
3696 VM_altstr_get
3697
3698 string altstr_get(string, float)
3699 ========================
3700 */
3701 void VM_altstr_get(prvm_prog_t *prog)
3702 {
3703         const char *altstr, *pos;
3704         char *out;
3705         int count, size;
3706         char outstr[VM_TEMPSTRING_MAXSIZE];
3707
3708         VM_SAFEPARMCOUNT( 2, VM_altstr_get );
3709
3710         altstr = PRVM_G_STRING( OFS_PARM0 );
3711
3712         count = (int)PRVM_G_FLOAT( OFS_PARM1 );
3713         count = count * 2 + 1;
3714
3715         for( pos = altstr ; *pos && count ; pos++ )
3716                 if( *pos == '\\' ) {
3717                         if( !*++pos )
3718                                 break;
3719                 } else if( *pos == '\'' )
3720                         count--;
3721
3722         if( !*pos ) {
3723                 PRVM_G_INT( OFS_RETURN ) = 0;
3724                 return;
3725         }
3726
3727         for( out = outstr, size = sizeof(outstr) - 1 ; size && *pos ; size--, pos++, out++ )
3728                 if( *pos == '\\' ) {
3729                         if( !*++pos )
3730                                 break;
3731                         *out = *pos;
3732                         size--;
3733                 } else if( *pos == '\'' )
3734                         break;
3735                 else
3736                         *out = *pos;
3737
3738         *out = '\0';
3739         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outstr, out - outstr);
3740 }
3741
3742 /*
3743 ========================
3744 VM_altstr_set
3745
3746 string altstr_set(string altstr, float num, string set)
3747 ========================
3748 */
3749 void VM_altstr_set(prvm_prog_t *prog)
3750 {
3751     int num;
3752         const char *altstr, *str;
3753         const char *in;
3754         char *out;
3755         char outstr[VM_TEMPSTRING_MAXSIZE];
3756
3757         VM_SAFEPARMCOUNT( 3, VM_altstr_set );
3758
3759         altstr = PRVM_G_STRING( OFS_PARM0 );
3760
3761         num = (int)PRVM_G_FLOAT( OFS_PARM1 );
3762
3763         str = PRVM_G_STRING( OFS_PARM2 );
3764
3765         out = outstr;
3766         for( num = num * 2 + 1, in = altstr; *in && num; *out++ = *in++ )
3767                 if( *in == '\\' ) {
3768                         if( !*++in ) {
3769                                 break;
3770                         }
3771                 } else if( *in == '\'' ) {
3772                         num--;
3773                 }
3774
3775         // copy set in
3776         for( ; *str; *out++ = *str++ );
3777         // now jump over the old content
3778         for( ; *in ; in++ )
3779                 if( *in == '\'' || (*in == '\\' && !*++in) )
3780                         break;
3781
3782         out += dp_strlcpy(out, in, outstr + sizeof(outstr) - out);
3783         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outstr, out - outstr);
3784 }
3785
3786 /*
3787 ========================
3788 VM_altstr_ins
3789 insert after num
3790 string  altstr_ins(string altstr, float num, string set)
3791 ========================
3792 */
3793 void VM_altstr_ins(prvm_prog_t *prog)
3794 {
3795         int num;
3796         const char *set;
3797         const char *in;
3798         char *out;
3799         char outstr[VM_TEMPSTRING_MAXSIZE];
3800
3801         VM_SAFEPARMCOUNT(3, VM_altstr_ins);
3802
3803         in = PRVM_G_STRING( OFS_PARM0 );
3804         num = (int)PRVM_G_FLOAT( OFS_PARM1 );
3805         set = PRVM_G_STRING( OFS_PARM2 );
3806
3807         out = outstr;
3808         for( num = num * 2 + 2 ; *in && num > 0 ; *out++ = *in++ )
3809                 if( *in == '\\' ) {
3810                         if( !*++in ) {
3811                                 break;
3812                         }
3813                 } else if( *in == '\'' ) {
3814                         num--;
3815                 }
3816
3817         *out++ = '\'';
3818         for( ; *set ; *out++ = *set++ );
3819         *out++ = '\'';
3820
3821         out += dp_strlcpy(out, in, outstr + sizeof(outstr) - out);
3822         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outstr, out - outstr);
3823 }
3824
3825
3826 ////////////////////////////////////////
3827 // BufString functions
3828 ////////////////////////////////////////
3829 //[515]: string buffers support
3830
3831 static size_t stringbuffers_sortlength;
3832
3833 static void BufStr_Expand(prvm_prog_t *prog, prvm_stringbuffer_t *stringbuffer, int strindex)
3834 {
3835         if (stringbuffer->max_strings <= strindex)
3836         {
3837                 char **oldstrings = stringbuffer->strings;
3838                 stringbuffer->max_strings = max(stringbuffer->max_strings * 2, 128);
3839                 while (stringbuffer->max_strings <= strindex)
3840                         stringbuffer->max_strings *= 2;
3841                 stringbuffer->strings = (char **) Mem_Alloc(prog->progs_mempool, stringbuffer->max_strings * sizeof(stringbuffer->strings[0]));
3842                 if (stringbuffer->num_strings > 0)
3843                         memcpy(stringbuffer->strings, oldstrings, stringbuffer->num_strings * sizeof(stringbuffer->strings[0]));
3844                 if (oldstrings)
3845                         Mem_Free(oldstrings);
3846         }
3847 }
3848
3849 static void BufStr_Shrink(prvm_prog_t *prog, prvm_stringbuffer_t *stringbuffer)
3850 {
3851         // reduce num_strings if there are empty string slots at the end
3852         while (stringbuffer->num_strings > 0 && stringbuffer->strings[stringbuffer->num_strings - 1] == NULL)
3853                 stringbuffer->num_strings--;
3854
3855         // if empty, free the string pointer array
3856         if (stringbuffer->num_strings == 0)
3857         {
3858                 stringbuffer->max_strings = 0;
3859                 if (stringbuffer->strings)
3860                         Mem_Free(stringbuffer->strings);
3861                 stringbuffer->strings = NULL;
3862         }
3863 }
3864
3865 static int BufStr_SortStringsUP (const void *in1, const void *in2)
3866 {
3867         const char *a, *b;
3868         a = *((const char **) in1);
3869         b = *((const char **) in2);
3870         if(!a || !a[0]) return 1;
3871         if(!b || !b[0]) return -1;
3872         return strncmp(a, b, stringbuffers_sortlength);
3873 }
3874
3875 static int BufStr_SortStringsDOWN (const void *in1, const void *in2)
3876 {
3877         const char *a, *b;
3878         a = *((const char **) in1);
3879         b = *((const char **) in2);
3880         if(!a || !a[0]) return 1;
3881         if(!b || !b[0]) return -1;
3882         return strncmp(b, a, stringbuffers_sortlength);
3883 }
3884
3885 prvm_stringbuffer_t *BufStr_FindCreateReplace (prvm_prog_t *prog, int bufindex, unsigned flags, const char *format)
3886 {
3887         prvm_stringbuffer_t *stringbuffer;
3888         int i;
3889
3890         if (bufindex < 0)
3891                 return NULL;
3892
3893         // find buffer with wanted index
3894         if (bufindex < (int)Mem_ExpandableArray_IndexRange(&prog->stringbuffersarray))
3895         {
3896                 if ( (stringbuffer = (prvm_stringbuffer_t*) Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, bufindex)) )
3897                 {
3898                         if (stringbuffer->flags & STRINGBUFFER_TEMP)
3899                                 stringbuffer->flags = flags; // created but has not been used yet
3900                         return stringbuffer;
3901                 }
3902                 return NULL;
3903         }
3904
3905         // allocate new buffer with wanted index
3906         while(1)
3907         {
3908                 stringbuffer = (prvm_stringbuffer_t *) Mem_ExpandableArray_AllocRecord(&prog->stringbuffersarray);
3909                 stringbuffer->flags = STRINGBUFFER_TEMP;
3910                 for (i = 0;stringbuffer != Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, i);i++);
3911                 if (i == bufindex)
3912                 {
3913                         stringbuffer->flags = flags; // mark as used
3914                         break;
3915                 }
3916         }
3917         return stringbuffer;
3918 }
3919
3920 void BufStr_Set(prvm_prog_t *prog, prvm_stringbuffer_t *stringbuffer, int strindex, const char *str)
3921 {
3922         size_t  alloclen;
3923
3924         if (!stringbuffer || strindex < 0)
3925                 return;
3926
3927         BufStr_Expand(prog, stringbuffer, strindex);
3928         stringbuffer->num_strings = max(stringbuffer->num_strings, strindex + 1);
3929         if (stringbuffer->strings[strindex])
3930                 Mem_Free(stringbuffer->strings[strindex]);
3931         stringbuffer->strings[strindex] = NULL;
3932
3933         if (str)
3934         {
3935                 // not the NULL string!
3936                 alloclen = strlen(str) + 1;
3937                 stringbuffer->strings[strindex] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
3938                 memcpy(stringbuffer->strings[strindex], str, alloclen);
3939         }
3940
3941         BufStr_Shrink(prog, stringbuffer);
3942 }
3943
3944 void BufStr_Del(prvm_prog_t *prog, prvm_stringbuffer_t *stringbuffer)
3945 {
3946         int i;
3947         
3948         if (!stringbuffer)
3949                 return;
3950
3951         for (i = 0;i < stringbuffer->num_strings;i++)
3952                 if (stringbuffer->strings[i])
3953                         Mem_Free(stringbuffer->strings[i]);
3954         if (stringbuffer->strings)
3955                 Mem_Free(stringbuffer->strings);
3956         if(stringbuffer->origin)
3957                 PRVM_Free((char *)stringbuffer->origin);
3958         Mem_ExpandableArray_FreeRecord(&prog->stringbuffersarray, stringbuffer);
3959 }
3960
3961 void BufStr_Flush(prvm_prog_t *prog)
3962 {
3963         prvm_stringbuffer_t *stringbuffer;
3964         int i, numbuffers;
3965
3966         numbuffers = (int)Mem_ExpandableArray_IndexRange(&prog->stringbuffersarray);
3967         for (i = 0; i < numbuffers; i++)
3968                 if ( (stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, i)) )
3969                         BufStr_Del(prog, stringbuffer);
3970         Mem_ExpandableArray_NewArray(&prog->stringbuffersarray, prog->progs_mempool, sizeof(prvm_stringbuffer_t), 64);
3971 }
3972
3973 /*
3974 ========================
3975 VM_buf_create
3976 creates new buffer, and returns it's index, returns -1 if failed
3977 float buf_create(prvm_prog_t *prog) = #460;
3978 float newbuf(string format, float flags) = #460;
3979 ========================
3980 */
3981
3982 void VM_buf_create (prvm_prog_t *prog)
3983 {
3984         prvm_stringbuffer_t *stringbuffer;
3985         int i;
3986
3987         VM_SAFEPARMCOUNTRANGE(0, 2, VM_buf_create);
3988
3989         // VorteX: optional parm1 (buffer format) is unfinished, to keep intact with future databuffers extension must be set to "string"
3990         if(prog->argc >= 1 && strcmp(PRVM_G_STRING(OFS_PARM0), "string"))
3991         {
3992                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3993                 return;
3994         }
3995         stringbuffer = (prvm_stringbuffer_t *) Mem_ExpandableArray_AllocRecord(&prog->stringbuffersarray);
3996         for (i = 0;stringbuffer != Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, i);i++);
3997         stringbuffer->origin = PRVM_AllocationOrigin(prog);
3998         // optional flags parm
3999         if (prog->argc >= 2)
4000                 stringbuffer->flags = (int)PRVM_G_FLOAT(OFS_PARM1) & STRINGBUFFER_QCFLAGS;
4001         PRVM_G_FLOAT(OFS_RETURN) = i;
4002 }
4003
4004
4005
4006 /*
4007 ========================
4008 VM_buf_del
4009 deletes buffer and all strings in it
4010 void buf_del(float bufhandle) = #461;
4011 ========================
4012 */
4013 void VM_buf_del (prvm_prog_t *prog)
4014 {
4015         prvm_stringbuffer_t *stringbuffer;
4016         VM_SAFEPARMCOUNT(1, VM_buf_del);
4017         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4018         if (stringbuffer)
4019                 BufStr_Del(prog, stringbuffer);
4020         else
4021         {
4022                 VM_Warning(prog, "VM_buf_del: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4023                 return;
4024         }
4025 }
4026
4027 /*
4028 ========================
4029 VM_buf_getsize
4030 how many strings are stored in buffer
4031 float buf_getsize(float bufhandle) = #462;
4032 ========================
4033 */
4034 void VM_buf_getsize (prvm_prog_t *prog)
4035 {
4036         prvm_stringbuffer_t *stringbuffer;
4037         VM_SAFEPARMCOUNT(1, VM_buf_getsize);
4038
4039         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4040         if(!stringbuffer)
4041         {
4042                 PRVM_G_FLOAT(OFS_RETURN) = -1;
4043                 VM_Warning(prog, "VM_buf_getsize: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4044                 return;
4045         }
4046         else
4047                 PRVM_G_FLOAT(OFS_RETURN) = stringbuffer->num_strings;
4048 }
4049
4050 /*
4051 ========================
4052 VM_buf_copy
4053 copy all content from one buffer to another, make sure it exists
4054 void buf_copy(float bufhandle_from, float bufhandle_to) = #463;
4055 ========================
4056 */
4057 void VM_buf_copy (prvm_prog_t *prog)
4058 {
4059         prvm_stringbuffer_t *srcstringbuffer, *dststringbuffer;
4060         int i;
4061         VM_SAFEPARMCOUNT(2, VM_buf_copy);
4062
4063         srcstringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4064         if(!srcstringbuffer)
4065         {
4066                 VM_Warning(prog, "VM_buf_copy: invalid source buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4067                 return;
4068         }
4069         i = (int)PRVM_G_FLOAT(OFS_PARM1);
4070         if(i == (int)PRVM_G_FLOAT(OFS_PARM0))
4071         {
4072                 VM_Warning(prog, "VM_buf_copy: source == destination (%i) in %s\n", i, prog->name);
4073                 return;
4074         }
4075         dststringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4076         if(!dststringbuffer)
4077         {
4078                 VM_Warning(prog, "VM_buf_copy: invalid destination buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), prog->name);
4079                 return;
4080         }
4081
4082         for (i = 0;i < dststringbuffer->num_strings;i++)
4083                 if (dststringbuffer->strings[i])
4084                         Mem_Free(dststringbuffer->strings[i]);
4085         if (dststringbuffer->strings)
4086                 Mem_Free(dststringbuffer->strings);
4087         *dststringbuffer = *srcstringbuffer;
4088         if (dststringbuffer->max_strings)
4089                 dststringbuffer->strings = (char **)Mem_Alloc(prog->progs_mempool, sizeof(dststringbuffer->strings[0]) * dststringbuffer->max_strings);
4090
4091         for (i = 0;i < dststringbuffer->num_strings;i++)
4092         {
4093                 if (srcstringbuffer->strings[i])
4094                 {
4095                         size_t stringlen;
4096                         stringlen = strlen(srcstringbuffer->strings[i]) + 1;
4097                         dststringbuffer->strings[i] = (char *)Mem_Alloc(prog->progs_mempool, stringlen);
4098                         memcpy(dststringbuffer->strings[i], srcstringbuffer->strings[i], stringlen);
4099                 }
4100         }
4101 }
4102
4103 /*
4104 ========================
4105 VM_buf_sort
4106 sort buffer by beginnings of strings (cmplength defaults it's length)
4107 "backward == true" means that sorting goes upside-down
4108 void buf_sort(float bufhandle, float cmplength, float backward) = #464;
4109 ========================
4110 */
4111 void VM_buf_sort (prvm_prog_t *prog)
4112 {
4113         prvm_stringbuffer_t *stringbuffer;
4114         VM_SAFEPARMCOUNT(3, VM_buf_sort);
4115
4116         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4117         if(!stringbuffer)
4118         {
4119                 VM_Warning(prog, "VM_buf_sort: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4120                 return;
4121         }
4122         if(stringbuffer->num_strings <= 0)
4123         {
4124                 VM_Warning(prog, "VM_buf_sort: tried to sort empty buffer %i in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4125                 return;
4126         }
4127         stringbuffers_sortlength = (int)PRVM_G_FLOAT(OFS_PARM1);
4128         if(stringbuffers_sortlength <= 0)
4129                 stringbuffers_sortlength = 0x7FFFFFFF;
4130
4131         if(!PRVM_G_FLOAT(OFS_PARM2))
4132                 qsort(stringbuffer->strings, stringbuffer->num_strings, sizeof(char*), BufStr_SortStringsUP);
4133         else
4134                 qsort(stringbuffer->strings, stringbuffer->num_strings, sizeof(char*), BufStr_SortStringsDOWN);
4135
4136         BufStr_Shrink(prog, stringbuffer);
4137 }
4138
4139 /*
4140 ========================
4141 VM_buf_implode
4142 concantenates all buffer string into one with "glue" separator and returns it as tempstring
4143 string buf_implode(float bufhandle, string glue) = #465;
4144 ========================
4145 */
4146 void VM_buf_implode (prvm_prog_t *prog)
4147 {
4148         prvm_stringbuffer_t *stringbuffer;
4149         char k[VM_TEMPSTRING_MAXSIZE];
4150         size_t k_len;
4151         const char *sep;
4152         int i;
4153         size_t l;
4154
4155         VM_SAFEPARMCOUNT(2, VM_buf_implode);
4156
4157         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4158         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
4159         if(!stringbuffer)
4160         {
4161                 VM_Warning(prog, "VM_buf_implode: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4162                 return;
4163         }
4164         if(!stringbuffer->num_strings)
4165                 return;
4166         sep = PRVM_G_STRING(OFS_PARM1);
4167         k[0] = '\0';
4168         k_len = 0;
4169         for(l = i = 0;i < stringbuffer->num_strings;i++)
4170         {
4171                 if(stringbuffer->strings[i])
4172                 {
4173                         l += (i > 0 ? strlen(sep) : 0) + strlen(stringbuffer->strings[i]);
4174                         if (l >= sizeof(k) - 1)
4175                                 break;
4176                         dp_strlcat(k, sep, sizeof(k));
4177                         k_len = dp_strlcat(k, stringbuffer->strings[i], sizeof(k));
4178                 }
4179         }
4180         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, k, k_len);
4181 }
4182
4183 /*
4184 ========================
4185 VM_bufstr_get
4186 get a string from buffer, returns tempstring, dont str_unzone it!
4187 string bufstr_get(float bufhandle, float string_index) = #465;
4188 ========================
4189 */
4190 void VM_bufstr_get (prvm_prog_t *prog)
4191 {
4192         prvm_stringbuffer_t *stringbuffer;
4193         int                             strindex;
4194         VM_SAFEPARMCOUNT(2, VM_bufstr_get);
4195
4196         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
4197         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4198         if(!stringbuffer)
4199         {
4200                 VM_Warning(prog, "VM_bufstr_get: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4201                 return;
4202         }
4203         strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
4204         if (strindex < 0)
4205         {
4206                 // VM_Warning(prog, "VM_bufstr_get: invalid string index %i used in %s\n", strindex, prog->name);
4207                 return;
4208         }
4209         if (strindex < stringbuffer->num_strings && stringbuffer->strings[strindex])
4210                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, stringbuffer->strings[strindex], strlen(stringbuffer->strings[strindex]));
4211 }
4212
4213 /*
4214 ========================
4215 VM_bufstr_set
4216 copies a string into selected slot of buffer
4217 void bufstr_set(float bufhandle, float string_index, string str) = #466;
4218 ========================
4219 */
4220 void VM_bufstr_set (prvm_prog_t *prog)
4221 {
4222         int                             strindex;
4223         prvm_stringbuffer_t *stringbuffer;
4224         const char              *news;
4225
4226         VM_SAFEPARMCOUNT(3, VM_bufstr_set);
4227
4228         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4229         if(!stringbuffer)
4230         {
4231                 VM_Warning(prog, "VM_bufstr_set: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4232                 return;
4233         }
4234         strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
4235         if(strindex < 0 || strindex >= 1000000) // huge number of strings
4236         {
4237                 VM_Warning(prog, "VM_bufstr_set: invalid string index %i used in %s\n", strindex, prog->name);
4238                 return;
4239         }
4240
4241         news = PRVM_G_STRING(OFS_PARM2);
4242         BufStr_Set(prog, stringbuffer, strindex, news);
4243 }
4244
4245 /*
4246 ========================
4247 VM_bufstr_add
4248 adds string to buffer in first free slot and returns its index
4249 "order == true" means that string will be added after last "full" slot
4250 float bufstr_add(float bufhandle, string str, float order) = #467;
4251 ========================
4252 */
4253 void VM_bufstr_add (prvm_prog_t *prog)
4254 {
4255         int                             order, strindex;
4256         prvm_stringbuffer_t *stringbuffer;
4257         const char              *string;
4258         size_t                  alloclen;
4259
4260         VM_SAFEPARMCOUNT(3, VM_bufstr_add);
4261
4262         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4263         PRVM_G_FLOAT(OFS_RETURN) = -1;
4264         if(!stringbuffer)
4265         {
4266                 VM_Warning(prog, "VM_bufstr_add: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4267                 return;
4268         }
4269         if(!PRVM_G_INT(OFS_PARM1)) // NULL string
4270         {
4271                 VM_Warning(prog, "VM_bufstr_add: can not add an empty string to buffer %i in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4272                 return;
4273         }
4274         string = PRVM_G_STRING(OFS_PARM1);
4275         order = (int)PRVM_G_FLOAT(OFS_PARM2);
4276         if(order)
4277                 strindex = stringbuffer->num_strings;
4278         else
4279                 for (strindex = 0;strindex < stringbuffer->num_strings;strindex++)
4280                         if (stringbuffer->strings[strindex] == NULL)
4281                                 break;
4282
4283         BufStr_Expand(prog, stringbuffer, strindex);
4284
4285         stringbuffer->num_strings = max(stringbuffer->num_strings, strindex + 1);
4286         alloclen = strlen(string) + 1;
4287         stringbuffer->strings[strindex] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
4288         memcpy(stringbuffer->strings[strindex], string, alloclen);
4289
4290         PRVM_G_FLOAT(OFS_RETURN) = strindex;
4291 }
4292
4293 /*
4294 ========================
4295 VM_bufstr_free
4296 delete string from buffer
4297 void bufstr_free(float bufhandle, float string_index) = #468;
4298 ========================
4299 */
4300 void VM_bufstr_free (prvm_prog_t *prog)
4301 {
4302         int                             i;
4303         prvm_stringbuffer_t     *stringbuffer;
4304         VM_SAFEPARMCOUNT(2, VM_bufstr_free);
4305
4306         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4307         if(!stringbuffer)
4308         {
4309                 VM_Warning(prog, "VM_bufstr_free: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4310                 return;
4311         }
4312         i = (int)PRVM_G_FLOAT(OFS_PARM1);
4313         if(i < 0)
4314         {
4315                 VM_Warning(prog, "VM_bufstr_free: invalid string index %i used in %s\n", i, prog->name);
4316                 return;
4317         }
4318
4319         if (i < stringbuffer->num_strings)
4320         {
4321                 if(stringbuffer->strings[i])
4322                         Mem_Free(stringbuffer->strings[i]);
4323                 stringbuffer->strings[i] = NULL;
4324         }
4325
4326         BufStr_Shrink(prog, stringbuffer);
4327 }
4328
4329 /*
4330 ========================
4331 VM_buf_loadfile
4332 load a file into string buffer, return 0 or 1
4333 float buf_loadfile(string filename, float bufhandle) = #535;
4334 ========================
4335 */
4336 void VM_buf_loadfile(prvm_prog_t *prog)
4337 {
4338         size_t alloclen;
4339         prvm_stringbuffer_t *stringbuffer;
4340         char string[VM_TEMPSTRING_MAXSIZE];
4341         int strindex, c, end;
4342         const char *filename;
4343         char vabuf[1024];
4344         qfile_t *file;
4345
4346         VM_SAFEPARMCOUNT(2, VM_buf_loadfile);
4347
4348         // get file
4349         filename = PRVM_G_STRING(OFS_PARM0);
4350         file = FS_OpenVirtualFile(va(vabuf, sizeof(vabuf), "data/%s", filename), false);
4351         if (file == NULL)
4352                 file = FS_OpenVirtualFile(va(vabuf, sizeof(vabuf), "%s", filename), false);
4353         if (file == NULL)
4354         {
4355                 if (developer_extra.integer)
4356                         VM_Warning(prog, "VM_buf_loadfile: failed to open file %s in %s\n", filename, prog->name);
4357                 PRVM_G_FLOAT(OFS_RETURN) = 0;
4358                 return;
4359         }
4360
4361         // get string buffer
4362         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM1));
4363         if(!stringbuffer)
4364         {
4365                 VM_Warning(prog, "VM_buf_loadfile: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), prog->name);
4366                 PRVM_G_FLOAT(OFS_RETURN) = 0;
4367                 return;
4368         }
4369
4370         // read file (append to the end of buffer)
4371         strindex = stringbuffer->num_strings;
4372         while(1)
4373         {
4374                 // read line
4375                 end = 0;
4376                 for (;;)
4377                 {
4378                         c = FS_Getc(file);
4379                         if (c == '\r' || c == '\n' || c < 0)
4380                                 break;
4381                         if (end < VM_TEMPSTRING_MAXSIZE - 1)
4382                                 string[end++] = c;
4383                 }
4384                 string[end] = 0;
4385                 // remove \n following \r
4386                 if (c == '\r')
4387                 {
4388                         c = FS_Getc(file);
4389                         if (c != '\n')
4390                                 FS_UnGetc(file, (unsigned char)c);
4391                 }
4392                 // add and continue
4393                 if (c >= 0 || end)
4394                 {
4395                         BufStr_Expand(prog, stringbuffer, strindex);
4396                         stringbuffer->num_strings = max(stringbuffer->num_strings, strindex + 1);
4397                         alloclen = strlen(string) + 1;
4398                         stringbuffer->strings[strindex] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
4399                         memcpy(stringbuffer->strings[strindex], string, alloclen);
4400                         strindex = stringbuffer->num_strings;
4401                 }
4402                 else
4403                         break;
4404         }
4405
4406         // close file
4407         FS_Close(file);
4408         PRVM_G_FLOAT(OFS_RETURN) = 1;
4409 }
4410
4411 /*
4412 ========================
4413 VM_buf_writefile
4414 writes stringbuffer to a file, returns 0 or 1
4415 float buf_writefile(float filehandle, float bufhandle, [, float startpos, float numstrings]) = #468;
4416 ========================
4417 */
4418
4419 void VM_buf_writefile(prvm_prog_t *prog)
4420 {
4421         int filenum, strindex, strnum, strlength;
4422         prvm_stringbuffer_t *stringbuffer;
4423
4424         VM_SAFEPARMCOUNTRANGE(2, 4, VM_buf_writefile);
4425
4426         // get file
4427         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
4428         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
4429         {
4430                 VM_Warning(prog, "VM_buf_writefile: invalid file handle %i used in %s\n", filenum, prog->name);
4431                 return;
4432         }
4433         if (prog->openfiles[filenum] == NULL)
4434         {
4435                 VM_Warning(prog, "VM_buf_writefile: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
4436                 return;
4437         }
4438         
4439         // get string buffer
4440         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM1));
4441         if(!stringbuffer)
4442         {
4443                 VM_Warning(prog, "VM_buf_writefile: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), prog->name);
4444                 PRVM_G_FLOAT(OFS_RETURN) = 0;
4445                 return;
4446         }
4447
4448         // get start and end parms
4449         if (prog->argc > 3)
4450         {
4451                 strindex = (int)PRVM_G_FLOAT(OFS_PARM2);
4452                 strnum = (int)PRVM_G_FLOAT(OFS_PARM3);
4453         }
4454         else if (prog->argc > 2)
4455         {
4456                 strindex = (int)PRVM_G_FLOAT(OFS_PARM2);
4457                 strnum = stringbuffer->num_strings - strindex;
4458         }
4459         else
4460         {
4461                 strindex = 0;
4462                 strnum = stringbuffer->num_strings;
4463         }
4464         if (strindex < 0 || strindex >= stringbuffer->num_strings)
4465         {
4466                 VM_Warning(prog, "VM_buf_writefile: wrong start string index %i used in %s\n", strindex, prog->name);
4467                 PRVM_G_FLOAT(OFS_RETURN) = 0;
4468                 return;
4469         }
4470         if (strnum < 0)
4471         {
4472                 VM_Warning(prog, "VM_buf_writefile: wrong strings count %i used in %s\n", strnum, prog->name);
4473                 PRVM_G_FLOAT(OFS_RETURN) = 0;
4474                 return;
4475         }
4476
4477         // write
4478         while(strindex < stringbuffer->num_strings && strnum)
4479         {
4480                 if (stringbuffer->strings[strindex])
4481                 {
4482                         if ((strlength = (int)strlen(stringbuffer->strings[strindex])))
4483                                 FS_Write(prog->openfiles[filenum], stringbuffer->strings[strindex], strlength);
4484                         FS_Write(prog->openfiles[filenum], "\n", 1);
4485                 }
4486                 strindex++;
4487                 strnum--;
4488         }
4489
4490         PRVM_G_FLOAT(OFS_RETURN) = 1;
4491 }
4492
4493 #define MATCH_AUTO     0
4494 #define MATCH_WHOLE    1
4495 #define MATCH_LEFT     2
4496 #define MATCH_RIGHT    3
4497 #define MATCH_MIDDLE   4
4498 #define MATCH_PATTERN  5
4499
4500 static const char *detect_match_rule(char *pattern, int *matchrule)
4501 {
4502         char *ppos, *qpos;
4503         int patternlength;
4504
4505         patternlength = (int)strlen(pattern);
4506         ppos = strchr(pattern, '*');
4507         qpos = strchr(pattern, '?');
4508         // has ? - pattern
4509         if (qpos) 
4510         {
4511                 *matchrule = MATCH_PATTERN;
4512                 return pattern;
4513         }
4514         // has * - left, mid, right or pattern
4515         if (ppos)
4516         {
4517                 // starts with * - may be right/mid or pattern
4518                 if ((ppos - pattern) == 0)
4519                 {
4520                         ppos = strchr(pattern+1, '*');
4521                         // *something 
4522                         if (!ppos) 
4523                         {
4524                                 *matchrule = MATCH_RIGHT;
4525                                 return pattern+1;
4526                         }
4527                         // *something*
4528                         if ((ppos - pattern) == patternlength)
4529                         {
4530                                 *matchrule = MATCH_MIDDLE;
4531                                 *ppos = 0;
4532                                 return pattern+1;
4533                         }
4534                         // *som*thing
4535                         *matchrule = MATCH_PATTERN;
4536                         return pattern;
4537                 }
4538                 // end with * - left
4539                 if ((ppos - pattern) == patternlength)
4540                 {
4541                         *matchrule = MATCH_LEFT;
4542                         *ppos = 0;
4543                         return pattern;
4544                 }
4545                 // som*thing
4546                 *matchrule = MATCH_PATTERN;
4547                 return pattern;
4548         }
4549         // have no wildcards - whole string
4550         *matchrule = MATCH_WHOLE;
4551         return pattern;
4552 }
4553
4554 // todo: support UTF8
4555 static qbool match_rule(const char *string, int max_string, const char *pattern, int patternlength, int rule)
4556 {
4557         const char *mid;
4558
4559         if (rule == 1)
4560                 return !strncmp(string, pattern, max_string) ? true : false;
4561         if (rule == 2)
4562                 return !strncmp(string, pattern, patternlength) ? true : false;
4563         if (rule == 3)
4564         {
4565                 mid = strstr(string, pattern);
4566                 return mid && !*(mid+patternlength);
4567         }
4568         if (rule == 4)
4569                 return strstr(string, pattern) ? true : false;
4570         // pattern
4571         return matchpattern_with_separator(string, pattern, false, "", false) ? true : false;
4572 }
4573
4574 /*
4575 ========================
4576 VM_bufstr_find
4577 find an index of bufstring matching rule
4578 float bufstr_find(float bufhandle, string match, float matchrule, float startpos, float step) = #468;
4579 ========================
4580 */
4581
4582 void VM_bufstr_find(prvm_prog_t *prog)
4583 {
4584         prvm_stringbuffer_t *stringbuffer;
4585         char string[VM_TEMPSTRING_MAXSIZE];
4586         int matchrule, matchlen, i, step;
4587         const char *match;
4588
4589         VM_SAFEPARMCOUNTRANGE(3, 5, VM_bufstr_find);
4590
4591         PRVM_G_FLOAT(OFS_RETURN) = -1;
4592
4593         // get string buffer
4594         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4595         if(!stringbuffer)
4596         {
4597                 VM_Warning(prog, "VM_bufstr_find: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4598                 return;
4599         }
4600
4601         // get pattern/rule
4602         matchrule = (int)PRVM_G_FLOAT(OFS_PARM2);
4603         if (matchrule < 0 || matchrule > 5)
4604         {
4605                 VM_Warning(prog, "VM_bufstr_find: invalid match rule %i in %s\n", matchrule, prog->name);
4606                 return;
4607         }
4608         if (matchrule)
4609                 match = PRVM_G_STRING(OFS_PARM1);
4610         else
4611         {
4612                 dp_strlcpy(string, PRVM_G_STRING(OFS_PARM1), sizeof(string));
4613                 match = detect_match_rule(string, &matchrule);
4614         }
4615         matchlen = (int)strlen(match);
4616
4617         // find
4618         i = (prog->argc > 3) ? (int)PRVM_G_FLOAT(OFS_PARM3) : 0;
4619         step = (prog->argc > 4) ? (int)PRVM_G_FLOAT(OFS_PARM4) : 1;
4620         while(i < stringbuffer->num_strings)
4621         {
4622                 if (stringbuffer->strings[i] && match_rule(stringbuffer->strings[i], VM_TEMPSTRING_MAXSIZE, match, matchlen, matchrule))
4623                 {
4624                         PRVM_G_FLOAT(OFS_RETURN) = i;
4625                         break;
4626                 }
4627                 i += step;
4628         }
4629 }
4630
4631 /*
4632 ========================
4633 VM_matchpattern
4634 float matchpattern(string s, string pattern, float matchrule, float startpos) = #468;
4635 ========================
4636 */
4637 void VM_matchpattern(prvm_prog_t *prog)
4638 {
4639         const char *s, *match;
4640         char string[VM_TEMPSTRING_MAXSIZE];
4641         int matchrule, l;
4642
4643         VM_SAFEPARMCOUNTRANGE(2, 4, VM_matchpattern);
4644
4645         s = PRVM_G_STRING(OFS_PARM0);
4646
4647         // get pattern/rule
4648         matchrule = (int)PRVM_G_FLOAT(OFS_PARM2);
4649         if (matchrule < 0 || matchrule > 5)
4650         {
4651                 VM_Warning(prog, "VM_matchpattern: invalid match rule %i in %s\n", matchrule, prog->name);
4652                 return;
4653         }
4654         if (matchrule)
4655                 match = PRVM_G_STRING(OFS_PARM1);
4656         else
4657         {
4658                 dp_strlcpy(string, PRVM_G_STRING(OFS_PARM1), sizeof(string));
4659                 match = detect_match_rule(string, &matchrule);
4660         }
4661
4662         // offset
4663         l = (int)strlen(match);
4664         if (prog->argc > 3)
4665                 s += max(0, min((unsigned int)PRVM_G_FLOAT(OFS_PARM3), strlen(s)-1));
4666
4667         // match
4668         PRVM_G_FLOAT(OFS_RETURN) = match_rule(s, VM_TEMPSTRING_MAXSIZE, match, l, matchrule);
4669 }
4670
4671 /*
4672 ========================
4673 VM_buf_cvarlist
4674 ========================
4675 */
4676
4677 void VM_buf_cvarlist(prvm_prog_t *prog)
4678 {
4679         cvar_t *cvar;
4680         const char *partial, *antipartial;
4681         size_t len, antilen;
4682         size_t alloclen;
4683         qbool ispattern, antiispattern;
4684         int n;
4685         prvm_stringbuffer_t     *stringbuffer;
4686         VM_SAFEPARMCOUNTRANGE(2, 3, VM_buf_cvarlist);
4687
4688         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4689         if(!stringbuffer)
4690         {
4691                 VM_Warning(prog, "VM_bufstr_free: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4692                 return;
4693         }
4694
4695         partial = PRVM_G_STRING(OFS_PARM1);
4696         if(!partial)
4697                 len = 0;
4698         else
4699                 len = strlen(partial);
4700
4701         if(prog->argc == 3)
4702                 antipartial = PRVM_G_STRING(OFS_PARM2);
4703         else
4704                 antipartial = NULL;
4705         if(!antipartial)
4706                 antilen = 0;
4707         else
4708                 antilen = strlen(antipartial);
4709         
4710         for (n = 0;n < stringbuffer->num_strings;n++)
4711                 if (stringbuffer->strings[n])
4712                         Mem_Free(stringbuffer->strings[n]);
4713         if (stringbuffer->strings)
4714                 Mem_Free(stringbuffer->strings);
4715         stringbuffer->strings = NULL;
4716
4717         ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
4718         antiispattern = antipartial && (strchr(antipartial, '*') || strchr(antipartial, '?'));
4719
4720         n = 0;
4721         for(cvar = prog->console_cmd->cvars->vars; cvar; cvar = cvar->next)
4722         {
4723                 if(len && (ispattern ? !matchpattern_with_separator(cvar->name, partial, false, "", false) : strncmp(partial, cvar->name, len)))
4724                         continue;
4725
4726                 if(antilen && (antiispattern ? matchpattern_with_separator(cvar->name, antipartial, false, "", false) : !strncmp(antipartial, cvar->name, antilen)))
4727                         continue;
4728
4729                 ++n;
4730         }
4731
4732         stringbuffer->max_strings = stringbuffer->num_strings = n;
4733         if (stringbuffer->max_strings)
4734                 stringbuffer->strings = (char **)Mem_Alloc(prog->progs_mempool, sizeof(stringbuffer->strings[0]) * stringbuffer->max_strings);
4735         
4736         n = 0;
4737         for(cvar = prog->console_cmd->cvars->vars; cvar; cvar = cvar->next)
4738         {
4739                 if(len && (ispattern ? !matchpattern_with_separator(cvar->name, partial, false, "", false) : strncmp(partial, cvar->name, len)))
4740                         continue;
4741
4742                 if(antilen && (antiispattern ? matchpattern_with_separator(cvar->name, antipartial, false, "", false) : !strncmp(antipartial, cvar->name, antilen)))
4743                         continue;
4744
4745                 alloclen = strlen(cvar->name) + 1;
4746                 stringbuffer->strings[n] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
4747                 memcpy(stringbuffer->strings[n], cvar->name, alloclen);
4748
4749                 ++n;
4750         }
4751 }
4752
4753
4754
4755
4756 //=============
4757
4758 /*
4759 ==============
4760 VM_changeyaw
4761
4762 This was a major timewaster in progs, so it was converted to C
4763 ==============
4764 */
4765 void VM_changeyaw (prvm_prog_t *prog)
4766 {
4767         prvm_edict_t            *ent;
4768         float           ideal, current, move, speed;
4769
4770         // this is called (VERY HACKISHLY) by VM_SV_MoveToGoal, so it can not use any
4771         // parameters because they are the parameters to VM_SV_MoveToGoal, not this
4772         //VM_SAFEPARMCOUNT(0, VM_changeyaw);
4773
4774         ent = PRVM_PROG_TO_EDICT(PRVM_gameglobaledict(self));
4775         if (ent == prog->edicts)
4776         {
4777                 VM_Warning(prog, "changeyaw: can not modify world entity\n");
4778                 return;
4779         }
4780         if (ent->free)
4781         {
4782                 VM_Warning(prog, "changeyaw: can not modify free entity\n");
4783                 return;
4784         }
4785         current = PRVM_gameedictvector(ent, angles)[1];
4786         current = ANGLEMOD(current);
4787         ideal = PRVM_gameedictfloat(ent, ideal_yaw);
4788         speed = PRVM_gameedictfloat(ent, yaw_speed);
4789
4790         if (current == ideal)
4791                 return;
4792         move = ideal - current;
4793         if (ideal > current)
4794         {
4795                 if (move >= 180)
4796                         move = move - 360;
4797         }
4798         else
4799         {
4800                 if (move <= -180)
4801                         move = move + 360;
4802         }
4803         if (move > 0)
4804         {
4805                 if (move > speed)
4806                         move = speed;
4807         }
4808         else
4809         {
4810                 if (move < -speed)
4811                         move = -speed;
4812         }
4813
4814         current += move;
4815         PRVM_gameedictvector(ent, angles)[1] = ANGLEMOD(current);
4816 }
4817
4818 /*
4819 ==============
4820 VM_changepitch
4821 ==============
4822 */
4823 void VM_changepitch (prvm_prog_t *prog)
4824 {
4825         prvm_edict_t            *ent;
4826         float           ideal, current, move, speed;
4827
4828         VM_SAFEPARMCOUNT(1, VM_changepitch);
4829
4830         ent = PRVM_G_EDICT(OFS_PARM0);
4831         if (ent == prog->edicts)
4832         {
4833                 VM_Warning(prog, "changepitch: can not modify world entity\n");
4834                 return;
4835         }
4836         if (ent->free)
4837         {
4838                 VM_Warning(prog, "changepitch: can not modify free entity\n");
4839                 return;
4840         }
4841         current = PRVM_gameedictvector(ent, angles)[0];
4842         current = ANGLEMOD(current);
4843         ideal = PRVM_gameedictfloat(ent, idealpitch);
4844         speed = PRVM_gameedictfloat(ent, pitch_speed);
4845
4846         if (current == ideal)
4847                 return;
4848         move = ideal - current;
4849         if (ideal > current)
4850         {
4851                 if (move >= 180)
4852                         move = move - 360;
4853         }
4854         else
4855         {
4856                 if (move <= -180)
4857                         move = move + 360;
4858         }
4859         if (move > 0)
4860         {
4861                 if (move > speed)
4862                         move = speed;
4863         }
4864         else
4865         {
4866                 if (move < -speed)
4867                         move = -speed;
4868         }
4869
4870         current += move;
4871         PRVM_gameedictvector(ent, angles)[0] = ANGLEMOD(current);
4872 }
4873
4874
4875 void VM_uncolorstring (prvm_prog_t *prog)
4876 {
4877         char szNewString[VM_TEMPSTRING_MAXSIZE];
4878         size_t szNewString_len;
4879         const char *szString;
4880
4881         // Prepare Strings
4882         VM_SAFEPARMCOUNT(1, VM_uncolorstring);
4883         szString = PRVM_G_STRING(OFS_PARM0);
4884         szNewString_len = COM_StringDecolorize(szString, 0, szNewString, sizeof(szNewString), true);
4885         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString, szNewString_len);
4886 }
4887
4888 // #221 float(string str, string sub[, float startpos]) strstrofs (FTE_STRINGS)
4889 //strstr, without generating a new string. Use in conjunction with FRIK_FILE's substring for more similar strstr.
4890 void VM_strstrofs (prvm_prog_t *prog)
4891 {
4892         const char *instr, *match;
4893         int firstofs;
4894         VM_SAFEPARMCOUNTRANGE(2, 3, VM_strstrofs);
4895         instr = PRVM_G_STRING(OFS_PARM0);
4896         match = PRVM_G_STRING(OFS_PARM1);
4897         firstofs = (prog->argc > 2)?(int)PRVM_G_FLOAT(OFS_PARM2):0;
4898         firstofs = (int)u8_bytelen(instr, firstofs);
4899
4900         if (firstofs && (firstofs < 0 || firstofs > (int)strlen(instr)))
4901         {
4902                 PRVM_G_FLOAT(OFS_RETURN) = -1;
4903                 return;
4904         }
4905
4906         match = strstr(instr+firstofs, match);
4907         if (!match)
4908                 PRVM_G_FLOAT(OFS_RETURN) = -1;
4909         else
4910                 PRVM_G_FLOAT(OFS_RETURN) = u8_strnlen(instr, match-instr);
4911 }
4912
4913 //#222 string(string s, float index) str2chr (FTE_STRINGS)
4914 void VM_str2chr (prvm_prog_t *prog)
4915 {
4916         const char *s;
4917         Uchar ch;
4918         int index;
4919         VM_SAFEPARMCOUNT(2, VM_str2chr);
4920         s = PRVM_G_STRING(OFS_PARM0);
4921         index = (int)u8_bytelen(s, (int)PRVM_G_FLOAT(OFS_PARM1));
4922
4923         if((unsigned)index < strlen(s))
4924         {
4925                 if (utf8_enable.integer)
4926                         ch = u8_getchar_noendptr(s + index);
4927                 else
4928                         ch = (unsigned char)s[index];
4929                 PRVM_G_FLOAT(OFS_RETURN) = ch;
4930         }
4931         else
4932                 PRVM_G_FLOAT(OFS_RETURN) = 0;
4933 }
4934
4935 //#223 string(float c, ...) chr2str (FTE_STRINGS)
4936 void VM_chr2str (prvm_prog_t *prog)
4937 {
4938         /*
4939         char    t[9];
4940         int             i;
4941         VM_SAFEPARMCOUNTRANGE(0, 8, VM_chr2str);
4942         for(i = 0;i < prog->argc && i < (int)sizeof(t) - 1;i++)
4943                 t[i] = (unsigned char)PRVM_G_FLOAT(OFS_PARM0+i*3);
4944         t[i] = 0;
4945         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, t);
4946         */
4947         char t[9 * 4 + 1];
4948         int i;
4949         size_t len = 0;
4950
4951         VM_SAFEPARMCOUNTRANGE(0, 8, VM_chr2str);
4952         for(i = 0; i < prog->argc && len < sizeof(t)-1; ++i)
4953                 len += u8_fromchar((Uchar)PRVM_G_FLOAT(OFS_PARM0+i*3), t + len, sizeof(t)-1);
4954         t[len] = '\0';
4955         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, t, len);
4956 }
4957
4958 static int chrconv_number(int i, int base, int conv)
4959 {
4960         i -= base;
4961         switch (conv)
4962         {
4963         default:
4964         case 5:
4965         case 6:
4966         case 0:
4967                 break;
4968         case 1:
4969                 base = '0';
4970                 break;
4971         case 2:
4972                 base = '0'+128;
4973                 break;
4974         case 3:
4975                 base = '0'-30;
4976                 break;
4977         case 4:
4978                 base = '0'+128-30;
4979                 break;
4980         }
4981         return i + base;
4982 }
4983 static int chrconv_punct(int i, int base, int conv)
4984 {
4985         i -= base;
4986         switch (conv)
4987         {
4988         default:
4989         case 0:
4990                 break;
4991         case 1:
4992                 base = 0;
4993                 break;
4994         case 2:
4995                 base = 128;
4996                 break;
4997         }
4998         return i + base;
4999 }
5000
5001 static int chrchar_alpha(int i, int basec, int baset, int convc, int convt, int charnum)
5002 {
5003         //convert case and colour seperatly...
5004
5005         i -= baset + basec;
5006         switch (convt)
5007         {
5008         default:
5009         case 0:
5010                 break;
5011         case 1:
5012                 baset = 0;
5013                 break;
5014         case 2:
5015                 baset = 128;
5016                 break;
5017
5018         case 5:
5019         case 6:
5020                 baset = 128*((charnum&1) == (convt-5));
5021                 break;
5022         }
5023
5024         switch (convc)
5025         {
5026         default:
5027         case 0:
5028                 break;
5029         case 1:
5030                 basec = 'a';
5031                 break;
5032         case 2:
5033                 basec = 'A';
5034                 break;
5035         }
5036         return i + basec + baset;
5037 }
5038 // #224 string(float ccase, float calpha, float cnum, string s, ...) strconv (FTE_STRINGS)
5039 //bulk convert a string. change case or colouring.
5040 void VM_strconv (prvm_prog_t *prog)
5041 {
5042         int ccase, redalpha, rednum;
5043         unsigned i;
5044         size_t resbuf_len;
5045         unsigned char resbuf[VM_TEMPSTRING_MAXSIZE];
5046         unsigned char *result = resbuf;
5047
5048         VM_SAFEPARMCOUNTRANGE(3, 8, VM_strconv);
5049
5050         ccase = (int) PRVM_G_FLOAT(OFS_PARM0);  //0 same, 1 lower, 2 upper
5051         redalpha = (int) PRVM_G_FLOAT(OFS_PARM1);       //0 same, 1 white, 2 red,  5 alternate, 6 alternate-alternate
5052         rednum = (int) PRVM_G_FLOAT(OFS_PARM2); //0 same, 1 white, 2 red, 3 redspecial, 4 whitespecial, 5 alternate, 6 alternate-alternate
5053         resbuf_len = VM_VarString(prog, 3, (char *) resbuf, sizeof(resbuf));
5054
5055         for (i = 0; i < resbuf_len; i++, result++)      //should this be done backwards?
5056         {
5057                 if (*result >= '0' && *result <= '9')   //normal numbers...
5058                         *result = chrconv_number(*result, '0', rednum);
5059                 else if (*result >= '0'+128 && *result <= '9'+128)
5060                         *result = chrconv_number(*result, '0'+128, rednum);
5061                 else if (*result >= '0'+128-30 && *result <= '9'+128-30)
5062                         *result = chrconv_number(*result, '0'+128-30, rednum);
5063                 else if (*result >= '0'-30 && *result <= '9'-30)
5064                         *result = chrconv_number(*result, '0'-30, rednum);
5065
5066                 else if (*result >= 'a' && *result <= 'z')      //normal numbers...
5067                         *result = chrchar_alpha(*result, 'a', 0, ccase, redalpha, i);
5068                 else if (*result >= 'A' && *result <= 'Z')      //normal numbers...
5069                         *result = chrchar_alpha(*result, 'A', 0, ccase, redalpha, i);
5070                 else if (*result >= 'a'+128 && *result <= 'z'+128)      //normal numbers...
5071                         *result = chrchar_alpha(*result, 'a', 128, ccase, redalpha, i);
5072                 else if (*result >= 'A'+128 && *result <= 'Z'+128)      //normal numbers...
5073                         *result = chrchar_alpha(*result, 'A', 128, ccase, redalpha, i);
5074
5075                 else if ((*result & 127) < 16 || !redalpha)     //special chars..
5076                         *result = *result;
5077                 else if (*result < 128)
5078                         *result = chrconv_punct(*result, 0, redalpha);
5079                 else
5080                         *result = chrconv_punct(*result, 128, redalpha);
5081         }
5082         *result = '\0';
5083
5084         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, (char *)resbuf, result - resbuf);
5085 }
5086
5087 // #225 string(float chars, string s, ...) strpad (FTE_STRINGS)
5088 void VM_strpad (prvm_prog_t *prog)
5089 {
5090         char src[VM_TEMPSTRING_MAXSIZE];
5091         char destbuf[VM_TEMPSTRING_MAXSIZE];
5092         size_t destbuf_len;
5093         int pad;
5094
5095         VM_SAFEPARMCOUNTRANGE(1, 8, VM_strpad);
5096         pad = (int) PRVM_G_FLOAT(OFS_PARM0);
5097         VM_VarString(prog, 1, src, sizeof(src));
5098
5099         // note: < 0 = left padding, > 0 = right padding,
5100         // this is reverse logic of printf!
5101         destbuf_len = dpsnprintf(destbuf, sizeof(destbuf), "%*s", -pad, src);
5102
5103         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, destbuf, destbuf_len);
5104 }
5105
5106 // #226 string(string info, string key, string value, ...) infoadd (FTE_STRINGS)
5107 //uses qw style \key\value strings
5108 void VM_infoadd (prvm_prog_t *prog)
5109 {
5110         const char *info, *key;
5111         char value[VM_TEMPSTRING_MAXSIZE];
5112         char temp[VM_TEMPSTRING_MAXSIZE];
5113
5114         VM_SAFEPARMCOUNTRANGE(2, 8, VM_infoadd);
5115         info = PRVM_G_STRING(OFS_PARM0);
5116         key = PRVM_G_STRING(OFS_PARM1);
5117         VM_VarString(prog, 2, value, sizeof(value));
5118
5119         dp_strlcpy(temp, info, VM_TEMPSTRING_MAXSIZE);
5120
5121         InfoString_SetValue(temp, VM_TEMPSTRING_MAXSIZE, key, value);
5122
5123         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, temp, strlen(temp));
5124 }
5125
5126 // #227 string(string info, string key) infoget (FTE_STRINGS)
5127 //uses qw style \key\value strings
5128 void VM_infoget (prvm_prog_t *prog)
5129 {
5130         const char *info;
5131         const char *key;
5132         char value[VM_TEMPSTRING_MAXSIZE];
5133
5134         VM_SAFEPARMCOUNT(2, VM_infoget);
5135         info = PRVM_G_STRING(OFS_PARM0);
5136         key = PRVM_G_STRING(OFS_PARM1);
5137
5138         InfoString_GetValue(info, key, value, VM_TEMPSTRING_MAXSIZE);
5139
5140         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, value, strlen(value));
5141 }
5142
5143 //#228 float(string s1, string s2, float len) strncmp (FTE_STRINGS)
5144 // also float(string s1, string s2) strcmp (FRIK_FILE)
5145 void VM_strncmp (prvm_prog_t *prog)
5146 {
5147         const char *s1, *s2;
5148         VM_SAFEPARMCOUNTRANGE(2, 3, VM_strncmp);
5149         s1 = PRVM_G_STRING(OFS_PARM0);
5150         s2 = PRVM_G_STRING(OFS_PARM1);
5151         if (prog->argc > 2)
5152         {
5153                 PRVM_G_FLOAT(OFS_RETURN) = strncmp(s1, s2, (size_t)PRVM_G_FLOAT(OFS_PARM2));
5154         }
5155         else
5156         {
5157                 PRVM_G_FLOAT(OFS_RETURN) = strcmp(s1, s2);
5158         }
5159 }
5160
5161 // #229 float(string s1, string s2) strcasecmp (FTE_STRINGS)
5162 // #230 float(string s1, string s2, float len) strncasecmp (FTE_STRINGS)
5163 void VM_strncasecmp (prvm_prog_t *prog)
5164 {
5165         const char *s1, *s2;
5166         VM_SAFEPARMCOUNTRANGE(2, 3, VM_strncasecmp);
5167         s1 = PRVM_G_STRING(OFS_PARM0);
5168         s2 = PRVM_G_STRING(OFS_PARM1);
5169         if (prog->argc > 2)
5170         {
5171                 PRVM_G_FLOAT(OFS_RETURN) = strncasecmp(s1, s2, (size_t)PRVM_G_FLOAT(OFS_PARM2));
5172         }
5173         else
5174         {
5175                 PRVM_G_FLOAT(OFS_RETURN) = strcasecmp(s1, s2);
5176         }
5177 }
5178
5179 // #494 float(float caseinsensitive, string s, ...) crc16
5180 void VM_crc16(prvm_prog_t *prog)
5181 {
5182         float insensitive;
5183         char s[VM_TEMPSTRING_MAXSIZE];
5184         size_t slen;
5185
5186         VM_SAFEPARMCOUNTRANGE(2, 8, VM_crc16);
5187         insensitive = PRVM_G_FLOAT(OFS_PARM0);
5188         slen = VM_VarString(prog, 1, s, sizeof(s));
5189         PRVM_G_FLOAT(OFS_RETURN) = (unsigned short) ((insensitive ? CRC_Block_CaseInsensitive : CRC_Block) ((unsigned char *) s, slen));
5190 }
5191
5192 // #639 float(string digest, string data, ...) digest_hex
5193 void VM_digest_hex(prvm_prog_t *prog)
5194 {
5195         const char *digest;
5196
5197         char out[32];
5198         char outhex[65];
5199         int outlen;
5200
5201         char s[VM_TEMPSTRING_MAXSIZE];
5202         size_t len;
5203
5204         VM_SAFEPARMCOUNTRANGE(2, 8, VM_digest_hex);
5205         digest = PRVM_G_STRING(OFS_PARM0);
5206         if(!digest)
5207                 digest = "";
5208         len = VM_VarString(prog, 1, s, sizeof(s));
5209
5210         outlen = 0;
5211
5212         if(!strcmp(digest, "MD4"))
5213         {
5214                 outlen = 16;
5215                 mdfour((unsigned char *) out, (unsigned char *) s, len);
5216         }
5217         else if(!strcmp(digest, "SHA256") && Crypto_Available())
5218         {
5219                 outlen = 32;
5220                 sha256((unsigned char *) out, (unsigned char *) s, len);
5221         }
5222         // no warning needed on mismatch - we return string_null to QC
5223
5224         if(outlen)
5225         {
5226                 int i;
5227                 static const char *hexmap = "0123456789abcdef";
5228                 for(i = 0; i < outlen; ++i)
5229                 {
5230                         outhex[2*i]   = hexmap[(out[i] >> 4) & 15];
5231                         outhex[2*i+1] = hexmap[(out[i] >> 0) & 15];
5232                 }
5233                 outhex[2*i] = '\0';
5234                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outhex, 2*i);
5235         }
5236         else
5237                 PRVM_G_INT(OFS_RETURN) = 0;
5238 }
5239
5240 void VM_wasfreed (prvm_prog_t *prog)
5241 {
5242         VM_SAFEPARMCOUNT(1, VM_wasfreed);
5243         PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_EDICT(OFS_PARM0)->free;
5244 }
5245
5246 void VM_SetTraceGlobals(prvm_prog_t *prog, const trace_t *trace)
5247 {
5248         PRVM_gameglobalfloat(trace_allsolid) = trace->allsolid;
5249         PRVM_gameglobalfloat(trace_startsolid) = trace->startsolid;
5250         PRVM_gameglobalfloat(trace_fraction) = trace->fraction;
5251         PRVM_gameglobalfloat(trace_inwater) = trace->inwater;
5252         PRVM_gameglobalfloat(trace_inopen) = trace->inopen;
5253         VectorCopy(trace->endpos, PRVM_gameglobalvector(trace_endpos));
5254         VectorCopy(trace->plane.normal, PRVM_gameglobalvector(trace_plane_normal));
5255         PRVM_gameglobalfloat(trace_plane_dist) = trace->plane.dist;
5256         PRVM_gameglobaledict(trace_ent) = PRVM_EDICT_TO_PROG(trace->ent ? trace->ent : prog->edicts);
5257         PRVM_gameglobalfloat(trace_dpstartcontents) = trace->startsupercontents;
5258         PRVM_gameglobalfloat(trace_dphitcontents) = trace->hitsupercontents;
5259         PRVM_gameglobalfloat(trace_dphitq3surfaceflags) = trace->hitq3surfaceflags;
5260         PRVM_gameglobalstring(trace_dphittexturename) = trace->hittexture ? PRVM_SetTempString(prog, trace->hittexture->name, strlen(trace->hittexture->name)) : 0;
5261 }
5262
5263 void VM_ClearTraceGlobals(prvm_prog_t *prog)
5264 {
5265         // clean up all trace globals when leaving the VM (anti-triggerbot safeguard)
5266         PRVM_gameglobalfloat(trace_allsolid) = 0;
5267         PRVM_gameglobalfloat(trace_startsolid) = 0;
5268         PRVM_gameglobalfloat(trace_fraction) = 0;
5269         PRVM_gameglobalfloat(trace_inwater) = 0;
5270         PRVM_gameglobalfloat(trace_inopen) = 0;
5271         VectorClear(PRVM_gameglobalvector(trace_endpos));
5272         VectorClear(PRVM_gameglobalvector(trace_plane_normal));
5273         PRVM_gameglobalfloat(trace_plane_dist) = 0;
5274         PRVM_gameglobaledict(trace_ent) = PRVM_EDICT_TO_PROG(prog->edicts);
5275         PRVM_gameglobalfloat(trace_dpstartcontents) = 0;
5276         PRVM_gameglobalfloat(trace_dphitcontents) = 0;
5277         PRVM_gameglobalfloat(trace_dphitq3surfaceflags) = 0;
5278         PRVM_gameglobalstring(trace_dphittexturename) = 0;
5279 }
5280
5281 //=============
5282
5283 void VM_Cmd_Init(prvm_prog_t *prog)
5284 {
5285         // only init the stuff for the current prog
5286         VM_Files_Init(prog);
5287         VM_Search_Init(prog);
5288 }
5289
5290 static void animatemodel_reset(prvm_prog_t *prog);
5291
5292 void VM_Cmd_Reset(prvm_prog_t *prog)
5293 {
5294         CL_PurgeOwner( MENUOWNER );
5295         VM_Search_Reset(prog);
5296         VM_Files_CloseAll(prog);
5297         animatemodel_reset(prog);
5298 }
5299
5300 // #510 string(string input, ...) uri_escape (DP_QC_URI_ESCAPE)
5301 // does URI escaping on a string (replace evil stuff by %AB escapes)
5302 void VM_uri_escape (prvm_prog_t *prog)
5303 {
5304         char src[VM_TEMPSTRING_MAXSIZE];
5305         char dest[VM_TEMPSTRING_MAXSIZE];
5306         char *p, *q;
5307         static const char *hex = "0123456789ABCDEF";
5308
5309         VM_SAFEPARMCOUNTRANGE(1, 8, VM_uri_escape);
5310         VM_VarString(prog, 0, src, sizeof(src));
5311
5312         for(p = src, q = dest; *p && q < dest + sizeof(dest) - 3; ++p)
5313         {
5314                 if((*p >= 'A' && *p <= 'Z')
5315                         || (*p >= 'a' && *p <= 'z')
5316                         || (*p >= '0' && *p <= '9')
5317                         || (*p == '-')  || (*p == '_') || (*p == '.')
5318                         || (*p == '!')  || (*p == '~')
5319                         || (*p == '\'') || (*p == '(') || (*p == ')'))
5320                         *q++ = *p;
5321                 else
5322                 {
5323                         *q++ = '%';
5324                         *q++ = hex[(*(unsigned char *)p >> 4) & 0xF];
5325                         *q++ = hex[ *(unsigned char *)p       & 0xF];
5326                 }
5327         }
5328         *q = '\0';
5329
5330         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, dest, q - dest);
5331 }
5332
5333 // #510 string(string input, ...) uri_unescape (DP_QC_URI_ESCAPE)
5334 // does URI unescaping on a string (get back the evil stuff)
5335 void VM_uri_unescape (prvm_prog_t *prog)
5336 {
5337         char src[VM_TEMPSTRING_MAXSIZE];
5338         char dest[VM_TEMPSTRING_MAXSIZE];
5339         char *p, *q;
5340         int hi, lo;
5341
5342         VM_SAFEPARMCOUNTRANGE(1, 8, VM_uri_unescape);
5343         VM_VarString(prog, 0, src, sizeof(src));
5344
5345         for(p = src, q = dest; *p; ) // no need to check size, because unescape can't expand
5346         {
5347                 if(*p == '%')
5348                 {
5349                         if(p[1] >= '0' && p[1] <= '9')
5350                                 hi = p[1] - '0';
5351                         else if(p[1] >= 'a' && p[1] <= 'f')
5352                                 hi = p[1] - 'a' + 10;
5353                         else if(p[1] >= 'A' && p[1] <= 'F')
5354                                 hi = p[1] - 'A' + 10;
5355                         else
5356                                 goto nohex;
5357                         if(p[2] >= '0' && p[2] <= '9')
5358                                 lo = p[2] - '0';
5359                         else if(p[2] >= 'a' && p[2] <= 'f')
5360                                 lo = p[2] - 'a' + 10;
5361                         else if(p[2] >= 'A' && p[2] <= 'F')
5362                                 lo = p[2] - 'A' + 10;
5363                         else
5364                                 goto nohex;
5365                         if(hi != 0 || lo != 0) // don't unescape NUL bytes
5366                                 *q++ = (char) (hi * 0x10 + lo);
5367                         p += 3;
5368                         continue;
5369                 }
5370
5371 nohex:
5372                 // otherwise:
5373                 *q++ = *p++;
5374         }
5375         *q = '\0';
5376
5377         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, dest, q - dest);
5378 }
5379
5380 // #502 string(string filename) whichpack (DP_QC_WHICHPACK)
5381 // returns the name of the pack containing a file, or "" if it is not in any pack (but local or non-existant)
5382 void VM_whichpack (prvm_prog_t *prog)
5383 {
5384         const char *fn, *pack;
5385
5386         VM_SAFEPARMCOUNT(1, VM_whichpack);
5387         fn = PRVM_G_STRING(OFS_PARM0);
5388         pack = FS_WhichPack(fn);
5389
5390         PRVM_G_INT(OFS_RETURN) = pack ? PRVM_SetTempString(prog, pack, strlen(pack)) : 0;
5391 }
5392
5393 typedef struct
5394 {
5395         prvm_prog_t *prog;
5396         double starttime;
5397         float id;
5398         char buffer[MAX_INPUTLINE];
5399         char posttype[128];
5400         unsigned char *postdata; // free when uri_to_prog_t is freed
5401         size_t postlen;
5402         char *sigdata; // free when uri_to_prog_t is freed
5403         size_t siglen;
5404 }
5405 uri_to_prog_t;
5406
5407 static void uri_to_string_callback(int status, size_t length_received, unsigned char *buffer, void *cbdata)
5408 {
5409         prvm_prog_t *prog;
5410         uri_to_prog_t *handle = (uri_to_prog_t *) cbdata;
5411
5412         prog = handle->prog;
5413         if(!prog->loaded)
5414         {
5415                 // curl reply came too late... so just drop it
5416                 if(handle->postdata)
5417                         Z_Free(handle->postdata);
5418                 if(handle->sigdata)
5419                         Z_Free(handle->sigdata);
5420                 Z_Free(handle);
5421                 return;
5422         }
5423
5424         if((prog->starttime == handle->starttime) && (PRVM_allfunction(URI_Get_Callback)))
5425         {
5426                 if(length_received >= sizeof(handle->buffer))
5427                         length_received = sizeof(handle->buffer) - 1;
5428                 handle->buffer[length_received] = '\0';
5429
5430                 PRVM_G_FLOAT(OFS_PARM0) = handle->id;
5431                 PRVM_G_FLOAT(OFS_PARM1) = status;
5432                 PRVM_G_INT(OFS_PARM2) = PRVM_SetTempString(prog, handle->buffer, length_received);
5433                 prog->ExecuteProgram(prog, PRVM_allfunction(URI_Get_Callback), "QC function URI_Get_Callback is missing");
5434         }
5435
5436         if(handle->postdata)
5437                 Z_Free(handle->postdata);
5438         if(handle->sigdata)
5439                 Z_Free(handle->sigdata);
5440         Z_Free(handle);
5441 }
5442
5443 // uri_get() gets content from an URL and calls a callback "uri_get_callback" with it set as string; an unique ID of the transfer is returned
5444 // returns 1 on success, and then calls the callback with the ID, 0 or the HTTP status code, and the received data in a string
5445 void VM_uri_get (prvm_prog_t *prog)
5446 {
5447         const char *url;
5448         float id;
5449         qbool ret;
5450         uri_to_prog_t *handle;
5451         const char *posttype = NULL;
5452         const char *postseparator = NULL;
5453         int poststringbuffer = -1;
5454         int postkeyid = -1;
5455         const char *query_string = NULL;
5456         size_t lq;
5457
5458         if(!PRVM_allfunction(URI_Get_Callback))
5459                 prog->error_cmd("uri_get called by %s without URI_Get_Callback defined", prog->name);
5460
5461         VM_SAFEPARMCOUNTRANGE(2, 6, VM_uri_get);
5462
5463         url = PRVM_G_STRING(OFS_PARM0);
5464         id = PRVM_G_FLOAT(OFS_PARM1);
5465         if(prog->argc >= 3)
5466                 posttype = PRVM_G_STRING(OFS_PARM2);
5467         if(prog->argc >= 4)
5468                 postseparator = PRVM_G_STRING(OFS_PARM3);
5469         if(prog->argc >= 5)
5470                 poststringbuffer = PRVM_G_FLOAT(OFS_PARM4);
5471         if(prog->argc >= 6)
5472                 postkeyid = PRVM_G_FLOAT(OFS_PARM5);
5473         handle = (uri_to_prog_t *) Z_Malloc(sizeof(*handle)); // this can't be the prog's mem pool, as curl may call the callback later!
5474
5475         query_string = strchr(url, '?');
5476         if(query_string)
5477                 ++query_string;
5478         lq = query_string ? strlen(query_string) : 0;
5479
5480         handle->prog = prog;
5481         handle->starttime = prog->starttime;
5482         handle->id = id;
5483         if(postseparator && posttype && *posttype)
5484         {
5485                 size_t l = strlen(postseparator);
5486                 if(poststringbuffer >= 0)
5487                 {
5488                         size_t ltotal;
5489                         int i;
5490                         // "implode"
5491                         prvm_stringbuffer_t *stringbuffer;
5492                         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, poststringbuffer);
5493                         if(!stringbuffer)
5494                         {
5495                                 VM_Warning(prog, "uri_get: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
5496                                 return;
5497                         }
5498                         ltotal = 0;
5499                         for(i = 0;i < stringbuffer->num_strings;i++)
5500                         {
5501                                 if(i > 0)
5502                                         ltotal += l;
5503                                 if(stringbuffer->strings[i])
5504                                         ltotal += strlen(stringbuffer->strings[i]);
5505                         }
5506                         handle->postdata = (unsigned char *)Z_Malloc(ltotal + 1 + lq);
5507                         handle->postlen = ltotal;
5508                         ltotal = 0;
5509                         for(i = 0;i < stringbuffer->num_strings;i++)
5510                         {
5511                                 if(i > 0)
5512                                 {
5513                                         memcpy(handle->postdata + ltotal, postseparator, l);
5514                                         ltotal += l;
5515                                 }
5516                                 if(stringbuffer->strings[i])
5517                                 {
5518                                         memcpy(handle->postdata + ltotal, stringbuffer->strings[i], strlen(stringbuffer->strings[i]));
5519                                         ltotal += strlen(stringbuffer->strings[i]);
5520                                 }
5521                         }
5522                         if(ltotal != handle->postlen)
5523                                 prog->error_cmd("%s: string buffer content size mismatch, possible overrun", prog->name);
5524                 }
5525                 else
5526                 {
5527                         handle->postdata = (unsigned char *)Z_Malloc(l + 1 + lq);
5528                         handle->postlen = l;
5529                         memcpy(handle->postdata, postseparator, l);
5530                 }
5531                 handle->postdata[handle->postlen] = 0;
5532                 if(query_string)
5533                         memcpy(handle->postdata + handle->postlen + 1, query_string, lq);
5534                 if(postkeyid >= 0)
5535                 {
5536                         // POST: we sign postdata \0 query string
5537                         size_t ll;
5538                         handle->sigdata = (char *)Z_Malloc(8192);
5539                         dp_strlcpy(handle->sigdata, "X-D0-Blind-ID-Detached-Signature: ", 8192);
5540                         l = strlen(handle->sigdata);
5541                         handle->siglen = Crypto_SignDataDetached(handle->postdata, handle->postlen + 1 + lq, postkeyid, handle->sigdata + l, 8192 - l);
5542                         if(!handle->siglen)
5543                         {
5544                                 Z_Free(handle->sigdata);
5545                                 handle->sigdata = NULL;
5546                                 goto out1;
5547                         }
5548                         ll = base64_encode((unsigned char *) (handle->sigdata + l), handle->siglen, 8192 - l - 1);
5549                         if(!ll)
5550                         {
5551                                 Z_Free(handle->sigdata);
5552                                 handle->sigdata = NULL;
5553                                 goto out1;
5554                         }
5555                         handle->siglen = l + ll;
5556                         handle->sigdata[handle->siglen] = 0;
5557                 }
5558 out1:
5559                 dp_strlcpy(handle->posttype, posttype, sizeof(handle->posttype));
5560                 ret = Curl_Begin_ToMemory_POST(url, handle->sigdata, 0, handle->posttype, handle->postdata, handle->postlen, (unsigned char *) handle->buffer, sizeof(handle->buffer), uri_to_string_callback, handle);
5561         }
5562         else
5563         {
5564                 if(postkeyid >= 0 && query_string)
5565                 {
5566                         // GET: we sign JUST the query string
5567                         size_t l, ll;
5568                         handle->sigdata = (char *)Z_Malloc(8192);
5569                         dp_strlcpy(handle->sigdata, "X-D0-Blind-ID-Detached-Signature: ", 8192);
5570                         l = strlen(handle->sigdata);
5571                         handle->siglen = Crypto_SignDataDetached(query_string, lq, postkeyid, handle->sigdata + l, 8192 - l);
5572                         if(!handle->siglen)
5573                         {
5574                                 Z_Free(handle->sigdata);
5575                                 handle->sigdata = NULL;
5576                                 goto out2;
5577                         }
5578                         ll = base64_encode((unsigned char *) (handle->sigdata + l), handle->siglen, 8192 - l - 1);
5579                         if(!ll)
5580                         {
5581                                 Z_Free(handle->sigdata);
5582                                 handle->sigdata = NULL;
5583                                 goto out2;
5584                         }
5585                         handle->siglen = l + ll;
5586                         handle->sigdata[handle->siglen] = 0;
5587                 }
5588 out2:
5589                 handle->postdata = NULL;
5590                 handle->postlen = 0;
5591                 ret = Curl_Begin_ToMemory_POST(url, handle->sigdata, 0, NULL, NULL, 0, (unsigned char *) handle->buffer, sizeof(handle->buffer), uri_to_string_callback, handle);
5592         }
5593         if(ret)
5594         {
5595                 PRVM_G_INT(OFS_RETURN) = 1;
5596         }
5597         else
5598         {
5599                 if(handle->postdata)
5600                         Z_Free(handle->postdata);
5601                 if(handle->sigdata)
5602                         Z_Free(handle->sigdata);
5603                 Z_Free(handle);
5604                 PRVM_G_INT(OFS_RETURN) = 0;
5605         }
5606 }
5607
5608 void VM_netaddress_resolve (prvm_prog_t *prog)
5609 {
5610         const char *ip;
5611         char normalized[128];
5612         size_t normalized_len;
5613         int port;
5614         lhnetaddress_t addr;
5615
5616         VM_SAFEPARMCOUNTRANGE(1, 2, VM_netaddress_resolve);
5617
5618         ip = PRVM_G_STRING(OFS_PARM0);
5619         port = 0;
5620         if(prog->argc > 1)
5621                 port = (int) PRVM_G_FLOAT(OFS_PARM1);
5622
5623         if(LHNETADDRESS_FromString(&addr, ip, port) && (normalized_len = LHNETADDRESS_ToString(&addr, normalized, sizeof(normalized), prog->argc > 1)))
5624                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, normalized, normalized_len);
5625         else
5626                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
5627 }
5628
5629 //string(prvm_prog_t *prog) getextresponse = #624; // returns the next extResponse packet that was sent to this client
5630 void VM_CL_getextresponse (prvm_prog_t *prog)
5631 {
5632         VM_SAFEPARMCOUNT(0,VM_argv);
5633
5634         if (cl_net_extresponse_count <= 0)
5635                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
5636         else
5637         {
5638                 int first;
5639                 --cl_net_extresponse_count;
5640                 first = (cl_net_extresponse_last + NET_EXTRESPONSE_MAX - cl_net_extresponse_count) % NET_EXTRESPONSE_MAX;
5641                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, cl_net_extresponse[first], strlen(cl_net_extresponse[first]));
5642         }
5643 }
5644
5645 void VM_SV_getextresponse (prvm_prog_t *prog)
5646 {
5647         VM_SAFEPARMCOUNT(0,VM_argv);
5648
5649         if (sv_net_extresponse_count <= 0)
5650                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
5651         else
5652         {
5653                 int first;
5654                 --sv_net_extresponse_count;
5655                 first = (sv_net_extresponse_last + NET_EXTRESPONSE_MAX - sv_net_extresponse_count) % NET_EXTRESPONSE_MAX;
5656                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, sv_net_extresponse[first], strlen(sv_net_extresponse[first]));
5657         }
5658 }
5659
5660 // DP_QC_NUDGEOUTOFSOLID
5661 // float(entity ent) nudgeoutofsolid = #567;
5662 void VM_nudgeoutofsolid(prvm_prog_t *prog)
5663 {
5664         prvm_edict_t *ent;
5665
5666         VM_SAFEPARMCOUNTRANGE(1, 1, VM_nudgeoutofsolid);
5667
5668         ent = PRVM_G_EDICT(OFS_PARM0);
5669         if (ent == prog->edicts)
5670         {
5671                 VM_Warning(prog, "nudgeoutofsolid: can not modify world entity\n");
5672                 PRVM_G_FLOAT(OFS_RETURN) = 0;
5673                 return;
5674         }
5675         if (ent->free)
5676         {
5677                 VM_Warning(prog, "nudgeoutofsolid: can not modify free entity\n");
5678                 PRVM_G_FLOAT(OFS_RETURN) = 0;
5679                 return;
5680         }
5681
5682         PRVM_G_FLOAT(OFS_RETURN) = PHYS_NudgeOutOfSolid(prog, ent);
5683
5684         if (PRVM_G_FLOAT(OFS_RETURN) > 0)
5685         {
5686                 if (prog == SVVM_prog)
5687                         SV_LinkEdict(ent);
5688                 else if (prog == CLVM_prog)
5689                         CL_LinkEdict(ent);
5690                 else
5691                         Sys_Error("PHYS_NudgeOutOfSolid: cannot be called from %s VM\n", prog->name);
5692         }
5693 }
5694
5695 /*
5696 =========
5697 Common functions between menu.dat and clsprogs
5698 =========
5699 */
5700
5701 //#349 float() isdemo 
5702 void VM_CL_isdemo (prvm_prog_t *prog)
5703 {
5704         VM_SAFEPARMCOUNT(0, VM_CL_isdemo);
5705         PRVM_G_FLOAT(OFS_RETURN) = cls.demoplayback;
5706 }
5707
5708 //#355 float() videoplaying 
5709 void VM_CL_videoplaying (prvm_prog_t *prog)
5710 {
5711         VM_SAFEPARMCOUNT(0, VM_CL_videoplaying);
5712         PRVM_G_FLOAT(OFS_RETURN) = cl_videoplaying;
5713 }
5714
5715 /*
5716 =========
5717 VM_M_callfunction
5718
5719         callfunction(...,string function_name)
5720 Extension: pass
5721 =========
5722 */
5723 void VM_callfunction(prvm_prog_t *prog)
5724 {
5725         mfunction_t *func;
5726         const char *s;
5727
5728         VM_SAFEPARMCOUNTRANGE(1, 8, VM_callfunction);
5729
5730         s = PRVM_G_STRING(OFS_PARM0+(prog->argc - 1)*3);
5731
5732         VM_CheckEmptyString(prog, s);
5733
5734         func = PRVM_ED_FindFunction(prog, s);
5735
5736         if(!func)
5737                 prog->error_cmd("VM_callfunction: function %s not found !", s);
5738         else if (func->first_statement < 0)
5739         {
5740                 // negative statements are built in functions
5741                 int builtinnumber = -func->first_statement;
5742                 prog->xfunction->builtinsprofile++;
5743                 if (builtinnumber < prog->numbuiltins && prog->builtins[builtinnumber])
5744                         prog->builtins[builtinnumber](prog);
5745                 else
5746                         prog->error_cmd("No such builtin #%i in %s; most likely cause: outdated engine build. Try updating!", builtinnumber, prog->name);
5747         }
5748         else if(func - prog->functions > 0)
5749         {
5750                 prog->argc--;
5751                 prog->ExecuteProgram(prog, func - prog->functions,"");
5752                 prog->argc++;
5753         }
5754 }
5755
5756 /*
5757 =========
5758 VM_isfunction
5759
5760 float   isfunction(string function_name)
5761 =========
5762 */
5763 void VM_isfunction(prvm_prog_t *prog)
5764 {
5765         mfunction_t *func;
5766         const char *s;
5767
5768         VM_SAFEPARMCOUNT(1, VM_isfunction);
5769
5770         s = PRVM_G_STRING(OFS_PARM0);
5771
5772         VM_CheckEmptyString(prog, s);
5773
5774         func = PRVM_ED_FindFunction(prog, s);
5775
5776         if(!func)
5777                 PRVM_G_FLOAT(OFS_RETURN) = false;
5778         else
5779                 PRVM_G_FLOAT(OFS_RETURN) = true;
5780 }
5781
5782 /*
5783 =========
5784 VM_sprintf
5785
5786 string sprintf(string format, ...)
5787 =========
5788 */
5789
5790 void VM_sprintf(prvm_prog_t *prog)
5791 {
5792         const char *s, *s0;
5793         char outbuf[MAX_INPUTLINE];
5794         char *o = outbuf, *end = outbuf + sizeof(outbuf), *err;
5795         const char *p;
5796         int argpos = 1;
5797         int width, precision, thisarg, flags;
5798         char formatbuf[16];
5799         char *f;
5800         int isfloat;
5801         static prvm_int_t dummyivec[3] = {0, 0, 0};
5802         static prvm_vec_t dummyvec[3] = {0, 0, 0};
5803         char vabuf[1024];
5804
5805 #define PRINTF_ALTERNATE 1
5806 #define PRINTF_ZEROPAD 2
5807 #define PRINTF_LEFT 4
5808 #define PRINTF_SPACEPOSITIVE 8
5809 #define PRINTF_SIGNPOSITIVE 16
5810
5811         formatbuf[0] = '%';
5812
5813         s = PRVM_G_STRING(OFS_PARM0);
5814
5815 #define GETARG_FLOAT(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_FLOAT(OFS_PARM0 + 3 * (a))) : 0)
5816 #define GETARG_VECTOR(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_VECTOR(OFS_PARM0 + 3 * (a))) : dummyvec)
5817 #define GETARG_INT(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_INT(OFS_PARM0 + 3 * (a))) : 0)
5818 #define GETARG_INTVECTOR(a) (((a)>=1 && (a)<prog->argc) ? ((prvm_int_t*) PRVM_G_VECTOR(OFS_PARM0 + 3 * (a))) : dummyivec)
5819 #define GETARG_STRING(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_STRING(OFS_PARM0 + 3 * (a))) : "")
5820
5821         for(;;)
5822         {
5823                 s0 = s;
5824                 switch(*s)
5825                 {
5826                         case 0:
5827                                 goto finished;
5828                         case '%':
5829                                 ++s;
5830
5831                                 if(*s == '%')
5832                                         goto verbatim;
5833
5834                                 // complete directive format:
5835                                 // %3$*1$.*2$ld
5836                                 
5837                                 width = -1;
5838                                 precision = -1;
5839                                 thisarg = -1;
5840                                 flags = 0;
5841                                 isfloat = -1;
5842
5843                                 // is number following?
5844                                 if(*s >= '0' && *s <= '9')
5845                                 {
5846                                         width = strtol(s, &err, 10);
5847                                         if(!err)
5848                                         {
5849                                                 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
5850                                                 goto finished;
5851                                         }
5852                                         if(*err == '$')
5853                                         {
5854                                                 thisarg = width;
5855                                                 width = -1;
5856                                                 s = err + 1;
5857                                         }
5858                                         else
5859                                         {
5860                                                 if(*s == '0')
5861                                                 {
5862                                                         flags |= PRINTF_ZEROPAD;
5863                                                         if(width == 0)
5864                                                                 width = -1; // it was just a flag
5865                                                 }
5866                                                 s = err;
5867                                         }
5868                                 }
5869
5870                                 if(width < 0)
5871                                 {
5872                                         for(;;)
5873                                         {
5874                                                 switch(*s)
5875                                                 {
5876                                                         case '#': flags |= PRINTF_ALTERNATE; break;
5877                                                         case '0': flags |= PRINTF_ZEROPAD; break;
5878                                                         case '-': flags |= PRINTF_LEFT; break;
5879                                                         case ' ': flags |= PRINTF_SPACEPOSITIVE; break;
5880                                                         case '+': flags |= PRINTF_SIGNPOSITIVE; break;
5881                                                         default:
5882                                                                 goto noflags;
5883                                                 }
5884                                                 ++s;
5885                                         }
5886 noflags:
5887                                         if(*s == '*')
5888                                         {
5889                                                 ++s;
5890                                                 if(*s >= '0' && *s <= '9')
5891                                                 {
5892                                                         width = strtol(s, &err, 10);
5893                                                         if(!err || *err != '$')
5894                                                         {
5895                                                                 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
5896                                                                 goto finished;
5897                                                         }
5898                                                         s = err + 1;
5899                                                 }
5900                                                 else
5901                                                         width = argpos++;
5902                                                 width = GETARG_FLOAT(width);
5903                                                 if(width < 0)
5904                                                 {
5905                                                         flags |= PRINTF_LEFT;
5906                                                         width = -width;
5907                                                 }
5908                                         }
5909                                         else if(*s >= '0' && *s <= '9')
5910                                         {
5911                                                 width = strtol(s, &err, 10);
5912                                                 if(!err)
5913                                                 {
5914                                                         VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
5915                                                         goto finished;
5916                                                 }
5917                                                 s = err;
5918                                                 if(width < 0)
5919                                                 {
5920                                                         flags |= PRINTF_LEFT;
5921                                                         width = -width;
5922                                                 }
5923                                         }
5924                                         // otherwise width stays -1
5925                                 }
5926
5927                                 if(*s == '.')
5928                                 {
5929                                         ++s;
5930                                         if(*s == '*')
5931                                         {
5932                                                 ++s;
5933                                                 if(*s >= '0' && *s <= '9')
5934                                                 {
5935                                                         precision = strtol(s, &err, 10);
5936                                                         if(!err || *err != '$')
5937                                                         {
5938                                                                 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
5939                                                                 goto finished;
5940                                                         }
5941                                                         s = err + 1;
5942                                                 }
5943                                                 else
5944                                                         precision = argpos++;
5945                                                 precision = GETARG_FLOAT(precision);
5946                                         }
5947                                         else if(*s >= '0' && *s <= '9')
5948                                         {
5949                                                 precision = strtol(s, &err, 10);
5950                                                 if(!err)
5951                                                 {
5952                                                         VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
5953                                                         goto finished;
5954                                                 }
5955                                                 s = err;
5956                                         }
5957                                         else
5958                                         {
5959                                                 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
5960                                                 goto finished;
5961                                         }
5962                                 }
5963
5964                                 for(;;)
5965                                 {
5966                                         switch(*s)
5967                                         {
5968                                                 case 'h': isfloat = 1; break;
5969                                                 case 'l': isfloat = 0; break;
5970                                                 case 'L': isfloat = 0; break;
5971                                                 case 'j': break;
5972                                                 case 'z': break;
5973                                                 case 't': break;
5974                                                 default:
5975                                                         goto nolength;
5976                                         }
5977                                         ++s;
5978                                 }
5979 nolength:
5980
5981                                 // now s points to the final directive char and is no longer changed
5982                                 if(isfloat < 0)
5983                                 {
5984                                         if(*s == 'i')
5985                                                 isfloat = 0;
5986                                         else
5987                                                 isfloat = 1;
5988                                 }
5989
5990                                 if(thisarg < 0)
5991                                         thisarg = argpos++;
5992
5993                                 if(o < end - 1)
5994                                 {
5995                                         f = &formatbuf[1];
5996                                         if(*s != 's' && *s != 'c')
5997                                                 if(flags & PRINTF_ALTERNATE) *f++ = '#';
5998                                         if(flags & PRINTF_ZEROPAD) *f++ = '0';
5999                                         if(flags & PRINTF_LEFT) *f++ = '-';
6000                                         if(flags & PRINTF_SPACEPOSITIVE) *f++ = ' ';
6001                                         if(flags & PRINTF_SIGNPOSITIVE) *f++ = '+';
6002                                         *f++ = '*';
6003                                         if(precision >= 0)
6004                                         {
6005                                                 *f++ = '.';
6006                                                 *f++ = '*';
6007                                         }
6008                                         if(*s == 'd' || *s == 'i' || *s == 'o' || *s == 'u' || *s == 'x' || *s == 'X')
6009                                         {
6010                                                 // make it use a good integer type
6011                                                 for(p = INT_LOSSLESS_FORMAT_SIZE; *p; )
6012                                                         *f++ = *p++;
6013                                         }
6014                                         *f++ = *s;
6015                                         *f++ = 0;
6016
6017                                         if(width < 0) // not set
6018                                                 width = 0;
6019
6020                                         switch(*s)
6021                                         {
6022                                                 case 'd': case 'i':
6023                                                         if(precision < 0) // not set
6024                                                                 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? INT_LOSSLESS_FORMAT_CONVERT_S(GETARG_FLOAT(thisarg)) : INT_LOSSLESS_FORMAT_CONVERT_S(GETARG_INT(thisarg))));
6025                                                         else
6026                                                                 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? INT_LOSSLESS_FORMAT_CONVERT_S(GETARG_FLOAT(thisarg)) : INT_LOSSLESS_FORMAT_CONVERT_S(GETARG_INT(thisarg))));
6027                                                         break;
6028                                                 case 'o': case 'u': case 'x': case 'X':
6029                                                         if(precision < 0) // not set
6030                                                                 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? INT_LOSSLESS_FORMAT_CONVERT_U(GETARG_FLOAT(thisarg)) : INT_LOSSLESS_FORMAT_CONVERT_U(GETARG_INT(thisarg))));
6031                                                         else
6032                                                                 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? INT_LOSSLESS_FORMAT_CONVERT_U(GETARG_FLOAT(thisarg)) : INT_LOSSLESS_FORMAT_CONVERT_U(GETARG_INT(thisarg))));
6033                                                         break;
6034                                                 case 'e': case 'E': case 'f': case 'F': case 'g': case 'G':
6035                                                         if(precision < 0) // not set
6036                                                                 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? (double) GETARG_FLOAT(thisarg) : (double) GETARG_INT(thisarg)));
6037                                                         else
6038                                                                 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? (double) GETARG_FLOAT(thisarg) : (double) GETARG_INT(thisarg)));
6039                                                         break;
6040                                                 case 'v': case 'V':
6041                                                         f[-2] += 'g' - 'v';
6042                                                         if(precision < 0) // not set
6043                                                                 o += dpsnprintf(o, end - o, va(vabuf, sizeof(vabuf), "%s %s %s", /* NESTED SPRINTF IS NESTED */ formatbuf, formatbuf, formatbuf),
6044                                                                         width, (isfloat ? (double) GETARG_VECTOR(thisarg)[0] : (double) GETARG_INTVECTOR(thisarg)[0]),
6045                                                                         width, (isfloat ? (double) GETARG_VECTOR(thisarg)[1] : (double) GETARG_INTVECTOR(thisarg)[1]),
6046                                                                         width, (isfloat ? (double) GETARG_VECTOR(thisarg)[2] : (double) GETARG_INTVECTOR(thisarg)[2])
6047                                                                 );
6048                                                         else
6049                                                                 o += dpsnprintf(o, end - o, va(vabuf, sizeof(vabuf), "%s %s %s", /* NESTED SPRINTF IS NESTED */ formatbuf, formatbuf, formatbuf),
6050                                                                         width, precision, (isfloat ? (double) GETARG_VECTOR(thisarg)[0] : (double) GETARG_INTVECTOR(thisarg)[0]),
6051                                                                         width, precision, (isfloat ? (double) GETARG_VECTOR(thisarg)[1] : (double) GETARG_INTVECTOR(thisarg)[1]),
6052                                                                         width, precision, (isfloat ? (double) GETARG_VECTOR(thisarg)[2] : (double) GETARG_INTVECTOR(thisarg)[2])
6053                                                                 );
6054                                                         break;
6055                                                 case 'c':
6056                                                         if(flags & PRINTF_ALTERNATE)
6057                                                         {
6058                                                                 if(precision < 0) // not set
6059                                                                         o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg)));
6060                                                                 else
6061                                                                         o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg)));
6062                                                         }
6063                                                         else
6064                                                         {
6065                                                                 unsigned int c = (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg));
6066                                                                 char charbuf16[16];
6067                                                                 const char *buf = u8_encodech(c, NULL, charbuf16);
6068                                                                 if(!buf)
6069                                                                         buf = "";
6070                                                                 if(precision < 0) // not set
6071                                                                         precision = end - o - 1;
6072                                                                 o += u8_strpad(o, end - o, buf, (flags & PRINTF_LEFT) != 0, width, precision);
6073                                                         }
6074                                                         break;
6075                                                 //spike FIXME -- 'S' for quoted tokenize-safe-or-print escaping of strings so stuff can safely survive console commands.
6076                                                 case 's':
6077                                                         if(flags & PRINTF_ALTERNATE)
6078                                                         {
6079                                                                 if(precision < 0) // not set
6080                                                                         o += dpsnprintf(o, end - o, formatbuf, width, GETARG_STRING(thisarg));
6081                                                                 else
6082                                                                         o += dpsnprintf(o, end - o, formatbuf, width, precision, GETARG_STRING(thisarg));
6083                                                         }
6084                                                         else
6085                                                         {
6086                                                                 if(precision < 0) // not set
6087                                                                         precision = end - o - 1;
6088                                                                 if(flags & PRINTF_SIGNPOSITIVE)
6089                                                                         o += u8_strpad(o, end - o, GETARG_STRING(thisarg), (flags & PRINTF_LEFT) != 0, width, precision);
6090                                                                 else
6091                                                                         o += u8_strpad_colorcodes(o, end - o, GETARG_STRING(thisarg), (flags & PRINTF_LEFT) != 0, width, precision);
6092                                                         }
6093                                                         break;
6094                                                 default:
6095                                                         VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
6096                                                         goto finished;
6097                                         }
6098                                 }
6099                                 ++s;
6100                                 break;
6101                         default:
6102 verbatim:
6103                                 if(o < end - 1)
6104                                         *o++ = *s;
6105                                 ++s;
6106                                 break;
6107                 }
6108         }
6109
6110 finished:
6111         *o = '\0';
6112         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outbuf, o - outbuf);
6113 }
6114
6115
6116 // surface querying
6117
6118 static model_t *getmodel(prvm_prog_t *prog, prvm_edict_t *ed)
6119 {
6120         if (prog == SVVM_prog)
6121                 return SV_GetModelFromEdict(ed);
6122         else if (prog == CLVM_prog)
6123                 return CL_GetModelFromEdict(ed);
6124         else
6125                 return NULL;
6126 }
6127
6128 struct animatemodel_cache
6129 {
6130         model_t *model;
6131         frameblend_t frameblend[MAX_FRAMEBLENDS];
6132         skeleton_t *skeleton_p;
6133         skeleton_t skeleton;
6134         float *data_vertex3f;
6135         float *data_svector3f;
6136         float *data_tvector3f;
6137         float *data_normal3f;
6138         int max_vertices;
6139         float *buf_vertex3f;
6140         float *buf_svector3f;
6141         float *buf_tvector3f;
6142         float *buf_normal3f;
6143 };
6144
6145 static void animatemodel_reset(prvm_prog_t *prog)
6146 {
6147         if (!prog->animatemodel_cache)
6148                 return;
6149         if(prog->animatemodel_cache->buf_vertex3f) Mem_Free(prog->animatemodel_cache->buf_vertex3f);
6150         if(prog->animatemodel_cache->buf_svector3f) Mem_Free(prog->animatemodel_cache->buf_svector3f);
6151         if(prog->animatemodel_cache->buf_tvector3f) Mem_Free(prog->animatemodel_cache->buf_tvector3f);
6152         if(prog->animatemodel_cache->buf_normal3f) Mem_Free(prog->animatemodel_cache->buf_normal3f);
6153         Mem_Free(prog->animatemodel_cache);
6154 }
6155
6156 static void animatemodel(prvm_prog_t *prog, model_t *model, prvm_edict_t *ed)
6157 {
6158         skeleton_t *skeleton;
6159         int skeletonindex = -1;
6160         qbool need = false;
6161         struct animatemodel_cache *animatemodel_cache;
6162         if (!prog->animatemodel_cache)
6163         {
6164                 prog->animatemodel_cache = (struct animatemodel_cache *)Mem_Alloc(prog->progs_mempool, sizeof(struct animatemodel_cache));
6165                 memset(prog->animatemodel_cache, 0, sizeof(struct animatemodel_cache));
6166         }
6167         animatemodel_cache = prog->animatemodel_cache;
6168         if(!(model->surfmesh.isanimated && model->AnimateVertices))
6169         {
6170                 animatemodel_cache->data_vertex3f = model->surfmesh.data_vertex3f;
6171                 animatemodel_cache->data_svector3f = model->surfmesh.data_svector3f;
6172                 animatemodel_cache->data_tvector3f = model->surfmesh.data_tvector3f;
6173                 animatemodel_cache->data_normal3f = model->surfmesh.data_normal3f;
6174                 return;
6175         }
6176         need |= (animatemodel_cache->model != model);
6177         VM_GenerateFrameGroupBlend(prog, ed->priv.server->framegroupblend, ed);
6178         VM_FrameBlendFromFrameGroupBlend(ed->priv.server->frameblend, ed->priv.server->framegroupblend, model, PRVM_serverglobalfloat(time));
6179         need |= (memcmp(&animatemodel_cache->frameblend, &ed->priv.server->frameblend, sizeof(ed->priv.server->frameblend))) != 0;
6180         skeletonindex = (int)PRVM_gameedictfloat(ed, skeletonindex) - 1;
6181         if (!(skeletonindex >= 0 && skeletonindex < MAX_EDICTS && (skeleton = prog->skeletons[skeletonindex]) && skeleton->model->num_bones == ed->priv.server->skeleton.model->num_bones))
6182                 skeleton = NULL;
6183         need |= (animatemodel_cache->skeleton_p != skeleton);
6184         if(skeleton)
6185                 need |= (memcmp(&animatemodel_cache->skeleton, skeleton, sizeof(ed->priv.server->skeleton))) != 0;
6186         if(!need)
6187                 return;
6188         if(model->surfmesh.num_vertices > animatemodel_cache->max_vertices)
6189         {
6190                 animatemodel_cache->max_vertices = model->surfmesh.num_vertices * 2;
6191                 if(animatemodel_cache->buf_vertex3f) Mem_Free(animatemodel_cache->buf_vertex3f);
6192                 if(animatemodel_cache->buf_svector3f) Mem_Free(animatemodel_cache->buf_svector3f);
6193                 if(animatemodel_cache->buf_tvector3f) Mem_Free(animatemodel_cache->buf_tvector3f);
6194                 if(animatemodel_cache->buf_normal3f) Mem_Free(animatemodel_cache->buf_normal3f);
6195                 animatemodel_cache->buf_vertex3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache->max_vertices);
6196                 animatemodel_cache->buf_svector3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache->max_vertices);
6197                 animatemodel_cache->buf_tvector3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache->max_vertices);
6198                 animatemodel_cache->buf_normal3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache->max_vertices);
6199         }
6200         animatemodel_cache->data_vertex3f = animatemodel_cache->buf_vertex3f;
6201         animatemodel_cache->data_svector3f = animatemodel_cache->buf_svector3f;
6202         animatemodel_cache->data_tvector3f = animatemodel_cache->buf_tvector3f;
6203         animatemodel_cache->data_normal3f = animatemodel_cache->buf_normal3f;
6204         VM_UpdateEdictSkeleton(prog, ed, model, ed->priv.server->frameblend);
6205         model->AnimateVertices(model, ed->priv.server->frameblend, &ed->priv.server->skeleton, animatemodel_cache->data_vertex3f, animatemodel_cache->data_normal3f, animatemodel_cache->data_svector3f, animatemodel_cache->data_tvector3f);
6206         animatemodel_cache->model = model;
6207         memcpy(&animatemodel_cache->frameblend, &ed->priv.server->frameblend, sizeof(ed->priv.server->frameblend));
6208         animatemodel_cache->skeleton_p = skeleton;
6209         if(skeleton)
6210                 memcpy(&animatemodel_cache->skeleton, skeleton, sizeof(ed->priv.server->skeleton));
6211 }
6212
6213 static void getmatrix(prvm_prog_t *prog, prvm_edict_t *ed, matrix4x4_t *out)
6214 {
6215         if (prog == SVVM_prog)
6216                 SV_GetEntityMatrix(prog, ed, out, false);
6217         else if (prog == CLVM_prog)
6218                 CL_GetEntityMatrix(prog, ed, out, false);
6219         else
6220                 *out = identitymatrix;
6221 }
6222
6223 static void applytransform_forward(prvm_prog_t *prog, const vec3_t in, prvm_edict_t *ed, vec3_t out)
6224 {
6225         matrix4x4_t m;
6226         getmatrix(prog, ed, &m);
6227         Matrix4x4_Transform(&m, in, out);
6228 }
6229
6230 static void applytransform_forward_direction(prvm_prog_t *prog, const vec3_t in, prvm_edict_t *ed, vec3_t out)
6231 {
6232         matrix4x4_t m;
6233         getmatrix(prog, ed, &m);
6234         Matrix4x4_Transform3x3(&m, in, out);
6235 }
6236
6237 static void applytransform_inverted(prvm_prog_t *prog, const vec3_t in, prvm_edict_t *ed, vec3_t out)
6238 {
6239         matrix4x4_t m, n;
6240         getmatrix(prog, ed, &m);
6241         Matrix4x4_Invert_Full(&n, &m);
6242         Matrix4x4_Transform3x3(&n, in, out);
6243 }
6244
6245 static void applytransform_forward_normal(prvm_prog_t *prog, const vec3_t in, prvm_edict_t *ed, vec3_t out)
6246 {
6247         matrix4x4_t m;
6248         float p[4];
6249         getmatrix(prog, ed, &m);
6250         Matrix4x4_TransformPositivePlane(&m, in[0], in[1], in[2], 0, p);
6251         VectorCopy(p, out);
6252 }
6253
6254 static void clippointtosurface(prvm_prog_t *prog, prvm_edict_t *ed, model_t *model, msurface_t *surface, vec3_t p, vec3_t out)
6255 {
6256         int i, j, k;
6257         float *v[3], facenormal[3], edgenormal[3], sidenormal[3], temp[3], offsetdist, dist, bestdist;
6258         const int *e;
6259         animatemodel(prog, model, ed);
6260         bestdist = 1000000000;
6261         VectorCopy(p, out);
6262         for (i = 0, e = (model->surfmesh.data_element3i + 3 * surface->num_firsttriangle);i < surface->num_triangles;i++, e += 3)
6263         {
6264                 // clip original point to each triangle of the surface and find the
6265                 // triangle that is closest
6266                 v[0] = prog->animatemodel_cache->data_vertex3f + e[0] * 3;
6267                 v[1] = prog->animatemodel_cache->data_vertex3f + e[1] * 3;
6268                 v[2] = prog->animatemodel_cache->data_vertex3f + e[2] * 3;
6269                 TriangleNormal(v[0], v[1], v[2], facenormal);
6270                 VectorNormalize(facenormal);
6271                 offsetdist = DotProduct(v[0], facenormal) - DotProduct(p, facenormal);
6272                 VectorMA(p, offsetdist, facenormal, temp);
6273                 for (j = 0, k = 2;j < 3;k = j, j++)
6274                 {
6275                         VectorSubtract(v[k], v[j], edgenormal);
6276                         CrossProduct(edgenormal, facenormal, sidenormal);
6277                         VectorNormalize(sidenormal);
6278                         offsetdist = DotProduct(v[k], sidenormal) - DotProduct(temp, sidenormal);
6279                         if (offsetdist < 0)
6280                                 VectorMA(temp, offsetdist, sidenormal, temp);
6281                 }
6282                 dist = VectorDistance2(temp, p);
6283                 if (bestdist > dist)
6284                 {
6285                         bestdist = dist;
6286                         VectorCopy(temp, out);
6287                 }
6288         }
6289 }
6290
6291 static msurface_t *getsurface(model_t *model, int surfacenum)
6292 {
6293         if (surfacenum < 0 || surfacenum >= model->submodelsurfaces_end - model->submodelsurfaces_start)
6294                 return NULL;
6295         return model->data_surfaces + surfacenum + model->submodelsurfaces_start;
6296 }
6297
6298
6299 //PF_getsurfacenumpoints, // #434 float(entity e, float s) getsurfacenumpoints = #434;
6300 void VM_getsurfacenumpoints(prvm_prog_t *prog)
6301 {
6302         model_t *model;
6303         msurface_t *surface;
6304         VM_SAFEPARMCOUNT(2, VM_getsurfacenumpoints);
6305         // return 0 if no such surface
6306         if (!(model = getmodel(prog, PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6307         {
6308                 PRVM_G_FLOAT(OFS_RETURN) = 0;
6309                 return;
6310         }
6311
6312         // note: this (incorrectly) assumes it is a simple polygon
6313         PRVM_G_FLOAT(OFS_RETURN) = surface->num_vertices;
6314 }
6315 //PF_getsurfacepoint,     // #435 vector(entity e, float s, float n) getsurfacepoint = #435;
6316 void VM_getsurfacepoint(prvm_prog_t *prog)
6317 {
6318         prvm_edict_t *ed;
6319         model_t *model;
6320         msurface_t *surface;
6321         int pointnum;
6322         vec3_t result;
6323         VM_SAFEPARMCOUNT(3, VM_getsurfacepoint);
6324         VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6325         ed = PRVM_G_EDICT(OFS_PARM0);
6326         if (!(model = getmodel(prog, ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6327                 return;
6328         // note: this (incorrectly) assumes it is a simple polygon
6329         pointnum = (int)PRVM_G_FLOAT(OFS_PARM2);
6330         if (pointnum < 0 || pointnum >= surface->num_vertices)
6331                 return;
6332         animatemodel(prog, model, ed);
6333         applytransform_forward(prog, &(prog->animatemodel_cache->data_vertex3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, result);
6334         VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6335 }
6336 //PF_getsurfacepointattribute,     // #486 vector(entity e, float s, float n, float a) getsurfacepointattribute = #486;
6337 // float SPA_POSITION = 0;
6338 // float SPA_S_AXIS = 1;
6339 // float SPA_T_AXIS = 2;
6340 // float SPA_R_AXIS = 3; // same as SPA_NORMAL
6341 // float SPA_TEXCOORDS0 = 4;
6342 // float SPA_LIGHTMAP0_TEXCOORDS = 5;
6343 // float SPA_LIGHTMAP0_COLOR = 6;
6344 void VM_getsurfacepointattribute(prvm_prog_t *prog)
6345 {
6346         prvm_edict_t *ed;
6347         model_t *model;
6348         msurface_t *surface;
6349         int pointnum;
6350         int attributetype;
6351         vec3_t result;
6352
6353         VM_SAFEPARMCOUNT(4, VM_getsurfacepointattribute);
6354         VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6355         ed = PRVM_G_EDICT(OFS_PARM0);
6356         if (!(model = getmodel(prog, ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6357                 return;
6358         pointnum = (int)PRVM_G_FLOAT(OFS_PARM2);
6359         if (pointnum < 0 || pointnum >= surface->num_vertices)
6360                 return;
6361         attributetype = (int) PRVM_G_FLOAT(OFS_PARM3);
6362
6363         animatemodel(prog, model, ed);
6364
6365         switch( attributetype ) {
6366                 // float SPA_POSITION = 0;
6367                 case 0:
6368                         applytransform_forward(prog, &(prog->animatemodel_cache->data_vertex3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, result);
6369                         VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6370                         break;
6371                 // float SPA_S_AXIS = 1;
6372                 case 1:
6373                         applytransform_forward_direction(prog, &(prog->animatemodel_cache->data_svector3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, result);
6374                         VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6375                         break;
6376                 // float SPA_T_AXIS = 2;
6377                 case 2:
6378                         applytransform_forward_direction(prog, &(prog->animatemodel_cache->data_tvector3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, result);
6379                         VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6380                         break;
6381                 // float SPA_R_AXIS = 3; // same as SPA_NORMAL
6382                 case 3:
6383                         applytransform_forward_direction(prog, &(prog->animatemodel_cache->data_normal3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, result);
6384                         VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6385                         break;
6386                 // float SPA_TEXCOORDS0 = 4;
6387                 case 4: {
6388                         float *texcoord = &(model->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[pointnum * 2];
6389                         result[0] = texcoord[0];
6390                         result[1] = texcoord[1];
6391                         result[2] = 0.0f;
6392                         VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6393                         break;
6394                 }
6395                 // float SPA_LIGHTMAP0_TEXCOORDS = 5;
6396                 case 5: {
6397                         float *texcoord = &(model->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[pointnum * 2];
6398                         result[0] = texcoord[0];
6399                         result[1] = texcoord[1];
6400                         result[2] = 0.0f;
6401                         VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6402                         break;
6403                 }
6404                 // float SPA_LIGHTMAP0_COLOR = 6;
6405                 case 6:
6406                         // ignore alpha for now..
6407                         VectorCopy( &(model->surfmesh.data_lightmapcolor4f + 4 * surface->num_firstvertex)[pointnum * 4], PRVM_G_VECTOR(OFS_RETURN));
6408                         break;
6409                 default:
6410                         VectorSet( PRVM_G_VECTOR(OFS_RETURN), 0.0f, 0.0f, 0.0f );
6411                         break;
6412         }
6413 }
6414 //PF_getsurfacenormal,    // #436 vector(entity e, float s) getsurfacenormal = #436;
6415 void VM_getsurfacenormal(prvm_prog_t *prog)
6416 {
6417         model_t *model;
6418         msurface_t *surface;
6419         vec3_t normal;
6420         vec3_t result;
6421         VM_SAFEPARMCOUNT(2, VM_getsurfacenormal);
6422         VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6423         if (!(model = getmodel(prog, PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6424                 return;
6425         // note: this only returns the first triangle, so it doesn't work very
6426         // well for curved surfaces or arbitrary meshes
6427         animatemodel(prog, model, PRVM_G_EDICT(OFS_PARM0));
6428         TriangleNormal((prog->animatemodel_cache->data_vertex3f + 3 * surface->num_firstvertex), (prog->animatemodel_cache->data_vertex3f + 3 * surface->num_firstvertex) + 3, (prog->animatemodel_cache->data_vertex3f + 3 * surface->num_firstvertex) + 6, normal);
6429         applytransform_forward_normal(prog, normal, PRVM_G_EDICT(OFS_PARM0), result);
6430         VectorNormalize(result);
6431         VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6432 }
6433 //PF_getsurfacetexture,   // #437 string(entity e, float s) getsurfacetexture = #437;
6434 void VM_getsurfacetexture(prvm_prog_t *prog)
6435 {
6436         model_t *model;
6437         msurface_t *surface;
6438
6439         VM_SAFEPARMCOUNT(2, VM_getsurfacetexture);
6440         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
6441         if (!(model = getmodel(prog, PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6442                 return;
6443         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, surface->texture->name, strlen(surface->texture->name));
6444 }
6445 //PF_getsurfacenearpoint, // #438 float(entity e, vector p) getsurfacenearpoint = #438;
6446 void VM_getsurfacenearpoint(prvm_prog_t *prog)
6447 {
6448         int surfacenum, best;
6449         vec3_t clipped, p;
6450         vec_t dist, bestdist;
6451         prvm_edict_t *ed;
6452         model_t *model;
6453         msurface_t *surface;
6454         vec3_t point;
6455         VM_SAFEPARMCOUNT(2, VM_getsurfacenearpoint);
6456         PRVM_G_FLOAT(OFS_RETURN) = -1;
6457         ed = PRVM_G_EDICT(OFS_PARM0);
6458         VectorCopy(PRVM_G_VECTOR(OFS_PARM1), point);
6459
6460         if (!ed || ed->free)
6461                 return;
6462         model = getmodel(prog, ed);
6463         if (!model || !model->num_surfaces)
6464                 return;
6465
6466         animatemodel(prog, model, ed);
6467
6468         applytransform_inverted(prog, point, ed, p);
6469         best = -1;
6470         bestdist = 1000000000;
6471         for (surfacenum = model->submodelsurfaces_start;surfacenum < model->submodelsurfaces_end;surfacenum++)
6472         {
6473                 surface = model->data_surfaces + surfacenum;
6474                 // first see if the nearest point on the surface's box is closer than the previous match
6475                 clipped[0] = bound(surface->mins[0], p[0], surface->maxs[0]) - p[0];
6476                 clipped[1] = bound(surface->mins[1], p[1], surface->maxs[1]) - p[1];
6477                 clipped[2] = bound(surface->mins[2], p[2], surface->maxs[2]) - p[2];
6478                 dist = VectorLength2(clipped);
6479                 if (dist < bestdist)
6480                 {
6481                         // it is, check the nearest point on the actual geometry
6482                         clippointtosurface(prog, ed, model, surface, p, clipped);
6483                         VectorSubtract(clipped, p, clipped);
6484                         dist += VectorLength2(clipped);
6485                         if (dist < bestdist)
6486                         {
6487                                 // that's closer too, store it as the best match
6488                                 best = surfacenum - model->submodelsurfaces_start;
6489                                 bestdist = dist;
6490                         }
6491                 }
6492         }
6493         PRVM_G_FLOAT(OFS_RETURN) = best;
6494 }
6495 //PF_getsurfaceclippedpoint, // #439 vector(entity e, float s, vector p) getsurfaceclippedpoint = #439;
6496 void VM_getsurfaceclippedpoint(prvm_prog_t *prog)
6497 {
6498         prvm_edict_t *ed;
6499         model_t *model;
6500         msurface_t *surface;
6501         vec3_t p, out, inp;
6502         VM_SAFEPARMCOUNT(3, VM_getsurfaceclippedpoint);
6503         VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6504         ed = PRVM_G_EDICT(OFS_PARM0);
6505         if (!(model = getmodel(prog, ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6506                 return;
6507         animatemodel(prog, model, ed);
6508         VectorCopy(PRVM_G_VECTOR(OFS_PARM2), inp);
6509         applytransform_inverted(prog, inp, ed, p);
6510         clippointtosurface(prog, ed, model, surface, p, out);
6511         VectorAdd(out, PRVM_serveredictvector(ed, origin), PRVM_G_VECTOR(OFS_RETURN));
6512 }
6513
6514 //PF_getsurfacenumtriangles, // #??? float(entity e, float s) getsurfacenumtriangles = #???;
6515 void VM_getsurfacenumtriangles(prvm_prog_t *prog)
6516 {
6517        model_t *model;
6518        msurface_t *surface;
6519        VM_SAFEPARMCOUNT(2, VM_getsurfacenumtriangles);
6520        // return 0 if no such surface
6521        if (!(model = getmodel(prog, PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6522        {
6523                PRVM_G_FLOAT(OFS_RETURN) = 0;
6524                return;
6525        }
6526
6527        PRVM_G_FLOAT(OFS_RETURN) = surface->num_triangles;
6528 }
6529 //PF_getsurfacetriangle,     // #??? vector(entity e, float s, float n) getsurfacetriangle = #???;
6530 void VM_getsurfacetriangle(prvm_prog_t *prog)
6531 {
6532        const vec3_t d = {-1, -1, -1};
6533        prvm_edict_t *ed;
6534        model_t *model;
6535        msurface_t *surface;
6536        int trinum;
6537        VM_SAFEPARMCOUNT(3, VM_getsurfacetriangle);
6538        VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6539        ed = PRVM_G_EDICT(OFS_PARM0);
6540        if (!(model = getmodel(prog, ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6541                return;
6542        trinum = (int)PRVM_G_FLOAT(OFS_PARM2);
6543        if (trinum < 0 || trinum >= surface->num_triangles)
6544                return;
6545        // FIXME: implement rotation/scaling
6546        VectorMA(&(model->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[trinum * 3], surface->num_firstvertex, d, PRVM_G_VECTOR(OFS_RETURN));
6547 }
6548
6549 //
6550 // physics builtins
6551 //
6552
6553 #ifdef USEODE
6554 #define VM_physics_ApplyCmd(ed,f) if (!ed->priv.server->ode_body) VM_physics_newstackfunction(prog, ed, f); else World_Physics_ApplyCmd(ed, f)
6555
6556 static edict_odefunc_t *VM_physics_newstackfunction(prvm_prog_t *prog, prvm_edict_t *ed, edict_odefunc_t *f)
6557 {
6558         edict_odefunc_t *newfunc, *func;
6559
6560         newfunc = (edict_odefunc_t *)Mem_Alloc(prog->progs_mempool, sizeof(edict_odefunc_t));
6561         memcpy(newfunc, f, sizeof(edict_odefunc_t));
6562         newfunc->next = NULL;
6563         if (!ed->priv.server->ode_func)
6564                 ed->priv.server->ode_func = newfunc;
6565         else
6566         {
6567                 for (func = ed->priv.server->ode_func; func->next; func = func->next);
6568                 func->next = newfunc;
6569         }
6570         return newfunc;
6571 }
6572 #endif
6573
6574 // void(entity e, float physics_enabled) physics_enable = #;
6575 void VM_physics_enable(prvm_prog_t *prog)
6576 {
6577 #ifdef USEODE
6578         prvm_edict_t *ed;
6579         edict_odefunc_t f;
6580 #endif
6581         VM_SAFEPARMCOUNT(2, VM_physics_enable);
6582 #ifdef USEODE
6583         ed = PRVM_G_EDICT(OFS_PARM0);
6584         if (!ed)
6585         {
6586                 if (developer.integer > 0)
6587                         VM_Warning(prog, "VM_physics_enable: null entity!\n");
6588                 return;
6589         }
6590         // entity should have MOVETYPE_PHYSICS already set, this can damage memory (making leaked allocation) so warn about this even if non-developer
6591         if (PRVM_serveredictfloat(ed, movetype) != MOVETYPE_PHYSICS)
6592         {
6593                 VM_Warning(prog, "VM_physics_enable: entity is not MOVETYPE_PHYSICS!\n");
6594                 return;
6595         }
6596         f.type = PRVM_G_FLOAT(OFS_PARM1) == 0 ? ODEFUNC_DISABLE : ODEFUNC_ENABLE;
6597         VM_physics_ApplyCmd(ed, &f);
6598 #endif
6599 }
6600
6601 // void(entity e, vector force, vector relative_ofs) physics_addforce = #;
6602 void VM_physics_addforce(prvm_prog_t *prog)
6603 {
6604 #ifdef USEODE
6605         prvm_edict_t *ed;
6606         edict_odefunc_t f;
6607 #endif
6608         VM_SAFEPARMCOUNT(3, VM_physics_addforce);
6609 #ifdef USEODE
6610         ed = PRVM_G_EDICT(OFS_PARM0);
6611         if (!ed)
6612         {
6613                 if (developer.integer > 0)
6614                         VM_Warning(prog, "VM_physics_addforce: null entity!\n");
6615                 return;
6616         }
6617         // entity should have MOVETYPE_PHYSICS already set, this can damage memory (making leaked allocation) so warn about this even if non-developer
6618         if (PRVM_serveredictfloat(ed, movetype) != MOVETYPE_PHYSICS)
6619         {
6620                 VM_Warning(prog, "VM_physics_addforce: entity is not MOVETYPE_PHYSICS!\n");
6621                 return;
6622         }
6623         f.type = ODEFUNC_FORCE;
6624         VectorCopy(PRVM_G_VECTOR(OFS_PARM1), f.v1);
6625         VectorCopy(PRVM_G_VECTOR(OFS_PARM2), f.v2);
6626         VM_physics_ApplyCmd(ed, &f);
6627 #endif
6628 }
6629
6630 // void(entity e, vector torque) physics_addtorque = #;
6631 void VM_physics_addtorque(prvm_prog_t *prog)
6632 {
6633 #ifdef USEODE
6634         prvm_edict_t *ed;
6635         edict_odefunc_t f;
6636 #endif
6637         VM_SAFEPARMCOUNT(2, VM_physics_addtorque);
6638 #ifdef USEODE
6639         ed = PRVM_G_EDICT(OFS_PARM0);
6640         if (!ed)
6641         {
6642                 if (developer.integer > 0)
6643                         VM_Warning(prog, "VM_physics_addtorque: null entity!\n");
6644                 return;
6645         }
6646         // entity should have MOVETYPE_PHYSICS already set, this can damage memory (making leaked allocation) so warn about this even if non-developer
6647         if (PRVM_serveredictfloat(ed, movetype) != MOVETYPE_PHYSICS)
6648         {
6649                 VM_Warning(prog, "VM_physics_addtorque: entity is not MOVETYPE_PHYSICS!\n");
6650                 return;
6651         }
6652         f.type = ODEFUNC_TORQUE;
6653         VectorCopy(PRVM_G_VECTOR(OFS_PARM1), f.v1);
6654         VM_physics_ApplyCmd(ed, &f);
6655 #endif
6656 }
6657
6658 extern cvar_t prvm_coverage;
6659 void VM_coverage(prvm_prog_t *prog)
6660 {
6661         VM_SAFEPARMCOUNT(0, VM_coverage);
6662         if (prog->explicit_profile[prog->xstatement]++ == 0 && (prvm_coverage.integer & 2))
6663                 PRVM_ExplicitCoverageEvent(prog, prog->xfunction, prog->xstatement);
6664 }