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