]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - prvm_cmds.c
removed OffscreenGecko support because it is not maintained
[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 #include "mdfour.h"
17
18 extern cvar_t prvm_backtraceforwarnings;
19
20 // LordHavoc: changed this to NOT use a return statement, so that it can be used in functions that must return a value
21 void VM_Warning(const char *fmt, ...)
22 {
23         va_list argptr;
24         char msg[MAX_INPUTLINE];
25         static double recursive = -1;
26
27         va_start(argptr,fmt);
28         dpvsnprintf(msg,sizeof(msg),fmt,argptr);
29         va_end(argptr);
30
31         Con_DPrint(msg);
32
33         // TODO: either add a cvar/cmd to control the state dumping or replace some of the calls with Con_Printf [9/13/2006 Black]
34         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
35         {
36                 recursive = realtime;
37                 PRVM_PrintState();
38                 recursive = -1;
39         }
40 }
41
42
43 //============================================================================
44 // Common
45
46 // TODO DONE: move vm_files and vm_fssearchlist to prvm_prog_t struct
47 // TODO: move vm_files and vm_fssearchlist back [9/13/2006 Black]
48 // TODO: (move vm_files and vm_fssearchlist to prvm_prog_t struct again) [2007-01-23 LordHavoc]
49 // TODO: will this war ever end? [2007-01-23 LordHavoc]
50
51 void VM_CheckEmptyString (const char *s)
52 {
53         if (ISWHITESPACE(s[0]))
54                 PRVM_ERROR ("%s: Bad string", PRVM_NAME);
55 }
56
57 void VM_GenerateFrameGroupBlend(framegroupblend_t *framegroupblend, const prvm_edict_t *ed)
58 {
59         // self.frame is the interpolation target (new frame)
60         // self.frame1time is the animation base time for the interpolation target
61         // self.frame2 is the interpolation start (previous frame)
62         // self.frame2time is the animation base time for the interpolation start
63         // self.lerpfrac is the interpolation strength for self.frame2
64         // self.lerpfrac3 is the interpolation strength for self.frame3
65         // self.lerpfrac4 is the interpolation strength for self.frame4
66         // pitch angle on a player model where the animator set up 5 sets of
67         // animations and the csqc simply lerps between sets)
68         framegroupblend[0].frame = (int) PRVM_gameedictfloat(ed, frame     );
69         framegroupblend[1].frame = (int) PRVM_gameedictfloat(ed, frame2    );
70         framegroupblend[2].frame = (int) PRVM_gameedictfloat(ed, frame3    );
71         framegroupblend[3].frame = (int) PRVM_gameedictfloat(ed, frame4    );
72         framegroupblend[0].start =       PRVM_gameedictfloat(ed, frame1time);
73         framegroupblend[1].start =       PRVM_gameedictfloat(ed, frame2time);
74         framegroupblend[2].start =       PRVM_gameedictfloat(ed, frame3time);
75         framegroupblend[3].start =       PRVM_gameedictfloat(ed, frame4time);
76         framegroupblend[1].lerp  =       PRVM_gameedictfloat(ed, lerpfrac  );
77         framegroupblend[2].lerp  =       PRVM_gameedictfloat(ed, lerpfrac3 );
78         framegroupblend[3].lerp  =       PRVM_gameedictfloat(ed, lerpfrac4 );
79         // assume that the (missing) lerpfrac1 is whatever remains after lerpfrac2+lerpfrac3+lerpfrac4 are summed
80         framegroupblend[0].lerp = 1 - framegroupblend[1].lerp - framegroupblend[2].lerp - framegroupblend[3].lerp;
81 }
82
83 // LordHavoc: quite tempting to break apart this function to reuse the
84 //            duplicated code, but I suspect it is better for performance
85 //            this way
86 void VM_FrameBlendFromFrameGroupBlend(frameblend_t *frameblend, const framegroupblend_t *framegroupblend, const dp_model_t *model)
87 {
88         int sub2, numframes, f, i, k;
89         int isfirstframegroup = true;
90         int nolerp;
91         double sublerp, lerp, d;
92         const animscene_t *scene;
93         const framegroupblend_t *g;
94         frameblend_t *blend = frameblend;
95
96         memset(blend, 0, MAX_FRAMEBLENDS * sizeof(*blend));
97
98         if (!model || !model->surfmesh.isanimated)
99         {
100                 blend[0].lerp = 1;
101                 return;
102         }
103
104         nolerp = (model->type == mod_sprite) ? !r_lerpsprites.integer : !r_lerpmodels.integer;
105         numframes = model->numframes;
106         for (k = 0, g = framegroupblend;k < MAX_FRAMEGROUPBLENDS;k++, g++)
107         {
108                 f = g->frame;
109                 if ((unsigned int)f >= (unsigned int)numframes)
110                 {
111                         Con_DPrintf("VM_FrameBlendFromFrameGroupBlend: no such frame %d in model %s\n", f, model->name);
112                         f = 0;
113                 }
114                 d = lerp = g->lerp;
115                 if (lerp <= 0)
116                         continue;
117                 if (nolerp)
118                 {
119                         if (isfirstframegroup)
120                         {
121                                 d = lerp = 1;
122                                 isfirstframegroup = false;
123                         }
124                         else
125                                 continue;
126                 }
127                 if (model->animscenes)
128                 {
129                         scene = model->animscenes + f;
130                         f = scene->firstframe;
131                         if (scene->framecount > 1)
132                         {
133                                 // this code path is only used on .zym models and torches
134                                 sublerp = scene->framerate * (cl.time - g->start);
135                                 f = (int) floor(sublerp);
136                                 sublerp -= f;
137                                 sub2 = f + 1;
138                                 if (sublerp < (1.0 / 65536.0f))
139                                         sublerp = 0;
140                                 if (sublerp > (65535.0f / 65536.0f))
141                                         sublerp = 1;
142                                 if (nolerp)
143                                         sublerp = 0;
144                                 if (scene->loop)
145                                 {
146                                         f = (f % scene->framecount);
147                                         sub2 = (sub2 % scene->framecount);
148                                 }
149                                 f = bound(0, f, (scene->framecount - 1)) + scene->firstframe;
150                                 sub2 = bound(0, sub2, (scene->framecount - 1)) + scene->firstframe;
151                                 d = sublerp * lerp;
152                                 // two framelerps produced from one animation
153                                 if (d > 0)
154                                 {
155                                         for (i = 0;i < MAX_FRAMEBLENDS;i++)
156                                         {
157                                                 if (blend[i].lerp <= 0 || blend[i].subframe == sub2)
158                                                 {
159                                                         blend[i].subframe = sub2;
160                                                         blend[i].lerp += d;
161                                                         break;
162                                                 }
163                                         }
164                                 }
165                                 d = (1 - sublerp) * lerp;
166                         }
167                 }
168                 if (d > 0)
169                 {
170                         for (i = 0;i < MAX_FRAMEBLENDS;i++)
171                         {
172                                 if (blend[i].lerp <= 0 || blend[i].subframe == f)
173                                 {
174                                         blend[i].subframe = f;
175                                         blend[i].lerp += d;
176                                         break;
177                                 }
178                         }
179                 }
180         }
181 }
182
183 void VM_UpdateEdictSkeleton(prvm_edict_t *ed, const dp_model_t *edmodel, const frameblend_t *frameblend)
184 {
185         if (ed->priv.server->skeleton.model != edmodel)
186         {
187                 VM_RemoveEdictSkeleton(ed);
188                 ed->priv.server->skeleton.model = edmodel;
189         }
190         if (!ed->priv.server->skeleton.model || !ed->priv.server->skeleton.model->num_bones)
191         {
192                 if(ed->priv.server->skeleton.relativetransforms)
193                         Mem_Free(ed->priv.server->skeleton.relativetransforms);
194                 ed->priv.server->skeleton.relativetransforms = NULL;
195                 return;
196         }
197
198         {
199                 int skeletonindex = -1;
200                 skeleton_t *skeleton;
201                 skeletonindex = (int)PRVM_gameedictfloat(ed, skeletonindex) - 1;
202                 if (skeletonindex >= 0 && skeletonindex < MAX_EDICTS && (skeleton = prog->skeletons[skeletonindex]) && skeleton->model->num_bones == ed->priv.server->skeleton.model->num_bones)
203                 {
204                         // custom skeleton controlled by the game (FTE_CSQC_SKELETONOBJECTS)
205                         if (!ed->priv.server->skeleton.relativetransforms)
206                                 ed->priv.server->skeleton.relativetransforms = (matrix4x4_t *)Mem_Alloc(prog->progs_mempool, ed->priv.server->skeleton.model->num_bones * sizeof(matrix4x4_t));
207                         memcpy(ed->priv.server->skeleton.relativetransforms, skeleton->relativetransforms, ed->priv.server->skeleton.model->num_bones * sizeof(matrix4x4_t));
208                 }
209                 else
210                 {
211                         if(ed->priv.server->skeleton.relativetransforms)
212                                 Mem_Free(ed->priv.server->skeleton.relativetransforms);
213                         ed->priv.server->skeleton.relativetransforms = NULL;
214                 }
215         }
216 }
217
218 void VM_RemoveEdictSkeleton(prvm_edict_t *ed)
219 {
220         if (ed->priv.server->skeleton.relativetransforms)
221                 Mem_Free(ed->priv.server->skeleton.relativetransforms);
222         memset(&ed->priv.server->skeleton, 0, sizeof(ed->priv.server->skeleton));
223 }
224
225
226
227
228 //============================================================================
229 //BUILT-IN FUNCTIONS
230
231 void VM_VarString(int first, char *out, int outlength)
232 {
233         int i;
234         const char *s;
235         char *outend;
236
237         outend = out + outlength - 1;
238         for (i = first;i < prog->argc && out < outend;i++)
239         {
240                 s = PRVM_G_STRING((OFS_PARM0+i*3));
241                 while (out < outend && *s)
242                         *out++ = *s++;
243         }
244         *out++ = 0;
245 }
246
247 /*
248 =================
249 VM_checkextension
250
251 returns true if the extension is supported by the server
252
253 checkextension(extensionname)
254 =================
255 */
256
257 // kind of helper function
258 static qboolean checkextension(const char *name)
259 {
260         int len;
261         const char *e, *start;
262         len = (int)strlen(name);
263
264         for (e = prog->extensionstring;*e;e++)
265         {
266                 while (*e == ' ')
267                         e++;
268                 if (!*e)
269                         break;
270                 start = e;
271                 while (*e && *e != ' ')
272                         e++;
273                 if ((e - start) == len && !strncasecmp(start, name, len))
274                 {
275                         // special sheck for ODE
276                         if (!strncasecmp("DP_PHYSICS_ODE", name, 14))
277                         {
278 #ifdef USEODE
279                                 return ode_dll ? true : false;
280 #else
281                                 return false;
282 #endif
283                         }
284
285                         // special sheck for d0_blind_id
286                         if (!strcasecmp("DP_CRYPTO", name))
287                                 return Crypto_Available();
288                         if (!strcasecmp("DP_QC_DIGEST_SHA256", name))
289                                 return Crypto_Available();
290
291                         return true;
292                 }
293         }
294         return false;
295 }
296
297 void VM_checkextension (void)
298 {
299         VM_SAFEPARMCOUNT(1,VM_checkextension);
300
301         PRVM_G_FLOAT(OFS_RETURN) = checkextension(PRVM_G_STRING(OFS_PARM0));
302 }
303
304 /*
305 =================
306 VM_error
307
308 This is a TERMINAL error, which will kill off the entire prog.
309 Dumps self.
310
311 error(value)
312 =================
313 */
314 void VM_error (void)
315 {
316         prvm_edict_t    *ed;
317         char string[VM_STRINGTEMP_LENGTH];
318
319         VM_VarString(0, string, sizeof(string));
320         Con_Printf("======%s ERROR in %s:\n%s\n", PRVM_NAME, PRVM_GetString(prog->xfunction->s_name), string);
321         ed = PRVM_PROG_TO_EDICT(PRVM_allglobaledict(self));
322         PRVM_ED_Print(ed, NULL);
323
324         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);
325 }
326
327 /*
328 =================
329 VM_objerror
330
331 Dumps out self, then an error message.  The program is aborted and self is
332 removed, but the level can continue.
333
334 objerror(value)
335 =================
336 */
337 void VM_objerror (void)
338 {
339         prvm_edict_t    *ed;
340         char string[VM_STRINGTEMP_LENGTH];
341
342         VM_VarString(0, string, sizeof(string));
343         Con_Printf("======OBJECT ERROR======\n"); // , PRVM_NAME, PRVM_GetString(prog->xfunction->s_name), string); // or include them? FIXME
344         ed = PRVM_PROG_TO_EDICT(PRVM_allglobaledict(self));
345         PRVM_ED_Print(ed, NULL);
346         PRVM_ED_Free (ed);
347         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);
348 }
349
350 /*
351 =================
352 VM_print
353
354 print to console
355
356 print(...[string])
357 =================
358 */
359 void VM_print (void)
360 {
361         char string[VM_STRINGTEMP_LENGTH];
362
363         VM_VarString(0, string, sizeof(string));
364         Con_Print(string);
365 }
366
367 /*
368 =================
369 VM_bprint
370
371 broadcast print to everyone on server
372
373 bprint(...[string])
374 =================
375 */
376 void VM_bprint (void)
377 {
378         char string[VM_STRINGTEMP_LENGTH];
379
380         if(!sv.active)
381         {
382                 VM_Warning("VM_bprint: game is not server(%s) !\n", PRVM_NAME);
383                 return;
384         }
385
386         VM_VarString(0, string, sizeof(string));
387         SV_BroadcastPrint(string);
388 }
389
390 /*
391 =================
392 VM_sprint (menu & client but only if server.active == true)
393
394 single print to a specific client
395
396 sprint(float clientnum,...[string])
397 =================
398 */
399 void VM_sprint (void)
400 {
401         client_t        *client;
402         int                     clientnum;
403         char string[VM_STRINGTEMP_LENGTH];
404
405         VM_SAFEPARMCOUNTRANGE(1, 8, VM_sprint);
406
407         //find client for this entity
408         clientnum = (int)PRVM_G_FLOAT(OFS_PARM0);
409         if (!sv.active  || clientnum < 0 || clientnum >= svs.maxclients || !svs.clients[clientnum].active)
410         {
411                 VM_Warning("VM_sprint: %s: invalid client or server is not active !\n", PRVM_NAME);
412                 return;
413         }
414
415         client = svs.clients + clientnum;
416         if (!client->netconnection)
417                 return;
418
419         VM_VarString(1, string, sizeof(string));
420         MSG_WriteChar(&client->netconnection->message,svc_print);
421         MSG_WriteString(&client->netconnection->message, string);
422 }
423
424 /*
425 =================
426 VM_centerprint
427
428 single print to the screen
429
430 centerprint(value)
431 =================
432 */
433 void VM_centerprint (void)
434 {
435         char string[VM_STRINGTEMP_LENGTH];
436
437         VM_SAFEPARMCOUNTRANGE(1, 8, VM_centerprint);
438         VM_VarString(0, string, sizeof(string));
439         SCR_CenterPrint(string);
440 }
441
442 /*
443 =================
444 VM_normalize
445
446 vector normalize(vector)
447 =================
448 */
449 void VM_normalize (void)
450 {
451         float   *value1;
452         vec3_t  newvalue;
453         double  f;
454
455         VM_SAFEPARMCOUNT(1,VM_normalize);
456
457         value1 = PRVM_G_VECTOR(OFS_PARM0);
458
459         f = VectorLength2(value1);
460         if (f)
461         {
462                 f = 1.0 / sqrt(f);
463                 VectorScale(value1, f, newvalue);
464         }
465         else
466                 VectorClear(newvalue);
467
468         VectorCopy (newvalue, PRVM_G_VECTOR(OFS_RETURN));
469 }
470
471 /*
472 =================
473 VM_vlen
474
475 scalar vlen(vector)
476 =================
477 */
478 void VM_vlen (void)
479 {
480         VM_SAFEPARMCOUNT(1,VM_vlen);
481         PRVM_G_FLOAT(OFS_RETURN) = VectorLength(PRVM_G_VECTOR(OFS_PARM0));
482 }
483
484 /*
485 =================
486 VM_vectoyaw
487
488 float vectoyaw(vector)
489 =================
490 */
491 void VM_vectoyaw (void)
492 {
493         float   *value1;
494         float   yaw;
495
496         VM_SAFEPARMCOUNT(1,VM_vectoyaw);
497
498         value1 = PRVM_G_VECTOR(OFS_PARM0);
499
500         if (value1[1] == 0 && value1[0] == 0)
501                 yaw = 0;
502         else
503         {
504                 yaw = (int) (atan2(value1[1], value1[0]) * 180 / M_PI);
505                 if (yaw < 0)
506                         yaw += 360;
507         }
508
509         PRVM_G_FLOAT(OFS_RETURN) = yaw;
510 }
511
512
513 /*
514 =================
515 VM_vectoangles
516
517 vector vectoangles(vector[, vector])
518 =================
519 */
520 void VM_vectoangles (void)
521 {
522         VM_SAFEPARMCOUNTRANGE(1, 2,VM_vectoangles);
523
524         AnglesFromVectors(PRVM_G_VECTOR(OFS_RETURN), PRVM_G_VECTOR(OFS_PARM0), prog->argc >= 2 ? PRVM_G_VECTOR(OFS_PARM1) : NULL, true);
525 }
526
527 /*
528 =================
529 VM_random
530
531 Returns a number from 0<= num < 1
532
533 float random()
534 =================
535 */
536 void VM_random (void)
537 {
538         VM_SAFEPARMCOUNT(0,VM_random);
539
540         PRVM_G_FLOAT(OFS_RETURN) = lhrandom(0, 1);
541 }
542
543 /*
544 =========
545 VM_localsound
546
547 localsound(string sample)
548 =========
549 */
550 void VM_localsound(void)
551 {
552         const char *s;
553
554         VM_SAFEPARMCOUNT(1,VM_localsound);
555
556         s = PRVM_G_STRING(OFS_PARM0);
557
558         if(!S_LocalSound (s))
559         {
560                 PRVM_G_FLOAT(OFS_RETURN) = -4;
561                 VM_Warning("VM_localsound: Failed to play %s for %s !\n", s, PRVM_NAME);
562                 return;
563         }
564
565         PRVM_G_FLOAT(OFS_RETURN) = 1;
566 }
567
568 /*
569 =================
570 VM_break
571
572 break()
573 =================
574 */
575 void VM_break (void)
576 {
577         PRVM_ERROR ("%s: break statement", PRVM_NAME);
578 }
579
580 //============================================================================
581
582 /*
583 =================
584 VM_localcmd
585
586 Sends text over to the client's execution buffer
587
588 [localcmd (string, ...) or]
589 cmd (string, ...)
590 =================
591 */
592 void VM_localcmd (void)
593 {
594         char string[VM_STRINGTEMP_LENGTH];
595         VM_SAFEPARMCOUNTRANGE(1, 8, VM_localcmd);
596         VM_VarString(0, string, sizeof(string));
597         Cbuf_AddText(string);
598 }
599
600 static qboolean PRVM_Cvar_ReadOk(const char *string)
601 {
602         cvar_t *cvar;
603         cvar = Cvar_FindVar(string);
604         return ((cvar) && ((cvar->flags & CVAR_PRIVATE) == 0));
605 }
606
607 /*
608 =================
609 VM_cvar
610
611 float cvar (string)
612 =================
613 */
614 void VM_cvar (void)
615 {
616         char string[VM_STRINGTEMP_LENGTH];
617         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar);
618         VM_VarString(0, string, sizeof(string));
619         VM_CheckEmptyString(string);
620         PRVM_G_FLOAT(OFS_RETURN) = PRVM_Cvar_ReadOk(string) ? Cvar_VariableValue(string) : 0;
621 }
622
623 /*
624 =================
625 VM_cvar
626
627 float cvar_type (string)
628 float CVAR_TYPEFLAG_EXISTS = 1;
629 float CVAR_TYPEFLAG_SAVED = 2;
630 float CVAR_TYPEFLAG_PRIVATE = 4;
631 float CVAR_TYPEFLAG_ENGINE = 8;
632 float CVAR_TYPEFLAG_HASDESCRIPTION = 16;
633 float CVAR_TYPEFLAG_READONLY = 32;
634 =================
635 */
636 void VM_cvar_type (void)
637 {
638         char string[VM_STRINGTEMP_LENGTH];
639         cvar_t *cvar;
640         int ret;
641
642         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar);
643         VM_VarString(0, string, sizeof(string));
644         VM_CheckEmptyString(string);
645         cvar = Cvar_FindVar(string);
646
647
648         if(!cvar)
649         {
650                 PRVM_G_FLOAT(OFS_RETURN) = 0;
651                 return; // CVAR_TYPE_NONE
652         }
653
654         ret = 1; // CVAR_EXISTS
655         if(cvar->flags & CVAR_SAVE)
656                 ret |= 2; // CVAR_TYPE_SAVED
657         if(cvar->flags & CVAR_PRIVATE)
658                 ret |= 4; // CVAR_TYPE_PRIVATE
659         if(!(cvar->flags & CVAR_ALLOCATED))
660                 ret |= 8; // CVAR_TYPE_ENGINE
661         if(cvar->description != cvar_dummy_description)
662                 ret |= 16; // CVAR_TYPE_HASDESCRIPTION
663         if(cvar->flags & CVAR_READONLY)
664                 ret |= 32; // CVAR_TYPE_READONLY
665         
666         PRVM_G_FLOAT(OFS_RETURN) = ret;
667 }
668
669 /*
670 =================
671 VM_cvar_string
672
673 const string    VM_cvar_string (string, ...)
674 =================
675 */
676 void VM_cvar_string(void)
677 {
678         char string[VM_STRINGTEMP_LENGTH];
679         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_string);
680         VM_VarString(0, string, sizeof(string));
681         VM_CheckEmptyString(string);
682         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(PRVM_Cvar_ReadOk(string) ? Cvar_VariableString(string) : "");
683 }
684
685
686 /*
687 ========================
688 VM_cvar_defstring
689
690 const string    VM_cvar_defstring (string, ...)
691 ========================
692 */
693 void VM_cvar_defstring (void)
694 {
695         char string[VM_STRINGTEMP_LENGTH];
696         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_defstring);
697         VM_VarString(0, string, sizeof(string));
698         VM_CheckEmptyString(string);
699         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(Cvar_VariableDefString(string));
700 }
701
702 /*
703 ========================
704 VM_cvar_defstring
705
706 const string    VM_cvar_description (string, ...)
707 ========================
708 */
709 void VM_cvar_description (void)
710 {
711         char string[VM_STRINGTEMP_LENGTH];
712         VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_description);
713         VM_VarString(0, string, sizeof(string));
714         VM_CheckEmptyString(string);
715         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(Cvar_VariableDescription(string));
716 }
717 /*
718 =================
719 VM_cvar_set
720
721 void cvar_set (string,string, ...)
722 =================
723 */
724 void VM_cvar_set (void)
725 {
726         const char *name;
727         char string[VM_STRINGTEMP_LENGTH];
728         VM_SAFEPARMCOUNTRANGE(2,8,VM_cvar_set);
729         VM_VarString(1, string, sizeof(string));
730         name = PRVM_G_STRING(OFS_PARM0);
731         VM_CheckEmptyString(name);
732         Cvar_Set(name, string);
733 }
734
735 /*
736 =========
737 VM_dprint
738
739 dprint(...[string])
740 =========
741 */
742 void VM_dprint (void)
743 {
744         char string[VM_STRINGTEMP_LENGTH];
745         VM_SAFEPARMCOUNTRANGE(1, 8, VM_dprint);
746         VM_VarString(0, string, sizeof(string));
747 #if 1
748         Con_DPrintf("%s", string);
749 #else
750         Con_DPrintf("%s: %s", PRVM_NAME, string);
751 #endif
752 }
753
754 /*
755 =========
756 VM_ftos
757
758 string  ftos(float)
759 =========
760 */
761
762 void VM_ftos (void)
763 {
764         float v;
765         char s[128];
766
767         VM_SAFEPARMCOUNT(1, VM_ftos);
768
769         v = PRVM_G_FLOAT(OFS_PARM0);
770
771         if ((float)((int)v) == v)
772                 dpsnprintf(s, sizeof(s), "%i", (int)v);
773         else
774                 dpsnprintf(s, sizeof(s), "%f", v);
775         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(s);
776 }
777
778 /*
779 =========
780 VM_fabs
781
782 float   fabs(float)
783 =========
784 */
785
786 void VM_fabs (void)
787 {
788         float   v;
789
790         VM_SAFEPARMCOUNT(1,VM_fabs);
791
792         v = PRVM_G_FLOAT(OFS_PARM0);
793         PRVM_G_FLOAT(OFS_RETURN) = fabs(v);
794 }
795
796 /*
797 =========
798 VM_vtos
799
800 string  vtos(vector)
801 =========
802 */
803
804 void VM_vtos (void)
805 {
806         char s[512];
807
808         VM_SAFEPARMCOUNT(1,VM_vtos);
809
810         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]);
811         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(s);
812 }
813
814 /*
815 =========
816 VM_etos
817
818 string  etos(entity)
819 =========
820 */
821
822 void VM_etos (void)
823 {
824         char s[128];
825
826         VM_SAFEPARMCOUNT(1, VM_etos);
827
828         dpsnprintf (s, sizeof(s), "entity %i", PRVM_G_EDICTNUM(OFS_PARM0));
829         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(s);
830 }
831
832 /*
833 =========
834 VM_stof
835
836 float stof(...[string])
837 =========
838 */
839 void VM_stof(void)
840 {
841         char string[VM_STRINGTEMP_LENGTH];
842         VM_SAFEPARMCOUNTRANGE(1, 8, VM_stof);
843         VM_VarString(0, string, sizeof(string));
844         PRVM_G_FLOAT(OFS_RETURN) = atof(string);
845 }
846
847 /*
848 ========================
849 VM_itof
850
851 float itof(intt ent)
852 ========================
853 */
854 void VM_itof(void)
855 {
856         VM_SAFEPARMCOUNT(1, VM_itof);
857         PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
858 }
859
860 /*
861 ========================
862 VM_ftoe
863
864 entity ftoe(float num)
865 ========================
866 */
867 void VM_ftoe(void)
868 {
869         int ent;
870         VM_SAFEPARMCOUNT(1, VM_ftoe);
871
872         ent = (int)PRVM_G_FLOAT(OFS_PARM0);
873         if (ent < 0 || ent >= prog->max_edicts || PRVM_PROG_TO_EDICT(ent)->priv.required->free)
874                 ent = 0; // return world instead of a free or invalid entity
875
876         PRVM_G_INT(OFS_RETURN) = ent;
877 }
878
879 /*
880 ========================
881 VM_etof
882
883 float etof(entity ent)
884 ========================
885 */
886 void VM_etof(void)
887 {
888         VM_SAFEPARMCOUNT(1, VM_etof);
889         PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_EDICTNUM(OFS_PARM0);
890 }
891
892 /*
893 =========
894 VM_strftime
895
896 string strftime(float uselocaltime, string[, string ...])
897 =========
898 */
899 void VM_strftime(void)
900 {
901         time_t t;
902 #if _MSC_VER >= 1400
903         struct tm tm;
904         int tmresult;
905 #else
906         struct tm *tm;
907 #endif
908         char fmt[VM_STRINGTEMP_LENGTH];
909         char result[VM_STRINGTEMP_LENGTH];
910         VM_SAFEPARMCOUNTRANGE(2, 8, VM_strftime);
911         VM_VarString(1, fmt, sizeof(fmt));
912         t = time(NULL);
913 #if _MSC_VER >= 1400
914         if (PRVM_G_FLOAT(OFS_PARM0))
915                 tmresult = localtime_s(&tm, &t);
916         else
917                 tmresult = gmtime_s(&tm, &t);
918         if (!tmresult)
919 #else
920         if (PRVM_G_FLOAT(OFS_PARM0))
921                 tm = localtime(&t);
922         else
923                 tm = gmtime(&t);
924         if (!tm)
925 #endif
926         {
927                 PRVM_G_INT(OFS_RETURN) = 0;
928                 return;
929         }
930 #if _MSC_VER >= 1400
931         strftime(result, sizeof(result), fmt, &tm);
932 #else
933         strftime(result, sizeof(result), fmt, tm);
934 #endif
935         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(result);
936 }
937
938 /*
939 =========
940 VM_spawn
941
942 entity spawn()
943 =========
944 */
945
946 void VM_spawn (void)
947 {
948         prvm_edict_t    *ed;
949         VM_SAFEPARMCOUNT(0, VM_spawn);
950         prog->xfunction->builtinsprofile += 20;
951         ed = PRVM_ED_Alloc();
952         VM_RETURN_EDICT(ed);
953 }
954
955 /*
956 =========
957 VM_remove
958
959 remove(entity e)
960 =========
961 */
962
963 void VM_remove (void)
964 {
965         prvm_edict_t    *ed;
966         prog->xfunction->builtinsprofile += 20;
967
968         VM_SAFEPARMCOUNT(1, VM_remove);
969
970         ed = PRVM_G_EDICT(OFS_PARM0);
971         if( PRVM_NUM_FOR_EDICT(ed) <= prog->reserved_edicts )
972         {
973                 if (developer.integer > 0)
974                         VM_Warning( "VM_remove: tried to remove the null entity or a reserved entity!\n" );
975         }
976         else if( ed->priv.required->free )
977         {
978                 if (developer.integer > 0)
979                         VM_Warning( "VM_remove: tried to remove an already freed entity!\n" );
980         }
981         else
982                 PRVM_ED_Free (ed);
983 }
984
985 /*
986 =========
987 VM_find
988
989 entity  find(entity start, .string field, string match)
990 =========
991 */
992
993 void VM_find (void)
994 {
995         int             e;
996         int             f;
997         const char      *s, *t;
998         prvm_edict_t    *ed;
999
1000         VM_SAFEPARMCOUNT(3,VM_find);
1001
1002         e = PRVM_G_EDICTNUM(OFS_PARM0);
1003         f = PRVM_G_INT(OFS_PARM1);
1004         s = PRVM_G_STRING(OFS_PARM2);
1005
1006         // LordHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
1007         // expects it to find all the monsters, so we must be careful to support
1008         // searching for ""
1009
1010         for (e++ ; e < prog->num_edicts ; e++)
1011         {
1012                 prog->xfunction->builtinsprofile++;
1013                 ed = PRVM_EDICT_NUM(e);
1014                 if (ed->priv.required->free)
1015                         continue;
1016                 t = PRVM_E_STRING(ed,f);
1017                 if (!t)
1018                         t = "";
1019                 if (!strcmp(t,s))
1020                 {
1021                         VM_RETURN_EDICT(ed);
1022                         return;
1023                 }
1024         }
1025
1026         VM_RETURN_EDICT(prog->edicts);
1027 }
1028
1029 /*
1030 =========
1031 VM_findfloat
1032
1033   entity        findfloat(entity start, .float field, float match)
1034   entity        findentity(entity start, .entity field, entity match)
1035 =========
1036 */
1037 // LordHavoc: added this for searching float, int, and entity reference fields
1038 void VM_findfloat (void)
1039 {
1040         int             e;
1041         int             f;
1042         float   s;
1043         prvm_edict_t    *ed;
1044
1045         VM_SAFEPARMCOUNT(3,VM_findfloat);
1046
1047         e = PRVM_G_EDICTNUM(OFS_PARM0);
1048         f = PRVM_G_INT(OFS_PARM1);
1049         s = PRVM_G_FLOAT(OFS_PARM2);
1050
1051         for (e++ ; e < prog->num_edicts ; e++)
1052         {
1053                 prog->xfunction->builtinsprofile++;
1054                 ed = PRVM_EDICT_NUM(e);
1055                 if (ed->priv.required->free)
1056                         continue;
1057                 if (PRVM_E_FLOAT(ed,f) == s)
1058                 {
1059                         VM_RETURN_EDICT(ed);
1060                         return;
1061                 }
1062         }
1063
1064         VM_RETURN_EDICT(prog->edicts);
1065 }
1066
1067 /*
1068 =========
1069 VM_findchain
1070
1071 entity  findchain(.string field, string match)
1072 =========
1073 */
1074 // chained search for strings in entity fields
1075 // entity(.string field, string match) findchain = #402;
1076 void VM_findchain (void)
1077 {
1078         int             i;
1079         int             f;
1080         const char      *s, *t;
1081         prvm_edict_t    *ent, *chain;
1082         int chainfield;
1083
1084         VM_SAFEPARMCOUNTRANGE(2,3,VM_findchain);
1085
1086         if(prog->argc == 3)
1087                 chainfield = PRVM_G_INT(OFS_PARM2);
1088         else
1089                 chainfield = prog->fieldoffsets.chain;
1090         if (chainfield < 0)
1091                 PRVM_ERROR("VM_findchain: %s doesnt have the specified chain field !", PRVM_NAME);
1092
1093         chain = prog->edicts;
1094
1095         f = PRVM_G_INT(OFS_PARM0);
1096         s = PRVM_G_STRING(OFS_PARM1);
1097
1098         // LordHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
1099         // expects it to find all the monsters, so we must be careful to support
1100         // searching for ""
1101
1102         ent = PRVM_NEXT_EDICT(prog->edicts);
1103         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1104         {
1105                 prog->xfunction->builtinsprofile++;
1106                 if (ent->priv.required->free)
1107                         continue;
1108                 t = PRVM_E_STRING(ent,f);
1109                 if (!t)
1110                         t = "";
1111                 if (strcmp(t,s))
1112                         continue;
1113
1114                 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_NUM_FOR_EDICT(chain);
1115                 chain = ent;
1116         }
1117
1118         VM_RETURN_EDICT(chain);
1119 }
1120
1121 /*
1122 =========
1123 VM_findchainfloat
1124
1125 entity  findchainfloat(.string field, float match)
1126 entity  findchainentity(.string field, entity match)
1127 =========
1128 */
1129 // LordHavoc: chained search for float, int, and entity reference fields
1130 // entity(.string field, float match) findchainfloat = #403;
1131 void VM_findchainfloat (void)
1132 {
1133         int             i;
1134         int             f;
1135         float   s;
1136         prvm_edict_t    *ent, *chain;
1137         int chainfield;
1138
1139         VM_SAFEPARMCOUNTRANGE(2, 3, VM_findchainfloat);
1140
1141         if(prog->argc == 3)
1142                 chainfield = PRVM_G_INT(OFS_PARM2);
1143         else
1144                 chainfield = prog->fieldoffsets.chain;
1145         if (chainfield < 0)
1146                 PRVM_ERROR("VM_findchain: %s doesnt have the specified chain field !", PRVM_NAME);
1147
1148         chain = (prvm_edict_t *)prog->edicts;
1149
1150         f = PRVM_G_INT(OFS_PARM0);
1151         s = PRVM_G_FLOAT(OFS_PARM1);
1152
1153         ent = PRVM_NEXT_EDICT(prog->edicts);
1154         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1155         {
1156                 prog->xfunction->builtinsprofile++;
1157                 if (ent->priv.required->free)
1158                         continue;
1159                 if (PRVM_E_FLOAT(ent,f) != s)
1160                         continue;
1161
1162                 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_EDICT_TO_PROG(chain);
1163                 chain = ent;
1164         }
1165
1166         VM_RETURN_EDICT(chain);
1167 }
1168
1169 /*
1170 ========================
1171 VM_findflags
1172
1173 entity  findflags(entity start, .float field, float match)
1174 ========================
1175 */
1176 // LordHavoc: search for flags in float fields
1177 void VM_findflags (void)
1178 {
1179         int             e;
1180         int             f;
1181         int             s;
1182         prvm_edict_t    *ed;
1183
1184         VM_SAFEPARMCOUNT(3, VM_findflags);
1185
1186
1187         e = PRVM_G_EDICTNUM(OFS_PARM0);
1188         f = PRVM_G_INT(OFS_PARM1);
1189         s = (int)PRVM_G_FLOAT(OFS_PARM2);
1190
1191         for (e++ ; e < prog->num_edicts ; e++)
1192         {
1193                 prog->xfunction->builtinsprofile++;
1194                 ed = PRVM_EDICT_NUM(e);
1195                 if (ed->priv.required->free)
1196                         continue;
1197                 if (!PRVM_E_FLOAT(ed,f))
1198                         continue;
1199                 if ((int)PRVM_E_FLOAT(ed,f) & s)
1200                 {
1201                         VM_RETURN_EDICT(ed);
1202                         return;
1203                 }
1204         }
1205
1206         VM_RETURN_EDICT(prog->edicts);
1207 }
1208
1209 /*
1210 ========================
1211 VM_findchainflags
1212
1213 entity  findchainflags(.float field, float match)
1214 ========================
1215 */
1216 // LordHavoc: chained search for flags in float fields
1217 void VM_findchainflags (void)
1218 {
1219         int             i;
1220         int             f;
1221         int             s;
1222         prvm_edict_t    *ent, *chain;
1223         int chainfield;
1224
1225         VM_SAFEPARMCOUNTRANGE(2, 3, VM_findchainflags);
1226
1227         if(prog->argc == 3)
1228                 chainfield = PRVM_G_INT(OFS_PARM2);
1229         else
1230                 chainfield = prog->fieldoffsets.chain;
1231         if (chainfield < 0)
1232                 PRVM_ERROR("VM_findchain: %s doesnt have the specified chain field !", PRVM_NAME);
1233
1234         chain = (prvm_edict_t *)prog->edicts;
1235
1236         f = PRVM_G_INT(OFS_PARM0);
1237         s = (int)PRVM_G_FLOAT(OFS_PARM1);
1238
1239         ent = PRVM_NEXT_EDICT(prog->edicts);
1240         for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1241         {
1242                 prog->xfunction->builtinsprofile++;
1243                 if (ent->priv.required->free)
1244                         continue;
1245                 if (!PRVM_E_FLOAT(ent,f))
1246                         continue;
1247                 if (!((int)PRVM_E_FLOAT(ent,f) & s))
1248                         continue;
1249
1250                 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_EDICT_TO_PROG(chain);
1251                 chain = ent;
1252         }
1253
1254         VM_RETURN_EDICT(chain);
1255 }
1256
1257 /*
1258 =========
1259 VM_precache_sound
1260
1261 string  precache_sound (string sample)
1262 =========
1263 */
1264 void VM_precache_sound (void)
1265 {
1266         const char *s;
1267
1268         VM_SAFEPARMCOUNT(1, VM_precache_sound);
1269
1270         s = PRVM_G_STRING(OFS_PARM0);
1271         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
1272         //VM_CheckEmptyString(s);
1273
1274         if(snd_initialized.integer && !S_PrecacheSound(s, true, true))
1275         {
1276                 VM_Warning("VM_precache_sound: Failed to load %s for %s\n", s, PRVM_NAME);
1277                 return;
1278         }
1279 }
1280
1281 /*
1282 =================
1283 VM_precache_file
1284
1285 returns the same string as output
1286
1287 does nothing, only used by qcc to build .pak archives
1288 =================
1289 */
1290 void VM_precache_file (void)
1291 {
1292         VM_SAFEPARMCOUNT(1,VM_precache_file);
1293         // precache_file is only used to copy files with qcc, it does nothing
1294         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
1295 }
1296
1297 /*
1298 =========
1299 VM_coredump
1300
1301 coredump()
1302 =========
1303 */
1304 void VM_coredump (void)
1305 {
1306         VM_SAFEPARMCOUNT(0,VM_coredump);
1307
1308         Cbuf_AddText("prvm_edicts ");
1309         Cbuf_AddText(PRVM_NAME);
1310         Cbuf_AddText("\n");
1311 }
1312
1313 /*
1314 =========
1315 VM_stackdump
1316
1317 stackdump()
1318 =========
1319 */
1320 void PRVM_StackTrace(void);
1321 void VM_stackdump (void)
1322 {
1323         VM_SAFEPARMCOUNT(0, VM_stackdump);
1324
1325         PRVM_StackTrace();
1326 }
1327
1328 /*
1329 =========
1330 VM_crash
1331
1332 crash()
1333 =========
1334 */
1335
1336 void VM_crash(void)
1337 {
1338         VM_SAFEPARMCOUNT(0, VM_crash);
1339
1340         PRVM_ERROR("Crash called by %s",PRVM_NAME);
1341 }
1342
1343 /*
1344 =========
1345 VM_traceon
1346
1347 traceon()
1348 =========
1349 */
1350 void VM_traceon (void)
1351 {
1352         VM_SAFEPARMCOUNT(0,VM_traceon);
1353
1354         prog->trace = true;
1355 }
1356
1357 /*
1358 =========
1359 VM_traceoff
1360
1361 traceoff()
1362 =========
1363 */
1364 void VM_traceoff (void)
1365 {
1366         VM_SAFEPARMCOUNT(0,VM_traceoff);
1367
1368         prog->trace = false;
1369 }
1370
1371 /*
1372 =========
1373 VM_eprint
1374
1375 eprint(entity e)
1376 =========
1377 */
1378 void VM_eprint (void)
1379 {
1380         VM_SAFEPARMCOUNT(1,VM_eprint);
1381
1382         PRVM_ED_PrintNum (PRVM_G_EDICTNUM(OFS_PARM0), NULL);
1383 }
1384
1385 /*
1386 =========
1387 VM_rint
1388
1389 float   rint(float)
1390 =========
1391 */
1392 void VM_rint (void)
1393 {
1394         float f;
1395         VM_SAFEPARMCOUNT(1,VM_rint);
1396
1397         f = PRVM_G_FLOAT(OFS_PARM0);
1398         if (f > 0)
1399                 PRVM_G_FLOAT(OFS_RETURN) = floor(f + 0.5);
1400         else
1401                 PRVM_G_FLOAT(OFS_RETURN) = ceil(f - 0.5);
1402 }
1403
1404 /*
1405 =========
1406 VM_floor
1407
1408 float   floor(float)
1409 =========
1410 */
1411 void VM_floor (void)
1412 {
1413         VM_SAFEPARMCOUNT(1,VM_floor);
1414
1415         PRVM_G_FLOAT(OFS_RETURN) = floor(PRVM_G_FLOAT(OFS_PARM0));
1416 }
1417
1418 /*
1419 =========
1420 VM_ceil
1421
1422 float   ceil(float)
1423 =========
1424 */
1425 void VM_ceil (void)
1426 {
1427         VM_SAFEPARMCOUNT(1,VM_ceil);
1428
1429         PRVM_G_FLOAT(OFS_RETURN) = ceil(PRVM_G_FLOAT(OFS_PARM0));
1430 }
1431
1432
1433 /*
1434 =============
1435 VM_nextent
1436
1437 entity  nextent(entity)
1438 =============
1439 */
1440 void VM_nextent (void)
1441 {
1442         int             i;
1443         prvm_edict_t    *ent;
1444
1445         VM_SAFEPARMCOUNT(1, VM_nextent);
1446
1447         i = PRVM_G_EDICTNUM(OFS_PARM0);
1448         while (1)
1449         {
1450                 prog->xfunction->builtinsprofile++;
1451                 i++;
1452                 if (i == prog->num_edicts)
1453                 {
1454                         VM_RETURN_EDICT(prog->edicts);
1455                         return;
1456                 }
1457                 ent = PRVM_EDICT_NUM(i);
1458                 if (!ent->priv.required->free)
1459                 {
1460                         VM_RETURN_EDICT(ent);
1461                         return;
1462                 }
1463         }
1464 }
1465
1466 //=============================================================================
1467
1468 /*
1469 ==============
1470 VM_changelevel
1471 server and menu
1472
1473 changelevel(string map)
1474 ==============
1475 */
1476 void VM_changelevel (void)
1477 {
1478         VM_SAFEPARMCOUNT(1, VM_changelevel);
1479
1480         if(!sv.active)
1481         {
1482                 VM_Warning("VM_changelevel: game is not server (%s)\n", PRVM_NAME);
1483                 return;
1484         }
1485
1486 // make sure we don't issue two changelevels
1487         if (svs.changelevel_issued)
1488                 return;
1489         svs.changelevel_issued = true;
1490
1491         Cbuf_AddText (va("changelevel %s\n",PRVM_G_STRING(OFS_PARM0)));
1492 }
1493
1494 /*
1495 =========
1496 VM_sin
1497
1498 float   sin(float)
1499 =========
1500 */
1501 void VM_sin (void)
1502 {
1503         VM_SAFEPARMCOUNT(1,VM_sin);
1504         PRVM_G_FLOAT(OFS_RETURN) = sin(PRVM_G_FLOAT(OFS_PARM0));
1505 }
1506
1507 /*
1508 =========
1509 VM_cos
1510 float   cos(float)
1511 =========
1512 */
1513 void VM_cos (void)
1514 {
1515         VM_SAFEPARMCOUNT(1,VM_cos);
1516         PRVM_G_FLOAT(OFS_RETURN) = cos(PRVM_G_FLOAT(OFS_PARM0));
1517 }
1518
1519 /*
1520 =========
1521 VM_sqrt
1522
1523 float   sqrt(float)
1524 =========
1525 */
1526 void VM_sqrt (void)
1527 {
1528         VM_SAFEPARMCOUNT(1,VM_sqrt);
1529         PRVM_G_FLOAT(OFS_RETURN) = sqrt(PRVM_G_FLOAT(OFS_PARM0));
1530 }
1531
1532 /*
1533 =========
1534 VM_asin
1535
1536 float   asin(float)
1537 =========
1538 */
1539 void VM_asin (void)
1540 {
1541         VM_SAFEPARMCOUNT(1,VM_asin);
1542         PRVM_G_FLOAT(OFS_RETURN) = asin(PRVM_G_FLOAT(OFS_PARM0));
1543 }
1544
1545 /*
1546 =========
1547 VM_acos
1548 float   acos(float)
1549 =========
1550 */
1551 void VM_acos (void)
1552 {
1553         VM_SAFEPARMCOUNT(1,VM_acos);
1554         PRVM_G_FLOAT(OFS_RETURN) = acos(PRVM_G_FLOAT(OFS_PARM0));
1555 }
1556
1557 /*
1558 =========
1559 VM_atan
1560 float   atan(float)
1561 =========
1562 */
1563 void VM_atan (void)
1564 {
1565         VM_SAFEPARMCOUNT(1,VM_atan);
1566         PRVM_G_FLOAT(OFS_RETURN) = atan(PRVM_G_FLOAT(OFS_PARM0));
1567 }
1568
1569 /*
1570 =========
1571 VM_atan2
1572 float   atan2(float,float)
1573 =========
1574 */
1575 void VM_atan2 (void)
1576 {
1577         VM_SAFEPARMCOUNT(2,VM_atan2);
1578         PRVM_G_FLOAT(OFS_RETURN) = atan2(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1579 }
1580
1581 /*
1582 =========
1583 VM_tan
1584 float   tan(float)
1585 =========
1586 */
1587 void VM_tan (void)
1588 {
1589         VM_SAFEPARMCOUNT(1,VM_tan);
1590         PRVM_G_FLOAT(OFS_RETURN) = tan(PRVM_G_FLOAT(OFS_PARM0));
1591 }
1592
1593 /*
1594 =================
1595 VM_randomvec
1596
1597 Returns a vector of length < 1 and > 0
1598
1599 vector randomvec()
1600 =================
1601 */
1602 void VM_randomvec (void)
1603 {
1604         vec3_t          temp;
1605         //float         length;
1606
1607         VM_SAFEPARMCOUNT(0, VM_randomvec);
1608
1609         //// WTF ??
1610         do
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         }
1616         while (DotProduct(temp, temp) >= 1);
1617         VectorCopy (temp, PRVM_G_VECTOR(OFS_RETURN));
1618
1619         /*
1620         temp[0] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1621         temp[1] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1622         temp[2] = (rand()&32767) * (2.0 / 32767.0) - 1.0;
1623         // length returned always > 0
1624         length = (rand()&32766 + 1) * (1.0 / 32767.0) / VectorLength(temp);
1625         VectorScale(temp,length, temp);*/
1626         //VectorCopy(temp, PRVM_G_VECTOR(OFS_RETURN));
1627 }
1628
1629 //=============================================================================
1630
1631 /*
1632 =========
1633 VM_registercvar
1634
1635 float   registercvar (string name, string value[, float flags])
1636 =========
1637 */
1638 void VM_registercvar (void)
1639 {
1640         const char *name, *value;
1641         int     flags;
1642
1643         VM_SAFEPARMCOUNTRANGE(2, 3, VM_registercvar);
1644
1645         name = PRVM_G_STRING(OFS_PARM0);
1646         value = PRVM_G_STRING(OFS_PARM1);
1647         flags = prog->argc >= 3 ? (int)PRVM_G_FLOAT(OFS_PARM2) : 0;
1648         PRVM_G_FLOAT(OFS_RETURN) = 0;
1649
1650         if(flags > CVAR_MAXFLAGSVAL)
1651                 return;
1652
1653 // first check to see if it has already been defined
1654         if (Cvar_FindVar (name))
1655                 return;
1656
1657 // check for overlap with a command
1658         if (Cmd_Exists (name))
1659         {
1660                 VM_Warning("VM_registercvar: %s is a command\n", name);
1661                 return;
1662         }
1663
1664         Cvar_Get(name, value, flags, NULL);
1665
1666         PRVM_G_FLOAT(OFS_RETURN) = 1; // success
1667 }
1668
1669
1670 /*
1671 =================
1672 VM_min
1673
1674 returns the minimum of two supplied floats
1675
1676 float min(float a, float b, ...[float])
1677 =================
1678 */
1679 void VM_min (void)
1680 {
1681         VM_SAFEPARMCOUNTRANGE(2, 8, VM_min);
1682         // LordHavoc: 3+ argument enhancement suggested by FrikaC
1683         if (prog->argc >= 3)
1684         {
1685                 int i;
1686                 float f = PRVM_G_FLOAT(OFS_PARM0);
1687                 for (i = 1;i < prog->argc;i++)
1688                         if (f > PRVM_G_FLOAT((OFS_PARM0+i*3)))
1689                                 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1690                 PRVM_G_FLOAT(OFS_RETURN) = f;
1691         }
1692         else
1693                 PRVM_G_FLOAT(OFS_RETURN) = min(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1694 }
1695
1696 /*
1697 =================
1698 VM_max
1699
1700 returns the maximum of two supplied floats
1701
1702 float   max(float a, float b, ...[float])
1703 =================
1704 */
1705 void VM_max (void)
1706 {
1707         VM_SAFEPARMCOUNTRANGE(2, 8, VM_max);
1708         // LordHavoc: 3+ argument enhancement suggested by FrikaC
1709         if (prog->argc >= 3)
1710         {
1711                 int i;
1712                 float f = PRVM_G_FLOAT(OFS_PARM0);
1713                 for (i = 1;i < prog->argc;i++)
1714                         if (f < PRVM_G_FLOAT((OFS_PARM0+i*3)))
1715                                 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1716                 PRVM_G_FLOAT(OFS_RETURN) = f;
1717         }
1718         else
1719                 PRVM_G_FLOAT(OFS_RETURN) = max(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1720 }
1721
1722 /*
1723 =================
1724 VM_bound
1725
1726 returns number bounded by supplied range
1727
1728 float   bound(float min, float value, float max)
1729 =================
1730 */
1731 void VM_bound (void)
1732 {
1733         VM_SAFEPARMCOUNT(3,VM_bound);
1734         PRVM_G_FLOAT(OFS_RETURN) = bound(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1), PRVM_G_FLOAT(OFS_PARM2));
1735 }
1736
1737 /*
1738 =================
1739 VM_pow
1740
1741 returns a raised to power b
1742
1743 float   pow(float a, float b)
1744 =================
1745 */
1746 void VM_pow (void)
1747 {
1748         VM_SAFEPARMCOUNT(2,VM_pow);
1749         PRVM_G_FLOAT(OFS_RETURN) = pow(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1750 }
1751
1752 void VM_log (void)
1753 {
1754         VM_SAFEPARMCOUNT(1,VM_log);
1755         PRVM_G_FLOAT(OFS_RETURN) = log(PRVM_G_FLOAT(OFS_PARM0));
1756 }
1757
1758 void VM_Files_Init(void)
1759 {
1760         int i;
1761         for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1762                 prog->openfiles[i] = NULL;
1763 }
1764
1765 void VM_Files_CloseAll(void)
1766 {
1767         int i;
1768         for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1769         {
1770                 if (prog->openfiles[i])
1771                         FS_Close(prog->openfiles[i]);
1772                 prog->openfiles[i] = NULL;
1773         }
1774 }
1775
1776 static qfile_t *VM_GetFileHandle( int index )
1777 {
1778         if (index < 0 || index >= PRVM_MAX_OPENFILES)
1779         {
1780                 Con_Printf("VM_GetFileHandle: invalid file handle %i used in %s\n", index, PRVM_NAME);
1781                 return NULL;
1782         }
1783         if (prog->openfiles[index] == NULL)
1784         {
1785                 Con_Printf("VM_GetFileHandle: no such file handle %i (or file has been closed) in %s\n", index, PRVM_NAME);
1786                 return NULL;
1787         }
1788         return prog->openfiles[index];
1789 }
1790
1791 /*
1792 =========
1793 VM_fopen
1794
1795 float   fopen(string filename, float mode)
1796 =========
1797 */
1798 // float(string filename, float mode) fopen = #110;
1799 // opens a file inside quake/gamedir/data/ (mode is FILE_READ, FILE_APPEND, or FILE_WRITE),
1800 // returns fhandle >= 0 if successful, or fhandle < 0 if unable to open file for any reason
1801 void VM_fopen(void)
1802 {
1803         int filenum, mode;
1804         const char *modestring, *filename;
1805
1806         VM_SAFEPARMCOUNT(2,VM_fopen);
1807
1808         for (filenum = 0;filenum < PRVM_MAX_OPENFILES;filenum++)
1809                 if (prog->openfiles[filenum] == NULL)
1810                         break;
1811         if (filenum >= PRVM_MAX_OPENFILES)
1812         {
1813                 PRVM_G_FLOAT(OFS_RETURN) = -2;
1814                 VM_Warning("VM_fopen: %s ran out of file handles (%i)\n", PRVM_NAME, PRVM_MAX_OPENFILES);
1815                 return;
1816         }
1817         filename = PRVM_G_STRING(OFS_PARM0);
1818         mode = (int)PRVM_G_FLOAT(OFS_PARM1);
1819         switch(mode)
1820         {
1821         case 0: // FILE_READ
1822                 modestring = "rb";
1823                 prog->openfiles[filenum] = FS_OpenVirtualFile(va("data/%s", filename), false);
1824                 if (prog->openfiles[filenum] == NULL)
1825                         prog->openfiles[filenum] = FS_OpenVirtualFile(va("%s", filename), false);
1826                 break;
1827         case 1: // FILE_APPEND
1828                 modestring = "a";
1829                 prog->openfiles[filenum] = FS_OpenRealFile(va("data/%s", filename), modestring, false);
1830                 break;
1831         case 2: // FILE_WRITE
1832                 modestring = "w";
1833                 prog->openfiles[filenum] = FS_OpenRealFile(va("data/%s", filename), modestring, false);
1834                 break;
1835         default:
1836                 PRVM_G_FLOAT(OFS_RETURN) = -3;
1837                 VM_Warning("VM_fopen: %s: no such mode %i (valid: 0 = read, 1 = append, 2 = write)\n", PRVM_NAME, mode);
1838                 return;
1839         }
1840
1841         if (prog->openfiles[filenum] == NULL)
1842         {
1843                 PRVM_G_FLOAT(OFS_RETURN) = -1;
1844                 if (developer_extra.integer)
1845                         VM_Warning("VM_fopen: %s: %s mode %s failed\n", PRVM_NAME, filename, modestring);
1846         }
1847         else
1848         {
1849                 PRVM_G_FLOAT(OFS_RETURN) = filenum;
1850                 if (developer_extra.integer)
1851                         Con_DPrintf("VM_fopen: %s: %s mode %s opened as #%i\n", PRVM_NAME, filename, modestring, filenum);
1852                 prog->openfiles_origin[filenum] = PRVM_AllocationOrigin();
1853         }
1854 }
1855
1856 /*
1857 =========
1858 VM_fclose
1859
1860 fclose(float fhandle)
1861 =========
1862 */
1863 //void(float fhandle) fclose = #111; // closes a file
1864 void VM_fclose(void)
1865 {
1866         int filenum;
1867
1868         VM_SAFEPARMCOUNT(1,VM_fclose);
1869
1870         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1871         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1872         {
1873                 VM_Warning("VM_fclose: invalid file handle %i used in %s\n", filenum, PRVM_NAME);
1874                 return;
1875         }
1876         if (prog->openfiles[filenum] == NULL)
1877         {
1878                 VM_Warning("VM_fclose: no such file handle %i (or file has been closed) in %s\n", filenum, PRVM_NAME);
1879                 return;
1880         }
1881         FS_Close(prog->openfiles[filenum]);
1882         prog->openfiles[filenum] = NULL;
1883         if(prog->openfiles_origin[filenum])
1884                 PRVM_Free((char *)prog->openfiles_origin[filenum]);
1885         if (developer_extra.integer)
1886                 Con_DPrintf("VM_fclose: %s: #%i closed\n", PRVM_NAME, filenum);
1887 }
1888
1889 /*
1890 =========
1891 VM_fgets
1892
1893 string  fgets(float fhandle)
1894 =========
1895 */
1896 //string(float fhandle) fgets = #112; // reads a line of text from the file and returns as a tempstring
1897 void VM_fgets(void)
1898 {
1899         int c, end;
1900         char string[VM_STRINGTEMP_LENGTH];
1901         int filenum;
1902
1903         VM_SAFEPARMCOUNT(1,VM_fgets);
1904
1905         // set the return value regardless of any possible errors
1906         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
1907
1908         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1909         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1910         {
1911                 VM_Warning("VM_fgets: invalid file handle %i used in %s\n", filenum, PRVM_NAME);
1912                 return;
1913         }
1914         if (prog->openfiles[filenum] == NULL)
1915         {
1916                 VM_Warning("VM_fgets: no such file handle %i (or file has been closed) in %s\n", filenum, PRVM_NAME);
1917                 return;
1918         }
1919         end = 0;
1920         for (;;)
1921         {
1922                 c = FS_Getc(prog->openfiles[filenum]);
1923                 if (c == '\r' || c == '\n' || c < 0)
1924                         break;
1925                 if (end < VM_STRINGTEMP_LENGTH - 1)
1926                         string[end++] = c;
1927         }
1928         string[end] = 0;
1929         // remove \n following \r
1930         if (c == '\r')
1931         {
1932                 c = FS_Getc(prog->openfiles[filenum]);
1933                 if (c != '\n')
1934                         FS_UnGetc(prog->openfiles[filenum], (unsigned char)c);
1935         }
1936         if (developer_extra.integer)
1937                 Con_DPrintf("fgets: %s: %s\n", PRVM_NAME, string);
1938         if (c >= 0 || end)
1939                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
1940 }
1941
1942 /*
1943 =========
1944 VM_fputs
1945
1946 fputs(float fhandle, string s)
1947 =========
1948 */
1949 //void(float fhandle, string s) fputs = #113; // writes a line of text to the end of the file
1950 void VM_fputs(void)
1951 {
1952         int stringlength;
1953         char string[VM_STRINGTEMP_LENGTH];
1954         int filenum;
1955
1956         VM_SAFEPARMCOUNT(2,VM_fputs);
1957
1958         filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1959         if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1960         {
1961                 VM_Warning("VM_fputs: invalid file handle %i used in %s\n", filenum, PRVM_NAME);
1962                 return;
1963         }
1964         if (prog->openfiles[filenum] == NULL)
1965         {
1966                 VM_Warning("VM_fputs: no such file handle %i (or file has been closed) in %s\n", filenum, PRVM_NAME);
1967                 return;
1968         }
1969         VM_VarString(1, string, sizeof(string));
1970         if ((stringlength = (int)strlen(string)))
1971                 FS_Write(prog->openfiles[filenum], string, stringlength);
1972         if (developer_extra.integer)
1973                 Con_DPrintf("fputs: %s: %s\n", PRVM_NAME, string);
1974 }
1975
1976 /*
1977 =========
1978 VM_writetofile
1979
1980         writetofile(float fhandle, entity ent)
1981 =========
1982 */
1983 void VM_writetofile(void)
1984 {
1985         prvm_edict_t * ent;
1986         qfile_t *file;
1987
1988         VM_SAFEPARMCOUNT(2, VM_writetofile);
1989
1990         file = VM_GetFileHandle( (int)PRVM_G_FLOAT(OFS_PARM0) );
1991         if( !file )
1992         {
1993                 VM_Warning("VM_writetofile: invalid or closed file handle\n");
1994                 return;
1995         }
1996
1997         ent = PRVM_G_EDICT(OFS_PARM1);
1998         if(ent->priv.required->free)
1999         {
2000                 VM_Warning("VM_writetofile: %s: entity %i is free !\n", PRVM_NAME, PRVM_NUM_FOR_EDICT(ent));
2001                 return;
2002         }
2003
2004         PRVM_ED_Write (file, ent);
2005 }
2006
2007 // KrimZon - DP_QC_ENTITYDATA
2008 /*
2009 =========
2010 VM_numentityfields
2011
2012 float() numentityfields
2013 Return the number of entity fields - NOT offsets
2014 =========
2015 */
2016 void VM_numentityfields(void)
2017 {
2018         PRVM_G_FLOAT(OFS_RETURN) = prog->numfielddefs;
2019 }
2020
2021 // KrimZon - DP_QC_ENTITYDATA
2022 /*
2023 =========
2024 VM_entityfieldname
2025
2026 string(float fieldnum) entityfieldname
2027 Return name of the specified field as a string, or empty if the field is invalid (warning)
2028 =========
2029 */
2030 void VM_entityfieldname(void)
2031 {
2032         ddef_t *d;
2033         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2034         
2035         if (i < 0 || i >= prog->numfielddefs)
2036         {
2037         VM_Warning("VM_entityfieldname: %s: field index out of bounds\n", PRVM_NAME);
2038         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
2039                 return;
2040         }
2041         
2042         d = &prog->fielddefs[i];
2043         PRVM_G_INT(OFS_RETURN) = d->s_name; // presuming that s_name points to a string already
2044 }
2045
2046 // KrimZon - DP_QC_ENTITYDATA
2047 /*
2048 =========
2049 VM_entityfieldtype
2050
2051 float(float fieldnum) entityfieldtype
2052 =========
2053 */
2054 void VM_entityfieldtype(void)
2055 {
2056         ddef_t *d;
2057         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2058         
2059         if (i < 0 || i >= prog->numfielddefs)
2060         {
2061                 VM_Warning("VM_entityfieldtype: %s: field index out of bounds\n", PRVM_NAME);
2062                 PRVM_G_FLOAT(OFS_RETURN) = -1.0;
2063                 return;
2064         }
2065         
2066         d = &prog->fielddefs[i];
2067         PRVM_G_FLOAT(OFS_RETURN) = (float)d->type;
2068 }
2069
2070 // KrimZon - DP_QC_ENTITYDATA
2071 /*
2072 =========
2073 VM_getentityfieldstring
2074
2075 string(float fieldnum, entity ent) getentityfieldstring
2076 =========
2077 */
2078 void VM_getentityfieldstring(void)
2079 {
2080         // put the data into a string
2081         ddef_t *d;
2082         int type, j;
2083         int *v;
2084         prvm_edict_t * ent;
2085         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2086         
2087         if (i < 0 || i >= prog->numfielddefs)
2088         {
2089         VM_Warning("VM_entityfielddata: %s: field index out of bounds\n", PRVM_NAME);
2090                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
2091                 return;
2092         }
2093         
2094         d = &prog->fielddefs[i];
2095         
2096         // get the entity
2097         ent = PRVM_G_EDICT(OFS_PARM1);
2098         if(ent->priv.required->free)
2099         {
2100                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
2101                 VM_Warning("VM_entityfielddata: %s: entity %i is free !\n", PRVM_NAME, PRVM_NUM_FOR_EDICT(ent));
2102                 return;
2103         }
2104         v = (int *)((char *)ent->fields.vp + d->ofs*4);
2105         
2106         // if it's 0 or blank, return an empty string
2107         type = d->type & ~DEF_SAVEGLOBAL;
2108         for (j=0 ; j<prvm_type_size[type] ; j++)
2109                 if (v[j])
2110                         break;
2111         if (j == prvm_type_size[type])
2112         {
2113                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
2114                 return;
2115         }
2116                 
2117         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(PRVM_UglyValueString((etype_t)d->type, (prvm_eval_t *)v));
2118 }
2119
2120 // KrimZon - DP_QC_ENTITYDATA
2121 /*
2122 =========
2123 VM_putentityfieldstring
2124
2125 float(float fieldnum, entity ent, string s) putentityfieldstring
2126 =========
2127 */
2128 void VM_putentityfieldstring(void)
2129 {
2130         ddef_t *d;
2131         prvm_edict_t * ent;
2132         int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2133
2134         if (i < 0 || i >= prog->numfielddefs)
2135         {
2136         VM_Warning("VM_entityfielddata: %s: field index out of bounds\n", PRVM_NAME);
2137                 PRVM_G_FLOAT(OFS_RETURN) = 0.0f;
2138                 return;
2139         }
2140
2141         d = &prog->fielddefs[i];
2142
2143         // get the entity
2144         ent = PRVM_G_EDICT(OFS_PARM1);
2145         if(ent->priv.required->free)
2146         {
2147                 VM_Warning("VM_entityfielddata: %s: entity %i is free !\n", PRVM_NAME, PRVM_NUM_FOR_EDICT(ent));
2148                 PRVM_G_FLOAT(OFS_RETURN) = 0.0f;
2149                 return;
2150         }
2151
2152         // parse the string into the value
2153         PRVM_G_FLOAT(OFS_RETURN) = ( PRVM_ED_ParseEpair(ent, d, PRVM_G_STRING(OFS_PARM2), false) ) ? 1.0f : 0.0f;
2154 }
2155
2156 /*
2157 =========
2158 VM_strlen
2159
2160 float   strlen(string s)
2161 =========
2162 */
2163 //float(string s) strlen = #114; // returns how many characters are in a string
2164 void VM_strlen(void)
2165 {
2166         VM_SAFEPARMCOUNT(1,VM_strlen);
2167
2168         //PRVM_G_FLOAT(OFS_RETURN) = strlen(PRVM_G_STRING(OFS_PARM0));
2169         PRVM_G_FLOAT(OFS_RETURN) = u8_strlen(PRVM_G_STRING(OFS_PARM0));
2170 }
2171
2172 // DRESK - Decolorized String
2173 /*
2174 =========
2175 VM_strdecolorize
2176
2177 string  strdecolorize(string s)
2178 =========
2179 */
2180 // string (string s) strdecolorize = #472; // returns the passed in string with color codes stripped
2181 void VM_strdecolorize(void)
2182 {
2183         char szNewString[VM_STRINGTEMP_LENGTH];
2184         const char *szString;
2185
2186         // Prepare Strings
2187         VM_SAFEPARMCOUNT(1,VM_strdecolorize);
2188         szString = PRVM_G_STRING(OFS_PARM0);
2189         COM_StringDecolorize(szString, 0, szNewString, sizeof(szNewString), TRUE);
2190         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(szNewString);
2191 }
2192
2193 // DRESK - String Length (not counting color codes)
2194 /*
2195 =========
2196 VM_strlennocol
2197
2198 float   strlennocol(string s)
2199 =========
2200 */
2201 // float(string s) strlennocol = #471; // returns how many characters are in a string not including color codes
2202 // For example, ^2Dresk returns a length of 5
2203 void VM_strlennocol(void)
2204 {
2205         const char *szString;
2206         int nCnt;
2207
2208         VM_SAFEPARMCOUNT(1,VM_strlennocol);
2209
2210         szString = PRVM_G_STRING(OFS_PARM0);
2211
2212         //nCnt = COM_StringLengthNoColors(szString, 0, NULL);
2213         nCnt = u8_COM_StringLengthNoColors(szString, 0, NULL);
2214
2215         PRVM_G_FLOAT(OFS_RETURN) = nCnt;
2216 }
2217
2218 // DRESK - String to Uppercase and Lowercase
2219 /*
2220 =========
2221 VM_strtolower
2222
2223 string  strtolower(string s)
2224 =========
2225 */
2226 // string (string s) strtolower = #480; // returns passed in string in lowercase form
2227 void VM_strtolower(void)
2228 {
2229         char szNewString[VM_STRINGTEMP_LENGTH];
2230         const char *szString;
2231
2232         // Prepare Strings
2233         VM_SAFEPARMCOUNT(1,VM_strtolower);
2234         szString = PRVM_G_STRING(OFS_PARM0);
2235
2236         COM_ToLowerString(szString, szNewString, sizeof(szNewString) );
2237
2238         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(szNewString);
2239 }
2240
2241 /*
2242 =========
2243 VM_strtoupper
2244
2245 string  strtoupper(string s)
2246 =========
2247 */
2248 // string (string s) strtoupper = #481; // returns passed in string in uppercase form
2249 void VM_strtoupper(void)
2250 {
2251         char szNewString[VM_STRINGTEMP_LENGTH];
2252         const char *szString;
2253
2254         // Prepare Strings
2255         VM_SAFEPARMCOUNT(1,VM_strtoupper);
2256         szString = PRVM_G_STRING(OFS_PARM0);
2257
2258         COM_ToUpperString(szString, szNewString, sizeof(szNewString) );
2259
2260         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(szNewString);
2261 }
2262
2263 /*
2264 =========
2265 VM_strcat
2266
2267 string strcat(string,string,...[string])
2268 =========
2269 */
2270 //string(string s1, string s2) strcat = #115;
2271 // concatenates two strings (for example "abc", "def" would return "abcdef")
2272 // and returns as a tempstring
2273 void VM_strcat(void)
2274 {
2275         char s[VM_STRINGTEMP_LENGTH];
2276         VM_SAFEPARMCOUNTRANGE(1, 8, VM_strcat);
2277
2278         VM_VarString(0, s, sizeof(s));
2279         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(s);
2280 }
2281
2282 /*
2283 =========
2284 VM_substring
2285
2286 string  substring(string s, float start, float length)
2287 =========
2288 */
2289 // string(string s, float start, float length) substring = #116;
2290 // returns a section of a string as a tempstring
2291 void VM_substring(void)
2292 {
2293         int start, length;
2294         int u_slength = 0, u_start;
2295         size_t u_length;
2296         const char *s;
2297         char string[VM_STRINGTEMP_LENGTH];
2298
2299         VM_SAFEPARMCOUNT(3,VM_substring);
2300
2301         /*
2302         s = PRVM_G_STRING(OFS_PARM0);
2303         start = (int)PRVM_G_FLOAT(OFS_PARM1);
2304         length = (int)PRVM_G_FLOAT(OFS_PARM2);
2305         slength = strlen(s);
2306
2307         if (start < 0) // FTE_STRINGS feature
2308                 start += slength;
2309         start = bound(0, start, slength);
2310
2311         if (length < 0) // FTE_STRINGS feature
2312                 length += slength - start + 1;
2313         maxlen = min((int)sizeof(string) - 1, slength - start);
2314         length = bound(0, length, maxlen);
2315
2316         memcpy(string, s + start, length);
2317         string[length] = 0;
2318         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
2319         */
2320         
2321         s = PRVM_G_STRING(OFS_PARM0);
2322         start = (int)PRVM_G_FLOAT(OFS_PARM1);
2323         length = (int)PRVM_G_FLOAT(OFS_PARM2);
2324
2325         if (start < 0) // FTE_STRINGS feature
2326         {
2327                 u_slength = u8_strlen(s);
2328                 start += u_slength;
2329                 start = bound(0, start, u_slength);
2330         }
2331
2332         if (length < 0) // FTE_STRINGS feature
2333         {
2334                 if (!u_slength) // it's not calculated when it's not needed above
2335                         u_slength = u8_strlen(s);
2336                 length += u_slength - start + 1;
2337         }
2338                 
2339         // positive start, positive length
2340         u_start = u8_byteofs(s, start, NULL);
2341         if (u_start < 0)
2342         {
2343                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
2344                 return;
2345         }
2346         u_length = u8_bytelen(s + u_start, length);
2347         if (u_length >= sizeof(string)-1)
2348                 u_length = sizeof(string)-1;
2349         
2350         memcpy(string, s + u_start, u_length);
2351         string[u_length] = 0;
2352         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
2353 }
2354
2355 /*
2356 =========
2357 VM_strreplace
2358
2359 string(string search, string replace, string subject) strreplace = #484;
2360 =========
2361 */
2362 // replaces all occurrences of search with replace in the string subject, and returns the result
2363 void VM_strreplace(void)
2364 {
2365         int i, j, si;
2366         const char *search, *replace, *subject;
2367         char string[VM_STRINGTEMP_LENGTH];
2368         int search_len, replace_len, subject_len;
2369
2370         VM_SAFEPARMCOUNT(3,VM_strreplace);
2371
2372         search = PRVM_G_STRING(OFS_PARM0);
2373         replace = PRVM_G_STRING(OFS_PARM1);
2374         subject = PRVM_G_STRING(OFS_PARM2);
2375
2376         search_len = (int)strlen(search);
2377         replace_len = (int)strlen(replace);
2378         subject_len = (int)strlen(subject);
2379
2380         si = 0;
2381         for (i = 0; i <= subject_len - search_len; i++)
2382         {
2383                 for (j = 0; j < search_len; j++) // thus, i+j < subject_len
2384                         if (subject[i+j] != search[j])
2385                                 break;
2386                 if (j == search_len)
2387                 {
2388                         // NOTE: if search_len == 0, we always hit THIS case, and never the other
2389                         // found it at offset 'i'
2390                         for (j = 0; j < replace_len && si < (int)sizeof(string) - 1; j++)
2391                                 string[si++] = replace[j];
2392                         if(search_len > 0)
2393                         {
2394                                 i += search_len - 1;
2395                         }
2396                         else
2397                         {
2398                                 // the above would subtract 1 from i... so we
2399                                 // don't do that, but instead output the next
2400                                 // char
2401                                 if (si < (int)sizeof(string) - 1)
2402                                         string[si++] = subject[i];
2403                         }
2404                 }
2405                 else
2406                 {
2407                         // in THIS case, we know search_len > 0, thus i < subject_len
2408                         // not found
2409                         if (si < (int)sizeof(string) - 1)
2410                                 string[si++] = subject[i];
2411                 }
2412         }
2413         // remaining chars (these cannot match)
2414         for (; i < subject_len; i++)
2415                 if (si < (int)sizeof(string) - 1)
2416                         string[si++] = subject[i];
2417         string[si] = '\0';
2418
2419         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
2420 }
2421
2422 /*
2423 =========
2424 VM_strireplace
2425
2426 string(string search, string replace, string subject) strireplace = #485;
2427 =========
2428 */
2429 // case-insensitive version of strreplace
2430 void VM_strireplace(void)
2431 {
2432         int i, j, si;
2433         const char *search, *replace, *subject;
2434         char string[VM_STRINGTEMP_LENGTH];
2435         int search_len, replace_len, subject_len;
2436
2437         VM_SAFEPARMCOUNT(3,VM_strreplace);
2438
2439         search = PRVM_G_STRING(OFS_PARM0);
2440         replace = PRVM_G_STRING(OFS_PARM1);
2441         subject = PRVM_G_STRING(OFS_PARM2);
2442
2443         search_len = (int)strlen(search);
2444         replace_len = (int)strlen(replace);
2445         subject_len = (int)strlen(subject);
2446
2447         si = 0;
2448         for (i = 0; i <= subject_len - search_len; i++)
2449         {
2450                 for (j = 0; j < search_len; j++) // thus, i+j < subject_len
2451                         if (tolower(subject[i+j]) != tolower(search[j]))
2452                                 break;
2453                 if (j == search_len)
2454                 {
2455                         // NOTE: if search_len == 0, we always hit THIS case, and never the other
2456                         // found it at offset 'i'
2457                         for (j = 0; j < replace_len && si < (int)sizeof(string) - 1; j++)
2458                                 string[si++] = replace[j];
2459                         if(search_len > 0)
2460                         {
2461                                 i += search_len - 1;
2462                         }
2463                         else
2464                         {
2465                                 // the above would subtract 1 from i... so we
2466                                 // don't do that, but instead output the next
2467                                 // char
2468                                 if (si < (int)sizeof(string) - 1)
2469                                         string[si++] = subject[i];
2470                         }
2471                 }
2472                 else
2473                 {
2474                         // in THIS case, we know search_len > 0, thus i < subject_len
2475                         // not found
2476                         if (si < (int)sizeof(string) - 1)
2477                                 string[si++] = subject[i];
2478                 }
2479         }
2480         // remaining chars (these cannot match)
2481         for (; i < subject_len; i++)
2482                 if (si < (int)sizeof(string) - 1)
2483                         string[si++] = subject[i];
2484         string[si] = '\0';
2485
2486         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(string);
2487 }
2488
2489 /*
2490 =========
2491 VM_stov
2492
2493 vector  stov(string s)
2494 =========
2495 */
2496 //vector(string s) stov = #117; // returns vector value from a string
2497 void VM_stov(void)
2498 {
2499         char string[VM_STRINGTEMP_LENGTH];
2500
2501         VM_SAFEPARMCOUNT(1,VM_stov);
2502
2503         VM_VarString(0, string, sizeof(string));
2504         Math_atov(string, PRVM_G_VECTOR(OFS_RETURN));
2505 }
2506
2507 /*
2508 =========
2509 VM_strzone
2510
2511 string  strzone(string s)
2512 =========
2513 */
2514 //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)
2515 void VM_strzone(void)
2516 {
2517         char *out;
2518         char string[VM_STRINGTEMP_LENGTH];
2519         size_t alloclen;
2520
2521         VM_SAFEPARMCOUNT(1,VM_strzone);
2522
2523         VM_VarString(0, string, sizeof(string));
2524         alloclen = strlen(string) + 1;
2525         PRVM_G_INT(OFS_RETURN) = PRVM_AllocString(alloclen, &out);
2526         memcpy(out, string, alloclen);
2527 }
2528
2529 /*
2530 =========
2531 VM_strunzone
2532
2533 strunzone(string s)
2534 =========
2535 */
2536 //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!!!)
2537 void VM_strunzone(void)
2538 {
2539         VM_SAFEPARMCOUNT(1,VM_strunzone);
2540         PRVM_FreeString(PRVM_G_INT(OFS_PARM0));
2541 }
2542
2543 /*
2544 =========
2545 VM_command (used by client and menu)
2546
2547 clientcommand(float client, string s) (for client and menu)
2548 =========
2549 */
2550 //void(entity e, string s) clientcommand = #440; // executes a command string as if it came from the specified client
2551 //this function originally written by KrimZon, made shorter by LordHavoc
2552 void VM_clcommand (void)
2553 {
2554         client_t *temp_client;
2555         int i;
2556
2557         VM_SAFEPARMCOUNT(2,VM_clcommand);
2558
2559         i = (int)PRVM_G_FLOAT(OFS_PARM0);
2560         if (!sv.active  || i < 0 || i >= svs.maxclients || !svs.clients[i].active)
2561         {
2562                 VM_Warning("VM_clientcommand: %s: invalid client/server is not active !\n", PRVM_NAME);
2563                 return;
2564         }
2565
2566         temp_client = host_client;
2567         host_client = svs.clients + i;
2568         Cmd_ExecuteString (PRVM_G_STRING(OFS_PARM1), src_client);
2569         host_client = temp_client;
2570 }
2571
2572
2573 /*
2574 =========
2575 VM_tokenize
2576
2577 float tokenize(string s)
2578 =========
2579 */
2580 //float(string s) tokenize = #441; // takes apart a string into individal words (access them with argv), returns how many
2581 //this function originally written by KrimZon, made shorter by LordHavoc
2582 //20040203: rewritten by LordHavoc (no longer uses allocations)
2583 static int num_tokens = 0;
2584 static int tokens[VM_STRINGTEMP_LENGTH / 2];
2585 static int tokens_startpos[VM_STRINGTEMP_LENGTH / 2];
2586 static int tokens_endpos[VM_STRINGTEMP_LENGTH / 2];
2587 static char tokenize_string[VM_STRINGTEMP_LENGTH];
2588 void VM_tokenize (void)
2589 {
2590         const char *p;
2591
2592         VM_SAFEPARMCOUNT(1,VM_tokenize);
2593
2594         strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2595         p = tokenize_string;
2596
2597         num_tokens = 0;
2598         for(;;)
2599         {
2600                 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
2601                         break;
2602
2603                 // skip whitespace here to find token start pos
2604                 while(*p && ISWHITESPACE(*p))
2605                         ++p;
2606
2607                 tokens_startpos[num_tokens] = p - tokenize_string;
2608                 if(!COM_ParseToken_VM_Tokenize(&p, false))
2609                         break;
2610                 tokens_endpos[num_tokens] = p - tokenize_string;
2611                 tokens[num_tokens] = PRVM_SetTempString(com_token);
2612                 ++num_tokens;
2613         }
2614
2615         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2616 }
2617
2618 //float(string s) tokenize = #514; // takes apart a string into individal words (access them with argv), returns how many
2619 void VM_tokenize_console (void)
2620 {
2621         const char *p;
2622
2623         VM_SAFEPARMCOUNT(1,VM_tokenize);
2624
2625         strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2626         p = tokenize_string;
2627
2628         num_tokens = 0;
2629         for(;;)
2630         {
2631                 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
2632                         break;
2633
2634                 // skip whitespace here to find token start pos
2635                 while(*p && ISWHITESPACE(*p))
2636                         ++p;
2637
2638                 tokens_startpos[num_tokens] = p - tokenize_string;
2639                 if(!COM_ParseToken_Console(&p))
2640                         break;
2641                 tokens_endpos[num_tokens] = p - tokenize_string;
2642                 tokens[num_tokens] = PRVM_SetTempString(com_token);
2643                 ++num_tokens;
2644         }
2645
2646         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2647 }
2648
2649 /*
2650 =========
2651 VM_tokenizebyseparator
2652
2653 float tokenizebyseparator(string s, string separator1, ...)
2654 =========
2655 */
2656 //float(string s, string separator1, ...) tokenizebyseparator = #479; // takes apart a string into individal words (access them with argv), returns how many
2657 //this function returns the token preceding each instance of a separator (of
2658 //which there can be multiple), and the text following the last separator
2659 //useful for parsing certain kinds of data like IP addresses
2660 //example:
2661 //numnumbers = tokenizebyseparator("10.1.2.3", ".");
2662 //returns 4 and the tokens "10" "1" "2" "3".
2663 void VM_tokenizebyseparator (void)
2664 {
2665         int j, k;
2666         int numseparators;
2667         int separatorlen[7];
2668         const char *separators[7];
2669         const char *p, *p0;
2670         const char *token;
2671         char tokentext[MAX_INPUTLINE];
2672
2673         VM_SAFEPARMCOUNTRANGE(2, 8,VM_tokenizebyseparator);
2674
2675         strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2676         p = tokenize_string;
2677
2678         numseparators = 0;
2679         for (j = 1;j < prog->argc;j++)
2680         {
2681                 // skip any blank separator strings
2682                 const char *s = PRVM_G_STRING(OFS_PARM0+j*3);
2683                 if (!s[0])
2684                         continue;
2685                 separators[numseparators] = s;
2686                 separatorlen[numseparators] = strlen(s);
2687                 numseparators++;
2688         }
2689
2690         num_tokens = 0;
2691         j = 0;
2692
2693         while (num_tokens < (int)(sizeof(tokens)/sizeof(tokens[0])))
2694         {
2695                 token = tokentext + j;
2696                 tokens_startpos[num_tokens] = p - tokenize_string;
2697                 p0 = p;
2698                 while (*p)
2699                 {
2700                         for (k = 0;k < numseparators;k++)
2701                         {
2702                                 if (!strncmp(p, separators[k], separatorlen[k]))
2703                                 {
2704                                         p += separatorlen[k];
2705                                         break;
2706                                 }
2707                         }
2708                         if (k < numseparators)
2709                                 break;
2710                         if (j < (int)sizeof(tokentext)-1)
2711                                 tokentext[j++] = *p;
2712                         p++;
2713                         p0 = p;
2714                 }
2715                 tokens_endpos[num_tokens] = p0 - tokenize_string;
2716                 if (j >= (int)sizeof(tokentext))
2717                         break;
2718                 tokentext[j++] = 0;
2719                 tokens[num_tokens++] = PRVM_SetTempString(token);
2720                 if (!*p)
2721                         break;
2722         }
2723
2724         PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2725 }
2726
2727 //string(float n) argv = #442; // returns a word from the tokenized string (returns nothing for an invalid index)
2728 //this function originally written by KrimZon, made shorter by LordHavoc
2729 void VM_argv (void)
2730 {
2731         int token_num;
2732
2733         VM_SAFEPARMCOUNT(1,VM_argv);
2734
2735         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2736
2737         if(token_num < 0)
2738                 token_num += num_tokens;
2739
2740         if (token_num >= 0 && token_num < num_tokens)
2741                 PRVM_G_INT(OFS_RETURN) = tokens[token_num];
2742         else
2743                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
2744 }
2745
2746 //float(float n) argv_start_index = #515; // returns the start index of a token
2747 void VM_argv_start_index (void)
2748 {
2749         int token_num;
2750
2751         VM_SAFEPARMCOUNT(1,VM_argv);
2752
2753         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2754
2755         if(token_num < 0)
2756                 token_num += num_tokens;
2757
2758         if (token_num >= 0 && token_num < num_tokens)
2759                 PRVM_G_FLOAT(OFS_RETURN) = tokens_startpos[token_num];
2760         else
2761                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2762 }
2763
2764 //float(float n) argv_end_index = #516; // returns the end index of a token
2765 void VM_argv_end_index (void)
2766 {
2767         int token_num;
2768
2769         VM_SAFEPARMCOUNT(1,VM_argv);
2770
2771         token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2772
2773         if(token_num < 0)
2774                 token_num += num_tokens;
2775
2776         if (token_num >= 0 && token_num < num_tokens)
2777                 PRVM_G_FLOAT(OFS_RETURN) = tokens_endpos[token_num];
2778         else
2779                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2780 }
2781
2782 /*
2783 =========
2784 VM_isserver
2785
2786 float   isserver()
2787 =========
2788 */
2789 void VM_isserver(void)
2790 {
2791         VM_SAFEPARMCOUNT(0,VM_serverstate);
2792
2793         PRVM_G_FLOAT(OFS_RETURN) = sv.active && (svs.maxclients > 1 || cls.state == ca_dedicated);
2794 }
2795
2796 /*
2797 =========
2798 VM_clientcount
2799
2800 float   clientcount()
2801 =========
2802 */
2803 void VM_clientcount(void)
2804 {
2805         VM_SAFEPARMCOUNT(0,VM_clientcount);
2806
2807         PRVM_G_FLOAT(OFS_RETURN) = svs.maxclients;
2808 }
2809
2810 /*
2811 =========
2812 VM_clientstate
2813
2814 float   clientstate()
2815 =========
2816 */
2817 void VM_clientstate(void)
2818 {
2819         VM_SAFEPARMCOUNT(0,VM_clientstate);
2820
2821
2822         switch( cls.state ) {
2823                 case ca_uninitialized:
2824                 case ca_dedicated:
2825                         PRVM_G_FLOAT(OFS_RETURN) = 0;
2826                         break;
2827                 case ca_disconnected:
2828                         PRVM_G_FLOAT(OFS_RETURN) = 1;
2829                         break;
2830                 case ca_connected:
2831                         PRVM_G_FLOAT(OFS_RETURN) = 2;
2832                         break;
2833                 default:
2834                         // should never be reached!
2835                         break;
2836         }
2837 }
2838
2839 /*
2840 =========
2841 VM_getostype
2842
2843 float   getostype(void)
2844 =========
2845 */ // not used at the moment -> not included in the common list
2846 void VM_getostype(void)
2847 {
2848         VM_SAFEPARMCOUNT(0,VM_getostype);
2849
2850         /*
2851         OS_WINDOWS
2852         OS_LINUX
2853         OS_MAC - not supported
2854         */
2855
2856 #ifdef WIN32
2857         PRVM_G_FLOAT(OFS_RETURN) = 0;
2858 #elif defined(MACOSX)
2859         PRVM_G_FLOAT(OFS_RETURN) = 2;
2860 #else
2861         PRVM_G_FLOAT(OFS_RETURN) = 1;
2862 #endif
2863 }
2864
2865 /*
2866 =========
2867 VM_gettime
2868
2869 float   gettime(void)
2870 =========
2871 */
2872 extern double host_starttime;
2873 float CDAudio_GetPosition(void);
2874 void VM_gettime(void)
2875 {
2876         int timer_index;
2877
2878         VM_SAFEPARMCOUNTRANGE(0,1,VM_gettime);
2879
2880         if(prog->argc == 0)
2881         {
2882                 PRVM_G_FLOAT(OFS_RETURN) = (float) realtime;
2883         }
2884         else
2885         {
2886                 timer_index = (int) PRVM_G_FLOAT(OFS_PARM0);
2887         switch(timer_index)
2888         {
2889             case 0: // GETTIME_FRAMESTART
2890                 PRVM_G_FLOAT(OFS_RETURN) = (float) realtime;
2891                 break;
2892             case 1: // GETTIME_REALTIME
2893                 PRVM_G_FLOAT(OFS_RETURN) = (float) Sys_DoubleTime();
2894                 break;
2895             case 2: // GETTIME_HIRES
2896                 PRVM_G_FLOAT(OFS_RETURN) = (float) (Sys_DoubleTime() - realtime);
2897                 break;
2898             case 3: // GETTIME_UPTIME
2899                 PRVM_G_FLOAT(OFS_RETURN) = (float) (Sys_DoubleTime() - host_starttime);
2900                 break;
2901             case 4: // GETTIME_CDTRACK
2902                 PRVM_G_FLOAT(OFS_RETURN) = (float) CDAudio_GetPosition();
2903                 break;
2904                         default:
2905                                 VM_Warning("VM_gettime: %s: unsupported timer specified, returning realtime\n", PRVM_NAME);
2906                                 PRVM_G_FLOAT(OFS_RETURN) = (float) realtime;
2907                                 break;
2908                 }
2909         }
2910 }
2911
2912 /*
2913 =========
2914 VM_getsoundtime
2915
2916 float   getsoundtime(void)
2917 =========
2918 */
2919
2920 void VM_getsoundtime (void)
2921 {
2922         int entnum, entchannel, pnum;
2923         VM_SAFEPARMCOUNT(2,VM_getsoundtime);
2924
2925         pnum = PRVM_GetProgNr();
2926         if (pnum == PRVM_MENUPROG)
2927         {
2928                 VM_Warning("VM_getsoundtime: %s: not supported on this progs\n", PRVM_NAME);
2929                 PRVM_G_FLOAT(OFS_RETURN) = -1;
2930                 return;
2931         }
2932         entnum = ((pnum == PRVM_CLIENTPROG) ? MAX_EDICTS : 0) + PRVM_NUM_FOR_EDICT(PRVM_G_EDICT(OFS_PARM0));
2933         entchannel = (int)PRVM_G_FLOAT(OFS_PARM1);
2934         entchannel = CHAN_USER2ENGINE(entchannel);
2935         if (!IS_CHAN(entchannel))
2936                 VM_Warning("VM_getsoundtime: %s: bad channel %i\n", PRVM_NAME, entchannel);
2937         PRVM_G_FLOAT(OFS_RETURN) = (float)S_GetEntChannelPosition(entnum, entchannel);
2938 }
2939
2940 /*
2941 =========
2942 VM_GetSoundLen
2943
2944 string  soundlength (string sample)
2945 =========
2946 */
2947 void VM_soundlength (void)
2948 {
2949         const char *s;
2950
2951         VM_SAFEPARMCOUNT(1, VM_soundlength);
2952
2953         s = PRVM_G_STRING(OFS_PARM0);
2954         PRVM_G_FLOAT(OFS_RETURN) = S_SoundLength(s);
2955 }
2956
2957 /*
2958 =========
2959 VM_loadfromdata
2960
2961 loadfromdata(string data)
2962 =========
2963 */
2964 void VM_loadfromdata(void)
2965 {
2966         VM_SAFEPARMCOUNT(1,VM_loadentsfromfile);
2967
2968         PRVM_ED_LoadFromFile(PRVM_G_STRING(OFS_PARM0));
2969 }
2970
2971 /*
2972 ========================
2973 VM_parseentitydata
2974
2975 parseentitydata(entity ent, string data)
2976 ========================
2977 */
2978 void VM_parseentitydata(void)
2979 {
2980         prvm_edict_t *ent;
2981         const char *data;
2982
2983         VM_SAFEPARMCOUNT(2, VM_parseentitydata);
2984
2985         // get edict and test it
2986         ent = PRVM_G_EDICT(OFS_PARM0);
2987         if (ent->priv.required->free)
2988                 PRVM_ERROR ("VM_parseentitydata: %s: Can only set already spawned entities (entity %i is free)!", PRVM_NAME, PRVM_NUM_FOR_EDICT(ent));
2989
2990         data = PRVM_G_STRING(OFS_PARM1);
2991
2992         // parse the opening brace
2993         if (!COM_ParseToken_Simple(&data, false, false) || com_token[0] != '{' )
2994                 PRVM_ERROR ("VM_parseentitydata: %s: Couldn't parse entity data:\n%s", PRVM_NAME, data );
2995
2996         PRVM_ED_ParseEdict (data, ent);
2997 }
2998
2999 /*
3000 =========
3001 VM_loadfromfile
3002
3003 loadfromfile(string file)
3004 =========
3005 */
3006 void VM_loadfromfile(void)
3007 {
3008         const char *filename;
3009         char *data;
3010
3011         VM_SAFEPARMCOUNT(1,VM_loadfromfile);
3012
3013         filename = PRVM_G_STRING(OFS_PARM0);
3014         if (FS_CheckNastyPath(filename, false))
3015         {
3016                 PRVM_G_FLOAT(OFS_RETURN) = -4;
3017                 VM_Warning("VM_loadfromfile: %s dangerous or non-portable filename \"%s\" not allowed. (contains : or \\ or begins with .. or /)\n", PRVM_NAME, filename);
3018                 return;
3019         }
3020
3021         // not conform with VM_fopen
3022         data = (char *)FS_LoadFile(filename, tempmempool, false, NULL);
3023         if (data == NULL)
3024                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3025
3026         PRVM_ED_LoadFromFile(data);
3027
3028         if(data)
3029                 Mem_Free(data);
3030 }
3031
3032
3033 /*
3034 =========
3035 VM_modulo
3036
3037 float   mod(float val, float m)
3038 =========
3039 */
3040 void VM_modulo(void)
3041 {
3042         int val, m;
3043         VM_SAFEPARMCOUNT(2,VM_module);
3044
3045         val = (int) PRVM_G_FLOAT(OFS_PARM0);
3046         m       = (int) PRVM_G_FLOAT(OFS_PARM1);
3047
3048         PRVM_G_FLOAT(OFS_RETURN) = (float) (val % m);
3049 }
3050
3051 void VM_Search_Init(void)
3052 {
3053         int i;
3054         for (i = 0;i < PRVM_MAX_OPENSEARCHES;i++)
3055                 prog->opensearches[i] = NULL;
3056 }
3057
3058 void VM_Search_Reset(void)
3059 {
3060         int i;
3061         // reset the fssearch list
3062         for(i = 0; i < PRVM_MAX_OPENSEARCHES; i++)
3063         {
3064                 if(prog->opensearches[i])
3065                         FS_FreeSearch(prog->opensearches[i]);
3066                 prog->opensearches[i] = NULL;
3067         }
3068 }
3069
3070 /*
3071 =========
3072 VM_search_begin
3073
3074 float search_begin(string pattern, float caseinsensitive, float quiet)
3075 =========
3076 */
3077 void VM_search_begin(void)
3078 {
3079         int handle;
3080         const char *pattern;
3081         int caseinsens, quiet;
3082
3083         VM_SAFEPARMCOUNT(3, VM_search_begin);
3084
3085         pattern = PRVM_G_STRING(OFS_PARM0);
3086
3087         VM_CheckEmptyString(pattern);
3088
3089         caseinsens = (int)PRVM_G_FLOAT(OFS_PARM1);
3090         quiet = (int)PRVM_G_FLOAT(OFS_PARM2);
3091
3092         for(handle = 0; handle < PRVM_MAX_OPENSEARCHES; handle++)
3093                 if(!prog->opensearches[handle])
3094                         break;
3095
3096         if(handle >= PRVM_MAX_OPENSEARCHES)
3097         {
3098                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3099                 VM_Warning("VM_search_begin: %s ran out of search handles (%i)\n", PRVM_NAME, PRVM_MAX_OPENSEARCHES);
3100                 return;
3101         }
3102
3103         if(!(prog->opensearches[handle] = FS_Search(pattern,caseinsens, quiet)))
3104                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3105         else
3106         {
3107                 prog->opensearches_origin[handle] = PRVM_AllocationOrigin();
3108                 PRVM_G_FLOAT(OFS_RETURN) = handle;
3109         }
3110 }
3111
3112 /*
3113 =========
3114 VM_search_end
3115
3116 void    search_end(float handle)
3117 =========
3118 */
3119 void VM_search_end(void)
3120 {
3121         int handle;
3122         VM_SAFEPARMCOUNT(1, VM_search_end);
3123
3124         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3125
3126         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3127         {
3128                 VM_Warning("VM_search_end: invalid handle %i used in %s\n", handle, PRVM_NAME);
3129                 return;
3130         }
3131         if(prog->opensearches[handle] == NULL)
3132         {
3133                 VM_Warning("VM_search_end: no such handle %i in %s\n", handle, PRVM_NAME);
3134                 return;
3135         }
3136
3137         FS_FreeSearch(prog->opensearches[handle]);
3138         prog->opensearches[handle] = NULL;
3139         if(prog->opensearches_origin[handle])
3140                 PRVM_Free((char *)prog->opensearches_origin[handle]);
3141 }
3142
3143 /*
3144 =========
3145 VM_search_getsize
3146
3147 float   search_getsize(float handle)
3148 =========
3149 */
3150 void VM_search_getsize(void)
3151 {
3152         int handle;
3153         VM_SAFEPARMCOUNT(1, VM_M_search_getsize);
3154
3155         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3156
3157         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3158         {
3159                 VM_Warning("VM_search_getsize: invalid handle %i used in %s\n", handle, PRVM_NAME);
3160                 return;
3161         }
3162         if(prog->opensearches[handle] == NULL)
3163         {
3164                 VM_Warning("VM_search_getsize: no such handle %i in %s\n", handle, PRVM_NAME);
3165                 return;
3166         }
3167
3168         PRVM_G_FLOAT(OFS_RETURN) = prog->opensearches[handle]->numfilenames;
3169 }
3170
3171 /*
3172 =========
3173 VM_search_getfilename
3174
3175 string  search_getfilename(float handle, float num)
3176 =========
3177 */
3178 void VM_search_getfilename(void)
3179 {
3180         int handle, filenum;
3181         VM_SAFEPARMCOUNT(2, VM_search_getfilename);
3182
3183         handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3184         filenum = (int)PRVM_G_FLOAT(OFS_PARM1);
3185
3186         if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3187         {
3188                 VM_Warning("VM_search_getfilename: invalid handle %i used in %s\n", handle, PRVM_NAME);
3189                 return;
3190         }
3191         if(prog->opensearches[handle] == NULL)
3192         {
3193                 VM_Warning("VM_search_getfilename: no such handle %i in %s\n", handle, PRVM_NAME);
3194                 return;
3195         }
3196         if(filenum < 0 || filenum >= prog->opensearches[handle]->numfilenames)
3197         {
3198                 VM_Warning("VM_search_getfilename: invalid filenum %i in %s\n", filenum, PRVM_NAME);
3199                 return;
3200         }
3201
3202         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog->opensearches[handle]->filenames[filenum]);
3203 }
3204
3205 /*
3206 =========
3207 VM_chr
3208
3209 string  chr(float ascii)
3210 =========
3211 */
3212 void VM_chr(void)
3213 {
3214         /*
3215         char tmp[2];
3216         VM_SAFEPARMCOUNT(1, VM_chr);
3217
3218         tmp[0] = (unsigned char) PRVM_G_FLOAT(OFS_PARM0);
3219         tmp[1] = 0;
3220
3221         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(tmp);
3222         */
3223         
3224         char tmp[8];
3225         int len;
3226         VM_SAFEPARMCOUNT(1, VM_chr);
3227
3228         len = u8_fromchar((Uchar)PRVM_G_FLOAT(OFS_PARM0), tmp, sizeof(tmp));
3229         tmp[len] = 0;
3230         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(tmp);
3231 }
3232
3233 //=============================================================================
3234 // Draw builtins (client & menu)
3235
3236 /*
3237 =========
3238 VM_iscachedpic
3239
3240 float   iscachedpic(string pic)
3241 =========
3242 */
3243 void VM_iscachedpic(void)
3244 {
3245         VM_SAFEPARMCOUNT(1,VM_iscachedpic);
3246
3247         // drawq hasnt such a function, thus always return true
3248         PRVM_G_FLOAT(OFS_RETURN) = false;
3249 }
3250
3251 /*
3252 =========
3253 VM_precache_pic
3254
3255 string  precache_pic(string pic)
3256 =========
3257 */
3258 void VM_precache_pic(void)
3259 {
3260         const char      *s;
3261
3262         VM_SAFEPARMCOUNT(1, VM_precache_pic);
3263
3264         s = PRVM_G_STRING(OFS_PARM0);
3265         PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
3266         VM_CheckEmptyString (s);
3267
3268         // AK Draw_CachePic is supposed to always return a valid pointer
3269         if( Draw_CachePic_Flags(s, 0)->tex == r_texture_notexture )
3270                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
3271 }
3272
3273 /*
3274 =========
3275 VM_freepic
3276
3277 freepic(string s)
3278 =========
3279 */
3280 void VM_freepic(void)
3281 {
3282         const char *s;
3283
3284         VM_SAFEPARMCOUNT(1,VM_freepic);
3285
3286         s = PRVM_G_STRING(OFS_PARM0);
3287         VM_CheckEmptyString (s);
3288
3289         Draw_FreePic(s);
3290 }
3291
3292 void getdrawfontscale(float *sx, float *sy)
3293 {
3294         vec3_t v;
3295         *sx = *sy = 1;
3296         VectorCopy(PRVM_drawglobalvector(drawfontscale), v);
3297         if(VectorLength2(v) > 0)
3298         {
3299                 *sx = v[0];
3300                 *sy = v[1];
3301         }
3302 }
3303
3304 dp_font_t *getdrawfont(void)
3305 {
3306         int f = (int) PRVM_drawglobalfloat(drawfont);
3307         if(f < 0 || f >= dp_fonts.maxsize)
3308                 return FONT_DEFAULT;
3309         return &dp_fonts.f[f];
3310 }
3311
3312 /*
3313 =========
3314 VM_drawcharacter
3315
3316 float   drawcharacter(vector position, float character, vector scale, vector rgb, float alpha, float flag)
3317 =========
3318 */
3319 void VM_drawcharacter(void)
3320 {
3321         float *pos,*scale,*rgb;
3322         char   character;
3323         int flag;
3324         float sx, sy;
3325         VM_SAFEPARMCOUNT(6,VM_drawcharacter);
3326
3327         character = (char) PRVM_G_FLOAT(OFS_PARM1);
3328         if(character == 0)
3329         {
3330                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3331                 VM_Warning("VM_drawcharacter: %s passed null character !\n",PRVM_NAME);
3332                 return;
3333         }
3334
3335         pos = PRVM_G_VECTOR(OFS_PARM0);
3336         scale = PRVM_G_VECTOR(OFS_PARM2);
3337         rgb = PRVM_G_VECTOR(OFS_PARM3);
3338         flag = (int)PRVM_G_FLOAT(OFS_PARM5);
3339
3340         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3341         {
3342                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3343                 VM_Warning("VM_drawcharacter: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3344                 return;
3345         }
3346
3347         if(pos[2] || scale[2])
3348                 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")));
3349
3350         if(!scale[0] || !scale[1])
3351         {
3352                 PRVM_G_FLOAT(OFS_RETURN) = -3;
3353                 VM_Warning("VM_drawcharacter: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
3354                 return;
3355         }
3356
3357         getdrawfontscale(&sx, &sy);
3358         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());
3359         PRVM_G_FLOAT(OFS_RETURN) = 1;
3360 }
3361
3362 /*
3363 =========
3364 VM_drawstring
3365
3366 float   drawstring(vector position, string text, vector scale, vector rgb, float alpha[, float flag])
3367 =========
3368 */
3369 void VM_drawstring(void)
3370 {
3371         float *pos,*scale,*rgb;
3372         const char  *string;
3373         int flag = 0;
3374         float sx, sy;
3375         VM_SAFEPARMCOUNTRANGE(5,6,VM_drawstring);
3376
3377         string = PRVM_G_STRING(OFS_PARM1);
3378         pos = PRVM_G_VECTOR(OFS_PARM0);
3379         scale = PRVM_G_VECTOR(OFS_PARM2);
3380         rgb = PRVM_G_VECTOR(OFS_PARM3);
3381         if (prog->argc >= 6)
3382                 flag = (int)PRVM_G_FLOAT(OFS_PARM5);
3383
3384         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3385         {
3386                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3387                 VM_Warning("VM_drawstring: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3388                 return;
3389         }
3390
3391         if(!scale[0] || !scale[1])
3392         {
3393                 PRVM_G_FLOAT(OFS_RETURN) = -3;
3394                 VM_Warning("VM_drawstring: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
3395                 return;
3396         }
3397
3398         if(pos[2] || scale[2])
3399                 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")));
3400
3401         getdrawfontscale(&sx, &sy);
3402         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());
3403         //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);
3404         PRVM_G_FLOAT(OFS_RETURN) = 1;
3405 }
3406
3407 /*
3408 =========
3409 VM_drawcolorcodedstring
3410
3411 float   drawcolorcodedstring(vector position, string text, vector scale, float alpha, float flag)
3412 /
3413 float   drawcolorcodedstring(vector position, string text, vector scale, vector rgb, float alpha, float flag)
3414 =========
3415 */
3416 void VM_drawcolorcodedstring(void)
3417 {
3418         float *pos, *scale;
3419         const char  *string;
3420         int flag;
3421         vec3_t rgb;
3422         float sx, sy, alpha;
3423
3424         VM_SAFEPARMCOUNTRANGE(5,6,VM_drawcolorcodedstring);
3425
3426         if (prog->argc == 6) // full 6 parms, like normal drawstring
3427         {
3428                 pos = PRVM_G_VECTOR(OFS_PARM0);
3429                 string = PRVM_G_STRING(OFS_PARM1);
3430                 scale = PRVM_G_VECTOR(OFS_PARM2);
3431                 VectorCopy(PRVM_G_VECTOR(OFS_PARM3), rgb); 
3432                 alpha = PRVM_G_FLOAT(OFS_PARM4);
3433                 flag = (int)PRVM_G_FLOAT(OFS_PARM5);
3434         }
3435         else
3436         {
3437                 pos = PRVM_G_VECTOR(OFS_PARM0);
3438                 string = PRVM_G_STRING(OFS_PARM1);
3439                 scale = PRVM_G_VECTOR(OFS_PARM2);
3440                 rgb[0] = 1.0;
3441                 rgb[1] = 1.0;
3442                 rgb[2] = 1.0;
3443                 alpha = PRVM_G_FLOAT(OFS_PARM3);
3444                 flag = (int)PRVM_G_FLOAT(OFS_PARM4);
3445         }
3446
3447         if(flag < DRAWFLAG_NORMAL || flag >= DRAWFLAG_NUMFLAGS)
3448         {
3449                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3450                 VM_Warning("VM_drawcolorcodedstring: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3451                 return;
3452         }
3453
3454         if(!scale[0] || !scale[1])
3455         {
3456                 PRVM_G_FLOAT(OFS_RETURN) = -3;
3457                 VM_Warning("VM_drawcolorcodedstring: scale %s is null !\n", (scale[0] == 0) ? ((scale[1] == 0) ? "x and y" : "x") : "y");
3458                 return;
3459         }
3460
3461         if(pos[2] || scale[2])
3462                 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")));
3463
3464         getdrawfontscale(&sx, &sy);
3465         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());
3466         if (prog->argc == 6) // also return vector of last color
3467                 VectorCopy(DrawQ_Color, PRVM_G_VECTOR(OFS_RETURN));
3468         else
3469                 PRVM_G_FLOAT(OFS_RETURN) = 1;
3470 }
3471 /*
3472 =========
3473 VM_stringwidth
3474
3475 float   stringwidth(string text, float allowColorCodes, float size)
3476 =========
3477 */
3478 void VM_stringwidth(void)
3479 {
3480         const char  *string;
3481         float *szv;
3482         float mult; // sz is intended font size so we can later add freetype support, mult is font size multiplier in pixels per character cell
3483         int colors;
3484         float sx, sy;
3485         size_t maxlen = 0;
3486         VM_SAFEPARMCOUNTRANGE(2,3,VM_drawstring);
3487
3488         getdrawfontscale(&sx, &sy);
3489         if(prog->argc == 3)
3490         {
3491                 szv = PRVM_G_VECTOR(OFS_PARM2);
3492                 mult = 1;
3493         }
3494         else
3495         {
3496                 // we want the width for 8x8 font size, divided by 8
3497                 static float defsize[] = {8, 8};
3498                 szv = defsize;
3499                 mult = 0.125;
3500                 // to make sure snapping is turned off, ALWAYS use a nontrivial scale in this case
3501                 if(sx >= 0.9 && sx <= 1.1)
3502                 {
3503                         mult *= 2;
3504                         sx /= 2;
3505                         sy /= 2;
3506                 }
3507         }
3508
3509         string = PRVM_G_STRING(OFS_PARM0);
3510         colors = (int)PRVM_G_FLOAT(OFS_PARM1);
3511
3512         PRVM_G_FLOAT(OFS_RETURN) = DrawQ_TextWidth_UntilWidth_TrackColors_Scale(string, &maxlen, szv[0], szv[1], sx, sy, NULL, !colors, getdrawfont(), 1000000000) * mult;
3513 /*
3514         if(prog->argc == 3)
3515         {
3516                 mult = sz = PRVM_G_FLOAT(OFS_PARM2);
3517         }
3518         else
3519         {
3520                 sz = 8;
3521                 mult = 1;
3522         }
3523
3524         string = PRVM_G_STRING(OFS_PARM0);
3525         colors = (int)PRVM_G_FLOAT(OFS_PARM1);
3526
3527         PRVM_G_FLOAT(OFS_RETURN) = DrawQ_TextWidth(string, 0, !colors, getdrawfont()) * mult; // 1x1 characters, don't actually draw
3528 */
3529 }
3530
3531 /*
3532 =========
3533 VM_findfont
3534
3535 float findfont(string s)
3536 =========
3537 */
3538
3539 float getdrawfontnum(const char *fontname)
3540 {
3541         int i;
3542
3543         for(i = 0; i < dp_fonts.maxsize; ++i)
3544                 if(!strcmp(dp_fonts.f[i].title, fontname))
3545                         return i;
3546         return -1;
3547 }
3548
3549 void VM_findfont(void)
3550 {
3551         VM_SAFEPARMCOUNT(1,VM_findfont);
3552         PRVM_G_FLOAT(OFS_RETURN) = getdrawfontnum(PRVM_G_STRING(OFS_PARM0));
3553 }
3554
3555 /*
3556 =========
3557 VM_loadfont
3558
3559 float loadfont(string fontname, string fontmaps, string sizes, float slot)
3560 =========
3561 */
3562
3563 dp_font_t *FindFont(const char *title, qboolean allocate_new);
3564 void LoadFont(qboolean override, const char *name, dp_font_t *fnt, float scale, float voffset);
3565 void VM_loadfont(void)
3566 {
3567         const char *fontname, *filelist, *sizes, *c, *cm;
3568         char mainfont[MAX_QPATH];
3569         int i, numsizes;
3570         float sz, scale, voffset;
3571         dp_font_t *f;
3572
3573         VM_SAFEPARMCOUNTRANGE(3,6,VM_loadfont);
3574
3575         fontname = PRVM_G_STRING(OFS_PARM0);
3576         if (!fontname[0])
3577                 fontname = "default";
3578
3579         filelist = PRVM_G_STRING(OFS_PARM1);
3580         if (!filelist[0])
3581                 filelist = "gfx/conchars";
3582
3583         sizes = PRVM_G_STRING(OFS_PARM2);
3584         if (!sizes[0])
3585                 sizes = "10";
3586
3587         // find a font
3588         f = NULL;
3589         if (prog->argc >= 4)
3590         {
3591                 i = PRVM_G_FLOAT(OFS_PARM3);
3592                 if (i >= 0 && i < dp_fonts.maxsize)
3593                 {
3594                         f = &dp_fonts.f[i];
3595                         strlcpy(f->title, fontname, sizeof(f->title)); // replace name
3596                 }
3597         }
3598         if (!f)
3599                 f = FindFont(fontname, true);
3600         if (!f)
3601         {
3602                 PRVM_G_FLOAT(OFS_RETURN) = -1;
3603                 return; // something go wrong
3604         }
3605
3606         memset(f->fallbacks, 0, sizeof(f->fallbacks));
3607         memset(f->fallback_faces, 0, sizeof(f->fallback_faces));
3608
3609         // first font is handled "normally"
3610         c = strchr(filelist, ':');
3611         cm = strchr(filelist, ',');
3612         if(c && (!cm || c < cm))
3613                 f->req_face = atoi(c+1);
3614         else
3615         {
3616                 f->req_face = 0;
3617                 c = cm;
3618         }
3619         if(!c || (c - filelist) > MAX_QPATH)
3620                 strlcpy(mainfont, filelist, sizeof(mainfont));
3621         else
3622         {
3623                 memcpy(mainfont, filelist, c - filelist);
3624                 mainfont[c - filelist] = 0;
3625         }
3626
3627         // handle fallbacks
3628         for(i = 0; i < MAX_FONT_FALLBACKS; ++i)
3629         {
3630                 c = strchr(filelist, ',');
3631                 if(!c)
3632                         break;
3633                 filelist = c + 1;
3634                 if(!*filelist)
3635                         break;
3636                 c = strchr(filelist, ':');
3637                 cm = strchr(filelist, ',');
3638                 if(c && (!cm || c < cm))
3639                         f->fallback_faces[i] = atoi(c+1);
3640                 else
3641                 {
3642                         f->fallback_faces[i] = 0; // f->req_face; could make it stick to the default-font's face index
3643                         c = cm;
3644                 }
3645                 if(!c || (c-filelist) > MAX_QPATH)
3646                 {
3647                         strlcpy(f->fallbacks[i], filelist, sizeof(mainfont));
3648                 }
3649                 else
3650                 {
3651                         memcpy(f->fallbacks[i], filelist, c - filelist);
3652                         f->fallbacks[i][c - filelist] = 0;
3653                 }
3654         }
3655
3656         // handle sizes
3657         for(i = 0; i < MAX_FONT_SIZES; ++i)
3658                 f->req_sizes[i] = -1;
3659         for (numsizes = 0,c = sizes;;)
3660         {
3661                 if (!COM_ParseToken_VM_Tokenize(&c, 0))
3662                         break;
3663                 sz = atof(com_token);
3664                 // detect crap size
3665                 if (sz < 0.001f || sz > 1000.0f)
3666                 {
3667                         VM_Warning("VM_loadfont: crap size %s", com_token);
3668                         continue;
3669                 }
3670                 // check overflow
3671                 if (numsizes == MAX_FONT_SIZES)
3672                 {
3673                         VM_Warning("VM_loadfont: MAX_FONT_SIZES = %i exceeded", MAX_FONT_SIZES);
3674                         break;
3675                 }
3676                 f->req_sizes[numsizes] = sz;
3677                 numsizes++;
3678         }
3679
3680         // additional scale/hoffset parms
3681         scale = 1;
3682         voffset = 0;
3683         if (prog->argc >= 5)
3684         {
3685                 scale = PRVM_G_FLOAT(OFS_PARM4);
3686                 if (scale <= 0)
3687                         scale = 1;
3688         }
3689         if (prog->argc >= 6)
3690                 voffset = PRVM_G_FLOAT(OFS_PARM5);
3691
3692         // load
3693         LoadFont(true, mainfont, f, scale, voffset);
3694
3695         // return index of loaded font
3696         PRVM_G_FLOAT(OFS_RETURN) = (f - dp_fonts.f);
3697 }
3698
3699 /*
3700 =========
3701 VM_drawpic
3702
3703 float   drawpic(vector position, string pic, vector size, vector rgb, float alpha, float flag)
3704 =========
3705 */
3706 void VM_drawpic(void)
3707 {
3708         const char *picname;
3709         float *size, *pos, *rgb;
3710         int flag = 0;
3711
3712         VM_SAFEPARMCOUNTRANGE(5,6,VM_drawpic);
3713
3714         picname = PRVM_G_STRING(OFS_PARM1);
3715         VM_CheckEmptyString (picname);
3716
3717         // is pic cached ? no function yet for that
3718         if(!1)
3719         {
3720                 PRVM_G_FLOAT(OFS_RETURN) = -4;
3721                 VM_Warning("VM_drawpic: %s: %s not cached !\n", PRVM_NAME, picname);
3722                 return;
3723         }
3724
3725         pos = PRVM_G_VECTOR(OFS_PARM0);
3726         size = PRVM_G_VECTOR(OFS_PARM2);
3727         rgb = PRVM_G_VECTOR(OFS_PARM3);
3728         if (prog->argc >= 6)
3729                 flag = (int) PRVM_G_FLOAT(OFS_PARM5);
3730
3731         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3732         {
3733                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3734                 VM_Warning("VM_drawpic: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3735                 return;
3736         }
3737
3738         if(pos[2] || size[2])
3739                 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")));
3740
3741         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);
3742         PRVM_G_FLOAT(OFS_RETURN) = 1;
3743 }
3744 /*
3745 =========
3746 VM_drawrotpic
3747
3748 float   drawrotpic(vector position, string pic, vector size, vector org, float angle, vector rgb, float alpha, float flag)
3749 =========
3750 */
3751 void VM_drawrotpic(void)
3752 {
3753         const char *picname;
3754         float *size, *pos, *org, *rgb;
3755         int flag;
3756
3757         VM_SAFEPARMCOUNT(8,VM_drawrotpic);
3758
3759         picname = PRVM_G_STRING(OFS_PARM1);
3760         VM_CheckEmptyString (picname);
3761
3762         // is pic cached ? no function yet for that
3763         if(!1)
3764         {
3765                 PRVM_G_FLOAT(OFS_RETURN) = -4;
3766                 VM_Warning("VM_drawrotpic: %s: %s not cached !\n", PRVM_NAME, picname);
3767                 return;
3768         }
3769
3770         pos = PRVM_G_VECTOR(OFS_PARM0);
3771         size = PRVM_G_VECTOR(OFS_PARM2);
3772         org = PRVM_G_VECTOR(OFS_PARM3);
3773         rgb = PRVM_G_VECTOR(OFS_PARM5);
3774         flag = (int) PRVM_G_FLOAT(OFS_PARM7);
3775
3776         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3777         {
3778                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3779                 VM_Warning("VM_drawrotpic: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3780                 return;
3781         }
3782
3783         if(pos[2] || size[2] || org[2])
3784                 Con_Printf("VM_drawrotpic: z value from pos/size/org discarded\n");
3785
3786         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);
3787         PRVM_G_FLOAT(OFS_RETURN) = 1;
3788 }
3789 /*
3790 =========
3791 VM_drawsubpic
3792
3793 float   drawsubpic(vector position, vector size, string pic, vector srcPos, vector srcSize, vector rgb, float alpha, float flag)
3794
3795 =========
3796 */
3797 void VM_drawsubpic(void)
3798 {
3799         const char *picname;
3800         float *size, *pos, *rgb, *srcPos, *srcSize, alpha;
3801         int flag;
3802
3803         VM_SAFEPARMCOUNT(8,VM_drawsubpic);
3804
3805         picname = PRVM_G_STRING(OFS_PARM2);
3806         VM_CheckEmptyString (picname);
3807
3808         // is pic cached ? no function yet for that
3809         if(!1)
3810         {
3811                 PRVM_G_FLOAT(OFS_RETURN) = -4;
3812                 VM_Warning("VM_drawsubpic: %s: %s not cached !\n", PRVM_NAME, picname);
3813                 return;
3814         }
3815
3816         pos = PRVM_G_VECTOR(OFS_PARM0);
3817         size = PRVM_G_VECTOR(OFS_PARM1);
3818         srcPos = PRVM_G_VECTOR(OFS_PARM3);
3819         srcSize = PRVM_G_VECTOR(OFS_PARM4);
3820         rgb = PRVM_G_VECTOR(OFS_PARM5);
3821         alpha = PRVM_G_FLOAT(OFS_PARM6);
3822         flag = (int) PRVM_G_FLOAT(OFS_PARM7);
3823
3824         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3825         {
3826                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3827                 VM_Warning("VM_drawsubpic: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3828                 return;
3829         }
3830
3831         if(pos[2] || size[2])
3832                 Con_Printf("VM_drawsubpic: z value%s from %s discarded\n",(pos[2] && size[2]) ? "s" : " ",((pos[2] && size[2]) ? "pos and size" : (pos[2] ? "pos" : "size")));
3833
3834         DrawQ_SuperPic(pos[0], pos[1], Draw_CachePic_Flags (picname, CACHEPICFLAG_NOTPERSISTENT),
3835                 size[0], size[1],
3836                 srcPos[0],              srcPos[1],              rgb[0], rgb[1], rgb[2], alpha,
3837                 srcPos[0] + srcSize[0], srcPos[1],              rgb[0], rgb[1], rgb[2], alpha,
3838                 srcPos[0],              srcPos[1] + srcSize[1], rgb[0], rgb[1], rgb[2], alpha,
3839                 srcPos[0] + srcSize[0], srcPos[1] + srcSize[1], rgb[0], rgb[1], rgb[2], alpha,
3840                 flag);
3841         PRVM_G_FLOAT(OFS_RETURN) = 1;
3842 }
3843
3844 /*
3845 =========
3846 VM_drawfill
3847
3848 float drawfill(vector position, vector size, vector rgb, float alpha, float flag)
3849 =========
3850 */
3851 void VM_drawfill(void)
3852 {
3853         float *size, *pos, *rgb;
3854         int flag;
3855
3856         VM_SAFEPARMCOUNT(5,VM_drawfill);
3857
3858
3859         pos = PRVM_G_VECTOR(OFS_PARM0);
3860         size = PRVM_G_VECTOR(OFS_PARM1);
3861         rgb = PRVM_G_VECTOR(OFS_PARM2);
3862         flag = (int) PRVM_G_FLOAT(OFS_PARM4);
3863
3864         if(flag < DRAWFLAG_NORMAL || flag >=DRAWFLAG_NUMFLAGS)
3865         {
3866                 PRVM_G_FLOAT(OFS_RETURN) = -2;
3867                 VM_Warning("VM_drawfill: %s: wrong DRAWFLAG %i !\n",PRVM_NAME,flag);
3868                 return;
3869         }
3870
3871         if(pos[2] || size[2])
3872                 Con_Printf("VM_drawfill: z value%s from %s discarded\n",(pos[2] && size[2]) ? "s" : " ",((pos[2] && size[2]) ? "pos and size" : (pos[2] ? "pos" : "size")));
3873
3874         DrawQ_Fill(pos[0], pos[1], size[0], size[1], rgb[0], rgb[1], rgb[2], PRVM_G_FLOAT(OFS_PARM3), flag);
3875         PRVM_G_FLOAT(OFS_RETURN) = 1;
3876 }
3877
3878 /*
3879 =========
3880 VM_drawsetcliparea
3881
3882 drawsetcliparea(float x, float y, float width, float height)
3883 =========
3884 */
3885 void VM_drawsetcliparea(void)
3886 {
3887         float x,y,w,h;
3888         VM_SAFEPARMCOUNT(4,VM_drawsetcliparea);
3889
3890         x = bound(0, PRVM_G_FLOAT(OFS_PARM0), vid_conwidth.integer);
3891         y = bound(0, PRVM_G_FLOAT(OFS_PARM1), vid_conheight.integer);
3892         w = bound(0, PRVM_G_FLOAT(OFS_PARM2) + PRVM_G_FLOAT(OFS_PARM0) - x, (vid_conwidth.integer  - x));
3893         h = bound(0, PRVM_G_FLOAT(OFS_PARM3) + PRVM_G_FLOAT(OFS_PARM1) - y, (vid_conheight.integer - y));
3894
3895         DrawQ_SetClipArea(x, y, w, h);
3896 }
3897
3898 /*
3899 =========
3900 VM_drawresetcliparea
3901
3902 drawresetcliparea()
3903 =========
3904 */
3905 void VM_drawresetcliparea(void)
3906 {
3907         VM_SAFEPARMCOUNT(0,VM_drawresetcliparea);
3908
3909         DrawQ_ResetClipArea();
3910 }
3911
3912 /*
3913 =========
3914 VM_getimagesize
3915
3916 vector  getimagesize(string pic)
3917 =========
3918 */
3919 void VM_getimagesize(void)
3920 {
3921         const char *p;
3922         cachepic_t *pic;
3923
3924         VM_SAFEPARMCOUNT(1,VM_getimagesize);
3925
3926         p = PRVM_G_STRING(OFS_PARM0);
3927         VM_CheckEmptyString (p);
3928
3929         pic = Draw_CachePic_Flags (p, CACHEPICFLAG_NOTPERSISTENT);
3930
3931         PRVM_G_VECTOR(OFS_RETURN)[0] = pic->width;
3932         PRVM_G_VECTOR(OFS_RETURN)[1] = pic->height;
3933         PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
3934 }
3935
3936 /*
3937 =========
3938 VM_keynumtostring
3939
3940 string keynumtostring(float keynum)
3941 =========
3942 */
3943 void VM_keynumtostring (void)
3944 {
3945         VM_SAFEPARMCOUNT(1, VM_keynumtostring);
3946
3947         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(Key_KeynumToString((int)PRVM_G_FLOAT(OFS_PARM0)));
3948 }
3949
3950 /*
3951 =========
3952 VM_findkeysforcommand
3953
3954 string  findkeysforcommand(string command, float bindmap)
3955
3956 the returned string is an altstring
3957 =========
3958 */
3959 #define FKFC_NUMKEYS 5
3960 void M_FindKeysForCommand(const char *command, int *keys);
3961 void VM_findkeysforcommand(void)
3962 {
3963         const char *cmd;
3964         char ret[VM_STRINGTEMP_LENGTH];
3965         int keys[FKFC_NUMKEYS];
3966         int i;
3967         int bindmap;
3968
3969         VM_SAFEPARMCOUNTRANGE(1, 2, VM_findkeysforcommand);
3970
3971         cmd = PRVM_G_STRING(OFS_PARM0);
3972         if(prog->argc == 2)
3973                 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM1), MAX_BINDMAPS-1);
3974         else
3975                 bindmap = 0; // consistent to "bind"
3976
3977         VM_CheckEmptyString(cmd);
3978
3979         Key_FindKeysForCommand(cmd, keys, FKFC_NUMKEYS, bindmap);
3980
3981         ret[0] = 0;
3982         for(i = 0; i < FKFC_NUMKEYS; i++)
3983                 strlcat(ret, va(" \'%i\'", keys[i]), sizeof(ret));
3984
3985         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(ret);
3986 }
3987
3988 /*
3989 =========
3990 VM_stringtokeynum
3991
3992 float stringtokeynum(string key)
3993 =========
3994 */
3995 void VM_stringtokeynum (void)
3996 {
3997         VM_SAFEPARMCOUNT( 1, VM_keynumtostring );
3998
3999         PRVM_G_FLOAT(OFS_RETURN) = Key_StringToKeynum(PRVM_G_STRING(OFS_PARM0));
4000 }
4001
4002 /*
4003 =========
4004 VM_getkeybind
4005
4006 string getkeybind(float key, float bindmap)
4007 =========
4008 */
4009 void VM_getkeybind (void)
4010 {
4011         int bindmap;
4012         VM_SAFEPARMCOUNTRANGE(1, 2, VM_CL_getkeybind);
4013         if(prog->argc == 2)
4014                 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM1), MAX_BINDMAPS-1);
4015         else
4016                 bindmap = 0; // consistent to "bind"
4017
4018         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(Key_GetBind((int)PRVM_G_FLOAT(OFS_PARM0), bindmap));
4019 }
4020
4021 /*
4022 =========
4023 VM_setkeybind
4024
4025 float setkeybind(float key, string cmd, float bindmap)
4026 =========
4027 */
4028 void VM_setkeybind (void)
4029 {
4030         int bindmap;
4031         VM_SAFEPARMCOUNTRANGE(2, 3, VM_CL_setkeybind);
4032         if(prog->argc == 3)
4033                 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM2), MAX_BINDMAPS-1);
4034         else
4035                 bindmap = 0; // consistent to "bind"
4036
4037         PRVM_G_FLOAT(OFS_RETURN) = 0;
4038         if(Key_SetBinding((int)PRVM_G_FLOAT(OFS_PARM0), bindmap, PRVM_G_STRING(OFS_PARM1)))
4039                 PRVM_G_FLOAT(OFS_RETURN) = 1;
4040 }
4041
4042 /*
4043 =========
4044 VM_getbindmap
4045
4046 vector getbindmaps()
4047 =========
4048 */
4049 void VM_getbindmaps (void)
4050 {
4051         int fg, bg;
4052         VM_SAFEPARMCOUNT(0, VM_CL_getbindmap);
4053         Key_GetBindMap(&fg, &bg);
4054         PRVM_G_VECTOR(OFS_RETURN)[0] = fg;
4055         PRVM_G_VECTOR(OFS_RETURN)[1] = bg;
4056         PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
4057 }
4058
4059 /*
4060 =========
4061 VM_setbindmap
4062
4063 float setbindmaps(vector bindmap)
4064 =========
4065 */
4066 void VM_setbindmaps (void)
4067 {
4068         VM_SAFEPARMCOUNT(1, VM_CL_setbindmap);
4069         PRVM_G_FLOAT(OFS_RETURN) = 0;
4070         if(PRVM_G_VECTOR(OFS_PARM0)[2] == 0)
4071                 if(Key_SetBindMap((int)PRVM_G_VECTOR(OFS_PARM0)[0], (int)PRVM_G_VECTOR(OFS_PARM0)[1]))
4072                         PRVM_G_FLOAT(OFS_RETURN) = 1;
4073 }
4074
4075 // CL_Video interface functions
4076
4077 /*
4078 ========================
4079 VM_cin_open
4080
4081 float cin_open(string file, string name)
4082 ========================
4083 */
4084 void VM_cin_open( void )
4085 {
4086         const char *file;
4087         const char *name;
4088
4089         VM_SAFEPARMCOUNT( 2, VM_cin_open );
4090
4091         file = PRVM_G_STRING( OFS_PARM0 );
4092         name = PRVM_G_STRING( OFS_PARM1 );
4093
4094         VM_CheckEmptyString( file );
4095     VM_CheckEmptyString( name );
4096
4097         if( CL_OpenVideo( file, name, MENUOWNER, "" ) )
4098                 PRVM_G_FLOAT( OFS_RETURN ) = 1;
4099         else
4100                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
4101 }
4102
4103 /*
4104 ========================
4105 VM_cin_close
4106
4107 void cin_close(string name)
4108 ========================
4109 */
4110 void VM_cin_close( void )
4111 {
4112         const char *name;
4113
4114         VM_SAFEPARMCOUNT( 1, VM_cin_close );
4115
4116         name = PRVM_G_STRING( OFS_PARM0 );
4117         VM_CheckEmptyString( name );
4118
4119         CL_CloseVideo( CL_GetVideoByName( name ) );
4120 }
4121
4122 /*
4123 ========================
4124 VM_cin_setstate
4125 void cin_setstate(string name, float type)
4126 ========================
4127 */
4128 void VM_cin_setstate( void )
4129 {
4130         const char *name;
4131         clvideostate_t  state;
4132         clvideo_t               *video;
4133
4134         VM_SAFEPARMCOUNT( 2, VM_cin_netstate );
4135
4136         name = PRVM_G_STRING( OFS_PARM0 );
4137         VM_CheckEmptyString( name );
4138
4139         state = (clvideostate_t)((int)PRVM_G_FLOAT( OFS_PARM1 ));
4140
4141         video = CL_GetVideoByName( name );
4142         if( video && state > CLVIDEO_UNUSED && state < CLVIDEO_STATECOUNT )
4143                 CL_SetVideoState( video, state );
4144 }
4145
4146 /*
4147 ========================
4148 VM_cin_getstate
4149
4150 float cin_getstate(string name)
4151 ========================
4152 */
4153 void VM_cin_getstate( void )
4154 {
4155         const char *name;
4156         clvideo_t               *video;
4157
4158         VM_SAFEPARMCOUNT( 1, VM_cin_getstate );
4159
4160         name = PRVM_G_STRING( OFS_PARM0 );
4161         VM_CheckEmptyString( name );
4162
4163         video = CL_GetVideoByName( name );
4164         if( video )
4165                 PRVM_G_FLOAT( OFS_RETURN ) = (int)video->state;
4166         else
4167                 PRVM_G_FLOAT( OFS_RETURN ) = 0;
4168 }
4169
4170 /*
4171 ========================
4172 VM_cin_restart
4173
4174 void cin_restart(string name)
4175 ========================
4176 */
4177 void VM_cin_restart( void )
4178 {
4179         const char *name;
4180         clvideo_t               *video;
4181
4182         VM_SAFEPARMCOUNT( 1, VM_cin_restart );
4183
4184         name = PRVM_G_STRING( OFS_PARM0 );
4185         VM_CheckEmptyString( name );
4186
4187         video = CL_GetVideoByName( name );
4188         if( video )
4189                 CL_RestartVideo( video );
4190 }
4191
4192 /*
4193 ========================
4194 VM_Gecko_Init
4195 ========================
4196 */
4197 void VM_Gecko_Init( void ) {
4198         // REMOVED
4199 }
4200
4201 /*
4202 ========================
4203 VM_Gecko_Destroy
4204 ========================
4205 */
4206 void VM_Gecko_Destroy( void ) {
4207         // REMOVED
4208 }
4209
4210 /*
4211 ========================
4212 VM_gecko_create
4213
4214 float[bool] gecko_create( string name )
4215 ========================
4216 */
4217 void VM_gecko_create( void ) {
4218         // REMOVED
4219         PRVM_G_FLOAT( OFS_RETURN ) = 0;
4220 }
4221
4222 /*
4223 ========================
4224 VM_gecko_destroy
4225
4226 void gecko_destroy( string name )
4227 ========================
4228 */
4229 void VM_gecko_destroy( void ) {
4230         // REMOVED
4231 }
4232
4233 /*
4234 ========================
4235 VM_gecko_navigate
4236
4237 void gecko_navigate( string name, string URI )
4238 ========================
4239 */
4240 void VM_gecko_navigate( void ) {
4241         // REMOVED
4242 }
4243
4244 /*
4245 ========================
4246 VM_gecko_keyevent
4247
4248 float[bool] gecko_keyevent( string name, float key, float eventtype ) 
4249 ========================
4250 */
4251 void VM_gecko_keyevent( void ) {
4252         // REMOVED
4253         PRVM_G_FLOAT( OFS_RETURN ) = 0;
4254 }
4255
4256 /*
4257 ========================
4258 VM_gecko_movemouse
4259
4260 void gecko_mousemove( string name, float x, float y )
4261 ========================
4262 */
4263 void VM_gecko_movemouse( void ) {
4264         // REMOVED
4265 }
4266
4267
4268 /*
4269 ========================
4270 VM_gecko_resize
4271
4272 void gecko_resize( string name, float w, float h )
4273 ========================
4274 */
4275 void VM_gecko_resize( void ) {
4276         // REMOVED
4277 }
4278
4279
4280 /*
4281 ========================
4282 VM_gecko_get_texture_extent
4283
4284 vector gecko_get_texture_extent( string name )
4285 ========================
4286 */
4287 void VM_gecko_get_texture_extent( void ) {
4288         // REMOVED
4289         PRVM_G_VECTOR(OFS_RETURN)[0] = 0;
4290         PRVM_G_VECTOR(OFS_RETURN)[1] = 0;
4291 }
4292
4293
4294
4295 /*
4296 ==============
4297 VM_makevectors
4298
4299 Writes new values for v_forward, v_up, and v_right based on angles
4300 void makevectors(vector angle)
4301 ==============
4302 */
4303 void VM_makevectors (void)
4304 {
4305         VM_SAFEPARMCOUNT(1, VM_makevectors);
4306         AngleVectors(PRVM_G_VECTOR(OFS_PARM0), PRVM_gameglobalvector(v_forward), PRVM_gameglobalvector(v_right), PRVM_gameglobalvector(v_up));
4307 }
4308
4309 /*
4310 ==============
4311 VM_vectorvectors
4312
4313 Writes new values for v_forward, v_up, and v_right based on the given forward vector
4314 vectorvectors(vector)
4315 ==============
4316 */
4317 void VM_vectorvectors (void)
4318 {
4319         VM_SAFEPARMCOUNT(1, VM_vectorvectors);
4320         VectorNormalize2(PRVM_G_VECTOR(OFS_PARM0), PRVM_gameglobalvector(v_forward));
4321         VectorVectors(PRVM_gameglobalvector(v_forward), PRVM_gameglobalvector(v_right), PRVM_gameglobalvector(v_up));
4322 }
4323
4324 /*
4325 ========================
4326 VM_drawline
4327
4328 void drawline(float width, vector pos1, vector pos2, vector rgb, float alpha, float flags)
4329 ========================
4330 */
4331 void VM_drawline (void)
4332 {
4333         float   *c1, *c2, *rgb;
4334         float   alpha, width;
4335         unsigned char   flags;
4336
4337         VM_SAFEPARMCOUNT(6, VM_drawline);
4338         width   = PRVM_G_FLOAT(OFS_PARM0);
4339         c1              = PRVM_G_VECTOR(OFS_PARM1);
4340         c2              = PRVM_G_VECTOR(OFS_PARM2);
4341         rgb             = PRVM_G_VECTOR(OFS_PARM3);
4342         alpha   = PRVM_G_FLOAT(OFS_PARM4);
4343         flags   = (int)PRVM_G_FLOAT(OFS_PARM5);
4344         DrawQ_Line(width, c1[0], c1[1], c2[0], c2[1], rgb[0], rgb[1], rgb[2], alpha, flags);
4345 }
4346
4347 // float(float number, float quantity) bitshift (EXT_BITSHIFT)
4348 void VM_bitshift (void)
4349 {
4350         int n1, n2;
4351         VM_SAFEPARMCOUNT(2, VM_bitshift);
4352
4353         n1 = (int)fabs((float)((int)PRVM_G_FLOAT(OFS_PARM0)));
4354         n2 = (int)PRVM_G_FLOAT(OFS_PARM1);
4355         if(!n1)
4356                 PRVM_G_FLOAT(OFS_RETURN) = n1;
4357         else
4358         if(n2 < 0)
4359                 PRVM_G_FLOAT(OFS_RETURN) = (n1 >> -n2);
4360         else
4361                 PRVM_G_FLOAT(OFS_RETURN) = (n1 << n2);
4362 }
4363
4364 ////////////////////////////////////////
4365 // AltString functions
4366 ////////////////////////////////////////
4367
4368 /*
4369 ========================
4370 VM_altstr_count
4371
4372 float altstr_count(string)
4373 ========================
4374 */
4375 void VM_altstr_count( void )
4376 {
4377         const char *altstr, *pos;
4378         int     count;
4379
4380         VM_SAFEPARMCOUNT( 1, VM_altstr_count );
4381
4382         altstr = PRVM_G_STRING( OFS_PARM0 );
4383         //VM_CheckEmptyString( altstr );
4384
4385         for( count = 0, pos = altstr ; *pos ; pos++ ) {
4386                 if( *pos == '\\' ) {
4387                         if( !*++pos ) {
4388                                 break;
4389                         }
4390                 } else if( *pos == '\'' ) {
4391                         count++;
4392                 }
4393         }
4394
4395         PRVM_G_FLOAT( OFS_RETURN ) = (float) (count / 2);
4396 }
4397
4398 /*
4399 ========================
4400 VM_altstr_prepare
4401
4402 string altstr_prepare(string)
4403 ========================
4404 */
4405 void VM_altstr_prepare( void )
4406 {
4407         char *out;
4408         const char *instr, *in;
4409         int size;
4410         char outstr[VM_STRINGTEMP_LENGTH];
4411
4412         VM_SAFEPARMCOUNT( 1, VM_altstr_prepare );
4413
4414         instr = PRVM_G_STRING( OFS_PARM0 );
4415
4416         for( out = outstr, in = instr, size = sizeof(outstr) - 1 ; size && *in ; size--, in++, out++ )
4417                 if( *in == '\'' ) {
4418                         *out++ = '\\';
4419                         *out = '\'';
4420                         size--;
4421                 } else
4422                         *out = *in;
4423         *out = 0;
4424
4425         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString( outstr );
4426 }
4427
4428 /*
4429 ========================
4430 VM_altstr_get
4431
4432 string altstr_get(string, float)
4433 ========================
4434 */
4435 void VM_altstr_get( void )
4436 {
4437         const char *altstr, *pos;
4438         char *out;
4439         int count, size;
4440         char outstr[VM_STRINGTEMP_LENGTH];
4441
4442         VM_SAFEPARMCOUNT( 2, VM_altstr_get );
4443
4444         altstr = PRVM_G_STRING( OFS_PARM0 );
4445
4446         count = (int)PRVM_G_FLOAT( OFS_PARM1 );
4447         count = count * 2 + 1;
4448
4449         for( pos = altstr ; *pos && count ; pos++ )
4450                 if( *pos == '\\' ) {
4451                         if( !*++pos )
4452                                 break;
4453                 } else if( *pos == '\'' )
4454                         count--;
4455
4456         if( !*pos ) {
4457                 PRVM_G_INT( OFS_RETURN ) = 0;
4458                 return;
4459         }
4460
4461         for( out = outstr, size = sizeof(outstr) - 1 ; size && *pos ; size--, pos++, out++ )
4462                 if( *pos == '\\' ) {
4463                         if( !*++pos )
4464                                 break;
4465                         *out = *pos;
4466                         size--;
4467                 } else if( *pos == '\'' )
4468                         break;
4469                 else
4470                         *out = *pos;
4471
4472         *out = 0;
4473         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString( outstr );
4474 }
4475
4476 /*
4477 ========================
4478 VM_altstr_set
4479
4480 string altstr_set(string altstr, float num, string set)
4481 ========================
4482 */
4483 void VM_altstr_set( void )
4484 {
4485     int num;
4486         const char *altstr, *str;
4487         const char *in;
4488         char *out;
4489         char outstr[VM_STRINGTEMP_LENGTH];
4490
4491         VM_SAFEPARMCOUNT( 3, VM_altstr_set );
4492
4493         altstr = PRVM_G_STRING( OFS_PARM0 );
4494
4495         num = (int)PRVM_G_FLOAT( OFS_PARM1 );
4496
4497         str = PRVM_G_STRING( OFS_PARM2 );
4498
4499         out = outstr;
4500         for( num = num * 2 + 1, in = altstr; *in && num; *out++ = *in++ )
4501                 if( *in == '\\' ) {
4502                         if( !*++in ) {
4503                                 break;
4504                         }
4505                 } else if( *in == '\'' ) {
4506                         num--;
4507                 }
4508
4509         // copy set in
4510         for( ; *str; *out++ = *str++ );
4511         // now jump over the old content
4512         for( ; *in ; in++ )
4513                 if( *in == '\'' || (*in == '\\' && !*++in) )
4514                         break;
4515
4516         strlcpy(out, in, outstr + sizeof(outstr) - out);
4517         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString( outstr );
4518 }
4519
4520 /*
4521 ========================
4522 VM_altstr_ins
4523 insert after num
4524 string  altstr_ins(string altstr, float num, string set)
4525 ========================
4526 */
4527 void VM_altstr_ins(void)
4528 {
4529         int num;
4530         const char *set;
4531         const char *in;
4532         char *out;
4533         char outstr[VM_STRINGTEMP_LENGTH];
4534
4535         VM_SAFEPARMCOUNT(3, VM_altstr_ins);
4536
4537         in = PRVM_G_STRING( OFS_PARM0 );
4538         num = (int)PRVM_G_FLOAT( OFS_PARM1 );
4539         set = PRVM_G_STRING( OFS_PARM2 );
4540
4541         out = outstr;
4542         for( num = num * 2 + 2 ; *in && num > 0 ; *out++ = *in++ )
4543                 if( *in == '\\' ) {
4544                         if( !*++in ) {
4545                                 break;
4546                         }
4547                 } else if( *in == '\'' ) {
4548                         num--;
4549                 }
4550
4551         *out++ = '\'';
4552         for( ; *set ; *out++ = *set++ );
4553         *out++ = '\'';
4554
4555         strlcpy(out, in, outstr + sizeof(outstr) - out);
4556         PRVM_G_INT( OFS_RETURN ) = PRVM_SetTempString( outstr );
4557 }
4558
4559
4560 ////////////////////////////////////////
4561 // BufString functions
4562 ////////////////////////////////////////
4563 //[515]: string buffers support
4564
4565 static size_t stringbuffers_sortlength;
4566
4567 static void BufStr_Expand(prvm_stringbuffer_t *stringbuffer, int strindex)
4568 {
4569         if (stringbuffer->max_strings <= strindex)
4570         {
4571                 char **oldstrings = stringbuffer->strings;
4572                 stringbuffer->max_strings = max(stringbuffer->max_strings * 2, 128);
4573                 while (stringbuffer->max_strings <= strindex)
4574                         stringbuffer->max_strings *= 2;
4575                 stringbuffer->strings = (char **) Mem_Alloc(prog->progs_mempool, stringbuffer->max_strings * sizeof(stringbuffer->strings[0]));
4576                 if (stringbuffer->num_strings > 0)
4577                         memcpy(stringbuffer->strings, oldstrings, stringbuffer->num_strings * sizeof(stringbuffer->strings[0]));
4578                 if (oldstrings)
4579                         Mem_Free(oldstrings);
4580         }
4581 }
4582
4583 static void BufStr_Shrink(prvm_stringbuffer_t *stringbuffer)
4584 {
4585         // reduce num_strings if there are empty string slots at the end
4586         while (stringbuffer->num_strings > 0 && stringbuffer->strings[stringbuffer->num_strings - 1] == NULL)
4587                 stringbuffer->num_strings--;
4588
4589         // if empty, free the string pointer array
4590         if (stringbuffer->num_strings == 0)
4591         {
4592                 stringbuffer->max_strings = 0;
4593                 if (stringbuffer->strings)
4594                         Mem_Free(stringbuffer->strings);
4595                 stringbuffer->strings = NULL;
4596         }
4597 }
4598
4599 static int BufStr_SortStringsUP (const void *in1, const void *in2)
4600 {
4601         const char *a, *b;
4602         a = *((const char **) in1);
4603         b = *((const char **) in2);
4604         if(!a || !a[0]) return 1;
4605         if(!b || !b[0]) return -1;
4606         return strncmp(a, b, stringbuffers_sortlength);
4607 }
4608
4609 static int BufStr_SortStringsDOWN (const void *in1, const void *in2)
4610 {
4611         const char *a, *b;
4612         a = *((const char **) in1);
4613         b = *((const char **) in2);
4614         if(!a || !a[0]) return 1;
4615         if(!b || !b[0]) return -1;
4616         return strncmp(b, a, stringbuffers_sortlength);
4617 }
4618
4619 /*
4620 ========================
4621 VM_buf_create
4622 creates new buffer, and returns it's index, returns -1 if failed
4623 float buf_create(void) = #460;
4624 float newbuf(string format, float flags) = #460;
4625 ========================
4626 */
4627
4628 void VM_buf_create (void)
4629 {
4630         prvm_stringbuffer_t *stringbuffer;
4631         int i;
4632         
4633         VM_SAFEPARMCOUNTRANGE(0, 2, VM_buf_create);
4634
4635         // VorteX: optional parm1 (buffer format) is unfinished, to keep intact with future databuffers extension must be set to "string"
4636         if(prog->argc >= 1 && strcmp(PRVM_G_STRING(OFS_PARM0), "string"))
4637         {
4638                 PRVM_G_FLOAT(OFS_RETURN) = -1;
4639                 return;
4640         }
4641         stringbuffer = (prvm_stringbuffer_t *) Mem_ExpandableArray_AllocRecord(&prog->stringbuffersarray);
4642         for (i = 0;stringbuffer != Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, i);i++);
4643         stringbuffer->origin = PRVM_AllocationOrigin();
4644         // optional flags parm
4645         if (prog->argc >= 2)
4646                 stringbuffer->flags = (int)PRVM_G_FLOAT(OFS_PARM1) & 0xFF;
4647         PRVM_G_FLOAT(OFS_RETURN) = i;
4648 }
4649
4650
4651
4652 /*
4653 ========================
4654 VM_buf_del
4655 deletes buffer and all strings in it
4656 void buf_del(float bufhandle) = #461;
4657 ========================
4658 */
4659 void VM_buf_del (void)
4660 {
4661         prvm_stringbuffer_t *stringbuffer;
4662         VM_SAFEPARMCOUNT(1, VM_buf_del);
4663         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4664         if (stringbuffer)
4665         {
4666                 int i;
4667                 for (i = 0;i < stringbuffer->num_strings;i++)
4668                         if (stringbuffer->strings[i])
4669                                 Mem_Free(stringbuffer->strings[i]);
4670                 if (stringbuffer->strings)
4671                         Mem_Free(stringbuffer->strings);
4672                 if(stringbuffer->origin)
4673                         PRVM_Free((char *)stringbuffer->origin);
4674                 Mem_ExpandableArray_FreeRecord(&prog->stringbuffersarray, stringbuffer);
4675         }
4676         else
4677         {
4678                 VM_Warning("VM_buf_del: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4679                 return;
4680         }
4681 }
4682
4683 /*
4684 ========================
4685 VM_buf_getsize
4686 how many strings are stored in buffer
4687 float buf_getsize(float bufhandle) = #462;
4688 ========================
4689 */
4690 void VM_buf_getsize (void)
4691 {
4692         prvm_stringbuffer_t *stringbuffer;
4693         VM_SAFEPARMCOUNT(1, VM_buf_getsize);
4694
4695         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4696         if(!stringbuffer)
4697         {
4698                 PRVM_G_FLOAT(OFS_RETURN) = -1;
4699                 VM_Warning("VM_buf_getsize: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4700                 return;
4701         }
4702         else
4703                 PRVM_G_FLOAT(OFS_RETURN) = stringbuffer->num_strings;
4704 }
4705
4706 /*
4707 ========================
4708 VM_buf_copy
4709 copy all content from one buffer to another, make sure it exists
4710 void buf_copy(float bufhandle_from, float bufhandle_to) = #463;
4711 ========================
4712 */
4713 void VM_buf_copy (void)
4714 {
4715         prvm_stringbuffer_t *srcstringbuffer, *dststringbuffer;
4716         int i;
4717         VM_SAFEPARMCOUNT(2, VM_buf_copy);
4718
4719         srcstringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4720         if(!srcstringbuffer)
4721         {
4722                 VM_Warning("VM_buf_copy: invalid source buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4723                 return;
4724         }
4725         i = (int)PRVM_G_FLOAT(OFS_PARM1);
4726         if(i == (int)PRVM_G_FLOAT(OFS_PARM0))
4727         {
4728                 VM_Warning("VM_buf_copy: source == destination (%i) in %s\n", i, PRVM_NAME);
4729                 return;
4730         }
4731         dststringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4732         if(!dststringbuffer)
4733         {
4734                 VM_Warning("VM_buf_copy: invalid destination buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), PRVM_NAME);
4735                 return;
4736         }
4737
4738         for (i = 0;i < dststringbuffer->num_strings;i++)
4739                 if (dststringbuffer->strings[i])
4740                         Mem_Free(dststringbuffer->strings[i]);
4741         if (dststringbuffer->strings)
4742                 Mem_Free(dststringbuffer->strings);
4743         *dststringbuffer = *srcstringbuffer;
4744         if (dststringbuffer->max_strings)
4745                 dststringbuffer->strings = (char **)Mem_Alloc(prog->progs_mempool, sizeof(dststringbuffer->strings[0]) * dststringbuffer->max_strings);
4746
4747         for (i = 0;i < dststringbuffer->num_strings;i++)
4748         {
4749                 if (srcstringbuffer->strings[i])
4750                 {
4751                         size_t stringlen;
4752                         stringlen = strlen(srcstringbuffer->strings[i]) + 1;
4753                         dststringbuffer->strings[i] = (char *)Mem_Alloc(prog->progs_mempool, stringlen);
4754                         memcpy(dststringbuffer->strings[i], srcstringbuffer->strings[i], stringlen);
4755                 }
4756         }
4757 }
4758
4759 /*
4760 ========================
4761 VM_buf_sort
4762 sort buffer by beginnings of strings (cmplength defaults it's length)
4763 "backward == TRUE" means that sorting goes upside-down
4764 void buf_sort(float bufhandle, float cmplength, float backward) = #464;
4765 ========================
4766 */
4767 void VM_buf_sort (void)
4768 {
4769         prvm_stringbuffer_t *stringbuffer;
4770         VM_SAFEPARMCOUNT(3, VM_buf_sort);
4771
4772         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4773         if(!stringbuffer)
4774         {
4775                 VM_Warning("VM_buf_sort: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4776                 return;
4777         }
4778         if(stringbuffer->num_strings <= 0)
4779         {
4780                 VM_Warning("VM_buf_sort: tried to sort empty buffer %i in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4781                 return;
4782         }
4783         stringbuffers_sortlength = (int)PRVM_G_FLOAT(OFS_PARM1);
4784         if(stringbuffers_sortlength <= 0)
4785                 stringbuffers_sortlength = 0x7FFFFFFF;
4786
4787         if(!PRVM_G_FLOAT(OFS_PARM2))
4788                 qsort(stringbuffer->strings, stringbuffer->num_strings, sizeof(char*), BufStr_SortStringsUP);
4789         else
4790                 qsort(stringbuffer->strings, stringbuffer->num_strings, sizeof(char*), BufStr_SortStringsDOWN);
4791
4792         BufStr_Shrink(stringbuffer);
4793 }
4794
4795 /*
4796 ========================
4797 VM_buf_implode
4798 concantenates all buffer string into one with "glue" separator and returns it as tempstring
4799 string buf_implode(float bufhandle, string glue) = #465;
4800 ========================
4801 */
4802 void VM_buf_implode (void)
4803 {
4804         prvm_stringbuffer_t *stringbuffer;
4805         char                    k[VM_STRINGTEMP_LENGTH];
4806         const char              *sep;
4807         int                             i;
4808         size_t                  l;
4809         VM_SAFEPARMCOUNT(2, VM_buf_implode);
4810
4811         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4812         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
4813         if(!stringbuffer)
4814         {
4815                 VM_Warning("VM_buf_implode: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4816                 return;
4817         }
4818         if(!stringbuffer->num_strings)
4819                 return;
4820         sep = PRVM_G_STRING(OFS_PARM1);
4821         k[0] = 0;
4822         for(l = i = 0;i < stringbuffer->num_strings;i++)
4823         {
4824                 if(stringbuffer->strings[i])
4825                 {
4826                         l += (i > 0 ? strlen(sep) : 0) + strlen(stringbuffer->strings[i]);
4827                         if (l >= sizeof(k) - 1)
4828                                 break;
4829                         strlcat(k, sep, sizeof(k));
4830                         strlcat(k, stringbuffer->strings[i], sizeof(k));
4831                 }
4832         }
4833         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(k);
4834 }
4835
4836 /*
4837 ========================
4838 VM_bufstr_get
4839 get a string from buffer, returns tempstring, dont str_unzone it!
4840 string bufstr_get(float bufhandle, float string_index) = #465;
4841 ========================
4842 */
4843 void VM_bufstr_get (void)
4844 {
4845         prvm_stringbuffer_t *stringbuffer;
4846         int                             strindex;
4847         VM_SAFEPARMCOUNT(2, VM_bufstr_get);
4848
4849         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
4850         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4851         if(!stringbuffer)
4852         {
4853                 VM_Warning("VM_bufstr_get: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4854                 return;
4855         }
4856         strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
4857         if (strindex < 0)
4858         {
4859                 // VM_Warning("VM_bufstr_get: invalid string index %i used in %s\n", strindex, PRVM_NAME);
4860                 return;
4861         }
4862         if (strindex < stringbuffer->num_strings && stringbuffer->strings[strindex])
4863                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(stringbuffer->strings[strindex]);
4864 }
4865
4866 /*
4867 ========================
4868 VM_bufstr_set
4869 copies a string into selected slot of buffer
4870 void bufstr_set(float bufhandle, float string_index, string str) = #466;
4871 ========================
4872 */
4873 void VM_bufstr_set (void)
4874 {
4875         size_t alloclen;
4876         int                             strindex;
4877         prvm_stringbuffer_t *stringbuffer;
4878         const char              *news;
4879
4880         VM_SAFEPARMCOUNT(3, VM_bufstr_set);
4881
4882         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4883         if(!stringbuffer)
4884         {
4885                 VM_Warning("VM_bufstr_set: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4886                 return;
4887         }
4888         strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
4889         if(strindex < 0 || strindex >= 1000000) // huge number of strings
4890         {
4891                 VM_Warning("VM_bufstr_set: invalid string index %i used in %s\n", strindex, PRVM_NAME);
4892                 return;
4893         }
4894
4895         BufStr_Expand(stringbuffer, strindex);
4896         stringbuffer->num_strings = max(stringbuffer->num_strings, strindex + 1);
4897
4898         if(stringbuffer->strings[strindex])
4899                 Mem_Free(stringbuffer->strings[strindex]);
4900         stringbuffer->strings[strindex] = NULL;
4901
4902         if(PRVM_G_INT(OFS_PARM2))
4903         {
4904                 // not the NULL string!
4905                 news = PRVM_G_STRING(OFS_PARM2);
4906                 alloclen = strlen(news) + 1;
4907                 stringbuffer->strings[strindex] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
4908                 memcpy(stringbuffer->strings[strindex], news, alloclen);
4909         }
4910
4911         BufStr_Shrink(stringbuffer);
4912 }
4913
4914 /*
4915 ========================
4916 VM_bufstr_add
4917 adds string to buffer in first free slot and returns its index
4918 "order == TRUE" means that string will be added after last "full" slot
4919 float bufstr_add(float bufhandle, string str, float order) = #467;
4920 ========================
4921 */
4922 void VM_bufstr_add (void)
4923 {
4924         int                             order, strindex;
4925         prvm_stringbuffer_t *stringbuffer;
4926         const char              *string;
4927         size_t                  alloclen;
4928
4929         VM_SAFEPARMCOUNT(3, VM_bufstr_add);
4930
4931         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4932         PRVM_G_FLOAT(OFS_RETURN) = -1;
4933         if(!stringbuffer)
4934         {
4935                 VM_Warning("VM_bufstr_add: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4936                 return;
4937         }
4938         if(!PRVM_G_INT(OFS_PARM1)) // NULL string
4939         {
4940                 VM_Warning("VM_bufstr_add: can not add an empty string to buffer %i in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4941                 return;
4942         }
4943         string = PRVM_G_STRING(OFS_PARM1);
4944         order = (int)PRVM_G_FLOAT(OFS_PARM2);
4945         if(order)
4946                 strindex = stringbuffer->num_strings;
4947         else
4948                 for (strindex = 0;strindex < stringbuffer->num_strings;strindex++)
4949                         if (stringbuffer->strings[strindex] == NULL)
4950                                 break;
4951
4952         BufStr_Expand(stringbuffer, strindex);
4953
4954         stringbuffer->num_strings = max(stringbuffer->num_strings, strindex + 1);
4955         alloclen = strlen(string) + 1;
4956         stringbuffer->strings[strindex] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
4957         memcpy(stringbuffer->strings[strindex], string, alloclen);
4958
4959         PRVM_G_FLOAT(OFS_RETURN) = strindex;
4960 }
4961
4962 /*
4963 ========================
4964 VM_bufstr_free
4965 delete string from buffer
4966 void bufstr_free(float bufhandle, float string_index) = #468;
4967 ========================
4968 */
4969 void VM_bufstr_free (void)
4970 {
4971         int                             i;
4972         prvm_stringbuffer_t     *stringbuffer;
4973         VM_SAFEPARMCOUNT(2, VM_bufstr_free);
4974
4975         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4976         if(!stringbuffer)
4977         {
4978                 VM_Warning("VM_bufstr_free: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
4979                 return;
4980         }
4981         i = (int)PRVM_G_FLOAT(OFS_PARM1);
4982         if(i < 0)
4983         {
4984                 VM_Warning("VM_bufstr_free: invalid string index %i used in %s\n", i, PRVM_NAME);
4985                 return;
4986         }
4987
4988         if (i < stringbuffer->num_strings)
4989         {
4990                 if(stringbuffer->strings[i])
4991                         Mem_Free(stringbuffer->strings[i]);
4992                 stringbuffer->strings[i] = NULL;
4993         }
4994
4995         BufStr_Shrink(stringbuffer);
4996 }
4997
4998
4999
5000
5001
5002
5003
5004 void VM_buf_cvarlist(void)
5005 {
5006         cvar_t *cvar;
5007         const char *partial, *antipartial;
5008         size_t len, antilen;
5009         size_t alloclen;
5010         qboolean ispattern, antiispattern;
5011         int n;
5012         prvm_stringbuffer_t     *stringbuffer;
5013         VM_SAFEPARMCOUNTRANGE(2, 3, VM_buf_cvarlist);
5014
5015         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
5016         if(!stringbuffer)
5017         {
5018                 VM_Warning("VM_bufstr_free: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
5019                 return;
5020         }
5021
5022         partial = PRVM_G_STRING(OFS_PARM1);
5023         if(!partial)
5024                 len = 0;
5025         else
5026                 len = strlen(partial);
5027
5028         if(prog->argc == 3)
5029                 antipartial = PRVM_G_STRING(OFS_PARM2);
5030         else
5031                 antipartial = NULL;
5032         if(!antipartial)
5033                 antilen = 0;
5034         else
5035                 antilen = strlen(antipartial);
5036         
5037         for (n = 0;n < stringbuffer->num_strings;n++)
5038                 if (stringbuffer->strings[n])
5039                         Mem_Free(stringbuffer->strings[n]);
5040         if (stringbuffer->strings)
5041                 Mem_Free(stringbuffer->strings);
5042         stringbuffer->strings = NULL;
5043
5044         ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
5045         antiispattern = antipartial && (strchr(antipartial, '*') || strchr(antipartial, '?'));
5046
5047         n = 0;
5048         for(cvar = cvar_vars; cvar; cvar = cvar->next)
5049         {
5050                 if(len && (ispattern ? !matchpattern_with_separator(cvar->name, partial, false, "", false) : strncmp(partial, cvar->name, len)))
5051                         continue;
5052
5053                 if(antilen && (antiispattern ? matchpattern_with_separator(cvar->name, antipartial, false, "", false) : !strncmp(antipartial, cvar->name, antilen)))
5054                         continue;
5055
5056                 ++n;
5057         }
5058
5059         stringbuffer->max_strings = stringbuffer->num_strings = n;
5060         if (stringbuffer->max_strings)
5061                 stringbuffer->strings = (char **)Mem_Alloc(prog->progs_mempool, sizeof(stringbuffer->strings[0]) * stringbuffer->max_strings);
5062         
5063         n = 0;
5064         for(cvar = cvar_vars; cvar; cvar = cvar->next)
5065         {
5066                 if(len && (ispattern ? !matchpattern_with_separator(cvar->name, partial, false, "", false) : strncmp(partial, cvar->name, len)))
5067                         continue;
5068
5069                 if(antilen && (antiispattern ? matchpattern_with_separator(cvar->name, antipartial, false, "", false) : !strncmp(antipartial, cvar->name, antilen)))
5070                         continue;
5071
5072                 alloclen = strlen(cvar->name) + 1;
5073                 stringbuffer->strings[n] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
5074                 memcpy(stringbuffer->strings[n], cvar->name, alloclen);
5075
5076                 ++n;
5077         }
5078 }
5079
5080
5081
5082
5083 //=============
5084
5085 /*
5086 ==============
5087 VM_changeyaw
5088
5089 This was a major timewaster in progs, so it was converted to C
5090 ==============
5091 */
5092 void VM_changeyaw (void)
5093 {
5094         prvm_edict_t            *ent;
5095         float           ideal, current, move, speed;
5096
5097         // this is called (VERY HACKISHLY) by SV_MoveToGoal, so it can not use any
5098         // parameters because they are the parameters to SV_MoveToGoal, not this
5099         //VM_SAFEPARMCOUNT(0, VM_changeyaw);
5100
5101         ent = PRVM_PROG_TO_EDICT(PRVM_gameglobaledict(self));
5102         if (ent == prog->edicts)
5103         {
5104                 VM_Warning("changeyaw: can not modify world entity\n");
5105                 return;
5106         }
5107         if (ent->priv.server->free)
5108         {
5109                 VM_Warning("changeyaw: can not modify free entity\n");
5110                 return;
5111         }
5112         current = PRVM_gameedictvector(ent, angles)[1];
5113         current = ANGLEMOD(current);
5114         ideal = PRVM_gameedictfloat(ent, ideal_yaw);
5115         speed = PRVM_gameedictfloat(ent, yaw_speed);
5116
5117         if (current == ideal)
5118                 return;
5119         move = ideal - current;
5120         if (ideal > current)
5121         {
5122                 if (move >= 180)
5123                         move = move - 360;
5124         }
5125         else
5126         {
5127                 if (move <= -180)
5128                         move = move + 360;
5129         }
5130         if (move > 0)
5131         {
5132                 if (move > speed)
5133                         move = speed;
5134         }
5135         else
5136         {
5137                 if (move < -speed)
5138                         move = -speed;
5139         }
5140
5141         current += move;
5142         PRVM_gameedictvector(ent, angles)[1] = ANGLEMOD(current);
5143 }
5144
5145 /*
5146 ==============
5147 VM_changepitch
5148 ==============
5149 */
5150 void VM_changepitch (void)
5151 {
5152         prvm_edict_t            *ent;
5153         float           ideal, current, move, speed;
5154
5155         VM_SAFEPARMCOUNT(1, VM_changepitch);
5156
5157         ent = PRVM_G_EDICT(OFS_PARM0);
5158         if (ent == prog->edicts)
5159         {
5160                 VM_Warning("changepitch: can not modify world entity\n");
5161                 return;
5162         }
5163         if (ent->priv.server->free)
5164         {
5165                 VM_Warning("changepitch: can not modify free entity\n");
5166                 return;
5167         }
5168         current = PRVM_gameedictvector(ent, angles)[0];
5169         current = ANGLEMOD(current);
5170         ideal = PRVM_gameedictfloat(ent, idealpitch);
5171         speed = PRVM_gameedictfloat(ent, pitch_speed);
5172
5173         if (current == ideal)
5174                 return;
5175         move = ideal - current;
5176         if (ideal > current)
5177         {
5178                 if (move >= 180)
5179                         move = move - 360;
5180         }
5181         else
5182         {
5183                 if (move <= -180)
5184                         move = move + 360;
5185         }
5186         if (move > 0)
5187         {
5188                 if (move > speed)
5189                         move = speed;
5190         }
5191         else
5192         {
5193                 if (move < -speed)
5194                         move = -speed;
5195         }
5196
5197         current += move;
5198         PRVM_gameedictvector(ent, angles)[0] = ANGLEMOD(current);
5199 }
5200
5201
5202 void VM_uncolorstring (void)
5203 {
5204         char szNewString[VM_STRINGTEMP_LENGTH];
5205         const char *szString;
5206
5207         // Prepare Strings
5208         VM_SAFEPARMCOUNT(1, VM_uncolorstring);
5209         szString = PRVM_G_STRING(OFS_PARM0);
5210         COM_StringDecolorize(szString, 0, szNewString, sizeof(szNewString), TRUE);
5211         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(szNewString);
5212         
5213 }
5214
5215 // #221 float(string str, string sub[, float startpos]) strstrofs (FTE_STRINGS)
5216 //strstr, without generating a new string. Use in conjunction with FRIK_FILE's substring for more similar strstr.
5217 void VM_strstrofs (void)
5218 {
5219         const char *instr, *match;
5220         int firstofs;
5221         VM_SAFEPARMCOUNTRANGE(2, 3, VM_strstrofs);
5222         instr = PRVM_G_STRING(OFS_PARM0);
5223         match = PRVM_G_STRING(OFS_PARM1);
5224         firstofs = (prog->argc > 2)?(int)PRVM_G_FLOAT(OFS_PARM2):0;
5225         firstofs = u8_bytelen(instr, firstofs);
5226
5227         if (firstofs && (firstofs < 0 || firstofs > (int)strlen(instr)))
5228         {
5229                 PRVM_G_FLOAT(OFS_RETURN) = -1;
5230                 return;
5231         }
5232
5233         match = strstr(instr+firstofs, match);
5234         if (!match)
5235                 PRVM_G_FLOAT(OFS_RETURN) = -1;
5236         else
5237                 PRVM_G_FLOAT(OFS_RETURN) = u8_strnlen(instr, match-instr);
5238 }
5239
5240 //#222 string(string s, float index) str2chr (FTE_STRINGS)
5241 void VM_str2chr (void)
5242 {
5243         const char *s;
5244         Uchar ch;
5245         int index;
5246         VM_SAFEPARMCOUNT(2, VM_str2chr);
5247         s = PRVM_G_STRING(OFS_PARM0);
5248         index = u8_bytelen(s, (int)PRVM_G_FLOAT(OFS_PARM1));
5249
5250         if((unsigned)index < strlen(s))
5251         {
5252                 if (utf8_enable.integer)
5253                         ch = u8_getchar_noendptr(s + index);
5254                 else
5255                         ch = (unsigned char)s[index];
5256                 PRVM_G_FLOAT(OFS_RETURN) = ch;
5257         }
5258         else
5259                 PRVM_G_FLOAT(OFS_RETURN) = 0;
5260 }
5261
5262 //#223 string(float c, ...) chr2str (FTE_STRINGS)
5263 void VM_chr2str (void)
5264 {
5265         /*
5266         char    t[9];
5267         int             i;
5268         VM_SAFEPARMCOUNTRANGE(0, 8, VM_chr2str);
5269         for(i = 0;i < prog->argc && i < (int)sizeof(t) - 1;i++)
5270                 t[i] = (unsigned char)PRVM_G_FLOAT(OFS_PARM0+i*3);
5271         t[i] = 0;
5272         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(t);
5273         */
5274         char t[9 * 4 + 1];
5275         int i;
5276         size_t len = 0;
5277         VM_SAFEPARMCOUNTRANGE(0, 8, VM_chr2str);
5278         for(i = 0; i < prog->argc && len < sizeof(t)-1; ++i)
5279                 len += u8_fromchar((Uchar)PRVM_G_FLOAT(OFS_PARM0+i*3), t + len, sizeof(t)-1);
5280         t[len] = 0;
5281         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(t);
5282 }
5283
5284 static int chrconv_number(int i, int base, int conv)
5285 {
5286         i -= base;
5287         switch (conv)
5288         {
5289         default:
5290         case 5:
5291         case 6:
5292         case 0:
5293                 break;
5294         case 1:
5295                 base = '0';
5296                 break;
5297         case 2:
5298                 base = '0'+128;
5299                 break;
5300         case 3:
5301                 base = '0'-30;
5302                 break;
5303         case 4:
5304                 base = '0'+128-30;
5305                 break;
5306         }
5307         return i + base;
5308 }
5309 static int chrconv_punct(int i, int base, int conv)
5310 {
5311         i -= base;
5312         switch (conv)
5313         {
5314         default:
5315         case 0:
5316                 break;
5317         case 1:
5318                 base = 0;
5319                 break;
5320         case 2:
5321                 base = 128;
5322                 break;
5323         }
5324         return i + base;
5325 }
5326
5327 static int chrchar_alpha(int i, int basec, int baset, int convc, int convt, int charnum)
5328 {
5329         //convert case and colour seperatly...
5330
5331         i -= baset + basec;
5332         switch (convt)
5333         {
5334         default:
5335         case 0:
5336                 break;
5337         case 1:
5338                 baset = 0;
5339                 break;
5340         case 2:
5341                 baset = 128;
5342                 break;
5343
5344         case 5:
5345         case 6:
5346                 baset = 128*((charnum&1) == (convt-5));
5347                 break;
5348         }
5349
5350         switch (convc)
5351         {
5352         default:
5353         case 0:
5354                 break;
5355         case 1:
5356                 basec = 'a';
5357                 break;
5358         case 2:
5359                 basec = 'A';
5360                 break;
5361         }
5362         return i + basec + baset;
5363 }
5364 // #224 string(float ccase, float calpha, float cnum, string s, ...) strconv (FTE_STRINGS)
5365 //bulk convert a string. change case or colouring.
5366 void VM_strconv (void)
5367 {
5368         int ccase, redalpha, rednum, len, i;
5369         unsigned char resbuf[VM_STRINGTEMP_LENGTH];
5370         unsigned char *result = resbuf;
5371
5372         VM_SAFEPARMCOUNTRANGE(3, 8, VM_strconv);
5373
5374         ccase = (int) PRVM_G_FLOAT(OFS_PARM0);  //0 same, 1 lower, 2 upper
5375         redalpha = (int) PRVM_G_FLOAT(OFS_PARM1);       //0 same, 1 white, 2 red,  5 alternate, 6 alternate-alternate
5376         rednum = (int) PRVM_G_FLOAT(OFS_PARM2); //0 same, 1 white, 2 red, 3 redspecial, 4 whitespecial, 5 alternate, 6 alternate-alternate
5377         VM_VarString(3, (char *) resbuf, sizeof(resbuf));
5378         len = strlen((char *) resbuf);
5379
5380         for (i = 0; i < len; i++, result++)     //should this be done backwards?
5381         {
5382                 if (*result >= '0' && *result <= '9')   //normal numbers...
5383                         *result = chrconv_number(*result, '0', rednum);
5384                 else if (*result >= '0'+128 && *result <= '9'+128)
5385                         *result = chrconv_number(*result, '0'+128, rednum);
5386                 else if (*result >= '0'+128-30 && *result <= '9'+128-30)
5387                         *result = chrconv_number(*result, '0'+128-30, rednum);
5388                 else if (*result >= '0'-30 && *result <= '9'-30)
5389                         *result = chrconv_number(*result, '0'-30, rednum);
5390
5391                 else if (*result >= 'a' && *result <= 'z')      //normal numbers...
5392                         *result = chrchar_alpha(*result, 'a', 0, ccase, redalpha, i);
5393                 else if (*result >= 'A' && *result <= 'Z')      //normal numbers...
5394                         *result = chrchar_alpha(*result, 'A', 0, ccase, redalpha, i);
5395                 else if (*result >= 'a'+128 && *result <= 'z'+128)      //normal numbers...
5396                         *result = chrchar_alpha(*result, 'a', 128, ccase, redalpha, i);
5397                 else if (*result >= 'A'+128 && *result <= 'Z'+128)      //normal numbers...
5398                         *result = chrchar_alpha(*result, 'A', 128, ccase, redalpha, i);
5399
5400                 else if ((*result & 127) < 16 || !redalpha)     //special chars..
5401                         *result = *result;
5402                 else if (*result < 128)
5403                         *result = chrconv_punct(*result, 0, redalpha);
5404                 else
5405                         *result = chrconv_punct(*result, 128, redalpha);
5406         }
5407         *result = '\0';
5408
5409         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString((char *) resbuf);
5410 }
5411
5412 // #225 string(float chars, string s, ...) strpad (FTE_STRINGS)
5413 void VM_strpad (void)
5414 {
5415         char src[VM_STRINGTEMP_LENGTH];
5416         char destbuf[VM_STRINGTEMP_LENGTH];
5417         int pad;
5418         VM_SAFEPARMCOUNTRANGE(1, 8, VM_strpad);
5419         pad = (int) PRVM_G_FLOAT(OFS_PARM0);
5420         VM_VarString(1, src, sizeof(src));
5421
5422         // note: < 0 = left padding, > 0 = right padding,
5423         // this is reverse logic of printf!
5424         dpsnprintf(destbuf, sizeof(destbuf), "%*s", -pad, src);
5425
5426         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(destbuf);
5427 }
5428
5429 // #226 string(string info, string key, string value, ...) infoadd (FTE_STRINGS)
5430 //uses qw style \key\value strings
5431 void VM_infoadd (void)
5432 {
5433         const char *info, *key;
5434         char value[VM_STRINGTEMP_LENGTH];
5435         char temp[VM_STRINGTEMP_LENGTH];
5436
5437         VM_SAFEPARMCOUNTRANGE(2, 8, VM_infoadd);
5438         info = PRVM_G_STRING(OFS_PARM0);
5439         key = PRVM_G_STRING(OFS_PARM1);
5440         VM_VarString(2, value, sizeof(value));
5441
5442         strlcpy(temp, info, VM_STRINGTEMP_LENGTH);
5443
5444         InfoString_SetValue(temp, VM_STRINGTEMP_LENGTH, key, value);
5445
5446         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(temp);
5447 }
5448
5449 // #227 string(string info, string key) infoget (FTE_STRINGS)
5450 //uses qw style \key\value strings
5451 void VM_infoget (void)
5452 {
5453         const char *info;
5454         const char *key;
5455         char value[VM_STRINGTEMP_LENGTH];
5456
5457         VM_SAFEPARMCOUNT(2, VM_infoget);
5458         info = PRVM_G_STRING(OFS_PARM0);
5459         key = PRVM_G_STRING(OFS_PARM1);
5460
5461         InfoString_GetValue(info, key, value, VM_STRINGTEMP_LENGTH);
5462
5463         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(value);
5464 }
5465
5466 //#228 float(string s1, string s2, float len) strncmp (FTE_STRINGS)
5467 // also float(string s1, string s2) strcmp (FRIK_FILE)
5468 void VM_strncmp (void)
5469 {
5470         const char *s1, *s2;
5471         VM_SAFEPARMCOUNTRANGE(2, 3, VM_strncmp);
5472         s1 = PRVM_G_STRING(OFS_PARM0);
5473         s2 = PRVM_G_STRING(OFS_PARM1);
5474         if (prog->argc > 2)
5475         {
5476                 PRVM_G_FLOAT(OFS_RETURN) = strncmp(s1, s2, (size_t)PRVM_G_FLOAT(OFS_PARM2));
5477         }
5478         else
5479         {
5480                 PRVM_G_FLOAT(OFS_RETURN) = strcmp(s1, s2);
5481         }
5482 }
5483
5484 // #229 float(string s1, string s2) strcasecmp (FTE_STRINGS)
5485 // #230 float(string s1, string s2, float len) strncasecmp (FTE_STRINGS)
5486 void VM_strncasecmp (void)
5487 {
5488         const char *s1, *s2;
5489         VM_SAFEPARMCOUNTRANGE(2, 3, VM_strncasecmp);
5490         s1 = PRVM_G_STRING(OFS_PARM0);
5491         s2 = PRVM_G_STRING(OFS_PARM1);
5492         if (prog->argc > 2)
5493         {
5494                 PRVM_G_FLOAT(OFS_RETURN) = strncasecmp(s1, s2, (size_t)PRVM_G_FLOAT(OFS_PARM2));
5495         }
5496         else
5497         {
5498                 PRVM_G_FLOAT(OFS_RETURN) = strcasecmp(s1, s2);
5499         }
5500 }
5501
5502 // #494 float(float caseinsensitive, string s, ...) crc16
5503 void VM_crc16(void)
5504 {
5505         float insensitive;
5506         static char s[VM_STRINGTEMP_LENGTH];
5507         VM_SAFEPARMCOUNTRANGE(2, 8, VM_crc16);
5508         insensitive = PRVM_G_FLOAT(OFS_PARM0);
5509         VM_VarString(1, s, sizeof(s));
5510         PRVM_G_FLOAT(OFS_RETURN) = (unsigned short) ((insensitive ? CRC_Block_CaseInsensitive : CRC_Block) ((unsigned char *) s, strlen(s)));
5511 }
5512
5513 // #639 float(string digest, string data, ...) digest_hex
5514 void VM_digest_hex(void)
5515 {
5516         const char *digest;
5517
5518         static char out[32];
5519         static char outhex[65];
5520         int outlen;
5521
5522         static char s[VM_STRINGTEMP_LENGTH];
5523         int len;
5524
5525         VM_SAFEPARMCOUNTRANGE(2, 8, VM_digest_hex);
5526         digest = PRVM_G_STRING(OFS_PARM0);
5527         if(!digest)
5528                 digest = "";
5529         VM_VarString(1, s, sizeof(s));
5530         len = strlen(s);
5531
5532         outlen = 0;
5533
5534         if(!strcmp(digest, "MD4"))
5535         {
5536                 outlen = 16;
5537                 mdfour((unsigned char *) out, (unsigned char *) s, len);
5538         }
5539         else if(!strcmp(digest, "SHA256") && Crypto_Available())
5540         {
5541                 outlen = 32;
5542                 sha256((unsigned char *) out, (unsigned char *) s, len);
5543         }
5544         // no warning needed on mismatch - we return string_null to QC
5545
5546         if(outlen)
5547         {
5548                 int i;
5549                 static const char *hexmap = "0123456789abcdef";
5550                 for(i = 0; i < outlen; ++i)
5551                 {
5552                         outhex[2*i]   = hexmap[(out[i] >> 4) & 15];
5553                         outhex[2*i+1] = hexmap[(out[i] >> 0) & 15];
5554                 }
5555                 outhex[2*i] = 0;
5556                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(outhex);
5557         }
5558         else
5559                 PRVM_G_INT(OFS_RETURN) = 0;
5560 }
5561
5562 void VM_wasfreed (void)
5563 {
5564         VM_SAFEPARMCOUNT(1, VM_wasfreed);
5565         PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_EDICT(OFS_PARM0)->priv.required->free;
5566 }
5567
5568 void VM_SetTraceGlobals(const trace_t *trace)
5569 {
5570         PRVM_gameglobalfloat(trace_allsolid) = trace->allsolid;
5571         PRVM_gameglobalfloat(trace_startsolid) = trace->startsolid;
5572         PRVM_gameglobalfloat(trace_fraction) = trace->fraction;
5573         PRVM_gameglobalfloat(trace_inwater) = trace->inwater;
5574         PRVM_gameglobalfloat(trace_inopen) = trace->inopen;
5575         VectorCopy(trace->endpos, PRVM_gameglobalvector(trace_endpos));
5576         VectorCopy(trace->plane.normal, PRVM_gameglobalvector(trace_plane_normal));
5577         PRVM_gameglobalfloat(trace_plane_dist) = trace->plane.dist;
5578         PRVM_gameglobaledict(trace_ent) = PRVM_EDICT_TO_PROG(trace->ent ? trace->ent : prog->edicts);
5579         PRVM_gameglobalfloat(trace_dpstartcontents) = trace->startsupercontents;
5580         PRVM_gameglobalfloat(trace_dphitcontents) = trace->hitsupercontents;
5581         PRVM_gameglobalfloat(trace_dphitq3surfaceflags) = trace->hitq3surfaceflags;
5582         PRVM_gameglobalstring(trace_dphittexturename) = trace->hittexture ? PRVM_SetTempString(trace->hittexture->name) : 0;
5583 }
5584
5585 void VM_ClearTraceGlobals(void)
5586 {
5587         // clean up all trace globals when leaving the VM (anti-triggerbot safeguard)
5588         PRVM_gameglobalfloat(trace_allsolid) = 0;
5589         PRVM_gameglobalfloat(trace_startsolid) = 0;
5590         PRVM_gameglobalfloat(trace_fraction) = 0;
5591         PRVM_gameglobalfloat(trace_inwater) = 0;
5592         PRVM_gameglobalfloat(trace_inopen) = 0;
5593         VectorClear(PRVM_gameglobalvector(trace_endpos));
5594         VectorClear(PRVM_gameglobalvector(trace_plane_normal));
5595         PRVM_gameglobalfloat(trace_plane_dist) = 0;
5596         PRVM_gameglobaledict(trace_ent) = PRVM_EDICT_TO_PROG(prog->edicts);
5597         PRVM_gameglobalfloat(trace_dpstartcontents) = 0;
5598         PRVM_gameglobalfloat(trace_dphitcontents) = 0;
5599         PRVM_gameglobalfloat(trace_dphitq3surfaceflags) = 0;
5600         PRVM_gameglobalstring(trace_dphittexturename) = 0;
5601 }
5602
5603 //=============
5604
5605 void VM_Cmd_Init(void)
5606 {
5607         // only init the stuff for the current prog
5608         VM_Files_Init();
5609         VM_Search_Init();
5610 //      VM_BufStr_Init();
5611 }
5612
5613 void VM_Cmd_Reset(void)
5614 {
5615         CL_PurgeOwner( MENUOWNER );
5616         VM_Search_Reset();
5617         VM_Files_CloseAll();
5618 //      VM_BufStr_ShutDown();
5619 }
5620
5621 // #510 string(string input, ...) uri_escape (DP_QC_URI_ESCAPE)
5622 // does URI escaping on a string (replace evil stuff by %AB escapes)
5623 void VM_uri_escape (void)
5624 {
5625         char src[VM_STRINGTEMP_LENGTH];
5626         char dest[VM_STRINGTEMP_LENGTH];
5627         char *p, *q;
5628         static const char *hex = "0123456789ABCDEF";
5629
5630         VM_SAFEPARMCOUNTRANGE(1, 8, VM_uri_escape);
5631         VM_VarString(0, src, sizeof(src));
5632
5633         for(p = src, q = dest; *p && q < dest + sizeof(dest) - 3; ++p)
5634         {
5635                 if((*p >= 'A' && *p <= 'Z')
5636                         || (*p >= 'a' && *p <= 'z')
5637                         || (*p >= '0' && *p <= '9')
5638                         || (*p == '-')  || (*p == '_') || (*p == '.')
5639                         || (*p == '!')  || (*p == '~')
5640                         || (*p == '\'') || (*p == '(') || (*p == ')'))
5641                         *q++ = *p;
5642                 else
5643                 {
5644                         *q++ = '%';
5645                         *q++ = hex[(*(unsigned char *)p >> 4) & 0xF];
5646                         *q++ = hex[ *(unsigned char *)p       & 0xF];
5647                 }
5648         }
5649         *q++ = 0;
5650
5651         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(dest);
5652 }
5653
5654 // #510 string(string input, ...) uri_unescape (DP_QC_URI_ESCAPE)
5655 // does URI unescaping on a string (get back the evil stuff)
5656 void VM_uri_unescape (void)
5657 {
5658         char src[VM_STRINGTEMP_LENGTH];
5659         char dest[VM_STRINGTEMP_LENGTH];
5660         char *p, *q;
5661         int hi, lo;
5662
5663         VM_SAFEPARMCOUNTRANGE(1, 8, VM_uri_unescape);
5664         VM_VarString(0, src, sizeof(src));
5665
5666         for(p = src, q = dest; *p; ) // no need to check size, because unescape can't expand
5667         {
5668                 if(*p == '%')
5669                 {
5670                         if(p[1] >= '0' && p[1] <= '9')
5671                                 hi = p[1] - '0';
5672                         else if(p[1] >= 'a' && p[1] <= 'f')
5673                                 hi = p[1] - 'a' + 10;
5674                         else if(p[1] >= 'A' && p[1] <= 'F')
5675                                 hi = p[1] - 'A' + 10;
5676                         else
5677                                 goto nohex;
5678                         if(p[2] >= '0' && p[2] <= '9')
5679                                 lo = p[2] - '0';
5680                         else if(p[2] >= 'a' && p[2] <= 'f')
5681                                 lo = p[2] - 'a' + 10;
5682                         else if(p[2] >= 'A' && p[2] <= 'F')
5683                                 lo = p[2] - 'A' + 10;
5684                         else
5685                                 goto nohex;
5686                         if(hi != 0 || lo != 0) // don't unescape NUL bytes
5687                                 *q++ = (char) (hi * 0x10 + lo);
5688                         p += 3;
5689                         continue;
5690                 }
5691
5692 nohex:
5693                 // otherwise:
5694                 *q++ = *p++;
5695         }
5696         *q++ = 0;
5697
5698         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(dest);
5699 }
5700
5701 // #502 string(string filename) whichpack (DP_QC_WHICHPACK)
5702 // returns the name of the pack containing a file, or "" if it is not in any pack (but local or non-existant)
5703 void VM_whichpack (void)
5704 {
5705         const char *fn, *pack;
5706
5707         VM_SAFEPARMCOUNT(1, VM_whichpack);
5708         fn = PRVM_G_STRING(OFS_PARM0);
5709         pack = FS_WhichPack(fn);
5710
5711         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(pack ? pack : "");
5712 }
5713
5714 typedef struct
5715 {
5716         int prognr;
5717         double starttime;
5718         float id;
5719         char buffer[MAX_INPUTLINE];
5720         unsigned char *postdata; // free when uri_to_prog_t is freed
5721         size_t postlen;
5722         char *sigdata; // free when uri_to_prog_t is freed
5723         size_t siglen;
5724 }
5725 uri_to_prog_t;
5726
5727 static void uri_to_string_callback(int status, size_t length_received, unsigned char *buffer, void *cbdata)
5728 {
5729         uri_to_prog_t *handle = (uri_to_prog_t *) cbdata;
5730
5731         if(!PRVM_ProgLoaded(handle->prognr))
5732         {
5733                 // curl reply came too late... so just drop it
5734                 if(handle->postdata)
5735                         Z_Free(handle->postdata);
5736                 if(handle->sigdata)
5737                         Z_Free(handle->sigdata);
5738                 Z_Free(handle);
5739                 return;
5740         }
5741                 
5742         PRVM_SetProg(handle->prognr);
5743         PRVM_Begin;
5744                 if((prog->starttime == handle->starttime) && (PRVM_allfunction(URI_Get_Callback)))
5745                 {
5746                         if(length_received >= sizeof(handle->buffer))
5747                                 length_received = sizeof(handle->buffer) - 1;
5748                         handle->buffer[length_received] = 0;
5749                 
5750                         PRVM_G_FLOAT(OFS_PARM0) = handle->id;
5751                         PRVM_G_FLOAT(OFS_PARM1) = status;
5752                         PRVM_G_INT(OFS_PARM2) = PRVM_SetTempString(handle->buffer);
5753                         PRVM_ExecuteProgram(PRVM_allfunction(URI_Get_Callback), "QC function URI_Get_Callback is missing");
5754                 }
5755         PRVM_End;
5756         
5757         if(handle->postdata)
5758                 Z_Free(handle->postdata);
5759         if(handle->sigdata)
5760                 Z_Free(handle->sigdata);
5761         Z_Free(handle);
5762 }
5763
5764 // uri_get() gets content from an URL and calls a callback "uri_get_callback" with it set as string; an unique ID of the transfer is returned
5765 // returns 1 on success, and then calls the callback with the ID, 0 or the HTTP status code, and the received data in a string
5766 void VM_uri_get (void)
5767 {
5768         const char *url;
5769         float id;
5770         qboolean ret;
5771         uri_to_prog_t *handle;
5772         const char *posttype = NULL;
5773         const char *postseparator = NULL;
5774         int poststringbuffer = -1;
5775         int postkeyid = -1;
5776         const char *query_string = NULL;
5777         size_t lq;
5778
5779         if(!PRVM_allfunction(URI_Get_Callback))
5780                 PRVM_ERROR("uri_get called by %s without URI_Get_Callback defined", PRVM_NAME);
5781
5782         VM_SAFEPARMCOUNTRANGE(2, 6, VM_uri_get);
5783
5784         url = PRVM_G_STRING(OFS_PARM0);
5785         id = PRVM_G_FLOAT(OFS_PARM1);
5786         if(prog->argc >= 3)
5787                 posttype = PRVM_G_STRING(OFS_PARM2);
5788         if(prog->argc >= 4)
5789                 postseparator = PRVM_G_STRING(OFS_PARM3);
5790         if(prog->argc >= 5)
5791                 poststringbuffer = PRVM_G_FLOAT(OFS_PARM4);
5792         if(prog->argc >= 6)
5793                 postkeyid = PRVM_G_FLOAT(OFS_PARM5);
5794         handle = (uri_to_prog_t *) Z_Malloc(sizeof(*handle)); // this can't be the prog's mem pool, as curl may call the callback later!
5795
5796         query_string = strchr(url, '?');
5797         if(query_string)
5798                 ++query_string;
5799         lq = query_string ? strlen(query_string) : 0;
5800
5801         handle->prognr = PRVM_GetProgNr();
5802         handle->starttime = prog->starttime;
5803         handle->id = id;
5804         if(postseparator && posttype && *posttype)
5805         {
5806                 size_t l = strlen(postseparator);
5807                 if(poststringbuffer >= 0)
5808                 {
5809                         size_t ltotal;
5810                         int i;
5811                         // "implode"
5812                         prvm_stringbuffer_t *stringbuffer;
5813                         stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, poststringbuffer);
5814                         if(!stringbuffer)
5815                         {
5816                                 VM_Warning("uri_get: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), PRVM_NAME);
5817                                 return;
5818                         }
5819                         ltotal = 0;
5820                         for(i = 0;i < stringbuffer->num_strings;i++)
5821                         {
5822                                 if(i > 0)
5823                                         ltotal += l;
5824                                 if(stringbuffer->strings[i])
5825                                         ltotal += strlen(stringbuffer->strings[i]);
5826                         }
5827                         handle->postdata = (unsigned char *)Z_Malloc(ltotal + 1 + lq);
5828                         handle->postlen = ltotal;
5829                         ltotal = 0;
5830                         for(i = 0;i < stringbuffer->num_strings;i++)
5831                         {
5832                                 if(i > 0)
5833                                 {
5834                                         memcpy(handle->postdata + ltotal, postseparator, l);
5835                                         ltotal += l;
5836                                 }
5837                                 if(stringbuffer->strings[i])
5838                                 {
5839                                         memcpy(handle->postdata + ltotal, stringbuffer->strings[i], strlen(stringbuffer->strings[i]));
5840                                         ltotal += strlen(stringbuffer->strings[i]);
5841                                 }
5842                         }
5843                         if(ltotal != handle->postlen)
5844                                 PRVM_ERROR ("%s: string buffer content size mismatch, possible overrun", PRVM_NAME);
5845                 }
5846                 else
5847                 {
5848                         handle->postdata = (unsigned char *)Z_Malloc(l + 1 + lq);
5849                         handle->postlen = l;
5850                         memcpy(handle->postdata, postseparator, l);
5851                 }
5852                 handle->postdata[handle->postlen] = 0;
5853                 if(query_string)
5854                         memcpy(handle->postdata + handle->postlen + 1, query_string, lq);
5855                 if(postkeyid >= 0)
5856                 {
5857                         // POST: we sign postdata \0 query string
5858                         size_t ll;
5859                         handle->sigdata = (char *)Z_Malloc(8192);
5860                         strlcpy(handle->sigdata, "X-D0-Blind-ID-Detached-Signature: ", 8192);
5861                         l = strlen(handle->sigdata);
5862                         handle->siglen = Crypto_SignDataDetached(handle->postdata, handle->postlen + 1 + lq, postkeyid, handle->sigdata + l, 8192 - l);
5863                         if(!handle->siglen)
5864                         {
5865                                 Z_Free(handle->sigdata);
5866                                 handle->sigdata = NULL;
5867                                 goto out1;
5868                         }
5869                         ll = base64_encode((unsigned char *) (handle->sigdata + l), handle->siglen, 8192 - l - 1);
5870                         if(!ll)
5871                         {
5872                                 Z_Free(handle->sigdata);
5873                                 handle->sigdata = NULL;
5874                                 goto out1;
5875                         }
5876                         handle->siglen = l + ll;
5877                         handle->sigdata[handle->siglen] = 0;
5878                 }
5879 out1:
5880                 ret = Curl_Begin_ToMemory_POST(url, handle->sigdata, 0, posttype, handle->postdata, handle->postlen, (unsigned char *) handle->buffer, sizeof(handle->buffer), uri_to_string_callback, handle);
5881         }
5882         else
5883         {
5884                 if(postkeyid >= 0 && query_string)
5885                 {
5886                         // GET: we sign JUST the query string
5887                         size_t l, ll;
5888                         handle->sigdata = (char *)Z_Malloc(8192);
5889                         strlcpy(handle->sigdata, "X-D0-Blind-ID-Detached-Signature: ", 8192);
5890                         l = strlen(handle->sigdata);
5891                         handle->siglen = Crypto_SignDataDetached(query_string, lq, postkeyid, handle->sigdata + l, 8192 - l);
5892                         if(!handle->siglen)
5893                         {
5894                                 Z_Free(handle->sigdata);
5895                                 handle->sigdata = NULL;
5896                                 goto out2;
5897                         }
5898                         ll = base64_encode((unsigned char *) (handle->sigdata + l), handle->siglen, 8192 - l - 1);
5899                         if(!ll)
5900                         {
5901                                 Z_Free(handle->sigdata);
5902                                 handle->sigdata = NULL;
5903                                 goto out2;
5904                         }
5905                         handle->siglen = l + ll;
5906                         handle->sigdata[handle->siglen] = 0;
5907                 }
5908 out2:
5909                 handle->postdata = NULL;
5910                 handle->postlen = 0;
5911                 ret = Curl_Begin_ToMemory(url, 0, (unsigned char *) handle->buffer, sizeof(handle->buffer), uri_to_string_callback, handle);
5912         }
5913         if(ret)
5914         {
5915                 PRVM_G_INT(OFS_RETURN) = 1;
5916         }
5917         else
5918         {
5919                 if(handle->postdata)
5920                         Z_Free(handle->postdata);
5921                 if(handle->sigdata)
5922                         Z_Free(handle->sigdata);
5923                 Z_Free(handle);
5924                 PRVM_G_INT(OFS_RETURN) = 0;
5925         }
5926 }
5927
5928 void VM_netaddress_resolve (void)
5929 {
5930         const char *ip;
5931         char normalized[128];
5932         int port;
5933         lhnetaddress_t addr;
5934
5935         VM_SAFEPARMCOUNTRANGE(1, 2, VM_netaddress_resolve);
5936
5937         ip = PRVM_G_STRING(OFS_PARM0);
5938         port = 0;
5939         if(prog->argc > 1)
5940                 port = (int) PRVM_G_FLOAT(OFS_PARM1);
5941
5942         if(LHNETADDRESS_FromString(&addr, ip, port) && LHNETADDRESS_ToString(&addr, normalized, sizeof(normalized), prog->argc > 1))
5943                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(normalized);
5944         else
5945                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString("");
5946 }
5947
5948 //string(void) getextresponse = #624; // returns the next extResponse packet that was sent to this client
5949 void VM_CL_getextresponse (void)
5950 {
5951         VM_SAFEPARMCOUNT(0,VM_argv);
5952
5953         if (cl_net_extresponse_count <= 0)
5954                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
5955         else
5956         {
5957                 int first;
5958                 --cl_net_extresponse_count;
5959                 first = (cl_net_extresponse_last + NET_EXTRESPONSE_MAX - cl_net_extresponse_count) % NET_EXTRESPONSE_MAX;
5960                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(cl_net_extresponse[first]);
5961         }
5962 }
5963
5964 void VM_SV_getextresponse (void)
5965 {
5966         VM_SAFEPARMCOUNT(0,VM_argv);
5967
5968         if (sv_net_extresponse_count <= 0)
5969                 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
5970         else
5971         {
5972                 int first;
5973                 --sv_net_extresponse_count;
5974                 first = (sv_net_extresponse_last + NET_EXTRESPONSE_MAX - sv_net_extresponse_count) % NET_EXTRESPONSE_MAX;
5975                 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(sv_net_extresponse[first]);
5976         }
5977 }
5978
5979 /*
5980 =========
5981 Common functions between menu.dat and clsprogs
5982 =========
5983 */
5984
5985 //#349 float() isdemo 
5986 void VM_CL_isdemo (void)
5987 {
5988         VM_SAFEPARMCOUNT(0, VM_CL_isdemo);
5989         PRVM_G_FLOAT(OFS_RETURN) = cls.demoplayback;
5990 }
5991
5992 //#355 float() videoplaying 
5993 void VM_CL_videoplaying (void)
5994 {
5995         VM_SAFEPARMCOUNT(0, VM_CL_videoplaying);
5996         PRVM_G_FLOAT(OFS_RETURN) = cl_videoplaying;
5997 }
5998
5999 /*
6000 =========
6001 VM_M_callfunction
6002
6003         callfunction(...,string function_name)
6004 Extension: pass
6005 =========
6006 */
6007 mfunction_t *PRVM_ED_FindFunction (const char *name);
6008 void VM_callfunction(void)
6009 {
6010         mfunction_t *func;
6011         const char *s;
6012
6013         VM_SAFEPARMCOUNTRANGE(1, 8, VM_callfunction);
6014
6015         s = PRVM_G_STRING(OFS_PARM0+(prog->argc - 1)*3);
6016
6017         VM_CheckEmptyString(s);
6018
6019         func = PRVM_ED_FindFunction(s);
6020
6021         if(!func)
6022                 PRVM_ERROR("VM_callfunciton: function %s not found !", s);
6023         else if (func->first_statement < 0)
6024         {
6025                 // negative statements are built in functions
6026                 int builtinnumber = -func->first_statement;
6027                 prog->xfunction->builtinsprofile++;
6028                 if (builtinnumber < prog->numbuiltins && prog->builtins[builtinnumber])
6029                         prog->builtins[builtinnumber]();
6030                 else
6031                         PRVM_ERROR("No such builtin #%i in %s; most likely cause: outdated engine build. Try updating!", builtinnumber, PRVM_NAME);
6032         }
6033         else if(func - prog->functions > 0)
6034         {
6035                 prog->argc--;
6036                 PRVM_ExecuteProgram(func - prog->functions,"");
6037                 prog->argc++;
6038         }
6039 }
6040
6041 /*
6042 =========
6043 VM_isfunction
6044
6045 float   isfunction(string function_name)
6046 =========
6047 */
6048 mfunction_t *PRVM_ED_FindFunction (const char *name);
6049 void VM_isfunction(void)
6050 {
6051         mfunction_t *func;
6052         const char *s;
6053
6054         VM_SAFEPARMCOUNT(1, VM_isfunction);
6055
6056         s = PRVM_G_STRING(OFS_PARM0);
6057
6058         VM_CheckEmptyString(s);
6059
6060         func = PRVM_ED_FindFunction(s);
6061
6062         if(!func)
6063                 PRVM_G_FLOAT(OFS_RETURN) = false;
6064         else
6065                 PRVM_G_FLOAT(OFS_RETURN) = true;
6066 }
6067
6068 /*
6069 =========
6070 VM_sprintf
6071
6072 string sprintf(string format, ...)
6073 =========
6074 */
6075
6076 void VM_sprintf(void)
6077 {
6078         const char *s, *s0;
6079         char outbuf[MAX_INPUTLINE];
6080         char *o = outbuf, *end = outbuf + sizeof(outbuf), *err;
6081         int argpos = 1;
6082         int width, precision, thisarg, flags;
6083         char formatbuf[16];
6084         char *f;
6085         int isfloat;
6086         static int dummyivec[3] = {0, 0, 0};
6087         static float dummyvec[3] = {0, 0, 0};
6088
6089 #define PRINTF_ALTERNATE 1
6090 #define PRINTF_ZEROPAD 2
6091 #define PRINTF_LEFT 4
6092 #define PRINTF_SPACEPOSITIVE 8
6093 #define PRINTF_SIGNPOSITIVE 16
6094
6095         formatbuf[0] = '%';
6096
6097         s = PRVM_G_STRING(OFS_PARM0);
6098
6099 #define GETARG_FLOAT(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_FLOAT(OFS_PARM0 + 3 * (a))) : 0)
6100 #define GETARG_VECTOR(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_VECTOR(OFS_PARM0 + 3 * (a))) : dummyvec)
6101 #define GETARG_INT(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_INT(OFS_PARM0 + 3 * (a))) : 0)
6102 #define GETARG_INTVECTOR(a) (((a)>=1 && (a)<prog->argc) ? ((int*) PRVM_G_VECTOR(OFS_PARM0 + 3 * (a))) : dummyivec)
6103 #define GETARG_STRING(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_STRING(OFS_PARM0 + 3 * (a))) : "")
6104
6105         for(;;)
6106         {
6107                 s0 = s;
6108                 switch(*s)
6109                 {
6110                         case 0:
6111                                 goto finished;
6112                         case '%':
6113                                 ++s;
6114
6115                                 if(*s == '%')
6116                                         goto verbatim;
6117
6118                                 // complete directive format:
6119                                 // %3$*1$.*2$ld
6120                                 
6121                                 width = -1;
6122                                 precision = -1;
6123                                 thisarg = -1;
6124                                 flags = 0;
6125                                 isfloat = -1;
6126
6127                                 // is number following?
6128                                 if(*s >= '0' && *s <= '9')
6129                                 {
6130                                         width = strtol(s, &err, 10);
6131                                         if(!err)
6132                                         {
6133                                                 VM_Warning("VM_sprintf: invalid directive in %s: %s\n", PRVM_NAME, s0);
6134                                                 goto finished;
6135                                         }
6136                                         if(*err == '$')
6137                                         {
6138                                                 thisarg = width;
6139                                                 width = -1;
6140                                                 s = err + 1;
6141                                         }
6142                                         else
6143                                         {
6144                                                 if(*s == '0')
6145                                                 {
6146                                                         flags |= PRINTF_ZEROPAD;
6147                                                         if(width == 0)
6148                                                                 width = -1; // it was just a flag
6149                                                 }
6150                                                 s = err;
6151                                         }
6152                                 }
6153
6154                                 if(width < 0)
6155                                 {
6156                                         for(;;)
6157                                         {
6158                                                 switch(*s)
6159                                                 {
6160                                                         case '#': flags |= PRINTF_ALTERNATE; break;
6161                                                         case '0': flags |= PRINTF_ZEROPAD; break;
6162                                                         case '-': flags |= PRINTF_LEFT; break;
6163                                                         case ' ': flags |= PRINTF_SPACEPOSITIVE; break;
6164                                                         case '+': flags |= PRINTF_SIGNPOSITIVE; break;
6165                                                         default:
6166                                                                 goto noflags;
6167                                                 }
6168                                                 ++s;
6169                                         }
6170 noflags:
6171                                         if(*s == '*')
6172                                         {
6173                                                 ++s;
6174                                                 if(*s >= '0' && *s <= '9')
6175                                                 {
6176                                                         width = strtol(s, &err, 10);
6177                                                         if(!err || *err != '$')
6178                                                         {
6179                                                                 VM_Warning("VM_sprintf: invalid directive in %s: %s\n", PRVM_NAME, s0);
6180                                                                 goto finished;
6181                                                         }
6182                                                         s = err + 1;
6183                                                 }
6184                                                 else
6185                                                         width = argpos++;
6186                                                 width = GETARG_FLOAT(width);
6187                                                 if(width < 0)
6188                                                 {
6189                                                         flags |= PRINTF_LEFT;
6190                                                         width = -width;
6191                                                 }
6192                                         }
6193                                         else if(*s >= '0' && *s <= '9')
6194                                         {
6195                                                 width = strtol(s, &err, 10);
6196                                                 if(!err)
6197                                                 {
6198                                                         VM_Warning("VM_sprintf: invalid directive in %s: %s\n", PRVM_NAME, s0);
6199                                                         goto finished;
6200                                                 }
6201                                                 s = err;
6202                                                 if(width < 0)
6203                                                 {
6204                                                         flags |= PRINTF_LEFT;
6205                                                         width = -width;
6206                                                 }
6207                                         }
6208                                         // otherwise width stays -1
6209                                 }
6210
6211                                 if(*s == '.')
6212                                 {
6213                                         ++s;
6214                                         if(*s == '*')
6215                                         {
6216                                                 ++s;
6217                                                 if(*s >= '0' && *s <= '9')
6218                                                 {
6219                                                         precision = strtol(s, &err, 10);
6220                                                         if(!err || *err != '$')
6221                                                         {
6222                                                                 VM_Warning("VM_sprintf: invalid directive in %s: %s\n", PRVM_NAME, s0);
6223                                                                 goto finished;
6224                                                         }
6225                                                         s = err + 1;
6226                                                 }
6227                                                 else
6228                                                         precision = argpos++;
6229                                                 precision = GETARG_FLOAT(precision);
6230                                         }
6231                                         else if(*s >= '0' && *s <= '9')
6232                                         {
6233                                                 precision = strtol(s, &err, 10);
6234                                                 if(!err)
6235                                                 {
6236                                                         VM_Warning("VM_sprintf: invalid directive in %s: %s\n", PRVM_NAME, s0);
6237                                                         goto finished;
6238                                                 }
6239                                                 s = err;
6240                                         }
6241                                         else
6242                                         {
6243                                                 VM_Warning("VM_sprintf: invalid directive in %s: %s\n", PRVM_NAME, s0);
6244                                                 goto finished;
6245                                         }
6246                                 }
6247
6248                                 for(;;)
6249                                 {
6250                                         switch(*s)
6251                                         {
6252                                                 case 'h': isfloat = 1; break;
6253                                                 case 'l': isfloat = 0; break;
6254                                                 case 'L': isfloat = 0; break;
6255                                                 case 'j': break;
6256                                                 case 'z': break;
6257                                                 case 't': break;
6258                                                 default:
6259                                                         goto nolength;
6260                                         }
6261                                         ++s;
6262                                 }
6263 nolength:
6264
6265                                 // now s points to the final directive char and is no longer changed
6266                                 if(isfloat < 0)
6267                                 {
6268                                         if(*s == 'i')
6269                                                 isfloat = 0;
6270                                         else
6271                                                 isfloat = 1;
6272                                 }
6273
6274                                 if(thisarg < 0)
6275                                         thisarg = argpos++;
6276
6277                                 if(o < end - 1)
6278                                 {
6279                                         f = &formatbuf[1];
6280                                         if(*s != 's' && *s != 'c')
6281                                                 if(flags & PRINTF_ALTERNATE) *f++ = '#';
6282                                         if(flags & PRINTF_ZEROPAD) *f++ = '0';
6283                                         if(flags & PRINTF_LEFT) *f++ = '-';
6284                                         if(flags & PRINTF_SPACEPOSITIVE) *f++ = ' ';
6285                                         if(flags & PRINTF_SIGNPOSITIVE) *f++ = '+';
6286                                         *f++ = '*';
6287                                         if(precision >= 0)
6288                                         {
6289                                                 *f++ = '.';
6290                                                 *f++ = '*';
6291                                         }
6292                                         *f++ = *s;
6293                                         *f++ = 0;
6294
6295                                         if(width < 0) // not set
6296                                                 width = 0;
6297
6298                                         switch(*s)
6299                                         {
6300                                                 case 'd': case 'i':
6301                                                         if(precision < 0) // not set
6302                                                                 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? (int) GETARG_FLOAT(thisarg) : (int) GETARG_INT(thisarg)));
6303                                                         else
6304                                                                 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? (int) GETARG_FLOAT(thisarg) : (int) GETARG_INT(thisarg)));
6305                                                         break;
6306                                                 case 'o': case 'u': case 'x': case 'X':
6307                                                         if(precision < 0) // not set
6308                                                                 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg)));
6309                                                         else
6310                                                                 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg)));
6311                                                         break;
6312                                                 case 'e': case 'E': case 'f': case 'F': case 'g': case 'G':
6313                                                         if(precision < 0) // not set
6314                                                                 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? (double) GETARG_FLOAT(thisarg) : (double) GETARG_INT(thisarg)));
6315                                                         else
6316                                                                 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? (double) GETARG_FLOAT(thisarg) : (double) GETARG_INT(thisarg)));
6317                                                         break;
6318                                                 case 'v': case 'V':
6319                                                         f[-2] += 'g' - 'v';
6320                                                         if(precision < 0) // not set
6321                                                                 o += dpsnprintf(o, end - o, va("%s %s %s", /* NESTED SPRINTF IS NESTED */ formatbuf, formatbuf, formatbuf),
6322                                                                         width, (isfloat ? (double) GETARG_VECTOR(thisarg)[0] : (double) GETARG_INTVECTOR(thisarg)[0]),
6323                                                                         width, (isfloat ? (double) GETARG_VECTOR(thisarg)[1] : (double) GETARG_INTVECTOR(thisarg)[1]),
6324                                                                         width, (isfloat ? (double) GETARG_VECTOR(thisarg)[2] : (double) GETARG_INTVECTOR(thisarg)[2])
6325                                                                 );
6326                                                         else
6327                                                                 o += dpsnprintf(o, end - o, va("%s %s %s", /* NESTED SPRINTF IS NESTED */ formatbuf, formatbuf, formatbuf),
6328                                                                         width, precision, (isfloat ? (double) GETARG_VECTOR(thisarg)[0] : (double) GETARG_INTVECTOR(thisarg)[0]),
6329                                                                         width, precision, (isfloat ? (double) GETARG_VECTOR(thisarg)[1] : (double) GETARG_INTVECTOR(thisarg)[1]),
6330                                                                         width, precision, (isfloat ? (double) GETARG_VECTOR(thisarg)[2] : (double) GETARG_INTVECTOR(thisarg)[2])
6331                                                                 );
6332                                                         break;
6333                                                 case 'c':
6334                                                         if(flags & PRINTF_ALTERNATE)
6335                                                         {
6336                                                                 if(precision < 0) // not set
6337                                                                         o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg)));
6338                                                                 else
6339                                                                         o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg)));
6340                                                         }
6341                                                         else
6342                                                         {
6343                                                                 unsigned int c = (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg));
6344                                                                 const char *buf = u8_encodech(c, NULL);
6345                                                                 if(!buf)
6346                                                                         buf = "";
6347                                                                 if(precision < 0) // not set
6348                                                                         precision = end - o - 1;
6349                                                                 o += u8_strpad(o, end - o, buf, (flags & PRINTF_LEFT) != 0, width, precision);
6350                                                         }
6351                                                         break;
6352                                                 case 's':
6353                                                         if(flags & PRINTF_ALTERNATE)
6354                                                         {
6355                                                                 if(precision < 0) // not set
6356                                                                         o += dpsnprintf(o, end - o, formatbuf, width, GETARG_STRING(thisarg));
6357                                                                 else
6358                                                                         o += dpsnprintf(o, end - o, formatbuf, width, precision, GETARG_STRING(thisarg));
6359                                                         }
6360                                                         else
6361                                                         {
6362                                                                 if(precision < 0) // not set
6363                                                                         precision = end - o - 1;
6364                                                                 o += u8_strpad(o, end - o, GETARG_STRING(thisarg), (flags & PRINTF_LEFT) != 0, width, precision);
6365                                                         }
6366                                                         break;
6367                                                 default:
6368                                                         VM_Warning("VM_sprintf: invalid directive in %s: %s\n", PRVM_NAME, s0);
6369                                                         goto finished;
6370                                         }
6371                                 }
6372                                 ++s;
6373                                 break;
6374                         default:
6375 verbatim:
6376                                 if(o < end - 1)
6377                                         *o++ = *s++;
6378                                 break;
6379                 }
6380         }
6381 finished:
6382         *o = 0;
6383         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(outbuf);
6384 }
6385
6386
6387 // surface querying
6388
6389 static dp_model_t *getmodel(prvm_edict_t *ed)
6390 {
6391         switch(PRVM_GetProgNr())
6392         {
6393                 case PRVM_SERVERPROG:
6394                         return SV_GetModelFromEdict(ed);
6395                 case PRVM_CLIENTPROG:
6396                         return CL_GetModelFromEdict(ed);
6397                 default:
6398                         return NULL;
6399         }
6400 }
6401
6402 typedef struct
6403 {
6404         unsigned int progid;
6405         dp_model_t *model;
6406         frameblend_t frameblend[MAX_FRAMEBLENDS];
6407         skeleton_t *skeleton_p;
6408         skeleton_t skeleton;
6409         float *data_vertex3f;
6410         float *data_svector3f;
6411         float *data_tvector3f;
6412         float *data_normal3f;
6413         int max_vertices;
6414         float *buf_vertex3f;
6415         float *buf_svector3f;
6416         float *buf_tvector3f;
6417         float *buf_normal3f;
6418 }
6419 animatemodel_cache_t;
6420 static animatemodel_cache_t animatemodel_cache;
6421
6422 void animatemodel(dp_model_t *model, prvm_edict_t *ed)
6423 {
6424         skeleton_t *skeleton;
6425         int skeletonindex = -1;
6426         qboolean need = false;
6427         if(!(model->surfmesh.isanimated && model->AnimateVertices))
6428         {
6429                 animatemodel_cache.data_vertex3f = model->surfmesh.data_vertex3f;
6430                 animatemodel_cache.data_svector3f = model->surfmesh.data_svector3f;
6431                 animatemodel_cache.data_tvector3f = model->surfmesh.data_tvector3f;
6432                 animatemodel_cache.data_normal3f = model->surfmesh.data_normal3f;
6433                 return;
6434         }
6435         if(animatemodel_cache.progid != prog->id)
6436                 memset(&animatemodel_cache, 0, sizeof(animatemodel_cache));
6437         need |= (animatemodel_cache.model != model);
6438         VM_GenerateFrameGroupBlend(ed->priv.server->framegroupblend, ed);
6439         VM_FrameBlendFromFrameGroupBlend(ed->priv.server->frameblend, ed->priv.server->framegroupblend, model);
6440         need |= (memcmp(&animatemodel_cache.frameblend, &ed->priv.server->frameblend, sizeof(ed->priv.server->frameblend))) != 0;
6441         skeletonindex = (int)PRVM_gameedictfloat(ed, skeletonindex) - 1;
6442         if (!(skeletonindex >= 0 && skeletonindex < MAX_EDICTS && (skeleton = prog->skeletons[skeletonindex]) && skeleton->model->num_bones == ed->priv.server->skeleton.model->num_bones))
6443                 skeleton = NULL;
6444         need |= (animatemodel_cache.skeleton_p != skeleton);
6445         if(skeleton)
6446                 need |= (memcmp(&animatemodel_cache.skeleton, skeleton, sizeof(ed->priv.server->skeleton))) != 0;
6447         if(!need)
6448                 return;
6449         if(model->surfmesh.num_vertices > animatemodel_cache.max_vertices)
6450         {
6451                 animatemodel_cache.max_vertices = model->surfmesh.num_vertices * 2;
6452                 if(animatemodel_cache.buf_vertex3f) Mem_Free(animatemodel_cache.buf_vertex3f);
6453                 if(animatemodel_cache.buf_svector3f) Mem_Free(animatemodel_cache.buf_svector3f);
6454                 if(animatemodel_cache.buf_tvector3f) Mem_Free(animatemodel_cache.buf_tvector3f);
6455                 if(animatemodel_cache.buf_normal3f) Mem_Free(animatemodel_cache.buf_normal3f);
6456                 animatemodel_cache.buf_vertex3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache.max_vertices);
6457                 animatemodel_cache.buf_svector3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache.max_vertices);
6458                 animatemodel_cache.buf_tvector3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache.max_vertices);
6459                 animatemodel_cache.buf_normal3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache.max_vertices);
6460         }
6461         animatemodel_cache.data_vertex3f = animatemodel_cache.buf_vertex3f;
6462         animatemodel_cache.data_svector3f = animatemodel_cache.buf_svector3f;
6463         animatemodel_cache.data_tvector3f = animatemodel_cache.buf_tvector3f;
6464         animatemodel_cache.data_normal3f = animatemodel_cache.buf_normal3f;
6465         VM_UpdateEdictSkeleton(ed, model, ed->priv.server->frameblend);
6466         model->AnimateVertices(model, ed->priv.server->frameblend, &ed->priv.server->skeleton, animatemodel_cache.data_vertex3f, animatemodel_cache.data_normal3f, animatemodel_cache.data_svector3f, animatemodel_cache.data_tvector3f);
6467         animatemodel_cache.progid = prog->id;
6468         animatemodel_cache.model = model;
6469         memcpy(&animatemodel_cache.frameblend, &ed->priv.server->frameblend, sizeof(ed->priv.server->frameblend));
6470         animatemodel_cache.skeleton_p = skeleton;
6471         if(skeleton)
6472                 memcpy(&animatemodel_cache.skeleton, skeleton, sizeof(ed->priv.server->skeleton));
6473 }
6474
6475 static void getmatrix(prvm_edict_t *ed, matrix4x4_t *out)
6476 {
6477         switch(PRVM_GetProgNr())
6478         {
6479                 case PRVM_SERVERPROG:
6480                         SV_GetEntityMatrix(ed, out, false);
6481                         break;
6482                 case PRVM_CLIENTPROG:
6483                         CL_GetEntityMatrix(ed, out, false);
6484                         break;
6485                 default:
6486                         *out = identitymatrix;
6487                         break;
6488         }
6489 }
6490
6491 static void applytransform_forward(const vec3_t in, prvm_edict_t *ed, vec3_t out)
6492 {
6493         matrix4x4_t m;
6494         getmatrix(ed, &m);
6495         Matrix4x4_Transform(&m, in, out);
6496 }
6497
6498 static void applytransform_forward_direction(const vec3_t in, prvm_edict_t *ed, vec3_t out)
6499 {
6500         matrix4x4_t m;
6501         getmatrix(ed, &m);
6502         Matrix4x4_Transform3x3(&m, in, out);
6503 }
6504
6505 static void applytransform_inverted(const vec3_t in, prvm_edict_t *ed, vec3_t out)
6506 {
6507         matrix4x4_t m, n;
6508         getmatrix(ed, &m);
6509         Matrix4x4_Invert_Full(&n, &m);
6510         Matrix4x4_Transform3x3(&n, in, out);
6511 }
6512
6513 static void applytransform_forward_normal(const vec3_t in, prvm_edict_t *ed, vec3_t out)
6514 {
6515         matrix4x4_t m;
6516         float p[4];
6517         getmatrix(ed, &m);
6518         Matrix4x4_TransformPositivePlane(&m, in[0], in[1], in[2], 0, p);
6519         VectorCopy(p, out);
6520 }
6521
6522 static void clippointtosurface(prvm_edict_t *ed, dp_model_t *model, msurface_t *surface, vec3_t p, vec3_t out)
6523 {
6524         int i, j, k;
6525         float *v[3], facenormal[3], edgenormal[3], sidenormal[3], temp[3], offsetdist, dist, bestdist;
6526         const int *e;
6527         animatemodel(model, ed);
6528         bestdist = 1000000000;
6529         VectorCopy(p, out);
6530         for (i = 0, e = (model->surfmesh.data_element3i + 3 * surface->num_firsttriangle);i < surface->num_triangles;i++, e += 3)
6531         {
6532                 // clip original point to each triangle of the surface and find the
6533                 // triangle that is closest
6534                 v[0] = animatemodel_cache.data_vertex3f + e[0] * 3;
6535                 v[1] = animatemodel_cache.data_vertex3f + e[1] * 3;
6536                 v[2] = animatemodel_cache.data_vertex3f + e[2] * 3;
6537                 TriangleNormal(v[0], v[1], v[2], facenormal);
6538                 VectorNormalize(facenormal);
6539                 offsetdist = DotProduct(v[0], facenormal) - DotProduct(p, facenormal);
6540                 VectorMA(p, offsetdist, facenormal, temp);
6541                 for (j = 0, k = 2;j < 3;k = j, j++)
6542                 {
6543                         VectorSubtract(v[k], v[j], edgenormal);
6544                         CrossProduct(edgenormal, facenormal, sidenormal);
6545                         VectorNormalize(sidenormal);
6546                         offsetdist = DotProduct(v[k], sidenormal) - DotProduct(temp, sidenormal);
6547                         if (offsetdist < 0)
6548                                 VectorMA(temp, offsetdist, sidenormal, temp);
6549                 }
6550                 dist = VectorDistance2(temp, p);
6551                 if (bestdist > dist)
6552                 {
6553                         bestdist = dist;
6554                         VectorCopy(temp, out);
6555                 }
6556         }
6557 }
6558
6559 static msurface_t *getsurface(dp_model_t *model, int surfacenum)
6560 {
6561         if (surfacenum < 0 || surfacenum >= model->nummodelsurfaces)
6562                 return NULL;
6563         return model->data_surfaces + surfacenum + model->firstmodelsurface;
6564 }
6565
6566
6567 //PF_getsurfacenumpoints, // #434 float(entity e, float s) getsurfacenumpoints = #434;
6568 void VM_getsurfacenumpoints(void)
6569 {
6570         dp_model_t *model;
6571         msurface_t *surface;
6572         VM_SAFEPARMCOUNT(2, VM_getsurfacenumpoints);
6573         // return 0 if no such surface
6574         if (!(model = getmodel(PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6575         {
6576                 PRVM_G_FLOAT(OFS_RETURN) = 0;
6577                 return;
6578         }
6579
6580         // note: this (incorrectly) assumes it is a simple polygon
6581         PRVM_G_FLOAT(OFS_RETURN) = surface->num_vertices;
6582 }
6583 //PF_getsurfacepoint,     // #435 vector(entity e, float s, float n) getsurfacepoint = #435;
6584 void VM_getsurfacepoint(void)
6585 {
6586         prvm_edict_t *ed;
6587         dp_model_t *model;
6588         msurface_t *surface;
6589         int pointnum;
6590         VM_SAFEPARMCOUNT(3, VM_getsurfacepoint);
6591         VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6592         ed = PRVM_G_EDICT(OFS_PARM0);
6593         if (!(model = getmodel(ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6594                 return;
6595         // note: this (incorrectly) assumes it is a simple polygon
6596         pointnum = (int)PRVM_G_FLOAT(OFS_PARM2);
6597         if (pointnum < 0 || pointnum >= surface->num_vertices)
6598                 return;
6599         animatemodel(model, ed);
6600         applytransform_forward(&(animatemodel_cache.data_vertex3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, PRVM_G_VECTOR(OFS_RETURN));
6601 }
6602 //PF_getsurfacepointattribute,     // #486 vector(entity e, float s, float n, float a) getsurfacepointattribute = #486;
6603 // float SPA_POSITION = 0;
6604 // float SPA_S_AXIS = 1;
6605 // float SPA_T_AXIS = 2;
6606 // float SPA_R_AXIS = 3; // same as SPA_NORMAL
6607 // float SPA_TEXCOORDS0 = 4;
6608 // float SPA_LIGHTMAP0_TEXCOORDS = 5;
6609 // float SPA_LIGHTMAP0_COLOR = 6;
6610 void VM_getsurfacepointattribute(void)
6611 {
6612         prvm_edict_t *ed;
6613         dp_model_t *model;
6614         msurface_t *surface;
6615         int pointnum;
6616         int attributetype;
6617
6618         VM_SAFEPARMCOUNT(4, VM_getsurfacepoint);
6619         VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6620         ed = PRVM_G_EDICT(OFS_PARM0);
6621         if (!(model = getmodel(ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6622                 return;
6623         pointnum = (int)PRVM_G_FLOAT(OFS_PARM2);
6624         if (pointnum < 0 || pointnum >= surface->num_vertices)
6625                 return;
6626         attributetype = (int) PRVM_G_FLOAT(OFS_PARM3);
6627
6628         animatemodel(model, ed);
6629
6630         switch( attributetype ) {
6631                 // float SPA_POSITION = 0;
6632                 case 0:
6633                         applytransform_forward(&(animatemodel_cache.data_vertex3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, PRVM_G_VECTOR(OFS_RETURN));
6634                         break;
6635                 // float SPA_S_AXIS = 1;
6636                 case 1:
6637                         applytransform_forward_direction(&(animatemodel_cache.data_svector3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, PRVM_G_VECTOR(OFS_RETURN));
6638                         break;
6639                 // float SPA_T_AXIS = 2;
6640                 case 2:
6641                         applytransform_forward_direction(&(animatemodel_cache.data_tvector3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, PRVM_G_VECTOR(OFS_RETURN));
6642                         break;
6643                 // float SPA_R_AXIS = 3; // same as SPA_NORMAL
6644                 case 3:
6645                         applytransform_forward_direction(&(animatemodel_cache.data_normal3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, PRVM_G_VECTOR(OFS_RETURN));
6646                         break;
6647                 // float SPA_TEXCOORDS0 = 4;
6648                 case 4: {
6649                         float *ret = PRVM_G_VECTOR(OFS_RETURN);
6650                         float *texcoord = &(model->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[pointnum * 2];
6651                         ret[0] = texcoord[0];
6652                         ret[1] = texcoord[1];
6653                         ret[2] = 0.0f;
6654                         break;
6655                 }
6656                 // float SPA_LIGHTMAP0_TEXCOORDS = 5;
6657                 case 5: {
6658                         float *ret = PRVM_G_VECTOR(OFS_RETURN);
6659                         float *texcoord = &(model->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[pointnum * 2];
6660                         ret[0] = texcoord[0];
6661                         ret[1] = texcoord[1];
6662                         ret[2] = 0.0f;
6663                         break;
6664                 }
6665                 // float SPA_LIGHTMAP0_COLOR = 6;
6666                 case 6:
6667                         // ignore alpha for now..
6668                         VectorCopy( &(model->surfmesh.data_lightmapcolor4f + 4 * surface->num_firstvertex)[pointnum * 4], PRVM_G_VECTOR(OFS_RETURN));
6669                         break;
6670                 default:
6671                         VectorSet( PRVM_G_VECTOR(OFS_RETURN), 0.0f, 0.0f, 0.0f );
6672                         break;
6673         }
6674 }
6675 //PF_getsurfacenormal,    // #436 vector(entity e, float s) getsurfacenormal = #436;
6676 void VM_getsurfacenormal(void)
6677 {
6678         dp_model_t *model;
6679         msurface_t *surface;
6680         vec3_t normal;
6681         VM_SAFEPARMCOUNT(2, VM_getsurfacenormal);
6682         VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6683         if (!(model = getmodel(PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6684                 return;
6685         // note: this only returns the first triangle, so it doesn't work very
6686         // well for curved surfaces or arbitrary meshes
6687         animatemodel(model, PRVM_G_EDICT(OFS_PARM0));
6688         TriangleNormal((animatemodel_cache.data_vertex3f + 3 * surface->num_firstvertex), (animatemodel_cache.data_vertex3f + 3 * surface->num_firstvertex) + 3, (animatemodel_cache.data_vertex3f + 3 * surface->num_firstvertex) + 6, normal);
6689         applytransform_forward_normal(normal, PRVM_G_EDICT(OFS_PARM0), PRVM_G_VECTOR(OFS_RETURN));
6690         VectorNormalize(PRVM_G_VECTOR(OFS_RETURN));
6691 }
6692 //PF_getsurfacetexture,   // #437 string(entity e, float s) getsurfacetexture = #437;
6693 void VM_getsurfacetexture(void)
6694 {
6695         dp_model_t *model;
6696         msurface_t *surface;
6697         VM_SAFEPARMCOUNT(2, VM_getsurfacetexture);
6698         PRVM_G_INT(OFS_RETURN) = OFS_NULL;
6699         if (!(model = getmodel(PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6700                 return;
6701         PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(surface->texture->name);
6702 }
6703 //PF_getsurfacenearpoint, // #438 float(entity e, vector p) getsurfacenearpoint = #438;
6704 void VM_getsurfacenearpoint(void)
6705 {
6706         int surfacenum, best;
6707         vec3_t clipped, p;
6708         vec_t dist, bestdist;
6709         prvm_edict_t *ed;
6710         dp_model_t *model;
6711         msurface_t *surface;
6712         vec_t *point;
6713         VM_SAFEPARMCOUNT(2, VM_getsurfacenearpoint);
6714         PRVM_G_FLOAT(OFS_RETURN) = -1;
6715         ed = PRVM_G_EDICT(OFS_PARM0);
6716         point = PRVM_G_VECTOR(OFS_PARM1);
6717
6718         if (!ed || ed->priv.server->free)
6719                 return;
6720         model = getmodel(ed);
6721         if (!model || !model->num_surfaces)
6722                 return;
6723
6724         animatemodel(model, ed);
6725
6726         applytransform_inverted(point, ed, p);
6727         best = -1;
6728         bestdist = 1000000000;
6729         for (surfacenum = 0;surfacenum < model->nummodelsurfaces;surfacenum++)
6730         {
6731                 surface = model->data_surfaces + surfacenum + model->firstmodelsurface;
6732                 // first see if the nearest point on the surface's box is closer than the previous match
6733                 clipped[0] = bound(surface->mins[0], p[0], surface->maxs[0]) - p[0];
6734                 clipped[1] = bound(surface->mins[1], p[1], surface->maxs[1]) - p[1];
6735                 clipped[2] = bound(surface->mins[2], p[2], surface->maxs[2]) - p[2];
6736                 dist = VectorLength2(clipped);
6737                 if (dist < bestdist)
6738                 {
6739                         // it is, check the nearest point on the actual geometry
6740                         clippointtosurface(ed, model, surface, p, clipped);
6741                         VectorSubtract(clipped, p, clipped);
6742                         dist += VectorLength2(clipped);
6743                         if (dist < bestdist)
6744                         {
6745                                 // that's closer too, store it as the best match
6746                                 best = surfacenum;
6747                                 bestdist = dist;
6748                         }
6749                 }
6750         }
6751         PRVM_G_FLOAT(OFS_RETURN) = best;
6752 }
6753 //PF_getsurfaceclippedpoint, // #439 vector(entity e, float s, vector p) getsurfaceclippedpoint = #439;
6754 void VM_getsurfaceclippedpoint(void)
6755 {
6756         prvm_edict_t *ed;
6757         dp_model_t *model;
6758         msurface_t *surface;
6759         vec3_t p, out;
6760         VM_SAFEPARMCOUNT(3, VM_te_getsurfaceclippedpoint);
6761         VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6762         ed = PRVM_G_EDICT(OFS_PARM0);
6763         if (!(model = getmodel(ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6764                 return;
6765         animatemodel(model, ed);
6766         applytransform_inverted(PRVM_G_VECTOR(OFS_PARM2), ed, p);
6767         clippointtosurface(ed, model, surface, p, out);
6768         VectorAdd(out, PRVM_serveredictvector(ed, origin), PRVM_G_VECTOR(OFS_RETURN));
6769 }
6770
6771 //PF_getsurfacenumtriangles, // #??? float(entity e, float s) getsurfacenumtriangles = #???;
6772 void VM_getsurfacenumtriangles(void)
6773 {
6774        dp_model_t *model;
6775        msurface_t *surface;
6776        VM_SAFEPARMCOUNT(2, VM_SV_getsurfacenumtriangles);
6777        // return 0 if no such surface
6778        if (!(model = getmodel(PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6779        {
6780                PRVM_G_FLOAT(OFS_RETURN) = 0;
6781                return;
6782        }
6783
6784        // note: this (incorrectly) assumes it is a simple polygon
6785        PRVM_G_FLOAT(OFS_RETURN) = surface->num_triangles;
6786 }
6787 //PF_getsurfacetriangle,     // #??? vector(entity e, float s, float n) getsurfacetriangle = #???;
6788 void VM_getsurfacetriangle(void)
6789 {
6790        const vec3_t d = {-1, -1, -1};
6791        prvm_edict_t *ed;
6792        dp_model_t *model;
6793        msurface_t *surface;
6794        int trinum;
6795        VM_SAFEPARMCOUNT(3, VM_SV_getsurfacetriangle);
6796        VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6797        ed = PRVM_G_EDICT(OFS_PARM0);
6798        if (!(model = getmodel(ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6799                return;
6800        trinum = (int)PRVM_G_FLOAT(OFS_PARM2);
6801        if (trinum < 0 || trinum >= surface->num_triangles)
6802                return;
6803        // FIXME: implement rotation/scaling
6804        VectorMA(&(model->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[trinum * 3], surface->num_firstvertex, d, PRVM_G_VECTOR(OFS_RETURN));
6805 }
6806
6807 //
6808 // physics builtins
6809 //
6810
6811 void World_Physics_ApplyCmd(prvm_edict_t *ed, edict_odefunc_t *f);
6812
6813 #define VM_physics_ApplyCmd(ed,f) if (!ed->priv.server->ode_body) VM_physics_newstackfunction(ed, f); else World_Physics_ApplyCmd(ed, f)
6814
6815 edict_odefunc_t *VM_physics_newstackfunction(prvm_edict_t *ed, edict_odefunc_t *f)
6816 {
6817         edict_odefunc_t *newfunc, *func;
6818
6819         newfunc = (edict_odefunc_t *)Mem_Alloc(prog->progs_mempool, sizeof(edict_odefunc_t));
6820         memcpy(newfunc, f, sizeof(edict_odefunc_t));
6821         newfunc->next = NULL;
6822         if (!ed->priv.server->ode_func)
6823                 ed->priv.server->ode_func = newfunc;
6824         else
6825         {
6826                 for (func = ed->priv.server->ode_func; func->next; func = func->next);
6827                 func->next = newfunc;
6828         }
6829         return newfunc;
6830 }
6831
6832 // void(entity e, float physics_enabled) physics_enable = #;
6833 void VM_physics_enable(void)
6834 {
6835         prvm_edict_t *ed;
6836         edict_odefunc_t f;
6837         
6838         VM_SAFEPARMCOUNT(2, VM_physics_enable);
6839         ed = PRVM_G_EDICT(OFS_PARM0);
6840         if (!ed)
6841         {
6842                 if (developer.integer > 0)
6843                         VM_Warning("VM_physics_enable: null entity!\n");
6844                 return;
6845         }
6846         // entity should have MOVETYPE_PHYSICS already set, this can damage memory (making leaked allocation) so warn about this even if non-developer
6847         if (PRVM_serveredictfloat(ed, movetype) != MOVETYPE_PHYSICS)
6848         {
6849                 VM_Warning("VM_physics_enable: entity is not MOVETYPE_PHYSICS!\n");
6850                 return;
6851         }
6852         f.type = PRVM_G_FLOAT(OFS_PARM1) == 0 ? ODEFUNC_DISABLE : ODEFUNC_ENABLE;
6853         VM_physics_ApplyCmd(ed, &f);
6854 }
6855
6856 // void(entity e, vector force, vector relative_ofs) physics_addforce = #;
6857 void VM_physics_addforce(void)
6858 {
6859         prvm_edict_t *ed;
6860         edict_odefunc_t f;
6861         
6862         VM_SAFEPARMCOUNT(3, VM_physics_addforce);
6863         ed = PRVM_G_EDICT(OFS_PARM0);
6864         if (!ed)
6865         {
6866                 if (developer.integer > 0)
6867                         VM_Warning("VM_physics_addforce: null entity!\n");
6868                 return;
6869         }
6870         // entity should have MOVETYPE_PHYSICS already set, this can damage memory (making leaked allocation) so warn about this even if non-developer
6871         if (PRVM_serveredictfloat(ed, movetype) != MOVETYPE_PHYSICS)
6872         {
6873                 VM_Warning("VM_physics_addforce: entity is not MOVETYPE_PHYSICS!\n");
6874                 return;
6875         }
6876         f.type = ODEFUNC_RELFORCEATPOS;
6877         VectorCopy(PRVM_G_VECTOR(OFS_PARM1), f.v1);
6878         VectorSubtract(PRVM_serveredictvector(ed, origin), PRVM_G_VECTOR(OFS_PARM2), f.v2);
6879         VM_physics_ApplyCmd(ed, &f);
6880 }
6881
6882 // void(entity e, vector torque) physics_addtorque = #;
6883 void VM_physics_addtorque(void)
6884 {
6885         prvm_edict_t *ed;
6886         edict_odefunc_t f;
6887         
6888         VM_SAFEPARMCOUNT(2, VM_physics_addtorque);
6889         ed = PRVM_G_EDICT(OFS_PARM0);
6890         if (!ed)
6891         {
6892                 if (developer.integer > 0)
6893                         VM_Warning("VM_physics_addtorque: null entity!\n");
6894                 return;
6895         }
6896         // entity should have MOVETYPE_PHYSICS already set, this can damage memory (making leaked allocation) so warn about this even if non-developer
6897         if (PRVM_serveredictfloat(ed, movetype) != MOVETYPE_PHYSICS)
6898         {
6899                 VM_Warning("VM_physics_addtorque: entity is not MOVETYPE_PHYSICS!\n");
6900                 return;
6901         }
6902         f.type = ODEFUNC_RELTORQUE;
6903         VectorCopy(PRVM_G_VECTOR(OFS_PARM1), f.v1);
6904         VM_physics_ApplyCmd(ed, &f);
6905 }