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