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