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