added DP_ASINACOSATANATAN2TAN extension which adds common trig functions missing...
[xonotic/darkplaces.git] / prvm_cmds.c
1 // AK
2 // Basically every vm builtin cmd should be in here.
3 // All 3 builtin and extension lists can be found here
4 // cause large (I think they will) parts are from pr_cmds the same copyright like in pr_cmds
5 // also applies here
6
7 #include "prvm_cmds.h"
8
9 // 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);
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 /*
1791 =========
1792 VM_strcat
1793
1794 string strcat(string,string,...[string])
1795 =========
1796 */
1797 //string(string s1, string s2) strcat = #115;
1798 // concatenates two strings (for example "abc", "def" would return "abcdef")
1799 // and returns as a tempstring
1800 void VM_strcat(void)
1801 {
1802         char *s;
1803
1804         if(prog->argc < 1)
1805                 PRVM_ERROR("VM_strcat wrong parameter count (min. 1 expected ) !");
1806
1807         s = VM_GetTempString();
1808         VM_VarString(0, s, VM_STRINGTEMP_LENGTH);
1809         PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(s);
1810 }
1811
1812 /*
1813 =========
1814 VM_substring
1815
1816 string  substring(string s, float start, float length)
1817 =========
1818 */
1819 // string(string s, float start, float length) substring = #116;
1820 // returns a section of a string as a tempstring
1821 void VM_substring(void)
1822 {
1823         int i, start, length;
1824         const char *s;
1825         char *string;
1826
1827         VM_SAFEPARMCOUNT(3,VM_substring);
1828
1829         string = VM_GetTempString();
1830         s = PRVM_G_STRING(OFS_PARM0);
1831         start = (int)PRVM_G_FLOAT(OFS_PARM1);
1832         length = (int)PRVM_G_FLOAT(OFS_PARM2);
1833         if (!s)
1834                 s = "";
1835         for (i = 0;i < start && *s;i++, s++);
1836         for (i = 0;i < VM_STRINGTEMP_LENGTH - 1 && *s && i < length;i++, s++)
1837                 string[i] = *s;
1838         string[i] = 0;
1839         PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(string);
1840 }
1841
1842 /*
1843 =========
1844 VM_stov
1845
1846 vector  stov(string s)
1847 =========
1848 */
1849 //vector(string s) stov = #117; // returns vector value from a string
1850 void VM_stov(void)
1851 {
1852         char string[VM_STRINGTEMP_LENGTH];
1853
1854         VM_SAFEPARMCOUNT(1,VM_stov);
1855
1856         VM_VarString(0, string, sizeof(string));
1857         Math_atov(string, PRVM_G_VECTOR(OFS_RETURN));
1858 }
1859
1860 /*
1861 =========
1862 VM_strzone
1863
1864 string  strzone(string s)
1865 =========
1866 */
1867 //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)
1868 void VM_strzone(void)
1869 {
1870         char *out;
1871         char string[VM_STRINGTEMP_LENGTH];
1872         size_t alloclen;
1873
1874         VM_SAFEPARMCOUNT(1,VM_strzone);
1875
1876         VM_VarString(0, string, sizeof(string));
1877         alloclen = strlen(string) + 1;
1878         PRVM_G_INT(OFS_RETURN) = PRVM_AllocString(alloclen, &out);
1879         memcpy(out, string, alloclen);
1880 }
1881
1882 /*
1883 =========
1884 VM_strunzone
1885
1886 strunzone(string s)
1887 =========
1888 */
1889 //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!!!)
1890 void VM_strunzone(void)
1891 {
1892         VM_SAFEPARMCOUNT(1,VM_strunzone);
1893         PRVM_FreeString(PRVM_G_INT(OFS_PARM0));
1894 }
1895
1896 /*
1897 =========
1898 VM_command (used by client and menu)
1899
1900 clientcommand(float client, string s) (for client and menu)
1901 =========
1902 */
1903 //void(entity e, string s) clientcommand = #440; // executes a command string as if it came from the specified client
1904 //this function originally written by KrimZon, made shorter by LordHavoc
1905 void VM_clcommand (void)
1906 {
1907         client_t *temp_client;
1908         int i;
1909
1910         VM_SAFEPARMCOUNT(2,VM_clcommand);
1911
1912         i = (int)PRVM_G_FLOAT(OFS_PARM0);
1913         if (!sv.active  || i < 0 || i >= svs.maxclients || !svs.clients[i].active)
1914         {
1915                 VM_Warning("VM_clientcommand: %s: invalid client/server is not active !\n", PRVM_NAME);
1916                 return;
1917         }
1918
1919         temp_client = host_client;
1920         host_client = svs.clients + i;
1921         Cmd_ExecuteString (PRVM_G_STRING(OFS_PARM1), src_client);
1922         host_client = temp_client;
1923 }
1924
1925
1926 /*
1927 =========
1928 VM_tokenize
1929
1930 float tokenize(string s)
1931 =========
1932 */
1933 //float(string s) tokenize = #441; // takes apart a string into individal words (access them with argv), returns how many
1934 //this function originally written by KrimZon, made shorter by LordHavoc
1935 //20040203: rewritten by LordHavoc (no longer uses allocations)
1936 int num_tokens = 0;
1937 char *tokens[256], tokenbuf[MAX_INPUTLINE];
1938 void VM_tokenize (void)
1939 {
1940         size_t pos;
1941         const char *p;
1942
1943         VM_SAFEPARMCOUNT(1,VM_tokenize);
1944
1945         p = PRVM_G_STRING(OFS_PARM0);
1946
1947         num_tokens = 0;
1948         pos = 0;
1949         while(COM_ParseToken(&p, false))
1950         {
1951                 size_t tokenlen;
1952                 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
1953                         break;
1954                 tokenlen = strlen(com_token) + 1;
1955                 if (pos + tokenlen > sizeof(tokenbuf))
1956                         break;
1957                 tokens[num_tokens++] = tokenbuf + pos;
1958                 memcpy(tokenbuf + pos, com_token, tokenlen);
1959                 pos += tokenlen;
1960         }
1961
1962         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
1963 }
1964
1965 //string(float n) argv = #442; // returns a word from the tokenized string (returns nothing for an invalid index)
1966 //this function originally written by KrimZon, made shorter by LordHavoc
1967 void VM_argv (void)
1968 {
1969         int token_num;
1970
1971         VM_SAFEPARMCOUNT(1,VM_argv);
1972
1973         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
1974
1975         if (token_num >= 0 && token_num < num_tokens)
1976                 PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(tokens[token_num]);
1977         else
1978                 PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(NULL);
1979 }
1980
1981 /*
1982 //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)
1983 void PF_setattachment (void)
1984 {
1985         prvm_edict_t *e = PRVM_G_EDICT(OFS_PARM0);
1986         prvm_edict_t *tagentity = PRVM_G_EDICT(OFS_PARM1);
1987         char *tagname = PRVM_G_STRING(OFS_PARM2);
1988         prvm_eval_t *v;
1989         int i, modelindex;
1990         model_t *model;
1991
1992         if (tagentity == NULL)
1993                 tagentity = prog->edicts;
1994
1995         v = PRVM_GETEDICTFIELDVALUE(e, eval_tag_entity);
1996         if (v)
1997                 fields.server->edict = PRVM_EDICT_TO_PROG(tagentity);
1998
1999         v = PRVM_GETEDICTFIELDVALUE(e, eval_tag_index);
2000         if (v)
2001                 fields.server->_float = 0;
2002         if (tagentity != NULL && tagentity != prog->edicts && tagname && tagname[0])
2003         {
2004                 modelindex = (int)tagentity->fields.server->modelindex;
2005                 if (modelindex >= 0 && modelindex < MAX_MODELS)
2006                 {
2007                         model = sv.models[modelindex];
2008                         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)
2009                                 for (i = 0;i < model->data_overridetagnamesforskin[(unsigned int)tagentity->fields.server->skin].num_overridetagnames;i++)
2010                                         if (!strcmp(tagname, model->data_overridetagnamesforskin[(unsigned int)tagentity->fields.server->skin].data_overridetagnames[i].name))
2011                                                 fields.server->_float = i + 1;
2012                         // FIXME: use a model function to get tag info (need to handle skeletal)
2013                         if (fields.server->_float == 0 && model->num_tags)
2014                                 for (i = 0;i < model->num_tags;i++)
2015                                         if (!strcmp(tagname, model->data_tags[i].name))
2016                                                 fields.server->_float = i + 1;
2017                         if (fields.server->_float == 0)
2018                                 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);
2019                 }
2020                 else
2021                         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));
2022         }
2023 }*/
2024
2025 /*
2026 =========
2027 VM_isserver
2028
2029 float   isserver()
2030 =========
2031 */
2032 void VM_isserver(void)
2033 {
2034         VM_SAFEPARMCOUNT(0,VM_serverstate);
2035
2036         PRVM_G_FLOAT(OFS_RETURN) = sv.active;
2037 }
2038
2039 /*
2040 =========
2041 VM_clientcount
2042
2043 float   clientcount()
2044 =========
2045 */
2046 void VM_clientcount(void)
2047 {
2048         VM_SAFEPARMCOUNT(0,VM_clientcount);
2049
2050         PRVM_G_FLOAT(OFS_RETURN) = svs.maxclients;
2051 }
2052
2053 /*
2054 =========
2055 VM_clientstate
2056
2057 float   clientstate()
2058 =========
2059 */
2060 void VM_clientstate(void)
2061 {
2062         VM_SAFEPARMCOUNT(0,VM_clientstate);
2063
2064         PRVM_G_FLOAT(OFS_RETURN) = cls.state;
2065 }
2066
2067 /*
2068 =========
2069 VM_getostype
2070
2071 float   getostype(void)
2072 =========
2073 */ // not used at the moment -> not included in the common list
2074 void VM_getostype(void)
2075 {
2076         VM_SAFEPARMCOUNT(0,VM_getostype);
2077
2078         /*
2079         OS_WINDOWS
2080         OS_LINUX
2081         OS_MAC - not supported
2082         */
2083
2084 #ifdef WIN32
2085         PRVM_G_FLOAT(OFS_RETURN) = 0;
2086 #elif defined(MACOSX)
2087         PRVM_G_FLOAT(OFS_RETURN) = 2;
2088 #else
2089         PRVM_G_FLOAT(OFS_RETURN) = 1;
2090 #endif
2091 }
2092
2093 /*
2094 =========
2095 VM_getmousepos
2096
2097 vector  getmousepos()
2098 =========
2099 */
2100 void VM_getmousepos(void)
2101 {
2102
2103         VM_SAFEPARMCOUNT(0,VM_getmousepos);
2104
2105         PRVM_G_VECTOR(OFS_RETURN)[0] = in_mouse_x * vid_conwidth.integer / vid.width;
2106         PRVM_G_VECTOR(OFS_RETURN)[1] = in_mouse_y * vid_conheight.integer / vid.height;
2107         PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
2108 }
2109
2110 /*
2111 =========
2112 VM_gettime
2113
2114 float   gettime(void)
2115 =========
2116 */
2117 void VM_gettime(void)
2118 {
2119         VM_SAFEPARMCOUNT(0,VM_gettime);
2120
2121         PRVM_G_FLOAT(OFS_RETURN) = (float) *prog->time;
2122 }
2123
2124 /*
2125 =========
2126 VM_loadfromdata
2127
2128 loadfromdata(string data)
2129 =========
2130 */
2131 void VM_loadfromdata(void)
2132 {
2133         VM_SAFEPARMCOUNT(1,VM_loadentsfromfile);
2134
2135         PRVM_ED_LoadFromFile(PRVM_G_STRING(OFS_PARM0));
2136 }
2137
2138 /*
2139 ========================
2140 VM_parseentitydata
2141
2142 parseentitydata(entity ent, string data)
2143 ========================
2144 */
2145 void VM_parseentitydata(void)
2146 {
2147         prvm_edict_t *ent;
2148         const char *data;
2149
2150         VM_SAFEPARMCOUNT(2, VM_parseentitydata);
2151
2152     // get edict and test it
2153         ent = PRVM_G_EDICT(OFS_PARM0);
2154         if (ent->priv.required->free)
2155                 PRVM_ERROR ("VM_parseentitydata: %s: Can only set already spawned entities (entity %i is free)!", PRVM_NAME, PRVM_NUM_FOR_EDICT(ent));
2156
2157         data = PRVM_G_STRING(OFS_PARM1);
2158
2159     // parse the opening brace
2160         if (!COM_ParseTokenConsole(&data) || com_token[0] != '{' )
2161                 PRVM_ERROR ("VM_parseentitydata: %s: Couldn't parse entity data:\n%s", PRVM_NAME, data );
2162
2163         PRVM_ED_ParseEdict (data, ent);
2164 }
2165
2166 /*
2167 =========
2168 VM_loadfromfile
2169
2170 loadfromfile(string file)
2171 =========
2172 */
2173 void VM_loadfromfile(void)
2174 {
2175         const char *filename;
2176         char *data;
2177
2178         VM_SAFEPARMCOUNT(1,VM_loadfromfile);
2179
2180         filename = PRVM_G_STRING(OFS_PARM0);
2181         // .. is parent directory on many platforms
2182         // / is parent directory on Amiga
2183         // : is root of drive on Amiga (also used as a directory separator on Mac, but / works there too, so that's a bad idea)
2184         // \ is a windows-ism (so it's naughty to use it, / works on all platforms)
2185         if ((filename[0] == '.' && filename[1] == '.') || filename[0] == '/' || strrchr(filename, ':') || strrchr(filename, '\\'))
2186         {
2187                 PRVM_G_FLOAT(OFS_RETURN) = -4;
2188                 VM_Warning("VM_loadfromfile: %s dangerous or non-portable filename \"%s\" not allowed. (contains : or \\ or begins with .. or /)\n", PRVM_NAME, filename);
2189                 return;
2190         }
2191
2192         // not conform with VM_fopen
2193         data = (char *)FS_LoadFile(filename, tempmempool, false, NULL);
2194         if (data == NULL)
2195                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2196
2197         PRVM_ED_LoadFromFile(data);
2198
2199         if(data)
2200                 Mem_Free(data);
2201 }
2202
2203
2204 /*
2205 =========
2206 VM_modulo
2207
2208 float   mod(float val, float m)
2209 =========
2210 */
2211 void VM_modulo(void)
2212 {
2213         int val, m;
2214         VM_SAFEPARMCOUNT(2,VM_module);
2215
2216         val = (int) PRVM_G_FLOAT(OFS_PARM0);
2217         m       = (int) PRVM_G_FLOAT(OFS_PARM1);
2218
2219         PRVM_G_FLOAT(OFS_RETURN) = (float) (val % m);
2220 }
2221
2222 void VM_Search_Init(void)
2223 {
2224         int i;
2225         for (i = 0;i < PRVM_MAX_OPENSEARCHES;i++)
2226                 prog->opensearches[i] = NULL;
2227 }
2228
2229 void VM_Search_Reset(void)
2230 {
2231         int i;
2232         // reset the fssearch list
2233         for(i = 0; i < PRVM_MAX_OPENSEARCHES; i++)
2234         {
2235                 if(prog->opensearches[i])
2236                         FS_FreeSearch(prog->opensearches[i]);
2237                 prog->opensearches[i] = NULL;
2238         }
2239 }
2240
2241 /*
2242 =========
2243 VM_search_begin
2244
2245 float search_begin(string pattern, float caseinsensitive, float quiet)
2246 =========
2247 */
2248 void VM_search_begin(void)
2249 {
2250         int handle;
2251         const char *pattern;
2252         int caseinsens, quiet;
2253
2254         VM_SAFEPARMCOUNT(3, VM_search_begin);
2255
2256         pattern = PRVM_G_STRING(OFS_PARM0);
2257
2258         VM_CheckEmptyString(pattern);
2259
2260         caseinsens = (int)PRVM_G_FLOAT(OFS_PARM1);
2261         quiet = (int)PRVM_G_FLOAT(OFS_PARM2);
2262
2263         for(handle = 0; handle < PRVM_MAX_OPENSEARCHES; handle++)
2264                 if(!prog->opensearches[handle])
2265                         break;
2266
2267         if(handle >= PRVM_MAX_OPENSEARCHES)
2268         {
2269                 PRVM_G_FLOAT(OFS_RETURN) = -2;
2270                 VM_Warning("VM_search_begin: %s ran out of search handles (%i)\n", PRVM_NAME, PRVM_MAX_OPENSEARCHES);
2271                 return;
2272         }
2273
2274         if(!(prog->opensearches[handle] = FS_Search(pattern,caseinsens, quiet)))
2275                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2276         else
2277                 PRVM_G_FLOAT(OFS_RETURN) = handle;
2278 }
2279
2280 /*
2281 =========
2282 VM_search_end
2283
2284 void    search_end(float handle)
2285 =========
2286 */
2287 void VM_search_end(void)
2288 {
2289         int handle;
2290         VM_SAFEPARMCOUNT(1, VM_search_end);
2291
2292         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
2293
2294         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
2295         {
2296                 VM_Warning("VM_search_end: invalid handle %i used in %s\n", handle, PRVM_NAME);
2297                 return;
2298         }
2299         if(prog->opensearches[handle] == NULL)
2300         {
2301                 VM_Warning("VM_search_end: no such handle %i in %s\n", handle, PRVM_NAME);
2302                 return;
2303         }
2304
2305         FS_FreeSearch(prog->opensearches[handle]);
2306         prog->opensearches[handle] = NULL;
2307 }
2308
2309 /*
2310 =========
2311 VM_search_getsize
2312
2313 float   search_getsize(float handle)
2314 =========
2315 */
2316 void VM_search_getsize(void)
2317 {
2318         int handle;
2319         VM_SAFEPARMCOUNT(1, VM_M_search_getsize);
2320
2321         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
2322
2323         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
2324         {
2325                 VM_Warning("VM_search_getsize: invalid handle %i used in %s\n", handle, PRVM_NAME);
2326                 return;
2327         }
2328         if(prog->opensearches[handle] == NULL)
2329         {
2330                 VM_Warning("VM_search_getsize: no such handle %i in %s\n", handle, PRVM_NAME);
2331                 return;
2332         }
2333
2334         PRVM_G_FLOAT(OFS_RETURN) = prog->opensearches[handle]->numfilenames;
2335 }
2336
2337 /*
2338 =========
2339 VM_search_getfilename
2340
2341 string  search_getfilename(float handle, float num)
2342 =========
2343 */
2344 void VM_search_getfilename(void)
2345 {
2346         int handle, filenum;
2347         char *tmp;
2348         VM_SAFEPARMCOUNT(2, VM_search_getfilename);
2349
2350         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
2351         filenum = (int)PRVM_G_FLOAT(OFS_PARM1);
2352
2353         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
2354         {
2355                 VM_Warning("VM_search_getfilename: invalid handle %i used in %s\n", handle, PRVM_NAME);
2356                 return;
2357         }
2358         if(prog->opensearches[handle] == NULL)
2359         {
2360                 VM_Warning("VM_search_getfilename: no such handle %i in %s\n", handle, PRVM_NAME);
2361                 return;
2362         }
2363         if(filenum < 0 || filenum >= prog->opensearches[handle]->numfilenames)
2364         {
2365                 VM_Warning("VM_search_getfilename: invalid filenum %i in %s\n", filenum, PRVM_NAME);
2366                 return;
2367         }
2368
2369         tmp = VM_GetTempString();
2370         strlcpy(tmp, prog->opensearches[handle]->filenames[filenum], VM_STRINGTEMP_LENGTH);
2371
2372         PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(tmp);
2373 }
2374
2375 /*
2376 =========
2377 VM_chr
2378
2379 string  chr(float ascii)
2380 =========
2381 */
2382 void VM_chr(void)
2383 {
2384         char *tmp;
2385         VM_SAFEPARMCOUNT(1, VM_chr);
2386
2387         tmp = VM_GetTempString();
2388         tmp[0] = (unsigned char) PRVM_G_FLOAT(OFS_PARM0);
2389         tmp[1] = 0;
2390
2391         PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(tmp);
2392 }
2393
2394 //=============================================================================
2395 // Draw builtins (client & menu)
2396
2397 /*
2398 =========
2399 VM_iscachedpic
2400
2401 float   iscachedpic(string pic)
2402 =========
2403 */
2404 void VM_iscachedpic(void)
2405 {
2406         VM_SAFEPARMCOUNT(1,VM_iscachedpic);
2407
2408         // drawq hasnt such a function, thus always return true
2409         PRVM_G_FLOAT(OFS_RETURN) = false;
2410 }
2411
2412 /*
2413 =========
2414 VM_precache_pic
2415
2416 string  precache_pic(string pic)
2417 =========
2418 */
2419 void VM_precache_pic(void)
2420 {
2421         const char      *s;
2422
2423         VM_SAFEPARMCOUNT(1, VM_precache_pic);
2424
2425         s = PRVM_G_STRING(OFS_PARM0);
2426         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
2427
2428         if(!s)
2429                 PRVM_ERROR ("VM_precache_pic: %s: NULL", PRVM_NAME);
2430
2431         VM_CheckEmptyString (s);
2432
2433         // AK Draw_CachePic is supposed to always return a valid pointer
2434         if( Draw_CachePic(s, false)->tex == r_texture_notexture )
2435                 PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(NULL);
2436 }
2437
2438 /*
2439 =========
2440 VM_freepic
2441
2442 freepic(string s)
2443 =========
2444 */
2445 void VM_freepic(void)
2446 {
2447         const char *s;
2448
2449         VM_SAFEPARMCOUNT(1,VM_freepic);
2450
2451         s = PRVM_G_STRING(OFS_PARM0);
2452
2453         if(!s)
2454                 PRVM_ERROR ("VM_freepic: %s: NULL");
2455
2456         VM_CheckEmptyString (s);
2457
2458         Draw_FreePic(s);
2459 }
2460
2461 /*
2462 =========
2463 VM_drawcharacter
2464
2465 float   drawcharacter(vector position, float character, vector scale, vector rgb, float alpha, float flag)
2466 =========
2467 */
2468 void VM_drawcharacter(void)
2469 {
2470         float *pos,*scale,*rgb;
2471         char   character;
2472         int flag;
2473         VM_SAFEPARMCOUNT(6,VM_drawcharacter);
2474
2475         character = (char) PRVM_G_FLOAT(OFS_PARM1);
2476         if(character == 0)
2477         {
2478                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2479                 VM_Warning("VM_drawcharacter: %s passed null character !\n",PRVM_NAME);
2480                 return;
2481         }
2482
2483         pos = PRVM_G_VECTOR(OFS_PARM0);
2484         scale = PRVM_G_VECTOR(OFS_PARM2);
2485         rgb = PRVM_G_VECTOR(OFS_PARM3);
2486         flag = (int)PRVM_G_FLOAT(OFS_PARM5);
2487
2488         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
2489         {
2490                 PRVM_G_FLOAT(OFS_RETURN) = -2;
2491                 VM_Warning("VM_drawcharacter: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
2492                 return;
2493         }
2494
2495         if(pos[2] || scale[2])
2496                 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")));
2497
2498         if(!scale[0] || !scale[1])
2499         {
2500                 PRVM_G_FLOAT(OFS_RETURN) = -3;
2501                 VM_Warning("VM_drawcharacter: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
2502                 return;
2503         }
2504
2505         DrawQ_String (pos[0], pos[1], &character, 1, scale[0], scale[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag);
2506         PRVM_G_FLOAT(OFS_RETURN) = 1;
2507 }
2508
2509 /*
2510 =========
2511 VM_drawstring
2512
2513 float   drawstring(vector position, string text, vector scale, vector rgb, float alpha, float flag)
2514 =========
2515 */
2516 void VM_drawstring(void)
2517 {
2518         float *pos,*scale,*rgb;
2519         const char  *string;
2520         int flag;
2521         VM_SAFEPARMCOUNT(6,VM_drawstring);
2522
2523         string = PRVM_G_STRING(OFS_PARM1);
2524         if(!string)
2525         {
2526                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2527                 VM_Warning("VM_drawstring: %s passed null string !\n",PRVM_NAME);
2528                 return;
2529         }
2530
2531         //VM_CheckEmptyString(string); Why should it be checked - perhaps the menu wants to support the precolored letters, too?
2532
2533         pos = PRVM_G_VECTOR(OFS_PARM0);
2534         scale = PRVM_G_VECTOR(OFS_PARM2);
2535         rgb = PRVM_G_VECTOR(OFS_PARM3);
2536         flag = (int)PRVM_G_FLOAT(OFS_PARM5);
2537
2538         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
2539         {
2540                 PRVM_G_FLOAT(OFS_RETURN) = -2;
2541                 VM_Warning("VM_drawstring: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
2542                 return;
2543         }
2544
2545         if(!scale[0] || !scale[1])
2546         {
2547                 PRVM_G_FLOAT(OFS_RETURN) = -3;
2548                 VM_Warning("VM_drawstring: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
2549                 return;
2550         }
2551
2552         if(pos[2] || scale[2])
2553                 Con_Printf("VM_drawstring: z value%c from %s discarded\n",(pos[2] && scale[2]) ? 's' : 0,((pos[2] && scale[2]) ? "pos and scale" : (pos[2] ? "pos" : "scale")));
2554
2555         DrawQ_String (pos[0], pos[1], string, 0, scale[0], scale[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag);
2556         PRVM_G_FLOAT(OFS_RETURN) = 1;
2557 }
2558 /*
2559 =========
2560 VM_drawpic
2561
2562 float   drawpic(vector position, string pic, vector size, vector rgb, float alpha, float flag)
2563 =========
2564 */
2565 void VM_drawpic(void)
2566 {
2567         const char *picname;
2568         float *size, *pos, *rgb;
2569         int flag;
2570
2571         VM_SAFEPARMCOUNT(6,VM_drawpic);
2572
2573         picname = PRVM_G_STRING(OFS_PARM1);
2574
2575         if(!picname)
2576         {
2577                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2578                 VM_Warning("VM_drawpic: %s passed null picture name !\n", PRVM_NAME);
2579                 return;
2580         }
2581
2582         VM_CheckEmptyString (picname);
2583
2584         // is pic cached ? no function yet for that
2585         if(!1)
2586         {
2587                 PRVM_G_FLOAT(OFS_RETURN) = -4;
2588                 VM_Warning("VM_drawpic: %s: %s not cached !\n", PRVM_NAME, picname);
2589                 return;
2590         }
2591
2592         pos = PRVM_G_VECTOR(OFS_PARM0);
2593         size = PRVM_G_VECTOR(OFS_PARM2);
2594         rgb = PRVM_G_VECTOR(OFS_PARM3);
2595         flag = (int) PRVM_G_FLOAT(OFS_PARM5);
2596
2597         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
2598         {
2599                 PRVM_G_FLOAT(OFS_RETURN) = -2;
2600                 VM_Warning("VM_drawstring: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
2601                 return;
2602         }
2603
2604         if(pos[2] || size[2])
2605                 Con_Printf("VM_drawstring: z value%c from %s discarded\n",(pos[2] && size[2]) ? 's' : 0,((pos[2] && size[2]) ? "pos and size" : (pos[2] ? "pos" : "size")));
2606
2607         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);
2608         PRVM_G_FLOAT(OFS_RETURN) = 1;
2609 }
2610
2611 /*
2612 =========
2613 VM_drawfill
2614
2615 float drawfill(vector position, vector size, vector rgb, float alpha, float flag)
2616 =========
2617 */
2618 void VM_drawfill(void)
2619 {
2620         float *size, *pos, *rgb;
2621         int flag;
2622
2623         VM_SAFEPARMCOUNT(5,VM_drawfill);
2624
2625
2626         pos = PRVM_G_VECTOR(OFS_PARM0);
2627         size = PRVM_G_VECTOR(OFS_PARM1);
2628         rgb = PRVM_G_VECTOR(OFS_PARM2);
2629         flag = (int) PRVM_G_FLOAT(OFS_PARM4);
2630
2631         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
2632         {
2633                 PRVM_G_FLOAT(OFS_RETURN) = -2;
2634                 VM_Warning("VM_drawstring: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
2635                 return;
2636         }
2637
2638         if(pos[2] || size[2])
2639                 Con_Printf("VM_drawstring: z value%c from %s discarded\n",(pos[2] && size[2]) ? 's' : 0,((pos[2] && size[2]) ? "pos and size" : (pos[2] ? "pos" : "size")));
2640
2641         DrawQ_Pic(pos[0], pos[1], NULL, size[0], size[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM3), flag);
2642         PRVM_G_FLOAT(OFS_RETURN) = 1;
2643 }
2644
2645 /*
2646 =========
2647 VM_drawsetcliparea
2648
2649 drawsetcliparea(float x, float y, float width, float height)
2650 =========
2651 */
2652 void VM_drawsetcliparea(void)
2653 {
2654         float x,y,w,h;
2655         VM_SAFEPARMCOUNT(4,VM_drawsetcliparea);
2656
2657         x = bound(0, PRVM_G_FLOAT(OFS_PARM0), vid_conwidth.integer);
2658         y = bound(0, PRVM_G_FLOAT(OFS_PARM1), vid_conheight.integer);
2659         w = bound(0, PRVM_G_FLOAT(OFS_PARM2) + PRVM_G_FLOAT(OFS_PARM0) - x, (vid_conwidth.integer  - x));
2660         h = bound(0, PRVM_G_FLOAT(OFS_PARM3) + PRVM_G_FLOAT(OFS_PARM1) - y, (vid_conheight.integer - y));
2661
2662         DrawQ_SetClipArea(x, y, w, h);
2663 }
2664
2665 /*
2666 =========
2667 VM_drawresetcliparea
2668
2669 drawresetcliparea()
2670 =========
2671 */
2672 void VM_drawresetcliparea(void)
2673 {
2674         VM_SAFEPARMCOUNT(0,VM_drawresetcliparea);
2675
2676         DrawQ_ResetClipArea();
2677 }
2678
2679 /*
2680 =========
2681 VM_getimagesize
2682
2683 vector  getimagesize(string pic)
2684 =========
2685 */
2686 void VM_getimagesize(void)
2687 {
2688         const char *p;
2689         cachepic_t *pic;
2690
2691         VM_SAFEPARMCOUNT(1,VM_getimagesize);
2692
2693         p = PRVM_G_STRING(OFS_PARM0);
2694
2695         if(!p)
2696                 PRVM_ERROR("VM_getimagepos: %s passed null picture name !", PRVM_NAME);
2697
2698         VM_CheckEmptyString (p);
2699
2700         pic = Draw_CachePic (p, false);
2701
2702         PRVM_G_VECTOR(OFS_RETURN)[0] = pic->width;
2703         PRVM_G_VECTOR(OFS_RETURN)[1] = pic->height;
2704         PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
2705 }
2706
2707 /*
2708 =========
2709 VM_keynumtostring
2710
2711 string keynumtostring(float keynum)
2712 =========
2713 */
2714 void VM_keynumtostring (void)
2715 {
2716         int keynum;
2717         char *tmp;
2718         VM_SAFEPARMCOUNT(1, VM_keynumtostring);
2719
2720         keynum = (int)PRVM_G_FLOAT(OFS_PARM0);
2721
2722         tmp = VM_GetTempString();
2723
2724         strlcpy(tmp, Key_KeynumToString(keynum), VM_STRINGTEMP_LENGTH);
2725
2726         PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(tmp);
2727 }
2728
2729 /*
2730 =========
2731 VM_stringtokeynum
2732
2733 float stringtokeynum(string key)
2734 =========
2735 */
2736 void VM_stringtokeynum (void)
2737 {
2738         const char *str;
2739         VM_SAFEPARMCOUNT( 1, VM_keynumtostring );
2740
2741         str = PRVM_G_STRING( OFS_PARM0 );
2742
2743         PRVM_G_INT(OFS_RETURN) = Key_StringToKeynum( str );
2744 }
2745
2746 // CL_Video interface functions
2747
2748 /*
2749 ========================
2750 VM_cin_open
2751
2752 float cin_open(string file, string name)
2753 ========================
2754 */
2755 void VM_cin_open( void )
2756 {
2757         const char *file;
2758         const char *name;
2759
2760         VM_SAFEPARMCOUNT( 2, VM_cin_open );
2761
2762         file = PRVM_G_STRING( OFS_PARM0 );
2763         name = PRVM_G_STRING( OFS_PARM1 );
2764
2765         VM_CheckEmptyString( file );
2766     VM_CheckEmptyString( name );
2767
2768         if( CL_OpenVideo( file, name, MENUOWNER ) )
2769                 PRVM_G_FLOAT( OFS_RETURN ) = 1;
2770         else
2771                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
2772 }
2773
2774 /*
2775 ========================
2776 VM_cin_close
2777
2778 void cin_close(string name)
2779 ========================
2780 */
2781 void VM_cin_close( void )
2782 {
2783         const char *name;
2784
2785         VM_SAFEPARMCOUNT( 1, VM_cin_close );
2786
2787         name = PRVM_G_STRING( OFS_PARM0 );
2788         VM_CheckEmptyString( name );
2789
2790         CL_CloseVideo( CL_GetVideoByName( name ) );
2791 }
2792
2793 /*
2794 ========================
2795 VM_cin_setstate
2796 void cin_setstate(string name, float type)
2797 ========================
2798 */
2799 void VM_cin_setstate( void )
2800 {
2801         const char *name;
2802         clvideostate_t  state;
2803         clvideo_t               *video;
2804
2805         VM_SAFEPARMCOUNT( 2, VM_cin_netstate );
2806
2807         name = PRVM_G_STRING( OFS_PARM0 );
2808         VM_CheckEmptyString( name );
2809
2810         state = (clvideostate_t)((int)PRVM_G_FLOAT( OFS_PARM1 ));
2811
2812         video = CL_GetVideoByName( name );
2813         if( video && state > CLVIDEO_UNUSED && state < CLVIDEO_STATECOUNT )
2814                 CL_SetVideoState( video, state );
2815 }
2816
2817 /*
2818 ========================
2819 VM_cin_getstate
2820
2821 float cin_getstate(string name)
2822 ========================
2823 */
2824 void VM_cin_getstate( void )
2825 {
2826         const char *name;
2827         clvideo_t               *video;
2828
2829         VM_SAFEPARMCOUNT( 1, VM_cin_getstate );
2830
2831         name = PRVM_G_STRING( OFS_PARM0 );
2832         VM_CheckEmptyString( name );
2833
2834         video = CL_GetVideoByName( name );
2835         if( video )
2836                 PRVM_G_FLOAT( OFS_RETURN ) = (int)video->state;
2837         else
2838                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
2839 }
2840
2841 /*
2842 ========================
2843 VM_cin_restart
2844
2845 void cin_restart(string name)
2846 ========================
2847 */
2848 void VM_cin_restart( void )
2849 {
2850         const char *name;
2851         clvideo_t               *video;
2852
2853         VM_SAFEPARMCOUNT( 1, VM_cin_restart );
2854
2855         name = PRVM_G_STRING( OFS_PARM0 );
2856         VM_CheckEmptyString( name );
2857
2858         video = CL_GetVideoByName( name );
2859         if( video )
2860                 CL_RestartVideo( video );
2861 }
2862
2863 /*
2864 ==============
2865 VM_vectorvectors
2866
2867 Writes new values for v_forward, v_up, and v_right based on the given forward vector
2868 vectorvectors(vector, vector)
2869 ==============
2870 */
2871 void VM_vectorvectors (void)
2872 {
2873         VectorNormalize2(PRVM_G_VECTOR(OFS_PARM0), prog->globals.server->v_forward);
2874         VectorVectors(prog->globals.server->v_forward, prog->globals.server->v_right, prog->globals.server->v_up);
2875 }
2876
2877 /*
2878 ========================
2879 VM_drawline
2880
2881 void drawline(float width, vector pos1, vector pos2, vector rgb, float alpha, float flags)
2882 ========================
2883 */
2884 void VM_drawline (void)
2885 {
2886         float   *c1, *c2, *rgb;
2887         float   alpha, width;
2888         unsigned char   flags;
2889
2890         VM_SAFEPARMCOUNT(6, VM_drawline);
2891         width   = PRVM_G_FLOAT(OFS_PARM0);
2892         c1              = PRVM_G_VECTOR(OFS_PARM1);
2893         c2              = PRVM_G_VECTOR(OFS_PARM2);
2894         rgb             = PRVM_G_VECTOR(OFS_PARM3);
2895         alpha   = PRVM_G_FLOAT(OFS_PARM4);
2896         flags   = (int)PRVM_G_FLOAT(OFS_PARM5);
2897         DrawQ_Line(width, c1[0], c1[1], c2[0], c2[1], rgb[0], rgb[1], rgb[2], alpha, flags);
2898 }
2899
2900 //====================
2901 //QC POLYGON functions
2902 //====================
2903
2904 typedef struct
2905 {
2906         rtexture_t              *tex;
2907         float                   data[36];       //[515]: enough for polygons
2908         unsigned char                   flags;  //[515]: + VM_POLYGON_2D and VM_POLYGON_FL4V flags
2909 }vm_polygon_t;
2910
2911 //static float                  vm_polygon_linewidth = 1;
2912 static mempool_t                *vm_polygons_pool = NULL;
2913 static unsigned char                    vm_current_vertices = 0;
2914 static qboolean                 vm_polygons_initialized = false;
2915 static vm_polygon_t             *vm_polygons = NULL;
2916 static unsigned long    vm_polygons_num = 0, vm_drawpolygons_num = 0;   //[515]: ok long on 64bit ?
2917 static qboolean                 vm_polygonbegin = false;        //[515]: for "no-crap-on-the-screen" check
2918 #define VM_DEFPOLYNUM 64        //[515]: enough for default ?
2919
2920 #define VM_POLYGON_FL3V         16      //more than 2 vertices (used only for lines)
2921 #define VM_POLYGON_FLLINES      32
2922 #define VM_POLYGON_FL2D         64
2923 #define VM_POLYGON_FL4V         128     //4 vertices
2924
2925 void VM_InitPolygons (void)
2926 {
2927         vm_polygons_pool = Mem_AllocPool("VMPOLY", 0, NULL);
2928         vm_polygons = (vm_polygon_t *)Mem_Alloc(vm_polygons_pool, VM_DEFPOLYNUM*sizeof(vm_polygon_t));
2929         memset(vm_polygons, 0, VM_DEFPOLYNUM*sizeof(vm_polygon_t));
2930         vm_polygons_num = VM_DEFPOLYNUM;
2931         vm_drawpolygons_num = 0;
2932         vm_polygonbegin = false;
2933         vm_polygons_initialized = true;
2934 }
2935
2936 void VM_DrawPolygonCallback (const entity_render_t *ent, const rtlight_t *rtlight, int numsurfaces, int *surfacelist)
2937 {
2938         int surfacelistindex;
2939         // LordHavoc: FIXME: this is stupid code
2940         for (surfacelistindex = 0;surfacelistindex < numsurfaces;surfacelistindex++)
2941         {
2942                 const vm_polygon_t      *p = &vm_polygons[surfacelist[surfacelistindex]];
2943                 int                                     flags = p->flags & 0x0f;
2944
2945                 if(flags == DRAWFLAG_ADDITIVE)
2946                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE);
2947                 else if(flags == DRAWFLAG_MODULATE)
2948                         GL_BlendFunc(GL_DST_COLOR, GL_ZERO);
2949                 else if(flags == DRAWFLAG_2XMODULATE)
2950                         GL_BlendFunc(GL_DST_COLOR,GL_SRC_COLOR);
2951                 else
2952                         GL_BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2953
2954                 R_Mesh_TexBind(0, R_GetTexture(p->tex));
2955
2956                 CHECKGLERROR
2957                 //[515]: is speed is max ?
2958                 if(p->flags & VM_POLYGON_FLLINES)       //[515]: lines
2959                 {
2960                         qglLineWidth(p->data[13]);CHECKGLERROR
2961                         qglBegin(GL_LINE_LOOP);
2962                                 qglTexCoord1f   (p->data[12]);
2963                                 qglColor4f              (p->data[20], p->data[21], p->data[22], p->data[23]);
2964                                 qglVertex3f             (p->data[0] , p->data[1],  p->data[2]);
2965
2966                                 qglTexCoord1f   (p->data[14]);
2967                                 qglColor4f              (p->data[24], p->data[25], p->data[26], p->data[27]);
2968                                 qglVertex3f             (p->data[3] , p->data[4],  p->data[5]);
2969
2970                                 if(p->flags & VM_POLYGON_FL3V)
2971                                 {
2972                                         qglTexCoord1f   (p->data[16]);
2973                                         qglColor4f              (p->data[28], p->data[29], p->data[30], p->data[31]);
2974                                         qglVertex3f             (p->data[6] , p->data[7],  p->data[8]);
2975
2976                                         if(p->flags & VM_POLYGON_FL4V)
2977                                         {
2978                                                 qglTexCoord1f   (p->data[18]);
2979                                                 qglColor4f              (p->data[32], p->data[33], p->data[34], p->data[35]);
2980                                                 qglVertex3f             (p->data[9] , p->data[10],  p->data[11]);
2981                                         }
2982                                 }
2983                         qglEnd();
2984                         CHECKGLERROR
2985                 }
2986                 else
2987                 {
2988                         qglBegin(GL_POLYGON);
2989                                 qglTexCoord2f   (p->data[12], p->data[13]);
2990                                 qglColor4f              (p->data[20], p->data[21], p->data[22], p->data[23]);
2991                                 qglVertex3f             (p->data[0] , p->data[1],  p->data[2]);
2992
2993                                 qglTexCoord2f   (p->data[14], p->data[15]);
2994                                 qglColor4f              (p->data[24], p->data[25], p->data[26], p->data[27]);
2995                                 qglVertex3f             (p->data[3] , p->data[4],  p->data[5]);
2996
2997                                 qglTexCoord2f   (p->data[16], p->data[17]);
2998                                 qglColor4f              (p->data[28], p->data[29], p->data[30], p->data[31]);
2999                                 qglVertex3f             (p->data[6] , p->data[7],  p->data[8]);
3000
3001                                 if(p->flags & VM_POLYGON_FL4V)
3002                                 {
3003                                         qglTexCoord2f   (p->data[18], p->data[19]);
3004                                         qglColor4f              (p->data[32], p->data[33], p->data[34], p->data[35]);
3005                                         qglVertex3f             (p->data[9] , p->data[10],  p->data[11]);
3006                                 }
3007                         qglEnd();
3008                         CHECKGLERROR
3009                 }
3010         }
3011 }
3012
3013 void VM_AddPolygonTo2DScene (vm_polygon_t *p)
3014 {
3015         drawqueuemesh_t mesh;
3016         static int              picelements[6] = {0, 1, 2, 0, 2, 3};
3017
3018         mesh.texture = p->tex;
3019         mesh.data_element3i = picelements;
3020         mesh.data_vertex3f = p->data;
3021         mesh.data_texcoord2f = p->data + 12;
3022         mesh.data_color4f = p->data + 20;
3023         if(p->flags & VM_POLYGON_FL4V)
3024         {
3025                 mesh.num_vertices = 4;
3026                 mesh.num_triangles = 2;
3027         }
3028         else
3029         {
3030                 mesh.num_vertices = 3;
3031                 mesh.num_triangles = 1;
3032         }
3033         if(p->flags & VM_POLYGON_FLLINES)       //[515]: lines
3034                 DrawQ_LineLoop (&mesh, (p->flags&0x0f));
3035         else
3036                 DrawQ_Mesh (&mesh, (p->flags&0x0f));
3037 }
3038
3039 //void(string texturename, float flag, float 2d, float lines) R_BeginPolygon
3040 void VM_R_PolygonBegin (void)
3041 {
3042         vm_polygon_t    *p;
3043         const char              *picname;
3044         if(prog->argc < 2)
3045                 VM_SAFEPARMCOUNT(2, VM_R_PolygonBegin);
3046
3047         if(!vm_polygons_initialized)
3048                 VM_InitPolygons();
3049         if(vm_polygonbegin)
3050         {
3051                 VM_Warning("VM_R_PolygonBegin: called twice without VM_R_PolygonEnd after first\n");
3052                 return;
3053         }
3054         if(vm_drawpolygons_num >= vm_polygons_num)
3055         {
3056                 p = (vm_polygon_t *)Mem_Alloc(vm_polygons_pool, 2 * vm_polygons_num * sizeof(vm_polygon_t));
3057                 memset(p, 0, 2 * vm_polygons_num * sizeof(vm_polygon_t));
3058                 memcpy(p, vm_polygons, vm_polygons_num * sizeof(vm_polygon_t));
3059                 Mem_Free(vm_polygons);
3060                 vm_polygons = p;
3061                 vm_polygons_num *= 2;
3062         }
3063         p = &vm_polygons[vm_drawpolygons_num];
3064         picname = PRVM_G_STRING(OFS_PARM0);
3065         if(picname[0])
3066                 p->tex = Draw_CachePic(picname, true)->tex;
3067         else
3068                 p->tex = r_texture_white;
3069         p->flags = (unsigned char)PRVM_G_FLOAT(OFS_PARM1);
3070         vm_current_vertices = 0;
3071         vm_polygonbegin = true;
3072         if(prog->argc >= 3)
3073         {
3074                 if(PRVM_G_FLOAT(OFS_PARM2))
3075                         p->flags |= VM_POLYGON_FL2D;
3076                 if(prog->argc >= 4 && PRVM_G_FLOAT(OFS_PARM3))
3077                 {
3078                         p->data[13] = PRVM_G_FLOAT(OFS_PARM3);  //[515]: linewidth
3079                         p->flags |= VM_POLYGON_FLLINES;
3080                 }
3081         }
3082 }
3083
3084 //void(vector org, vector texcoords, vector rgb, float alpha) R_PolygonVertex
3085 void VM_R_PolygonVertex (void)
3086 {
3087         float                   *coords, *tx, *rgb, alpha;
3088         vm_polygon_t    *p;
3089         VM_SAFEPARMCOUNT(4, VM_R_PolygonVertex);
3090
3091         if(!vm_polygonbegin)
3092         {
3093                 VM_Warning("VM_R_PolygonVertex: VM_R_PolygonBegin wasn't called\n");
3094                 return;
3095         }
3096         coords  = PRVM_G_VECTOR(OFS_PARM0);
3097         tx              = PRVM_G_VECTOR(OFS_PARM1);
3098         rgb             = PRVM_G_VECTOR(OFS_PARM2);
3099         alpha = PRVM_G_FLOAT(OFS_PARM3);
3100
3101         p = &vm_polygons[vm_drawpolygons_num];
3102         if(vm_current_vertices > 4)
3103         {
3104                 VM_Warning("VM_R_PolygonVertex: may have 4 vertices max\n");
3105                 return;
3106         }
3107
3108         p->data[vm_current_vertices*3]          = coords[0];
3109         p->data[1+vm_current_vertices*3]        = coords[1];
3110         p->data[2+vm_current_vertices*3]        = coords[2];
3111
3112         p->data[12+vm_current_vertices*2]       = tx[0];
3113         if(!(p->flags & VM_POLYGON_FLLINES))
3114                 p->data[13+vm_current_vertices*2]       = tx[1];
3115
3116         p->data[20+vm_current_vertices*4]       = rgb[0];
3117         p->data[21+vm_current_vertices*4]       = rgb[1];
3118         p->data[22+vm_current_vertices*4]       = rgb[2];
3119         p->data[23+vm_current_vertices*4]       = alpha;
3120
3121         vm_current_vertices++;
3122         if(vm_current_vertices == 4)
3123                 p->flags |= VM_POLYGON_FL4V;
3124         else
3125                 if(vm_current_vertices == 3)
3126                         p->flags |= VM_POLYGON_FL3V;
3127 }
3128
3129 //void() R_EndPolygon
3130 void VM_R_PolygonEnd (void)
3131 {
3132         if(!vm_polygonbegin)
3133         {
3134                 VM_Warning("VM_R_PolygonEnd: VM_R_PolygonBegin wasn't called\n");
3135                 return;
3136         }
3137         vm_polygonbegin = false;
3138         if(vm_current_vertices > 2 || (vm_current_vertices >= 2 && vm_polygons[vm_drawpolygons_num].flags & VM_POLYGON_FLLINES))
3139         {
3140                 if(vm_polygons[vm_drawpolygons_num].flags & VM_POLYGON_FL2D)    //[515]: don't use qcpolygons memory if 2D
3141                         VM_AddPolygonTo2DScene(&vm_polygons[vm_drawpolygons_num]);
3142                 else
3143                         vm_drawpolygons_num++;
3144         }
3145         else
3146                 VM_Warning("VM_R_PolygonEnd: %i vertices isn't a good choice\n", vm_current_vertices);
3147 }
3148
3149 void VM_AddPolygonsToMeshQueue (void)
3150 {
3151         unsigned int i;
3152         if(!vm_drawpolygons_num)
3153                 return;
3154         for(i = 0;i < vm_drawpolygons_num;i++)
3155                 VM_DrawPolygonCallback(NULL, NULL, i, NULL);
3156         vm_drawpolygons_num = 0;
3157 }
3158
3159
3160
3161
3162 // float(float number, float quantity) bitshift (EXT_BITSHIFT)
3163 void VM_bitshift (void)
3164 {
3165         int n1, n2;
3166         VM_SAFEPARMCOUNT(2, VM_bitshift);
3167
3168         n1 = (int)fabs((int)PRVM_G_FLOAT(OFS_PARM0));
3169         n2 = (int)PRVM_G_FLOAT(OFS_PARM1);
3170         if(!n1)
3171                 PRVM_G_FLOAT(OFS_RETURN) = n1;
3172         else
3173         if(n2 < 0)
3174                 PRVM_G_FLOAT(OFS_RETURN) = (n1 >> -n2);
3175         else
3176                 PRVM_G_FLOAT(OFS_RETURN) = (n1 << n2);
3177 }
3178
3179 ////////////////////////////////////////
3180 // AltString functions
3181 ////////////////////////////////////////
3182
3183 /*
3184 ========================
3185 VM_altstr_count
3186
3187 float altstr_count(string)
3188 ========================
3189 */
3190 void VM_altstr_count( void )
3191 {
3192         const char *altstr, *pos;
3193         int     count;
3194
3195         VM_SAFEPARMCOUNT( 1, VM_altstr_count );
3196
3197         altstr = PRVM_G_STRING( OFS_PARM0 );
3198         //VM_CheckEmptyString( altstr );
3199
3200         for( count = 0, pos = altstr ; *pos ; pos++ ) {
3201                 if( *pos == '\\' ) {
3202                         if( !*++pos ) {
3203                                 break;
3204                         }
3205                 } else if( *pos == '\'' ) {
3206                         count++;
3207                 }
3208         }
3209
3210         PRVM_G_FLOAT( OFS_RETURN ) = (float) (count / 2);
3211 }
3212
3213 /*
3214 ========================
3215 VM_altstr_prepare
3216
3217 string altstr_prepare(string)
3218 ========================
3219 */
3220 void VM_altstr_prepare( void )
3221 {
3222         char *outstr, *out;
3223         const char *instr, *in;
3224         int size;
3225
3226         VM_SAFEPARMCOUNT( 1, VM_altstr_prepare );
3227
3228         instr = PRVM_G_STRING( OFS_PARM0 );
3229         //VM_CheckEmptyString( instr );
3230         outstr = VM_GetTempString();
3231
3232         for( out = outstr, in = instr, size = VM_STRINGTEMP_LENGTH - 1 ; size && *in ; size--, in++, out++ )
3233                 if( *in == '\'' ) {
3234                         *out++ = '\\';
3235                         *out = '\'';
3236                         size--;
3237                 } else
3238                         *out = *in;
3239         *out = 0;
3240
3241         PRVM_G_INT( OFS_RETURN ) = PRVM_SetEngineString( outstr );
3242 }
3243
3244 /*
3245 ========================
3246 VM_altstr_get
3247
3248 string altstr_get(string, float)
3249 ========================
3250 */
3251 void VM_altstr_get( void )
3252 {
3253         const char *altstr, *pos;
3254         char *outstr, *out;
3255         int count, size;
3256
3257         VM_SAFEPARMCOUNT( 2, VM_altstr_get );
3258
3259         altstr = PRVM_G_STRING( OFS_PARM0 );
3260         //VM_CheckEmptyString( altstr );
3261
3262         count = (int)PRVM_G_FLOAT( OFS_PARM1 );
3263         count = count * 2 + 1;
3264
3265         for( pos = altstr ; *pos && count ; pos++ )
3266                 if( *pos == '\\' ) {
3267                         if( !*++pos )
3268                                 break;
3269                 } else if( *pos == '\'' )
3270                         count--;
3271
3272         if( !*pos ) {
3273                 PRVM_G_INT( OFS_RETURN ) = PRVM_SetEngineString( NULL );
3274                 return;
3275         }
3276
3277     outstr = VM_GetTempString();
3278         for( out = outstr, size = VM_STRINGTEMP_LENGTH - 1 ; size && *pos ; size--, pos++, out++ )
3279                 if( *pos == '\\' ) {
3280                         if( !*++pos )
3281                                 break;
3282                         *out = *pos;
3283                         size--;
3284                 } else if( *pos == '\'' )
3285                         break;
3286                 else
3287                         *out = *pos;
3288
3289         *out = 0;
3290         PRVM_G_INT( OFS_RETURN ) = PRVM_SetEngineString( outstr );
3291 }
3292
3293 /*
3294 ========================
3295 VM_altstr_set
3296
3297 string altstr_set(string altstr, float num, string set)
3298 ========================
3299 */
3300 void VM_altstr_set( void )
3301 {
3302     int num;
3303         const char *altstr, *str;
3304         const char *in;
3305         char *outstr, *out;
3306
3307         VM_SAFEPARMCOUNT( 3, VM_altstr_set );
3308
3309         altstr = PRVM_G_STRING( OFS_PARM0 );
3310         //VM_CheckEmptyString( altstr );
3311
3312         num = (int)PRVM_G_FLOAT( OFS_PARM1 );
3313
3314         str = PRVM_G_STRING( OFS_PARM2 );
3315         //VM_CheckEmptyString( str );
3316
3317         outstr = out = VM_GetTempString();
3318         for( num = num * 2 + 1, in = altstr; *in && num; *out++ = *in++ )
3319                 if( *in == '\\' ) {
3320                         if( !*++in ) {
3321                                 break;
3322                         }
3323                 } else if( *in == '\'' ) {
3324                         num--;
3325                 }
3326
3327         if( !in ) {
3328                 PRVM_G_INT( OFS_RETURN ) = PRVM_SetEngineString( altstr );
3329                 return;
3330         }
3331         // copy set in
3332         for( ; *str; *out++ = *str++ );
3333         // now jump over the old content
3334         for( ; *in ; in++ )
3335                 if( *in == '\'' || (*in == '\\' && !*++in) )
3336                         break;
3337
3338         if( !in ) {
3339                 PRVM_G_INT( OFS_RETURN ) = PRVM_SetEngineString( NULL );
3340                 return;
3341         }
3342
3343         strlcpy(out, in, VM_STRINGTEMP_LENGTH);
3344         PRVM_G_INT( OFS_RETURN ) = PRVM_SetEngineString( outstr );
3345 }
3346
3347 /*
3348 ========================
3349 VM_altstr_ins
3350 insert after num
3351 string  altstr_ins(string altstr, float num, string set)
3352 ========================
3353 */
3354 void VM_altstr_ins(void)
3355 {
3356         int num;
3357         const char *setstr;
3358         const char *set;
3359         const char *instr;
3360         const char *in;
3361         char *outstr;
3362         char *out;
3363
3364         in = instr = PRVM_G_STRING( OFS_PARM0 );
3365         num = (int)PRVM_G_FLOAT( OFS_PARM1 );
3366         set = setstr = PRVM_G_STRING( OFS_PARM2 );
3367
3368         out = outstr = VM_GetTempString();
3369         for( num = num * 2 + 2 ; *in && num > 0 ; *out++ = *in++ )
3370                 if( *in == '\\' ) {
3371                         if( !*++in ) {
3372                                 break;
3373                         }
3374                 } else if( *in == '\'' ) {
3375                         num--;
3376                 }
3377
3378         *out++ = '\'';
3379         for( ; *set ; *out++ = *set++ );
3380         *out++ = '\'';
3381
3382         strlcpy(out, in, VM_STRINGTEMP_LENGTH);
3383         PRVM_G_INT( OFS_RETURN ) = PRVM_SetEngineString( outstr );
3384 }
3385
3386
3387 ////////////////////////////////////////
3388 // BufString functions
3389 ////////////////////////////////////////
3390 //[515]: string buffers support
3391 #define MAX_QCSTR_BUFFERS 128
3392 #define MAX_QCSTR_STRINGS 1024
3393
3394 typedef struct
3395 {
3396         int             num_strings;
3397         char    *strings[MAX_QCSTR_STRINGS];
3398 }qcstrbuffer_t;
3399
3400 static qcstrbuffer_t    *qcstringbuffers[MAX_QCSTR_BUFFERS];
3401 static int                              num_qcstringbuffers;
3402 static int                              buf_sortpower;
3403
3404 #define BUFSTR_BUFFER(a) (a>=MAX_QCSTR_BUFFERS) ? NULL : (qcstringbuffers[a])
3405 #define BUFSTR_ISFREE(a) (a<MAX_QCSTR_BUFFERS&&qcstringbuffers[a]&&qcstringbuffers[a]->num_strings<=0) ? 1 : 0
3406
3407 static int BufStr_FindFreeBuffer (void)
3408 {
3409         int     i;
3410         if(num_qcstringbuffers == MAX_QCSTR_BUFFERS)
3411                 return -1;
3412         for(i=0;i<MAX_QCSTR_BUFFERS;i++)
3413                 if(!qcstringbuffers[i])
3414                 {
3415                         qcstringbuffers[i] = (qcstrbuffer_t *)Z_Malloc(sizeof(qcstrbuffer_t));
3416                         memset(qcstringbuffers[i], 0, sizeof(qcstrbuffer_t));
3417                         return i;
3418                 }
3419         return -1;
3420 }
3421
3422 static void BufStr_ClearBuffer (int index)
3423 {
3424         qcstrbuffer_t   *b = qcstringbuffers[index];
3425         int                             i;
3426
3427         if(b)
3428         {
3429                 if(b->num_strings > 0)
3430                 {
3431                         for(i=0;i<b->num_strings;i++)
3432                                 if(b->strings[i])
3433                                         Z_Free(b->strings[i]);
3434                         num_qcstringbuffers--;
3435                 }
3436                 Z_Free(qcstringbuffers[index]);
3437                 qcstringbuffers[index] = NULL;
3438         }
3439 }
3440
3441 static int BufStr_FindFreeString (qcstrbuffer_t *b)
3442 {
3443         int                             i;
3444         for(i=0;i<b->num_strings;i++)
3445                 if(!b->strings[i] || !b->strings[i][0])
3446                         return i;
3447         if(i == MAX_QCSTR_STRINGS)      return -1;
3448         else                                            return i;
3449 }
3450
3451 static int BufStr_SortStringsUP (const void *in1, const void *in2)
3452 {
3453         const char *a, *b;
3454         a = *((const char **) in1);
3455         b = *((const char **) in2);
3456         if(!a[0])       return 1;
3457         if(!b[0])       return -1;
3458         return strncmp(a, b, buf_sortpower);
3459 }
3460
3461 static int BufStr_SortStringsDOWN (const void *in1, const void *in2)
3462 {
3463         const char *a, *b;
3464         a = *((const char **) in1);
3465         b = *((const char **) in2);
3466         if(!a[0])       return 1;
3467         if(!b[0])       return -1;
3468         return strncmp(b, a, buf_sortpower);
3469 }
3470
3471 #ifdef REMOVETHIS
3472 static void VM_BufStr_Init (void)
3473 {
3474         memset(qcstringbuffers, 0, sizeof(qcstringbuffers));
3475         num_qcstringbuffers = 0;
3476 }
3477
3478 static void VM_BufStr_ShutDown (void)
3479 {
3480         int i;
3481         for(i=0;i<MAX_QCSTR_BUFFERS && num_qcstringbuffers;i++)
3482                 BufStr_ClearBuffer(i);
3483 }
3484 #endif
3485
3486 /*
3487 ========================
3488 VM_buf_create
3489 creates new buffer, and returns it's index, returns -1 if failed
3490 float buf_create(void) = #460;
3491 ========================
3492 */
3493 void VM_buf_create (void)
3494 {
3495         int i;
3496         VM_SAFEPARMCOUNT(0, VM_buf_create);
3497         i = BufStr_FindFreeBuffer();
3498         if(i >= 0)
3499                 num_qcstringbuffers++;
3500         //else
3501                 //Con_Printf("VM_buf_create: buffers overflow in %s\n", PRVM_NAME);
3502         PRVM_G_FLOAT(OFS_RETURN) = i;
3503 }
3504
3505 /*
3506 ========================
3507 VM_buf_del
3508 deletes buffer and all strings in it
3509 void buf_del(float bufhandle) = #461;
3510 ========================
3511 */
3512 void VM_buf_del (void)
3513 {
3514         VM_SAFEPARMCOUNT(1, VM_buf_del);
3515         if(BUFSTR_BUFFER((int)PRVM_G_FLOAT(OFS_PARM0)))
3516                 BufStr_ClearBuffer((int)PRVM_G_FLOAT(OFS_PARM0));
3517         else
3518         {
3519                 VM_Warning("VM_buf_del: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3520                 return;
3521         }
3522 }
3523
3524 /*
3525 ========================
3526 VM_buf_getsize
3527 how many strings are stored in buffer
3528 float buf_getsize(float bufhandle) = #462;
3529 ========================
3530 */
3531 void VM_buf_getsize (void)
3532 {
3533         qcstrbuffer_t   *b;
3534         VM_SAFEPARMCOUNT(1, VM_buf_getsize);
3535
3536         b = BUFSTR_BUFFER((int)PRVM_G_FLOAT(OFS_PARM0));
3537         if(!b)
3538         {
3539                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3540                 VM_Warning("VM_buf_getsize: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3541                 return;
3542         }
3543         else
3544                 PRVM_G_FLOAT(OFS_RETURN) = b->num_strings;
3545 }
3546
3547 /*
3548 ========================
3549 VM_buf_copy
3550 copy all content from one buffer to another, make sure it exists
3551 void buf_copy(float bufhandle_from, float bufhandle_to) = #463;
3552 ========================
3553 */
3554 void VM_buf_copy (void)
3555 {
3556         qcstrbuffer_t   *b1, *b2;
3557         int                             i;
3558         VM_SAFEPARMCOUNT(2, VM_buf_copy);
3559
3560         b1 = BUFSTR_BUFFER((int)PRVM_G_FLOAT(OFS_PARM0));
3561         if(!b1)
3562         {
3563                 VM_Warning("VM_buf_copy: invalid source buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3564                 return;
3565         }
3566         i = (int)PRVM_G_FLOAT(OFS_PARM1);
3567         if(i == (int)PRVM_G_FLOAT(OFS_PARM0))
3568         {
3569                 VM_Warning("VM_buf_copy: source == destination (%i) in %s\n", i, PRVM_NAME);
3570                 return;
3571         }
3572         b2 = BUFSTR_BUFFER(i);
3573         if(!b2)
3574         {
3575                 VM_Warning("VM_buf_copy: invalid destination buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), PRVM_NAME);
3576                 return;
3577         }
3578
3579         BufStr_ClearBuffer(i);
3580         qcstringbuffers[i] = (qcstrbuffer_t *)Z_Malloc(sizeof(qcstrbuffer_t));
3581         memset(qcstringbuffers[i], 0, sizeof(qcstrbuffer_t));
3582         b2->num_strings = b1->num_strings;
3583
3584         for(i=0;i<b1->num_strings;i++)
3585                 if(b1->strings[i] && b1->strings[i][0])
3586                 {
3587                         size_t stringlen;
3588                         stringlen = strlen(b1->strings[i]) + 1;
3589                         b2->strings[i] = (char *)Z_Malloc(stringlen);
3590                         if(!b2->strings[i])
3591                         {
3592                                 VM_Warning("VM_buf_copy: not enough memory for buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), PRVM_NAME);
3593                                 break;
3594                         }
3595                         memcpy(b2->strings[i], b1->strings[i], stringlen);
3596                 }
3597 }
3598
3599 /*
3600 ========================
3601 VM_buf_sort
3602 sort buffer by beginnings of strings (sortpower defaults it's lenght)
3603 "backward == TRUE" means that sorting goes upside-down
3604 void buf_sort(float bufhandle, float sortpower, float backward) = #464;
3605 ========================
3606 */
3607 void VM_buf_sort (void)
3608 {
3609         qcstrbuffer_t   *b;
3610         int                             i;
3611         VM_SAFEPARMCOUNT(3, VM_buf_sort);
3612
3613         b = BUFSTR_BUFFER((int)PRVM_G_FLOAT(OFS_PARM0));
3614         if(!b)
3615         {
3616                 VM_Warning("VM_buf_sort: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3617                 return;
3618         }
3619         if(b->num_strings <= 0)
3620         {
3621                 VM_Warning("VM_buf_sort: tried to sort empty buffer %i in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3622                 return;
3623         }
3624         buf_sortpower = (int)PRVM_G_FLOAT(OFS_PARM1);
3625         if(buf_sortpower <= 0)
3626                 buf_sortpower = 99999999;
3627
3628         if(!PRVM_G_FLOAT(OFS_PARM2))
3629                 qsort(b->strings, b->num_strings, sizeof(char*), BufStr_SortStringsUP);
3630         else
3631                 qsort(b->strings, b->num_strings, sizeof(char*), BufStr_SortStringsDOWN);
3632
3633         for(i=b->num_strings-1;i>=0;i--)        //[515]: delete empty lines
3634                 if(b->strings)
3635                 {
3636                         if(b->strings[i][0])
3637                                 break;
3638                         else
3639                         {
3640                                 Z_Free(b->strings[i]);
3641                                 --b->num_strings;
3642                                 b->strings[i] = NULL;
3643                         }
3644                 }
3645                 else
3646                         --b->num_strings;
3647 }
3648
3649 /*
3650 ========================
3651 VM_buf_implode
3652 concantenates all buffer string into one with "glue" separator and returns it as tempstring
3653 string buf_implode(float bufhandle, string glue) = #465;
3654 ========================
3655 */
3656 void VM_buf_implode (void)
3657 {
3658         qcstrbuffer_t   *b;
3659         char                    *k;
3660         const char              *sep;
3661         int                             i;
3662         size_t                  l;
3663         VM_SAFEPARMCOUNT(2, VM_buf_implode);
3664
3665         b = BUFSTR_BUFFER((int)PRVM_G_FLOAT(OFS_PARM0));
3666         PRVM_G_INT(OFS_RETURN) = 0;
3667         if(!b)
3668         {
3669                 VM_Warning("VM_buf_implode: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3670                 return;
3671         }
3672         if(!b->num_strings)
3673                 return;
3674         sep = PRVM_G_STRING(OFS_PARM1);
3675         k = VM_GetTempString();
3676         k[0] = 0;
3677         for(l=i=0;i<b->num_strings;i++)
3678                 if(b->strings[i])
3679                 {
3680                         l += strlen(b->strings[i]);
3681                         if(l>=4095)
3682                                 break;
3683                         strlcat(k, b->strings[i], VM_STRINGTEMP_LENGTH);
3684                         if(sep && (i != b->num_strings-1))
3685                         {
3686                                 l += strlen(sep);
3687                                 if(l>=4095)
3688                                         break;
3689                                 strlcat(k, sep, VM_STRINGTEMP_LENGTH);
3690                         }
3691                 }
3692         PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(k);
3693 }
3694
3695 /*
3696 ========================
3697 VM_bufstr_get
3698 get a string from buffer, returns direct pointer, dont str_unzone it!
3699 string bufstr_get(float bufhandle, float string_index) = #465;
3700 ========================
3701 */
3702 void VM_bufstr_get (void)
3703 {
3704         qcstrbuffer_t   *b;
3705         int                             strindex;
3706         VM_SAFEPARMCOUNT(2, VM_bufstr_get);
3707
3708         b = BUFSTR_BUFFER((int)PRVM_G_FLOAT(OFS_PARM0));
3709         if(!b)
3710         {
3711                 VM_Warning("VM_bufstr_get: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
3712                 return;
3713         }
3714         strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
3715         if(strindex < 0 || strindex > MAX_QCSTR_STRINGS)
3716         {
3717                 VM_Warning("VM_bufstr_get: invalid string index %i used in %s\n", strindex, PRVM_NAME);
3718                 return;
3719         }
3720         PRVM_G_INT(OFS_RETURN) = 0;
3721         if(b->num_strings <= strindex)
3722                 return;
3723         if(b->strings[strindex])
3724                 PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(b->strings[strindex]);
3725 }
3726
3727 /*
3728 ========================
3729 VM_bufstr_set
3730 copies a string into selected slot of buffer
3731 void bufstr_set(float bufhandle, float string_index, string str) = #466;
3732 ========================
3733 */
3734 void VM_bufstr_set (void)
3735 {
3736         int                             bufindex, strindex;
3737         qcstrbuffer_t   *b;
3738         const char              *news;
3739         size_t                  alloclen;
3740
3741         VM_SAFEPARMCOUNT(3, VM_bufstr_set);
3742
3743         bufindex = (int)PRVM_G_FLOAT(OFS_PARM0);
3744         b = BUFSTR_BUFFER(bufindex);
3745         if(!b)
3746         {
3747                 VM_Warning("VM_bufstr_set: invalid buffer %i used in %s\n", bufindex, PRVM_NAME);
3748                 return;
3749         }
3750         strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
3751         if(strindex < 0 || strindex > MAX_QCSTR_STRINGS)
3752         {
3753                 VM_Warning("VM_bufstr_set: invalid string index %i used in %s\n", strindex, PRVM_NAME);
3754                 return;
3755         }
3756         news = PRVM_G_STRING(OFS_PARM2);
3757         if(!news)
3758         {
3759                 VM_Warning("VM_bufstr_set: null string used in %s\n", PRVM_NAME);
3760                 return;
3761         }
3762         if(b->strings[strindex])
3763                 Z_Free(b->strings[strindex]);
3764         alloclen = strlen(news) + 1;
3765         b->strings[strindex] = (char *)Z_Malloc(alloclen);
3766         memcpy(b->strings[strindex], news, alloclen);
3767 }
3768
3769 /*
3770 ========================
3771 VM_bufstr_add
3772 adds string to buffer in nearest free slot and returns it
3773 "order == TRUE" means that string will be added after last "full" slot
3774 float bufstr_add(float bufhandle, string str, float order) = #467;
3775 ========================
3776 */
3777 void VM_bufstr_add (void)
3778 {
3779         int                             bufindex, order, strindex;
3780         qcstrbuffer_t   *b;
3781         const char              *string;
3782         size_t                  alloclen;
3783
3784         VM_SAFEPARMCOUNT(3, VM_bufstr_add);
3785
3786         bufindex = (int)PRVM_G_FLOAT(OFS_PARM0);
3787         b = BUFSTR_BUFFER(bufindex);
3788         PRVM_G_FLOAT(OFS_RETURN) = -1;
3789         if(!b)
3790         {
3791                 VM_Warning("VM_bufstr_add: invalid buffer %i used in %s\n", bufindex, PRVM_NAME);
3792                 return;
3793         }
3794         string = PRVM_G_STRING(OFS_PARM1);
3795         if(!string)
3796         {
3797                 VM_Warning("VM_bufstr_add: null string used in %s\n", PRVM_NAME);
3798                 return;
3799         }
3800
3801         order = (int)PRVM_G_FLOAT(OFS_PARM2);
3802         if(order)
3803                 strindex = b->num_strings;
3804         else
3805         {
3806                 strindex = BufStr_FindFreeString(b);
3807                 if(strindex < 0)
3808                 {
3809                         VM_Warning("VM_bufstr_add: buffer %i has no free string slots in %s\n", bufindex, PRVM_NAME);
3810                         return;
3811                 }
3812         }
3813
3814         while(b->num_strings <= strindex)
3815     &