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