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