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