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