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