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