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