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