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