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