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