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