implement digest_hex()
[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 "quakedef.h"
8
9 #include "prvm_cmds.h"
10 #include "libcurl.h"
11 #include <time.h>
12
13 #include "cl_collision.h"
14 #include "clvm_cmds.h"
15 #include "ft2.h"
16
17 extern cvar_t prvm_backtraceforwarnings;
18
19 // LordHavoc: changed this to NOT use a return statement, so that it can be used in functions that must return a value
20 void VM_Warning(const char *fmt, ...)
21 {
22         va_list argptr;
23         char msg[MAX_INPUTLINE];
24         static double recursive = -1;
25
26         va_start(argptr,fmt);
27         dpvsnprintf(msg,sizeof(msg),fmt,argptr);
28         va_end(argptr);
29
30         Con_DPrint(msg);
31
32         // TODO: either add a cvar/cmd to control the state dumping or replace some of the calls with Con_Printf [9/13/2006 Black]
33         if(prvm_backtraceforwarnings.integer && recursive != realtime) // NOTE: this compares to the time, just in case if PRVM_PrintState causes a Host_Error and keeps recursive set
34         {
35                 recursive = realtime;
36                 PRVM_PrintState();
37                 recursive = -1;
38         }
39 }
40
41
42 //============================================================================
43 // Common
44
45 // TODO DONE: move vm_files and vm_fssearchlist to prvm_prog_t struct
46 // TODO: move vm_files and vm_fssearchlist back [9/13/2006 Black]
47 // TODO: (move vm_files and vm_fssearchlist to prvm_prog_t struct again) [2007-01-23 LordHavoc]
48 // TODO: will this war ever end? [2007-01-23 LordHavoc]
49
50 void VM_CheckEmptyString (const char *s)
51 {
52         if (ISWHITESPACE(s[0]))
53                 PRVM_ERROR ("%s: Bad string", PRVM_NAME);
54 }
55
56 void VM_GenerateFrameGroupBlend(framegroupblend_t *framegroupblend, const prvm_edict_t *ed)
57 {
58         // self.frame is the interpolation target (new frame)
59         // self.frame1time is the animation base time for the interpolation target
60         // self.frame2 is the interpolation start (previous frame)
61         // self.frame2time is the animation base time for the interpolation start
62         // self.lerpfrac is the interpolation strength for self.frame2
63         // self.lerpfrac3 is the interpolation strength for self.frame3
64         // self.lerpfrac4 is the interpolation strength for self.frame4
65         // pitch angle on a player model where the animator set up 5 sets of
66         // animations and the csqc simply lerps between sets)
67         framegroupblend[0].frame = (int) PRVM_gameedictfloat(ed, frame     );
68         framegroupblend[1].frame = (int) PRVM_gameedictfloat(ed, frame2    );
69         framegroupblend[2].frame = (int) PRVM_gameedictfloat(ed, frame3    );
70         framegroupblend[3].frame = (int) PRVM_gameedictfloat(ed, frame4    );
71         framegroupblend[0].start =       PRVM_gameedictfloat(ed, frame1time);
72         framegroupblend[1].start =       PRVM_gameedictfloat(ed, frame2time);
73         framegroupblend[2].start =       PRVM_gameedictfloat(ed, frame3time);
74         framegroupblend[3].start =       PRVM_gameedictfloat(ed, frame4time);
75         framegroupblend[1].lerp  =       PRVM_gameedictfloat(ed, lerpfrac  );
76         framegroupblend[2].lerp  =       PRVM_gameedictfloat(ed, lerpfrac3 );
77         framegroupblend[3].lerp  =       PRVM_gameedictfloat(ed, lerpfrac4 );
78         // assume that the (missing) lerpfrac1 is whatever remains after lerpfrac2+lerpfrac3+lerpfrac4 are summed
79         framegroupblend[0].lerp = 1 - framegroupblend[1].lerp - framegroupblend[2].lerp - framegroupblend[3].lerp;
80 }
81
82 // LordHavoc: quite tempting to break apart this function to reuse the
83 //            duplicated code, but I suspect it is better for performance
84 //            this way
85 void VM_FrameBlendFromFrameGroupBlend(frameblend_t *frameblend, const framegroupblend_t *framegroupblend, const dp_model_t *model)
86 {
87         int sub2, numframes, f, i, k;
88         int isfirstframegroup = true;
89         int nolerp;
90         double sublerp, lerp, d;
91         const animscene_t *scene;
92         const framegroupblend_t *g;
93         frameblend_t *blend = frameblend;
94
95         memset(blend, 0, MAX_FRAMEBLENDS * sizeof(*blend));
96
97         if (!model || !model->surfmesh.isanimated)
98         {
99                 blend[0].lerp = 1;
100                 return;
101         }
102
103         nolerp = (model->type == mod_sprite) ? !r_lerpsprites.integer : !r_lerpmodels.integer;
104         numframes = model->numframes;
105         for (k = 0, g = framegroupblend;k < MAX_FRAMEGROUPBLENDS;k++, g++)
106         {
107                 f = g->frame;
108                 if ((unsigned int)f >= (unsigned int)numframes)
109                 {
110                         Con_DPrintf("VM_FrameBlendFromFrameGroupBlend: no such frame %d in model %s\n", f, model->name);
111                         f = 0;
112                 }
113                 d = lerp = g->lerp;
114                 if (lerp <= 0)
115                         continue;
116                 if (nolerp)
117                 {
118                         if (isfirstframegroup)
119                         {
120                                 d = lerp = 1;
121                                 isfirstframegroup = false;
122                         }
123                         else
124                                 continue;
125                 }
126                 if (model->animscenes)
127                 {
128                         scene = model->animscenes + f;
129                         f = scene->firstframe;
130                         if (scene->framecount > 1)
131                         {
132                                 // this code path is only used on .zym models and torches
133                                 sublerp = scene->framerate * (cl.time - g->start);
134                                 f = (int) floor(sublerp);
135                                 sublerp -= f;
136                                 sub2 = f + 1;
137                                 if (sublerp < (1.0 / 65536.0f))
138                                         sublerp = 0;
139                                 if (sublerp > (65535.0f / 65536.0f))
140                                         sublerp = 1;
141                                 if (nolerp)
142                                         sublerp = 0;
143                                 if (scene->loop)
144                                 {
145                                         f = (f % scene->framecount);
146                                         sub2 = (sub2 % scene->framecount);
147                                 }
148                                 f = bound(0, f, (scene->framecount - 1)) + scene->firstframe;
149                                 sub2 = bound(0, sub2, (scene->framecount - 1)) + scene->firstframe;
150                                 d = sublerp * lerp;
151                                 // two framelerps produced from one animation
152                                 if (d > 0)
153                                 {
154                                         for (i = 0;i < MAX_FRAMEBLENDS;i++)
155                                         {
156                                                 if (blend[i].lerp <= 0 || blend[i].subframe == sub2)
157                                                 {
158                                                         blend[i].subframe = sub2;
159                                                         blend[i].lerp += d;
160                                                         break;
161                                                 }
162                                         }
163                                 }
164                                 d = (1 - sublerp) * lerp;
165                         }
166                 }
167                 if (d > 0)
168                 {
169                         for (i = 0;i < MAX_FRAMEBLENDS;i++)
170                         {
171                                 if (blend[i].lerp <= 0 || blend[i].subframe == f)
172                                 {
173                                         blend[i].subframe = f;
174                                         blend[i].lerp += d;
175                                         break;
176                                 }
177                         }
178                 }
179         }
180 }
181
182 void VM_UpdateEdictSkeleton(prvm_edict_t *ed, const dp_model_t *edmodel, const frameblend_t *frameblend)
183 {
184         if (ed->priv.server->skeleton.model != edmodel)
185         {
186                 VM_RemoveEdictSkeleton(ed);
187                 ed->priv.server->skeleton.model = edmodel;
188         }
189         if (!ed->priv.server->skeleton.model || !ed->priv.server->skeleton.model->num_bones)
190         {
191                 if(ed->priv.server->skeleton.relativetransforms)
192                         Mem_Free(ed->priv.server->skeleton.relativetransforms);
193                 ed->priv.server->skeleton.relativetransforms = NULL;
194                 return;
195         }
196
197         {
198                 int skeletonindex = -1;
199                 skeleton_t *skeleton;
200                 skeletonindex = (int)PRVM_gameedictfloat(ed, skeletonindex) - 1;
201                 if (skeletonindex >= 0 && skeletonindex < MAX_EDICTS && (skeleton = prog->skeletons[skeletonindex]) && skeleton->model->num_bones == ed->priv.server->skeleton.model->num_bones)
202                 {
203                         // custom skeleton controlled by the game (FTE_CSQC_SKELETONOBJECTS)
204                         if (!ed->priv.server->skeleton.relativetransforms)
205                                 ed->priv.server->skeleton.relativetransforms = (matrix4x4_t *)Mem_Alloc(prog->progs_mempool, ed->priv.server->skeleton.model->num_bones * sizeof(matrix4x4_t));
206                         memcpy(ed->priv.server->skeleton.relativetransforms, skeleton->relativetransforms, ed->priv.server->skeleton.model->num_bones * sizeof(matrix4x4_t));
207                 }
208                 else
209                 {
210                         if(ed->priv.server->skeleton.relativetransforms)
211                                 Mem_Free(ed->priv.server->skeleton.relativetransforms);
212                         ed->priv.server->skeleton.relativetransforms = NULL;
213                 }
214         }
215 }
216
217 void VM_RemoveEdictSkeleton(prvm_edict_t *ed)
218 {
219         if (ed->priv.server->skeleton.relativetransforms)
220                 Mem_Free(ed->priv.server->skeleton.relativetransforms);
221         memset(&ed->priv.server->skeleton, 0, sizeof(ed->priv.server->skeleton));
222 }
223
224
225
226
227 //============================================================================
228 //BUILT-IN FUNCTIONS
229
230 void VM_VarString(int first, char *out, int outlength)
231 {
232         int i;
233         const char *s;
234         char *outend;
235
236         outend = out + outlength - 1;
237         for (i = first;i < prog->argc && out < outend;i++)
238         {
239                 s = PRVM_G_STRING((OFS_PARM0+i*3));
240                 while (out < outend && *s)
241                         *out++ = *s++;
242         }
243         *out++ = 0;
244 }
245
246 /*
247 =================
248 VM_checkextension
249
250 returns true if the extension is supported by the server
251
252 checkextension(extensionname)
253 =================
254 */
255
256 // kind of helper function
257 static qboolean checkextension(const char *name)
258 {
259         int len;
260         const char *e, *start;
261         len = (int)strlen(name);
262
263         for (e = prog->extensionstring;*e;e++)
264         {
265                 while (*e == ' ')
266                         e++;
267                 if (!*e)
268                         break;
269                 start = e;
270                 while (*e && *e != ' ')
271                         e++;
272                 if ((e - start) == len && !strncasecmp(start, name, len))
273                 {
274                         // special sheck for ODE
275                         if (!strncasecmp("DP_PHYSICS_ODE", name, 14))
276                         {
277 #ifdef USEODE
278                                 return ode_dll ? true : false;
279 #else
280                                 return false;
281 #endif
282                         }
283
284                         // special sheck for d0_blind_id
285                         if (!strcasecmp("DP_CRYPTO", name))
286                                 return Crypto_Available();
287                         if (!strcasecmp("DP_QC_DIGEST_SHA256", name))
288                                 return Crypto_Available();
289
290                         return true;
291                 }
292         }
293         return false;
294 }
295
296 void VM_checkextension (void)
297 {
298         VM_SAFEPARMCOUNT(1,VM_checkextension);
299
300         PRVM_G_FLOAT(OFS_RETURN) = checkextension(PRVM_G_STRING(OFS_PARM0));
301 }
302
303 /*
304 =================
305 VM_error
306
307 This is a TERMINAL error, which will kill off the entire prog.
308 Dumps self.
309
310 error(value)
311 =================
312 */
313 void VM_error (void)
314 {
315         prvm_edict_t    *ed;
316         char string[VM_STRINGTEMP_LENGTH];
317
318         VM_VarString(0, string, sizeof(string));
319         Con_Printf("======%s ERROR in %s:\n%s\n", PRVM_NAME, PRVM_GetString(prog->xfunction->s_name), string);
320         ed = PRVM_PROG_TO_EDICT(PRVM_allglobaledict(self));
321         PRVM_ED_Print(ed, NULL);
322
323         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);
324 }
325
326 /*
327 =================
328 VM_objerror
329
330 Dumps out self, then an error message.  The program is aborted and self is
331 removed, but the level can continue.
332
333 objerror(value)
334 =================
335 */
336 void VM_objerror (void)
337 {
338         prvm_edict_t    *ed;
339         char string[VM_STRINGTEMP_LENGTH];
340
341         VM_VarString(0, string, sizeof(string));
342         Con_Printf("======OBJECT ERROR======\n"); // , PRVM_NAME, PRVM_GetString(prog->xfunction->s_name), string); // or include them? FIXME
343         ed = PRVM_PROG_TO_EDICT(PRVM_allglobaledict(self));
344         PRVM_ED_Print(ed, NULL);
345         PRVM_ED_Free (ed);
346         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);
347 }
348
349 /*
350 =================
351 VM_print
352
353 print to console
354
355 print(...[string])
356 =================
357 */
358 void VM_print (void)
359 {
360         char string[VM_STRINGTEMP_LENGTH];
361
362         VM_VarString(0, string, sizeof(string));
363         Con_Print(string);
364 }
365
366 /*
367 =================
368 VM_bprint
369
370 broadcast print to everyone on server
371
372 bprint(...[string])
373 =================
374 */
375 void VM_bprint (void)
376 {
377         char string[VM_STRINGTEMP_LENGTH];
378
379         if(!sv.active)
380         {
381                 VM_Warning("VM_bprint: game is not server(%s) !\n", PRVM_NAME);
382                 return;
383         }
384
385         VM_VarString(0, string, sizeof(string));
386         SV_BroadcastPrint(string);
387 }
388
389 /*
390 =================
391 VM_sprint (menu & client but only if server.active == true)
392
393 single print to a specific client
394
395 sprint(float clientnum,...[string])
396 =================
397 */
398 void VM_sprint (void)
399 {
400         client_t        *client;
401         int                     clientnum;
402         char string[VM_STRINGTEMP_LENGTH];
403
404         VM_SAFEPARMCOUNTRANGE(1, 8, VM_sprint);
405
406         //find client for this entity
407         clientnum = (int)PRVM_G_FLOAT(OFS_PARM0);
408         if (!sv.active  || clientnum < 0 || clientnum >= svs.maxclients || !svs.clients[clientnum].active)
409         {
410                 VM_Warning("VM_sprint: %s: invalid client or server is not active !\n", PRVM_NAME);
411                 return;
412         }
413
414         client = svs.clients + clientnum;
415         if (!client->netconnection)
416                 return;
417
418         VM_VarString(1, string, sizeof(string));
419         MSG_WriteChar(&client->netconnection->message,svc_print);
420         MSG_WriteString(&client->netconnection->message, string);
421 }
422
423 /*
424 =================
425 VM_centerprint
426
427 single print to the screen
428
429 centerprint(value)
430 =================
431 */
432 void VM_centerprint (void)
433 {
434         char string[VM_STRINGTEMP_LENGTH];
435
436         VM_SAFEPARMCOUNTRANGE(1, 8, VM_centerprint);
437         VM_VarString(0, string, sizeof(string));
438         SCR_CenterPrint(string);
439 }
440
441 /*
442 =================
443 VM_normalize
444
445 vector normalize(vector)
446 =================
447 */
448 void VM_normalize (void)
449 {
450         float   *value1;
451         vec3_t  newvalue;
452         double  f;
453
454         VM_SAFEPARMCOUNT(1,VM_normalize);
455
456         value1 = PRVM_G_VECTOR(OFS_PARM0);
457
458         f = VectorLength2(value1);
459         if (f)
460         {
461                 f = 1.0 / sqrt(f);
462                 VectorScale(value1, f, newvalue);
463         }
464         else
465                 VectorClear(newvalue);
466
467         VectorCopy (newvalue, PRVM_G_VECTOR(OFS_RETURN));
468 }
469
470 /*
471 =================
472 VM_vlen
473
474 scalar vlen(vector)
475 =================
476 */
477 void VM_vlen (void)
478 {
479         VM_SAFEPARMCOUNT(1,VM_vlen);
480         PRVM_G_FLOAT(OFS_RETURN) = VectorLength(PRVM_G_VECTOR(OFS_PARM0));
481 }
482
483 /*
484 =================
485 VM_vectoyaw
486
487 float vectoyaw(vector)
488 =================
489 */
490 void VM_vectoyaw (void)
491 {
492         float   *value1;
493         float   yaw;
494
495         VM_SAFEPARMCOUNT(1,VM_vectoyaw);
496
497         value1 = PRVM_G_VECTOR(OFS_PARM0);
498
499         if (value1[1] == 0 && value1[0] == 0)
500                 yaw = 0;
501         else
502         {
503                 yaw = (int) (atan2(value1[1], value1[0]) * 180 / M_PI);
504                 if (yaw < 0)
505                         yaw += 360;
506         }
507
508         PRVM_G_FLOAT(OFS_RETURN) = yaw;
509 }
510
511
512 /*
513 =================
514 VM_vectoangles
515
516 vector vectoangles(vector[, vector])
517 =================
518 */
519 void VM_vectoangles (void)
520 {
521         VM_SAFEPARMCOUNTRANGE(1, 2,VM_vectoangles);
522
523         AnglesFromVectors(PRVM_G_VECTOR(OFS_RETURN), PRVM_G_VECTOR(OFS_PARM0), prog->argc >= 2 ? PRVM_G_VECTOR(OFS_PARM1) : NULL, true);
524 }
525
526 /*
527 =================
528 VM_random
529
530 Returns a number from 0<= num < 1
531
532 float random()
533 =================
534 */
535 void VM_random (void)
536 {
537         VM_SAFEPARMCOUNT(0,VM_random);
538
539         PRVM_G_FLOAT(OFS_RETURN) = lhrandom(0, 1);
540 }
541
542 /*
543 =========
544 VM_localsound
545
546 localsound(string sample)
547 =========
548 */
549 void VM_localsound(void)
550 {
551         const char *s;
552
553         VM_SAFEPARMCOUNT(1,VM_localsound);
554
555         s = PRVM_G_STRING(OFS_PARM0);
556
557         if(!S_LocalSound (s))
558         {
559                 PRVM_G_FLOAT(OFS_RETURN) = -4;
560                 VM_Warning("VM_localsound: Failed to play %s for %s !\n", s, PRVM_NAME);
561                 return;
562         }
563
564         PRVM_G_FLOAT(OFS_RETURN) = 1;
565 }
566
567 /*
568 =================
569 VM_break
570
571 break()
572 =================
573 */
574 void VM_break (void)
575 {
576         PRVM_ERROR ("%s: break statement", PRVM_NAME);
577 }
578
579 //============================================================================
580
581 /*
582 =================
583 VM_localcmd
584
585 Sends text over to the client's execution buffer
586
587 [localcmd (string, ...) or]
588 cmd (string, ...)
589 =================
590 */
591 void VM_localcmd (void)
592 {
593         char string[VM_STRINGTEMP_LENGTH];
594         VM_SAFEPARMCOUNTRANGE(1, 8, VM_localcmd);
595         VM_VarString(0, string, sizeof(string));
596         Cbuf_AddText(string);
597 }
598
599 static qboolean PRVM_Cvar_ReadOk(const char *string)
600 {
601         cvar_t *cvar;
602         cvar = Cvar_FindVar(string);
603         return ((cvar) && ((cvar->flags & CVAR_PRIVATE) == 0));
604 }
605
606 /*
607 =================
608 VM_cvar
609
610 float cvar (string)
611 =================
612 */
613 void VM_cvar (void)
614 {
615         char string[VM_STRINGTEMP_LENGTH];
616         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar);
617         VM_VarString(0, string, sizeof(string));
618         VM_CheckEmptyString(string);
619         PRVM_G_FLOAT(OFS_RETURN) = PRVM_Cvar_ReadOk(string) ? Cvar_VariableValue(string) : 0;
620 }
621
622 /*
623 =================
624 VM_cvar
625
626 float cvar_type (string)
627 float CVAR_TYPEFLAG_EXISTS = 1;
628 float CVAR_TYPEFLAG_SAVED = 2;
629 float CVAR_TYPEFLAG_PRIVATE = 4;
630 float CVAR_TYPEFLAG_ENGINE = 8;
631 float CVAR_TYPEFLAG_HASDESCRIPTION = 16;
632 float CVAR_TYPEFLAG_READONLY = 32;
633 =================
634 */
635 void VM_cvar_type (void)
636 {
637         char string[VM_STRINGTEMP_LENGTH];
638         cvar_t *cvar;
639         int ret;
640
641         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar);
642         VM_VarString(0, string, sizeof(string));
643         VM_CheckEmptyString(string);
644         cvar = Cvar_FindVar(string);
645
646
647         if(!cvar)
648         {
649                 PRVM_G_FLOAT(OFS_RETURN) = 0;
650                 return; // CVAR_TYPE_NONE
651         }
652
653         ret = 1; // CVAR_EXISTS
654         if(cvar->flags & CVAR_SAVE)
655                 ret |= 2; // CVAR_TYPE_SAVED
656         if(cvar->flags & CVAR_PRIVATE)
657                 ret |= 4; // CVAR_TYPE_PRIVATE
658         if(!(cvar->flags & CVAR_ALLOCATED))
659                 ret |= 8; // CVAR_TYPE_ENGINE
660         if(cvar->description != cvar_dummy_description)
661                 ret |= 16; // CVAR_TYPE_HASDESCRIPTION
662         if(cvar->flags & CVAR_READONLY)
663                 ret |= 32; // CVAR_TYPE_READONLY
664         
665         PRVM_G_FLOAT(OFS_RETURN) = ret;
666 }
667
668 /*
669 =================
670 VM_cvar_string
671
672 const string    VM_cvar_string (string, ...)
673 =================
674 */
675 void VM_cvar_string(void)
676 {
677         char string[VM_STRINGTEMP_LENGTH];
678         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_string);
679         VM_VarString(0, string, sizeof(string));
680         VM_CheckEmptyString(string);
681         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(PRVM_Cvar_ReadOk(string) ? Cvar_VariableString(string) : "");
682 }
683
684
685 /*
686 ========================
687 VM_cvar_defstring
688
689 const string    VM_cvar_defstring (string, ...)
690 ========================
691 */
692 void VM_cvar_defstring (void)
693 {
694         char string[VM_STRINGTEMP_LENGTH];
695         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_defstring);
696         VM_VarString(0, string, sizeof(string));
697         VM_CheckEmptyString(string);
698         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(Cvar_VariableDefString(string));
699 }
700
701 /*
702 ========================
703 VM_cvar_defstring
704
705 const string    VM_cvar_description (string, ...)
706 ========================
707 */
708 void VM_cvar_description (void)
709 {
710         char string[VM_STRINGTEMP_LENGTH];
711         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_description);
712         VM_VarString(0, string, sizeof(string));
713         VM_CheckEmptyString(string);
714         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(Cvar_VariableDescription(string));
715 }
716 /*
717 =================
718 VM_cvar_set
719
720 void cvar_set (string,string, ...)
721 =================
722 */
723 void VM_cvar_set (void)
724 {
725         const char *name;
726         char string[VM_STRINGTEMP_LENGTH];
727         VM_SAFEPARMCOUNTRANGE(2,8,VM_cvar_set);
728         VM_VarString(1, string, sizeof(string));
729         name = PRVM_G_STRING(OFS_PARM0);
730         VM_CheckEmptyString(name);
731         Cvar_Set(name, string);
732 }
733
734 /*
735 =========
736 VM_dprint
737
738 dprint(...[string])
739 =========
740 */
741 void VM_dprint (void)
742 {
743         char string[VM_STRINGTEMP_LENGTH];
744         VM_SAFEPARMCOUNTRANGE(1, 8, VM_dprint);
745         VM_VarString(0, string, sizeof(string));
746 #if 1
747         Con_DPrintf("%s", string);
748 #else
749         Con_DPrintf("%s: %s", PRVM_NAME, string);
750 #endif
751 }
752
753 /*
754 =========
755 VM_ftos
756
757 string  ftos(float)
758 =========
759 */
760
761 void VM_ftos (void)
762 {
763         float v;
764         char s[128];
765
766         VM_SAFEPARMCOUNT(1, VM_ftos);
767
768         v = PRVM_G_FLOAT(OFS_PARM0);
769
770         if ((float)((int)v) == v)
771                 dpsnprintf(s, sizeof(s), "%i", (int)v);
772         else
773                 dpsnprintf(s, sizeof(s), "%f", v);
774         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(s);
775 }
776
777 /*
778 =========
779 VM_fabs
780
781 float   fabs(float)
782 =========
783 */
784
785 void VM_fabs (void)
786 {
787         float   v;
788
789         VM_SAFEPARMCOUNT(1,VM_fabs);
790
791         v = PRVM_G_FLOAT(OFS_PARM0);
792         PRVM_G_FLOAT(OFS_RETURN) = fabs(v);
793 }
794
795 /*
796 =========
797 VM_vtos
798
799 string  vtos(vector)
800 =========
801 */
802
803 void VM_vtos (void)
804 {
805         char s[512];
806
807         VM_SAFEPARMCOUNT(1,VM_vtos);
808
809         dpsnprintf (s, sizeof(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]);
810         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(s);
811 }
812
813 /*
814 =========
815 VM_etos
816
817 string  etos(entity)
818 =========
819 */
820
821 void VM_etos (void)
822 {
823         char s[128];
824
825         VM_SAFEPARMCOUNT(1, VM_etos);
826
827         dpsnprintf (s, sizeof(s), "entity %i", PRVM_G_EDICTNUM(OFS_PARM0));
828         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(s);
829 }
830
831 /*
832 =========
833 VM_stof
834
835 float stof(...[string])
836 =========
837 */
838 void VM_stof(void)
839 {
840         char string[VM_STRINGTEMP_LENGTH];
841         VM_SAFEPARMCOUNTRANGE(1, 8, VM_stof);
842         VM_VarString(0, string, sizeof(string));
843         PRVM_G_FLOAT(OFS_RETURN) = atof(string);
844 }
845
846 /*
847 ========================
848 VM_itof
849
850 float itof(intt ent)
851 ========================
852 */
853 void VM_itof(void)
854 {
855         VM_SAFEPARMCOUNT(1, VM_itof);
856         PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
857 }
858
859 /*
860 ========================
861 VM_ftoe
862
863 entity ftoe(float num)
864 ========================
865 */
866 void VM_ftoe(void)
867 {
868         int ent;
869         VM_SAFEPARMCOUNT(1, VM_ftoe);
870
871         ent = (int)PRVM_G_FLOAT(OFS_PARM0);
872         if (ent < 0 || ent >= prog->max_edicts || PRVM_PROG_TO_EDICT(ent)->priv.required->free)
873                 ent = 0; // return world instead of a free or invalid entity
874
875         PRVM_G_INT(OFS_RETURN) = ent;
876 }
877
878 /*
879 ========================
880 VM_etof
881
882 float etof(entity ent)
883 ========================
884 */
885 void VM_etof(void)
886 {
887         VM_SAFEPARMCOUNT(1, VM_etof);
888         PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_EDICTNUM(OFS_PARM0);
889 }
890
891 /*
892 =========
893 VM_strftime
894
895 string strftime(float uselocaltime, string[, string ...])
896 =========
897 */
898 void VM_strftime(void)
899 {
900         time_t t;
901 #if _MSC_VER >= 1400
902         struct tm tm;
903         int tmresult;
904 #else
905         struct tm *tm;
906 #endif
907         char fmt[VM_STRINGTEMP_LENGTH];
908         char result[VM_STRINGTEMP_LENGTH];
909         VM_SAFEPARMCOUNTRANGE(2, 8, VM_strftime);
910         VM_VarString(1, fmt, sizeof(fmt));
911         t = time(NULL);
912 #if _MSC_VER >= 1400
913         if (PRVM_G_FLOAT(OFS_PARM0))
914                 tmresult = localtime_s(&tm, &t);
915         else
916                 tmresult = gmtime_s(&tm, &t);
917         if (!tmresult)
918 #else
919         if (PRVM_G_FLOAT(OFS_PARM0))
920                 tm = localtime(&t);
921         else
922                 tm = gmtime(&t);
923         if (!tm)
924 #endif
925         {
926                 PRVM_G_INT(OFS_RETURN) = 0;
927                 return;
928         }
929 #if _MSC_VER >= 1400
930         strftime(result, sizeof(result), fmt, &tm);
931 #else
932         strftime(result, sizeof(result), fmt, tm);
933 #endif
934         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(result);
935 }
936
937 /*
938 =========
939 VM_spawn
940
941 entity spawn()
942 =========
943 */
944
945 void VM_spawn (void)
946 {
947         prvm_edict_t    *ed;
948         VM_SAFEPARMCOUNT(0, VM_spawn);
949         prog->xfunction->builtinsprofile += 20;
950         ed = PRVM_ED_Alloc();
951         VM_RETURN_EDICT(ed);
952 }
953
954 /*
955 =========
956 VM_remove
957
958 remove(entity e)
959 =========
960 */
961
962 void VM_remove (void)
963 {
964         prvm_edict_t    *ed;
965         prog->xfunction->builtinsprofile += 20;
966
967         VM_SAFEPARMCOUNT(1, VM_remove);
968
969         ed = PRVM_G_EDICT(OFS_PARM0);
970         if( PRVM_NUM_FOR_EDICT(ed) <= prog->reserved_edicts )
971         {
972                 if (developer.integer > 0)
973                         VM_Warning( "VM_remove: tried to remove the null entity or a reserved entity!\n" );
974         }
975         else if( ed->priv.required->free )
976         {
977                 if (developer.integer > 0)
978                         VM_Warning( "VM_remove: tried to remove an already freed entity!\n" );
979         }
980         else
981                 PRVM_ED_Free (ed);
982 }
983
984 /*
985 =========
986 VM_find
987
988 entity  find(entity start, .string field, string match)
989 =========
990 */
991
992 void VM_find (void)
993 {
994         int             e;
995         int             f;
996         const char      *s, *t;
997         prvm_edict_t    *ed;
998
999         VM_SAFEPARMCOUNT(3,VM_find);
1000
1001         e = PRVM_G_EDICTNUM(OFS_PARM0);
1002         f = PRVM_G_INT(OFS_PARM1);
1003         s = PRVM_G_STRING(OFS_PARM2);
1004
1005         // LordHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
1006         // expects it to find all the monsters, so we must be careful to support
1007         // searching for ""
1008
1009         for (e++ ; e < prog->num_edicts ; e++)
1010         {
1011                 prog->xfunction->builtinsprofile++;
1012                 ed = PRVM_EDICT_NUM(e);
1013                 if (ed->priv.required->free)
1014                         continue;
1015                 t = PRVM_E_STRING(ed,f);
1016                 if (!t)
1017                         t = "";
1018                 if (!strcmp(t,s))
1019                 {
1020                         VM_RETURN_EDICT(ed);
1021                         return;
1022                 }
1023         }
1024
1025         VM_RETURN_EDICT(prog->edicts);
1026 }
1027
1028 /*
1029 =========
1030 VM_findfloat
1031
1032   entity        findfloat(entity start, .float field, float match)
1033   entity        findentity(entity start, .entity field, entity match)
1034 =========
1035 */
1036 // LordHavoc: added this for searching float, int, and entity reference fields
1037 void VM_findfloat (void)
1038 {
1039         int             e;
1040         int             f;
1041         float   s;
1042         prvm_edict_t    *ed;
1043
1044         VM_SAFEPARMCOUNT(3,VM_findfloat);
1045
1046         e = PRVM_G_EDICTNUM(OFS_PARM0);
1047         f = PRVM_G_INT(OFS_PARM1);
1048         s = PRVM_G_FLOAT(OFS_PARM2);
1049
1050         for (e++ ; e < prog->num_edicts ; e++)
1051         {
1052                 prog->xfunction->builtinsprofile++;
1053                 ed = PRVM_EDICT_NUM(e);
1054                 if (ed->priv.required->free)
1055                         continue;
1056                 if (PRVM_E_FLOAT(ed,f) == s)
1057                 {
1058                         VM_RETURN_EDICT(ed);
1059                         return;
1060                 }
1061         }
1062
1063         VM_RETURN_EDICT(prog->edicts);
1064 }
1065
1066 /*
1067 =========
1068 VM_findchain
1069
1070 entity  findchain(.string field, string match)
1071 =========
1072 */
1073 // chained search for strings in entity fields
1074 // entity(.string field, string match) findchain = #402;
1075 void VM_findchain (void)
1076 {
1077         int             i;
1078         int             f;
1079         const char      *s, *t;
1080         prvm_edict_t    *ent, *chain;
1081         int chainfield;
1082
1083         VM_SAFEPARMCOUNTRANGE(2,3,VM_findchain);
1084
1085         if(prog->argc == 3)
1086                 chainfield = PRVM_G_INT(OFS_PARM2);
1087         else
1088                 chainfield = prog->fieldoffsets.chain;
1089         if (chainfield < 0)
1090                 PRVM_ERROR("VM_findchain: %s doesnt have the specified chain field !", PRVM_NAME);
1091
1092         chain = prog->edicts;
1093
1094         f = PRVM_G_INT(OFS_PARM0);
1095         s = PRVM_G_STRING(OFS_PARM1);
1096
1097         // LordHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
1098         // expects it to find all the monsters, so we must be careful to support
1099         // searching for ""
1100
1101         ent = PRVM_NEXT_EDICT(prog->edicts);
1102         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1103         {
1104                 prog->xfunction->builtinsprofile++;
1105                 if (ent->priv.required->free)
1106                         continue;
1107                 t = PRVM_E_STRING(ent,f);
1108                 if (!t)
1109                         t = "";
1110                 if (strcmp(t,s))
1111                         continue;
1112
1113                 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_NUM_FOR_EDICT(chain);
1114                 chain = ent;
1115         }
1116
1117         VM_RETURN_EDICT(chain);
1118 }
1119
1120 /*
1121 =========
1122 VM_findchainfloat
1123
1124 entity  findchainfloat(.string field, float match)
1125 entity  findchainentity(.string field, entity match)
1126 =========
1127 */
1128 // LordHavoc: chained search for float, int, and entity reference fields
1129 // entity(.string field, float match) findchainfloat = #403;
1130 void VM_findchainfloat (void)
1131 {
1132         int             i;
1133         int             f;
1134         float   s;
1135         prvm_edict_t    *ent, *chain;
1136         int chainfield;
1137
1138         VM_SAFEPARMCOUNTRANGE(2, 3, VM_findchainfloat);
1139
1140         if(prog->argc == 3)
1141                 chainfield = PRVM_G_INT(OFS_PARM2);
1142         else
1143                 chainfield = prog->fieldoffsets.chain;
1144         if (chainfield < 0)
1145                 PRVM_ERROR("VM_findchain: %s doesnt have the specified chain field !", PRVM_NAME);
1146
1147         chain = (prvm_edict_t *)prog->edicts;
1148
1149         f = PRVM_G_INT(OFS_PARM0);
1150         s = PRVM_G_FLOAT(OFS_PARM1);
1151
1152         ent = PRVM_NEXT_EDICT(prog->edicts);
1153         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1154         {
1155                 prog->xfunction->builtinsprofile++;
1156                 if (ent->priv.required->free)
1157                         continue;
1158                 if (PRVM_E_FLOAT(ent,f) != s)
1159                         continue;
1160
1161                 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_EDICT_TO_PROG(chain);
1162                 chain = ent;
1163         }
1164
1165         VM_RETURN_EDICT(chain);
1166 }
1167
1168 /*
1169 ========================
1170 VM_findflags
1171
1172 entity  findflags(entity start, .float field, float match)
1173 ========================
1174 */
1175 // LordHavoc: search for flags in float fields
1176 void VM_findflags (void)
1177 {
1178         int             e;
1179         int             f;
1180         int             s;
1181         prvm_edict_t    *ed;
1182
1183         VM_SAFEPARMCOUNT(3, VM_findflags);
1184
1185
1186         e = PRVM_G_EDICTNUM(OFS_PARM0);
1187         f = PRVM_G_INT(OFS_PARM1);
1188         s = (int)PRVM_G_FLOAT(OFS_PARM2);
1189
1190         for (e++ ; e < prog->num_edicts ; e++)
1191         {
1192                 prog->xfunction->builtinsprofile++;
1193                 ed = PRVM_EDICT_NUM(e);
1194                 if (ed->priv.required->free)
1195                         continue;
1196                 if (!PRVM_E_FLOAT(ed,f))
1197                         continue;
1198                 if ((int)PRVM_E_FLOAT(ed,f) & s)
1199                 {
1200                         VM_RETURN_EDICT(ed);
1201                         return;
1202                 }
1203         }
1204
1205         VM_RETURN_EDICT(prog->edicts);
1206 }
1207
1208 /*
1209 ========================
1210 VM_findchainflags
1211
1212 entity  findchainflags(.float field, float match)
1213 ========================
1214 */
1215 // LordHavoc: chained search for flags in float fields
1216 void VM_findchainflags (void)
1217 {
1218         int             i;
1219         int             f;
1220         int             s;
1221         prvm_edict_t    *ent, *chain;
1222         int chainfield;
1223
1224         VM_SAFEPARMCOUNTRANGE(2, 3, VM_findchainflags);
1225
1226         if(prog->argc == 3)
1227                 chainfield = PRVM_G_INT(OFS_PARM2);
1228         else
1229                 chainfield = prog->fieldoffsets.chain;
1230         if (chainfield < 0)
1231                 PRVM_ERROR("VM_findchain: %s doesnt have the specified chain field !", PRVM_NAME);
1232
1233         chain = (prvm_edict_t *)prog->edicts;
1234
1235         f = PRVM_G_INT(OFS_PARM0);
1236         s = (int)PRVM_G_FLOAT(OFS_PARM1);
1237
1238         ent = PRVM_NEXT_EDICT(prog->edicts);
1239         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1240         {
1241                 prog->xfunction->builtinsprofile++;
1242                 if (ent->priv.required->free)
1243                         continue;
1244                 if (!PRVM_E_FLOAT(ent,f))
1245                         continue;
1246                 if (!((int)PRVM_E_FLOAT(ent,f) & s))
1247                         continue;
1248
1249                 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_EDICT_TO_PROG(chain);
1250                 chain = ent;
1251         }
1252
1253         VM_RETURN_EDICT(chain);
1254 }
1255
1256 /*
1257 =========
1258 VM_precache_sound
1259
1260 string  precache_sound (string sample)
1261 =========
1262 */
1263 void VM_precache_sound (void)
1264 {
1265         const char *s;
1266
1267         VM_SAFEPARMCOUNT(1, VM_precache_sound);
1268
1269         s = PRVM_G_STRING(OFS_PARM0);
1270         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
1271         //VM_CheckEmptyString(s);
1272
1273         if(snd_initialized.integer && !S_PrecacheSound(s, true, true))
1274         {
1275                 VM_Warning("VM_precache_sound: Failed to load %s for %s\n", s, PRVM_NAME);
1276                 return;
1277         }
1278 }
1279
1280 /*
1281 =================
1282 VM_precache_file
1283
1284 returns the same string as output
1285
1286 does nothing, only used by qcc to build .pak archives
1287 =================
1288 */
1289 void VM_precache_file (void)
1290 {
1291         VM_SAFEPARMCOUNT(1,VM_precache_file);
1292         // precache_file is only used to copy files with qcc, it does nothing
1293         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
1294 }
1295
1296 /*
1297 =========
1298 VM_coredump
1299
1300 coredump()
1301 =========
1302 */
1303 void VM_coredump (void)
1304 {
1305         VM_SAFEPARMCOUNT(0,VM_coredump);
1306
1307         Cbuf_AddText("prvm_edicts ");
1308         Cbuf_AddText(PRVM_NAME);
1309         Cbuf_AddText("\n");
1310 }
1311
1312 /*
1313 =========
1314 VM_stackdump
1315
1316 stackdump()
1317 =========
1318 */
1319 void PRVM_StackTrace(void);
1320 void VM_stackdump (void)
1321 {
1322         VM_SAFEPARMCOUNT(0, VM_stackdump);
1323
1324         PRVM_StackTrace();
1325 }
1326
1327 /*
1328 =========
1329 VM_crash
1330
1331 crash()
1332 =========
1333 */
1334
1335 void VM_crash(void)
1336 {
1337         VM_SAFEPARMCOUNT(0, VM_crash);
1338
1339         PRVM_ERROR("Crash called by %s",PRVM_NAME);
1340 }
1341
1342 /*
1343 =========
1344 VM_traceon
1345
1346 traceon()
1347 =========
1348 */
1349 void VM_traceon (void)
1350 {
1351         VM_SAFEPARMCOUNT(0,VM_traceon);
1352
1353         prog->trace = true;
1354 }
1355
1356 /*
1357 =========
1358 VM_traceoff
1359
1360 traceoff()
1361 =========
1362 */
1363 void VM_traceoff (void)
1364 {
1365         VM_SAFEPARMCOUNT(0,VM_traceoff);
1366
1367         prog->trace = false;
1368 }
1369
1370 /*
1371 =========
1372 VM_eprint
1373
1374 eprint(entity e)
1375 =========
1376 */
1377 void VM_eprint (void)
1378 {
1379         VM_SAFEPARMCOUNT(1,VM_eprint);
1380
1381         PRVM_ED_PrintNum (PRVM_G_EDICTNUM(OFS_PARM0), NULL);
1382 }
1383
1384 /*
1385 =========
1386 VM_rint
1387
1388 float   rint(float)
1389 =========
1390 */
1391 void VM_rint (void)
1392 {
1393         float f;
1394         VM_SAFEPARMCOUNT(1,VM_rint);
1395
1396         f = PRVM_G_FLOAT(OFS_PARM0);
1397         if (f > 0)
1398                 PRVM_G_FLOAT(OFS_RETURN) = floor(f + 0.5);
1399         else
1400                 PRVM_G_FLOAT(OFS_RETURN) = ceil(f - 0.5);
1401 }
1402
1403 /*
1404 =========
1405 VM_floor
1406
1407 float   floor(float)
1408 =========
1409 */
1410 void VM_floor (void)
1411 {
1412         VM_SAFEPARMCOUNT(1,VM_floor);
1413
1414         PRVM_G_FLOAT(OFS_RETURN) = floor(PRVM_G_FLOAT(OFS_PARM0));
1415 }
1416
1417 /*
1418 =========
1419 VM_ceil
1420
1421 float   ceil(float)
1422 =========
1423 */
1424 void VM_ceil (void)
1425 {
1426         VM_SAFEPARMCOUNT(1,VM_ceil);
1427
1428         PRVM_G_FLOAT(OFS_RETURN) = ceil(PRVM_G_FLOAT(OFS_PARM0));
1429 }
1430
1431
1432 /*
1433 =============
1434 VM_nextent
1435
1436 entity  nextent(entity)
1437 =============
1438 */
1439 void VM_nextent (void)
1440 {
1441         int             i;
1442         prvm_edict_t    *ent;
1443
1444         VM_SAFEPARMCOUNT(1, VM_nextent);
1445
1446         i = PRVM_G_EDICTNUM(OFS_PARM0);
1447         while (1)
1448         {
1449                 prog->xfunction->builtinsprofile++;
1450                 i++;
1451                 if (i == prog->num_edicts)
1452                 {
1453                         VM_RETURN_EDICT(prog->edicts);
1454                         return;
1455                 }
1456                 ent = PRVM_EDICT_NUM(i);
1457                 if (!ent->priv.required->free)
1458                 {
1459                         VM_RETURN_EDICT(ent);
1460                         return;
1461                 }
1462         }
1463 }
1464
1465 //=============================================================================
1466
1467 /*
1468 ==============
1469 VM_changelevel
1470 server and menu
1471
1472 changelevel(string map)
1473 ==============
1474 */
1475 void VM_changelevel (void)
1476 {
1477         VM_SAFEPARMCOUNT(1, VM_changelevel);
1478
1479         if(!sv.active)
1480         {
1481                 VM_Warning("VM_changelevel: game is not server (%s)\n", PRVM_NAME);
1482                 return;
1483         }
1484
1485 // make sure we don't issue two changelevels
1486         if (svs.changelevel_issued)
1487                 return;
1488         svs.changelevel_issued = true;
1489
1490         Cbuf_AddText (va("changelevel %s\n",PRVM_G_STRING(OFS_PARM0)));
1491 }
1492
1493 /*
1494 =========
1495 VM_sin
1496
1497 float   sin(float)
1498 =========
1499 */
1500 void VM_sin (void)
1501 {
1502         VM_SAFEPARMCOUNT(1,VM_sin);
1503         PRVM_G_FLOAT(OFS_RETURN) = sin(PRVM_G_FLOAT(OFS_PARM0));
1504 }
1505
1506 /*
1507 =========
1508 VM_cos
1509 float   cos(float)
1510 =========
1511 */
1512 void VM_cos (void)
1513 {
1514         VM_SAFEPARMCOUNT(1,VM_cos);
1515         PRVM_G_FLOAT(OFS_RETURN) = cos(PRVM_G_FLOAT(OFS_PARM0));
1516 }
1517
1518 /*
1519 =========
1520 VM_sqrt
1521
1522 float   sqrt(float)
1523 =========
1524 */
1525 void VM_sqrt (void)
1526 {
1527         VM_SAFEPARMCOUNT(1,VM_sqrt);
1528         PRVM_G_FLOAT(OFS_RETURN) = sqrt(PRVM_G_FLOAT(OFS_PARM0));
1529 }
1530
1531 /*
1532 =========
1533 VM_asin
1534
1535 float   asin(float)
1536 =========
1537 */
1538 void VM_asin (void)
1539 {
1540         VM_SAFEPARMCOUNT(1,VM_asin);
1541         PRVM_G_FLOAT(OFS_RETURN) = asin(PRVM_G_FLOAT(OFS_PARM0));
1542 }
1543
1544 /*
1545 =========
1546 VM_acos
1547 float   acos(float)
1548 =========
1549 */
1550 void VM_acos (void)
1551 {
1552         VM_SAFEPARMCOUNT(1,VM_acos);
1553         PRVM_G_FLOAT(OFS_RETURN) = acos(PRVM_G_FLOAT(OFS_PARM0));
1554 }
1555
1556 /*
1557 =========
1558 VM_atan
1559 float   atan(float)
1560 =========
1561 */
1562 void VM_atan (void)
1563 {
1564         VM_SAFEPARMCOUNT(1,VM_atan);
1565         PRVM_G_FLOAT(OFS_RETURN) = atan(PRVM_G_FLOAT(OFS_PARM0));
1566 }
1567
1568 /*
1569 =========
1570 VM_atan2
1571 float   atan2(float,float)
1572 =========
1573 */
1574 void VM_atan2 (void)
1575 {
1576         VM_SAFEPARMCOUNT(2,VM_atan2);
1577         PRVM_G_FLOAT(OFS_RETURN) = atan2(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1578 }
1579
1580 /*
1581 =========
1582 VM_tan
1583 float   tan(float)
1584 =========
1585 */
1586 void VM_tan (void)
1587 {
1588         VM_SAFEPARMCOUNT(1,VM_tan);
1589         PRVM_G_FLOAT(OFS_RETURN) = tan(PRVM_G_FLOAT(OFS_PARM0));
1590 }
1591
1592 /*
1593 =================
1594 VM_randomvec
1595
1596 Returns a vector of length < 1 and > 0
1597
1598 vector randomvec()
1599 =================
1600 */
1601 void VM_randomvec (void)
1602 {
1603         vec3_t          temp;
1604         //float         length;
1605
1606         VM_SAFEPARMCOUNT(0, VM_randomvec);
1607
1608         //// WTF ??
1609         do
1610         {
1611                 temp[0] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1612                 temp[1] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1613                 temp[2] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1614         }
1615         while (DotProduct(temp, temp) >= 1);
1616         VectorCopy (temp, PRVM_G_VECTOR(OFS_RETURN));
1617
1618         /*
1619         temp[0] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1620         temp[1] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1621         temp[2] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1622         // length returned always > 0
1623         length = (rand()&32766 + 1) * (1.0 / 32767.0) / VectorLength(temp);
1624         VectorScale(temp,length, temp);*/
1625         //VectorCopy(temp, PRVM_G_VECTOR(OFS_RETURN));
1626 }
1627
1628 //=============================================================================
1629
1630 /*
1631 =========
1632 VM_registercvar
1633
1634 float   registercvar (string name, string value[, float flags])
1635 =========
1636 */
1637 void VM_registercvar (void)
1638 {
1639         const char *name, *value;
1640         int     flags;
1641
1642         VM_SAFEPARMCOUNTRANGE(2, 3, VM_registercvar);
1643
1644         name = PRVM_G_STRING(OFS_PARM0);
1645         value = PRVM_G_STRING(OFS_PARM1);
1646         flags = prog->argc >= 3 ? (int)PRVM_G_FLOAT(OFS_PARM2) : 0;
1647         PRVM_G_FLOAT(OFS_RETURN) = 0;
1648
1649         if(flags > CVAR_MAXFLAGSVAL)
1650                 return;
1651
1652 // first check to see if it has already been defined
1653         if (Cvar_FindVar (name))
1654                 return;
1655
1656 // check for overlap with a command
1657         if (Cmd_Exists (name))
1658         {
1659                 VM_Warning("VM_registercvar: %s is a command\n", name);
1660                 return;
1661         }
1662
1663         Cvar_Get(name, value, flags, NULL);
1664
1665         PRVM_G_FLOAT(OFS_RETURN) = 1; // success
1666 }
1667
1668
1669 /*
1670 =================
1671 VM_min
1672
1673 returns the minimum of two supplied floats
1674
1675 float min(float a, float b, ...[float])
1676 =================
1677 */
1678 void VM_min (void)
1679 {
1680         VM_SAFEPARMCOUNTRANGE(2, 8, VM_min);
1681         // LordHavoc: 3+ argument enhancement suggested by FrikaC
1682         if (prog->argc >= 3)
1683         {
1684                 int i;
1685                 float f = PRVM_G_FLOAT(OFS_PARM0);
1686                 for (i = 1;i < prog->argc;i++)
1687                         if (f > PRVM_G_FLOAT((OFS_PARM0+i*3)))
1688                                 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1689                 PRVM_G_FLOAT(OFS_RETURN) = f;
1690         }
1691         else
1692                 PRVM_G_FLOAT(OFS_RETURN) = min(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1693 }
1694
1695 /*
1696 =================
1697 VM_max
1698
1699 returns the maximum of two supplied floats
1700
1701 float   max(float a, float b, ...[float])
1702 =================
1703 */
1704 void VM_max (void)
1705 {
1706         VM_SAFEPARMCOUNTRANGE(2, 8, VM_max);
1707         // LordHavoc: 3+ argument enhancement suggested by FrikaC
1708         if (prog->argc >= 3)
1709         {
1710                 int i;
1711                 float f = PRVM_G_FLOAT(OFS_PARM0);
1712                 for (i = 1;i < prog->argc;i++)
1713                         if (f < PRVM_G_FLOAT((OFS_PARM0+i*3)))
1714                                 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1715                 PRVM_G_FLOAT(OFS_RETURN) = f;
1716         }
1717         else
1718                 PRVM_G_FLOAT(OFS_RETURN) = max(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1719 }
1720
1721 /*
1722 =================
1723 VM_bound
1724
1725 returns number bounded by supplied range
1726
1727 float   bound(float min, float value, float max)
1728 =================
1729 */
1730 void VM_bound (void)
1731 {
1732         VM_SAFEPARMCOUNT(3,VM_bound);
1733         PRVM_G_FLOAT(OFS_RETURN) = bound(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1), PRVM_G_FLOAT(OFS_PARM2));
1734 }
1735
1736 /*
1737 =================
1738 VM_pow
1739
1740 returns a raised to power b
1741
1742 float   pow(float a, float b)
1743 =================
1744 */
1745 void VM_pow (void)
1746 {
1747         VM_SAFEPARMCOUNT(2,VM_pow);
1748         PRVM_G_FLOAT(OFS_RETURN) = pow(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1749 }
1750
1751 void VM_log (void)
1752 {
1753         VM_SAFEPARMCOUNT(1,VM_log);
1754         PRVM_G_FLOAT(OFS_RETURN) = log(PRVM_G_FLOAT(OFS_PARM0));
1755 }
1756
1757 void VM_Files_Init(void)
1758 {
1759         int i;
1760         for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1761                 prog->openfiles[i] = NULL;
1762 }
1763
1764 void VM_Files_CloseAll(void)
1765 {
1766         int i;
1767         for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1768         {
1769                 if (prog->openfiles[i])
1770                         FS_Close(prog->openfiles[i]);
1771                 prog->openfiles[i] = NULL;
1772         }
1773 }
1774
1775 static qfile_t *VM_GetFileHandle( int index )
1776 {
1777         if (index < 0 || index >= PRVM_MAX_OPENFILES)
1778         {
1779                 Con_Printf("VM_GetFileHandle: invalid file handle %i used in %s\n", index, PRVM_NAME);
1780                 return NULL;
1781         }
1782         if (prog->openfiles[index] == NULL)
1783         {
1784                 Con_Printf("VM_GetFileHandle: no such file handle %i (or file has been closed) in %s\n", index, PRVM_NAME);
1785                 return NULL;
1786         }
1787         return prog->openfiles[index];
1788 }
1789
1790 /*
1791 =========
1792 VM_fopen
1793
1794 float   fopen(string filename, float mode)
1795 =========
1796 */
1797 // float(string filename, float mode) fopen = #110;
1798 // opens a file inside quake/gamedir/data/ (mode is FILE_READ, FILE_APPEND, or FILE_WRITE),
1799 // returns fhandle >= 0 if successful, or fhandle < 0 if unable to open file for any reason
1800 void VM_fopen(void)
1801 {
1802         int filenum, mode;
1803         const char *modestring, *filename;
1804
1805         VM_SAFEPARMCOUNT(2,VM_fopen);
1806
1807         for (filenum = 0;filenum < PRVM_MAX_OPENFILES;filenum++)
1808                 if (prog->openfiles[filenum] == NULL)
1809                         break;
1810         if (filenum >= PRVM_MAX_OPENFILES)
1811         {
1812                 PRVM_G_FLOAT(OFS_RETURN) = -2;
1813                 VM_Warning("VM_fopen: %s ran out of file handles (%i)\n", PRVM_NAME, PRVM_MAX_OPENFILES);
1814                 return;
1815         }
1816         filename = PRVM_G_STRING(OFS_PARM0);
1817         mode = (int)PRVM_G_FLOAT(OFS_PARM1);
1818         switch(mode)
1819         {
1820         case 0: // FILE_READ
1821                 modestring = "rb";
1822                 prog->openfiles[filenum] = FS_OpenVirtualFile(va("data/%s", filename), false);
1823                 if (prog->openfiles[filenum] == NULL)
1824                         prog->openfiles[filenum] = FS_OpenVirtualFile(va("%s", filename), false);
1825                 break;
1826         case 1: // FILE_APPEND
1827                 modestring = "a";
1828                 prog->openfiles[filenum] = FS_OpenRealFile(va("data/%s", filename), modestring, false);
1829                 break;
1830         case 2: // FILE_WRITE
1831                 modestring = "w";
1832                 prog->openfiles[filenum] = FS_OpenRealFile(va("data/%s", filename), modestring, false);
1833                 break;
1834         default:
1835                 PRVM_G_FLOAT(OFS_RETURN) = -3;
1836                 VM_Warning("VM_fopen: %s: no such mode %i (valid: 0 = read, 1 = append, 2 = write)\n", PRVM_NAME, mode);
1837                 return;
1838         }
1839
1840         if (prog->openfiles[filenum] == NULL)
1841         {
1842                 PRVM_G_FLOAT(OFS_RETURN) = -1;
1843                 if (developer_extra.integer)
1844                         VM_Warning("VM_fopen: %s: %s mode %s failed\n", PRVM_NAME, filename, modestring);
1845         }
1846         else
1847         {
1848                 PRVM_G_FLOAT(OFS_RETURN) = filenum;
1849                 if (developer_extra.integer)
1850                         Con_DPrintf("VM_fopen: %s: %s mode %s opened as #%i\n", PRVM_NAME, filename, modestring, filenum);
1851                 prog->openfiles_origin[filenum] = PRVM_AllocationOrigin();
1852         }
1853 }
1854
1855 /*
1856 =========
1857 VM_fclose
1858
1859 fclose(float fhandle)
1860 =========
1861 */
1862 //void(float fhandle) fclose = #111; // closes a file
1863 void VM_fclose(void)
1864 {
1865         int filenum;
1866
1867         VM_SAFEPARMCOUNT(1,VM_fclose);
1868
1869         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1870         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1871         {
1872                 VM_Warning("VM_fclose: invalid file handle %i used in %s\n", filenum, PRVM_NAME);
1873                 return;
1874         }
1875         if (prog->openfiles[filenum] == NULL)
1876         {
1877                 VM_Warning("VM_fclose: no such file handle %i (or file has been closed) in %s\n", filenum, PRVM_NAME);
1878                 return;
1879         }
1880         FS_Close(prog->openfiles[filenum]);
1881         prog->openfiles[filenum] = NULL;
1882         if(prog->openfiles_origin[filenum])
1883                 PRVM_Free((char *)prog->openfiles_origin[filenum]);
1884         if (developer_extra.integer)
1885                 Con_DPrintf("VM_fclose: %s: #%i closed\n", PRVM_NAME, filenum);
1886 }
1887
1888 /*
1889 =========
1890 VM_fgets
1891
1892 string  fgets(float fhandle)
1893 =========
1894 */
1895 //string(float fhandle) fgets = #112; // reads a line of text from the file and returns as a tempstring
1896 void VM_fgets(void)
1897 {
1898         int c, end;
1899         char string[VM_STRINGTEMP_LENGTH];
1900         int filenum;
1901
1902         VM_SAFEPARMCOUNT(1,VM_fgets);
1903
1904         // set the return value regardless of any possible errors
1905         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
1906
1907         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1908         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1909         {
1910                 VM_Warning("VM_fgets: invalid file handle %i used in %s\n", filenum, PRVM_NAME);
1911                 return;
1912         }
1913         if (prog->openfiles[filenum] == NULL)
1914         {
1915                 VM_Warning("VM_fgets: no such file handle %i (or file has been closed) in %s\n", filenum, PRVM_NAME);
1916                 return;
1917         }
1918         end = 0;
1919         for (;;)
1920         {
1921                 c = FS_Getc(prog->openfiles[filenum]);
1922                 if (c == '\r' || c == '\n' || c < 0)
1923                         break;
1924                 if (end < VM_STRINGTEMP_LENGTH - 1)
1925                         string[end++] = c;
1926         }
1927         string[end] = 0;
1928         // remove \n following \r
1929         if (c == '\r')
1930         {
1931                 c = FS_Getc(prog->openfiles[filenum]);
1932                 if (c != '\n')
1933                         FS_UnGetc(prog->openfiles[filenum], (unsigned char)c);
1934         }
1935         if (developer_extra.integer)
1936                 Con_DPrintf("fgets: %s: %s\n", PRVM_NAME, string);
1937         if (c >= 0 || end)
1938                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
1939 }
1940
1941 /*
1942 =========
1943 VM_fputs
1944
1945 fputs(float fhandle, string s)
1946 =========
1947 */
1948 //void(float fhandle, string s) fputs = #113; // writes a line of text to the end of the file
1949 void VM_fputs(void)
1950 {
1951         int stringlength;
1952         char string[VM_STRINGTEMP_LENGTH];
1953         int filenum;
1954
1955         VM_SAFEPARMCOUNT(2,VM_fputs);
1956
1957         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1958         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1959         {
1960                 VM_Warning("VM_fputs: invalid file handle %i used in %s\n", filenum, PRVM_NAME);
1961                 return;
1962         }
1963         if (prog->openfiles[filenum] == NULL)
1964         {
1965                 VM_Warning("VM_fputs: no such file handle %i (or file has been closed) in %s\n", filenum, PRVM_NAME);
1966                 return;
1967         }
1968         VM_VarString(1, string, sizeof(string));
1969         if ((stringlength = (int)strlen(string)))
1970                 FS_Write(prog->openfiles[filenum], string, stringlength);
1971         if (developer_extra.integer)
1972                 Con_DPrintf("fputs: %s: %s\n", PRVM_NAME, string);
1973 }
1974
1975 /*
1976 =========
1977 VM_writetofile
1978
1979         writetofile(float fhandle, entity ent)
1980 =========
1981 */
1982 void VM_writetofile(void)
1983 {
1984         prvm_edict_t * ent;
1985         qfile_t *file;
1986
1987         VM_SAFEPARMCOUNT(2, VM_writetofile);
1988
1989         file = VM_GetFileHandle( (int)PRVM_G_FLOAT(OFS_PARM0) );
1990         if( !file )
1991         {
1992                 VM_Warning("VM_writetofile: invalid or closed file handle\n");
1993                 return;
1994         }
1995
1996         ent = PRVM_G_EDICT(OFS_PARM1);
1997         if(ent->priv.required->free)
1998         {
1999                 VM_Warning("VM_writetofile: %s: entity %i is free !\n", PRVM_NAME, PRVM_NUM_FOR_EDICT(ent));
2000                 return;
2001         }
2002
2003         PRVM_ED_Write (file, ent);
2004 }
2005
2006 // KrimZon - DP_QC_ENTITYDATA
2007 /*
2008 =========
2009 VM_numentityfields
2010
2011 float() numentityfields
2012 Return the number of entity fields - NOT offsets
2013 =========
2014 */
2015 void VM_numentityfields(void)
2016 {
2017         PRVM_G_FLOAT(OFS_RETURN) = prog->numfielddefs;
2018 }
2019
2020 // KrimZon - DP_QC_ENTITYDATA
2021 /*
2022 =========
2023 VM_entityfieldname
2024
2025 string(float fieldnum) entityfieldname
2026 Return name of the specified field as a string, or empty if the field is invalid (warning)
2027 =========
2028 */
2029 void VM_entityfieldname(void)
2030 {
2031         ddef_t *d;
2032         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2033         
2034         if (i < 0 || i >= prog->numfielddefs)
2035         {
2036         VM_Warning("VM_entityfieldname: %s: field index out of bounds\n", PRVM_NAME);
2037         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
2038                 return;
2039         }
2040         
2041         d = &prog->fielddefs[i];
2042         PRVM_G_INT(OFS_RETURN) = d->s_name; // presuming that s_name points to a string already
2043 }
2044
2045 // KrimZon - DP_QC_ENTITYDATA
2046 /*
2047 =========
2048 VM_entityfieldtype
2049
2050 float(float fieldnum) entityfieldtype
2051 =========
2052 */
2053 void VM_entityfieldtype(void)
2054 {
2055         ddef_t *d;
2056         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2057         
2058         if (i < 0 || i >= prog->numfielddefs)
2059         {
2060                 VM_Warning("VM_entityfieldtype: %s: field index out of bounds\n", PRVM_NAME);
2061                 PRVM_G_FLOAT(OFS_RETURN) = -1.0;
2062                 return;
2063         }
2064         
2065         d = &prog->fielddefs[i];
2066         PRVM_G_FLOAT(OFS_RETURN) = (float)d->type;
2067 }
2068
2069 // KrimZon - DP_QC_ENTITYDATA
2070 /*
2071 =========
2072 VM_getentityfieldstring
2073
2074 string(float fieldnum, entity ent) getentityfieldstring
2075 =========
2076 */
2077 void VM_getentityfieldstring(void)
2078 {
2079         // put the data into a string
2080         ddef_t *d;
2081         int type, j;
2082         int *v;
2083         prvm_edict_t * ent;
2084         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2085         
2086         if (i < 0 || i >= prog->numfielddefs)
2087         {
2088         VM_Warning("VM_entityfielddata: %s: field index out of bounds\n", PRVM_NAME);
2089                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
2090                 return;
2091         }
2092         
2093         d = &prog->fielddefs[i];
2094         
2095         // get the entity
2096         ent = PRVM_G_EDICT(OFS_PARM1);
2097         if(ent->priv.required->free)
2098         {
2099                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
2100                 VM_Warning("VM_entityfielddata: %s: entity %i is free !\n", PRVM_NAME, PRVM_NUM_FOR_EDICT(ent));
2101                 return;
2102         }
2103         v = (int *)((char *)ent->fields.vp + d->ofs*4);
2104         
2105         // if it's 0 or blank, return an empty string
2106         type = d->type & ~DEF_SAVEGLOBAL;
2107         for (j=0 ; j<prvm_type_size[type] ; j++)
2108                 if (v[j])
2109                         break;
2110         if (j == prvm_type_size[type])
2111         {
2112                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
2113                 return;
2114         }
2115                 
2116         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(PRVM_UglyValueString((etype_t)d->type, (prvm_eval_t *)v));
2117 }
2118
2119 // KrimZon - DP_QC_ENTITYDATA
2120 /*
2121 =========
2122 VM_putentityfieldstring
2123
2124 float(float fieldnum, entity ent, string s) putentityfieldstring
2125 =========
2126 */
2127 void VM_putentityfieldstring(void)
2128 {
2129         ddef_t *d;
2130         prvm_edict_t * ent;
2131         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2132
2133         if (i < 0 || i >= prog->numfielddefs)
2134         {
2135         VM_Warning("VM_entityfielddata: %s: field index out of bounds\n", PRVM_NAME);
2136                 PRVM_G_FLOAT(OFS_RETURN) = 0.0f;
2137                 return;
2138         }
2139
2140         d = &prog->fielddefs[i];
2141
2142         // get the entity
2143         ent = PRVM_G_EDICT(OFS_PARM1);
2144         if(ent->priv.required->free)
2145         {
2146                 VM_Warning("VM_entityfielddata: %s: entity %i is free !\n", PRVM_NAME, PRVM_NUM_FOR_EDICT(ent));
2147                 PRVM_G_FLOAT(OFS_RETURN) = 0.0f;
2148                 return;
2149         }
2150
2151         // parse the string into the value
2152         PRVM_G_FLOAT(OFS_RETURN) = ( PRVM_ED_ParseEpair(ent, d, PRVM_G_STRING(OFS_PARM2), false) ) ? 1.0f : 0.0f;
2153 }
2154
2155 /*
2156 =========
2157 VM_strlen
2158
2159 float   strlen(string s)
2160 =========
2161 */
2162 //float(string s) strlen = #114; // returns how many characters are in a string
2163 void VM_strlen(void)
2164 {
2165         VM_SAFEPARMCOUNT(1,VM_strlen);
2166
2167         //PRVM_G_FLOAT(OFS_RETURN) = strlen(PRVM_G_STRING(OFS_PARM0));
2168         PRVM_G_FLOAT(OFS_RETURN) = u8_strlen(PRVM_G_STRING(OFS_PARM0));
2169 }
2170
2171 // DRESK - Decolorized String
2172 /*
2173 =========
2174 VM_strdecolorize
2175
2176 string  strdecolorize(string s)
2177 =========
2178 */
2179 // string (string s) strdecolorize = #472; // returns the passed in string with color codes stripped
2180 void VM_strdecolorize(void)
2181 {
2182         char szNewString[VM_STRINGTEMP_LENGTH];
2183         const char *szString;
2184
2185         // Prepare Strings
2186         VM_SAFEPARMCOUNT(1,VM_strdecolorize);
2187         szString = PRVM_G_STRING(OFS_PARM0);
2188         COM_StringDecolorize(szString, 0, szNewString, sizeof(szNewString), TRUE);
2189         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(szNewString);
2190 }
2191
2192 // DRESK - String Length (not counting color codes)
2193 /*
2194 =========
2195 VM_strlennocol
2196
2197 float   strlennocol(string s)
2198 =========
2199 */
2200 // float(string s) strlennocol = #471; // returns how many characters are in a string not including color codes
2201 // For example, ^2Dresk returns a length of 5
2202 void VM_strlennocol(void)
2203 {
2204         const char *szString;
2205         int nCnt;
2206
2207         VM_SAFEPARMCOUNT(1,VM_strlennocol);
2208
2209         szString = PRVM_G_STRING(OFS_PARM0);
2210
2211         //nCnt = COM_StringLengthNoColors(szString, 0, NULL);
2212         nCnt = u8_COM_StringLengthNoColors(szString, 0, NULL);
2213
2214         PRVM_G_FLOAT(OFS_RETURN) = nCnt;
2215 }
2216
2217 // DRESK - String to Uppercase and Lowercase
2218 /*
2219 =========
2220 VM_strtolower
2221
2222 string  strtolower(string s)
2223 =========
2224 */
2225 // string (string s) strtolower = #480; // returns passed in string in lowercase form
2226 void VM_strtolower(void)
2227 {
2228         char szNewString[VM_STRINGTEMP_LENGTH];
2229         const char *szString;
2230
2231         // Prepare Strings
2232         VM_SAFEPARMCOUNT(1,VM_strtolower);
2233         szString = PRVM_G_STRING(OFS_PARM0);
2234
2235         COM_ToLowerString(szString, szNewString, sizeof(szNewString) );
2236
2237         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(szNewString);
2238 }
2239
2240 /*
2241 =========
2242 VM_strtoupper
2243
2244 string  strtoupper(string s)
2245 =========
2246 */
2247 // string (string s) strtoupper = #481; // returns passed in string in uppercase form
2248 void VM_strtoupper(void)
2249 {
2250         char szNewString[VM_STRINGTEMP_LENGTH];
2251         const char *szString;
2252
2253         // Prepare Strings
2254         VM_SAFEPARMCOUNT(1,VM_strtoupper);
2255         szString = PRVM_G_STRING(OFS_PARM0);
2256
2257         COM_ToUpperString(szString, szNewString, sizeof(szNewString) );
2258
2259         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(szNewString);
2260 }
2261
2262 /*
2263 =========
2264 VM_strcat
2265
2266 string strcat(string,string,...[string])
2267 =========
2268 */
2269 //string(string s1, string s2) strcat = #115;
2270 // concatenates two strings (for example "abc", "def" would return "abcdef")
2271 // and returns as a tempstring
2272 void VM_strcat(void)
2273 {
2274         char s[VM_STRINGTEMP_LENGTH];
2275         VM_SAFEPARMCOUNTRANGE(1, 8, VM_strcat);
2276
2277         VM_VarString(0, s, sizeof(s));
2278         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(s);
2279 }
2280
2281 /*
2282 =========
2283 VM_substring
2284
2285 string  substring(string s, float start, float length)
2286 =========
2287 */
2288 // string(string s, float start, float length) substring = #116;
2289 // returns a section of a string as a tempstring
2290 void VM_substring(void)
2291 {
2292         int start, length;
2293         int u_slength = 0, u_start;
2294         size_t u_length;
2295         const char *s;
2296         char string[VM_STRINGTEMP_LENGTH];
2297
2298         VM_SAFEPARMCOUNT(3,VM_substring);
2299
2300         /*
2301         s = PRVM_G_STRING(OFS_PARM0);
2302         start = (int)PRVM_G_FLOAT(OFS_PARM1);
2303         length = (int)PRVM_G_FLOAT(OFS_PARM2);
2304         slength = strlen(s);
2305
2306         if (start < 0) // FTE_STRINGS feature
2307                 start += slength;
2308         start = bound(0, start, slength);
2309
2310         if (length < 0) // FTE_STRINGS feature
2311                 length += slength - start + 1;
2312         maxlen = min((int)sizeof(string) - 1, slength - start);
2313         length = bound(0, length, maxlen);
2314
2315         memcpy(string, s + start, length);
2316         string[length] = 0;
2317         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
2318         */
2319         
2320         s = PRVM_G_STRING(OFS_PARM0);
2321         start = (int)PRVM_G_FLOAT(OFS_PARM1);
2322         length = (int)PRVM_G_FLOAT(OFS_PARM2);
2323
2324         if (start < 0) // FTE_STRINGS feature
2325         {
2326                 u_slength = u8_strlen(s);
2327                 start += u_slength;
2328                 start = bound(0, start, u_slength);
2329         }
2330
2331         if (length < 0) // FTE_STRINGS feature
2332         {
2333                 if (!u_slength) // it's not calculated when it's not needed above
2334                         u_slength = u8_strlen(s);
2335                 length += u_slength - start + 1;
2336         }
2337                 
2338         // positive start, positive length
2339         u_start = u8_byteofs(s, start, NULL);
2340         if (u_start < 0)
2341         {
2342                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
2343                 return;
2344         }
2345         u_length = u8_bytelen(s + u_start, length);
2346         if (u_length >= sizeof(string)-1)
2347                 u_length = sizeof(string)-1;
2348         
2349         memcpy(string, s + u_start, u_length);
2350         string[u_length] = 0;
2351         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
2352 }
2353
2354 /*
2355 =========
2356 VM_strreplace
2357
2358 string(string search, string replace, string subject) strreplace = #484;
2359 =========
2360 */
2361 // replaces all occurrences of search with replace in the string subject, and returns the result
2362 void VM_strreplace(void)
2363 {
2364         int i, j, si;
2365         const char *search, *replace, *subject;
2366         char string[VM_STRINGTEMP_LENGTH];
2367         int search_len, replace_len, subject_len;
2368
2369         VM_SAFEPARMCOUNT(3,VM_strreplace);
2370
2371         search = PRVM_G_STRING(OFS_PARM0);
2372         replace = PRVM_G_STRING(OFS_PARM1);
2373         subject = PRVM_G_STRING(OFS_PARM2);
2374
2375         search_len = (int)strlen(search);
2376         replace_len = (int)strlen(replace);
2377         subject_len = (int)strlen(subject);
2378
2379         si = 0;
2380         for (i = 0; i <= subject_len - search_len; i++)
2381         {
2382                 for (j = 0; j < search_len; j++) // thus, i+j < subject_len
2383                         if (subject[i+j] != search[j])
2384                                 break;
2385                 if (j == search_len)
2386                 {
2387                         // NOTE: if search_len == 0, we always hit THIS case, and never the other
2388                         // found it at offset 'i'
2389                         for (j = 0; j < replace_len && si < (int)sizeof(string) - 1; j++)
2390                                 string[si++] = replace[j];
2391                         if(search_len > 0)
2392                         {
2393                                 i += search_len - 1;
2394                         }
2395                         else
2396                         {
2397                                 // the above would subtract 1 from i... so we
2398                                 // don't do that, but instead output the next
2399                                 // char
2400                                 if (si < (int)sizeof(string) - 1)
2401                                         string[si++] = subject[i];
2402                         }
2403                 }
2404                 else
2405                 {
2406                         // in THIS case, we know search_len > 0, thus i < subject_len
2407                         // not found
2408                         if (si < (int)sizeof(string) - 1)
2409                                 string[si++] = subject[i];
2410                 }
2411         }
2412         // remaining chars (these cannot match)
2413         for (; i < subject_len; i++)
2414                 if (si < (int)sizeof(string) - 1)
2415                         string[si++] = subject[i];
2416         string[si] = '\0';
2417
2418         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
2419 }
2420
2421 /*
2422 =========
2423 VM_strireplace
2424
2425 string(string search, string replace, string subject) strireplace = #485;
2426 =========
2427 */
2428 // case-insensitive version of strreplace
2429 void VM_strireplace(void)
2430 {
2431         int i, j, si;
2432         const char *search, *replace, *subject;
2433         char string[VM_STRINGTEMP_LENGTH];
2434         int search_len, replace_len, subject_len;
2435
2436         VM_SAFEPARMCOUNT(3,VM_strreplace);
2437
2438         search = PRVM_G_STRING(OFS_PARM0);
2439         replace = PRVM_G_STRING(OFS_PARM1);
2440         subject = PRVM_G_STRING(OFS_PARM2);
2441
2442         search_len = (int)strlen(search);
2443         replace_len = (int)strlen(replace);
2444         subject_len = (int)strlen(subject);
2445
2446         si = 0;
2447         for (i = 0; i <= subject_len - search_len; i++)
2448         {
2449                 for (j = 0; j < search_len; j++) // thus, i+j < subject_len
2450                         if (tolower(subject[i+j]) != tolower(search[j]))
2451                                 break;
2452                 if (j == search_len)
2453                 {
2454                         // NOTE: if search_len == 0, we always hit THIS case, and never the other
2455                         // found it at offset 'i'
2456                         for (j = 0; j < replace_len && si < (int)sizeof(string) - 1; j++)
2457                                 string[si++] = replace[j];
2458                         if(search_len > 0)
2459                         {
2460                                 i += search_len - 1;
2461                         }
2462                         else
2463                         {
2464                                 // the above would subtract 1 from i... so we
2465                                 // don't do that, but instead output the next
2466                                 // char
2467                                 if (si < (int)sizeof(string) - 1)
2468                                         string[si++] = subject[i];
2469                         }
2470                 }
2471                 else
2472                 {
2473                         // in THIS case, we know search_len > 0, thus i < subject_len
2474                         // not found
2475                         if (si < (int)sizeof(string) - 1)
2476                                 string[si++] = subject[i];
2477                 }
2478         }
2479         // remaining chars (these cannot match)
2480         for (; i < subject_len; i++)
2481                 if (si < (int)sizeof(string) - 1)
2482                         string[si++] = subject[i];
2483         string[si] = '\0';
2484
2485         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
2486 }
2487
2488 /*
2489 =========
2490 VM_stov
2491
2492 vector  stov(string s)
2493 =========
2494 */
2495 //vector(string s) stov = #117; // returns vector value from a string
2496 void VM_stov(void)
2497 {
2498         char string[VM_STRINGTEMP_LENGTH];
2499
2500         VM_SAFEPARMCOUNT(1,VM_stov);
2501
2502         VM_VarString(0, string, sizeof(string));
2503         Math_atov(string, PRVM_G_VECTOR(OFS_RETURN));
2504 }
2505
2506 /*
2507 =========
2508 VM_strzone
2509
2510 string  strzone(string s)
2511 =========
2512 */
2513 //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)
2514 void VM_strzone(void)
2515 {
2516         char *out;
2517         char string[VM_STRINGTEMP_LENGTH];
2518         size_t alloclen;
2519
2520         VM_SAFEPARMCOUNT(1,VM_strzone);
2521
2522         VM_VarString(0, string, sizeof(string));
2523         alloclen = strlen(string) + 1;
2524         PRVM_G_INT(OFS_RETURN) = PRVM_AllocString(alloclen, &out);
2525         memcpy(out, string, alloclen);
2526 }
2527
2528 /*
2529 =========
2530 VM_strunzone
2531
2532 strunzone(string s)
2533 =========
2534 */
2535 //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!!!)
2536 void VM_strunzone(void)
2537 {
2538         VM_SAFEPARMCOUNT(1,VM_strunzone);
2539         PRVM_FreeString(PRVM_G_INT(OFS_PARM0));
2540 }
2541
2542 /*
2543 =========
2544 VM_command (used by client and menu)
2545
2546 clientcommand(float client, string s) (for client and menu)
2547 =========
2548 */
2549 //void(entity e, string s) clientcommand = #440; // executes a command string as if it came from the specified client
2550 //this function originally written by KrimZon, made shorter by LordHavoc
2551 void VM_clcommand (void)
2552 {
2553         client_t *temp_client;
2554         int i;
2555
2556         VM_SAFEPARMCOUNT(2,VM_clcommand);
2557
2558         i = (int)PRVM_G_FLOAT(OFS_PARM0);
2559         if (!sv.active  || i < 0 || i >= svs.maxclients || !svs.clients[i].active)
2560         {
2561                 VM_Warning("VM_clientcommand: %s: invalid client/server is not active !\n", PRVM_NAME);
2562                 return;
2563         }
2564
2565         temp_client = host_client;
2566         host_client = svs.clients + i;
2567         Cmd_ExecuteString (PRVM_G_STRING(OFS_PARM1), src_client);
2568         host_client = temp_client;
2569 }
2570
2571
2572 /*
2573 =========
2574 VM_tokenize
2575
2576 float tokenize(string s)
2577 =========
2578 */
2579 //float(string s) tokenize = #441; // takes apart a string into individal words (access them with argv), returns how many
2580 //this function originally written by KrimZon, made shorter by LordHavoc
2581 //20040203: rewritten by LordHavoc (no longer uses allocations)
2582 static int num_tokens = 0;
2583 static int tokens[VM_STRINGTEMP_LENGTH / 2];
2584 static int tokens_startpos[VM_STRINGTEMP_LENGTH / 2];
2585 static int tokens_endpos[VM_STRINGTEMP_LENGTH / 2];
2586 static char tokenize_string[VM_STRINGTEMP_LENGTH];
2587 void VM_tokenize (void)
2588 {
2589         const char *p;
2590
2591         VM_SAFEPARMCOUNT(1,VM_tokenize);
2592
2593         strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2594         p = tokenize_string;
2595
2596         num_tokens = 0;
2597         for(;;)
2598         {
2599                 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
2600                         break;
2601
2602                 // skip whitespace here to find token start pos
2603                 while(*p && ISWHITESPACE(*p))
2604                         ++p;
2605
2606                 tokens_startpos[num_tokens] = p - tokenize_string;
2607                 if(!COM_ParseToken_VM_Tokenize(&p, false))
2608                         break;
2609                 tokens_endpos[num_tokens] = p - tokenize_string;
2610                 tokens[num_tokens] = PRVM_SetTempString(com_token);
2611                 ++num_tokens;
2612         }
2613
2614         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2615 }
2616
2617 //float(string s) tokenize = #514; // takes apart a string into individal words (access them with argv), returns how many
2618 void VM_tokenize_console (void)
2619 {
2620         const char *p;
2621
2622         VM_SAFEPARMCOUNT(1,VM_tokenize);
2623
2624         strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2625         p = tokenize_string;
2626
2627         num_tokens = 0;
2628         for(;;)
2629         {
2630                 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
2631                         break;
2632
2633                 // skip whitespace here to find token start pos
2634                 while(*p && ISWHITESPACE(*p))
2635                         ++p;
2636
2637                 tokens_startpos[num_tokens] = p - tokenize_string;
2638                 if(!COM_ParseToken_Console(&p))
2639                         break;
2640                 tokens_endpos[num_tokens] = p - tokenize_string;
2641                 tokens[num_tokens] = PRVM_SetTempString(com_token);
2642                 ++num_tokens;
2643         }
2644
2645         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2646 }
2647
2648 /*
2649 =========
2650 VM_tokenizebyseparator
2651
2652 float tokenizebyseparator(string s, string separator1, ...)
2653 =========
2654 */
2655 //float(string s, string separator1, ...) tokenizebyseparator = #479; // takes apart a string into individal words (access them with argv), returns how many
2656 //this function returns the token preceding each instance of a separator (of
2657 //which there can be multiple), and the text following the last separator
2658 //useful for parsing certain kinds of data like IP addresses
2659 //example:
2660 //numnumbers = tokenizebyseparator("10.1.2.3", ".");
2661 //returns 4 and the tokens "10" "1" "2" "3".
2662 void VM_tokenizebyseparator (void)
2663 {
2664         int j, k;
2665         int numseparators;
2666         int separatorlen[7];
2667         const char *separators[7];
2668         const char *p, *p0;
2669         const char *token;
2670         char tokentext[MAX_INPUTLINE];
2671
2672         VM_SAFEPARMCOUNTRANGE(2, 8,VM_tokenizebyseparator);
2673
2674         strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2675         p = tokenize_string;
2676
2677         numseparators = 0;
2678         for (j = 1;j < prog->argc;j++)
2679         {
2680                 // skip any blank separator strings
2681                 const char *s = PRVM_G_STRING(OFS_PARM0+j*3);
2682                 if (!s[0])
2683                         continue;
2684                 separators[numseparators] = s;
2685                 separatorlen[numseparators] = strlen(s);
2686                 numseparators++;
2687         }
2688
2689         num_tokens = 0;
2690         j = 0;
2691
2692         while (num_tokens < (int)(sizeof(tokens)/sizeof(tokens[0])))
2693         {
2694                 token = tokentext + j;
2695                 tokens_startpos[num_tokens] = p - tokenize_string;
2696                 p0 = p;
2697                 while (*p)
2698                 {
2699                         for (k = 0;k < numseparators;k++)
2700                         {
2701                                 if (!strncmp(p, separators[k], separatorlen[k]))
2702                                 {
2703                                         p += separatorlen[k];
2704                                         break;
2705                                 }
2706                         }
2707                         if (k < numseparators)
2708                                 break;
2709                         if (j < (int)sizeof(tokentext)-1)
2710                                 tokentext[j++] = *p;
2711                         p++;
2712                         p0 = p;
2713                 }
2714                 tokens_endpos[num_tokens] = p0 - tokenize_string;
2715                 if (j >= (int)sizeof(tokentext))
2716                         break;
2717                 tokentext[j++] = 0;
2718                 tokens[num_tokens++] = PRVM_SetTempString(token);
2719                 if (!*p)
2720                         break;
2721         }
2722
2723         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2724 }
2725
2726 //string(float n) argv = #442; // returns a word from the tokenized string (returns nothing for an invalid index)
2727 //this function originally written by KrimZon, made shorter by LordHavoc
2728 void VM_argv (void)
2729 {
2730         int token_num;
2731
2732         VM_SAFEPARMCOUNT(1,VM_argv);
2733
2734         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2735
2736         if(token_num < 0)
2737                 token_num += num_tokens;
2738
2739         if (token_num >= 0 && token_num < num_tokens)
2740                 PRVM_G_INT(OFS_RETURN) = tokens[token_num];
2741         else
2742                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
2743 }
2744
2745 //float(float n) argv_start_index = #515; // returns the start index of a token
2746 void VM_argv_start_index (void)
2747 {
2748         int token_num;
2749
2750         VM_SAFEPARMCOUNT(1,VM_argv);
2751
2752         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2753
2754         if(token_num < 0)
2755                 token_num += num_tokens;
2756
2757         if (token_num >= 0 && token_num < num_tokens)
2758                 PRVM_G_FLOAT(OFS_RETURN) = tokens_startpos[token_num];
2759         else
2760                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2761 }
2762
2763 //float(float n) argv_end_index = #516; // returns the end index of a token
2764 void VM_argv_end_index (void)
2765 {
2766         int token_num;
2767
2768         VM_SAFEPARMCOUNT(1,VM_argv);
2769
2770         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2771
2772         if(token_num < 0)
2773                 token_num += num_tokens;
2774
2775         if (token_num >= 0 && token_num < num_tokens)
2776                 PRVM_G_FLOAT(OFS_RETURN) = tokens_endpos[token_num];
2777         else
2778                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2779 }
2780
2781 /*
2782 =========
2783 VM_isserver
2784
2785 float   isserver()
2786 =========
2787 */
2788 void VM_isserver(void)
2789 {
2790         VM_SAFEPARMCOUNT(0,VM_serverstate);
2791
2792         PRVM_G_FLOAT(OFS_RETURN) = sv.active && (svs.maxclients > 1 || cls.state == ca_dedicated);
2793 }
2794
2795 /*
2796 =========
2797 VM_clientcount
2798
2799 float   clientcount()
2800 =========
2801 */
2802 void VM_clientcount(void)
2803 {
2804         VM_SAFEPARMCOUNT(0,VM_clientcount);
2805
2806         PRVM_G_FLOAT(OFS_RETURN) = svs.maxclients;
2807 }
2808
2809 /*
2810 =========
2811 VM_clientstate
2812
2813 float   clientstate()
2814 =========
2815 */
2816 void VM_clientstate(void)
2817 {
2818         VM_SAFEPARMCOUNT(0,VM_clientstate);
2819
2820
2821         switch( cls.state ) {
2822                 case ca_uninitialized:
2823                 case ca_dedicated:
2824                         PRVM_G_FLOAT(OFS_RETURN) = 0;
2825                         break;
2826                 case ca_disconnected:
2827                         PRVM_G_FLOAT(OFS_RETURN) = 1;
2828                         break;
2829                 case ca_connected:
2830                         PRVM_G_FLOAT(OFS_RETURN) = 2;
2831                         break;
2832                 default:
2833                         // should never be reached!
2834                         break;
2835         }
2836 }
2837
2838 /*
2839 =========
2840 VM_getostype
2841
2842 float   getostype(void)
2843 =========
2844 */ // not used at the moment -> not included in the common list
2845 void VM_getostype(void)
2846 {
2847         VM_SAFEPARMCOUNT(0,VM_getostype);
2848
2849         /*
2850         OS_WINDOWS
2851         OS_LINUX
2852         OS_MAC - not supported
2853         */
2854
2855 #ifdef WIN32
2856         PRVM_G_FLOAT(OFS_RETURN) = 0;
2857 #elif defined(MACOSX)
2858         PRVM_G_FLOAT(OFS_RETURN) = 2;
2859 #else
2860         PRVM_G_FLOAT(OFS_RETURN) = 1;
2861 #endif
2862 }
2863
2864 /*
2865 =========
2866 VM_gettime
2867
2868 float   gettime(void)
2869 =========
2870 */
2871 extern double host_starttime;
2872 float CDAudio_GetPosition(void);
2873 void VM_gettime(void)
2874 {
2875         int timer_index;
2876
2877         VM_SAFEPARMCOUNTRANGE(0,1,VM_gettime);
2878
2879         if(prog->argc == 0)
2880         {
2881                 PRVM_G_FLOAT(OFS_RETURN) = (float) realtime;
2882         }
2883         else
2884         {
2885                 timer_index = (int) PRVM_G_FLOAT(OFS_PARM0);
2886         switch(timer_index)
2887         {
2888             case 0: // GETTIME_FRAMESTART
2889                 PRVM_G_FLOAT(OFS_RETURN) = (float) realtime;
2890                 break;
2891             case 1: // GETTIME_REALTIME
2892                 PRVM_G_FLOAT(OFS_RETURN) = (float) Sys_DoubleTime();
2893                 break;
2894             case 2: // GETTIME_HIRES
2895                 PRVM_G_FLOAT(OFS_RETURN) = (float) (Sys_DoubleTime() - realtime);
2896                 break;
2897             case 3: // GETTIME_UPTIME
2898                 PRVM_G_FLOAT(OFS_RETURN) = (float) (Sys_DoubleTime() - host_starttime);
2899                 break;
2900             case 4: // GETTIME_CDTRACK
2901                 PRVM_G_FLOAT(OFS_RETURN) = (float) CDAudio_GetPosition();
2902                 break;
2903                         default:
2904                                 VM_Warning("VM_gettime: %s: unsupported timer specified, returning realtime\n", PRVM_NAME);
2905                                 PRVM_G_FLOAT(OFS_RETURN) = (float) realtime;
2906                                 break;
2907                 }
2908         }
2909 }
2910
2911 /*
2912 =========
2913 VM_getsoundtime
2914
2915 float   getsoundtime(void)
2916 =========
2917 */
2918
2919 void VM_getsoundtime (void)
2920 {
2921         int entnum, entchannel, pnum;
2922         VM_SAFEPARMCOUNT(2,VM_getsoundtime);
2923
2924         pnum = PRVM_GetProgNr();
2925         if (pnum == PRVM_MENUPROG)
2926         {
2927                 VM_Warning("VM_getsoundtime: %s: not supported on this progs\n", PRVM_NAME);
2928                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2929                 return;
2930         }
2931         entnum = ((pnum == PRVM_CLIENTPROG) ? MAX_EDICTS : 0) + PRVM_NUM_FOR_EDICT(PRVM_G_EDICT(OFS_PARM0));
2932         entchannel = (int)PRVM_G_FLOAT(OFS_PARM1);
2933         entchannel = CHAN_USER2ENGINE(entchannel);
2934         if (!IS_CHAN(entchannel))
2935                 VM_Warning("VM_getsoundtime: %s: bad channel %i\n", PRVM_NAME, entchannel);
2936         PRVM_G_FLOAT(OFS_RETURN) = (float)S_GetEntChannelPosition(entnum, entchannel);
2937 }
2938
2939 /*
2940 =========
2941 VM_GetSoundLen
2942
2943 string  soundlength (string sample)
2944 =========
2945 */
2946 void VM_soundlength (void)
2947 {
2948         const char *s;
2949
2950         VM_SAFEPARMCOUNT(1, VM_soundlength);
2951
2952         s = PRVM_G_STRING(OFS_PARM0);
2953         PRVM_G_FLOAT(OFS_RETURN) = S_SoundLength(s);
2954 }
2955
2956 /*
2957 =========
2958 VM_loadfromdata
2959
2960 loadfromdata(string data)
2961 =========
2962 */
2963 void VM_loadfromdata(void)
2964 {
2965         VM_SAFEPARMCOUNT(1,VM_loadentsfromfile);
2966
2967         PRVM_ED_LoadFromFile(PRVM_G_STRING(OFS_PARM0));
2968 }
2969
2970 /*
2971 ========================
2972 VM_parseentitydata
2973
2974 parseentitydata(entity ent, string data)
2975 ========================
2976 */
2977 void VM_parseentitydata(void)
2978 {
2979         prvm_edict_t *ent;
2980         const char *data;
2981
2982         VM_SAFEPARMCOUNT(2, VM_parseentitydata);
2983
2984         // get edict and test it
2985         ent = PRVM_G_EDICT(OFS_PARM0);
2986         if (ent->priv.required->free)
2987                 PRVM_ERROR ("VM_parseentitydata: %s: Can only set already spawned entities (entity %i is free)!", PRVM_NAME, PRVM_NUM_FOR_EDICT(ent));
2988
2989         data = PRVM_G_STRING(OFS_PARM1);
2990
2991         // parse the opening brace
2992         if (!COM_ParseToken_Simple(&data, false, false) || com_token[0] != '{' )
2993                 PRVM_ERROR ("VM_parseentitydata: %s: Couldn't parse entity data:\n%s", PRVM_NAME, data );
2994
2995         PRVM_ED_ParseEdict (data, ent);
2996 }
2997
2998 /*
2999 =========
3000 VM_loadfromfile
3001
3002 loadfromfile(string file)
3003 =========
3004 */
3005 void VM_loadfromfile(void)
3006 {
3007         const char *filename;
3008         char *data;
3009
3010         VM_SAFEPARMCOUNT(1,VM_loadfromfile);
3011
3012         filename = PRVM_G_STRING(OFS_PARM0);
3013         if (FS_CheckNastyPath(filename, false))
3014         {
3015                 PRVM_G_FLOAT(OFS_RETURN) = -4;
3016                 VM_Warning("VM_loadfromfile: %s dangerous or non-portable filename \"%s\" not allowed. (contains : or \\ or begins with .. or /)\n", PRVM_NAME, filename);
3017                 return;
3018         }
3019
3020         // not conform with VM_fopen
3021         data = (char *)FS_LoadFile(filename, tempmempool, false, NULL);
3022         if (data == NULL)
3023                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3024
3025         PRVM_ED_LoadFromFile(data);
3026
3027         if(data)
3028                 Mem_Free(data);
3029 }
3030
3031
3032 /*
3033 =========
3034 VM_modulo
3035
3036 float   mod(float val, float m)
3037 =========
3038 */
3039 void VM_modulo(void)
3040 {
3041         int val, m;
3042         VM_SAFEPARMCOUNT(2,VM_module);
3043
3044         val = (int) PRVM_G_FLOAT(OFS_PARM0);
3045         m       = (int) PRVM_G_FLOAT(OFS_PARM1);
3046
3047         PRVM_G_FLOAT(OFS_RETURN) = (float) (val % m);
3048 }
3049
3050 void VM_Search_Init(void)
3051 {
3052         int i;
3053         for (i = 0;i < PRVM_MAX_OPENSEARCHES;i++)
3054                 prog->opensearches[i] = NULL;
3055 }
3056
3057 void VM_Search_Reset(void)
3058 {
3059         int i;
3060         // reset the fssearch list
3061         for(i = 0; i < PRVM_MAX_OPENSEARCHES; i++)
3062         {
3063                 if(prog->opensearches[i])
3064                         FS_FreeSearch(prog->opensearches[i]);
3065                 prog->opensearches[i] = NULL;
3066         }
3067 }
3068
3069 /*
3070 =========
3071 VM_search_begin
3072
3073 float search_begin(string pattern, float caseinsensitive, float quiet)
3074 =========
3075 */
3076 void VM_search_begin(void)
3077 {
3078         int handle;
3079         const char *pattern;
3080         int caseinsens, quiet;
3081
3082         VM_SAFEPARMCOUNT(3, VM_search_begin);
3083
3084         pattern = PRVM_G_STRING(OFS_PARM0);
3085
3086         VM_CheckEmptyString(pattern);
3087
3088         caseinsens = (int)PRVM_G_FLOAT(OFS_PARM1);
3089         quiet = (int)PRVM_G_FLOAT(OFS_PARM2);
3090
3091         for(handle = 0; handle < PRVM_MAX_OPENSEARCHES; handle++)
3092                 if(!prog->opensearches[handle])
3093                         break;
3094
3095         if(handle >= PRVM_MAX_OPENSEARCHES)
3096         {
3097                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3098                 VM_Warning("VM_search_begin: %s ran out of search handles (%i)\n", PRVM_NAME, PRVM_MAX_OPENSEARCHES);
3099                 return;
3100         }
3101
3102         if(!(prog->opensearches[handle] = FS_Search(pattern,caseinsens, quiet)))
3103                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3104         else
3105         {
3106                 prog->opensearches_origin[handle] = PRVM_AllocationOrigin();
3107                 PRVM_G_FLOAT(OFS_RETURN) = handle;
3108         }
3109 }
3110
3111 /*
3112 =========
3113 VM_search_end
3114
3115 void    search_end(float handle)
3116 =========
3117 */
3118 void VM_search_end(void)
3119 {
3120         int handle;
3121         VM_SAFEPARMCOUNT(1, VM_search_end);
3122
3123         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3124
3125         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3126         {
3127                 VM_Warning("VM_search_end: invalid handle %i used in %s\n", handle, PRVM_NAME);
3128                 return;
3129         }
3130         if(prog->opensearches[handle] == NULL)
3131         {
3132                 VM_Warning("VM_search_end: no such handle %i in %s\n", handle, PRVM_NAME);
3133                 return;
3134         }
3135
3136         FS_FreeSearch(prog->opensearches[handle]);
3137         prog->opensearches[handle] = NULL;
3138         if(prog->opensearches_origin[handle])
3139                 PRVM_Free((char *)prog->opensearches_origin[handle]);
3140 }
3141
3142 /*
3143 =========
3144 VM_search_getsize
3145
3146 float   search_getsize(float handle)
3147 =========
3148 */
3149 void VM_search_getsize(void)
3150 {
3151         int handle;
3152         VM_SAFEPARMCOUNT(1, VM_M_search_getsize);
3153
3154         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3155
3156         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3157         {
3158                 VM_Warning("VM_search_getsize: invalid handle %i used in %s\n", handle, PRVM_NAME);
3159                 return;
3160         }
3161         if(prog->opensearches[handle] == NULL)
3162         {
3163                 VM_Warning("VM_search_getsize: no such handle %i in %s\n", handle, PRVM_NAME);
3164                 return;
3165         }
3166
3167         PRVM_G_FLOAT(OFS_RETURN) = prog->opensearches[handle]->numfilenames;
3168 }
3169
3170 /*
3171 =========
3172 VM_search_getfilename
3173
3174 string  search_getfilename(float handle, float num)
3175 =========
3176 */
3177 void VM_search_getfilename(void)
3178 {
3179         int handle, filenum;
3180         VM_SAFEPARMCOUNT(2, VM_search_getfilename);
3181
3182         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3183         filenum = (int)PRVM_G_FLOAT(OFS_PARM1);
3184
3185         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3186         {
3187                 VM_Warning("VM_search_getfilename: invalid handle %i used in %s\n", handle, PRVM_NAME);
3188                 return;
3189         }
3190         if(prog->opensearches[handle] == NULL)
3191         {
3192                 VM_Warning("VM_search_getfilename: no such handle %i in %s\n", handle, PRVM_NAME);
3193                 return;
3194         }
3195         if(filenum < 0 || filenum >= prog->opensearches[handle]->numfilenames)
3196         {
3197                 VM_Warning("VM_search_getfilename: invalid filenum %i in %s\n", filenum, PRVM_NAME);
3198                 return;
3199         }
3200
3201         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog->opensearches[handle]->filenames[filenum]);
3202 }
3203
3204 /*
3205 =========
3206 VM_chr
3207
3208 string  chr(float ascii)
3209 =========
3210 */
3211 void VM_chr(void)
3212 {
3213         /*
3214         char tmp[2];
3215         VM_SAFEPARMCOUNT(1, VM_chr);
3216
3217         tmp[0] = (unsigned char) PRVM_G_FLOAT(OFS_PARM0);
3218         tmp[1] = 0;
3219
3220         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(tmp);
3221         */
3222         
3223         char tmp[8];
3224         int len;
3225         VM_SAFEPARMCOUNT(1, VM_chr);
3226
3227         len = u8_fromchar((Uchar)PRVM_G_FLOAT(OFS_PARM0), tmp, sizeof(tmp));
3228         tmp[len] = 0;
3229         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(tmp);
3230 }
3231
3232 //=============================================================================
3233 // Draw builtins (client & menu)
3234
3235 /*
3236 =========
3237 VM_iscachedpic
3238
3239 float   iscachedpic(string pic)
3240 =========
3241 */
3242 void VM_iscachedpic(void)
3243 {
3244         VM_SAFEPARMCOUNT(1,VM_iscachedpic);
3245
3246         // drawq hasnt such a function, thus always return true
3247         PRVM_G_FLOAT(OFS_RETURN) = false;
3248 }
3249
3250 /*
3251 =========
3252 VM_precache_pic
3253
3254 string  precache_pic(string pic)
3255 =========
3256 */
3257 void VM_precache_pic(void)
3258 {
3259         const char      *s;
3260
3261         VM_SAFEPARMCOUNT(1, VM_precache_pic);
3262
3263         s = PRVM_G_STRING(OFS_PARM0);
3264         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
3265         VM_CheckEmptyString (s);
3266
3267         // AK Draw_CachePic is supposed to always return a valid pointer
3268         if( Draw_CachePic_Flags(s, 0)->tex == r_texture_notexture )
3269                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
3270 }
3271
3272 /*
3273 =========
3274 VM_freepic
3275
3276 freepic(string s)
3277 =========
3278 */
3279 void VM_freepic(void)
3280 {
3281         const char *s;
3282
3283         VM_SAFEPARMCOUNT(1,VM_freepic);
3284
3285         s = PRVM_G_STRING(OFS_PARM0);
3286         VM_CheckEmptyString (s);
3287
3288         Draw_FreePic(s);
3289 }
3290
3291 void getdrawfontscale(float *sx, float *sy)
3292 {
3293         vec3_t v;
3294         *sx = *sy = 1;
3295         VectorCopy(PRVM_drawglobalvector(drawfontscale), v);
3296         if(VectorLength2(v) > 0)
3297         {
3298                 *sx = v[0];
3299                 *sy = v[1];
3300         }
3301 }
3302
3303 dp_font_t *getdrawfont(void)
3304 {
3305         int f = (int) PRVM_drawglobalfloat(drawfont);
3306         if(f < 0 || f >= dp_fonts.maxsize)
3307                 return FONT_DEFAULT;
3308         return &dp_fonts.f[f];
3309 }
3310
3311 /*
3312 =========
3313 VM_drawcharacter
3314
3315 float   drawcharacter(vector position, float character, vector scale, vector rgb, float alpha, float flag)
3316 =========
3317 */
3318 void VM_drawcharacter(void)
3319 {
3320         float *pos,*scale,*rgb;
3321         char   character;
3322         int flag;
3323         float sx, sy;
3324         VM_SAFEPARMCOUNT(6,VM_drawcharacter);
3325
3326         character = (char) PRVM_G_FLOAT(OFS_PARM1);
3327         if(character == 0)
3328         {
3329                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3330                 VM_Warning("VM_drawcharacter: %s passed null character !\n",PRVM_NAME);
3331                 return;
3332         }
3333
3334         pos = PRVM_G_VECTOR(OFS_PARM0);
3335         scale = PRVM_G_VECTOR(OFS_PARM2);
3336         rgb = PRVM_G_VECTOR(OFS_PARM3);
3337         flag = (int)PRVM_G_FLOAT(OFS_PARM5);
3338
3339         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3340         {
3341                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3342                 VM_Warning("VM_drawcharacter: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3343                 return;
3344         }
3345
3346         if(pos[2] || scale[2])
3347                 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")));
3348
3349         if(!scale[0] || !scale[1])
3350         {
3351                 PRVM_G_FLOAT(OFS_RETURN) = -3;
3352                 VM_Warning("VM_drawcharacter: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
3353                 return;
3354         }
3355
3356         getdrawfontscale(&sx, &sy);
3357         DrawQ_String_Scale(pos[0], pos[1], &character, 1, scale[0], scale[1], sx, sy, rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag, NULL, true, getdrawfont());
3358         PRVM_G_FLOAT(OFS_RETURN) = 1;
3359 }
3360
3361 /*
3362 =========
3363 VM_drawstring
3364
3365 float   drawstring(vector position, string text, vector scale, vector rgb, float alpha[, float flag])
3366 =========
3367 */
3368 void VM_drawstring(void)
3369 {
3370         float *pos,*scale,*rgb;
3371         const char  *string;
3372         int flag = 0;
3373         float sx, sy;
3374         VM_SAFEPARMCOUNTRANGE(5,6,VM_drawstring);
3375
3376         string = PRVM_G_STRING(OFS_PARM1);
3377         pos = PRVM_G_VECTOR(OFS_PARM0);
3378         scale = PRVM_G_VECTOR(OFS_PARM2);
3379         rgb = PRVM_G_VECTOR(OFS_PARM3);
3380         if (prog->argc >= 6)
3381                 flag = (int)PRVM_G_FLOAT(OFS_PARM5);
3382
3383         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3384         {
3385                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3386                 VM_Warning("VM_drawstring: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3387                 return;
3388         }
3389
3390         if(!scale[0] || !scale[1])
3391         {
3392                 PRVM_G_FLOAT(OFS_RETURN) = -3;
3393                 VM_Warning("VM_drawstring: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
3394                 return;
3395         }
3396
3397         if(pos[2] || scale[2])
3398                 Con_Printf("VM_drawstring: z value%s from %s discarded\n",(pos[2] && scale[2]) ? "s" : " ",((pos[2] && scale[2]) ? "pos and scale" : (pos[2] ? "pos" : "scale")));
3399
3400         getdrawfontscale(&sx, &sy);
3401         DrawQ_String_Scale(pos[0], pos[1], string, 0, scale[0], scale[1], sx, sy, rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag, NULL, true, getdrawfont());
3402         //Font_DrawString(pos[0], pos[1], string, 0, scale[0], scale[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag, NULL, true);
3403         PRVM_G_FLOAT(OFS_RETURN) = 1;
3404 }
3405
3406 /*
3407 =========
3408 VM_drawcolorcodedstring
3409
3410 float   drawcolorcodedstring(vector position, string text, vector scale, float alpha, float flag)
3411 /
3412 float   drawcolorcodedstring(vector position, string text, vector scale, vector rgb, float alpha, float flag)
3413 =========
3414 */
3415 void VM_drawcolorcodedstring(void)
3416 {
3417         float *pos, *scale;
3418         const char  *string;
3419         int flag;
3420         vec3_t rgb;
3421         float sx, sy, alpha;
3422
3423         VM_SAFEPARMCOUNTRANGE(5,6,VM_drawcolorcodedstring);
3424
3425         if (prog->argc == 6) // full 6 parms, like normal drawstring
3426         {
3427                 pos = PRVM_G_VECTOR(OFS_PARM0);
3428                 string = PRVM_G_STRING(OFS_PARM1);
3429                 scale = PRVM_G_VECTOR(OFS_PARM2);
3430                 VectorCopy(PRVM_G_VECTOR(OFS_PARM3), rgb); 
3431                 alpha = PRVM_G_FLOAT(OFS_PARM4);
3432                 flag = (int)PRVM_G_FLOAT(OFS_PARM5);
3433         }
3434         else
3435         {
3436                 pos = PRVM_G_VECTOR(OFS_PARM0);
3437                 string = PRVM_G_STRING(OFS_PARM1);
3438                 scale = PRVM_G_VECTOR(OFS_PARM2);
3439                 rgb[0] = 1.0;
3440                 rgb[1] = 1.0;
3441                 rgb[2] = 1.0;
3442                 alpha = PRVM_G_FLOAT(OFS_PARM3);
3443                 flag = (int)PRVM_G_FLOAT(OFS_PARM4);
3444         }
3445
3446         if(flag < DRAWFLAG_NORMAL || flag >= DRAWFLAG_NUMFLAGS)
3447         {
3448                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3449                 VM_Warning("VM_drawcolorcodedstring: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3450                 return;
3451         }
3452
3453         if(!scale[0] || !scale[1])
3454         {
3455                 PRVM_G_FLOAT(OFS_RETURN) = -3;
3456                 VM_Warning("VM_drawcolorcodedstring: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
3457                 return;
3458         }
3459
3460         if(pos[2] || scale[2])
3461                 Con_Printf("VM_drawcolorcodedstring: z value%s from %s discarded\n",(pos[2] && scale[2]) ? "s" : " ",((pos[2] && scale[2]) ? "pos and scale" : (pos[2] ? "pos" : "scale")));
3462
3463         getdrawfontscale(&sx, &sy);
3464         DrawQ_String_Scale(pos[0], pos[1], string, 0, scale[0], scale[1], sx, sy, rgb[0], rgb[1], rgb[2], alpha, flag, NULL, false, getdrawfont());
3465         if (prog->argc == 6) // also return vector of last color
3466                 VectorCopy(DrawQ_Color, PRVM_G_VECTOR(OFS_RETURN));
3467         else
3468                 PRVM_G_FLOAT(OFS_RETURN) = 1;
3469 }
3470 /*
3471 =========
3472 VM_stringwidth
3473
3474 float   stringwidth(string text, float allowColorCodes, float size)
3475 =========
3476 */
3477 void VM_stringwidth(void)
3478 {
3479         const char  *string;
3480         float *szv;
3481         float mult; // sz is intended font size so we can later add freetype support, mult is font size multiplier in pixels per character cell
3482         int colors;
3483         float sx, sy;
3484         size_t maxlen = 0;
3485         VM_SAFEPARMCOUNTRANGE(2,3,VM_drawstring);
3486
3487         getdrawfontscale(&sx, &sy);
3488         if(prog->argc == 3)
3489         {
3490                 szv = PRVM_G_VECTOR(OFS_PARM2);
3491                 mult = 1;
3492         }
3493         else
3494         {
3495                 // we want the width for 8x8 font size, divided by 8
3496                 static float defsize[] = {8, 8};
3497                 szv = defsize;
3498                 mult = 0.125;
3499                 // to make sure snapping is turned off, ALWAYS use a nontrivial scale in this case
3500                 if(sx >= 0.9 && sx <= 1.1)
3501                 {
3502                         mult *= 2;
3503                         sx /= 2;
3504                         sy /= 2;
3505                 }
3506         }
3507
3508         string = PRVM_G_STRING(OFS_PARM0);
3509         colors = (int)PRVM_G_FLOAT(OFS_PARM1);
3510
3511         PRVM_G_FLOAT(OFS_RETURN) = DrawQ_TextWidth_UntilWidth_TrackColors_Scale(string, &maxlen, szv[0], szv[1], sx, sy, NULL, !colors, getdrawfont(), 1000000000) * mult;
3512 /*
3513         if(prog->argc == 3)
3514         {
3515                 mult = sz = PRVM_G_FLOAT(OFS_PARM2);
3516         }
3517         else
3518         {
3519                 sz = 8;
3520                 mult = 1;
3521         }
3522
3523         string = PRVM_G_STRING(OFS_PARM0);
3524         colors = (int)PRVM_G_FLOAT(OFS_PARM1);
3525
3526         PRVM_G_FLOAT(OFS_RETURN) = DrawQ_TextWidth(string, 0, !colors, getdrawfont()) * mult; // 1x1 characters, don't actually draw
3527 */
3528 }
3529
3530 /*
3531 =========
3532 VM_findfont
3533
3534 float findfont(string s)
3535 =========
3536 */
3537
3538 float getdrawfontnum(const char *fontname)
3539 {
3540         int i;
3541
3542         for(i = 0; i < dp_fonts.maxsize; ++i)
3543                 if(!strcmp(dp_fonts.f[i].title, fontname))
3544                         return i;
3545         return -1;
3546 }
3547
3548 void VM_findfont(void)
3549 {
3550         VM_SAFEPARMCOUNT(1,VM_findfont);
3551         PRVM_G_FLOAT(OFS_RETURN) = getdrawfontnum(PRVM_G_STRING(OFS_PARM0));
3552 }
3553
3554 /*
3555 =========
3556 VM_loadfont
3557
3558 float loadfont(string fontname, string fontmaps, string sizes, float slot)
3559 =========
3560 */
3561
3562 dp_font_t *FindFont(const char *title, qboolean allocate_new);
3563 void LoadFont(qboolean override, const char *name, dp_font_t *fnt, float scale, float voffset);
3564 void VM_loadfont(void)
3565 {
3566         const char *fontname, *filelist, *sizes, *c, *cm;
3567         char mainfont[MAX_QPATH];
3568         int i, numsizes;
3569         float sz, scale, voffset;
3570         dp_font_t *f;
3571
3572         VM_SAFEPARMCOUNTRANGE(3,6,VM_loadfont);
3573
3574         fontname = PRVM_G_STRING(OFS_PARM0);
3575         if (!fontname[0])
3576                 fontname = "default";
3577
3578         filelist = PRVM_G_STRING(OFS_PARM1);
3579         if (!filelist[0])
3580                 filelist = "gfx/conchars";
3581
3582         sizes = PRVM_G_STRING(OFS_PARM2);
3583         if (!sizes[0])
3584                 sizes = "10";
3585
3586         // find a font
3587         f = NULL;
3588         if (prog->argc >= 4)
3589         {
3590                 i = PRVM_G_FLOAT(OFS_PARM3);
3591                 if (i >= 0 && i < dp_fonts.maxsize)
3592                 {
3593                         f = &dp_fonts.f[i];
3594                         strlcpy(f->title, fontname, sizeof(f->title)); // replace name
3595                 }
3596         }
3597         if (!f)
3598                 f = FindFont(fontname, true);
3599         if (!f)
3600         {
3601                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3602                 return; // something go wrong
3603         }
3604
3605         memset(f->fallbacks, 0, sizeof(f->fallbacks));
3606         memset(f->fallback_faces, 0, sizeof(f->fallback_faces));
3607
3608         // first font is handled "normally"
3609         c = strchr(filelist, ':');
3610         cm = strchr(filelist, ',');
3611         if(c && (!cm || c < cm))
3612                 f->req_face = atoi(c+1);
3613         else
3614         {
3615                 f->req_face = 0;
3616                 c = cm;
3617         }
3618         if(!c || (c - filelist) > MAX_QPATH)
3619                 strlcpy(mainfont, filelist, sizeof(mainfont));
3620         else
3621         {
3622                 memcpy(mainfont, filelist, c - filelist);
3623                 mainfont[c - filelist] = 0;
3624         }
3625
3626         // handle fallbacks
3627         for(i = 0; i < MAX_FONT_FALLBACKS; ++i)
3628         {
3629                 c = strchr(filelist, ',');
3630                 if(!c)
3631                         break;
3632                 filelist = c + 1;
3633                 if(!*filelist)
3634                         break;
3635                 c = strchr(filelist, ':');
3636                 cm = strchr(filelist, ',');
3637                 if(c && (!cm || c < cm))
3638                         f->fallback_faces[i] = atoi(c+1);
3639                 else
3640                 {
3641                         f->fallback_faces[i] = 0; // f->req_face; could make it stick to the default-font's face index
3642                         c = cm;
3643                 }
3644                 if(!c || (c-filelist) > MAX_QPATH)
3645                 {
3646                         strlcpy(f->fallbacks[i], filelist, sizeof(mainfont));
3647                 }
3648                 else
3649                 {
3650                         memcpy(f->fallbacks[i], filelist, c - filelist);
3651                         f->fallbacks[i][c - filelist] = 0;
3652                 }
3653         }
3654
3655         // handle sizes
3656         for(i = 0; i < MAX_FONT_SIZES; ++i)
3657                 f->req_sizes[i] = -1;
3658         for (numsizes = 0,c = sizes;;)
3659         {
3660                 if (!COM_ParseToken_VM_Tokenize(&c, 0))
3661                         break;
3662                 sz = atof(com_token);
3663                 // detect crap size
3664                 if (sz < 0.001f || sz > 1000.0f)
3665                 {
3666                         VM_Warning("VM_loadfont: crap size %s", com_token);
3667                         continue;
3668                 }
3669                 // check overflow
3670                 if (numsizes == MAX_FONT_SIZES)
3671                 {
3672                         VM_Warning("VM_loadfont: MAX_FONT_SIZES = %i exceeded", MAX_FONT_SIZES);
3673                         break;
3674                 }
3675                 f->req_sizes[numsizes] = sz;
3676                 numsizes++;
3677         }
3678
3679         // additional scale/hoffset parms
3680         scale = 1;
3681         voffset = 0;
3682         if (prog->argc >= 5)
3683         {
3684                 scale = PRVM_G_FLOAT(OFS_PARM4);
3685                 if (scale <= 0)
3686                         scale = 1;
3687         }
3688         if (prog->argc >= 6)
3689                 voffset = PRVM_G_FLOAT(OFS_PARM5);
3690
3691         // load
3692         LoadFont(true, mainfont, f, scale, voffset);
3693
3694         // return index of loaded font
3695         PRVM_G_FLOAT(OFS_RETURN) = (f - dp_fonts.f);
3696 }
3697
3698 /*
3699 =========
3700 VM_drawpic
3701
3702 float   drawpic(vector position, string pic, vector size, vector rgb, float alpha, float flag)
3703 =========
3704 */
3705 void VM_drawpic(void)
3706 {
3707         const char *picname;
3708         float *size, *pos, *rgb;
3709         int flag = 0;
3710
3711         VM_SAFEPARMCOUNTRANGE(5,6,VM_drawpic);
3712
3713         picname = PRVM_G_STRING(OFS_PARM1);
3714         VM_CheckEmptyString (picname);
3715
3716         // is pic cached ? no function yet for that
3717         if(!1)
3718         {
3719                 PRVM_G_FLOAT(OFS_RETURN) = -4;
3720                 VM_Warning("VM_drawpic: %s: %s not cached !\n", PRVM_NAME, picname);
3721                 return;
3722         }
3723
3724         pos = PRVM_G_VECTOR(OFS_PARM0);
3725         size = PRVM_G_VECTOR(OFS_PARM2);
3726         rgb = PRVM_G_VECTOR(OFS_PARM3);
3727         if (prog->argc >= 6)
3728                 flag = (int) PRVM_G_FLOAT(OFS_PARM5);
3729
3730         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3731         {
3732                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3733                 VM_Warning("VM_drawpic: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3734                 return;
3735         }
3736
3737         if(pos[2] || size[2])
3738                 Con_Printf("VM_drawpic: z value%s from %s discarded\n",(pos[2] && size[2]) ? "s" : " ",((pos[2] && size[2]) ? "pos and size" : (pos[2] ? "pos" : "size")));
3739
3740         DrawQ_Pic(pos[0], pos[1], Draw_CachePic_Flags (picname, CACHEPICFLAG_NOTPERSISTENT), size[0], size[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM4), flag);
3741         PRVM_G_FLOAT(OFS_RETURN) = 1;
3742 }
3743 /*
3744 =========
3745 VM_drawrotpic
3746
3747 float   drawrotpic(vector position, string pic, vector size, vector org, float angle, vector rgb, float alpha, float flag)
3748 =========
3749 */
3750 void VM_drawrotpic(void)
3751 {
3752         const char *picname;
3753         float *size, *pos, *org, *rgb;
3754         int flag;
3755
3756         VM_SAFEPARMCOUNT(8,VM_drawrotpic);
3757
3758         picname = PRVM_G_STRING(OFS_PARM1);
3759         VM_CheckEmptyString (picname);
3760
3761         // is pic cached ? no function yet for that
3762         if(!1)
3763         {
3764                 PRVM_G_FLOAT(OFS_RETURN) = -4;
3765                 VM_Warning("VM_drawrotpic: %s: %s not cached !\n", PRVM_NAME, picname);
3766                 return;
3767         }
3768
3769         pos = PRVM_G_VECTOR(OFS_PARM0);
3770         size = PRVM_G_VECTOR(OFS_PARM2);
3771         org = PRVM_G_VECTOR(OFS_PARM3);
3772         rgb = PRVM_G_VECTOR(OFS_PARM5);
3773         flag = (int) PRVM_G_FLOAT(OFS_PARM7);
3774
3775         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3776         {
3777                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3778                 VM_Warning("VM_drawrotpic: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3779                 return;
3780         }
3781
3782         if(pos[2] || size[2] || org[2])
3783                 Con_Printf("VM_drawrotpic: z value from pos/size/org discarded\n");
3784
3785         DrawQ_RotPic(pos[0], pos[1], Draw_CachePic_Flags(picname, CACHEPICFLAG_NOTPERSISTENT), size[0], size[1], org[0], org[1], PRVM_G_FLOAT(OFS_PARM4), rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM6), flag);
3786         PRVM_G_FLOAT(OFS_RETURN) = 1;
3787 }
3788 /*
3789 =========
3790 VM_drawsubpic
3791
3792 float   drawsubpic(vector position, vector size, string pic, vector srcPos, vector srcSize, vector rgb, float alpha, float flag)
3793
3794 =========
3795 */
3796 void VM_drawsubpic(void)
3797 {
3798         const char *picname;
3799         float *size, *pos, *rgb, *srcPos, *srcSize, alpha;
3800         int flag;
3801
3802         VM_SAFEPARMCOUNT(8,VM_drawsubpic);
3803
3804         picname = PRVM_G_STRING(OFS_PARM2);
3805         VM_CheckEmptyString (picname);
3806
3807         // is pic cached ? no function yet for that
3808         if(!1)
3809         {
3810                 PRVM_G_FLOAT(OFS_RETURN) = -4;
3811                 VM_Warning("VM_drawsubpic: %s: %s not cached !\n", PRVM_NAME, picname);
3812                 return;
3813         }
3814
3815         pos = PRVM_G_VECTOR(OFS_PARM0);
3816         size = PRVM_G_VECTOR(OFS_PARM1);
3817         srcPos = PRVM_G_VECTOR(OFS_PARM3);
3818         srcSize = PRVM_G_VECTOR(OFS_PARM4);
3819         rgb = PRVM_G_VECTOR(OFS_PARM5);
3820         alpha = PRVM_G_FLOAT(OFS_PARM6);
3821         flag = (int) PRVM_G_FLOAT(OFS_PARM7);
3822
3823         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3824         {
3825                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3826                 VM_Warning("VM_drawsubpic: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3827                 return;
3828         }
3829
3830         if(pos[2] || size[2])
3831                 Con_Printf("VM_drawsubpic: z value%s from %s discarded\n",(pos[2] && size[2]) ? "s" : " ",((pos[2] && size[2]) ? "pos and size" : (pos[2] ? "pos" : "size")));
3832
3833         DrawQ_SuperPic(pos[0], pos[1], Draw_CachePic_Flags (picname, CACHEPICFLAG_NOTPERSISTENT),
3834                 size[0], size[1],
3835                 srcPos[0],              srcPos[1],              rgb[0], rgb[1], rgb[2], alpha,
3836                 srcPos[0] + srcSize[0], srcPos[1],              rgb[0], rgb[1], rgb[2], alpha,
3837                 srcPos[0],              srcPos[1] + srcSize[1], rgb[0], rgb[1], rgb[2], alpha,
3838                 srcPos[0] + srcSize[0], srcPos[1] + srcSize[1], rgb[0], rgb[1], rgb[2], alpha,
3839                 flag);
3840         PRVM_G_FLOAT(OFS_RETURN) = 1;
3841 }
3842
3843 /*
3844 =========
3845 VM_drawfill
3846
3847 float drawfill(vector position, vector size, vector rgb, float alpha, float flag)
3848 =========
3849 */
3850 void VM_drawfill(void)
3851 {
3852         float *size, *pos, *rgb;
3853         int flag;
3854
3855         VM_SAFEPARMCOUNT(5,VM_drawfill);
3856
3857
3858         pos = PRVM_G_VECTOR(OFS_PARM0);
3859         size = PRVM_G_VECTOR(OFS_PARM1);
3860         rgb = PRVM_G_VECTOR(OFS_PARM2);
3861         flag = (int) PRVM_G_FLOAT(OFS_PARM4);
3862
3863         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3864         {
3865                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3866                 VM_Warning("VM_drawfill: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3867                 return;
3868         }
3869
3870         if(pos[2] || size[2])
3871                 Con_Printf("VM_drawfill: z value%s from %s discarded\n",(pos[2] && size[2]) ? "s" : " ",((pos[2] && size[2]) ? "pos and size" : (pos[2] ? "pos" : "size")));
3872
3873         DrawQ_Fill(pos[0], pos[1], size[0], size[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM3), flag);
3874         PRVM_G_FLOAT(OFS_RETURN) = 1;
3875 }
3876
3877 /*
3878 =========
3879 VM_drawsetcliparea
3880
3881 drawsetcliparea(float x, float y, float width, float height)
3882 =========
3883 */
3884 void VM_drawsetcliparea(void)
3885 {
3886         float x,y,w,h;
3887         VM_SAFEPARMCOUNT(4,VM_drawsetcliparea);
3888
3889         x = bound(0, PRVM_G_FLOAT(OFS_PARM0), vid_conwidth.integer);
3890         y = bound(0, PRVM_G_FLOAT(OFS_PARM1), vid_conheight.integer);
3891         w = bound(0, PRVM_G_FLOAT(OFS_PARM2) + PRVM_G_FLOAT(OFS_PARM0) - x, (vid_conwidth.integer  - x));
3892         h = bound(0, PRVM_G_FLOAT(OFS_PARM3) + PRVM_G_FLOAT(OFS_PARM1) - y, (vid_conheight.integer - y));
3893
3894         DrawQ_SetClipArea(x, y, w, h);
3895 }
3896
3897 /*
3898 =========
3899 VM_drawresetcliparea
3900
3901 drawresetcliparea()
3902 =========
3903 */
3904 void VM_drawresetcliparea(void)
3905 {
3906         VM_SAFEPARMCOUNT(0,VM_drawresetcliparea);
3907
3908         DrawQ_ResetClipArea();
3909 }
3910
3911 /*
3912 =========
3913 VM_getimagesize
3914
3915 vector  getimagesize(string pic)
3916 =========
3917 */
3918 void VM_getimagesize(void)
3919 {
3920         const char *p;
3921         cachepic_t *pic;
3922
3923         VM_SAFEPARMCOUNT(1,VM_getimagesize);
3924
3925         p = PRVM_G_STRING(OFS_PARM0);
3926         VM_CheckEmptyString (p);
3927
3928         pic = Draw_CachePic_Flags (p, CACHEPICFLAG_NOTPERSISTENT);
3929
3930         PRVM_G_VECTOR(OFS_RETURN)[0] = pic->width;
3931         PRVM_G_VECTOR(OFS_RETURN)[1] = pic->height;
3932         PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
3933 }
3934
3935 /*
3936 =========
3937 VM_keynumtostring
3938
3939 string keynumtostring(float keynum)
3940 =========
3941 */
3942 void VM_keynumtostring (void)
3943 {
3944         VM_SAFEPARMCOUNT(1, VM_keynumtostring);
3945
3946         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(Key_KeynumToString((int)PRVM_G_FLOAT(OFS_PARM0)));
3947 }
3948
3949 /*
3950 =========
3951 VM_findkeysforcommand
3952
3953 string  findkeysforcommand(string command, float bindmap)
3954
3955 the returned string is an altstring
3956 =========
3957 */
3958 #define FKFC_NUMKEYS 5
3959 void M_FindKeysForCommand(const char *command, int *keys);
3960 void VM_findkeysforcommand(void)
3961 {
3962         const char *cmd;
3963         char ret[VM_STRINGTEMP_LENGTH];
3964         int keys[FKFC_NUMKEYS];
3965         int i;
3966         int bindmap;
3967
3968         VM_SAFEPARMCOUNTRANGE(1, 2, VM_findkeysforcommand);
3969
3970         cmd = PRVM_G_STRING(OFS_PARM0);
3971         if(prog->argc == 2)
3972                 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM1), MAX_BINDMAPS-1);
3973         else
3974                 bindmap = 0; // consistent to "bind"
3975
3976         VM_CheckEmptyString(cmd);
3977
3978         Key_FindKeysForCommand(cmd, keys, FKFC_NUMKEYS, bindmap);
3979
3980         ret[0] = 0;
3981         for(i = 0; i < FKFC_NUMKEYS; i++)
3982                 strlcat(ret, va(" \'%i\'", keys[i]), sizeof(ret));
3983
3984         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(ret);
3985 }
3986
3987 /*
3988 =========
3989 VM_stringtokeynum
3990
3991 float stringtokeynum(string key)
3992 =========
3993 */
3994 void VM_stringtokeynum (void)
3995 {
3996         VM_SAFEPARMCOUNT( 1, VM_keynumtostring );
3997
3998         PRVM_G_FLOAT(OFS_RETURN) = Key_StringToKeynum(PRVM_G_STRING(OFS_PARM0));
3999 }
4000
4001 /*
4002 =========
4003 VM_getkeybind
4004
4005 string getkeybind(float key, float bindmap)
4006 =========
4007 */
4008 void VM_getkeybind (void)
4009 {
4010         int bindmap;
4011         VM_SAFEPARMCOUNTRANGE(1, 2, VM_CL_getkeybind);
4012         if(prog->argc == 2)
4013                 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM1), MAX_BINDMAPS-1);
4014         else
4015                 bindmap = 0; // consistent to "bind"
4016
4017         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(Key_GetBind((int)PRVM_G_FLOAT(OFS_PARM0), bindmap));
4018 }
4019
4020 /*
4021 =========
4022 VM_setkeybind
4023
4024 float setkeybind(float key, string cmd, float bindmap)
4025 =========
4026 */
4027 void VM_setkeybind (void)
4028 {
4029         int bindmap;
4030         VM_SAFEPARMCOUNTRANGE(2, 3, VM_CL_setkeybind);
4031         if(prog->argc == 3)
4032                 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM2), MAX_BINDMAPS-1);
4033         else
4034                 bindmap = 0; // consistent to "bind"
4035
4036         PRVM_G_FLOAT(OFS_RETURN) = 0;
4037         if(Key_SetBinding((int)PRVM_G_FLOAT(OFS_PARM0), bindmap, PRVM_G_STRING(OFS_PARM1)))
4038                 PRVM_G_FLOAT(OFS_RETURN) = 1;
4039 }
4040
4041 /*
4042 =========
4043 VM_getbindmap
4044
4045 vector getbindmaps()
4046 =========
4047 */
4048 void VM_getbindmaps (void)
4049 {
4050         int fg, bg;
4051         VM_SAFEPARMCOUNT(0, VM_CL_getbindmap);
4052         Key_GetBindMap(&fg, &bg);
4053         PRVM_G_VECTOR(OFS_RETURN)[0] = fg;
4054         PRVM_G_VECTOR(OFS_RETURN)[1] = bg;
4055         PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
4056 }
4057
4058 /*
4059 =========
4060 VM_setbindmap
4061
4062 float setbindmaps(vector bindmap)
4063 =========
4064 */
4065 void VM_setbindmaps (void)
4066 {
4067         VM_SAFEPARMCOUNT(1, VM_CL_setbindmap);
4068         PRVM_G_FLOAT(OFS_RETURN) = 0;
4069         if(PRVM_G_VECTOR(OFS_PARM0)[2] == 0)
4070                 if(Key_SetBindMap((int)PRVM_G_VECTOR(OFS_PARM0)[0], (int)PRVM_G_VECTOR(OFS_PARM0)[1]))
4071                         PRVM_G_FLOAT(OFS_RETURN) = 1;
4072 }
4073
4074 // CL_Video interface functions
4075
4076 /*
4077 ========================
4078 VM_cin_open
4079
4080 float cin_open(string file, string name)
4081 ========================
4082 */
4083 void VM_cin_open( void )
4084 {
4085         const char *file;
4086         const char *name;
4087
4088         VM_SAFEPARMCOUNT( 2, VM_cin_open );
4089
4090         file = PRVM_G_STRING( OFS_PARM0 );
4091         name = PRVM_G_STRING( OFS_PARM1 );
4092
4093         VM_CheckEmptyString( file );
4094     VM_CheckEmptyString( name );
4095
4096         if( CL_OpenVideo( file, name, MENUOWNER, "" ) )
4097                 PRVM_G_FLOAT( OFS_RETURN ) = 1;
4098         else
4099                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
4100 }
4101
4102 /*
4103 ========================
4104 VM_cin_close
4105
4106 void cin_close(string name)
4107 ========================
4108 */
4109 void VM_cin_close( void )
4110 {
4111         const char *name;
4112
4113         VM_SAFEPARMCOUNT( 1, VM_cin_close );
4114
4115         name = PRVM_G_STRING( OFS_PARM0 );
4116         VM_CheckEmptyString( name );
4117
4118         CL_CloseVideo( CL_GetVideoByName( name ) );
4119 }
4120
4121 /*
4122 ========================
4123 VM_cin_setstate
4124 void cin_setstate(string name, float type)
4125 ========================
4126 */
4127 void VM_cin_setstate( void )
4128 {
4129         const char *name;
4130         clvideostate_t  state;
4131         clvideo_t               *video;
4132
4133         VM_SAFEPARMCOUNT( 2, VM_cin_netstate );
4134
4135         name = PRVM_G_STRING( OFS_PARM0 );
4136         VM_CheckEmptyString( name );
4137
4138         state = (clvideostate_t)((int)PRVM_G_FLOAT( OFS_PARM1 ));
4139
4140         video = CL_GetVideoByName( name );
4141         if( video && state > CLVIDEO_UNUSED && state < CLVIDEO_STATECOUNT )
4142                 CL_SetVideoState( video, state );
4143 }
4144
4145 /*
4146 ========================
4147 VM_cin_getstate
4148
4149 float cin_getstate(string name)
4150 ========================
4151 */
4152 void VM_cin_getstate( void )
4153 {
4154         const char *name;
4155         clvideo_t               *video;
4156
4157         VM_SAFEPARMCOUNT( 1, VM_cin_getstate );
4158
4159         name = PRVM_G_STRING( OFS_PARM0 );
4160         VM_CheckEmptyString( name );
4161
4162         video = CL_GetVideoByName( name );
4163         if( video )
4164                 PRVM_G_FLOAT( OFS_RETURN ) = (int)video->state;
4165         else
4166                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
4167 }
4168
4169 /*
4170 ========================
4171 VM_cin_restart
4172
4173 void cin_restart(string name)
4174 ========================
4175 */
4176 void VM_cin_restart( void )
4177 {
4178         const char *name;
4179         clvideo_t               *video;
4180
4181         VM_SAFEPARMCOUNT( 1, VM_cin_restart );
4182
4183         name = PRVM_G_STRING( OFS_PARM0 );
4184         VM_CheckEmptyString( name );
4185
4186         video = CL_GetVideoByName( name );
4187         if( video )
4188                 CL_RestartVideo( video );
4189 }
4190
4191 /*
4192 ========================
4193 VM_Gecko_Init
4194 ========================
4195 */
4196 void VM_Gecko_Init( void ) {
4197         // the prog struct is memset to 0 by Initprog? [12/6/2007 Black]
4198         // FIXME: remove the other _Init functions then, too? [12/6/2007 Black]
4199 }
4200
4201 /*
4202 ========================
4203 VM_Gecko_Destroy
4204 ========================
4205 */
4206 void VM_Gecko_Destroy( void ) {
4207         int i;
4208         for( i = 0 ; i < PRVM_MAX_GECKOINSTANCES ; i++ ) {
4209                 clgecko_t **instance = &prog->opengeckoinstances[ i ];
4210                 if( *instance ) {
4211                         CL_Gecko_DestroyBrowser( *instance );
4212                 }
4213                 *instance = NULL;
4214         }
4215 }
4216
4217 /*
4218 ========================
4219 VM_gecko_create
4220
4221 float[bool] gecko_create( string name )
4222 ========================
4223 */
4224 void VM_gecko_create( void ) {
4225         const char *name;
4226         int i;
4227         clgecko_t *instance;
4228         
4229         VM_SAFEPARMCOUNT( 1, VM_gecko_create );
4230
4231         name = PRVM_G_STRING( OFS_PARM0 );
4232         VM_CheckEmptyString( name );
4233
4234         // find an empty slot for this gecko browser..
4235         for( i = 0 ; i < PRVM_MAX_GECKOINSTANCES ; i++ ) {
4236                 if( prog->opengeckoinstances[ i ] == NULL ) {
4237                         break;
4238                 }
4239         }
4240         if( i == PRVM_MAX_GECKOINSTANCES ) {
4241                         VM_Warning("VM_gecko_create: %s ran out of gecko handles (%i)\n", PRVM_NAME, PRVM_MAX_GECKOINSTANCES);
4242                         PRVM_G_FLOAT( OFS_RETURN ) = 0;
4243                         return;
4244         }
4245
4246         instance = prog->opengeckoinstances[ i ] = CL_Gecko_CreateBrowser( name, PRVM_GetProgNr() );
4247    if( !instance ) {
4248                 // TODO: error handling [12/3/2007 Black]
4249                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
4250                 return;
4251         }
4252         PRVM_G_FLOAT( OFS_RETURN ) = 1;
4253 }
4254
4255 /*
4256 ========================
4257 VM_gecko_destroy
4258
4259 void gecko_destroy( string name )
4260 ========================
4261 */
4262 void VM_gecko_destroy( void ) {
4263         const char *name;
4264         clgecko_t *instance;
4265
4266         VM_SAFEPARMCOUNT( 1, VM_gecko_destroy );
4267
4268         name = PRVM_G_STRING( OFS_PARM0 );
4269         VM_CheckEmptyString( name );
4270         instance = CL_Gecko_FindBrowser( name );
4271         if( !instance ) {
4272                 return;
4273         }
4274         CL_Gecko_DestroyBrowser( instance );
4275 }
4276
4277 /*
4278 ========================
4279 VM_gecko_navigate
4280
4281 void gecko_navigate( string name, string URI )
4282 ========================
4283 */
4284 void VM_gecko_navigate( void ) {
4285         const char *name;
4286         const char *URI;
4287         clgecko_t *instance;
4288
4289         VM_SAFEPARMCOUNT( 2, VM_gecko_navigate );
4290
4291         name = PRVM_G_STRING( OFS_PARM0 );
4292         URI = PRVM_G_STRING( OFS_PARM1 );
4293         VM_CheckEmptyString( name );
4294         VM_CheckEmptyString( URI );
4295
4296    instance = CL_Gecko_FindBrowser( name );
4297         if( !instance ) {
4298                 return;
4299         }
4300         CL_Gecko_NavigateToURI( instance, URI );
4301 }
4302
4303 /*
4304 ========================
4305 VM_gecko_keyevent
4306
4307 float[bool] gecko_keyevent( string name, float key, float eventtype ) 
4308 ========================
4309 */
4310 void VM_gecko_keyevent( void ) {
4311         const char *name;
4312         unsigned int key;
4313         clgecko_buttoneventtype_t eventtype;
4314         clgecko_t *instance;
4315
4316         VM_SAFEPARMCOUNT( 3, VM_gecko_keyevent );
4317
4318         name = PRVM_G_STRING( OFS_PARM0 );
4319         VM_CheckEmptyString( name );
4320         key = (unsigned int) PRVM_G_FLOAT( OFS_PARM1 );
4321         switch( (unsigned int) PRVM_G_FLOAT( OFS_PARM2 ) ) {
4322         case 0:
4323                 eventtype = CLG_BET_DOWN;
4324                 break;
4325         case 1:
4326                 eventtype = CLG_BET_UP;
4327                 break;
4328         case 2:
4329                 eventtype = CLG_BET_PRESS;
4330                 break;
4331         case 3:
4332                 eventtype = CLG_BET_DOUBLECLICK;
4333                 break;
4334         default:
4335                 // TODO: console printf? [12/3/2007 Black]
4336                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
4337                 return;
4338         }
4339
4340         instance = CL_Gecko_FindBrowser( name );
4341         if( !instance ) {
4342                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
4343                 return;
4344         }
4345
4346         PRVM_G_FLOAT( OFS_RETURN ) = (CL_Gecko_Event_Key( instance, (keynum_t) key, eventtype ) == true);
4347 }
4348
4349 /*
4350 ========================
4351 VM_gecko_movemouse
4352
4353 void gecko_mousemove( string name, float x, float y )
4354 ========================
4355 */
4356 void VM_gecko_movemouse( void ) {
4357         const char *name;
4358         float x, y;
4359         clgecko_t *instance;
4360
4361         VM_SAFEPARMCOUNT( 3, VM_gecko_movemouse );
4362
4363         name = PRVM_G_STRING( OFS_PARM0 );
4364         VM_CheckEmptyString( name );
4365         x = PRVM_G_FLOAT( OFS_PARM1 );
4366         y = PRVM_G_FLOAT( OFS_PARM2 );
4367         
4368         instance = CL_Gecko_FindBrowser( name );
4369         if( !instance ) {
4370                 return;
4371         }
4372         CL_Gecko_Event_CursorMove( instance, x, y );
4373 }
4374
4375
4376 /*
4377 ========================
4378 VM_gecko_resize
4379
4380 void gecko_resize( string name, float w, float h )
4381 ========================
4382 */
4383 void VM_gecko_resize( void ) {
4384         const char *name;
4385         float w, h;
4386         clgecko_t *instance;
4387
4388         VM_SAFEPARMCOUNT( 3, VM_gecko_movemouse );
4389
4390         name = PRVM_G_STRING( OFS_PARM0 );
4391         VM_CheckEmptyString( name );
4392         w = PRVM_G_FLOAT( OFS_PARM1 );
4393         h = PRVM_G_FLOAT( OFS_PARM2 );
4394         
4395         instance = CL_Gecko_FindBrowser( name );
4396         if( !instance ) {
4397                 return;
4398         }
4399         CL_Gecko_Resize( instance, (int) w, (int) h );
4400 }
4401
4402
4403 /*
4404 ========================
4405 VM_gecko_get_texture_extent
4406
4407 vector gecko_get_texture_extent( string name )
4408 ========================
4409 */
4410 void VM_gecko_get_texture_extent( void ) {
4411         const char *name;
4412         clgecko_t *instance;
4413
4414         VM_SAFEPARMCOUNT( 1, VM_gecko_movemouse );
4415
4416         name = PRVM_G_STRING( OFS_PARM0 );
4417         VM_CheckEmptyString( name );
4418         
4419         PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
4420         instance = CL_Gecko_FindBrowser( name );
4421         if( !instance ) {
4422                 PRVM_G_VECTOR(OFS_RETURN)[0] = 0;
4423                 PRVM_G_VECTOR(OFS_RETURN)[1] = 0;
4424                 return;
4425         }
4426         CL_Gecko_GetTextureExtent( instance, 
4427                 PRVM_G_VECTOR(OFS_RETURN), PRVM_G_VECTOR(OFS_RETURN)+1 );
4428 }
4429
4430
4431
4432 /*
4433 ==============
4434 VM_makevectors
4435
4436 Writes new values for v_forward, v_up, and v_right based on angles
4437 void makevectors(vector angle)
4438 ==============
4439 */
4440 void VM_makevectors (void)
4441 {
4442         VM_SAFEPARMCOUNT(1, VM_makevectors);
4443         AngleVectors(PRVM_G_VECTOR(OFS_PARM0), PRVM_gameglobalvector(v_forward), PRVM_gameglobalvector(v_right), PRVM_gameglobalvector(v_up));
4444 }
4445
4446 /*
4447 ==============
4448 VM_vectorvectors
4449
4450 Writes new values for v_forward, v_up, and v_right based on the given forward vector
4451 vectorvectors(vector)
4452 ==============
4453 */
4454 void VM_vectorvectors (void)
4455 {
4456         VM_SAFEPARMCOUNT(1, VM_vectorvectors);
4457         VectorNormalize2(PRVM_G_VECTOR(OFS_PARM0), PRVM_gameglobalvector(v_forward));
4458         VectorVectors(PRVM_gameglobalvector(v_forward), PRVM_gameglobalvector(v_right), PRVM_gameglobalvector(v_up));
4459 }
4460
4461 /*
4462 ========================
4463 VM_drawline
4464
4465 void drawline(float width, vector pos1, vector pos2, vector rgb, float alpha, float flags)
4466 ========================
4467 */
4468 void VM_drawline (void)
4469 {
4470         float   *c1, *c2, *rgb;
4471         float   alpha, width;
4472         unsigned char   flags;
4473
4474         VM_SAFEPARMCOUNT(6, VM_drawline);
4475         width   = PRVM_G_FLOAT(OFS_PARM0);
4476         c1              = PRVM_G_VECTOR(OFS_PARM1);
4477         c2              = PRVM_G_VECTOR(OFS_PARM2);
4478         rgb             = PRVM_G_VECTOR(OFS_PARM3);
4479         alpha   = PRVM_G_FLOAT(OFS_PARM4);
4480         flags   = (int)PRVM_G_FLOAT(OFS_PARM5);
4481         DrawQ_Line(width, c1[0], c1[1], c2[0], c2[1], rgb[0], rgb[1], rgb[2], alpha, flags);
4482 }
4483
4484 // float(float number, float quantity) bitshift (EXT_BITSHIFT)
4485 void VM_bitshift (void)
4486 {
4487         int n1, n2;
4488         VM_SAFEPARMCOUNT(2, VM_bitshift);
4489
4490         n1 = (int)fabs((float)((int)PRVM_G_FLOAT(OFS_PARM0)));
4491         n2 = (int)PRVM_G_FLOAT(OFS_PARM1);
4492         if(!n1)
4493                 PRVM_G_FLOAT(OFS_RETURN) = n1;
4494         else
4495         if(n2 < 0)
4496                 PRVM_G_FLOAT(OFS_RETURN) = (n1 >> -n2);
4497         else
4498                 PRVM_G_FLOAT(OFS_RETURN) = (n1 << n2);
4499 }
4500
4501 ////////////////////////////////////////
4502 // AltString functions
4503 ////////////////////////////////////////
4504
4505 /*
4506 ========================
4507 VM_altstr_count
4508
4509 float altstr_count(string)
4510 ========================
4511 */
4512 void VM_altstr_count( void )
4513 {
4514         const char *altstr, *pos;
4515         int     count;
4516
4517         VM_SAFEPARMCOUNT( 1, VM_altstr_count );
4518
4519