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