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