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