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