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