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