framegroups: add support for group names specified as // comment
[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
21 // LordHavoc: changed this to NOT use a return statement, so that it can be used in functions that must return a value
22 void VM_Warning(prvm_prog_t *prog, const char *fmt, ...)
23 {
24         va_list argptr;
25         char msg[MAX_INPUTLINE];
26         static double recursive = -1;
27
28         va_start(argptr,fmt);
29         dpvsnprintf(msg,sizeof(msg),fmt,argptr);
30         va_end(argptr);
31
32         Con_DPrint(msg);
33
34         // TODO: either add a cvar/cmd to control the state dumping or replace some of the calls with Con_Printf [9/13/2006 Black]
35         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
36         {
37                 recursive = realtime;
38                 PRVM_PrintState(prog);
39                 recursive = -1;
40         }
41 }
42
43
44 //============================================================================
45 // Common
46
47 // TODO DONE: move vm_files and vm_fssearchlist to prvm_prog_t struct
48 // TODO: move vm_files and vm_fssearchlist back [9/13/2006 Black]
49 // TODO: (move vm_files and vm_fssearchlist to prvm_prog_t struct again) [2007-01-23 LordHavoc]
50 // TODO: will this war ever end? [2007-01-23 LordHavoc]
51
52 void VM_CheckEmptyString(prvm_prog_t *prog, const char *s)
53 {
54         if (ISWHITESPACE(s[0]))
55                 prog->error_cmd("%s: Bad string", prog->name);
56 }
57
58 void VM_GenerateFrameGroupBlend(prvm_prog_t *prog, framegroupblend_t *framegroupblend, const prvm_edict_t *ed)
59 {
60         // self.frame is the interpolation target (new frame)
61         // self.frame1time is the animation base time for the interpolation target
62         // self.frame2 is the interpolation start (previous frame)
63         // self.frame2time is the animation base time for the interpolation start
64         // self.lerpfrac is the interpolation strength for self.frame2
65         // self.lerpfrac3 is the interpolation strength for self.frame3
66         // self.lerpfrac4 is the interpolation strength for self.frame4
67         // pitch angle on a player model where the animator set up 5 sets of
68         // animations and the csqc simply lerps between sets)
69         framegroupblend[0].frame = (int) PRVM_gameedictfloat(ed, frame     );
70         framegroupblend[1].frame = (int) PRVM_gameedictfloat(ed, frame2    );
71         framegroupblend[2].frame = (int) PRVM_gameedictfloat(ed, frame3    );
72         framegroupblend[3].frame = (int) PRVM_gameedictfloat(ed, frame4    );
73         framegroupblend[0].start =       PRVM_gameedictfloat(ed, frame1time);
74         framegroupblend[1].start =       PRVM_gameedictfloat(ed, frame2time);
75         framegroupblend[2].start =       PRVM_gameedictfloat(ed, frame3time);
76         framegroupblend[3].start =       PRVM_gameedictfloat(ed, frame4time);
77         framegroupblend[1].lerp  =       PRVM_gameedictfloat(ed, lerpfrac  );
78         framegroupblend[2].lerp  =       PRVM_gameedictfloat(ed, lerpfrac3 );
79         framegroupblend[3].lerp  =       PRVM_gameedictfloat(ed, lerpfrac4 );
80         // assume that the (missing) lerpfrac1 is whatever remains after lerpfrac2+lerpfrac3+lerpfrac4 are summed
81         framegroupblend[0].lerp = 1 - framegroupblend[1].lerp - framegroupblend[2].lerp - framegroupblend[3].lerp;
82 }
83
84 // LordHavoc: quite tempting to break apart this function to reuse the
85 //            duplicated code, but I suspect it is better for performance
86 //            this way
87 void VM_FrameBlendFromFrameGroupBlend(frameblend_t *frameblend, const framegroupblend_t *framegroupblend, const dp_model_t *model)
88 {
89         int sub2, numframes, f, i, k;
90         int isfirstframegroup = true;
91         int nolerp;
92         double sublerp, lerp, d;
93         const animscene_t *scene;
94         const framegroupblend_t *g;
95         frameblend_t *blend = frameblend;
96
97         memset(blend, 0, MAX_FRAMEBLENDS * sizeof(*blend));
98
99         if (!model || !model->surfmesh.isanimated)
100         {
101                 blend[0].lerp = 1;
102                 return;
103         }
104
105         nolerp = (model->type == mod_sprite) ? !r_lerpsprites.integer : !r_lerpmodels.integer;
106         numframes = model->numframes;
107         for (k = 0, g = framegroupblend;k < MAX_FRAMEGROUPBLENDS;k++, g++)
108         {
109                 f = g->frame;
110                 if ((unsigned int)f >= (unsigned int)numframes)
111                 {
112                         Con_DPrintf("VM_FrameBlendFromFrameGroupBlend: no such frame %d in model %s\n", f, model->name);
113                         f = 0;
114                 }
115                 d = lerp = g->lerp;
116                 if (lerp <= 0)
117                         continue;
118                 if (nolerp)
119                 {
120                         if (isfirstframegroup)
121                         {
122                                 d = lerp = 1;
123                                 isfirstframegroup = false;
124                         }
125                         else
126                                 continue;
127                 }
128                 if (model->animscenes)
129                 {
130                         scene = model->animscenes + f;
131                         f = scene->firstframe;
132                         if (scene->framecount > 1)
133                         {
134                                 // this code path is only used on .zym models and torches
135                                 sublerp = scene->framerate * (cl.time - g->start);
136                                 f = (int) floor(sublerp);
137                                 sublerp -= f;
138                                 sub2 = f + 1;
139                                 if (sublerp < (1.0 / 65536.0f))
140                                         sublerp = 0;
141                                 if (sublerp > (65535.0f / 65536.0f))
142                                         sublerp = 1;
143                                 if (nolerp)
144                                         sublerp = 0;
145                                 if (scene->loop)
146                                 {
147                                         f = (f % scene->framecount);
148                                         sub2 = (sub2 % scene->framecount);
149                                 }
150                                 f = bound(0, f, (scene->framecount - 1)) + scene->firstframe;
151                                 sub2 = bound(0, sub2, (scene->framecount - 1)) + scene->firstframe;
152                                 d = sublerp * lerp;
153                                 // two framelerps produced from one animation
154                                 if (d > 0)
155                                 {
156                                         for (i = 0;i < MAX_FRAMEBLENDS;i++)
157                                         {
158                                                 if (blend[i].lerp <= 0 || blend[i].subframe == sub2)
159                                                 {
160                                                         blend[i].subframe = sub2;
161                                                         blend[i].lerp += d;
162                                                         break;
163                                                 }
164                                         }
165                                 }
166                                 d = (1 - sublerp) * lerp;
167                         }
168                 }
169                 if (d > 0)
170                 {
171                         for (i = 0;i < MAX_FRAMEBLENDS;i++)
172                         {
173                                 if (blend[i].lerp <= 0 || blend[i].subframe == f)
174                                 {
175                                         blend[i].subframe = f;
176                                         blend[i].lerp += d;
177                                         break;
178                                 }
179                         }
180                 }
181         }
182 }
183
184 void VM_UpdateEdictSkeleton(prvm_prog_t *prog, prvm_edict_t *ed, const dp_model_t *edmodel, const frameblend_t *frameblend)
185 {
186         if (ed->priv.server->skeleton.model != edmodel)
187         {
188                 VM_RemoveEdictSkeleton(prog, ed);
189                 ed->priv.server->skeleton.model = edmodel;
190         }
191         if (!ed->priv.server->skeleton.model || !ed->priv.server->skeleton.model->num_bones)
192         {
193                 if(ed->priv.server->skeleton.relativetransforms)
194                         Mem_Free(ed->priv.server->skeleton.relativetransforms);
195                 ed->priv.server->skeleton.relativetransforms = NULL;
196                 return;
197         }
198
199         {
200                 int skeletonindex = -1;
201                 skeleton_t *skeleton;
202                 skeletonindex = (int)PRVM_gameedictfloat(ed, skeletonindex) - 1;
203                 if (skeletonindex >= 0 && skeletonindex < MAX_EDICTS && (skeleton = prog->skeletons[skeletonindex]) && skeleton->model->num_bones == ed->priv.server->skeleton.model->num_bones)
204                 {
205                         // custom skeleton controlled by the game (FTE_CSQC_SKELETONOBJECTS)
206                         if (!ed->priv.server->skeleton.relativetransforms)
207                                 ed->priv.server->skeleton.relativetransforms = (matrix4x4_t *)Mem_Alloc(prog->progs_mempool, ed->priv.server->skeleton.model->num_bones * sizeof(matrix4x4_t));
208                         memcpy(ed->priv.server->skeleton.relativetransforms, skeleton->relativetransforms, ed->priv.server->skeleton.model->num_bones * sizeof(matrix4x4_t));
209                 }
210                 else
211                 {
212                         if(ed->priv.server->skeleton.relativetransforms)
213                                 Mem_Free(ed->priv.server->skeleton.relativetransforms);
214                         ed->priv.server->skeleton.relativetransforms = NULL;
215                 }
216         }
217 }
218
219 void VM_RemoveEdictSkeleton(prvm_prog_t *prog, prvm_edict_t *ed)
220 {
221         if (ed->priv.server->skeleton.relativetransforms)
222                 Mem_Free(ed->priv.server->skeleton.relativetransforms);
223         memset(&ed->priv.server->skeleton, 0, sizeof(ed->priv.server->skeleton));
224 }
225
226
227
228
229 //============================================================================
230 //BUILT-IN FUNCTIONS
231
232 void VM_VarString(prvm_prog_t *prog, int first, char *out, int outlength)
233 {
234         int i;
235         const char *s;
236         char *outend;
237
238         outend = out + outlength - 1;
239         for (i = first;i < prog->argc && out < outend;i++)
240         {
241                 s = PRVM_G_STRING((OFS_PARM0+i*3));
242                 while (out < outend && *s)
243                         *out++ = *s++;
244         }
245         *out++ = 0;
246 }
247
248 /*
249 =================
250 VM_checkextension
251
252 returns true if the extension is supported by the server
253
254 checkextension(extensionname)
255 =================
256 */
257
258 // kind of helper function
259 static qboolean checkextension(prvm_prog_t *prog, const char *name)
260 {
261         int len;
262         const char *e, *start;
263         len = (int)strlen(name);
264
265         for (e = prog->extensionstring;*e;e++)
266         {
267                 while (*e == ' ')
268                         e++;
269                 if (!*e)
270                         break;
271                 start = e;
272                 while (*e && *e != ' ')
273                         e++;
274                 if ((e - start) == len && !strncasecmp(start, name, len))
275                 {
276                         // special sheck for ODE
277                         if (!strncasecmp("DP_PHYSICS_ODE", name, 14))
278                         {
279 #ifdef USEODE
280                                 return ode_dll ? true : false;
281 #else
282                                 return false;
283 #endif
284                         }
285
286                         // special sheck for d0_blind_id
287                         if (!strcasecmp("DP_CRYPTO", name))
288                                 return Crypto_Available();
289                         if (!strcasecmp("DP_QC_DIGEST_SHA256", name))
290                                 return Crypto_Available();
291
292                         return true;
293                 }
294         }
295         return false;
296 }
297
298 void VM_checkextension(prvm_prog_t *prog)
299 {
300         VM_SAFEPARMCOUNT(1,VM_checkextension);
301
302         PRVM_G_FLOAT(OFS_RETURN) = checkextension(prog, PRVM_G_STRING(OFS_PARM0));
303 }
304
305 /*
306 =================
307 VM_error
308
309 This is a TERMINAL error, which will kill off the entire prog.
310 Dumps self.
311
312 error(value)
313 =================
314 */
315 void VM_error(prvm_prog_t *prog)
316 {
317         prvm_edict_t    *ed;
318         char string[VM_STRINGTEMP_LENGTH];
319
320         VM_VarString(prog, 0, string, sizeof(string));
321         Con_Printf("======%s ERROR in %s:\n%s\n", prog->name, PRVM_GetString(prog, prog->xfunction->s_name), string);
322         ed = PRVM_PROG_TO_EDICT(PRVM_allglobaledict(self));
323         PRVM_ED_Print(prog, ed, NULL);
324
325         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);
326 }
327
328 /*
329 =================
330 VM_objerror
331
332 Dumps out self, then an error message.  The program is aborted and self is
333 removed, but the level can continue.
334
335 objerror(value)
336 =================
337 */
338 void VM_objerror(prvm_prog_t *prog)
339 {
340         prvm_edict_t    *ed;
341         char string[VM_STRINGTEMP_LENGTH];
342
343         VM_VarString(prog, 0, string, sizeof(string));
344         Con_Printf("======OBJECT ERROR======\n"); // , prog->name, PRVM_GetString(prog->xfunction->s_name), string); // or include them? FIXME
345         ed = PRVM_PROG_TO_EDICT(PRVM_allglobaledict(self));
346         PRVM_ED_Print(prog, ed, NULL);
347         PRVM_ED_Free (prog, ed);
348         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);
349 }
350
351 /*
352 =================
353 VM_print
354
355 print to console
356
357 print(...[string])
358 =================
359 */
360 void VM_print(prvm_prog_t *prog)
361 {
362         char string[VM_STRINGTEMP_LENGTH];
363
364         VM_VarString(prog, 0, string, sizeof(string));
365         Con_Print(string);
366 }
367
368 /*
369 =================
370 VM_bprint
371
372 broadcast print to everyone on server
373
374 bprint(...[string])
375 =================
376 */
377 void VM_bprint(prvm_prog_t *prog)
378 {
379         char string[VM_STRINGTEMP_LENGTH];
380
381         if(!sv.active)
382         {
383                 VM_Warning(prog, "VM_bprint: game is not server(%s) !\n", prog->name);
384                 return;
385         }
386
387         VM_VarString(prog, 0, string, sizeof(string));
388         SV_BroadcastPrint(string);
389 }
390
391 /*
392 =================
393 VM_sprint (menu & client but only if server.active == true)
394
395 single print to a specific client
396
397 sprint(float clientnum,...[string])
398 =================
399 */
400 void VM_sprint(prvm_prog_t *prog)
401 {
402         client_t        *client;
403         int                     clientnum;
404         char string[VM_STRINGTEMP_LENGTH];
405
406         VM_SAFEPARMCOUNTRANGE(1, 8, VM_sprint);
407
408         //find client for this entity
409         clientnum = (int)PRVM_G_FLOAT(OFS_PARM0);
410         if (!sv.active  || clientnum < 0 || clientnum >= svs.maxclients || !svs.clients[clientnum].active)
411         {
412                 VM_Warning(prog, "VM_sprint: %s: invalid client or server is not active !\n", prog->name);
413                 return;
414         }
415
416         client = svs.clients + clientnum;
417         if (!client->netconnection)
418                 return;
419
420         VM_VarString(prog, 1, string, sizeof(string));
421         MSG_WriteChar(&client->netconnection->message,svc_print);
422         MSG_WriteString(&client->netconnection->message, string);
423 }
424
425 /*
426 =================
427 VM_centerprint
428
429 single print to the screen
430
431 centerprint(value)
432 =================
433 */
434 void VM_centerprint(prvm_prog_t *prog)
435 {
436         char string[VM_STRINGTEMP_LENGTH];
437
438         VM_SAFEPARMCOUNTRANGE(1, 8, VM_centerprint);
439         VM_VarString(prog, 0, string, sizeof(string));
440         SCR_CenterPrint(string);
441 }
442
443 /*
444 =================
445 VM_normalize
446
447 vector normalize(vector)
448 =================
449 */
450 void VM_normalize(prvm_prog_t *prog)
451 {
452         float   *value1;
453         vec3_t  newvalue;
454         double  f;
455
456         VM_SAFEPARMCOUNT(1,VM_normalize);
457
458         value1 = PRVM_G_VECTOR(OFS_PARM0);
459
460         f = VectorLength2(value1);
461         if (f)
462         {
463                 f = 1.0 / sqrt(f);
464                 VectorScale(value1, f, newvalue);
465         }
466         else
467                 VectorClear(newvalue);
468
469         VectorCopy (newvalue, PRVM_G_VECTOR(OFS_RETURN));
470 }
471
472 /*
473 =================
474 VM_vlen
475
476 scalar vlen(vector)
477 =================
478 */
479 void VM_vlen(prvm_prog_t *prog)
480 {
481         VM_SAFEPARMCOUNT(1,VM_vlen);
482         PRVM_G_FLOAT(OFS_RETURN) = VectorLength(PRVM_G_VECTOR(OFS_PARM0));
483 }
484
485 /*
486 =================
487 VM_vectoyaw
488
489 float vectoyaw(vector)
490 =================
491 */
492 void VM_vectoyaw(prvm_prog_t *prog)
493 {
494         float   *value1;
495         float   yaw;
496
497         VM_SAFEPARMCOUNT(1,VM_vectoyaw);
498
499         value1 = PRVM_G_VECTOR(OFS_PARM0);
500
501         if (value1[1] == 0 && value1[0] == 0)
502                 yaw = 0;
503         else
504         {
505                 yaw = (int) (atan2(value1[1], value1[0]) * 180 / M_PI);
506                 if (yaw < 0)
507                         yaw += 360;
508         }
509
510         PRVM_G_FLOAT(OFS_RETURN) = yaw;
511 }
512
513
514 /*
515 =================
516 VM_vectoangles
517
518 vector vectoangles(vector[, vector])
519 =================
520 */
521 void VM_vectoangles(prvm_prog_t *prog)
522 {
523         VM_SAFEPARMCOUNTRANGE(1, 2,VM_vectoangles);
524
525         AnglesFromVectors(PRVM_G_VECTOR(OFS_RETURN), PRVM_G_VECTOR(OFS_PARM0), prog->argc >= 2 ? PRVM_G_VECTOR(OFS_PARM1) : NULL, true);
526 }
527
528 /*
529 =================
530 VM_random
531
532 Returns a number from 0<= num < 1
533
534 float random()
535 =================
536 */
537 void VM_random(prvm_prog_t *prog)
538 {
539         VM_SAFEPARMCOUNT(0,VM_random);
540
541         PRVM_G_FLOAT(OFS_RETURN) = lhrandom(0, 1);
542 }
543
544 /*
545 =========
546 VM_localsound
547
548 localsound(string sample)
549 =========
550 */
551 void VM_localsound(prvm_prog_t *prog)
552 {
553         const char *s;
554
555         VM_SAFEPARMCOUNT(1,VM_localsound);
556
557         s = PRVM_G_STRING(OFS_PARM0);
558
559         if(!S_LocalSound (s))
560         {
561                 PRVM_G_FLOAT(OFS_RETURN) = -4;
562                 VM_Warning(prog, "VM_localsound: Failed to play %s for %s !\n", s, prog->name);
563                 return;
564         }
565
566         PRVM_G_FLOAT(OFS_RETURN) = 1;
567 }
568
569 /*
570 =================
571 VM_break
572
573 break()
574 =================
575 */
576 void VM_break(prvm_prog_t *prog)
577 {
578         prog->error_cmd("%s: break statement", prog->name);
579 }
580
581 //============================================================================
582
583 /*
584 =================
585 VM_localcmd
586
587 Sends text over to the client's execution buffer
588
589 [localcmd (string, ...) or]
590 cmd (string, ...)
591 =================
592 */
593 void VM_localcmd(prvm_prog_t *prog)
594 {
595         char string[VM_STRINGTEMP_LENGTH];
596         VM_SAFEPARMCOUNTRANGE(1, 8, VM_localcmd);
597         VM_VarString(prog, 0, string, sizeof(string));
598         Cbuf_AddText(string);
599 }
600
601 static qboolean PRVM_Cvar_ReadOk(const char *string)
602 {
603         cvar_t *cvar;
604         cvar = Cvar_FindVar(string);
605         return ((cvar) && ((cvar->flags & CVAR_PRIVATE) == 0));
606 }
607
608 /*
609 =================
610 VM_cvar
611
612 float cvar (string)
613 =================
614 */
615 void VM_cvar(prvm_prog_t *prog)
616 {
617         char string[VM_STRINGTEMP_LENGTH];
618         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar);
619         VM_VarString(prog, 0, string, sizeof(string));
620         VM_CheckEmptyString(prog, string);
621         PRVM_G_FLOAT(OFS_RETURN) = PRVM_Cvar_ReadOk(string) ? Cvar_VariableValue(string) : 0;
622 }
623
624 /*
625 =================
626 VM_cvar
627
628 float cvar_type (string)
629 float CVAR_TYPEFLAG_EXISTS = 1;
630 float CVAR_TYPEFLAG_SAVED = 2;
631 float CVAR_TYPEFLAG_PRIVATE = 4;
632 float CVAR_TYPEFLAG_ENGINE = 8;
633 float CVAR_TYPEFLAG_HASDESCRIPTION = 16;
634 float CVAR_TYPEFLAG_READONLY = 32;
635 =================
636 */
637 void VM_cvar_type(prvm_prog_t *prog)
638 {
639         char string[VM_STRINGTEMP_LENGTH];
640         cvar_t *cvar;
641         int ret;
642
643         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar);
644         VM_VarString(prog, 0, string, sizeof(string));
645         VM_CheckEmptyString(prog, string);
646         cvar = Cvar_FindVar(string);
647
648
649         if(!cvar)
650         {
651                 PRVM_G_FLOAT(OFS_RETURN) = 0;
652                 return; // CVAR_TYPE_NONE
653         }
654
655         ret = 1; // CVAR_EXISTS
656         if(cvar->flags & CVAR_SAVE)
657                 ret |= 2; // CVAR_TYPE_SAVED
658         if(cvar->flags & CVAR_PRIVATE)
659                 ret |= 4; // CVAR_TYPE_PRIVATE
660         if(!(cvar->flags & CVAR_ALLOCATED))
661                 ret |= 8; // CVAR_TYPE_ENGINE
662         if(cvar->description != cvar_dummy_description)
663                 ret |= 16; // CVAR_TYPE_HASDESCRIPTION
664         if(cvar->flags & CVAR_READONLY)
665                 ret |= 32; // CVAR_TYPE_READONLY
666         
667         PRVM_G_FLOAT(OFS_RETURN) = ret;
668 }
669
670 /*
671 =================
672 VM_cvar_string
673
674 const string    VM_cvar_string (string, ...)
675 =================
676 */
677 void VM_cvar_string(prvm_prog_t *prog)
678 {
679         char string[VM_STRINGTEMP_LENGTH];
680         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_string);
681         VM_VarString(prog, 0, string, sizeof(string));
682         VM_CheckEmptyString(prog, string);
683         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, PRVM_Cvar_ReadOk(string) ? Cvar_VariableString(string) : "");
684 }
685
686
687 /*
688 ========================
689 VM_cvar_defstring
690
691 const string    VM_cvar_defstring (string, ...)
692 ========================
693 */
694 void VM_cvar_defstring(prvm_prog_t *prog)
695 {
696         char string[VM_STRINGTEMP_LENGTH];
697         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_defstring);
698         VM_VarString(prog, 0, string, sizeof(string));
699         VM_CheckEmptyString(prog, string);
700         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, Cvar_VariableDefString(string));
701 }
702
703 /*
704 ========================
705 VM_cvar_defstring
706
707 const string    VM_cvar_description (string, ...)
708 ========================
709 */
710 void VM_cvar_description(prvm_prog_t *prog)
711 {
712         char string[VM_STRINGTEMP_LENGTH];
713         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_description);
714         VM_VarString(prog, 0, string, sizeof(string));
715         VM_CheckEmptyString(prog, string);
716         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, Cvar_VariableDescription(string));
717 }
718 /*
719 =================
720 VM_cvar_set
721
722 void cvar_set (string,string, ...)
723 =================
724 */
725 void VM_cvar_set(prvm_prog_t *prog)
726 {
727         const char *name;
728         char string[VM_STRINGTEMP_LENGTH];
729         VM_SAFEPARMCOUNTRANGE(2,8,VM_cvar_set);
730         VM_VarString(prog, 1, string, sizeof(string));
731         name = PRVM_G_STRING(OFS_PARM0);
732         VM_CheckEmptyString(prog, name);
733         Cvar_Set(name, string);
734 }
735
736 /*
737 =========
738 VM_dprint
739
740 dprint(...[string])
741 =========
742 */
743 void VM_dprint(prvm_prog_t *prog)
744 {
745         char string[VM_STRINGTEMP_LENGTH];
746         VM_SAFEPARMCOUNTRANGE(1, 8, VM_dprint);
747         VM_VarString(prog, 0, string, sizeof(string));
748 #if 1
749         Con_DPrintf("%s", string);
750 #else
751         Con_DPrintf("%s: %s", prog->name, string);
752 #endif
753 }
754
755 /*
756 =========
757 VM_ftos
758
759 string  ftos(float)
760 =========
761 */
762
763 void VM_ftos(prvm_prog_t *prog)
764 {
765         float v;
766         char s[128];
767
768         VM_SAFEPARMCOUNT(1, VM_ftos);
769
770         v = PRVM_G_FLOAT(OFS_PARM0);
771
772         if ((float)((int)v) == v)
773                 dpsnprintf(s, sizeof(s), "%i", (int)v);
774         else
775                 dpsnprintf(s, sizeof(s), "%f", v);
776         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s);
777 }
778
779 /*
780 =========
781 VM_fabs
782
783 float   fabs(float)
784 =========
785 */
786
787 void VM_fabs(prvm_prog_t *prog)
788 {
789         float   v;
790
791         VM_SAFEPARMCOUNT(1,VM_fabs);
792
793         v = PRVM_G_FLOAT(OFS_PARM0);
794         PRVM_G_FLOAT(OFS_RETURN) = fabs(v);
795 }
796
797 /*
798 =========
799 VM_vtos
800
801 string  vtos(vector)
802 =========
803 */
804
805 void VM_vtos(prvm_prog_t *prog)
806 {
807         char s[512];
808
809         VM_SAFEPARMCOUNT(1,VM_vtos);
810
811         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]);
812         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s);
813 }
814
815 /*
816 =========
817 VM_etos
818
819 string  etos(entity)
820 =========
821 */
822
823 void VM_etos(prvm_prog_t *prog)
824 {
825         char s[128];
826
827         VM_SAFEPARMCOUNT(1, VM_etos);
828
829         dpsnprintf (s, sizeof(s), "entity %i", PRVM_G_EDICTNUM(OFS_PARM0));
830         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s);
831 }
832
833 /*
834 =========
835 VM_stof
836
837 float stof(...[string])
838 =========
839 */
840 void VM_stof(prvm_prog_t *prog)
841 {
842         char string[VM_STRINGTEMP_LENGTH];
843         VM_SAFEPARMCOUNTRANGE(1, 8, VM_stof);
844         VM_VarString(prog, 0, string, sizeof(string));
845         PRVM_G_FLOAT(OFS_RETURN) = atof(string);
846 }
847
848 /*
849 ========================
850 VM_itof
851
852 float itof(intt ent)
853 ========================
854 */
855 void VM_itof(prvm_prog_t *prog)
856 {
857         VM_SAFEPARMCOUNT(1, VM_itof);
858         PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
859 }
860
861 /*
862 ========================
863 VM_ftoe
864
865 entity ftoe(float num)
866 ========================
867 */
868 void VM_ftoe(prvm_prog_t *prog)
869 {
870         int ent;
871         VM_SAFEPARMCOUNT(1, VM_ftoe);
872
873         ent = (int)PRVM_G_FLOAT(OFS_PARM0);
874         if (ent < 0 || ent >= prog->max_edicts || PRVM_PROG_TO_EDICT(ent)->priv.required->free)
875                 ent = 0; // return world instead of a free or invalid entity
876
877         PRVM_G_INT(OFS_RETURN) = ent;
878 }
879
880 /*
881 ========================
882 VM_etof
883
884 float etof(entity ent)
885 ========================
886 */
887 void VM_etof(prvm_prog_t *prog)
888 {
889         VM_SAFEPARMCOUNT(1, VM_etof);
890         PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_EDICTNUM(OFS_PARM0);
891 }
892
893 /*
894 =========
895 VM_strftime
896
897 string strftime(float uselocaltime, string[, string ...])
898 =========
899 */
900 void VM_strftime(prvm_prog_t *prog)
901 {
902         time_t t;
903 #if _MSC_VER >= 1400
904         struct tm tm;
905         int tmresult;
906 #else
907         struct tm *tm;
908 #endif
909         char fmt[VM_STRINGTEMP_LENGTH];
910         char result[VM_STRINGTEMP_LENGTH];
911         VM_SAFEPARMCOUNTRANGE(2, 8, VM_strftime);
912         VM_VarString(prog, 1, fmt, sizeof(fmt));
913         t = time(NULL);
914 #if _MSC_VER >= 1400
915         if (PRVM_G_FLOAT(OFS_PARM0))
916                 tmresult = localtime_s(&tm, &t);
917         else
918                 tmresult = gmtime_s(&tm, &t);
919         if (!tmresult)
920 #else
921         if (PRVM_G_FLOAT(OFS_PARM0))
922                 tm = localtime(&t);
923         else
924                 tm = gmtime(&t);
925         if (!tm)
926 #endif
927         {
928                 PRVM_G_INT(OFS_RETURN) = 0;
929                 return;
930         }
931 #if _MSC_VER >= 1400
932         strftime(result, sizeof(result), fmt, &tm);
933 #else
934         strftime(result, sizeof(result), fmt, tm);
935 #endif
936         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, result);
937 }
938
939 /*
940 =========
941 VM_spawn
942
943 entity spawn()
944 =========
945 */
946
947 void VM_spawn(prvm_prog_t *prog)
948 {
949         prvm_edict_t    *ed;
950         VM_SAFEPARMCOUNT(0, VM_spawn);
951         prog->xfunction->builtinsprofile += 20;
952         ed = PRVM_ED_Alloc(prog);
953         VM_RETURN_EDICT(ed);
954 }
955
956 /*
957 =========
958 VM_remove
959
960 remove(entity e)
961 =========
962 */
963
964 void VM_remove(prvm_prog_t *prog)
965 {
966         prvm_edict_t    *ed;
967         prog->xfunction->builtinsprofile += 20;
968
969         VM_SAFEPARMCOUNT(1, VM_remove);
970
971         ed = PRVM_G_EDICT(OFS_PARM0);
972         if( PRVM_NUM_FOR_EDICT(ed) <= prog->reserved_edicts )
973         {
974                 if (developer.integer > 0)
975                         VM_Warning(prog, "VM_remove: tried to remove the null entity or a reserved entity!\n" );
976         }
977         else if( ed->priv.required->free )
978         {
979                 if (developer.integer > 0)
980                         VM_Warning(prog, "VM_remove: tried to remove an already freed entity!\n" );
981         }
982         else
983                 PRVM_ED_Free (prog, ed);
984 }
985
986 /*
987 =========
988 VM_find
989
990 entity  find(entity start, .string field, string match)
991 =========
992 */
993
994 void VM_find(prvm_prog_t *prog)
995 {
996         int             e;
997         int             f;
998         const char      *s, *t;
999         prvm_edict_t    *ed;
1000
1001         VM_SAFEPARMCOUNT(3,VM_find);
1002
1003         e = PRVM_G_EDICTNUM(OFS_PARM0);
1004         f = PRVM_G_INT(OFS_PARM1);
1005         s = PRVM_G_STRING(OFS_PARM2);
1006
1007         // LordHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
1008         // expects it to find all the monsters, so we must be careful to support
1009         // searching for ""
1010
1011         for (e++ ; e < prog->num_edicts ; e++)
1012         {
1013                 prog->xfunction->builtinsprofile++;
1014                 ed = PRVM_EDICT_NUM(e);
1015                 if (ed->priv.required->free)
1016                         continue;
1017                 t = PRVM_E_STRING(ed,f);
1018                 if (!t)
1019                         t = "";
1020                 if (!strcmp(t,s))
1021                 {
1022                         VM_RETURN_EDICT(ed);
1023                         return;
1024                 }
1025         }
1026
1027         VM_RETURN_EDICT(prog->edicts);
1028 }
1029
1030 /*
1031 =========
1032 VM_findfloat
1033
1034   entity        findfloat(entity start, .float field, float match)
1035   entity        findentity(entity start, .entity field, entity match)
1036 =========
1037 */
1038 // LordHavoc: added this for searching float, int, and entity reference fields
1039 void VM_findfloat(prvm_prog_t *prog)
1040 {
1041         int             e;
1042         int             f;
1043         float   s;
1044         prvm_edict_t    *ed;
1045
1046         VM_SAFEPARMCOUNT(3,VM_findfloat);
1047
1048         e = PRVM_G_EDICTNUM(OFS_PARM0);
1049         f = PRVM_G_INT(OFS_PARM1);
1050         s = PRVM_G_FLOAT(OFS_PARM2);
1051
1052         for (e++ ; e < prog->num_edicts ; e++)
1053         {
1054                 prog->xfunction->builtinsprofile++;
1055                 ed = PRVM_EDICT_NUM(e);
1056                 if (ed->priv.required->free)
1057                         continue;
1058                 if (PRVM_E_FLOAT(ed,f) == s)
1059                 {
1060                         VM_RETURN_EDICT(ed);
1061                         return;
1062                 }
1063         }
1064
1065         VM_RETURN_EDICT(prog->edicts);
1066 }
1067
1068 /*
1069 =========
1070 VM_findchain
1071
1072 entity  findchain(.string field, string match)
1073 =========
1074 */
1075 // chained search for strings in entity fields
1076 // entity(.string field, string match) findchain = #402;
1077 void VM_findchain(prvm_prog_t *prog)
1078 {
1079         int             i;
1080         int             f;
1081         const char      *s, *t;
1082         prvm_edict_t    *ent, *chain;
1083         int chainfield;
1084
1085         VM_SAFEPARMCOUNTRANGE(2,3,VM_findchain);
1086
1087         if(prog->argc == 3)
1088                 chainfield = PRVM_G_INT(OFS_PARM2);
1089         else
1090                 chainfield = prog->fieldoffsets.chain;
1091         if (chainfield < 0)
1092                 prog->error_cmd("VM_findchain: %s doesnt have the specified chain field !", prog->name);
1093
1094         chain = prog->edicts;
1095
1096         f = PRVM_G_INT(OFS_PARM0);
1097         s = PRVM_G_STRING(OFS_PARM1);
1098
1099         // LordHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
1100         // expects it to find all the monsters, so we must be careful to support
1101         // searching for ""
1102
1103         ent = PRVM_NEXT_EDICT(prog->edicts);
1104         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1105         {
1106                 prog->xfunction->builtinsprofile++;
1107                 if (ent->priv.required->free)
1108                         continue;
1109                 t = PRVM_E_STRING(ent,f);
1110                 if (!t)
1111                         t = "";
1112                 if (strcmp(t,s))
1113                         continue;
1114
1115                 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_NUM_FOR_EDICT(chain);
1116                 chain = ent;
1117         }
1118
1119         VM_RETURN_EDICT(chain);
1120 }
1121
1122 /*
1123 =========
1124 VM_findchainfloat
1125
1126 entity  findchainfloat(.string field, float match)
1127 entity  findchainentity(.string field, entity match)
1128 =========
1129 */
1130 // LordHavoc: chained search for float, int, and entity reference fields
1131 // entity(.string field, float match) findchainfloat = #403;
1132 void VM_findchainfloat(prvm_prog_t *prog)
1133 {
1134         int             i;
1135         int             f;
1136         float   s;
1137         prvm_edict_t    *ent, *chain;
1138         int chainfield;
1139
1140         VM_SAFEPARMCOUNTRANGE(2, 3, VM_findchainfloat);
1141
1142         if(prog->argc == 3)
1143                 chainfield = PRVM_G_INT(OFS_PARM2);
1144         else
1145                 chainfield = prog->fieldoffsets.chain;
1146         if (chainfield < 0)
1147                 prog->error_cmd("VM_findchain: %s doesnt have the specified chain field !", prog->name);
1148
1149         chain = (prvm_edict_t *)prog->edicts;
1150
1151         f = PRVM_G_INT(OFS_PARM0);
1152         s = PRVM_G_FLOAT(OFS_PARM1);
1153
1154         ent = PRVM_NEXT_EDICT(prog->edicts);
1155         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1156         {
1157                 prog->xfunction->builtinsprofile++;
1158                 if (ent->priv.required->free)
1159                         continue;
1160                 if (PRVM_E_FLOAT(ent,f) != s)
1161                         continue;
1162
1163                 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_EDICT_TO_PROG(chain);
1164                 chain = ent;
1165         }
1166
1167         VM_RETURN_EDICT(chain);
1168 }
1169
1170 /*
1171 ========================
1172 VM_findflags
1173
1174 entity  findflags(entity start, .float field, float match)
1175 ========================
1176 */
1177 // LordHavoc: search for flags in float fields
1178 void VM_findflags(prvm_prog_t *prog)
1179 {
1180         int             e;
1181         int             f;
1182         int             s;
1183         prvm_edict_t    *ed;
1184
1185         VM_SAFEPARMCOUNT(3, VM_findflags);
1186
1187
1188         e = PRVM_G_EDICTNUM(OFS_PARM0);
1189         f = PRVM_G_INT(OFS_PARM1);
1190         s = (int)PRVM_G_FLOAT(OFS_PARM2);
1191
1192         for (e++ ; e < prog->num_edicts ; e++)
1193         {
1194                 prog->xfunction->builtinsprofile++;
1195                 ed = PRVM_EDICT_NUM(e);
1196                 if (ed->priv.required->free)
1197                         continue;
1198                 if (!PRVM_E_FLOAT(ed,f))
1199                         continue;
1200                 if ((int)PRVM_E_FLOAT(ed,f) & s)
1201                 {
1202                         VM_RETURN_EDICT(ed);
1203                         return;
1204                 }
1205         }
1206
1207         VM_RETURN_EDICT(prog->edicts);
1208 }
1209
1210 /*
1211 ========================
1212 VM_findchainflags
1213
1214 entity  findchainflags(.float field, float match)
1215 ========================
1216 */
1217 // LordHavoc: chained search for flags in float fields
1218 void VM_findchainflags(prvm_prog_t *prog)
1219 {
1220         int             i;
1221         int             f;
1222         int             s;
1223         prvm_edict_t    *ent, *chain;
1224         int chainfield;
1225
1226         VM_SAFEPARMCOUNTRANGE(2, 3, VM_findchainflags);
1227
1228         if(prog->argc == 3)
1229                 chainfield = PRVM_G_INT(OFS_PARM2);
1230         else
1231                 chainfield = prog->fieldoffsets.chain;
1232         if (chainfield < 0)
1233                 prog->error_cmd("VM_findchain: %s doesnt have the specified chain field !", prog->name);
1234
1235         chain = (prvm_edict_t *)prog->edicts;
1236
1237         f = PRVM_G_INT(OFS_PARM0);
1238         s = (int)PRVM_G_FLOAT(OFS_PARM1);
1239
1240         ent = PRVM_NEXT_EDICT(prog->edicts);
1241         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1242         {
1243                 prog->xfunction->builtinsprofile++;
1244                 if (ent->priv.required->free)
1245                         continue;
1246                 if (!PRVM_E_FLOAT(ent,f))
1247                         continue;
1248                 if (!((int)PRVM_E_FLOAT(ent,f) & s))
1249                         continue;
1250
1251                 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_EDICT_TO_PROG(chain);
1252                 chain = ent;
1253         }
1254
1255         VM_RETURN_EDICT(chain);
1256 }
1257
1258 /*
1259 =========
1260 VM_precache_sound
1261
1262 string  precache_sound (string sample)
1263 =========
1264 */
1265 void VM_precache_sound(prvm_prog_t *prog)
1266 {
1267         const char *s;
1268
1269         VM_SAFEPARMCOUNT(1, VM_precache_sound);
1270
1271         s = PRVM_G_STRING(OFS_PARM0);
1272         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
1273         //VM_CheckEmptyString(prog, s);
1274
1275         if(snd_initialized.integer && !S_PrecacheSound(s, true, true))
1276         {
1277                 VM_Warning(prog, "VM_precache_sound: Failed to load %s for %s\n", s, prog->name);
1278                 return;
1279         }
1280 }
1281
1282 /*
1283 =================
1284 VM_precache_file
1285
1286 returns the same string as output
1287
1288 does nothing, only used by qcc to build .pak archives
1289 =================
1290 */
1291 void VM_precache_file(prvm_prog_t *prog)
1292 {
1293         VM_SAFEPARMCOUNT(1,VM_precache_file);
1294         // precache_file is only used to copy files with qcc, it does nothing
1295         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
1296 }
1297
1298 /*
1299 =========
1300 VM_coredump
1301
1302 coredump()
1303 =========
1304 */
1305 void VM_coredump(prvm_prog_t *prog)
1306 {
1307         VM_SAFEPARMCOUNT(0,VM_coredump);
1308
1309         Cbuf_AddText("prvm_edicts ");
1310         Cbuf_AddText(prog->name);
1311         Cbuf_AddText("\n");
1312 }
1313
1314 /*
1315 =========
1316 VM_stackdump
1317
1318 stackdump()
1319 =========
1320 */
1321 void VM_stackdump(prvm_prog_t *prog)
1322 {
1323         VM_SAFEPARMCOUNT(0, VM_stackdump);
1324
1325         PRVM_StackTrace(prog);
1326 }
1327
1328 /*
1329 =========
1330 VM_crash
1331
1332 crash()
1333 =========
1334 */
1335
1336 void VM_crash(prvm_prog_t *prog)
1337 {
1338         VM_SAFEPARMCOUNT(0, VM_crash);
1339
1340         prog->error_cmd("Crash called by %s",prog->name);
1341 }
1342
1343 /*
1344 =========
1345 VM_traceon
1346
1347 traceon()
1348 =========
1349 */
1350 void VM_traceon(prvm_prog_t *prog)
1351 {
1352         VM_SAFEPARMCOUNT(0,VM_traceon);
1353
1354         prog->trace = true;
1355 }
1356
1357 /*
1358 =========
1359 VM_traceoff
1360
1361 traceoff()
1362 =========
1363 */
1364 void VM_traceoff(prvm_prog_t *prog)
1365 {
1366         VM_SAFEPARMCOUNT(0,VM_traceoff);
1367
1368         prog->trace = false;
1369 }
1370
1371 /*
1372 =========
1373 VM_eprint
1374
1375 eprint(entity e)
1376 =========
1377 */
1378 void VM_eprint(prvm_prog_t *prog)
1379 {
1380         VM_SAFEPARMCOUNT(1,VM_eprint);
1381
1382         PRVM_ED_PrintNum (prog, PRVM_G_EDICTNUM(OFS_PARM0), NULL);
1383 }
1384
1385 /*
1386 =========
1387 VM_rint
1388
1389 float   rint(float)
1390 =========
1391 */
1392 void VM_rint(prvm_prog_t *prog)
1393 {
1394         float f;
1395         VM_SAFEPARMCOUNT(1,VM_rint);
1396
1397         f = PRVM_G_FLOAT(OFS_PARM0);
1398         if (f > 0)
1399                 PRVM_G_FLOAT(OFS_RETURN) = floor(f + 0.5);
1400         else
1401                 PRVM_G_FLOAT(OFS_RETURN) = ceil(f - 0.5);
1402 }
1403
1404 /*
1405 =========
1406 VM_floor
1407
1408 float   floor(float)
1409 =========
1410 */
1411 void VM_floor(prvm_prog_t *prog)
1412 {
1413         VM_SAFEPARMCOUNT(1,VM_floor);
1414
1415         PRVM_G_FLOAT(OFS_RETURN) = floor(PRVM_G_FLOAT(OFS_PARM0));
1416 }
1417
1418 /*
1419 =========
1420 VM_ceil
1421
1422 float   ceil(float)
1423 =========
1424 */
1425 void VM_ceil(prvm_prog_t *prog)
1426 {
1427         VM_SAFEPARMCOUNT(1,VM_ceil);
1428
1429         PRVM_G_FLOAT(OFS_RETURN) = ceil(PRVM_G_FLOAT(OFS_PARM0));
1430 }
1431
1432
1433 /*
1434 =============
1435 VM_nextent
1436
1437 entity  nextent(entity)
1438 =============
1439 */
1440 void VM_nextent(prvm_prog_t *prog)
1441 {
1442         int             i;
1443         prvm_edict_t    *ent;
1444
1445         VM_SAFEPARMCOUNT(1, VM_nextent);
1446
1447         i = PRVM_G_EDICTNUM(OFS_PARM0);
1448         while (1)
1449         {
1450                 prog->xfunction->builtinsprofile++;
1451                 i++;
1452                 if (i == prog->num_edicts)
1453                 {
1454                         VM_RETURN_EDICT(prog->edicts);
1455                         return;
1456                 }
1457                 ent = PRVM_EDICT_NUM(i);
1458                 if (!ent->priv.required->free)
1459                 {
1460                         VM_RETURN_EDICT(ent);
1461                         return;
1462                 }
1463         }
1464 }
1465
1466 //=============================================================================
1467
1468 /*
1469 ==============
1470 VM_changelevel
1471 server and menu
1472
1473 changelevel(string map)
1474 ==============
1475 */
1476 void VM_changelevel(prvm_prog_t *prog)
1477 {
1478         char vabuf[1024];
1479         VM_SAFEPARMCOUNT(1, VM_changelevel);
1480
1481         if(!sv.active)
1482         {
1483                 VM_Warning(prog, "VM_changelevel: game is not server (%s)\n", prog->name);
1484                 return;
1485         }
1486
1487 // make sure we don't issue two changelevels
1488         if (svs.changelevel_issued)
1489                 return;
1490         svs.changelevel_issued = true;
1491
1492         Cbuf_AddText(va(vabuf, sizeof(vabuf), "changelevel %s\n",PRVM_G_STRING(OFS_PARM0)));
1493 }
1494
1495 /*
1496 =========
1497 VM_sin
1498
1499 float   sin(float)
1500 =========
1501 */
1502 void VM_sin(prvm_prog_t *prog)
1503 {
1504         VM_SAFEPARMCOUNT(1,VM_sin);
1505         PRVM_G_FLOAT(OFS_RETURN) = sin(PRVM_G_FLOAT(OFS_PARM0));
1506 }
1507
1508 /*
1509 =========
1510 VM_cos
1511 float   cos(float)
1512 =========
1513 */
1514 void VM_cos(prvm_prog_t *prog)
1515 {
1516         VM_SAFEPARMCOUNT(1,VM_cos);
1517         PRVM_G_FLOAT(OFS_RETURN) = cos(PRVM_G_FLOAT(OFS_PARM0));
1518 }
1519
1520 /*
1521 =========
1522 VM_sqrt
1523
1524 float   sqrt(float)
1525 =========
1526 */
1527 void VM_sqrt(prvm_prog_t *prog)
1528 {
1529         VM_SAFEPARMCOUNT(1,VM_sqrt);
1530         PRVM_G_FLOAT(OFS_RETURN) = sqrt(PRVM_G_FLOAT(OFS_PARM0));
1531 }
1532
1533 /*
1534 =========
1535 VM_asin
1536
1537 float   asin(float)
1538 =========
1539 */
1540 void VM_asin(prvm_prog_t *prog)
1541 {
1542         VM_SAFEPARMCOUNT(1,VM_asin);
1543         PRVM_G_FLOAT(OFS_RETURN) = asin(PRVM_G_FLOAT(OFS_PARM0));
1544 }
1545
1546 /*
1547 =========
1548 VM_acos
1549 float   acos(float)
1550 =========
1551 */
1552 void VM_acos(prvm_prog_t *prog)
1553 {
1554         VM_SAFEPARMCOUNT(1,VM_acos);
1555         PRVM_G_FLOAT(OFS_RETURN) = acos(PRVM_G_FLOAT(OFS_PARM0));
1556 }
1557
1558 /*
1559 =========
1560 VM_atan
1561 float   atan(float)
1562 =========
1563 */
1564 void VM_atan(prvm_prog_t *prog)
1565 {
1566         VM_SAFEPARMCOUNT(1,VM_atan);
1567         PRVM_G_FLOAT(OFS_RETURN) = atan(PRVM_G_FLOAT(OFS_PARM0));
1568 }
1569
1570 /*
1571 =========
1572 VM_atan2
1573 float   atan2(float,float)
1574 =========
1575 */
1576 void VM_atan2(prvm_prog_t *prog)
1577 {
1578         VM_SAFEPARMCOUNT(2,VM_atan2);
1579         PRVM_G_FLOAT(OFS_RETURN) = atan2(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1580 }
1581
1582 /*
1583 =========
1584 VM_tan
1585 float   tan(float)
1586 =========
1587 */
1588 void VM_tan(prvm_prog_t *prog)
1589 {
1590         VM_SAFEPARMCOUNT(1,VM_tan);
1591         PRVM_G_FLOAT(OFS_RETURN) = tan(PRVM_G_FLOAT(OFS_PARM0));
1592 }
1593
1594 /*
1595 =================
1596 VM_randomvec
1597
1598 Returns a vector of length < 1 and > 0
1599
1600 vector randomvec()
1601 =================
1602 */
1603 void VM_randomvec(prvm_prog_t *prog)
1604 {
1605         vec3_t temp;
1606         VM_SAFEPARMCOUNT(0, VM_randomvec);
1607         VectorRandom(temp);
1608         VectorCopy(temp, PRVM_G_VECTOR(OFS_RETURN));
1609 }
1610
1611 //=============================================================================
1612
1613 /*
1614 =========
1615 VM_registercvar
1616
1617 float   registercvar (string name, string value[, float flags])
1618 =========
1619 */
1620 void VM_registercvar(prvm_prog_t *prog)
1621 {
1622         const char *name, *value;
1623         int     flags;
1624
1625         VM_SAFEPARMCOUNTRANGE(2, 3, VM_registercvar);
1626
1627         name = PRVM_G_STRING(OFS_PARM0);
1628         value = PRVM_G_STRING(OFS_PARM1);
1629         flags = prog->argc >= 3 ? (int)PRVM_G_FLOAT(OFS_PARM2) : 0;
1630         PRVM_G_FLOAT(OFS_RETURN) = 0;
1631
1632         if(flags > CVAR_MAXFLAGSVAL)
1633                 return;
1634
1635 // first check to see if it has already been defined
1636         if (Cvar_FindVar (name))
1637                 return;
1638
1639 // check for overlap with a command
1640         if (Cmd_Exists (name))
1641         {
1642                 VM_Warning(prog, "VM_registercvar: %s is a command\n", name);
1643                 return;
1644         }
1645
1646         Cvar_Get(name, value, flags, NULL);
1647
1648         PRVM_G_FLOAT(OFS_RETURN) = 1; // success
1649 }
1650
1651
1652 /*
1653 =================
1654 VM_min
1655
1656 returns the minimum of two supplied floats
1657
1658 float min(float a, float b, ...[float])
1659 =================
1660 */
1661 void VM_min(prvm_prog_t *prog)
1662 {
1663         VM_SAFEPARMCOUNTRANGE(2, 8, VM_min);
1664         // LordHavoc: 3+ argument enhancement suggested by FrikaC
1665         if (prog->argc >= 3)
1666         {
1667                 int i;
1668                 float f = PRVM_G_FLOAT(OFS_PARM0);
1669                 for (i = 1;i < prog->argc;i++)
1670                         if (f > PRVM_G_FLOAT((OFS_PARM0+i*3)))
1671                                 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1672                 PRVM_G_FLOAT(OFS_RETURN) = f;
1673         }
1674         else
1675                 PRVM_G_FLOAT(OFS_RETURN) = min(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1676 }
1677
1678 /*
1679 =================
1680 VM_max
1681
1682 returns the maximum of two supplied floats
1683
1684 float   max(float a, float b, ...[float])
1685 =================
1686 */
1687 void VM_max(prvm_prog_t *prog)
1688 {
1689         VM_SAFEPARMCOUNTRANGE(2, 8, VM_max);
1690         // LordHavoc: 3+ argument enhancement suggested by FrikaC
1691         if (prog->argc >= 3)
1692         {
1693                 int i;
1694                 float f = PRVM_G_FLOAT(OFS_PARM0);
1695                 for (i = 1;i < prog->argc;i++)
1696                         if (f < PRVM_G_FLOAT((OFS_PARM0+i*3)))
1697                                 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1698                 PRVM_G_FLOAT(OFS_RETURN) = f;
1699         }
1700         else
1701                 PRVM_G_FLOAT(OFS_RETURN) = max(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1702 }
1703
1704 /*
1705 =================
1706 VM_bound
1707
1708 returns number bounded by supplied range
1709
1710 float   bound(float min, float value, float max)
1711 =================
1712 */
1713 void VM_bound(prvm_prog_t *prog)
1714 {
1715         VM_SAFEPARMCOUNT(3,VM_bound);
1716         PRVM_G_FLOAT(OFS_RETURN) = bound(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1), PRVM_G_FLOAT(OFS_PARM2));
1717 }
1718
1719 /*
1720 =================
1721 VM_pow
1722
1723 returns a raised to power b
1724
1725 float   pow(float a, float b)
1726 =================
1727 */
1728 void VM_pow(prvm_prog_t *prog)
1729 {
1730         VM_SAFEPARMCOUNT(2,VM_pow);
1731         PRVM_G_FLOAT(OFS_RETURN) = pow(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1732 }
1733
1734 void VM_log(prvm_prog_t *prog)
1735 {
1736         VM_SAFEPARMCOUNT(1,VM_log);
1737         PRVM_G_FLOAT(OFS_RETURN) = log(PRVM_G_FLOAT(OFS_PARM0));
1738 }
1739
1740 void VM_Files_Init(prvm_prog_t *prog)
1741 {
1742         int i;
1743         for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1744                 prog->openfiles[i] = NULL;
1745 }
1746
1747 void VM_Files_CloseAll(prvm_prog_t *prog)
1748 {
1749         int i;
1750         for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1751         {
1752                 if (prog->openfiles[i])
1753                         FS_Close(prog->openfiles[i]);
1754                 prog->openfiles[i] = NULL;
1755         }
1756 }
1757
1758 static qfile_t *VM_GetFileHandle(prvm_prog_t *prog, int index)
1759 {
1760         if (index < 0 || index >= PRVM_MAX_OPENFILES)
1761         {
1762                 Con_Printf("VM_GetFileHandle: invalid file handle %i used in %s\n", index, prog->name);
1763                 return NULL;
1764         }
1765         if (prog->openfiles[index] == NULL)
1766         {
1767                 Con_Printf("VM_GetFileHandle: no such file handle %i (or file has been closed) in %s\n", index, prog->name);
1768                 return NULL;
1769         }
1770         return prog->openfiles[index];
1771 }
1772
1773 /*
1774 =========
1775 VM_fopen
1776
1777 float   fopen(string filename, float mode)
1778 =========
1779 */
1780 // float(string filename, float mode) fopen = #110;
1781 // opens a file inside quake/gamedir/data/ (mode is FILE_READ, FILE_APPEND, or FILE_WRITE),
1782 // returns fhandle >= 0 if successful, or fhandle < 0 if unable to open file for any reason
1783 void VM_fopen(prvm_prog_t *prog)
1784 {
1785         int filenum, mode;
1786         const char *modestring, *filename;
1787         char vabuf[1024];
1788
1789         VM_SAFEPARMCOUNT(2,VM_fopen);
1790
1791         for (filenum = 0;filenum < PRVM_MAX_OPENFILES;filenum++)
1792                 if (prog->openfiles[filenum] == NULL)
1793                         break;
1794         if (filenum >= PRVM_MAX_OPENFILES)
1795         {
1796                 PRVM_G_FLOAT(OFS_RETURN) = -2;
1797                 VM_Warning(prog, "VM_fopen: %s ran out of file handles (%i)\n", prog->name, PRVM_MAX_OPENFILES);
1798                 return;
1799         }
1800         filename = PRVM_G_STRING(OFS_PARM0);
1801         mode = (int)PRVM_G_FLOAT(OFS_PARM1);
1802         switch(mode)
1803         {
1804         case 0: // FILE_READ
1805                 modestring = "rb";
1806                 prog->openfiles[filenum] = FS_OpenVirtualFile(va(vabuf, sizeof(vabuf), "data/%s", filename), false);
1807                 if (prog->openfiles[filenum] == NULL)
1808                         prog->openfiles[filenum] = FS_OpenVirtualFile(va(vabuf, sizeof(vabuf), "%s", filename), false);
1809                 break;
1810         case 1: // FILE_APPEND
1811                 modestring = "a";
1812                 prog->openfiles[filenum] = FS_OpenRealFile(va(vabuf, sizeof(vabuf), "data/%s", filename), modestring, false);
1813                 break;
1814         case 2: // FILE_WRITE
1815                 modestring = "w";
1816                 prog->openfiles[filenum] = FS_OpenRealFile(va(vabuf, sizeof(vabuf), "data/%s", filename), modestring, false);
1817                 break;
1818         default:
1819                 PRVM_G_FLOAT(OFS_RETURN) = -3;
1820                 VM_Warning(prog, "VM_fopen: %s: no such mode %i (valid: 0 = read, 1 = append, 2 = write)\n", prog->name, mode);
1821                 return;
1822         }
1823
1824         if (prog->openfiles[filenum] == NULL)
1825         {
1826                 PRVM_G_FLOAT(OFS_RETURN) = -1;
1827                 if (developer_extra.integer)
1828                         VM_Warning(prog, "VM_fopen: %s: %s mode %s failed\n", prog->name, filename, modestring);
1829         }
1830         else
1831         {
1832                 PRVM_G_FLOAT(OFS_RETURN) = filenum;
1833                 if (developer_extra.integer)
1834                         Con_DPrintf("VM_fopen: %s: %s mode %s opened as #%i\n", prog->name, filename, modestring, filenum);
1835                 prog->openfiles_origin[filenum] = PRVM_AllocationOrigin(prog);
1836         }
1837 }
1838
1839 /*
1840 =========
1841 VM_fclose
1842
1843 fclose(float fhandle)
1844 =========
1845 */
1846 //void(float fhandle) fclose = #111; // closes a file
1847 void VM_fclose(prvm_prog_t *prog)
1848 {
1849         int filenum;
1850
1851         VM_SAFEPARMCOUNT(1,VM_fclose);
1852
1853         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1854         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1855         {
1856                 VM_Warning(prog, "VM_fclose: invalid file handle %i used in %s\n", filenum, prog->name);
1857                 return;
1858         }
1859         if (prog->openfiles[filenum] == NULL)
1860         {
1861                 VM_Warning(prog, "VM_fclose: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
1862                 return;
1863         }
1864         FS_Close(prog->openfiles[filenum]);
1865         prog->openfiles[filenum] = NULL;
1866         if(prog->openfiles_origin[filenum])
1867                 PRVM_Free((char *)prog->openfiles_origin[filenum]);
1868         if (developer_extra.integer)
1869                 Con_DPrintf("VM_fclose: %s: #%i closed\n", prog->name, filenum);
1870 }
1871
1872 /*
1873 =========
1874 VM_fgets
1875
1876 string  fgets(float fhandle)
1877 =========
1878 */
1879 //string(float fhandle) fgets = #112; // reads a line of text from the file and returns as a tempstring
1880 void VM_fgets(prvm_prog_t *prog)
1881 {
1882         int c, end;
1883         char string[VM_STRINGTEMP_LENGTH];
1884         int filenum;
1885
1886         VM_SAFEPARMCOUNT(1,VM_fgets);
1887
1888         // set the return value regardless of any possible errors
1889         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
1890
1891         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1892         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1893         {
1894                 VM_Warning(prog, "VM_fgets: invalid file handle %i used in %s\n", filenum, prog->name);
1895                 return;
1896         }
1897         if (prog->openfiles[filenum] == NULL)
1898         {
1899                 VM_Warning(prog, "VM_fgets: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
1900                 return;
1901         }
1902         end = 0;
1903         for (;;)
1904         {
1905                 c = FS_Getc(prog->openfiles[filenum]);
1906                 if (c == '\r' || c == '\n' || c < 0)
1907                         break;
1908                 if (end < VM_STRINGTEMP_LENGTH - 1)
1909                         string[end++] = c;
1910         }
1911         string[end] = 0;
1912         // remove \n following \r
1913         if (c == '\r')
1914         {
1915                 c = FS_Getc(prog->openfiles[filenum]);
1916                 if (c != '\n')
1917                         FS_UnGetc(prog->openfiles[filenum], (unsigned char)c);
1918         }
1919         if (developer_extra.integer)
1920                 Con_DPrintf("fgets: %s: %s\n", prog->name, string);
1921         if (c >= 0 || end)
1922                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string);
1923 }
1924
1925 /*
1926 =========
1927 VM_fputs
1928
1929 fputs(float fhandle, string s)
1930 =========
1931 */
1932 //void(float fhandle, string s) fputs = #113; // writes a line of text to the end of the file
1933 void VM_fputs(prvm_prog_t *prog)
1934 {
1935         int stringlength;
1936         char string[VM_STRINGTEMP_LENGTH];
1937         int filenum;
1938
1939         VM_SAFEPARMCOUNT(2,VM_fputs);
1940
1941         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1942         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1943         {
1944                 VM_Warning(prog, "VM_fputs: invalid file handle %i used in %s\n", filenum, prog->name);
1945                 return;
1946         }
1947         if (prog->openfiles[filenum] == NULL)
1948         {
1949                 VM_Warning(prog, "VM_fputs: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
1950                 return;
1951         }
1952         VM_VarString(prog, 1, string, sizeof(string));
1953         if ((stringlength = (int)strlen(string)))
1954                 FS_Write(prog->openfiles[filenum], string, stringlength);
1955         if (developer_extra.integer)
1956                 Con_DPrintf("fputs: %s: %s\n", prog->name, string);
1957 }
1958
1959 /*
1960 =========
1961 VM_writetofile
1962
1963         writetofile(float fhandle, entity ent)
1964 =========
1965 */
1966 void VM_writetofile(prvm_prog_t *prog)
1967 {
1968         prvm_edict_t * ent;
1969         qfile_t *file;
1970
1971         VM_SAFEPARMCOUNT(2, VM_writetofile);
1972
1973         file = VM_GetFileHandle(prog, (int)PRVM_G_FLOAT(OFS_PARM0));
1974         if( !file )
1975         {
1976                 VM_Warning(prog, "VM_writetofile: invalid or closed file handle\n");
1977                 return;
1978         }
1979
1980         ent = PRVM_G_EDICT(OFS_PARM1);
1981         if(ent->priv.required->free)
1982         {
1983                 VM_Warning(prog, "VM_writetofile: %s: entity %i is free !\n", prog->name, PRVM_NUM_FOR_EDICT(ent));
1984                 return;
1985         }
1986
1987         PRVM_ED_Write (prog, file, ent);
1988 }
1989
1990 // KrimZon - DP_QC_ENTITYDATA
1991 /*
1992 =========
1993 VM_numentityfields
1994
1995 float() numentityfields
1996 Return the number of entity fields - NOT offsets
1997 =========
1998 */
1999 void VM_numentityfields(prvm_prog_t *prog)
2000 {
2001         PRVM_G_FLOAT(OFS_RETURN) = prog->numfielddefs;
2002 }
2003
2004 // KrimZon - DP_QC_ENTITYDATA
2005 /*
2006 =========
2007 VM_entityfieldname
2008
2009 string(float fieldnum) entityfieldname
2010 Return name of the specified field as a string, or empty if the field is invalid (warning)
2011 =========
2012 */
2013 void VM_entityfieldname(prvm_prog_t *prog)
2014 {
2015         ddef_t *d;
2016         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2017         
2018         if (i < 0 || i >= prog->numfielddefs)
2019         {
2020         VM_Warning(prog, "VM_entityfieldname: %s: field index out of bounds\n", prog->name);
2021         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "");
2022                 return;
2023         }
2024         
2025         d = &prog->fielddefs[i];
2026         PRVM_G_INT(OFS_RETURN) = d->s_name; // presuming that s_name points to a string already
2027 }
2028
2029 // KrimZon - DP_QC_ENTITYDATA
2030 /*
2031 =========
2032 VM_entityfieldtype
2033
2034 float(float fieldnum) entityfieldtype
2035 =========
2036 */
2037 void VM_entityfieldtype(prvm_prog_t *prog)
2038 {
2039         ddef_t *d;
2040         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2041         
2042         if (i < 0 || i >= prog->numfielddefs)
2043         {
2044                 VM_Warning(prog, "VM_entityfieldtype: %s: field index out of bounds\n", prog->name);
2045                 PRVM_G_FLOAT(OFS_RETURN) = -1.0;
2046                 return;
2047         }
2048         
2049         d = &prog->fielddefs[i];
2050         PRVM_G_FLOAT(OFS_RETURN) = (float)d->type;
2051 }
2052
2053 // KrimZon - DP_QC_ENTITYDATA
2054 /*
2055 =========
2056 VM_getentityfieldstring
2057
2058 string(float fieldnum, entity ent) getentityfieldstring
2059 =========
2060 */
2061 void VM_getentityfieldstring(prvm_prog_t *prog)
2062 {
2063         // put the data into a string
2064         ddef_t *d;
2065         int type, j;
2066         int *v;
2067         prvm_edict_t * ent;
2068         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2069         char valuebuf[MAX_INPUTLINE];
2070         
2071         if (i < 0 || i >= prog->numfielddefs)
2072         {
2073         VM_Warning(prog, "VM_entityfielddata: %s: field index out of bounds\n", prog->name);
2074                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "");
2075                 return;
2076         }
2077         
2078         d = &prog->fielddefs[i];
2079         
2080         // get the entity
2081         ent = PRVM_G_EDICT(OFS_PARM1);
2082         if(ent->priv.required->free)
2083         {
2084                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "");
2085                 VM_Warning(prog, "VM_entityfielddata: %s: entity %i is free !\n", prog->name, PRVM_NUM_FOR_EDICT(ent));
2086                 return;
2087         }
2088         v = (int *)((char *)ent->fields.vp + d->ofs*4);
2089         
2090         // if it's 0 or blank, return an empty string
2091         type = d->type & ~DEF_SAVEGLOBAL;
2092         for (j=0 ; j<prvm_type_size[type] ; j++)
2093                 if (v[j])
2094                         break;
2095         if (j == prvm_type_size[type])
2096         {
2097                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "");
2098                 return;
2099         }
2100                 
2101         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, PRVM_UglyValueString(prog, (etype_t)d->type, (prvm_eval_t *)v, valuebuf, sizeof(valuebuf)));
2102 }
2103
2104 // KrimZon - DP_QC_ENTITYDATA
2105 /*
2106 =========
2107 VM_putentityfieldstring
2108
2109 float(float fieldnum, entity ent, string s) putentityfieldstring
2110 =========
2111 */
2112 void VM_putentityfieldstring(prvm_prog_t *prog)
2113 {
2114         ddef_t *d;
2115         prvm_edict_t * ent;
2116         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2117
2118         if (i < 0 || i >= prog->numfielddefs)
2119         {
2120         VM_Warning(prog, "VM_entityfielddata: %s: field index out of bounds\n", prog->name);
2121                 PRVM_G_FLOAT(OFS_RETURN) = 0.0f;
2122                 return;
2123         }
2124
2125         d = &prog->fielddefs[i];
2126
2127         // get the entity
2128         ent = PRVM_G_EDICT(OFS_PARM1);
2129         if(ent->priv.required->free)
2130         {
2131                 VM_Warning(prog, "VM_entityfielddata: %s: entity %i is free !\n", prog->name, PRVM_NUM_FOR_EDICT(ent));
2132                 PRVM_G_FLOAT(OFS_RETURN) = 0.0f;
2133                 return;
2134         }
2135
2136         // parse the string into the value
2137         PRVM_G_FLOAT(OFS_RETURN) = ( PRVM_ED_ParseEpair(prog, ent, d, PRVM_G_STRING(OFS_PARM2), false) ) ? 1.0f : 0.0f;
2138 }
2139
2140 /*
2141 =========
2142 VM_strlen
2143
2144 float   strlen(string s)
2145 =========
2146 */
2147 //float(string s) strlen = #114; // returns how many characters are in a string
2148 void VM_strlen(prvm_prog_t *prog)
2149 {
2150         VM_SAFEPARMCOUNT(1,VM_strlen);
2151
2152         //PRVM_G_FLOAT(OFS_RETURN) = strlen(PRVM_G_STRING(OFS_PARM0));
2153         PRVM_G_FLOAT(OFS_RETURN) = u8_strlen(PRVM_G_STRING(OFS_PARM0));
2154 }
2155
2156 // DRESK - Decolorized String
2157 /*
2158 =========
2159 VM_strdecolorize
2160
2161 string  strdecolorize(string s)
2162 =========
2163 */
2164 // string (string s) strdecolorize = #472; // returns the passed in string with color codes stripped
2165 void VM_strdecolorize(prvm_prog_t *prog)
2166 {
2167         char szNewString[VM_STRINGTEMP_LENGTH];
2168         const char *szString;
2169
2170         // Prepare Strings
2171         VM_SAFEPARMCOUNT(1,VM_strdecolorize);
2172         szString = PRVM_G_STRING(OFS_PARM0);
2173         COM_StringDecolorize(szString, 0, szNewString, sizeof(szNewString), TRUE);
2174         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString);
2175 }
2176
2177 // DRESK - String Length (not counting color codes)
2178 /*
2179 =========
2180 VM_strlennocol
2181
2182 float   strlennocol(string s)
2183 =========
2184 */
2185 // float(string s) strlennocol = #471; // returns how many characters are in a string not including color codes
2186 // For example, ^2Dresk returns a length of 5
2187 void VM_strlennocol(prvm_prog_t *prog)
2188 {
2189         const char *szString;
2190         int nCnt;
2191
2192         VM_SAFEPARMCOUNT(1,VM_strlennocol);
2193
2194         szString = PRVM_G_STRING(OFS_PARM0);
2195
2196         //nCnt = COM_StringLengthNoColors(szString, 0, NULL);
2197         nCnt = u8_COM_StringLengthNoColors(szString, 0, NULL);
2198
2199         PRVM_G_FLOAT(OFS_RETURN) = nCnt;
2200 }
2201
2202 // DRESK - String to Uppercase and Lowercase
2203 /*
2204 =========
2205 VM_strtolower
2206
2207 string  strtolower(string s)
2208 =========
2209 */
2210 // string (string s) strtolower = #480; // returns passed in string in lowercase form
2211 void VM_strtolower(prvm_prog_t *prog)
2212 {
2213         char szNewString[VM_STRINGTEMP_LENGTH];
2214         const char *szString;
2215
2216         // Prepare Strings
2217         VM_SAFEPARMCOUNT(1,VM_strtolower);
2218         szString = PRVM_G_STRING(OFS_PARM0);
2219
2220         COM_ToLowerString(szString, szNewString, sizeof(szNewString) );
2221
2222         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString);
2223 }
2224
2225 /*
2226 =========
2227 VM_strtoupper
2228
2229 string  strtoupper(string s)
2230 =========
2231 */
2232 // string (string s) strtoupper = #481; // returns passed in string in uppercase form
2233 void VM_strtoupper(prvm_prog_t *prog)
2234 {
2235         char szNewString[VM_STRINGTEMP_LENGTH];
2236         const char *szString;
2237
2238         // Prepare Strings
2239         VM_SAFEPARMCOUNT(1,VM_strtoupper);
2240         szString = PRVM_G_STRING(OFS_PARM0);
2241
2242         COM_ToUpperString(szString, szNewString, sizeof(szNewString) );
2243
2244         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString);
2245 }
2246
2247 /*
2248 =========
2249 VM_strcat
2250
2251 string strcat(string,string,...[string])
2252 =========
2253 */
2254 //string(string s1, string s2) strcat = #115;
2255 // concatenates two strings (for example "abc", "def" would return "abcdef")
2256 // and returns as a tempstring
2257 void VM_strcat(prvm_prog_t *prog)
2258 {
2259         char s[VM_STRINGTEMP_LENGTH];
2260         VM_SAFEPARMCOUNTRANGE(1, 8, VM_strcat);
2261
2262         VM_VarString(prog, 0, s, sizeof(s));
2263         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s);
2264 }
2265
2266 /*
2267 =========
2268 VM_substring
2269
2270 string  substring(string s, float start, float length)
2271 =========
2272 */
2273 // string(string s, float start, float length) substring = #116;
2274 // returns a section of a string as a tempstring
2275 void VM_substring(prvm_prog_t *prog)
2276 {
2277         int start, length;
2278         int u_slength = 0, u_start;
2279         size_t u_length;
2280         const char *s;
2281         char string[VM_STRINGTEMP_LENGTH];
2282
2283         VM_SAFEPARMCOUNT(3,VM_substring);
2284
2285         /*
2286         s = PRVM_G_STRING(OFS_PARM0);
2287         start = (int)PRVM_G_FLOAT(OFS_PARM1);
2288         length = (int)PRVM_G_FLOAT(OFS_PARM2);
2289         slength = strlen(s);
2290
2291         if (start < 0) // FTE_STRINGS feature
2292                 start += slength;
2293         start = bound(0, start, slength);
2294
2295         if (length < 0) // FTE_STRINGS feature
2296                 length += slength - start + 1;
2297         maxlen = min((int)sizeof(string) - 1, slength - start);
2298         length = bound(0, length, maxlen);
2299
2300         memcpy(string, s + start, length);
2301         string[length] = 0;
2302         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string);
2303         */
2304         
2305         s = PRVM_G_STRING(OFS_PARM0);
2306         start = (int)PRVM_G_FLOAT(OFS_PARM1);
2307         length = (int)PRVM_G_FLOAT(OFS_PARM2);
2308
2309         if (start < 0) // FTE_STRINGS feature
2310         {
2311                 u_slength = u8_strlen(s);
2312                 start += u_slength;
2313                 start = bound(0, start, u_slength);
2314         }
2315
2316         if (length < 0) // FTE_STRINGS feature
2317         {
2318                 if (!u_slength) // it's not calculated when it's not needed above
2319                         u_slength = u8_strlen(s);
2320                 length += u_slength - start + 1;
2321         }
2322                 
2323         // positive start, positive length
2324         u_start = u8_byteofs(s, start, NULL);
2325         if (u_start < 0)
2326         {
2327                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "");
2328                 return;
2329         }
2330         u_length = u8_bytelen(s + u_start, length);
2331         if (u_length >= sizeof(string)-1)
2332                 u_length = sizeof(string)-1;
2333         
2334         memcpy(string, s + u_start, u_length);
2335         string[u_length] = 0;
2336         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string);
2337 }
2338
2339 /*
2340 =========
2341 VM_strreplace
2342
2343 string(string search, string replace, string subject) strreplace = #484;
2344 =========
2345 */
2346 // replaces all occurrences of search with replace in the string subject, and returns the result
2347 void VM_strreplace(prvm_prog_t *prog)
2348 {
2349         int i, j, si;
2350         const char *search, *replace, *subject;
2351         char string[VM_STRINGTEMP_LENGTH];
2352         int search_len, replace_len, subject_len;
2353
2354         VM_SAFEPARMCOUNT(3,VM_strreplace);
2355
2356         search = PRVM_G_STRING(OFS_PARM0);
2357         replace = PRVM_G_STRING(OFS_PARM1);
2358         subject = PRVM_G_STRING(OFS_PARM2);
2359
2360         search_len = (int)strlen(search);
2361         replace_len = (int)strlen(replace);
2362         subject_len = (int)strlen(subject);
2363
2364         si = 0;
2365         for (i = 0; i <= subject_len - search_len; i++)
2366         {
2367                 for (j = 0; j < search_len; j++) // thus, i+j < subject_len
2368                         if (subject[i+j] != search[j])
2369                                 break;
2370                 if (j == search_len)
2371                 {
2372                         // NOTE: if search_len == 0, we always hit THIS case, and never the other
2373                         // found it at offset 'i'
2374                         for (j = 0; j < replace_len && si < (int)sizeof(string) - 1; j++)
2375                                 string[si++] = replace[j];
2376                         if(search_len > 0)
2377                         {
2378                                 i += search_len - 1;
2379                         }
2380                         else
2381                         {
2382                                 // the above would subtract 1 from i... so we
2383                                 // don't do that, but instead output the next
2384                                 // char
2385                                 if (si < (int)sizeof(string) - 1)
2386                                         string[si++] = subject[i];
2387                         }
2388                 }
2389                 else
2390                 {
2391                         // in THIS case, we know search_len > 0, thus i < subject_len
2392                         // not found
2393                         if (si < (int)sizeof(string) - 1)
2394                                 string[si++] = subject[i];
2395                 }
2396         }
2397         // remaining chars (these cannot match)
2398         for (; i < subject_len; i++)
2399                 if (si < (int)sizeof(string) - 1)
2400                         string[si++] = subject[i];
2401         string[si] = '\0';
2402
2403         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string);
2404 }
2405
2406 /*
2407 =========
2408 VM_strireplace
2409
2410 string(string search, string replace, string subject) strireplace = #485;
2411 =========
2412 */
2413 // case-insensitive version of strreplace
2414 void VM_strireplace(prvm_prog_t *prog)
2415 {
2416         int i, j, si;
2417         const char *search, *replace, *subject;
2418         char string[VM_STRINGTEMP_LENGTH];
2419         int search_len, replace_len, subject_len;
2420
2421         VM_SAFEPARMCOUNT(3,VM_strreplace);
2422
2423         search = PRVM_G_STRING(OFS_PARM0);
2424         replace = PRVM_G_STRING(OFS_PARM1);
2425         subject = PRVM_G_STRING(OFS_PARM2);
2426
2427         search_len = (int)strlen(search);
2428         replace_len = (int)strlen(replace);
2429         subject_len = (int)strlen(subject);
2430
2431         si = 0;
2432         for (i = 0; i <= subject_len - search_len; i++)
2433         {
2434                 for (j = 0; j < search_len; j++) // thus, i+j < subject_len
2435                         if (tolower(subject[i+j]) != tolower(search[j]))
2436                                 break;
2437                 if (j == search_len)
2438                 {
2439                         // NOTE: if search_len == 0, we always hit THIS case, and never the other
2440                         // found it at offset 'i'
2441                         for (j = 0; j < replace_len && si < (int)sizeof(string) - 1; j++)
2442                                 string[si++] = replace[j];
2443                         if(search_len > 0)
2444                         {
2445                                 i += search_len - 1;
2446                         }
2447                         else
2448                         {
2449                                 // the above would subtract 1 from i... so we
2450                                 // don't do that, but instead output the next
2451                                 // char
2452                                 if (si < (int)sizeof(string) - 1)
2453                                         string[si++] = subject[i];
2454                         }
2455                 }
2456                 else
2457                 {
2458                         // in THIS case, we know search_len > 0, thus i < subject_len
2459                         // not found
2460                         if (si < (int)sizeof(string) - 1)
2461                                 string[si++] = subject[i];
2462                 }
2463         }
2464         // remaining chars (these cannot match)
2465         for (; i < subject_len; i++)
2466                 if (si < (int)sizeof(string) - 1)
2467                         string[si++] = subject[i];
2468         string[si] = '\0';
2469
2470         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string);
2471 }
2472
2473 /*
2474 =========
2475 VM_stov
2476
2477 vector  stov(string s)
2478 =========
2479 */
2480 //vector(string s) stov = #117; // returns vector value from a string
2481 void VM_stov(prvm_prog_t *prog)
2482 {
2483         char string[VM_STRINGTEMP_LENGTH];
2484
2485         VM_SAFEPARMCOUNT(1,VM_stov);
2486
2487         VM_VarString(prog, 0, string, sizeof(string));
2488         Math_atov(string, PRVM_G_VECTOR(OFS_RETURN));
2489 }
2490
2491 /*
2492 =========
2493 VM_strzone
2494
2495 string  strzone(string s)
2496 =========
2497 */
2498 //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)
2499 void VM_strzone(prvm_prog_t *prog)
2500 {
2501         char *out;
2502         char string[VM_STRINGTEMP_LENGTH];
2503         size_t alloclen;
2504
2505         VM_SAFEPARMCOUNT(1,VM_strzone);
2506
2507         VM_VarString(prog, 0, string, sizeof(string));
2508         alloclen = strlen(string) + 1;
2509         PRVM_G_INT(OFS_RETURN) = PRVM_AllocString(prog, alloclen, &out);
2510         memcpy(out, string, alloclen);
2511 }
2512
2513 /*
2514 =========
2515 VM_strunzone
2516
2517 strunzone(string s)
2518 =========
2519 */
2520 //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!!!)
2521 void VM_strunzone(prvm_prog_t *prog)
2522 {
2523         VM_SAFEPARMCOUNT(1,VM_strunzone);
2524         PRVM_FreeString(prog, PRVM_G_INT(OFS_PARM0));
2525 }
2526
2527 /*
2528 =========
2529 VM_command (used by client and menu)
2530
2531 clientcommand(float client, string s) (for client and menu)
2532 =========
2533 */
2534 //void(entity e, string s) clientcommand = #440; // executes a command string as if it came from the specified client
2535 //this function originally written by KrimZon, made shorter by LordHavoc
2536 void VM_clcommand (prvm_prog_t *prog)
2537 {
2538         client_t *temp_client;
2539         int i;
2540
2541         VM_SAFEPARMCOUNT(2,VM_clcommand);
2542
2543         i = (int)PRVM_G_FLOAT(OFS_PARM0);
2544         if (!sv.active  || i < 0 || i >= svs.maxclients || !svs.clients[i].active)
2545         {
2546                 VM_Warning(prog, "VM_clientcommand: %s: invalid client/server is not active !\n", prog->name);
2547                 return;
2548         }
2549
2550         temp_client = host_client;
2551         host_client = svs.clients + i;
2552         Cmd_ExecuteString (PRVM_G_STRING(OFS_PARM1), src_client, true);
2553         host_client = temp_client;
2554 }
2555
2556
2557 /*
2558 =========
2559 VM_tokenize
2560
2561 float tokenize(string s)
2562 =========
2563 */
2564 //float(string s) tokenize = #441; // takes apart a string into individal words (access them with argv), returns how many
2565 //this function originally written by KrimZon, made shorter by LordHavoc
2566 //20040203: rewritten by LordHavoc (no longer uses allocations)
2567 static int num_tokens = 0;
2568 static int tokens[VM_STRINGTEMP_LENGTH / 2];
2569 static int tokens_startpos[VM_STRINGTEMP_LENGTH / 2];
2570 static int tokens_endpos[VM_STRINGTEMP_LENGTH / 2];
2571 static char tokenize_string[VM_STRINGTEMP_LENGTH];
2572 void VM_tokenize (prvm_prog_t *prog)
2573 {
2574         const char *p;
2575
2576         VM_SAFEPARMCOUNT(1,VM_tokenize);
2577
2578         strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2579         p = tokenize_string;
2580
2581         num_tokens = 0;
2582         for(;;)
2583         {
2584                 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
2585                         break;
2586
2587                 // skip whitespace here to find token start pos
2588                 while(*p && ISWHITESPACE(*p))
2589                         ++p;
2590
2591                 tokens_startpos[num_tokens] = p - tokenize_string;
2592                 if(!COM_ParseToken_VM_Tokenize(&p, false))
2593                         break;
2594                 tokens_endpos[num_tokens] = p - tokenize_string;
2595                 tokens[num_tokens] = PRVM_SetTempString(prog, com_token);
2596                 ++num_tokens;
2597         }
2598
2599         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2600 }
2601
2602 //float(string s) tokenize = #514; // takes apart a string into individal words (access them with argv), returns how many
2603 void VM_tokenize_console (prvm_prog_t *prog)
2604 {
2605         const char *p;
2606
2607         VM_SAFEPARMCOUNT(1,VM_tokenize);
2608
2609         strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2610         p = tokenize_string;
2611
2612         num_tokens = 0;
2613         for(;;)
2614         {
2615                 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
2616                         break;
2617
2618                 // skip whitespace here to find token start pos
2619                 while(*p && ISWHITESPACE(*p))
2620                         ++p;
2621
2622                 tokens_startpos[num_tokens] = p - tokenize_string;
2623                 if(!COM_ParseToken_Console(&p))
2624                         break;
2625                 tokens_endpos[num_tokens] = p - tokenize_string;
2626                 tokens[num_tokens] = PRVM_SetTempString(prog, com_token);
2627                 ++num_tokens;
2628         }
2629
2630         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2631 }
2632
2633 /*
2634 =========
2635 VM_tokenizebyseparator
2636
2637 float tokenizebyseparator(string s, string separator1, ...)
2638 =========
2639 */
2640 //float(string s, string separator1, ...) tokenizebyseparator = #479; // takes apart a string into individal words (access them with argv), returns how many
2641 //this function returns the token preceding each instance of a separator (of
2642 //which there can be multiple), and the text following the last separator
2643 //useful for parsing certain kinds of data like IP addresses
2644 //example:
2645 //numnumbers = tokenizebyseparator("10.1.2.3", ".");
2646 //returns 4 and the tokens "10" "1" "2" "3".
2647 void VM_tokenizebyseparator (prvm_prog_t *prog)
2648 {
2649         int j, k;
2650         int numseparators;
2651         int separatorlen[7];
2652         const char *separators[7];
2653         const char *p, *p0;
2654         const char *token;
2655         char tokentext[MAX_INPUTLINE];
2656
2657         VM_SAFEPARMCOUNTRANGE(2, 8,VM_tokenizebyseparator);
2658
2659         strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2660         p = tokenize_string;
2661
2662         numseparators = 0;
2663         for (j = 1;j < prog->argc;j++)
2664         {
2665                 // skip any blank separator strings
2666                 const char *s = PRVM_G_STRING(OFS_PARM0+j*3);
2667                 if (!s[0])
2668                         continue;
2669                 separators[numseparators] = s;
2670                 separatorlen[numseparators] = strlen(s);
2671                 numseparators++;
2672         }
2673
2674         num_tokens = 0;
2675         j = 0;
2676
2677         while (num_tokens < (int)(sizeof(tokens)/sizeof(tokens[0])))
2678         {
2679                 token = tokentext + j;
2680                 tokens_startpos[num_tokens] = p - tokenize_string;
2681                 p0 = p;
2682                 while (*p)
2683                 {
2684                         for (k = 0;k < numseparators;k++)
2685                         {
2686                                 if (!strncmp(p, separators[k], separatorlen[k]))
2687                                 {
2688                                         p += separatorlen[k];
2689                                         break;
2690                                 }
2691                         }
2692                         if (k < numseparators)
2693                                 break;
2694                         if (j < (int)sizeof(tokentext)-1)
2695                                 tokentext[j++] = *p;
2696                         p++;
2697                         p0 = p;
2698                 }
2699                 tokens_endpos[num_tokens] = p0 - tokenize_string;
2700                 if (j >= (int)sizeof(tokentext))
2701                         break;
2702                 tokentext[j++] = 0;
2703                 tokens[num_tokens++] = PRVM_SetTempString(prog, token);
2704                 if (!*p)
2705                         break;
2706         }
2707
2708         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2709 }
2710
2711 //string(float n) argv = #442; // returns a word from the tokenized string (returns nothing for an invalid index)
2712 //this function originally written by KrimZon, made shorter by LordHavoc
2713 void VM_argv (prvm_prog_t *prog)
2714 {
2715         int token_num;
2716
2717         VM_SAFEPARMCOUNT(1,VM_argv);
2718
2719         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2720
2721         if(token_num < 0)
2722                 token_num += num_tokens;
2723
2724         if (token_num >= 0 && token_num < num_tokens)
2725                 PRVM_G_INT(OFS_RETURN) = tokens[token_num];
2726         else
2727                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
2728 }
2729
2730 //float(float n) argv_start_index = #515; // returns the start index of a token
2731 void VM_argv_start_index (prvm_prog_t *prog)
2732 {
2733         int token_num;
2734
2735         VM_SAFEPARMCOUNT(1,VM_argv);
2736
2737         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2738
2739         if(token_num < 0)
2740                 token_num += num_tokens;
2741
2742         if (token_num >= 0 && token_num < num_tokens)
2743                 PRVM_G_FLOAT(OFS_RETURN) = tokens_startpos[token_num];
2744         else
2745                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2746 }
2747
2748 //float(float n) argv_end_index = #516; // returns the end index of a token
2749 void VM_argv_end_index (prvm_prog_t *prog)
2750 {
2751         int token_num;
2752
2753         VM_SAFEPARMCOUNT(1,VM_argv);
2754
2755         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2756
2757         if(token_num < 0)
2758                 token_num += num_tokens;
2759
2760         if (token_num >= 0 && token_num < num_tokens)
2761                 PRVM_G_FLOAT(OFS_RETURN) = tokens_endpos[token_num];
2762         else
2763                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2764 }
2765
2766 /*
2767 =========
2768 VM_isserver
2769
2770 float   isserver()
2771 =========
2772 */
2773 void VM_isserver(prvm_prog_t *prog)
2774 {
2775         VM_SAFEPARMCOUNT(0,VM_serverstate);
2776
2777         PRVM_G_FLOAT(OFS_RETURN) = sv.active && (svs.maxclients > 1 || cls.state == ca_dedicated);
2778 }
2779
2780 /*
2781 =========
2782 VM_clientcount
2783
2784 float   clientcount()
2785 =========
2786 */
2787 void VM_clientcount(prvm_prog_t *prog)
2788 {
2789         VM_SAFEPARMCOUNT(0,VM_clientcount);
2790
2791         PRVM_G_FLOAT(OFS_RETURN) = svs.maxclients;
2792 }
2793
2794 /*
2795 =========
2796 VM_clientstate
2797
2798 float   clientstate()
2799 =========
2800 */
2801 void VM_clientstate(prvm_prog_t *prog)
2802 {
2803         VM_SAFEPARMCOUNT(0,VM_clientstate);
2804
2805
2806         switch( cls.state ) {
2807                 case ca_uninitialized:
2808                 case ca_dedicated:
2809                         PRVM_G_FLOAT(OFS_RETURN) = 0;
2810                         break;
2811                 case ca_disconnected:
2812                         PRVM_G_FLOAT(OFS_RETURN) = 1;
2813                         break;
2814                 case ca_connected:
2815                         PRVM_G_FLOAT(OFS_RETURN) = 2;
2816                         break;
2817                 default:
2818                         // should never be reached!
2819                         break;
2820         }
2821 }
2822
2823 /*
2824 =========
2825 VM_getostype
2826
2827 float   getostype(prvm_prog_t *prog)
2828 =========
2829 */ // not used at the moment -> not included in the common list
2830 void VM_getostype(prvm_prog_t *prog)
2831 {
2832         VM_SAFEPARMCOUNT(0,VM_getostype);
2833
2834         /*
2835         OS_WINDOWS
2836         OS_LINUX
2837         OS_MAC - not supported
2838         */
2839
2840 #ifdef WIN32
2841         PRVM_G_FLOAT(OFS_RETURN) = 0;
2842 #elif defined(MACOSX)
2843         PRVM_G_FLOAT(OFS_RETURN) = 2;
2844 #else
2845         PRVM_G_FLOAT(OFS_RETURN) = 1;
2846 #endif
2847 }
2848
2849 /*
2850 =========
2851 VM_gettime
2852
2853 float   gettime(prvm_prog_t *prog)
2854 =========
2855 */
2856 float CDAudio_GetPosition(void);
2857 void VM_gettime(prvm_prog_t *prog)
2858 {
2859         int timer_index;
2860
2861         VM_SAFEPARMCOUNTRANGE(0,1,VM_gettime);
2862
2863         if(prog->argc == 0)
2864         {
2865                 PRVM_G_FLOAT(OFS_RETURN) = (float) realtime;
2866         }
2867         else
2868         {
2869                 timer_index = (int) PRVM_G_FLOAT(OFS_PARM0);
2870                 switch(timer_index)
2871                 {
2872                         case 0: // GETTIME_FRAMESTART
2873                                 PRVM_G_FLOAT(OFS_RETURN) = realtime;
2874                                 break;
2875                         case 1: // GETTIME_REALTIME
2876                                 PRVM_G_FLOAT(OFS_RETURN) = Sys_DirtyTime();
2877                                 break;
2878                         case 2: // GETTIME_HIRES
2879                                 PRVM_G_FLOAT(OFS_RETURN) = (Sys_DirtyTime() - host_dirtytime);
2880                                 break;
2881                         case 3: // GETTIME_UPTIME
2882                                 PRVM_G_FLOAT(OFS_RETURN) = realtime;
2883                                 break;
2884                         case 4: // GETTIME_CDTRACK
2885                                 PRVM_G_FLOAT(OFS_RETURN) = CDAudio_GetPosition();
2886                                 break;
2887                         default:
2888                                 VM_Warning(prog, "VM_gettime: %s: unsupported timer specified, returning realtime\n", prog->name);
2889                                 PRVM_G_FLOAT(OFS_RETURN) = realtime;
2890                                 break;
2891                 }
2892         }
2893 }
2894
2895 /*
2896 =========
2897 VM_getsoundtime
2898
2899 float   getsoundtime(prvm_prog_t *prog)
2900 =========
2901 */
2902
2903 void VM_getsoundtime (prvm_prog_t *prog)
2904 {
2905         int entnum, entchannel;
2906         VM_SAFEPARMCOUNT(2,VM_getsoundtime);
2907
2908         if (prog == SVVM_prog)
2909                 entnum = PRVM_NUM_FOR_EDICT(PRVM_G_EDICT(OFS_PARM0));
2910         else if (prog == CLVM_prog)
2911                 entnum = MAX_EDICTS + PRVM_NUM_FOR_EDICT(PRVM_G_EDICT(OFS_PARM0));
2912         else
2913         {
2914                 VM_Warning(prog, "VM_getsoundtime: %s: not supported on this progs\n", prog->name);
2915                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2916                 return;
2917         }
2918         entchannel = (int)PRVM_G_FLOAT(OFS_PARM1);
2919         entchannel = CHAN_USER2ENGINE(entchannel);
2920         if (!IS_CHAN(entchannel))
2921                 VM_Warning(prog, "VM_getsoundtime: %s: bad channel %i\n", prog->name, entchannel);
2922         PRVM_G_FLOAT(OFS_RETURN) = (float)S_GetEntChannelPosition(entnum, entchannel);
2923 }
2924
2925 /*
2926 =========
2927 VM_GetSoundLen
2928
2929 string  soundlength (string sample)
2930 =========
2931 */
2932 void VM_soundlength (prvm_prog_t *prog)
2933 {
2934         const char *s;
2935
2936         VM_SAFEPARMCOUNT(1, VM_soundlength);
2937
2938         s = PRVM_G_STRING(OFS_PARM0);
2939         PRVM_G_FLOAT(OFS_RETURN) = S_SoundLength(s);
2940 }
2941
2942 /*
2943 =========
2944 VM_loadfromdata
2945
2946 loadfromdata(string data)
2947 =========
2948 */
2949 void VM_loadfromdata(prvm_prog_t *prog)
2950 {
2951         VM_SAFEPARMCOUNT(1,VM_loadentsfromfile);
2952
2953         PRVM_ED_LoadFromFile(prog, PRVM_G_STRING(OFS_PARM0));
2954 }
2955
2956 /*
2957 ========================
2958 VM_parseentitydata
2959
2960 parseentitydata(entity ent, string data)
2961 ========================
2962 */
2963 void VM_parseentitydata(prvm_prog_t *prog)
2964 {
2965         prvm_edict_t *ent;
2966         const char *data;
2967
2968         VM_SAFEPARMCOUNT(2, VM_parseentitydata);
2969
2970         // get edict and test it
2971         ent = PRVM_G_EDICT(OFS_PARM0);
2972         if (ent->priv.required->free)
2973                 prog->error_cmd("VM_parseentitydata: %s: Can only set already spawned entities (entity %i is free)!", prog->name, PRVM_NUM_FOR_EDICT(ent));
2974
2975         data = PRVM_G_STRING(OFS_PARM1);
2976
2977         // parse the opening brace
2978         if (!COM_ParseToken_Simple(&data, false, false, true) || com_token[0] != '{' )
2979                 prog->error_cmd("VM_parseentitydata: %s: Couldn't parse entity data:\n%s", prog->name, data );
2980
2981         PRVM_ED_ParseEdict (prog, data, ent);
2982 }
2983
2984 /*
2985 =========
2986 VM_loadfromfile
2987
2988 loadfromfile(string file)
2989 =========
2990 */
2991 void VM_loadfromfile(prvm_prog_t *prog)
2992 {
2993         const char *filename;
2994         char *data;
2995
2996         VM_SAFEPARMCOUNT(1,VM_loadfromfile);
2997
2998         filename = PRVM_G_STRING(OFS_PARM0);
2999         if (FS_CheckNastyPath(filename, false))
3000         {
3001                 PRVM_G_FLOAT(OFS_RETURN) = -4;
3002                 VM_Warning(prog, "VM_loadfromfile: %s dangerous or non-portable filename \"%s\" not allowed. (contains : or \\ or begins with .. or /)\n", prog->name, filename);
3003                 return;
3004         }
3005
3006         // not conform with VM_fopen
3007         data = (char *)FS_LoadFile(filename, tempmempool, false, NULL);
3008         if (data == NULL)
3009                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3010
3011         PRVM_ED_LoadFromFile(prog, data);
3012
3013         if(data)
3014                 Mem_Free(data);
3015 }
3016
3017
3018 /*
3019 =========
3020 VM_modulo
3021
3022 float   mod(float val, float m)
3023 =========
3024 */
3025 void VM_modulo(prvm_prog_t *prog)
3026 {
3027         int val, m;
3028         VM_SAFEPARMCOUNT(2,VM_module);
3029
3030         val = (int) PRVM_G_FLOAT(OFS_PARM0);
3031         m       = (int) PRVM_G_FLOAT(OFS_PARM1);
3032
3033         PRVM_G_FLOAT(OFS_RETURN) = (float) (val % m);
3034 }
3035
3036 static void VM_Search_Init(prvm_prog_t *prog)
3037 {
3038         int i;
3039         for (i = 0;i < PRVM_MAX_OPENSEARCHES;i++)
3040                 prog->opensearches[i] = NULL;
3041 }
3042
3043 static void VM_Search_Reset(prvm_prog_t *prog)
3044 {
3045         int i;
3046         // reset the fssearch list
3047         for(i = 0; i < PRVM_MAX_OPENSEARCHES; i++)
3048         {
3049                 if(prog->opensearches[i])
3050                         FS_FreeSearch(prog->opensearches[i]);
3051                 prog->opensearches[i] = NULL;
3052         }
3053 }
3054
3055 /*
3056 =========
3057 VM_search_begin
3058
3059 float search_begin(string pattern, float caseinsensitive, float quiet)
3060 =========
3061 */
3062 void VM_search_begin(prvm_prog_t *prog)
3063 {
3064         int handle;
3065         const char *pattern;
3066         int caseinsens, quiet;
3067
3068         VM_SAFEPARMCOUNT(3, VM_search_begin);
3069
3070         pattern = PRVM_G_STRING(OFS_PARM0);
3071
3072         VM_CheckEmptyString(prog, pattern);
3073
3074         caseinsens = (int)PRVM_G_FLOAT(OFS_PARM1);
3075         quiet = (int)PRVM_G_FLOAT(OFS_PARM2);
3076
3077         for(handle = 0; handle < PRVM_MAX_OPENSEARCHES; handle++)
3078                 if(!prog->opensearches[handle])
3079                         break;
3080
3081         if(handle >= PRVM_MAX_OPENSEARCHES)
3082         {
3083                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3084                 VM_Warning(prog, "VM_search_begin: %s ran out of search handles (%i)\n", prog->name, PRVM_MAX_OPENSEARCHES);
3085                 return;
3086         }
3087
3088         if(!(prog->opensearches[handle] = FS_Search(pattern,caseinsens, quiet)))
3089                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3090         else
3091         {
3092                 prog->opensearches_origin[handle] = PRVM_AllocationOrigin(prog);
3093                 PRVM_G_FLOAT(OFS_RETURN) = handle;
3094         }
3095 }
3096
3097 /*
3098 =========
3099 VM_search_end
3100
3101 void    search_end(float handle)
3102 =========
3103 */
3104 void VM_search_end(prvm_prog_t *prog)
3105 {
3106         int handle;
3107         VM_SAFEPARMCOUNT(1, VM_search_end);
3108
3109         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3110
3111         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3112         {
3113                 VM_Warning(prog, "VM_search_end: invalid handle %i used in %s\n", handle, prog->name);
3114                 return;
3115         }
3116         if(prog->opensearches[handle] == NULL)
3117         {
3118                 VM_Warning(prog, "VM_search_end: no such handle %i in %s\n", handle, prog->name);
3119                 return;
3120         }
3121
3122         FS_FreeSearch(prog->opensearches[handle]);
3123         prog->opensearches[handle] = NULL;
3124         if(prog->opensearches_origin[handle])
3125                 PRVM_Free((char *)prog->opensearches_origin[handle]);
3126 }
3127
3128 /*
3129 =========
3130 VM_search_getsize
3131
3132 float   search_getsize(float handle)
3133 =========
3134 */
3135 void VM_search_getsize(prvm_prog_t *prog)
3136 {
3137         int handle;
3138         VM_SAFEPARMCOUNT(1, VM_M_search_getsize);
3139
3140         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3141
3142         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3143         {
3144                 VM_Warning(prog, "VM_search_getsize: invalid handle %i used in %s\n", handle, prog->name);
3145                 return;
3146         }
3147         if(prog->opensearches[handle] == NULL)
3148         {
3149                 VM_Warning(prog, "VM_search_getsize: no such handle %i in %s\n", handle, prog->name);
3150                 return;
3151         }
3152
3153         PRVM_G_FLOAT(OFS_RETURN) = prog->opensearches[handle]->numfilenames;
3154 }
3155
3156 /*
3157 =========
3158 VM_search_getfilename
3159
3160 string  search_getfilename(float handle, float num)
3161 =========
3162 */
3163 void VM_search_getfilename(prvm_prog_t *prog)
3164 {
3165         int handle, filenum;
3166         VM_SAFEPARMCOUNT(2, VM_search_getfilename);
3167
3168         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3169         filenum = (int)PRVM_G_FLOAT(OFS_PARM1);
3170
3171         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3172         {
3173                 VM_Warning(prog, "VM_search_getfilename: invalid handle %i used in %s\n", handle, prog->name);
3174                 return;
3175         }
3176         if(prog->opensearches[handle] == NULL)
3177         {
3178                 VM_Warning(prog, "VM_search_getfilename: no such handle %i in %s\n", handle, prog->name);
3179                 return;
3180         }
3181         if(filenum < 0 || filenum >= prog->opensearches[handle]->numfilenames)
3182         {
3183                 VM_Warning(prog, "VM_search_getfilename: invalid filenum %i in %s\n", filenum, prog->name);
3184                 return;
3185         }
3186
3187         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, prog->opensearches[handle]->filenames[filenum]);
3188 }
3189
3190 /*
3191 =========
3192 VM_chr
3193
3194 string  chr(float ascii)
3195 =========
3196 */
3197 void VM_chr(prvm_prog_t *prog)
3198 {
3199         /*
3200         char tmp[2];
3201         VM_SAFEPARMCOUNT(1, VM_chr);
3202
3203         tmp[0] = (unsigned char) PRVM_G_FLOAT(OFS_PARM0);
3204         tmp[1] = 0;
3205
3206         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, tmp);
3207         */
3208         
3209         char tmp[8];
3210         int len;
3211         VM_SAFEPARMCOUNT(1, VM_chr);
3212
3213         len = u8_fromchar((Uchar)PRVM_G_FLOAT(OFS_PARM0), tmp, sizeof(tmp));
3214         tmp[len] = 0;
3215         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, tmp);
3216 }
3217
3218 //=============================================================================
3219 // Draw builtins (client & menu)
3220
3221 /*
3222 =========
3223 VM_iscachedpic
3224
3225 float   iscachedpic(string pic)
3226 =========
3227 */
3228 void VM_iscachedpic(prvm_prog_t *prog)
3229 {
3230         VM_SAFEPARMCOUNT(1,VM_iscachedpic);
3231
3232         // drawq hasnt such a function, thus always return true
3233         PRVM_G_FLOAT(OFS_RETURN) = false;
3234 }
3235
3236 /*
3237 =========
3238 VM_precache_pic
3239
3240 string  precache_pic(string pic)
3241 =========
3242 */
3243 void VM_precache_pic(prvm_prog_t *prog)
3244 {
3245         const char      *s;
3246
3247         VM_SAFEPARMCOUNT(1, VM_precache_pic);
3248
3249         s = PRVM_G_STRING(OFS_PARM0);
3250         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
3251         VM_CheckEmptyString(prog, s);
3252
3253         // AK Draw_CachePic is supposed to always return a valid pointer
3254         if( Draw_CachePic_Flags(s, 0)->tex == r_texture_notexture )
3255                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
3256 }
3257
3258 /*
3259 =========
3260 VM_freepic
3261
3262 freepic(string s)
3263 =========
3264 */
3265 void VM_freepic(prvm_prog_t *prog)
3266 {
3267         const char *s;
3268
3269         VM_SAFEPARMCOUNT(1,VM_freepic);
3270
3271         s = PRVM_G_STRING(OFS_PARM0);
3272         VM_CheckEmptyString(prog, s);
3273
3274         Draw_FreePic(s);
3275 }
3276
3277 static void getdrawfontscale(prvm_prog_t *prog, float *sx, float *sy)
3278 {
3279         vec3_t v;
3280         *sx = *sy = 1;
3281         VectorCopy(PRVM_drawglobalvector(drawfontscale), v);
3282         if(VectorLength2(v) > 0)
3283         {
3284                 *sx = v[0];
3285                 *sy = v[1];
3286         }
3287 }
3288
3289 static dp_font_t *getdrawfont(prvm_prog_t *prog)
3290 {
3291         int f = (int) PRVM_drawglobalfloat(drawfont);
3292         if(f < 0 || f >= dp_fonts.maxsize)
3293                 return FONT_DEFAULT;
3294         return &dp_fonts.f[f];
3295 }
3296
3297 /*
3298 =========
3299 VM_drawcharacter
3300
3301 float   drawcharacter(vector position, float character, vector scale, vector rgb, float alpha, float flag)
3302 =========
3303 */
3304 void VM_drawcharacter(prvm_prog_t *prog)
3305 {
3306         float *pos,*scale,*rgb;
3307         char   character;
3308         int flag;
3309         float sx, sy;
3310         VM_SAFEPARMCOUNT(6,VM_drawcharacter);
3311
3312         character = (char) PRVM_G_FLOAT(OFS_PARM1);
3313         if(character == 0)
3314         {
3315                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3316                 VM_Warning(prog, "VM_drawcharacter: %s passed null character !\n",prog->name);
3317                 return;
3318         }
3319
3320         pos = PRVM_G_VECTOR(OFS_PARM0);
3321         scale = PRVM_G_VECTOR(OFS_PARM2);
3322         rgb = PRVM_G_VECTOR(OFS_PARM3);
3323         flag = (int)PRVM_G_FLOAT(OFS_PARM5);
3324
3325         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3326         {
3327                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3328                 VM_Warning(prog, "VM_drawcharacter: %s: wrong DRAWFLAG %i !\n",prog->name,flag);
3329                 return;
3330         }
3331
3332         if(pos[2] || scale[2])
3333                 Con_Printf("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")));
3334
3335         if(!scale[0] || !scale[1])
3336         {
3337                 PRVM_G_FLOAT(OFS_RETURN) = -3;
3338                 VM_Warning(prog, "VM_drawcharacter: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
3339                 return;
3340         }
3341
3342         getdrawfontscale(prog, &sx, &sy);
3343         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));
3344         PRVM_G_FLOAT(OFS_RETURN) = 1;
3345 }
3346
3347 /*
3348 =========
3349 VM_drawstring
3350
3351 float   drawstring(vector position, string text, vector scale, vector rgb, float alpha[, float flag])
3352 =========
3353 */
3354 void VM_drawstring(prvm_prog_t *prog)
3355 {
3356         float *pos,*scale,*rgb;
3357         const char  *string;
3358         int flag = 0;
3359         float sx, sy;
3360         VM_SAFEPARMCOUNTRANGE(5,6,VM_drawstring);
3361
3362         string = PRVM_G_STRING(OFS_PARM1);
3363         pos = PRVM_G_VECTOR(OFS_PARM0);
3364         scale = PRVM_G_VECTOR(OFS_PARM2);
3365         rgb = PRVM_G_VECTOR(OFS_PARM3);
3366         if (prog->argc >= 6)
3367                 flag = (int)PRVM_G_FLOAT(OFS_PARM5);
3368
3369         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3370         {
3371                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3372                 VM_Warning(prog, "VM_drawstring: %s: wrong DRAWFLAG %i !\n",prog->name,flag);
3373                 return;
3374         }
3375
3376         if(!scale[0] || !scale[1])
3377         {
3378                 PRVM_G_FLOAT(OFS_RETURN) = -3;
3379                 VM_Warning(prog, "VM_drawstring: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
3380                 return;
3381         }
3382
3383         if(pos[2] || scale[2])
3384                 Con_Printf("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")));
3385
3386         getdrawfontscale(prog, &sx, &sy);
3387         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));
3388         //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);
3389         PRVM_G_FLOAT(OFS_RETURN) = 1;
3390 }
3391
3392 /*
3393 =========
3394 VM_drawcolorcodedstring
3395
3396 float   drawcolorcodedstring(vector position, string text, vector scale, float alpha, float flag)
3397 /
3398 float   drawcolorcodedstring(vector position, string text, vector scale, vector rgb, float alpha, float flag)
3399 =========
3400 */
3401 void VM_drawcolorcodedstring(prvm_prog_t *prog)
3402 {
3403         float *pos, *scale;
3404         const char  *string;
3405         int flag;
3406         vec3_t rgb;
3407         float sx, sy, alpha;
3408
3409         VM_SAFEPARMCOUNTRANGE(5,6,VM_drawcolorcodedstring);
3410
3411         if (prog->argc == 6) // full 6 parms, like normal drawstring
3412         {
3413                 pos = PRVM_G_VECTOR(OFS_PARM0);
3414                 string = PRVM_G_STRING(OFS_PARM1);
3415                 scale = PRVM_G_VECTOR(OFS_PARM2);
3416                 VectorCopy(PRVM_G_VECTOR(OFS_PARM3), rgb); 
3417                 alpha = PRVM_G_FLOAT(OFS_PARM4);
3418                 flag = (int)PRVM_G_FLOAT(OFS_PARM5);
3419         }
3420         else
3421         {
3422                 pos = PRVM_G_VECTOR(OFS_PARM0);
3423                 string = PRVM_G_STRING(OFS_PARM1);
3424                 scale = PRVM_G_VECTOR(OFS_PARM2);
3425                 rgb[0] = 1.0;
3426                 rgb[1] = 1.0;
3427                 rgb[2] = 1.0;
3428                 alpha = PRVM_G_FLOAT(OFS_PARM3);
3429                 flag = (int)PRVM_G_FLOAT(OFS_PARM4);
3430         }
3431
3432         if(flag < DRAWFLAG_NORMAL || flag >= DRAWFLAG_NUMFLAGS)
3433         {
3434                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3435                 VM_Warning(prog, "VM_drawcolorcodedstring: %s: wrong DRAWFLAG %i !\n",prog->name,flag);
3436                 return;
3437         }
3438
3439         if(!scale[0] || !scale[1])
3440         {
3441                 PRVM_G_FLOAT(OFS_RETURN) = -3;
3442                 VM_Warning(prog, "VM_drawcolorcodedstring: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
3443                 return;
3444         }
3445
3446         if(pos[2] || scale[2])
3447                 Con_Printf("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")));
3448
3449         getdrawfontscale(prog, &sx, &sy);
3450         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));
3451         if (prog->argc == 6) // also return vector of last color
3452                 VectorCopy(DrawQ_Color, PRVM_G_VECTOR(OFS_RETURN));
3453         else
3454                 PRVM_G_FLOAT(OFS_RETURN) = 1;
3455 }
3456 /*
3457 =========
3458 VM_stringwidth
3459
3460 float   stringwidth(string text, float allowColorCodes, float size)
3461 =========
3462 */
3463 void VM_stringwidth(prvm_prog_t *prog)
3464 {
3465         const char  *string;
3466         float *szv;
3467         float mult; // sz is intended font size so we can later add freetype support, mult is font size multiplier in pixels per character cell
3468         int colors;
3469         float sx, sy;
3470         size_t maxlen = 0;
3471         VM_SAFEPARMCOUNTRANGE(2,3,VM_drawstring);
3472
3473         getdrawfontscale(prog, &sx, &sy);
3474         if(prog->argc == 3)
3475         {
3476                 szv = PRVM_G_VECTOR(OFS_PARM2);
3477                 mult = 1;
3478         }
3479         else
3480         {
3481                 // we want the width for 8x8 font size, divided by 8
3482                 static float defsize[] = {8, 8};
3483                 szv = defsize;
3484                 mult = 0.125;
3485                 // to make sure snapping is turned off, ALWAYS use a nontrivial scale in this case
3486                 if(sx >= 0.9 && sx <= 1.1)
3487                 {
3488                         mult *= 2;
3489                         sx /= 2;
3490                         sy /= 2;
3491                 }
3492         }
3493
3494         string = PRVM_G_STRING(OFS_PARM0);
3495         colors = (int)PRVM_G_FLOAT(OFS_PARM1);
3496
3497         PRVM_G_FLOAT(OFS_RETURN) = DrawQ_TextWidth_UntilWidth_TrackColors_Scale(string, &maxlen, szv[0], szv[1], sx, sy, NULL, !colors, getdrawfont(prog), 1000000000) * mult;
3498 /*
3499         if(prog->argc == 3)
3500         {
3501                 mult = sz = PRVM_G_FLOAT(OFS_PARM2);
3502         }
3503         else
3504         {
3505                 sz = 8;
3506                 mult = 1;
3507         }
3508
3509         string = PRVM_G_STRING(OFS_PARM0);
3510         colors = (int)PRVM_G_FLOAT(OFS_PARM1);
3511
3512         PRVM_G_FLOAT(OFS_RETURN) = DrawQ_TextWidth(string, 0, !colors, getdrawfont()) * mult; // 1x1 characters, don't actually draw
3513 */
3514 }
3515
3516 /*
3517 =========
3518 VM_findfont
3519
3520 float findfont(string s)
3521 =========
3522 */
3523
3524 static float getdrawfontnum(const char *fontname)
3525 {
3526         int i;
3527
3528         for(i = 0; i < dp_fonts.maxsize; ++i)
3529                 if(!strcmp(dp_fonts.f[i].title, fontname))
3530                         return i;
3531         return -1;
3532 }
3533
3534 void VM_findfont(prvm_prog_t *prog)
3535 {
3536         VM_SAFEPARMCOUNT(1,VM_findfont);
3537         PRVM_G_FLOAT(OFS_RETURN) = getdrawfontnum(PRVM_G_STRING(OFS_PARM0));
3538 }
3539
3540 /*
3541 =========
3542 VM_loadfont
3543
3544 float loadfont(string fontname, string fontmaps, string sizes, float slot)
3545 =========
3546 */
3547
3548 void VM_loadfont(prvm_prog_t *prog)
3549 {
3550         const char *fontname, *filelist, *sizes, *c, *cm;
3551         char mainfont[MAX_QPATH];
3552         int i, numsizes;
3553         float sz, scale, voffset;
3554         dp_font_t *f;
3555
3556         VM_SAFEPARMCOUNTRANGE(3,6,VM_loadfont);
3557
3558         fontname = PRVM_G_STRING(OFS_PARM0);
3559         if (!fontname[0])
3560                 fontname = "default";
3561
3562         filelist = PRVM_G_STRING(OFS_PARM1);
3563         if (!filelist[0])
3564                 filelist = "gfx/conchars";
3565
3566         sizes = PRVM_G_STRING(OFS_PARM2);
3567         if (!sizes[0])
3568                 sizes = "10";
3569
3570         // find a font
3571         f = NULL;
3572         if (prog->argc >= 4)
3573         {
3574                 i = PRVM_G_FLOAT(OFS_PARM3);
3575                 if (i >= 0 && i < dp_fonts.maxsize)
3576                 {
3577                         f = &dp_fonts.f[i];
3578                         strlcpy(f->title, fontname, sizeof(f->title)); // replace name
3579                 }
3580         }
3581         if (!f)
3582                 f = FindFont(fontname, true);
3583         if (!f)
3584         {
3585                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3586                 return; // something go wrong
3587         }
3588
3589         memset(f->fallbacks, 0, sizeof(f->fallbacks));
3590         memset(f->fallback_faces, 0, sizeof(f->fallback_faces));
3591
3592         // first font is handled "normally"
3593         c = strchr(filelist, ':');
3594         cm = strchr(filelist, ',');
3595         if(c && (!cm || c < cm))
3596                 f->req_face = atoi(c+1);
3597         else
3598         {
3599                 f->req_face = 0;
3600                 c = cm;
3601         }
3602         if(!c || (c - filelist) > MAX_QPATH)
3603                 strlcpy(mainfont, filelist, sizeof(mainfont));
3604         else
3605         {
3606                 memcpy(mainfont, filelist, c - filelist);
3607                 mainfont[c - filelist] = 0;
3608         }
3609
3610         // handle fallbacks
3611         for(i = 0; i < MAX_FONT_FALLBACKS; ++i)
3612         {
3613                 c = strchr(filelist, ',');
3614                 if(!c)
3615                         break;
3616                 filelist = c + 1;
3617                 if(!*filelist)
3618                         break;
3619                 c = strchr(filelist, ':');
3620                 cm = strchr(filelist, ',');
3621                 if(c && (!cm || c < cm))
3622                         f->fallback_faces[i] = atoi(c+1);
3623                 else
3624                 {
3625                         f->fallback_faces[i] = 0; // f->req_face; could make it stick to the default-font's face index
3626                         c = cm;
3627                 }
3628                 if(!c || (c-filelist) > MAX_QPATH)
3629                 {
3630                         strlcpy(f->fallbacks[i], filelist, sizeof(mainfont));
3631                 }
3632                 else
3633                 {
3634                         memcpy(f->fallbacks[i], filelist, c - filelist);
3635                         f->fallbacks[i][c - filelist] = 0;
3636                 }
3637         }
3638
3639         // handle sizes
3640         for(i = 0; i < MAX_FONT_SIZES; ++i)
3641                 f->req_sizes[i] = -1;
3642         for (numsizes = 0,c = sizes;;)
3643         {
3644                 if (!COM_ParseToken_VM_Tokenize(&c, 0))
3645                         break;
3646                 sz = atof(com_token);
3647                 // detect crap size
3648                 if (sz < 0.001f || sz > 1000.0f)
3649                 {
3650                         VM_Warning(prog, "VM_loadfont: crap size %s", com_token);
3651                         continue;
3652                 }
3653                 // check overflow
3654                 if (numsizes == MAX_FONT_SIZES)
3655                 {
3656                         VM_Warning(prog, "VM_loadfont: MAX_FONT_SIZES = %i exceeded", MAX_FONT_SIZES);
3657                         break;
3658                 }
3659                 f->req_sizes[numsizes] = sz;
3660                 numsizes++;
3661         }
3662
3663         // additional scale/hoffset parms
3664         scale = 1;
3665         voffset = 0;
3666         if (prog->argc >= 5)
3667         {
3668                 scale = PRVM_G_FLOAT(OFS_PARM4);
3669                 if (scale <= 0)
3670                         scale = 1;
3671         }
3672         if (prog->argc >= 6)
3673                 voffset = PRVM_G_FLOAT(OFS_PARM5);
3674
3675         // load
3676         LoadFont(true, mainfont, f, scale, voffset);
3677
3678         // return index of loaded font
3679         PRVM_G_FLOAT(OFS_RETURN) = (f - dp_fonts.f);
3680 }
3681
3682 /*
3683 =========
3684 VM_drawpic
3685
3686 float   drawpic(vector position, string pic, vector size, vector rgb, float alpha, float flag)
3687 =========
3688 */
3689 void VM_drawpic(prvm_prog_t *prog)
3690 {
3691         const char *picname;
3692         float *size, *pos, *rgb;
3693         int flag = 0;
3694
3695         VM_SAFEPARMCOUNTRANGE(5,6,VM_drawpic);
3696
3697         picname = PRVM_G_STRING(OFS_PARM1);
3698         VM_CheckEmptyString(prog, picname);
3699
3700         // is pic cached ? no function yet for that
3701         if(!1)
3702         {
3703                 PRVM_G_FLOAT(OFS_RETURN) = -4;
3704                 VM_Warning(prog, "VM_drawpic: %s: %s not cached !\n", prog->name, picname);
3705                 return;
3706         }
3707
3708         pos = PRVM_G_VECTOR(OFS_PARM0);
3709         size = PRVM_G_VECTOR(OFS_PARM2);
3710         rgb = PRVM_G_VECTOR(OFS_PARM3);
3711         if (prog->argc >= 6)
3712                 flag = (int) PRVM_G_FLOAT(OFS_PARM5);
3713
3714         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3715         {
3716                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3717                 VM_Warning(prog, "VM_drawpic: %s: wrong DRAWFLAG %i !\n",prog->name,flag);
3718                 return;
3719         }
3720
3721         if(pos[2] || size[2])
3722                 Con_Printf("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")));
3723
3724         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);
3725         PRVM_G_FLOAT(OFS_RETURN) = 1;
3726 }
3727 /*
3728 =========
3729 VM_drawrotpic
3730
3731 float   drawrotpic(vector position, string pic, vector size, vector org, float angle, vector rgb, float alpha, float flag)
3732 =========
3733 */
3734 void VM_drawrotpic(prvm_prog_t *prog)
3735 {
3736         const char *picname;
3737         float *size, *pos, *org, *rgb;
3738         int flag;
3739
3740         VM_SAFEPARMCOUNT(8,VM_drawrotpic);
3741
3742         picname = PRVM_G_STRING(OFS_PARM1);
3743         VM_CheckEmptyString(prog, picname);
3744
3745         // is pic cached ? no function yet for that
3746         if(!1)
3747         {
3748                 PRVM_G_FLOAT(OFS_RETURN) = -4;
3749                 VM_Warning(prog, "VM_drawrotpic: %s: %s not cached !\n", prog->name, picname);
3750                 return;
3751         }
3752
3753         pos = PRVM_G_VECTOR(OFS_PARM0);
3754         size = PRVM_G_VECTOR(OFS_PARM2);
3755         org = PRVM_G_VECTOR(OFS_PARM3);
3756         rgb = PRVM_G_VECTOR(OFS_PARM5);
3757         flag = (int) PRVM_G_FLOAT(OFS_PARM7);
3758
3759         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3760         {
3761                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3762                 VM_Warning(prog, "VM_drawrotpic: %s: wrong DRAWFLAG %i !\n",prog->name,flag);
3763                 return;
3764         }
3765
3766         if(pos[2] || size[2] || org[2])
3767                 Con_Printf("VM_drawrotpic: z value from pos/size/org discarded\n");
3768
3769         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);
3770         PRVM_G_FLOAT(OFS_RETURN) = 1;
3771 }
3772 /*
3773 =========
3774 VM_drawsubpic
3775
3776 float   drawsubpic(vector position, vector size, string pic, vector srcPos, vector srcSize, vector rgb, float alpha, float flag)
3777
3778 =========
3779 */
3780 void VM_drawsubpic(prvm_prog_t *prog)
3781 {
3782         const char *picname;
3783         float *size, *pos, *rgb, *srcPos, *srcSize, alpha;
3784         int flag;
3785
3786         VM_SAFEPARMCOUNT(8,VM_drawsubpic);
3787
3788         picname = PRVM_G_STRING(OFS_PARM2);
3789         VM_CheckEmptyString(prog, picname);
3790
3791         // is pic cached ? no function yet for that
3792         if(!1)
3793         {
3794                 PRVM_G_FLOAT(OFS_RETURN) = -4;
3795                 VM_Warning(prog, "VM_drawsubpic: %s: %s not cached !\n", prog->name, picname);
3796                 return;
3797         }
3798
3799         pos = PRVM_G_VECTOR(OFS_PARM0);
3800         size = PRVM_G_VECTOR(OFS_PARM1);
3801         srcPos = PRVM_G_VECTOR(OFS_PARM3);
3802         srcSize = PRVM_G_VECTOR(OFS_PARM4);
3803         rgb = PRVM_G_VECTOR(OFS_PARM5);
3804         alpha = PRVM_G_FLOAT(OFS_PARM6);
3805         flag = (int) PRVM_G_FLOAT(OFS_PARM7);
3806
3807         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3808         {
3809                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3810                 VM_Warning(prog, "VM_drawsubpic: %s: wrong DRAWFLAG %i !\n",prog->name,flag);
3811                 return;
3812         }
3813
3814         if(pos[2] || size[2])
3815                 Con_Printf("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")));
3816
3817         DrawQ_SuperPic(pos[0], pos[1], Draw_CachePic_Flags (picname, CACHEPICFLAG_NOTPERSISTENT),
3818                 size[0], size[1],
3819                 srcPos[0],              srcPos[1],              rgb[0], rgb[1], rgb[2], alpha,
3820                 srcPos[0] + srcSize[0], srcPos[1],              rgb[0], rgb[1], rgb[2], alpha,
3821                 srcPos[0],              srcPos[1] + srcSize[1], rgb[0], rgb[1], rgb[2], alpha,
3822                 srcPos[0] + srcSize[0], srcPos[1] + srcSize[1], rgb[0], rgb[1], rgb[2], alpha,
3823                 flag);
3824         PRVM_G_FLOAT(OFS_RETURN) = 1;
3825 }
3826
3827 /*
3828 =========
3829 VM_drawfill
3830
3831 float drawfill(vector position, vector size, vector rgb, float alpha, float flag)
3832 =========
3833 */
3834 void VM_drawfill(prvm_prog_t *prog)
3835 {
3836         float *size, *pos, *rgb;
3837         int flag;
3838
3839         VM_SAFEPARMCOUNT(5,VM_drawfill);
3840
3841
3842         pos = PRVM_G_VECTOR(OFS_PARM0);
3843         size = PRVM_G_VECTOR(OFS_PARM1);
3844         rgb = PRVM_G_VECTOR(OFS_PARM2);
3845         flag = (int) PRVM_G_FLOAT(OFS_PARM4);
3846
3847         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3848         {
3849                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3850                 VM_Warning(prog, "VM_drawfill: %s: wrong DRAWFLAG %i !\n",prog->name,flag);
3851                 return;
3852         }
3853
3854         if(pos[2] || size[2])
3855                 Con_Printf("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")));
3856
3857         DrawQ_Fill(pos[0], pos[1], size[0], size[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM3), flag);
3858         PRVM_G_FLOAT(OFS_RETURN) = 1;
3859 }
3860
3861 /*
3862 =========
3863 VM_drawsetcliparea
3864
3865 drawsetcliparea(float x, float y, float width, float height)
3866 =========
3867 */
3868 void VM_drawsetcliparea(prvm_prog_t *prog)
3869 {
3870         float x,y,w,h;
3871         VM_SAFEPARMCOUNT(4,VM_drawsetcliparea);
3872
3873         x = bound(0, PRVM_G_FLOAT(OFS_PARM0), vid_conwidth.integer);
3874         y = bound(0, PRVM_G_FLOAT(OFS_PARM1), vid_conheight.integer);
3875         w = bound(0, PRVM_G_FLOAT(OFS_PARM2) + PRVM_G_FLOAT(OFS_PARM0) - x, (vid_conwidth.integer  - x));
3876         h = bound(0, PRVM_G_FLOAT(OFS_PARM3) + PRVM_G_FLOAT(OFS_PARM1) - y, (vid_conheight.integer - y));
3877
3878         DrawQ_SetClipArea(x, y, w, h);
3879 }
3880
3881 /*
3882 =========
3883 VM_drawresetcliparea
3884
3885 drawresetcliparea()
3886 =========
3887 */
3888 void VM_drawresetcliparea(prvm_prog_t *prog)
3889 {
3890         VM_SAFEPARMCOUNT(0,VM_drawresetcliparea);
3891
3892         DrawQ_ResetClipArea();
3893 }
3894
3895 /*
3896 =========
3897 VM_getimagesize
3898
3899 vector  getimagesize(string pic)
3900 =========
3901 */
3902 void VM_getimagesize(prvm_prog_t *prog)
3903 {
3904         const char *p;
3905         cachepic_t *pic;
3906
3907         VM_SAFEPARMCOUNT(1,VM_getimagesize);
3908
3909         p = PRVM_G_STRING(OFS_PARM0);
3910         VM_CheckEmptyString(prog, p);
3911
3912         pic = Draw_CachePic_Flags (p, CACHEPICFLAG_NOTPERSISTENT);
3913
3914         PRVM_G_VECTOR(OFS_RETURN)[0] = pic->width;
3915         PRVM_G_VECTOR(OFS_RETURN)[1] = pic->height;
3916         PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
3917 }
3918
3919 /*
3920 =========
3921 VM_keynumtostring
3922
3923 string keynumtostring(float keynum)
3924 =========
3925 */
3926 void VM_keynumtostring (prvm_prog_t *prog)
3927 {
3928         char tinystr[2];
3929         VM_SAFEPARMCOUNT(1, VM_keynumtostring);
3930
3931         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, Key_KeynumToString((int)PRVM_G_FLOAT(OFS_PARM0), tinystr, sizeof(tinystr)));
3932 }
3933
3934 /*
3935 =========
3936 VM_findkeysforcommand
3937
3938 string  findkeysforcommand(string command, float bindmap)
3939
3940 the returned string is an altstring
3941 =========
3942 */
3943 #define FKFC_NUMKEYS 5
3944 void M_FindKeysForCommand(const char *command, int *keys);
3945 void VM_findkeysforcommand(prvm_prog_t *prog)
3946 {
3947         const char *cmd;
3948         char ret[VM_STRINGTEMP_LENGTH];
3949         int keys[FKFC_NUMKEYS];
3950         int i;
3951         int bindmap;
3952         char vabuf[1024];
3953
3954         VM_SAFEPARMCOUNTRANGE(1, 2, VM_findkeysforcommand);
3955
3956         cmd = PRVM_G_STRING(OFS_PARM0);
3957         if(prog->argc == 2)
3958                 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM1), MAX_BINDMAPS-1);
3959         else
3960                 bindmap = 0; // consistent to "bind"
3961
3962         VM_CheckEmptyString(prog, cmd);
3963
3964         Key_FindKeysForCommand(cmd, keys, FKFC_NUMKEYS, bindmap);
3965
3966         ret[0] = 0;
3967         for(i = 0; i < FKFC_NUMKEYS; i++)
3968                 strlcat(ret, va(vabuf, sizeof(vabuf), " \'%i\'", keys[i]), sizeof(ret));
3969
3970         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, ret);
3971 }
3972
3973 /*
3974 =========
3975 VM_stringtokeynum
3976
3977 float stringtokeynum(string key)
3978 =========
3979 */
3980 void VM_stringtokeynum (prvm_prog_t *prog)
3981 {
3982         VM_SAFEPARMCOUNT( 1, VM_keynumtostring );
3983
3984         PRVM_G_FLOAT(OFS_RETURN) = Key_StringToKeynum(PRVM_G_STRING(OFS_PARM0));
3985 }
3986
3987 /*
3988 =========
3989 VM_getkeybind
3990
3991 string getkeybind(float key, float bindmap)
3992 =========
3993 */
3994 void VM_getkeybind (prvm_prog_t *prog)
3995 {
3996         int bindmap;
3997         VM_SAFEPARMCOUNTRANGE(1, 2, VM_CL_getkeybind);
3998         if(prog->argc == 2)
3999                 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM1), MAX_BINDMAPS-1);
4000         else
4001                 bindmap = 0; // consistent to "bind"
4002
4003         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, Key_GetBind((int)PRVM_G_FLOAT(OFS_PARM0), bindmap));
4004 }
4005
4006 /*
4007 =========
4008 VM_setkeybind
4009
4010 float setkeybind(float key, string cmd, float bindmap)
4011 =========
4012 */
4013 void VM_setkeybind (prvm_prog_t *prog)
4014 {
4015         int bindmap;
4016         VM_SAFEPARMCOUNTRANGE(2, 3, VM_CL_setkeybind);
4017         if(prog->argc == 3)
4018                 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM2), MAX_BINDMAPS-1);
4019         else
4020                 bindmap = 0; // consistent to "bind"
4021
4022         PRVM_G_FLOAT(OFS_RETURN) = 0;
4023         if(Key_SetBinding((int)PRVM_G_FLOAT(OFS_PARM0), bindmap, PRVM_G_STRING(OFS_PARM1)))
4024                 PRVM_G_FLOAT(OFS_RETURN) = 1;
4025 }
4026
4027 /*
4028 =========
4029 VM_getbindmap
4030
4031 vector getbindmaps()
4032 =========
4033 */
4034 void VM_getbindmaps (prvm_prog_t *prog)
4035 {
4036         int fg, bg;
4037         VM_SAFEPARMCOUNT(0, VM_CL_getbindmap);
4038         Key_GetBindMap(&fg, &bg);
4039         PRVM_G_VECTOR(OFS_RETURN)[0] = fg;
4040         PRVM_G_VECTOR(OFS_RETURN)[1] = bg;
4041         PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
4042 }
4043
4044 /*
4045 =========
4046 VM_setbindmap
4047
4048 float setbindmaps(vector bindmap)
4049 =========
4050 */
4051 void VM_setbindmaps (prvm_prog_t *prog)
4052 {
4053         VM_SAFEPARMCOUNT(1, VM_CL_setbindmap);
4054         PRVM_G_FLOAT(OFS_RETURN) = 0;
4055         if(PRVM_G_VECTOR(OFS_PARM0)[2] == 0)
4056                 if(Key_SetBindMap((int)PRVM_G_VECTOR(OFS_PARM0)[0], (int)PRVM_G_VECTOR(OFS_PARM0)[1]))
4057                         PRVM_G_FLOAT(OFS_RETURN) = 1;
4058 }
4059
4060 // CL_Video interface functions
4061
4062 /*
4063 ========================
4064 VM_cin_open
4065
4066 float cin_open(string file, string name)
4067 ========================
4068 */
4069 void VM_cin_open(prvm_prog_t *prog)
4070 {
4071         const char *file;
4072         const char *name;
4073
4074         VM_SAFEPARMCOUNT( 2, VM_cin_open );
4075
4076         file = PRVM_G_STRING( OFS_PARM0 );
4077         name = PRVM_G_STRING( OFS_PARM1 );
4078
4079         VM_CheckEmptyString(prog,  file );
4080     VM_CheckEmptyString(prog,  name );
4081
4082         if( CL_OpenVideo( file, name, MENUOWNER, "" ) )
4083                 PRVM_G_FLOAT( OFS_RETURN ) = 1;
4084         else
4085                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
4086 }
4087
4088 /*
4089 ========================
4090 VM_cin_close
4091
4092 void cin_close(string name)
4093 ========================
4094 */
4095 void VM_cin_close(prvm_prog_t *prog)
4096 {
4097         const char *name;
4098
4099         VM_SAFEPARMCOUNT( 1, VM_cin_close );
4100
4101         name = PRVM_G_STRING( OFS_PARM0 );
4102         VM_CheckEmptyString(prog,  name );
4103
4104         CL_CloseVideo( CL_GetVideoByName( name ) );
4105 }
4106
4107 /*
4108 ========================
4109 VM_cin_setstate
4110 void cin_setstate(string name, float type)
4111 ========================
4112 */
4113 void VM_cin_setstate(prvm_prog_t *prog)
4114 {
4115         const char *name;
4116         clvideostate_t  state;
4117         clvideo_t               *video;
4118
4119         VM_SAFEPARMCOUNT( 2, VM_cin_netstate );
4120
4121         name = PRVM_G_STRING( OFS_PARM0 );
4122         VM_CheckEmptyString(prog,  name );
4123
4124         state = (clvideostate_t)((int)PRVM_G_FLOAT( OFS_PARM1 ));
4125
4126         video = CL_GetVideoByName( name );
4127         if( video && state > CLVIDEO_UNUSED && state < CLVIDEO_STATECOUNT )
4128                 CL_SetVideoState( video, state );
4129 }
4130
4131 /*
4132 ========================
4133 VM_cin_getstate
4134
4135 float cin_getstate(string name)
4136 ========================
4137 */
4138 void VM_cin_getstate(prvm_prog_t *prog)
4139 {
4140         const char *name;
4141         clvideo_t               *video;
4142
4143         VM_SAFEPARMCOUNT( 1, VM_cin_getstate );
4144
4145         name = PRVM_G_STRING( OFS_PARM0 );
4146         VM_CheckEmptyString(prog,  name );
4147
4148         video = CL_GetVideoByName( name );
4149         if( video )
4150                 PRVM_G_FLOAT( OFS_RETURN ) = (int)video->state;
4151         else
4152                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
4153 }
4154
4155 /*
4156 ========================
4157 VM_cin_restart
4158
4159 void cin_restart(string name)
4160 ========================
4161 */
4162 void VM_cin_restart(prvm_prog_t *prog)
4163 {
4164         const char *name;
4165         clvideo_t               *video;
4166
4167         VM_SAFEPARMCOUNT( 1, VM_cin_restart );
4168
4169         name = PRVM_G_STRING( OFS_PARM0 );
4170         VM_CheckEmptyString(prog,  name );
4171
4172         video = CL_GetVideoByName( name );
4173         if( video )
4174                 CL_RestartVideo( video );
4175 }
4176
4177 /*
4178 ========================
4179 VM_gecko_create
4180
4181 float[bool] gecko_create( string name )
4182 ========================
4183 */
4184 void VM_gecko_create(prvm_prog_t *prog) {
4185         // REMOVED
4186         PRVM_G_FLOAT( OFS_RETURN ) = 0;
4187 }
4188
4189 /*
4190 ========================
4191 VM_gecko_destroy
4192
4193 void gecko_destroy( string name )
4194 ========================
4195 */
4196 void VM_gecko_destroy(prvm_prog_t *prog) {
4197         // REMOVED
4198 }
4199
4200 /*
4201 ========================
4202 VM_gecko_navigate
4203
4204 void gecko_navigate( string name, string URI )
4205 ========================
4206 */
4207 void VM_gecko_navigate(prvm_prog_t *prog) {
4208         // REMOVED
4209 }
4210
4211 /*
4212 ========================
4213 VM_gecko_keyevent
4214
4215 float[bool] gecko_keyevent( string name, float key, float eventtype ) 
4216 ========================
4217 */
4218 void VM_gecko_keyevent(prvm_prog_t *prog) {
4219         // REMOVED
4220         PRVM_G_FLOAT( OFS_RETURN ) = 0;
4221 }
4222
4223 /*
4224 ========================
4225 VM_gecko_movemouse
4226
4227 void gecko_mousemove( string name, float x, float y )
4228 ========================
4229 */
4230 void VM_gecko_movemouse(prvm_prog_t *prog) {
4231         // REMOVED
4232 }
4233
4234
4235 /*
4236 ========================
4237 VM_gecko_resize
4238
4239 void gecko_resize( string name, float w, float h )
4240 ========================
4241 */
4242 void VM_gecko_resize(prvm_prog_t *prog) {
4243         // REMOVED
4244 }
4245
4246
4247 /*
4248 ========================
4249 VM_gecko_get_texture_extent
4250
4251 vector gecko_get_texture_extent( string name )
4252 ========================
4253 */
4254 void VM_gecko_get_texture_extent(prvm_prog_t *prog) {
4255         // REMOVED
4256         PRVM_G_VECTOR(OFS_RETURN)[0] = 0;
4257         PRVM_G_VECTOR(OFS_RETURN)[1] = 0;
4258 }
4259
4260
4261
4262 /*
4263 ==============
4264 VM_makevectors
4265
4266 Writes new values for v_forward, v_up, and v_right based on angles
4267 void makevectors(vector angle)
4268 ==============
4269 */
4270 void VM_makevectors (prvm_prog_t *prog)
4271 {
4272         VM_SAFEPARMCOUNT(1, VM_makevectors);
4273         AngleVectors(PRVM_G_VECTOR(OFS_PARM0), PRVM_gameglobalvector(v_forward), PRVM_gameglobalvector(v_right), PRVM_gameglobalvector(v_up));
4274 }
4275
4276 /*
4277 ==============
4278 VM_vectorvectors
4279
4280 Writes new values for v_forward, v_up, and v_right based on the given forward vector
4281 vectorvectors(vector)
4282 ==============
4283 */
4284 void VM_vectorvectors (prvm_prog_t *prog)
4285 {
4286         VM_SAFEPARMCOUNT(1, VM_vectorvectors);
4287         VectorNormalize2(PRVM_G_VECTOR(OFS_PARM0), PRVM_gameglobalvector(v_forward));
4288         VectorVectors(PRVM_gameglobalvector(v_forward), PRVM_gameglobalvector(v_right), PRVM_gameglobalvector(v_up));
4289 }
4290
4291 /*
4292 ========================
4293 VM_drawline
4294
4295 void drawline(float width, vector pos1, vector pos2, vector rgb, float alpha, float flags)
4296 ========================
4297 */
4298 void VM_drawline (prvm_prog_t *prog)
4299 {
4300         float   *c1, *c2, *rgb;
4301         float   alpha, width;
4302         unsigned char   flags;
4303
4304         VM_SAFEPARMCOUNT(6, VM_drawline);
4305         width   = PRVM_G_FLOAT(OFS_PARM0);
4306         c1              = PRVM_G_VECTOR(OFS_PARM1);
4307         c2              = PRVM_G_VECTOR(OFS_PARM2);
4308         rgb             = PRVM_G_VECTOR(OFS_PARM3);
4309         alpha   = PRVM_G_FLOAT(OFS_PARM4);
4310         flags   = (int)PRVM_G_FLOAT(OFS_PARM5);
4311         DrawQ_Line(width, c1[0], c1[1], c2[0], c2[1], rgb[0], rgb[1], rgb[2], alpha, flags);
4312 }
4313
4314 // float(float number, float quantity) bitshift (EXT_BITSHIFT)
4315 void VM_bitshift (prvm_prog_t *prog)
4316 {
4317         int n1, n2;
4318         VM_SAFEPARMCOUNT(2, VM_bitshift);
4319
4320         n1 = (int)fabs((float)((int)PRVM_G_FLOAT(OFS_PARM0)));
4321         n2 = (int)PRVM_G_FLOAT(OFS_PARM1);
4322         if(!n1)
4323                 PRVM_G_FLOAT(OFS_RETURN) = n1;
4324         else
4325         if(n2 < 0)
4326                 PRVM_G_FLOAT(OFS_RETURN) = (n1 >> -n2);
4327         else
4328                 PRVM_G_FLOAT(OFS_RETURN) = (n1 << n2);
4329 }
4330
4331 ////////////////////////////////////////
4332 // AltString functions
4333 ////////////////////////////////////////
4334
4335 /*
4336 ========================
4337 VM_altstr_count
4338
4339 float altstr_count(string)
4340 ========================
4341 */
4342 void VM_altstr_count(prvm_prog_t *prog)
4343 {
4344         const char *altstr, *pos;
4345         int     count;
4346
4347         VM_SAFEPARMCOUNT( 1, VM_altstr_count );
4348
4349         altstr = PRVM_G_STRING( OFS_PARM0 );
4350         //VM_CheckEmptyString(prog,  altstr );
4351
4352         for( count = 0, pos = altstr ; *pos ; pos++ ) {
4353                 if( *pos == '\\' ) {
4354                         if( !*++pos ) {
4355                                 break;
4356                         }
4357                 } else if( *pos == '\'' ) {
4358                         count++;
4359                 }
4360         }
4361
4362         PRVM_G_FLOAT( OFS_RETURN ) = (float) (count / 2);
4363 }
4364
4365 /*
4366 ========================
4367 VM_altstr_prepare
4368
4369 string altstr_prepare(string)
4370 ========================
4371 */
4372 void VM_altstr_prepare(prvm_prog_t *prog)
4373 {
4374         char *out;
4375         const char *instr, *in;
4376         int size;
4377         char outstr[VM_STRINGTEMP_LENGTH];
4378
4379         VM_SAFEPARMCOUNT( 1, VM_altstr_prepare );
4380
4381         instr = PRVM_G_STRING( OFS_PARM0 );
4382
4383         for( out = outstr, in = instr, size = sizeof(outstr) - 1 ; size && *in ; size--, in++, out++ )
4384                 if( *in == '\'' ) {
4385                         *out++ = '\\';
4386                         *out = '\'';
4387                         size--;
4388                 } else
4389                         *out = *in;
4390         *out = 0;
4391
4392         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString(prog,  outstr );
4393 }
4394
4395 /*
4396 ========================
4397 VM_altstr_get
4398
4399 string altstr_get(string, float)
4400 ========================
4401 */
4402 void VM_altstr_get(prvm_prog_t *prog)
4403 {
4404         const char *altstr, *pos;
4405         char *out;
4406         int count, size;
4407         char outstr[VM_STRINGTEMP_LENGTH];
4408
4409         VM_SAFEPARMCOUNT( 2, VM_altstr_get );
4410
4411         altstr = PRVM_G_STRING( OFS_PARM0 );
4412
4413         count = (int)PRVM_G_FLOAT( OFS_PARM1 );
4414         count = count * 2 + 1;
4415
4416         for( pos = altstr ; *pos && count ; pos++ )
4417                 if( *pos == '\\' ) {
4418                         if( !*++pos )
4419                                 break;
4420                 } else if( *pos == '\'' )
4421                         count--;
4422
4423         if( !*pos ) {
4424                 PRVM_G_INT( OFS_RETURN ) = 0;
4425                 return;
4426         }
4427
4428         for( out = outstr, size = sizeof(outstr) - 1 ; size && *pos ; size--, pos++, out++ )
4429                 if( *pos == '\\' ) {
4430                         if( !*++pos )
4431                                 break;
4432                         *out = *pos;
4433                         size--;
4434                 } else if( *pos == '\'' )
4435                         break;
4436                 else
4437                         *out = *pos;
4438
4439         *out = 0;
4440         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString(prog,  outstr );
4441 }
4442
4443 /*
4444 ========================
4445 VM_altstr_set
4446
4447 string altstr_set(string altstr, float num, string set)
4448 ========================
4449 */
4450 void VM_altstr_set(prvm_prog_t *prog)
4451 {
4452     int num;
4453         const char *altstr, *str;
4454         const char *in;
4455         char *out;
4456         char outstr[VM_STRINGTEMP_LENGTH];
4457
4458         VM_SAFEPARMCOUNT( 3, VM_altstr_set );
4459
4460         altstr = PRVM_G_STRING( OFS_PARM0 );
4461
4462         num = (int)PRVM_G_FLOAT( OFS_PARM1 );
4463
4464         str = PRVM_G_STRING( OFS_PARM2 );
4465
4466         out = outstr;
4467         for( num = num * 2 + 1, in = altstr; *in && num; *out++ = *in++ )
4468                 if( *in == '\\' ) {
4469                         if( !*++in ) {
4470                                 break;
4471                         }
4472                 } else if( *in == '\'' ) {
4473                         num--;
4474                 }
4475
4476         // copy set in
4477         for( ; *str; *out++ = *str++ );
4478         // now jump over the old content
4479         for( ; *in ; in++ )
4480                 if( *in == '\'' || (*in == '\\' && !*++in) )
4481                         break;
4482
4483         strlcpy(out, in, outstr + sizeof(outstr) - out);
4484         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString(prog,  outstr );
4485 }
4486
4487 /*
4488 ========================
4489 VM_altstr_ins
4490 insert after num
4491 string  altstr_ins(string altstr, float num, string set)
4492 ========================
4493 */
4494 void VM_altstr_ins(prvm_prog_t *prog)
4495 {
4496         int num;
4497         const char *set;
4498         const char *in;