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