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
13 #include "cl_collision.h"
14 #include "clvm_cmds.h"
19 extern cvar_t prvm_backtraceforwarnings;
21 extern dllhandle_t ode_dll;
24 // LadyHavoc: changed this to NOT use a return statement, so that it can be used in functions that must return a value
25 void VM_Warning(prvm_prog_t *prog, const char *fmt, ...)
28 char msg[MAX_INPUTLINE];
29 static double recursive = -1;
30 int outfd = sys.outfd;
32 // set output to stderr
33 sys.outfd = fileno(stderr);
36 dpvsnprintf(msg,sizeof(msg),fmt,argptr);
39 Con_Printf(CON_WARN "%s VM warning: %s", prog->name, msg);
41 // TODO: either add a cvar/cmd to control the state dumping or replace some of the calls with Con_Printf [9/13/2006 Black]
42 if(prvm_backtraceforwarnings.integer && recursive != host.realtime) // NOTE: this compares to the time, just in case if PRVM_PrintState causes a Host_Error and keeps recursive set
44 recursive = host.realtime;
45 PRVM_PrintState(prog, 0);
49 // restore configured outfd
54 //============================================================================
57 // TODO DONE: move vm_files and vm_fssearchlist to prvm_prog_t struct
58 // TODO: move vm_files and vm_fssearchlist back [9/13/2006 Black]
59 // TODO: (move vm_files and vm_fssearchlist to prvm_prog_t struct again) [2007-01-23 LadyHavoc]
60 // TODO: will this war ever end? [2007-01-23 LadyHavoc]
62 void VM_CheckEmptyString(prvm_prog_t *prog, const char *s)
64 if (ISWHITESPACE(s[0]))
65 prog->error_cmd("%s: Bad string", prog->name);
68 qbool PRVM_ConsoleCommand(prvm_prog_t *prog, const char *text, size_t textlen, int *func, qbool preserve_self, int curself, double ptime, const char *error_message)
70 int restorevm_tempstringsbuf_cursize;
71 int save_self = 0; // hush compiler warning
80 save_self = PRVM_gameglobaledict(self);
82 PRVM_gameglobalfloat(time) = ptime;
83 PRVM_gameglobaledict(self) = curself;
84 restorevm_tempstringsbuf_cursize = prog->tempstringsbuf.cursize;
85 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(prog, text, textlen);
86 prog->ExecuteProgram(prog, *func, error_message);
87 prog->tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
89 PRVM_gameglobaledict(self) = save_self;
90 r = (int) PRVM_G_FLOAT(OFS_RETURN) != 0;
96 void VM_GenerateFrameGroupBlend(prvm_prog_t *prog, framegroupblend_t *framegroupblend, const prvm_edict_t *ed)
98 // self.frame is the interpolation target (new frame)
99 // self.frame1time is the animation base time for the interpolation target
100 // self.frame2 is the interpolation start (previous frame)
101 // self.frame2time is the animation base time for the interpolation start
102 // self.lerpfrac is the interpolation strength for self.frame2
103 // self.lerpfrac3 is the interpolation strength for self.frame3
104 // self.lerpfrac4 is the interpolation strength for self.frame4
105 // pitch angle on a player model where the animator set up 5 sets of
106 // animations and the csqc simply lerps between sets)
107 framegroupblend[0].frame = (int) PRVM_gameedictfloat(ed, frame );
108 framegroupblend[1].frame = (int) PRVM_gameedictfloat(ed, frame2 );
109 framegroupblend[2].frame = (int) PRVM_gameedictfloat(ed, frame3 );
110 framegroupblend[3].frame = (int) PRVM_gameedictfloat(ed, frame4 );
111 framegroupblend[0].start = PRVM_gameedictfloat(ed, frame1time);
112 framegroupblend[1].start = PRVM_gameedictfloat(ed, frame2time);
113 framegroupblend[2].start = PRVM_gameedictfloat(ed, frame3time);
114 framegroupblend[3].start = PRVM_gameedictfloat(ed, frame4time);
115 framegroupblend[1].lerp = PRVM_gameedictfloat(ed, lerpfrac );
116 framegroupblend[2].lerp = PRVM_gameedictfloat(ed, lerpfrac3 );
117 framegroupblend[3].lerp = PRVM_gameedictfloat(ed, lerpfrac4 );
118 // assume that the (missing) lerpfrac1 is whatever remains after lerpfrac2+lerpfrac3+lerpfrac4 are summed
119 framegroupblend[0].lerp = 1 - framegroupblend[1].lerp - framegroupblend[2].lerp - framegroupblend[3].lerp;
122 // LadyHavoc: quite tempting to break apart this function to reuse the
123 // duplicated code, but I suspect it is better for performance
125 void VM_FrameBlendFromFrameGroupBlend(frameblend_t *frameblend, const framegroupblend_t *framegroupblend, const model_t *model, double curtime)
127 int sub2, numframes, f, i, k;
128 int isfirstframegroup = true;
130 double sublerp, lerp, d;
131 const animscene_t *scene;
132 const framegroupblend_t *g;
133 frameblend_t *blend = frameblend;
135 memset(blend, 0, MAX_FRAMEBLENDS * sizeof(*blend));
137 // rpolzer: Not testing isanimated here - a model might have
138 // "animations" that move no vertices (but only bones), thus rendering
139 // may assume it's not animated while processing can't.
146 nolerp = ((model->type == mod_sprite) ? !r_lerpsprites.integer : !r_lerpmodels.integer) || (model->nolerp == true);
147 numframes = model->numframes;
148 for (k = 0, g = framegroupblend;k < MAX_FRAMEGROUPBLENDS;k++, g++)
151 if ((unsigned int)f >= (unsigned int)numframes)
153 if (developer_extra.integer)
154 Con_DPrintf("VM_FrameBlendFromFrameGroupBlend: no such frame %d in model %s\n", f, model->name);
162 if (isfirstframegroup)
165 isfirstframegroup = false;
170 if (model->animscenes)
172 scene = model->animscenes + f;
173 f = scene->firstframe;
174 if (scene->framecount > 1)
176 // this code path is only used on .zym models and torches
177 sublerp = scene->framerate * (curtime - g->start);
178 f = (int) floor(sublerp);
181 if (sublerp < (1.0 / 65536.0f))
183 if (sublerp > (65535.0f / 65536.0f))
189 f = (f % scene->framecount);
190 sub2 = (sub2 % scene->framecount);
192 f = bound(0, f, (scene->framecount - 1)) + scene->firstframe;
193 sub2 = bound(0, sub2, (scene->framecount - 1)) + scene->firstframe;
195 // two framelerps produced from one animation
198 for (i = 0;i < MAX_FRAMEBLENDS;i++)
200 if (blend[i].lerp <= 0 || blend[i].subframe == sub2)
202 blend[i].subframe = sub2;
208 d = (1 - sublerp) * lerp;
213 for (i = 0;i < MAX_FRAMEBLENDS;i++)
215 if (blend[i].lerp <= 0 || blend[i].subframe == f)
217 blend[i].subframe = f;
226 void VM_UpdateEdictSkeleton(prvm_prog_t *prog, prvm_edict_t *ed, const model_t *edmodel, const frameblend_t *frameblend)
228 if (ed->priv.server->skeleton.model != edmodel)
230 VM_RemoveEdictSkeleton(prog, ed);
231 ed->priv.server->skeleton.model = edmodel;
233 if (!ed->priv.server->skeleton.model || !ed->priv.server->skeleton.model->num_bones)
235 if(ed->priv.server->skeleton.relativetransforms)
236 Mem_Free(ed->priv.server->skeleton.relativetransforms);
237 ed->priv.server->skeleton.relativetransforms = NULL;
242 int skeletonindex = -1;
243 skeleton_t *skeleton;
244 skeletonindex = (int)PRVM_gameedictfloat(ed, skeletonindex) - 1;
245 if (skeletonindex >= 0 && skeletonindex < MAX_EDICTS && (skeleton = prog->skeletons[skeletonindex]) && skeleton->model->num_bones == ed->priv.server->skeleton.model->num_bones)
247 // custom skeleton controlled by the game (FTE_CSQC_SKELETONOBJECTS)
248 if (!ed->priv.server->skeleton.relativetransforms)
249 ed->priv.server->skeleton.relativetransforms = (matrix4x4_t *)Mem_Alloc(prog->progs_mempool, ed->priv.server->skeleton.model->num_bones * sizeof(matrix4x4_t));
250 memcpy(ed->priv.server->skeleton.relativetransforms, skeleton->relativetransforms, ed->priv.server->skeleton.model->num_bones * sizeof(matrix4x4_t));
254 if(ed->priv.server->skeleton.relativetransforms)
255 Mem_Free(ed->priv.server->skeleton.relativetransforms);
256 ed->priv.server->skeleton.relativetransforms = NULL;
261 void VM_RemoveEdictSkeleton(prvm_prog_t *prog, prvm_edict_t *ed)
263 if (ed->priv.server->skeleton.relativetransforms)
264 Mem_Free(ed->priv.server->skeleton.relativetransforms);
265 memset(&ed->priv.server->skeleton, 0, sizeof(ed->priv.server->skeleton));
271 //============================================================================
275 // memccpy() is standard in POSIX.1-2001, POSIX.1-2008, SVr4, 4.3BSD, C23.
276 // Microsoft supports it, but apparently complains if we use it.
278 #define memccpy _memccpy
280 size_t VM_VarString(prvm_prog_t *prog, int first, char *out, size_t outsize)
285 char *outend = out + outsize - 1;
287 // bones_was_here: && out < outend improves perf significantly in some tests that don't trigger the warning,
288 // which seems odd, surely it would only help when the warning is printed?
289 for (i = first;i < prog->argc && out < outend;i++)
291 s = PRVM_G_STRING((OFS_PARM0+i*3));
294 // like dp_stpecpy but with a VM_Warning for use with `prvm_backtraceforwarnings 1`
295 p = (char *)memccpy(out, s, '\0', (outend + 1) - out);
300 VM_Warning(prog, "%lu of %lu bytes available, will truncate %lu byte string \"%s\"\n", (unsigned long)(outend - out), (unsigned long)outsize - 1, (unsigned long)strlen(s), s);
309 return outsize - ((outend + 1) - out);
316 returns true if the extension is supported by the server
318 checkextension(extensionname)
322 // kind of helper function
323 static qbool checkextension(prvm_prog_t *prog, const char *name)
327 for (e = prog->extensionstring;*e;e++)
329 if(!strcasecmp(*e, name))
332 // special sheck for ODE
333 if (!strncasecmp("DP_PHYSICS_ODE", name, 14))
335 #ifndef LINK_TO_LIBODE
336 return ode_dll ? true : false;
338 #ifdef LINK_TO_LIBODE
347 // special sheck for d0_blind_id
348 if (!strcasecmp("DP_CRYPTO", name))
349 return Crypto_Available();
350 if (!strcasecmp("DP_QC_DIGEST_SHA256", name))
351 return Crypto_Available();
353 // special shreck for libcurl
354 if (!strcasecmp("DP_QC_URI_GET", name) || !strcasecmp("DP_QC_URI_POST", name))
355 return Curl_Available();
363 void VM_checkextension(prvm_prog_t *prog)
365 VM_SAFEPARMCOUNT(1,VM_checkextension);
367 PRVM_G_FLOAT(OFS_RETURN) = checkextension(prog, PRVM_G_STRING(OFS_PARM0));
374 This is a TERMINAL error, which will kill off the entire prog.
380 void VM_error(prvm_prog_t *prog)
383 char string[VM_TEMPSTRING_MAXSIZE];
385 VM_VarString(prog, 0, string, sizeof(string));
386 Con_Printf(CON_ERROR "======%s ERROR in %s:\n%s\n", prog->name, PRVM_GetString(prog, prog->xfunction->s_name), string);
387 ed = PRVM_PROG_TO_EDICT(PRVM_allglobaledict(self));
388 PRVM_ED_Print(prog, ed, NULL);
390 prog->error_cmd("%s: Program error in function %s:\n%s\nTip: read above for entity information\n", prog->name, PRVM_GetString(prog, prog->xfunction->s_name), string);
397 Dumps out self, then an error message. The program is aborted and self is
398 removed, but the level can continue.
403 void VM_objerror(prvm_prog_t *prog)
406 char string[VM_TEMPSTRING_MAXSIZE];
408 VM_VarString(prog, 0, string, sizeof(string));
409 Con_Printf(CON_ERROR "======OBJECT ERROR======\n"); // , prog->name, PRVM_GetString(prog->xfunction->s_name), string); // or include them? FIXME
410 ed = PRVM_PROG_TO_EDICT(PRVM_allglobaledict(self));
411 PRVM_ED_Print(prog, ed, NULL);
412 PRVM_ED_Free (prog, ed);
413 Con_Printf(CON_ERROR "%s OBJECT ERROR in %s:\n%s\nTip: read above for entity information\n", prog->name, PRVM_GetString(prog, prog->xfunction->s_name), string);
425 void VM_print(prvm_prog_t *prog)
427 char string[VM_TEMPSTRING_MAXSIZE];
429 VM_VarString(prog, 0, string, sizeof(string));
437 broadcast print to everyone on server
442 void VM_bprint(prvm_prog_t *prog)
444 char string[VM_TEMPSTRING_MAXSIZE];
448 VM_Warning(prog, "VM_bprint: game is not server(%s) !\n", prog->name);
452 VM_VarString(prog, 0, string, sizeof(string));
453 SV_BroadcastPrint(string);
458 VM_sprint (menu & client but only if server.active == true)
460 single print to a specific client
462 sprint(float clientnum,...[string])
465 void VM_sprint(prvm_prog_t *prog)
469 char string[VM_TEMPSTRING_MAXSIZE];
471 VM_SAFEPARMCOUNTRANGE(1, 8, VM_sprint);
473 //find client for this entity
474 clientnum = (int)PRVM_G_FLOAT(OFS_PARM0);
475 if (!sv.active || clientnum < 0 || clientnum >= svs.maxclients || !svs.clients[clientnum].active)
477 VM_Warning(prog, "VM_sprint: %s: invalid client or server is not active !\n", prog->name);
481 client = svs.clients + clientnum;
482 if (!client->netconnection)
485 VM_VarString(prog, 1, string, sizeof(string));
486 MSG_WriteChar(&client->netconnection->message,svc_print);
487 MSG_WriteString(&client->netconnection->message, string);
494 single print to the screen
499 void VM_centerprint(prvm_prog_t *prog)
501 char string[VM_TEMPSTRING_MAXSIZE];
503 VM_SAFEPARMCOUNTRANGE(1, 8, VM_centerprint);
504 VM_VarString(prog, 0, string, sizeof(string));
505 SCR_CenterPrint(string);
512 vector normalize(vector)
515 void VM_normalize(prvm_prog_t *prog)
521 VM_SAFEPARMCOUNT(1,VM_normalize);
523 value1 = PRVM_G_VECTOR(OFS_PARM0);
525 f = VectorLength2(value1);
529 VectorScale(value1, f, newvalue);
532 VectorClear(newvalue);
534 VectorCopy (newvalue, PRVM_G_VECTOR(OFS_RETURN));
544 void VM_vlen(prvm_prog_t *prog)
546 VM_SAFEPARMCOUNT(1,VM_vlen);
547 PRVM_G_FLOAT(OFS_RETURN) = VectorLength(PRVM_G_VECTOR(OFS_PARM0));
554 float vectoyaw(vector)
557 void VM_vectoyaw(prvm_prog_t *prog)
562 VM_SAFEPARMCOUNT(1,VM_vectoyaw);
564 value1 = PRVM_G_VECTOR(OFS_PARM0);
566 if (value1[1] == 0 && value1[0] == 0)
570 yaw = (int) (atan2(value1[1], value1[0]) * 180 / M_PI);
575 PRVM_G_FLOAT(OFS_RETURN) = yaw;
583 vector vectoangles(vector[, vector])
586 void VM_vectoangles(prvm_prog_t *prog)
588 vec3_t result, forward, up;
589 VM_SAFEPARMCOUNTRANGE(1, 2,VM_vectoangles);
591 VectorCopy(PRVM_G_VECTOR(OFS_PARM0), forward);
594 VectorCopy(PRVM_G_VECTOR(OFS_PARM1), up);
595 AnglesFromVectors(result, forward, up, true);
598 AnglesFromVectors(result, forward, NULL, true);
599 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
606 Returns a random number > 0 and < 1
611 void VM_random(prvm_prog_t *prog)
613 VM_SAFEPARMCOUNT(0,VM_random);
615 PRVM_G_FLOAT(OFS_RETURN) = lhrandom(0, 1);
622 localsound(string sample, float chan, float vol)
625 void VM_localsound(prvm_prog_t *prog)
630 VM_SAFEPARMCOUNTRANGE(1, 3,VM_localsound);
632 s = PRVM_G_STRING(OFS_PARM0);
635 chan = PRVM_G_FLOAT(OFS_PARM1);
636 vol = PRVM_G_FLOAT(OFS_PARM2) == 0 ? 1 : PRVM_G_FLOAT(OFS_PARM2);
637 if(!S_LocalSoundEx(s, chan, vol))
639 PRVM_G_FLOAT(OFS_RETURN) = -4;
640 VM_Warning(prog, "VM_localsound: Failed to play %s for %s !\n", s, prog->name);
644 else if(!S_LocalSound (s))
646 PRVM_G_FLOAT(OFS_RETURN) = -4;
647 VM_Warning(prog, "VM_localsound: Failed to play %s for %s !\n", s, prog->name);
651 PRVM_G_FLOAT(OFS_RETURN) = 1;
661 void VM_break(prvm_prog_t *prog)
663 prog->error_cmd("%s: break statement", prog->name);
666 //============================================================================
672 Appends text to the command buffer
674 [localcmd (string, ...) or]
678 void VM_localcmd(prvm_prog_t *prog)
680 char string[VM_TEMPSTRING_MAXSIZE];
681 VM_SAFEPARMCOUNTRANGE(1, 8, VM_localcmd);
682 VM_VarString(prog, 0, string, sizeof(string));
683 Cbuf_AddText(cmd_local, string);
686 static qbool PRVM_Cvar_ReadOk(prvm_prog_t *prog, const char *string)
689 cvar = Cvar_FindVar(prog->console_cmd->cvars, string, prog->console_cmd->cvars_flagsmask);
690 return ((cvar) && ((cvar->flags & CF_PRIVATE) == 0));
700 void VM_cvar(prvm_prog_t *prog)
702 char string[VM_TEMPSTRING_MAXSIZE];
703 VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar);
704 VM_VarString(prog, 0, string, sizeof(string));
705 VM_CheckEmptyString(prog, string);
706 PRVM_G_FLOAT(OFS_RETURN) = PRVM_Cvar_ReadOk(prog, string) ? Cvar_VariableValue(prog->console_cmd->cvars, string, prog->console_cmd->cvars_flagsmask) : 0;
713 float cvar_type (string)
714 float CVAR_TYPEFLAG_EXISTS = 1;
715 float CVAR_TYPEFLAG_SAVED = 2;
716 float CVAR_TYPEFLAG_PRIVATE = 4;
717 float CVAR_TYPEFLAG_ENGINE = 8;
718 float CVAR_TYPEFLAG_HASDESCRIPTION = 16;
719 float CVAR_TYPEFLAG_READONLY = 32;
722 void VM_cvar_type(prvm_prog_t *prog)
724 char string[VM_TEMPSTRING_MAXSIZE];
728 VM_SAFEPARMCOUNTRANGE(1, 8, VM_cvar_type);
729 VM_VarString(prog, 0, string, sizeof(string));
730 VM_CheckEmptyString(prog, string);
731 cvar = Cvar_FindVar(prog->console_cmd->cvars, string, prog->console_cmd->cvars_flagsmask);
736 PRVM_G_FLOAT(OFS_RETURN) = 0;
737 return; // CVAR_TYPE_NONE
740 ret = 1; // CVAR_EXISTS
741 if(cvar->flags & CF_ARCHIVE)
742 ret |= 2; // CVAR_TYPE_SAVED
743 if(cvar->flags & CF_PRIVATE)
744 ret |= 4; // CVAR_TYPE_PRIVATE
745 if(!(cvar->flags & CF_ALLOCATED))
746 ret |= 8; // CVAR_TYPE_ENGINE
747 if(cvar->description != cvar_dummy_description)
748 ret |= 16; // CVAR_TYPE_HASDESCRIPTION
749 if(cvar->flags & CF_READONLY)
750 ret |= 32; // CVAR_TYPE_READONLY
752 PRVM_G_FLOAT(OFS_RETURN) = ret;
759 const string VM_cvar_string (string, ...)
762 void VM_cvar_string(prvm_prog_t *prog)
764 char cvar_name[VM_TEMPSTRING_MAXSIZE];
766 VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_string);
767 VM_VarString(prog, 0, cvar_name, sizeof(cvar_name));
768 VM_CheckEmptyString(prog, cvar_name);
769 if (PRVM_Cvar_ReadOk(prog, cvar_name))
771 const char *cvar_string = Cvar_VariableString(prog->console_cmd->cvars, cvar_name, prog->console_cmd->cvars_flagsmask);
772 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, cvar_string, strlen(cvar_string));
775 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
780 ========================
783 const string VM_cvar_defstring (string, ...)
784 ========================
786 void VM_cvar_defstring(prvm_prog_t *prog)
788 char cvar_name[VM_TEMPSTRING_MAXSIZE];
789 const char *cvar_defstring;
791 VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_defstring);
792 VM_VarString(prog, 0, cvar_name, sizeof(cvar_name));
793 VM_CheckEmptyString(prog, cvar_name);
794 cvar_defstring = Cvar_VariableDefString(prog->console_cmd->cvars, cvar_name, prog->console_cmd->cvars_flagsmask);
795 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, cvar_defstring, strlen(cvar_defstring));
799 ========================
802 const string VM_cvar_description (string, ...)
803 ========================
805 void VM_cvar_description(prvm_prog_t *prog)
807 char cvar_name[VM_TEMPSTRING_MAXSIZE];
808 const char *cvar_desc;
810 VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_description);
811 VM_VarString(prog, 0, cvar_name, sizeof(cvar_name));
812 VM_CheckEmptyString(prog, cvar_name);
813 cvar_desc = Cvar_VariableDescription(prog->console_cmd->cvars, cvar_name, prog->console_cmd->cvars_flagsmask);
814 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, cvar_desc, strlen(cvar_desc));
820 void cvar_set (string,string, ...)
823 void VM_cvar_set(prvm_prog_t *prog)
826 char value[VM_TEMPSTRING_MAXSIZE];
829 VM_SAFEPARMCOUNTRANGE(2,8,VM_cvar_set);
830 name = PRVM_G_STRING(OFS_PARM0);
831 VM_CheckEmptyString(prog, name);
832 cvar = Cvar_FindVar(prog->console_cmd->cvars, name, prog->console_cmd->cvars_flagsmask);
835 VM_Warning(prog, "VM_cvar_set: variable %s not found\n", name);
838 if (cvar->flags & CF_READONLY)
840 VM_Warning(prog, "VM_cvar_set: variable %s is read-only\n", cvar->name);
843 VM_VarString(prog, 1, value, sizeof(value));
844 Cvar_SetQuick(cvar, value);
854 void VM_dprint(prvm_prog_t *prog)
856 char string[VM_TEMPSTRING_MAXSIZE];
857 VM_SAFEPARMCOUNTRANGE(1, 8, VM_dprint);
858 VM_VarString(prog, 0, string, sizeof(string));
860 Con_DPrintf("%s", string);
862 Con_DPrintf("%s: %s", prog->name, string);
874 void VM_ftos(prvm_prog_t *prog)
880 VM_SAFEPARMCOUNT(1, VM_ftos);
882 v = PRVM_G_FLOAT(OFS_PARM0);
884 if ((prvm_vec_t)((prvm_int_t)v) == v)
885 slen = dpsnprintf(s, sizeof(s), "%.0f", v);
887 slen = dpsnprintf(s, sizeof(s), "%f", v);
888 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s, slen);
899 void VM_fabs(prvm_prog_t *prog)
903 VM_SAFEPARMCOUNT(1,VM_fabs);
905 v = PRVM_G_FLOAT(OFS_PARM0);
906 PRVM_G_FLOAT(OFS_RETURN) = fabs(v);
917 void VM_vtos(prvm_prog_t *prog)
922 VM_SAFEPARMCOUNT(1,VM_vtos);
924 slen = 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]);
925 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s, slen);
936 void VM_etos(prvm_prog_t *prog)
941 VM_SAFEPARMCOUNT(1, VM_etos);
943 slen = dpsnprintf(s, sizeof(s), "entity %i", PRVM_G_EDICTNUM(OFS_PARM0));
944 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s, slen);
951 float stof(...[string])
954 void VM_stof(prvm_prog_t *prog)
956 char string[VM_TEMPSTRING_MAXSIZE];
957 VM_SAFEPARMCOUNTRANGE(1, 8, VM_stof);
958 VM_VarString(prog, 0, string, sizeof(string));
959 PRVM_G_FLOAT(OFS_RETURN) = atof(string);
963 ========================
967 ========================
969 void VM_itof(prvm_prog_t *prog)
971 VM_SAFEPARMCOUNT(1, VM_itof);
972 PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
976 ========================
979 entity ftoe(float num)
980 ========================
982 void VM_ftoe(prvm_prog_t *prog)
985 VM_SAFEPARMCOUNT(1, VM_ftoe);
987 ent = (prvm_int_t)PRVM_G_FLOAT(OFS_PARM0);
988 if (ent < 0 || ent >= prog->max_edicts || PRVM_PROG_TO_EDICT(ent)->free)
989 ent = 0; // return world instead of a free or invalid entity
991 PRVM_G_INT(OFS_RETURN) = ent;
995 ========================
998 float etof(entity ent)
999 ========================
1001 void VM_etof(prvm_prog_t *prog)
1003 VM_SAFEPARMCOUNT(1, VM_etof);
1004 PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_EDICTNUM(OFS_PARM0);
1011 string strftime(float uselocaltime, string[, string ...])
1014 void VM_strftime(prvm_prog_t *prog)
1017 #if _MSC_VER >= 1400
1023 char fmt[VM_TEMPSTRING_MAXSIZE];
1024 char result[VM_TEMPSTRING_MAXSIZE];
1027 VM_SAFEPARMCOUNTRANGE(2, 8, VM_strftime);
1028 VM_VarString(prog, 1, fmt, sizeof(fmt));
1030 #if _MSC_VER >= 1400
1031 if (PRVM_G_FLOAT(OFS_PARM0))
1032 tmresult = localtime_s(&tm, &t);
1034 tmresult = gmtime_s(&tm, &t);
1037 if (PRVM_G_FLOAT(OFS_PARM0))
1044 PRVM_G_INT(OFS_RETURN) = 0;
1047 #if _MSC_VER >= 1400
1048 result_len = strftime(result, sizeof(result), fmt, &tm);
1050 result_len = strftime(result, sizeof(result), fmt, tm);
1052 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, result, result_len);
1063 void VM_spawn(prvm_prog_t *prog)
1066 VM_SAFEPARMCOUNT(0, VM_spawn);
1067 prog->xfunction->builtinsprofile += 20;
1068 ed = PRVM_ED_Alloc(prog);
1069 VM_RETURN_EDICT(ed);
1080 void VM_remove(prvm_prog_t *prog)
1083 prog->xfunction->builtinsprofile += 20;
1085 VM_SAFEPARMCOUNT(1, VM_remove);
1087 ed = PRVM_G_EDICT(OFS_PARM0);
1088 if( PRVM_NUM_FOR_EDICT(ed) <= prog->reserved_edicts )
1090 if (developer.integer > 0)
1091 VM_Warning(prog, "VM_remove: tried to remove the null entity or a reserved entity!\n" );
1095 if (developer.integer > 0)
1096 VM_Warning(prog, "VM_remove: tried to remove an already freed entity!\n" );
1099 PRVM_ED_Free (prog, ed);
1106 entity find(entity start, .string field, string match)
1110 void VM_find(prvm_prog_t *prog)
1117 VM_SAFEPARMCOUNT(3,VM_find);
1119 e = PRVM_G_EDICTNUM(OFS_PARM0);
1120 f = PRVM_G_INT(OFS_PARM1);
1121 s = PRVM_G_STRING(OFS_PARM2);
1123 // LadyHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
1124 // expects it to find all the monsters, so we must be careful to support
1127 for (e++ ; e < prog->num_edicts ; e++)
1129 prog->xfunction->builtinsprofile++;
1130 ed = PRVM_EDICT_NUM(e);
1133 t = PRVM_E_STRING(ed,f);
1138 VM_RETURN_EDICT(ed);
1143 VM_RETURN_EDICT(prog->edicts);
1150 entity findfloat(entity start, .float field, float match)
1151 entity findentity(entity start, .entity field, entity match)
1154 // LadyHavoc: added this for searching float, int, and entity reference fields
1155 void VM_findfloat(prvm_prog_t *prog)
1162 VM_SAFEPARMCOUNT(3,VM_findfloat);
1164 e = PRVM_G_EDICTNUM(OFS_PARM0);
1165 f = PRVM_G_INT(OFS_PARM1);
1166 s = PRVM_G_FLOAT(OFS_PARM2);
1168 for (e++ ; e < prog->num_edicts ; e++)
1170 prog->xfunction->builtinsprofile++;
1171 ed = PRVM_EDICT_NUM(e);
1174 if (PRVM_E_FLOAT(ed,f) == s)
1176 VM_RETURN_EDICT(ed);
1181 VM_RETURN_EDICT(prog->edicts);
1188 entity findchain(.string field, string match)
1191 // chained search for strings in entity fields
1192 // entity(.string field, string match) findchain = #402;
1193 void VM_findchain(prvm_prog_t *prog)
1198 prvm_edict_t *ent, *chain;
1201 VM_SAFEPARMCOUNTRANGE(2,3,VM_findchain);
1204 chainfield = PRVM_G_INT(OFS_PARM2);
1206 chainfield = prog->fieldoffsets.chain;
1208 prog->error_cmd("VM_findchain: %s doesnt have the specified chain field !", prog->name);
1210 chain = prog->edicts;
1212 f = PRVM_G_INT(OFS_PARM0);
1213 s = PRVM_G_STRING(OFS_PARM1);
1215 // LadyHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
1216 // expects it to find all the monsters, so we must be careful to support
1219 ent = PRVM_NEXT_EDICT(prog->edicts);
1220 for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1222 prog->xfunction->builtinsprofile++;
1225 t = PRVM_E_STRING(ent,f);
1231 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_NUM_FOR_EDICT(chain);
1235 VM_RETURN_EDICT(chain);
1242 entity findchainfloat(.string field, float match)
1243 entity findchainentity(.string field, entity match)
1246 // LadyHavoc: chained search for float, int, and entity reference fields
1247 // entity(.string field, float match) findchainfloat = #403;
1248 void VM_findchainfloat(prvm_prog_t *prog)
1253 prvm_edict_t *ent, *chain;
1256 VM_SAFEPARMCOUNTRANGE(2, 3, VM_findchainfloat);
1259 chainfield = PRVM_G_INT(OFS_PARM2);
1261 chainfield = prog->fieldoffsets.chain;
1263 prog->error_cmd("VM_findchainfloat: %s doesnt have the specified chain field !", prog->name);
1265 chain = (prvm_edict_t *)prog->edicts;
1267 f = PRVM_G_INT(OFS_PARM0);
1268 s = PRVM_G_FLOAT(OFS_PARM1);
1270 ent = PRVM_NEXT_EDICT(prog->edicts);
1271 for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1273 prog->xfunction->builtinsprofile++;
1276 if (PRVM_E_FLOAT(ent,f) != s)
1279 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_EDICT_TO_PROG(chain);
1283 VM_RETURN_EDICT(chain);
1287 ========================
1290 entity findflags(entity start, .float field, float match)
1291 ========================
1293 // LadyHavoc: search for flags in float fields
1294 void VM_findflags(prvm_prog_t *prog)
1301 VM_SAFEPARMCOUNT(3, VM_findflags);
1304 e = PRVM_G_EDICTNUM(OFS_PARM0);
1305 f = PRVM_G_INT(OFS_PARM1);
1306 s = (prvm_int_t)PRVM_G_FLOAT(OFS_PARM2);
1308 for (e++ ; e < prog->num_edicts ; e++)
1310 prog->xfunction->builtinsprofile++;
1311 ed = PRVM_EDICT_NUM(e);
1314 if (!PRVM_E_FLOAT(ed,f))
1316 if ((prvm_int_t)PRVM_E_FLOAT(ed,f) & s)
1318 VM_RETURN_EDICT(ed);
1323 VM_RETURN_EDICT(prog->edicts);
1327 ========================
1330 entity findchainflags(.float field, float match)
1331 ========================
1333 // LadyHavoc: chained search for flags in float fields
1334 void VM_findchainflags(prvm_prog_t *prog)
1339 prvm_edict_t *ent, *chain;
1342 VM_SAFEPARMCOUNTRANGE(2, 3, VM_findchainflags);
1345 chainfield = PRVM_G_INT(OFS_PARM2);
1347 chainfield = prog->fieldoffsets.chain;
1349 prog->error_cmd("VM_findchainflags: %s doesnt have the specified chain field !", prog->name);
1351 chain = (prvm_edict_t *)prog->edicts;
1353 f = PRVM_G_INT(OFS_PARM0);
1354 s = (prvm_int_t)PRVM_G_FLOAT(OFS_PARM1);
1356 ent = PRVM_NEXT_EDICT(prog->edicts);
1357 for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1359 prog->xfunction->builtinsprofile++;
1362 if (!PRVM_E_FLOAT(ent,f))
1364 if (!((prvm_int_t)PRVM_E_FLOAT(ent,f) & s))
1367 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_EDICT_TO_PROG(chain);
1371 VM_RETURN_EDICT(chain);
1378 string precache_sound (string sample)
1381 void VM_precache_sound(prvm_prog_t *prog)
1385 VM_SAFEPARMCOUNT(1, VM_precache_sound);
1387 s = PRVM_G_STRING(OFS_PARM0);
1388 PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
1389 //VM_CheckEmptyString(prog, s);
1391 if(snd_initialized.integer && !S_PrecacheSound(s, true, true))
1393 VM_Warning(prog, "VM_precache_sound: Failed to load %s for %s\n", s, prog->name);
1402 returns the same string as output
1404 does nothing, only used by qcc to build .pak archives
1407 void VM_precache_file(prvm_prog_t *prog)
1409 VM_SAFEPARMCOUNT(1,VM_precache_file);
1410 // precache_file is only used to copy files with qcc, it does nothing
1411 PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
1421 void VM_coredump(prvm_prog_t *prog)
1423 VM_SAFEPARMCOUNT(0,VM_coredump);
1425 Cbuf_AddText(cmd_local, "prvm_edicts ");
1426 Cbuf_AddText(cmd_local, prog->name);
1427 Cbuf_AddText(cmd_local, "\n");
1437 void VM_stackdump(prvm_prog_t *prog)
1439 VM_SAFEPARMCOUNT(0, VM_stackdump);
1441 PRVM_StackTrace(prog);
1452 void VM_crash(prvm_prog_t *prog)
1454 VM_SAFEPARMCOUNT(0, VM_crash);
1456 prog->error_cmd("Crash called by %s",prog->name);
1466 void VM_traceon(prvm_prog_t *prog)
1468 VM_SAFEPARMCOUNT(0,VM_traceon);
1480 void VM_traceoff(prvm_prog_t *prog)
1482 VM_SAFEPARMCOUNT(0,VM_traceoff);
1484 prog->trace = false;
1494 void VM_eprint(prvm_prog_t *prog)
1496 VM_SAFEPARMCOUNT(1,VM_eprint);
1498 PRVM_ED_PrintNum (prog, PRVM_G_EDICTNUM(OFS_PARM0), NULL);
1508 void VM_rint(prvm_prog_t *prog)
1511 VM_SAFEPARMCOUNT(1,VM_rint);
1513 f = PRVM_G_FLOAT(OFS_PARM0);
1515 PRVM_G_FLOAT(OFS_RETURN) = floor(f + 0.5);
1517 PRVM_G_FLOAT(OFS_RETURN) = ceil(f - 0.5);
1527 void VM_floor(prvm_prog_t *prog)
1529 VM_SAFEPARMCOUNT(1,VM_floor);
1531 PRVM_G_FLOAT(OFS_RETURN) = floor(PRVM_G_FLOAT(OFS_PARM0));
1541 void VM_ceil(prvm_prog_t *prog)
1543 VM_SAFEPARMCOUNT(1,VM_ceil);
1545 PRVM_G_FLOAT(OFS_RETURN) = ceil(PRVM_G_FLOAT(OFS_PARM0));
1553 entity nextent(entity)
1556 void VM_nextent(prvm_prog_t *prog)
1561 VM_SAFEPARMCOUNT(1, VM_nextent);
1563 i = PRVM_G_EDICTNUM(OFS_PARM0);
1566 prog->xfunction->builtinsprofile++;
1568 if (i == prog->num_edicts)
1570 VM_RETURN_EDICT(prog->edicts);
1573 ent = PRVM_EDICT_NUM(i);
1576 VM_RETURN_EDICT(ent);
1582 //=============================================================================
1589 changelevel(string map)
1592 void VM_changelevel(prvm_prog_t *prog)
1595 VM_SAFEPARMCOUNT(1, VM_changelevel);
1599 VM_Warning(prog, "VM_changelevel: game is not server (%s)\n", prog->name);
1603 // make sure we don't issue two changelevels
1604 if (svs.changelevel_issued)
1606 svs.changelevel_issued = true;
1608 Cbuf_AddText(cmd_local, va(vabuf, sizeof(vabuf), "changelevel %s\n", PRVM_G_STRING(OFS_PARM0)));
1618 void VM_sin(prvm_prog_t *prog)
1620 VM_SAFEPARMCOUNT(1,VM_sin);
1621 PRVM_G_FLOAT(OFS_RETURN) = sin(PRVM_G_FLOAT(OFS_PARM0));
1630 void VM_cos(prvm_prog_t *prog)
1632 VM_SAFEPARMCOUNT(1,VM_cos);
1633 PRVM_G_FLOAT(OFS_RETURN) = cos(PRVM_G_FLOAT(OFS_PARM0));
1643 void VM_sqrt(prvm_prog_t *prog)
1645 VM_SAFEPARMCOUNT(1,VM_sqrt);
1646 PRVM_G_FLOAT(OFS_RETURN) = sqrt(PRVM_G_FLOAT(OFS_PARM0));
1656 void VM_asin(prvm_prog_t *prog)
1658 VM_SAFEPARMCOUNT(1,VM_asin);
1659 PRVM_G_FLOAT(OFS_RETURN) = asin(PRVM_G_FLOAT(OFS_PARM0));
1668 void VM_acos(prvm_prog_t *prog)
1670 VM_SAFEPARMCOUNT(1,VM_acos);
1671 PRVM_G_FLOAT(OFS_RETURN) = acos(PRVM_G_FLOAT(OFS_PARM0));
1680 void VM_atan(prvm_prog_t *prog)
1682 VM_SAFEPARMCOUNT(1,VM_atan);
1683 PRVM_G_FLOAT(OFS_RETURN) = atan(PRVM_G_FLOAT(OFS_PARM0));
1689 float atan2(float,float)
1692 void VM_atan2(prvm_prog_t *prog)
1694 VM_SAFEPARMCOUNT(2,VM_atan2);
1695 PRVM_G_FLOAT(OFS_RETURN) = atan2(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1704 void VM_tan(prvm_prog_t *prog)
1706 VM_SAFEPARMCOUNT(1,VM_tan);
1707 PRVM_G_FLOAT(OFS_RETURN) = tan(PRVM_G_FLOAT(OFS_PARM0));
1714 Returns a vector of length < 1 and > 0
1719 void VM_randomvec(prvm_prog_t *prog)
1722 VM_SAFEPARMCOUNT(0, VM_randomvec);
1724 VectorCopy(temp, PRVM_G_VECTOR(OFS_RETURN));
1727 //=============================================================================
1733 float registercvar (string name, string value[, float flags])
1736 void VM_registercvar(prvm_prog_t *prog)
1738 const char *name, *value;
1741 VM_SAFEPARMCOUNTRANGE(2, 3, VM_registercvar);
1743 name = PRVM_G_STRING(OFS_PARM0);
1744 value = PRVM_G_STRING(OFS_PARM1);
1745 flags = prog->argc >= 3 ? (int)PRVM_G_FLOAT(OFS_PARM2) : 0;
1746 PRVM_G_FLOAT(OFS_RETURN) = 0;
1748 if(flags > CF_MAXFLAGSVAL)
1751 // first check to see if it has already been defined
1752 if (Cvar_FindVar (prog->console_cmd->cvars, name, prog->console_cmd->cvars_flagsmask))
1755 // check for overlap with a command
1756 if (Cmd_Exists(cmd_local, name))
1758 VM_Warning(prog, "VM_registercvar: %s is a command\n", name);
1762 Cvar_Get(prog->console_cmd->cvars, name, value, prog->console_cmd->cvars_flagsmask | flags, NULL);
1764 PRVM_G_FLOAT(OFS_RETURN) = 1; // success
1772 returns the minimum of two supplied floats
1774 float min(float a, float b, ...[float])
1777 void VM_min(prvm_prog_t *prog)
1779 VM_SAFEPARMCOUNTRANGE(2, 8, VM_min);
1780 // LadyHavoc: 3+ argument enhancement suggested by FrikaC
1781 if (prog->argc >= 3)
1784 float f = PRVM_G_FLOAT(OFS_PARM0);
1785 for (i = 1;i < prog->argc;i++)
1786 if (f > PRVM_G_FLOAT((OFS_PARM0+i*3)))
1787 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1788 PRVM_G_FLOAT(OFS_RETURN) = f;
1791 PRVM_G_FLOAT(OFS_RETURN) = min(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1798 returns the maximum of two supplied floats
1800 float max(float a, float b, ...[float])
1803 void VM_max(prvm_prog_t *prog)
1805 VM_SAFEPARMCOUNTRANGE(2, 8, VM_max);
1806 // LadyHavoc: 3+ argument enhancement suggested by FrikaC
1807 if (prog->argc >= 3)
1810 float f = PRVM_G_FLOAT(OFS_PARM0);
1811 for (i = 1;i < prog->argc;i++)
1812 if (f < PRVM_G_FLOAT((OFS_PARM0+i*3)))
1813 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1814 PRVM_G_FLOAT(OFS_RETURN) = f;
1817 PRVM_G_FLOAT(OFS_RETURN) = max(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1824 returns number bounded by supplied range
1826 float bound(float min, float value, float max)
1829 void VM_bound(prvm_prog_t *prog)
1831 VM_SAFEPARMCOUNT(3,VM_bound);
1832 PRVM_G_FLOAT(OFS_RETURN) = bound(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1), PRVM_G_FLOAT(OFS_PARM2));
1839 returns a raised to power b
1841 float pow(float a, float b)
1844 void VM_pow(prvm_prog_t *prog)
1846 VM_SAFEPARMCOUNT(2,VM_pow);
1847 PRVM_G_FLOAT(OFS_RETURN) = pow(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1850 void VM_log(prvm_prog_t *prog)
1852 VM_SAFEPARMCOUNT(1,VM_log);
1853 PRVM_G_FLOAT(OFS_RETURN) = log(PRVM_G_FLOAT(OFS_PARM0));
1856 void VM_Files_Init(prvm_prog_t *prog)
1859 for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1860 prog->openfiles[i] = NULL;
1863 void VM_Files_CloseAll(prvm_prog_t *prog)
1866 for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1868 if (prog->openfiles[i])
1869 FS_Close(prog->openfiles[i]);
1870 prog->openfiles[i] = NULL;
1874 static qfile_t *VM_GetFileHandle(prvm_prog_t *prog, int index)
1876 if (index < 0 || index >= PRVM_MAX_OPENFILES)
1878 Con_Printf("VM_GetFileHandle: invalid file handle %i used in %s\n", index, prog->name);
1881 if (prog->openfiles[index] == NULL)
1883 Con_Printf("VM_GetFileHandle: no such file handle %i (or file has been closed) in %s\n", index, prog->name);
1886 return prog->openfiles[index];
1893 float fopen(string filename, float mode)
1896 // float(string filename, float mode) fopen = #110;
1897 // opens a file inside quake/gamedir/data/ (mode is FILE_READ, FILE_APPEND, or FILE_WRITE),
1898 // returns fhandle >= 0 if successful, or fhandle < 0 if unable to open file for any reason
1899 void VM_fopen(prvm_prog_t *prog)
1902 const char *modestring, *filename;
1905 VM_SAFEPARMCOUNT(2,VM_fopen);
1907 for (filenum = 0;filenum < PRVM_MAX_OPENFILES;filenum++)
1908 if (prog->openfiles[filenum] == NULL)
1910 if (filenum >= PRVM_MAX_OPENFILES)
1912 PRVM_G_FLOAT(OFS_RETURN) = -2;
1913 VM_Warning(prog, "VM_fopen: %s ran out of file handles (%i)\n", prog->name, PRVM_MAX_OPENFILES);
1916 filename = PRVM_G_STRING(OFS_PARM0);
1917 mode = (int)PRVM_G_FLOAT(OFS_PARM1);
1920 case 0: // FILE_READ
1922 prog->openfiles[filenum] = FS_OpenVirtualFile(va(vabuf, sizeof(vabuf), "data/%s", filename), false);
1923 if (prog->openfiles[filenum] == NULL)
1924 prog->openfiles[filenum] = FS_OpenVirtualFile(va(vabuf, sizeof(vabuf), "%s", filename), false);
1926 case 1: // FILE_APPEND
1928 prog->openfiles[filenum] = FS_OpenRealFile(va(vabuf, sizeof(vabuf), "data/%s", filename), modestring, false);
1930 case 2: // FILE_WRITE
1932 prog->openfiles[filenum] = FS_OpenRealFile(va(vabuf, sizeof(vabuf), "data/%s", filename), modestring, false);
1935 PRVM_G_FLOAT(OFS_RETURN) = -3;
1936 VM_Warning(prog, "VM_fopen: %s: no such mode %i (valid: 0 = read, 1 = append, 2 = write)\n", prog->name, mode);
1940 if (prog->openfiles[filenum] == NULL)
1942 PRVM_G_FLOAT(OFS_RETURN) = -1;
1943 if (developer_extra.integer)
1944 VM_Warning(prog, "VM_fopen: %s: %s mode %s failed\n", prog->name, filename, modestring);
1948 PRVM_G_FLOAT(OFS_RETURN) = filenum;
1949 if (developer_extra.integer)
1950 Con_DPrintf("VM_fopen: %s: %s mode %s opened as #%i\n", prog->name, filename, modestring, filenum);
1951 prog->openfiles_origin[filenum] = PRVM_AllocationOrigin(prog);
1959 fclose(float fhandle)
1962 //void(float fhandle) fclose = #111; // closes a file
1963 void VM_fclose(prvm_prog_t *prog)
1967 VM_SAFEPARMCOUNT(1,VM_fclose);
1969 filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1970 if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1972 VM_Warning(prog, "VM_fclose: invalid file handle %i used in %s\n", filenum, prog->name);
1975 if (prog->openfiles[filenum] == NULL)
1977 VM_Warning(prog, "VM_fclose: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
1980 FS_Close(prog->openfiles[filenum]);
1981 prog->openfiles[filenum] = NULL;
1982 if(prog->openfiles_origin[filenum])
1983 PRVM_Free((char *)prog->openfiles_origin[filenum]);
1984 if (developer_extra.integer)
1985 Con_DPrintf("VM_fclose: %s: #%i closed\n", prog->name, filenum);
1992 string fgets(float fhandle)
1995 //string(float fhandle) fgets = #112; // reads a line of text from the file and returns as a tempstring
1996 void VM_fgets(prvm_prog_t *prog)
1999 char string[VM_TEMPSTRING_MAXSIZE];
2002 VM_SAFEPARMCOUNT(1,VM_fgets);
2004 // set the return value regardless of any possible errors
2005 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
2007 filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
2008 if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
2010 VM_Warning(prog, "VM_fgets: invalid file handle %i used in %s\n", filenum, prog->name);
2013 if (prog->openfiles[filenum] == NULL)
2015 VM_Warning(prog, "VM_fgets: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
2021 c = FS_Getc(prog->openfiles[filenum]);
2022 if (c == '\r' || c == '\n' || c < 0)
2024 if (end < VM_TEMPSTRING_MAXSIZE - 1)
2028 // remove \n following \r
2031 c = FS_Getc(prog->openfiles[filenum]);
2033 FS_UnGetc(prog->openfiles[filenum], (unsigned char)c);
2035 if (developer_extra.integer)
2036 Con_DPrintf("fgets: %s: %s\n", prog->name, string);
2038 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string, end);
2045 fputs(float fhandle, string s)
2048 //void(float fhandle, string s) fputs = #113; // writes a line of text to the end of the file
2049 void VM_fputs(prvm_prog_t *prog)
2051 size_t stringlength;
2052 char string[VM_TEMPSTRING_MAXSIZE];
2055 VM_SAFEPARMCOUNT(2,VM_fputs);
2057 filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
2058 if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
2060 VM_Warning(prog, "VM_fputs: invalid file handle %i used in %s\n", filenum, prog->name);
2063 if (prog->openfiles[filenum] == NULL)
2065 VM_Warning(prog, "VM_fputs: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
2068 stringlength = VM_VarString(prog, 1, string, sizeof(string));
2070 FS_Write(prog->openfiles[filenum], string, stringlength);
2071 if (developer_extra.integer)
2072 Con_DPrintf("fputs: %s: %s\n", prog->name, string);
2079 writetofile(float fhandle, entity ent)
2082 void VM_writetofile(prvm_prog_t *prog)
2087 VM_SAFEPARMCOUNT(2, VM_writetofile);
2089 file = VM_GetFileHandle(prog, (int)PRVM_G_FLOAT(OFS_PARM0));
2092 VM_Warning(prog, "VM_writetofile: invalid or closed file handle\n");
2096 ent = PRVM_G_EDICT(OFS_PARM1);
2099 VM_Warning(prog, "VM_writetofile: %s: entity %i is free !\n", prog->name, PRVM_NUM_FOR_EDICT(ent));
2103 PRVM_ED_Write (prog, file, ent);
2106 // KrimZon - DP_QC_ENTITYDATA
2111 float() numentityfields
2112 Return the number of entity fields - NOT offsets
2115 void VM_numentityfields(prvm_prog_t *prog)
2117 PRVM_G_FLOAT(OFS_RETURN) = prog->numfielddefs;
2120 // KrimZon - DP_QC_ENTITYDATA
2125 string(float fieldnum) entityfieldname
2126 Return name of the specified field as a string, or empty if the field is invalid (warning)
2129 void VM_entityfieldname(prvm_prog_t *prog)
2132 int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2134 if (i < 0 || i >= prog->numfielddefs)
2136 VM_Warning(prog, "VM_entityfieldname: %s: field index out of bounds\n", prog->name);
2137 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
2141 d = &prog->fielddefs[i];
2142 PRVM_G_INT(OFS_RETURN) = d->s_name; // presuming that s_name points to a string already
2145 // KrimZon - DP_QC_ENTITYDATA
2150 float(float fieldnum) entityfieldtype
2153 void VM_entityfieldtype(prvm_prog_t *prog)
2156 int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2158 if (i < 0 || i >= prog->numfielddefs)
2160 VM_Warning(prog, "VM_entityfieldtype: %s: field index out of bounds\n", prog->name);
2161 PRVM_G_FLOAT(OFS_RETURN) = -1.0;
2165 d = &prog->fielddefs[i];
2166 PRVM_G_FLOAT(OFS_RETURN) = (prvm_vec_t)d->type;
2169 // KrimZon - DP_QC_ENTITYDATA
2172 VM_getentityfieldstring
2174 string(float fieldnum, entity ent) getentityfieldstring
2177 void VM_getentityfieldstring(prvm_prog_t *prog)
2179 // put the data into a string
2184 int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2185 char valuebuf[MAX_INPUTLINE];
2187 if (i < 0 || i >= prog->numfielddefs)
2189 VM_Warning(prog, "VM_entityfielddata: %s: field index out of bounds\n", prog->name);
2190 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
2194 d = &prog->fielddefs[i];
2197 ent = PRVM_G_EDICT(OFS_PARM1);
2200 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
2201 VM_Warning(prog, "VM_entityfielddata: %s: entity %i is free !\n", prog->name, PRVM_NUM_FOR_EDICT(ent));
2204 val = (prvm_eval_t *)(ent->fields.fp + d->ofs);
2206 // if it's 0 or blank, return an empty string
2207 type = d->type & ~DEF_SAVEGLOBAL;
2208 for (j=0 ; j<prvm_type_size[type] ; j++)
2209 if (val->ivector[j])
2211 if (j == prvm_type_size[type])
2213 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
2217 PRVM_UglyValueString(prog, (etype_t)d->type, val, valuebuf, sizeof(valuebuf));
2218 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, valuebuf, strlen(valuebuf));
2221 // KrimZon - DP_QC_ENTITYDATA
2224 VM_putentityfieldstring
2226 float(float fieldnum, entity ent, string s) putentityfieldstring
2229 void VM_putentityfieldstring(prvm_prog_t *prog)
2233 int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2235 if (i < 0 || i >= prog->numfielddefs)
2237 VM_Warning(prog, "VM_entityfielddata: %s: field index out of bounds\n", prog->name);
2238 PRVM_G_FLOAT(OFS_RETURN) = 0.0f;
2242 d = &prog->fielddefs[i];
2245 ent = PRVM_G_EDICT(OFS_PARM1);
2248 VM_Warning(prog, "VM_entityfielddata: %s: entity %i is free !\n", prog->name, PRVM_NUM_FOR_EDICT(ent));
2249 PRVM_G_FLOAT(OFS_RETURN) = 0.0f;
2253 // parse the string into the value
2254 PRVM_G_FLOAT(OFS_RETURN) = ( PRVM_ED_ParseEpair(prog, ent, d, PRVM_G_STRING(OFS_PARM2), false) ) ? 1.0f : 0.0f;
2261 float strlen(string s)
2264 //float(string s) strlen = #114; // returns how many characters are in a string
2265 void VM_strlen(prvm_prog_t *prog)
2267 VM_SAFEPARMCOUNT(1,VM_strlen);
2269 //PRVM_G_FLOAT(OFS_RETURN) = strlen(PRVM_G_STRING(OFS_PARM0));
2270 PRVM_G_FLOAT(OFS_RETURN) = u8_strlen(PRVM_G_STRING(OFS_PARM0));
2273 // DRESK - Decolorized String
2278 string strdecolorize(string s)
2281 // string (string s) strdecolorize = #472; // returns the passed in string with color codes stripped
2282 void VM_strdecolorize(prvm_prog_t *prog)
2284 char szNewString[VM_TEMPSTRING_MAXSIZE];
2285 size_t szNewString_len;
2286 const char *szString;
2289 VM_SAFEPARMCOUNT(1,VM_strdecolorize);
2290 szString = PRVM_G_STRING(OFS_PARM0);
2291 szNewString_len = COM_StringDecolorize(szString, 0, szNewString, sizeof(szNewString), true);
2292 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString, szNewString_len);
2295 // DRESK - String Length (not counting color codes)
2300 float strlennocol(string s)
2303 // float(string s) strlennocol = #471; // returns how many characters are in a string not including color codes
2304 // For example, ^2Dresk returns a length of 5
2305 void VM_strlennocol(prvm_prog_t *prog)
2307 const char *szString;
2310 VM_SAFEPARMCOUNT(1,VM_strlennocol);
2312 szString = PRVM_G_STRING(OFS_PARM0);
2314 //nCnt = (int)COM_StringLengthNoColors(szString, 0, NULL);
2315 nCnt = (int)u8_COM_StringLengthNoColors(szString, 0, NULL);
2317 PRVM_G_FLOAT(OFS_RETURN) = nCnt;
2320 // DRESK - String to Uppercase and Lowercase
2325 string strtolower(string s)
2328 // string (string s) strtolower = #480; // returns passed in string in lowercase form
2329 void VM_strtolower(prvm_prog_t *prog)
2331 char szNewString[VM_TEMPSTRING_MAXSIZE];
2332 size_t szNewString_len;
2333 const char *szString;
2336 VM_SAFEPARMCOUNT(1,VM_strtolower);
2337 szString = PRVM_G_STRING(OFS_PARM0);
2339 szNewString_len = COM_ToLowerString(szString, szNewString, sizeof(szNewString) );
2341 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString, szNewString_len);
2348 string strtoupper(string s)
2351 // string (string s) strtoupper = #481; // returns passed in string in uppercase form
2352 void VM_strtoupper(prvm_prog_t *prog)
2354 char szNewString[VM_TEMPSTRING_MAXSIZE];
2355 size_t szNewString_len;
2356 const char *szString;
2359 VM_SAFEPARMCOUNT(1,VM_strtoupper);
2360 szString = PRVM_G_STRING(OFS_PARM0);
2362 szNewString_len = COM_ToUpperString(szString, szNewString, sizeof(szNewString) );
2364 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString, szNewString_len);
2371 string strcat(string s, string...)
2374 //string(string s, string...) strcat = #115;
2375 // concatenates strings (for example "abc", "def" would return "abcdef")
2376 // and returns as a tempstring
2377 void VM_strcat(prvm_prog_t *prog)
2379 char s[VM_TEMPSTRING_MAXSIZE];
2382 VM_SAFEPARMCOUNTRANGE(1, 8, VM_strcat);
2384 slen = VM_VarString(prog, 0, s, sizeof(s));
2385 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s, slen);
2392 string substring(string s, float start, float length)
2395 // string(string s, float start, float length) substring = #116;
2396 // returns a section of a string as a tempstring
2397 void VM_substring(prvm_prog_t *prog)
2400 int u_slength = 0, u_start;
2403 char string[VM_TEMPSTRING_MAXSIZE];
2405 VM_SAFEPARMCOUNT(3,VM_substring);
2408 s = PRVM_G_STRING(OFS_PARM0);
2409 start = (int)PRVM_G_FLOAT(OFS_PARM1);
2410 length = (int)PRVM_G_FLOAT(OFS_PARM2);
2411 slength = strlen(s);
2413 if (start < 0) // FTE_STRINGS feature
2415 start = bound(0, start, slength);
2417 if (length < 0) // FTE_STRINGS feature
2418 length += slength - start + 1;
2419 maxlen = min((int)sizeof(string) - 1, slength - start);
2420 length = bound(0, length, maxlen);
2422 memcpy(string, s + start, length);
2424 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string);
2427 s = PRVM_G_STRING(OFS_PARM0);
2428 start = (int)PRVM_G_FLOAT(OFS_PARM1);
2429 length = (int)PRVM_G_FLOAT(OFS_PARM2);
2431 if (start < 0) // FTE_STRINGS feature
2433 u_slength = (int)u8_strlen(s);
2435 start = bound(0, start, u_slength);
2438 if (length < 0) // FTE_STRINGS feature
2440 if (!u_slength) // it's not calculated when it's not needed above
2441 u_slength = (int)u8_strlen(s);
2442 length += u_slength - start + 1;
2445 // positive start, positive length
2446 u_start = u8_byteofs(s, start, NULL);
2449 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
2452 u_length = u8_bytelen(s + u_start, length);
2453 if (u_length >= sizeof(string)-1)
2454 u_length = sizeof(string)-1;
2456 memcpy(string, s + u_start, u_length);
2457 string[u_length] = '\0';
2458 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string, u_length);
2465 string(string search, string replace, string subject) strreplace = #484;
2468 // replaces all occurrences of search with replace in the string subject, and returns the result
2469 void VM_strreplace(prvm_prog_t *prog)
2472 const char *search, *replace, *subject;
2473 char string[VM_TEMPSTRING_MAXSIZE];
2474 int search_len, replace_len, subject_len;
2476 VM_SAFEPARMCOUNT(3,VM_strreplace);
2478 search = PRVM_G_STRING(OFS_PARM0);
2479 replace = PRVM_G_STRING(OFS_PARM1);
2480 subject = PRVM_G_STRING(OFS_PARM2);
2482 search_len = (int)strlen(search);
2483 replace_len = (int)strlen(replace);
2484 subject_len = (int)strlen(subject);
2487 for (i = 0; i <= subject_len - search_len; i++)
2489 for (j = 0; j < search_len; j++) // thus, i+j < subject_len
2490 if (subject[i+j] != search[j])
2492 if (j == search_len)
2494 // NOTE: if search_len == 0, we always hit THIS case, and never the other
2495 // found it at offset 'i'
2496 for (j = 0; j < replace_len && si < (int)sizeof(string) - 1; j++)
2497 string[si++] = replace[j];
2500 i += search_len - 1;
2504 // the above would subtract 1 from i... so we
2505 // don't do that, but instead output the next
2507 if (si < (int)sizeof(string) - 1)
2508 string[si++] = subject[i];
2513 // in THIS case, we know search_len > 0, thus i < subject_len
2515 if (si < (int)sizeof(string) - 1)
2516 string[si++] = subject[i];
2519 // remaining chars (these cannot match)
2520 for (; i < subject_len; i++)
2521 if (si < (int)sizeof(string) - 1)
2522 string[si++] = subject[i];
2525 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string, si);
2532 string(string search, string replace, string subject) strireplace = #485;
2535 // case-insensitive version of strreplace
2536 void VM_strireplace(prvm_prog_t *prog)
2539 const char *search, *replace, *subject;
2540 char string[VM_TEMPSTRING_MAXSIZE];
2541 int search_len, replace_len, subject_len;
2543 VM_SAFEPARMCOUNT(3, VM_strireplace);
2545 search = PRVM_G_STRING(OFS_PARM0);
2546 replace = PRVM_G_STRING(OFS_PARM1);
2547 subject = PRVM_G_STRING(OFS_PARM2);
2549 search_len = (int)strlen(search);
2550 replace_len = (int)strlen(replace);
2551 subject_len = (int)strlen(subject);
2554 for (i = 0; i <= subject_len - search_len; i++)
2556 for (j = 0; j < search_len; j++) // thus, i+j < subject_len
2557 if (tolower(subject[i+j]) != tolower(search[j]))
2559 if (j == search_len)
2561 // NOTE: if search_len == 0, we always hit THIS case, and never the other
2562 // found it at offset 'i'
2563 for (j = 0; j < replace_len && si < (int)sizeof(string) - 1; j++)
2564 string[si++] = replace[j];
2567 i += search_len - 1;
2571 // the above would subtract 1 from i... so we
2572 // don't do that, but instead output the next
2574 if (si < (int)sizeof(string) - 1)
2575 string[si++] = subject[i];
2580 // in THIS case, we know search_len > 0, thus i < subject_len
2582 if (si < (int)sizeof(string) - 1)
2583 string[si++] = subject[i];
2586 // remaining chars (these cannot match)
2587 for (; i < subject_len; i++)
2588 if (si < (int)sizeof(string) - 1)
2589 string[si++] = subject[i];
2592 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string, si);
2599 vector stov(string s)
2602 //vector(string s) stov = #117; // returns vector value from a string
2603 void VM_stov(prvm_prog_t *prog)
2605 char string[VM_TEMPSTRING_MAXSIZE];
2607 VM_SAFEPARMCOUNT(1,VM_stov);
2609 VM_VarString(prog, 0, string, sizeof(string));
2610 Math_atov(string, PRVM_G_VECTOR(OFS_RETURN));
2617 string strzone(string s)
2620 //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)
2621 void VM_strzone(prvm_prog_t *prog)
2624 char string[VM_TEMPSTRING_MAXSIZE];
2627 VM_SAFEPARMCOUNT(1,VM_strzone);
2629 alloclen = VM_VarString(prog, 0, string, sizeof(string)) + 1;
2630 PRVM_G_INT(OFS_RETURN) = PRVM_AllocString(prog, alloclen, &out);
2631 memcpy(out, string, alloclen);
2641 //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!!!)
2642 void VM_strunzone(prvm_prog_t *prog)
2644 VM_SAFEPARMCOUNT(1,VM_strunzone);
2645 PRVM_FreeString(prog, PRVM_G_INT(OFS_PARM0));
2652 float tokenize(string s)
2655 //float(string s) tokenize = #441; // takes apart a string into individal words (access them with argv), returns how many
2656 //this function originally written by KrimZon, made shorter by LadyHavoc
2657 //20040203: rewritten by LadyHavoc (no longer uses allocations)
2658 static int num_tokens = 0;
2659 static int tokens[VM_TEMPSTRING_MAXSIZE / 2];
2660 static int tokens_startpos[VM_TEMPSTRING_MAXSIZE / 2];
2661 static int tokens_endpos[VM_TEMPSTRING_MAXSIZE / 2];
2662 static char tokenize_string[VM_TEMPSTRING_MAXSIZE];
2663 void VM_tokenize (prvm_prog_t *prog)
2667 VM_SAFEPARMCOUNT(1,VM_tokenize);
2669 dp_strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2670 p = tokenize_string;
2675 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
2678 // skip whitespace here to find token start pos
2679 while(*p && ISWHITESPACE(*p))
2682 tokens_startpos[num_tokens] = p - tokenize_string;
2683 if(!COM_ParseToken_VM_Tokenize(&p, false))
2685 tokens_endpos[num_tokens] = p - tokenize_string;
2686 tokens[num_tokens] = PRVM_SetTempString(prog, com_token, com_token_len);
2690 PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2693 //float(string s) tokenize = #514; // takes apart a string into individal words (access them with argv), returns how many
2694 void VM_tokenize_console (prvm_prog_t *prog)
2698 VM_SAFEPARMCOUNT(1, VM_tokenize_console);
2700 dp_strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2701 p = tokenize_string;
2706 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
2709 // skip whitespace here to find token start pos
2710 while(*p && ISWHITESPACE(*p))
2713 tokens_startpos[num_tokens] = p - tokenize_string;
2714 if(!COM_ParseToken_Console(&p))
2716 tokens_endpos[num_tokens] = p - tokenize_string;
2717 tokens[num_tokens] = PRVM_SetTempString(prog, com_token, com_token_len);
2721 PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2726 VM_tokenizebyseparator
2728 float tokenizebyseparator(string s, string separator1, ...)
2731 //float(string s, string separator1, ...) tokenizebyseparator = #479; // takes apart a string into individal words (access them with argv), returns how many
2732 //this function returns the token preceding each instance of a separator (of
2733 //which there can be multiple), and the text following the last separator
2734 //useful for parsing certain kinds of data like IP addresses
2736 //numnumbers = tokenizebyseparator("10.1.2.3", ".");
2737 //returns 4 and the tokens "10" "1" "2" "3".
2738 void VM_tokenizebyseparator (prvm_prog_t *prog)
2742 int separatorlen[7];
2743 const char *separators[7];
2746 char tokentext[MAX_INPUTLINE];
2748 VM_SAFEPARMCOUNTRANGE(2, 8,VM_tokenizebyseparator);
2750 dp_strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2751 p = tokenize_string;
2754 for (j = 1;j < prog->argc;j++)
2756 // skip any blank separator strings
2757 const char *s = PRVM_G_STRING(OFS_PARM0+j*3);
2760 separators[numseparators] = s;
2761 separatorlen[numseparators] = (int)strlen(s);
2768 while (num_tokens < (int)(sizeof(tokens)/sizeof(tokens[0])))
2770 token = tokentext + j;
2771 tokens_startpos[num_tokens] = p - tokenize_string;
2775 for (k = 0;k < numseparators;k++)
2777 if (!strncmp(p, separators[k], separatorlen[k]))
2779 p += separatorlen[k];
2783 if (k < numseparators)
2785 if (j < (int)sizeof(tokentext)-1)
2786 tokentext[j++] = *p;
2790 tokens_endpos[num_tokens] = p0 - tokenize_string;
2791 if (j >= (int)sizeof(tokentext))
2793 tokentext[j++] = '\0';
2794 tokens[num_tokens++] = PRVM_SetTempString(prog, token, j - 1);
2799 PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2802 //string(float n) argv = #442; // returns a word from the tokenized string (returns nothing for an invalid index)
2803 //this function originally written by KrimZon, made shorter by LadyHavoc
2804 void VM_argv (prvm_prog_t *prog)
2808 VM_SAFEPARMCOUNT(1,VM_argv);
2810 token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2813 token_num += num_tokens;
2815 if (token_num >= 0 && token_num < num_tokens)
2816 PRVM_G_INT(OFS_RETURN) = tokens[token_num];
2818 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
2821 //float(float n) argv_start_index = #515; // returns the start index of a token
2822 void VM_argv_start_index (prvm_prog_t *prog)
2826 VM_SAFEPARMCOUNT(1,VM_argv);
2828 token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2831 token_num += num_tokens;
2833 if (token_num >= 0 && token_num < num_tokens)
2834 PRVM_G_FLOAT(OFS_RETURN) = tokens_startpos[token_num];
2836 PRVM_G_FLOAT(OFS_RETURN) = -1;
2839 //float(float n) argv_end_index = #516; // returns the end index of a token
2840 void VM_argv_end_index (prvm_prog_t *prog)
2844 VM_SAFEPARMCOUNT(1,VM_argv);
2846 token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2849 token_num += num_tokens;
2851 if (token_num >= 0 && token_num < num_tokens)
2852 PRVM_G_FLOAT(OFS_RETURN) = tokens_endpos[token_num];
2854 PRVM_G_FLOAT(OFS_RETURN) = -1;
2864 void VM_isserver(prvm_prog_t *prog)
2866 VM_SAFEPARMCOUNT(0, VM_isserver);
2868 PRVM_G_FLOAT(OFS_RETURN) = sv.active;
2878 void VM_clientcount(prvm_prog_t *prog)
2880 VM_SAFEPARMCOUNT(0,VM_clientcount);
2882 PRVM_G_FLOAT(OFS_RETURN) = svs.maxclients;
2892 void VM_clientstate(prvm_prog_t *prog)
2894 VM_SAFEPARMCOUNT(0,VM_clientstate);
2897 switch( cls.state ) {
2898 case ca_uninitialized:
2900 PRVM_G_FLOAT(OFS_RETURN) = 0;
2902 case ca_disconnected:
2903 PRVM_G_FLOAT(OFS_RETURN) = 1;
2906 PRVM_G_FLOAT(OFS_RETURN) = 2;
2909 // should never be reached!
2918 float getostype(prvm_prog_t *prog)
2920 */ // not used at the moment -> not included in the common list
2921 void VM_getostype(prvm_prog_t *prog)
2923 VM_SAFEPARMCOUNT(0,VM_getostype);
2928 OS_MAC - not supported
2932 PRVM_G_FLOAT(OFS_RETURN) = 0;
2933 #elif defined(MACOSX)
2934 PRVM_G_FLOAT(OFS_RETURN) = 2;
2936 PRVM_G_FLOAT(OFS_RETURN) = 1;
2944 float gettime(prvm_prog_t *prog)
2947 float CDAudio_GetPosition(void);
2948 void VM_gettime(prvm_prog_t *prog)
2952 VM_SAFEPARMCOUNTRANGE(0,1,VM_gettime);
2956 PRVM_G_FLOAT(OFS_RETURN) = (prvm_vec_t) host.realtime;
2960 timer_index = (int) PRVM_G_FLOAT(OFS_PARM0);
2963 case 0: // GETTIME_FRAMESTART
2964 PRVM_G_FLOAT(OFS_RETURN) = host.realtime;
2966 case 1: // GETTIME_REALTIME
2967 PRVM_G_FLOAT(OFS_RETURN) = Sys_DirtyTime();
2969 case 2: // GETTIME_HIRES
2970 PRVM_G_FLOAT(OFS_RETURN) = (Sys_DirtyTime() - host.dirtytime);
2972 case 3: // GETTIME_UPTIME
2973 PRVM_G_FLOAT(OFS_RETURN) = host.realtime;
2975 case 4: // GETTIME_CDTRACK
2976 PRVM_G_FLOAT(OFS_RETURN) = CDAudio_GetPosition();
2979 VM_Warning(prog, "VM_gettime: %s: unsupported timer specified, returning realtime\n", prog->name);
2980 PRVM_G_FLOAT(OFS_RETURN) = host.realtime;
2990 float getsoundtime(prvm_prog_t *prog)
2994 void VM_getsoundtime (prvm_prog_t *prog)
2996 int entnum, entchannel;
2997 VM_SAFEPARMCOUNT(2,VM_getsoundtime);
2999 if (prog == SVVM_prog)
3000 entnum = PRVM_NUM_FOR_EDICT(PRVM_G_EDICT(OFS_PARM0));
3001 else if (prog == CLVM_prog)
3002 entnum = MAX_EDICTS + PRVM_NUM_FOR_EDICT(PRVM_G_EDICT(OFS_PARM0));
3005 VM_Warning(prog, "VM_getsoundtime: %s: not supported on this progs\n", prog->name);
3006 PRVM_G_FLOAT(OFS_RETURN) = -1;
3009 entchannel = (int)PRVM_G_FLOAT(OFS_PARM1);
3010 entchannel = CHAN_USER2ENGINE(entchannel);
3011 if (!IS_CHAN(entchannel))
3012 VM_Warning(prog, "VM_getsoundtime: %s: bad channel %i\n", prog->name, entchannel);
3013 PRVM_G_FLOAT(OFS_RETURN) = (prvm_vec_t)S_GetEntChannelPosition(entnum, entchannel);
3020 string soundlength (string sample)
3023 void VM_soundlength (prvm_prog_t *prog)
3027 VM_SAFEPARMCOUNT(1, VM_soundlength);
3029 s = PRVM_G_STRING(OFS_PARM0);
3030 PRVM_G_FLOAT(OFS_RETURN) = S_SoundLength(s);
3037 loadfromdata(string data)
3040 void VM_loadfromdata(prvm_prog_t *prog)
3042 VM_SAFEPARMCOUNT(1, VM_loadfromdata);
3044 PRVM_ED_LoadFromFile(prog, PRVM_G_STRING(OFS_PARM0));
3048 ========================
3051 parseentitydata(entity ent, string data)
3052 ========================
3054 void VM_parseentitydata(prvm_prog_t *prog)
3059 VM_SAFEPARMCOUNT(2, VM_parseentitydata);
3061 // get edict and test it
3062 ent = PRVM_G_EDICT(OFS_PARM0);
3064 prog->error_cmd("VM_parseentitydata: %s: Can only set already spawned entities (entity %i is free)!", prog->name, PRVM_NUM_FOR_EDICT(ent));
3066 data = PRVM_G_STRING(OFS_PARM1);
3068 // parse the opening brace
3069 if (!COM_ParseToken_Simple(&data, false, false, true) || com_token[0] != '{' )
3070 prog->error_cmd("VM_parseentitydata: %s: Couldn't parse entity data:\n%s", prog->name, data );
3072 PRVM_ED_ParseEdict (prog, data, ent);
3079 loadfromfile(string file)
3082 void VM_loadfromfile(prvm_prog_t *prog)
3084 const char *filename;
3087 VM_SAFEPARMCOUNT(1,VM_loadfromfile);
3089 filename = PRVM_G_STRING(OFS_PARM0);
3090 if (FS_CheckNastyPath(filename, false))
3092 PRVM_G_FLOAT(OFS_RETURN) = -4;
3093 VM_Warning(prog, "VM_loadfromfile: %s dangerous or non-portable filename \"%s\" not allowed. (contains : or \\ or begins with .. or /)\n", prog->name, filename);
3097 // not conform with VM_fopen
3098 data = (char *)FS_LoadFile(filename, tempmempool, false, NULL);
3100 PRVM_G_FLOAT(OFS_RETURN) = -1;
3102 PRVM_ED_LoadFromFile(prog, data);
3113 float mod(float val, float m)
3116 void VM_modulo(prvm_prog_t *prog)
3120 VM_SAFEPARMCOUNT(2, VM_modulo);
3122 val = PRVM_G_FLOAT(OFS_PARM0);
3123 m = PRVM_G_FLOAT(OFS_PARM1);
3125 // matches how gmqcc implements % when mod() builtin isn't defined, and FTEQW mod()
3127 PRVM_G_FLOAT(OFS_RETURN) = val - m * (prvm_int_t)(val / m);
3130 VM_Warning(prog, "Attempted modulo of %f by zero\n", val);
3131 PRVM_G_FLOAT(OFS_RETURN) = 0;
3135 static void VM_Search_Init(prvm_prog_t *prog)
3138 for (i = 0;i < PRVM_MAX_OPENSEARCHES;i++)
3139 prog->opensearches[i] = NULL;
3142 static void VM_Search_Reset(prvm_prog_t *prog)
3145 // reset the fssearch list
3146 for(i = 0; i < PRVM_MAX_OPENSEARCHES; i++)
3148 if(prog->opensearches[i])
3149 FS_FreeSearch(prog->opensearches[i]);
3150 prog->opensearches[i] = NULL;
3158 float search_begin(string pattern, float caseinsensitive, float quiet[, string packfile])
3161 void VM_search_begin(prvm_prog_t *prog)
3164 const char *packfile = NULL, *pattern;
3165 int caseinsens, quiet;
3167 VM_SAFEPARMCOUNTRANGE(3, 4, VM_search_begin);
3169 pattern = PRVM_G_STRING(OFS_PARM0);
3171 VM_CheckEmptyString(prog, pattern);
3173 caseinsens = (int)PRVM_G_FLOAT(OFS_PARM1);
3174 quiet = (int)PRVM_G_FLOAT(OFS_PARM2);
3176 // optional packfile parameter (DP_QC_FS_SEARCH_PACKFILE)
3178 packfile = PRVM_G_STRING(OFS_PARM3);
3180 for(handle = 0; handle < PRVM_MAX_OPENSEARCHES; handle++)
3181 if(!prog->opensearches[handle])
3184 if(handle >= PRVM_MAX_OPENSEARCHES)
3186 PRVM_G_FLOAT(OFS_RETURN) = -2;
3187 VM_Warning(prog, "VM_search_begin: %s ran out of search handles (%i)\n", prog->name, PRVM_MAX_OPENSEARCHES);
3191 if(!(prog->opensearches[handle] = FS_Search(pattern,caseinsens, quiet, packfile)))
3192 PRVM_G_FLOAT(OFS_RETURN) = -1;
3195 prog->opensearches_origin[handle] = PRVM_AllocationOrigin(prog);
3196 PRVM_G_FLOAT(OFS_RETURN) = handle;
3204 void search_end(float handle)
3207 void VM_search_end(prvm_prog_t *prog)
3210 VM_SAFEPARMCOUNT(1, VM_search_end);
3212 handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3214 if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3216 VM_Warning(prog, "VM_search_end: invalid handle %i used in %s\n", handle, prog->name);
3219 if(prog->opensearches[handle] == NULL)
3221 VM_Warning(prog, "VM_search_end: no such handle %i in %s\n", handle, prog->name);
3225 FS_FreeSearch(prog->opensearches[handle]);
3226 prog->opensearches[handle] = NULL;
3227 if(prog->opensearches_origin[handle])
3228 PRVM_Free((char *)prog->opensearches_origin[handle]);
3235 float search_getsize(float handle)
3238 void VM_search_getsize(prvm_prog_t *prog)
3241 VM_SAFEPARMCOUNT(1, VM_search_getsize);
3243 handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3245 if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3247 VM_Warning(prog, "VM_search_getsize: invalid handle %i used in %s\n", handle, prog->name);
3250 if(prog->opensearches[handle] == NULL)
3252 VM_Warning(prog, "VM_search_getsize: no such handle %i in %s\n", handle, prog->name);
3256 PRVM_G_FLOAT(OFS_RETURN) = prog->opensearches[handle]->numfilenames;
3261 VM_search_getfilename
3263 string search_getfilename(float handle, float num)
3266 void VM_search_getfilename(prvm_prog_t *prog)
3268 int handle, filenum;
3270 VM_SAFEPARMCOUNT(2, VM_search_getfilename);
3272 handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3273 filenum = (int)PRVM_G_FLOAT(OFS_PARM1);
3275 if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3277 VM_Warning(prog, "VM_search_getfilename: invalid handle %i used in %s\n", handle, prog->name);
3280 if(prog->opensearches[handle] == NULL)
3282 VM_Warning(prog, "VM_search_getfilename: no such handle %i in %s\n", handle, prog->name);
3285 if(filenum < 0 || filenum >= prog->opensearches[handle]->numfilenames)
3287 VM_Warning(prog, "VM_search_getfilename: invalid filenum %i in %s\n", filenum, prog->name);
3291 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog,
3292 prog->opensearches[handle]->filenames[filenum],
3293 strlen(prog->opensearches[handle]->filenames[filenum]));
3300 string chr(float ascii)
3303 void VM_chr(prvm_prog_t *prog)
3307 VM_SAFEPARMCOUNT(1, VM_chr);
3309 tmp[0] = (unsigned char) PRVM_G_FLOAT(OFS_PARM0);
3312 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, tmp);
3318 VM_SAFEPARMCOUNT(1, VM_chr);
3319 len = u8_fromchar((Uchar)PRVM_G_FLOAT(OFS_PARM0), tmp, sizeof(tmp));
3321 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, tmp, len);
3328 string keynumtostring(float keynum)
3331 void VM_keynumtostring (prvm_prog_t *prog)
3333 char tinystr[TINYSTR_LEN];
3334 const char *str; // Key_KeynumToString doesn't always return tinystr
3336 VM_SAFEPARMCOUNT(1, VM_keynumtostring);
3337 str = Key_KeynumToString((int)PRVM_G_FLOAT(OFS_PARM0), tinystr, sizeof(tinystr));
3338 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, str, strlen(str));
3343 VM_findkeysforcommand
3345 string findkeysforcommand(string command, float bindmap)
3347 the returned string is an altstring
3350 #define FKFC_NUMKEYS 5
3351 void M_FindKeysForCommand(const char *command, int *keys);
3352 void VM_findkeysforcommand(prvm_prog_t *prog)
3355 char ret[VM_TEMPSTRING_MAXSIZE];
3357 int keys[FKFC_NUMKEYS];
3362 VM_SAFEPARMCOUNTRANGE(1, 2, VM_findkeysforcommand);
3364 cmd = PRVM_G_STRING(OFS_PARM0);
3366 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM1), MAX_BINDMAPS-1);
3368 bindmap = 0; // consistent to "bind"
3370 VM_CheckEmptyString(prog, cmd);
3372 Key_FindKeysForCommand(cmd, keys, FKFC_NUMKEYS, bindmap);
3375 for(i = 0; i < FKFC_NUMKEYS; i++)
3376 ret_len = dp_strlcat(ret, va(vabuf, sizeof(vabuf), " \'%i\'", keys[i]), sizeof(ret));
3378 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, ret, ret_len);
3385 float stringtokeynum(string key)
3388 void VM_stringtokeynum (prvm_prog_t *prog)
3390 VM_SAFEPARMCOUNT( 1, VM_stringtokeynum );
3392 PRVM_G_FLOAT(OFS_RETURN) = Key_StringToKeynum(PRVM_G_STRING(OFS_PARM0));
3399 string getkeybind(float key, float bindmap)
3402 void VM_getkeybind (prvm_prog_t *prog)
3407 VM_SAFEPARMCOUNTRANGE(1, 2, VM_getkeybind);
3409 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM1), MAX_BINDMAPS-1);
3411 bindmap = 0; // consistent to "bind"
3412 bind = Key_GetBind((int)PRVM_G_FLOAT(OFS_PARM0), bindmap);
3413 PRVM_G_INT(OFS_RETURN) = bind ? PRVM_SetTempString(prog, bind, strlen(bind)) : 0;
3420 float setkeybind(float key, string cmd, float bindmap)
3423 void VM_setkeybind (prvm_prog_t *prog)
3426 VM_SAFEPARMCOUNTRANGE(2, 3, VM_setkeybind);
3428 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM2), MAX_BINDMAPS-1);
3430 bindmap = 0; // consistent to "bind"
3432 PRVM_G_FLOAT(OFS_RETURN) = 0;
3433 if(Key_SetBinding((int)PRVM_G_FLOAT(OFS_PARM0), bindmap, PRVM_G_STRING(OFS_PARM1)))
3434 PRVM_G_FLOAT(OFS_RETURN) = 1;
3441 vector getbindmaps()
3444 void VM_getbindmaps (prvm_prog_t *prog)
3447 VM_SAFEPARMCOUNT(0, VM_getbindmaps);
3448 Key_GetBindMap(&fg, &bg);
3449 PRVM_G_VECTOR(OFS_RETURN)[0] = fg;
3450 PRVM_G_VECTOR(OFS_RETURN)[1] = bg;
3451 PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
3458 float setbindmaps(vector bindmap)
3461 void VM_setbindmaps (prvm_prog_t *prog)
3463 VM_SAFEPARMCOUNT(1, VM_setbindmaps);
3464 PRVM_G_FLOAT(OFS_RETURN) = 0;
3465 if(PRVM_G_VECTOR(OFS_PARM0)[2] == 0)
3466 if(Key_SetBindMap((int)PRVM_G_VECTOR(OFS_PARM0)[0], (int)PRVM_G_VECTOR(OFS_PARM0)[1]))
3467 PRVM_G_FLOAT(OFS_RETURN) = 1;
3471 ========================
3474 float[bool] gecko_create( string name )
3475 ========================
3477 void VM_gecko_create(prvm_prog_t *prog) {
3479 PRVM_G_FLOAT( OFS_RETURN ) = 0;
3483 ========================
3486 void gecko_destroy( string name )
3487 ========================
3489 void VM_gecko_destroy(prvm_prog_t *prog) {
3494 ========================
3497 void gecko_navigate( string name, string URI )
3498 ========================
3500 void VM_gecko_navigate(prvm_prog_t *prog) {
3505 ========================
3508 float[bool] gecko_keyevent( string name, float key, float eventtype )
3509 ========================
3511 void VM_gecko_keyevent(prvm_prog_t *prog) {
3513 PRVM_G_FLOAT( OFS_RETURN ) = 0;
3517 ========================
3520 void gecko_mousemove( string name, float x, float y )
3521 ========================
3523 void VM_gecko_movemouse(prvm_prog_t *prog) {
3529 ========================
3532 void gecko_resize( string name, float w, float h )
3533 ========================
3535 void VM_gecko_resize(prvm_prog_t *prog) {
3541 ========================
3542 VM_gecko_get_texture_extent
3544 vector gecko_get_texture_extent( string name )
3545 ========================
3547 void VM_gecko_get_texture_extent(prvm_prog_t *prog) {
3549 PRVM_G_VECTOR(OFS_RETURN)[0] = 0;
3550 PRVM_G_VECTOR(OFS_RETURN)[1] = 0;
3559 Writes new values for v_forward, v_up, and v_right based on angles
3560 void makevectors(vector angle)
3563 void VM_makevectors (prvm_prog_t *prog)
3565 vec3_t angles, forward, right, up;
3566 VM_SAFEPARMCOUNT(1, VM_makevectors);
3567 VectorCopy(PRVM_G_VECTOR(OFS_PARM0), angles);
3568 AngleVectors(angles, forward, right, up);
3569 VectorCopy(forward, PRVM_gameglobalvector(v_forward));
3570 VectorCopy(right, PRVM_gameglobalvector(v_right));
3571 VectorCopy(up, PRVM_gameglobalvector(v_up));
3578 Writes new values for v_forward, v_up, and v_right based on the given forward vector
3579 vectorvectors(vector)
3582 void VM_vectorvectors (prvm_prog_t *prog)
3584 vec3_t forward, right, up;
3585 VM_SAFEPARMCOUNT(1, VM_vectorvectors);
3586 VectorNormalize2(PRVM_G_VECTOR(OFS_PARM0), forward);
3587 VectorVectors(forward, right, up);
3588 VectorCopy(forward, PRVM_gameglobalvector(v_forward));
3589 VectorCopy(right, PRVM_gameglobalvector(v_right));
3590 VectorCopy(up, PRVM_gameglobalvector(v_up));
3593 // float(float number, float quantity) bitshift (EXT_BITSHIFT)
3594 void VM_bitshift (prvm_prog_t *prog)
3597 VM_SAFEPARMCOUNT(2, VM_bitshift);
3599 n1 = (prvm_int_t)fabs((prvm_vec_t)((prvm_int_t)PRVM_G_FLOAT(OFS_PARM0)));
3600 n2 = (prvm_int_t)PRVM_G_FLOAT(OFS_PARM1);
3602 PRVM_G_FLOAT(OFS_RETURN) = n1;
3605 PRVM_G_FLOAT(OFS_RETURN) = (n1 >> -n2);
3607 PRVM_G_FLOAT(OFS_RETURN) = (n1 << n2);
3610 ////////////////////////////////////////
3611 // AltString functions
3612 ////////////////////////////////////////
3615 ========================
3618 float altstr_count(string)
3619 ========================
3621 void VM_altstr_count(prvm_prog_t *prog)
3623 const char *altstr, *pos;
3626 VM_SAFEPARMCOUNT( 1, VM_altstr_count );
3628 altstr = PRVM_G_STRING( OFS_PARM0 );
3629 //VM_CheckEmptyString(prog, altstr );
3631 for( count = 0, pos = altstr ; *pos ; pos++ ) {
3632 if( *pos == '\\' ) {
3636 } else if( *pos == '\'' ) {
3641 PRVM_G_FLOAT( OFS_RETURN ) = (prvm_vec_t) (count / 2);
3645 ========================
3648 string altstr_prepare(string)
3649 ========================
3651 void VM_altstr_prepare(prvm_prog_t *prog)
3653 const char *instr, *in;
3654 char outstr[VM_TEMPSTRING_MAXSIZE];
3657 VM_SAFEPARMCOUNT( 1, VM_altstr_prepare );
3659 instr = PRVM_G_STRING( OFS_PARM0 );
3661 for (in = instr, outpos = 0; *in && outpos < sizeof(outstr) - 1; ++in)
3663 if (*in == '\'' && outpos < sizeof(outstr) - 2)
3665 outstr[outpos++] = '\\';
3666 outstr[outpos++] = '\'';
3669 outstr[outpos++] = *in;
3672 outstr[outpos] = '\0';
3673 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outstr, outpos);
3677 ========================
3680 string altstr_get(string, float)
3681 ========================
3683 void VM_altstr_get(prvm_prog_t *prog)
3685 const char *altstr, *pos;
3688 char outstr[VM_TEMPSTRING_MAXSIZE];
3690 VM_SAFEPARMCOUNT( 2, VM_altstr_get );
3692 altstr = PRVM_G_STRING( OFS_PARM0 );
3694 count = (int)PRVM_G_FLOAT( OFS_PARM1 );
3695 count = count * 2 + 1;
3697 for( pos = altstr ; *pos && count ; pos++ )
3698 if( *pos == '\\' ) {
3701 } else if( *pos == '\'' )
3705 PRVM_G_INT( OFS_RETURN ) = 0;
3709 for( out = outstr, size = sizeof(outstr) - 1 ; size && *pos ; size--, pos++, out++ )
3710 if( *pos == '\\' ) {
3715 } else if( *pos == '\'' )
3721 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outstr, out - outstr);
3725 ========================
3728 string altstr_set(string altstr, float num, string set)
3729 ========================
3731 void VM_altstr_set(prvm_prog_t *prog)
3734 const char *altstr, *str;
3737 char outstr[VM_TEMPSTRING_MAXSIZE];
3739 VM_SAFEPARMCOUNT( 3, VM_altstr_set );
3741 altstr = PRVM_G_STRING( OFS_PARM0 );
3743 num = (int)PRVM_G_FLOAT( OFS_PARM1 );
3745 str = PRVM_G_STRING( OFS_PARM2 );
3748 for( num = num * 2 + 1, in = altstr; *in && num; *out++ = *in++ )
3753 } else if( *in == '\'' ) {
3758 for( ; *str; *out++ = *str++ );
3759 // now jump over the old content
3761 if( *in == '\'' || (*in == '\\' && !*++in) )
3764 out += dp_strlcpy(out, in, outstr + sizeof(outstr) - out);
3765 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outstr, out - outstr);
3769 ========================
3772 string altstr_ins(string altstr, float num, string set)
3773 ========================
3775 void VM_altstr_ins(prvm_prog_t *prog)
3781 char outstr[VM_TEMPSTRING_MAXSIZE];
3783 VM_SAFEPARMCOUNT(3, VM_altstr_ins);
3785 in = PRVM_G_STRING( OFS_PARM0 );
3786 num = (int)PRVM_G_FLOAT( OFS_PARM1 );
3787 set = PRVM_G_STRING( OFS_PARM2 );
3790 for( num = num * 2 + 2 ; *in && num > 0 ; *out++ = *in++ )
3795 } else if( *in == '\'' ) {
3800 for( ; *set ; *out++ = *set++ );
3803 out += dp_strlcpy(out, in, outstr + sizeof(outstr) - out);
3804 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outstr, out - outstr);
3808 ////////////////////////////////////////
3809 // BufString functions
3810 ////////////////////////////////////////
3811 //[515]: string buffers support
3813 static size_t stringbuffers_sortlength;
3815 static void BufStr_Expand(prvm_prog_t *prog, prvm_stringbuffer_t *stringbuffer, int strindex)
3817 if (stringbuffer->max_strings <= strindex)
3819 char **oldstrings = stringbuffer->strings;
3820 stringbuffer->max_strings = max(stringbuffer->max_strings * 2, 128);
3821 while (stringbuffer->max_strings <= strindex)
3822 stringbuffer->max_strings *= 2;
3823 stringbuffer->strings = (char **) Mem_Alloc(prog->progs_mempool, stringbuffer->max_strings * sizeof(stringbuffer->strings[0]));
3824 if (stringbuffer->num_strings > 0)
3825 memcpy(stringbuffer->strings, oldstrings, stringbuffer->num_strings * sizeof(stringbuffer->strings[0]));
3827 Mem_Free(oldstrings);
3831 static void BufStr_Shrink(prvm_prog_t *prog, prvm_stringbuffer_t *stringbuffer)
3833 // reduce num_strings if there are empty string slots at the end
3834 while (stringbuffer->num_strings > 0 && stringbuffer->strings[stringbuffer->num_strings - 1] == NULL)
3835 stringbuffer->num_strings--;
3837 // if empty, free the string pointer array
3838 if (stringbuffer->num_strings == 0)
3840 stringbuffer->max_strings = 0;
3841 if (stringbuffer->strings)
3842 Mem_Free(stringbuffer->strings);
3843 stringbuffer->strings = NULL;
3847 static int BufStr_SortStringsUP (const void *in1, const void *in2)
3850 a = *((const char **) in1);
3851 b = *((const char **) in2);
3852 if(!a || !a[0]) return 1;
3853 if(!b || !b[0]) return -1;
3854 return strncmp(a, b, stringbuffers_sortlength);
3857 static int BufStr_SortStringsDOWN (const void *in1, const void *in2)
3860 a = *((const char **) in1);
3861 b = *((const char **) in2);
3862 if(!a || !a[0]) return 1;
3863 if(!b || !b[0]) return -1;
3864 return strncmp(b, a, stringbuffers_sortlength);
3867 prvm_stringbuffer_t *BufStr_FindCreateReplace (prvm_prog_t *prog, int bufindex, unsigned flags, const char *format)
3869 prvm_stringbuffer_t *stringbuffer;
3875 // find buffer with wanted index
3876 if (bufindex < (int)Mem_ExpandableArray_IndexRange(&prog->stringbuffersarray))
3878 if ( (stringbuffer = (prvm_stringbuffer_t*) Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, bufindex)) )
3880 if (stringbuffer->flags & STRINGBUFFER_TEMP)
3881 stringbuffer->flags = flags; // created but has not been used yet
3882 return stringbuffer;
3887 // allocate new buffer with wanted index
3890 stringbuffer = (prvm_stringbuffer_t *) Mem_ExpandableArray_AllocRecord(&prog->stringbuffersarray);
3891 stringbuffer->flags = STRINGBUFFER_TEMP;
3892 for (i = 0;stringbuffer != Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, i);i++);
3895 stringbuffer->flags = flags; // mark as used
3899 return stringbuffer;
3902 void BufStr_Set(prvm_prog_t *prog, prvm_stringbuffer_t *stringbuffer, int strindex, const char *str)
3906 if (!stringbuffer || strindex < 0)
3909 BufStr_Expand(prog, stringbuffer, strindex);
3910 stringbuffer->num_strings = max(stringbuffer->num_strings, strindex + 1);
3911 if (stringbuffer->strings[strindex])
3912 Mem_Free(stringbuffer->strings[strindex]);
3913 stringbuffer->strings[strindex] = NULL;
3917 // not the NULL string!
3918 alloclen = strlen(str) + 1;
3919 stringbuffer->strings[strindex] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
3920 memcpy(stringbuffer->strings[strindex], str, alloclen);
3923 BufStr_Shrink(prog, stringbuffer);
3926 void BufStr_Del(prvm_prog_t *prog, prvm_stringbuffer_t *stringbuffer)
3933 for (i = 0;i < stringbuffer->num_strings;i++)
3934 if (stringbuffer->strings[i])
3935 Mem_Free(stringbuffer->strings[i]);
3936 if (stringbuffer->strings)
3937 Mem_Free(stringbuffer->strings);
3938 if(stringbuffer->origin)
3939 PRVM_Free((char *)stringbuffer->origin);
3940 Mem_ExpandableArray_FreeRecord(&prog->stringbuffersarray, stringbuffer);
3943 void BufStr_Flush(prvm_prog_t *prog)
3945 prvm_stringbuffer_t *stringbuffer;
3948 numbuffers = (int)Mem_ExpandableArray_IndexRange(&prog->stringbuffersarray);
3949 for (i = 0; i < numbuffers; i++)
3950 if ( (stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, i)) )
3951 BufStr_Del(prog, stringbuffer);
3952 Mem_ExpandableArray_NewArray(&prog->stringbuffersarray, prog->progs_mempool, sizeof(prvm_stringbuffer_t), 64);
3956 ========================
3958 creates new buffer, and returns it's index, returns -1 if failed
3959 float buf_create(prvm_prog_t *prog) = #460;
3960 float newbuf(string format, float flags) = #460;
3961 ========================
3964 void VM_buf_create (prvm_prog_t *prog)
3966 prvm_stringbuffer_t *stringbuffer;
3969 VM_SAFEPARMCOUNTRANGE(0, 2, VM_buf_create);
3971 // VorteX: optional parm1 (buffer format) is unfinished, to keep intact with future databuffers extension must be set to "string"
3972 if(prog->argc >= 1 && strcmp(PRVM_G_STRING(OFS_PARM0), "string"))
3974 PRVM_G_FLOAT(OFS_RETURN) = -1;
3977 stringbuffer = (prvm_stringbuffer_t *) Mem_ExpandableArray_AllocRecord(&prog->stringbuffersarray);
3978 for (i = 0;stringbuffer != Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, i);i++);
3979 stringbuffer->origin = PRVM_AllocationOrigin(prog);
3980 // optional flags parm
3981 if (prog->argc >= 2)
3982 stringbuffer->flags = (int)PRVM_G_FLOAT(OFS_PARM1) & STRINGBUFFER_QCFLAGS;
3983 PRVM_G_FLOAT(OFS_RETURN) = i;
3989 ========================
3991 deletes buffer and all strings in it
3992 void buf_del(float bufhandle) = #461;
3993 ========================
3995 void VM_buf_del (prvm_prog_t *prog)
3997 prvm_stringbuffer_t *stringbuffer;
3998 VM_SAFEPARMCOUNT(1, VM_buf_del);
3999 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4001 BufStr_Del(prog, stringbuffer);
4004 VM_Warning(prog, "VM_buf_del: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4010 ========================
4012 how many strings are stored in buffer
4013 float buf_getsize(float bufhandle) = #462;
4014 ========================
4016 void VM_buf_getsize (prvm_prog_t *prog)
4018 prvm_stringbuffer_t *stringbuffer;
4019 VM_SAFEPARMCOUNT(1, VM_buf_getsize);
4021 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4024 PRVM_G_FLOAT(OFS_RETURN) = -1;
4025 VM_Warning(prog, "VM_buf_getsize: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4029 PRVM_G_FLOAT(OFS_RETURN) = stringbuffer->num_strings;
4033 ========================
4035 copy all content from one buffer to another, make sure it exists
4036 void buf_copy(float bufhandle_from, float bufhandle_to) = #463;
4037 ========================
4039 void VM_buf_copy (prvm_prog_t *prog)
4041 prvm_stringbuffer_t *srcstringbuffer, *dststringbuffer;
4043 VM_SAFEPARMCOUNT(2, VM_buf_copy);
4045 srcstringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4046 if(!srcstringbuffer)
4048 VM_Warning(prog, "VM_buf_copy: invalid source buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4051 i = (int)PRVM_G_FLOAT(OFS_PARM1);
4052 if(i == (int)PRVM_G_FLOAT(OFS_PARM0))
4054 VM_Warning(prog, "VM_buf_copy: source == destination (%i) in %s\n", i, prog->name);
4057 dststringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4058 if(!dststringbuffer)
4060 VM_Warning(prog, "VM_buf_copy: invalid destination buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), prog->name);
4064 for (i = 0;i < dststringbuffer->num_strings;i++)
4065 if (dststringbuffer->strings[i])
4066 Mem_Free(dststringbuffer->strings[i]);
4067 if (dststringbuffer->strings)
4068 Mem_Free(dststringbuffer->strings);
4069 *dststringbuffer = *srcstringbuffer;
4070 if (dststringbuffer->max_strings)
4071 dststringbuffer->strings = (char **)Mem_Alloc(prog->progs_mempool, sizeof(dststringbuffer->strings[0]) * dststringbuffer->max_strings);
4073 for (i = 0;i < dststringbuffer->num_strings;i++)
4075 if (srcstringbuffer->strings[i])
4078 stringlen = strlen(srcstringbuffer->strings[i]) + 1;
4079 dststringbuffer->strings[i] = (char *)Mem_Alloc(prog->progs_mempool, stringlen);
4080 memcpy(dststringbuffer->strings[i], srcstringbuffer->strings[i], stringlen);
4086 ========================
4088 sort buffer by beginnings of strings (cmplength defaults it's length)
4089 "backward == true" means that sorting goes upside-down
4090 void buf_sort(float bufhandle, float cmplength, float backward) = #464;
4091 ========================
4093 void VM_buf_sort (prvm_prog_t *prog)
4095 prvm_stringbuffer_t *stringbuffer;
4096 VM_SAFEPARMCOUNT(3, VM_buf_sort);
4098 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4101 VM_Warning(prog, "VM_buf_sort: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4104 if(stringbuffer->num_strings <= 0)
4106 VM_Warning(prog, "VM_buf_sort: tried to sort empty buffer %i in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4109 stringbuffers_sortlength = (int)PRVM_G_FLOAT(OFS_PARM1);
4110 if(stringbuffers_sortlength <= 0)
4111 stringbuffers_sortlength = 0x7FFFFFFF;
4113 if(!PRVM_G_FLOAT(OFS_PARM2))
4114 qsort(stringbuffer->strings, stringbuffer->num_strings, sizeof(char*), BufStr_SortStringsUP);
4116 qsort(stringbuffer->strings, stringbuffer->num_strings, sizeof(char*), BufStr_SortStringsDOWN);
4118 BufStr_Shrink(prog, stringbuffer);
4122 ========================
4124 concantenates all buffer string into one with "glue" separator and returns it as tempstring
4125 string buf_implode(float bufhandle, string glue) = #465;
4126 ========================
4128 void VM_buf_implode (prvm_prog_t *prog)
4130 prvm_stringbuffer_t *stringbuffer;
4131 char k[VM_TEMPSTRING_MAXSIZE];
4137 VM_SAFEPARMCOUNT(2, VM_buf_implode);
4139 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4140 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
4143 VM_Warning(prog, "VM_buf_implode: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4146 if(!stringbuffer->num_strings)
4148 sep = PRVM_G_STRING(OFS_PARM1);
4151 for(l = i = 0;i < stringbuffer->num_strings;i++)
4153 if(stringbuffer->strings[i])
4155 l += (i > 0 ? strlen(sep) : 0) + strlen(stringbuffer->strings[i]);
4156 if (l >= sizeof(k) - 1)
4158 dp_strlcat(k, sep, sizeof(k));
4159 k_len = dp_strlcat(k, stringbuffer->strings[i], sizeof(k));
4162 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, k, k_len);
4166 ========================
4168 get a string from buffer, returns tempstring, dont str_unzone it!
4169 string bufstr_get(float bufhandle, float string_index) = #465;
4170 ========================
4172 void VM_bufstr_get (prvm_prog_t *prog)
4174 prvm_stringbuffer_t *stringbuffer;
4176 VM_SAFEPARMCOUNT(2, VM_bufstr_get);
4178 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
4179 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4182 VM_Warning(prog, "VM_bufstr_get: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4185 strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
4188 // VM_Warning(prog, "VM_bufstr_get: invalid string index %i used in %s\n", strindex, prog->name);
4191 if (strindex < stringbuffer->num_strings && stringbuffer->strings[strindex])
4192 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, stringbuffer->strings[strindex], strlen(stringbuffer->strings[strindex]));
4196 ========================
4198 copies a string into selected slot of buffer
4199 void bufstr_set(float bufhandle, float string_index, string str) = #466;
4200 ========================
4202 void VM_bufstr_set (prvm_prog_t *prog)
4205 prvm_stringbuffer_t *stringbuffer;
4208 VM_SAFEPARMCOUNT(3, VM_bufstr_set);
4210 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4213 VM_Warning(prog, "VM_bufstr_set: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4216 strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
4217 if(strindex < 0 || strindex >= 1000000) // huge number of strings
4219 VM_Warning(prog, "VM_bufstr_set: invalid string index %i used in %s\n", strindex, prog->name);
4223 news = PRVM_G_STRING(OFS_PARM2);
4224 BufStr_Set(prog, stringbuffer, strindex, news);
4228 ========================
4230 adds string to buffer in first free slot and returns its index
4231 "order == true" means that string will be added after last "full" slot
4232 float bufstr_add(float bufhandle, string str, float order) = #467;
4233 ========================
4235 void VM_bufstr_add (prvm_prog_t *prog)
4237 int order, strindex;
4238 prvm_stringbuffer_t *stringbuffer;
4242 VM_SAFEPARMCOUNT(3, VM_bufstr_add);
4244 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4245 PRVM_G_FLOAT(OFS_RETURN) = -1;
4248 VM_Warning(prog, "VM_bufstr_add: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4251 if(!PRVM_G_INT(OFS_PARM1)) // NULL string
4253 VM_Warning(prog, "VM_bufstr_add: can not add an empty string to buffer %i in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4256 string = PRVM_G_STRING(OFS_PARM1);
4257 order = (int)PRVM_G_FLOAT(OFS_PARM2);
4259 strindex = stringbuffer->num_strings;
4261 for (strindex = 0;strindex < stringbuffer->num_strings;strindex++)
4262 if (stringbuffer->strings[strindex] == NULL)
4265 BufStr_Expand(prog, stringbuffer, strindex);
4267 stringbuffer->num_strings = max(stringbuffer->num_strings, strindex + 1);
4268 alloclen = strlen(string) + 1;
4269 stringbuffer->strings[strindex] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
4270 memcpy(stringbuffer->strings[strindex], string, alloclen);
4272 PRVM_G_FLOAT(OFS_RETURN) = strindex;
4276 ========================
4278 delete string from buffer
4279 void bufstr_free(float bufhandle, float string_index) = #468;
4280 ========================
4282 void VM_bufstr_free (prvm_prog_t *prog)
4285 prvm_stringbuffer_t *stringbuffer;
4286 VM_SAFEPARMCOUNT(2, VM_bufstr_free);
4288 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4291 VM_Warning(prog, "VM_bufstr_free: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4294 i = (int)PRVM_G_FLOAT(OFS_PARM1);
4297 VM_Warning(prog, "VM_bufstr_free: invalid string index %i used in %s\n", i, prog->name);
4301 if (i < stringbuffer->num_strings)
4303 if(stringbuffer->strings[i])
4304 Mem_Free(stringbuffer->strings[i]);
4305 stringbuffer->strings[i] = NULL;
4308 BufStr_Shrink(prog, stringbuffer);
4312 ========================
4314 load a file into string buffer, return 0 or 1
4315 float buf_loadfile(string filename, float bufhandle) = #535;
4316 ========================
4318 void VM_buf_loadfile(prvm_prog_t *prog)
4321 prvm_stringbuffer_t *stringbuffer;
4322 char string[VM_TEMPSTRING_MAXSIZE];
4323 int strindex, c, end;
4324 const char *filename;
4328 VM_SAFEPARMCOUNT(2, VM_buf_loadfile);
4331 filename = PRVM_G_STRING(OFS_PARM0);
4332 file = FS_OpenVirtualFile(va(vabuf, sizeof(vabuf), "data/%s", filename), false);
4334 file = FS_OpenVirtualFile(va(vabuf, sizeof(vabuf), "%s", filename), false);
4337 if (developer_extra.integer)
4338 VM_Warning(prog, "VM_buf_loadfile: failed to open file %s in %s\n", filename, prog->name);
4339 PRVM_G_FLOAT(OFS_RETURN) = 0;
4343 // get string buffer
4344 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM1));
4347 VM_Warning(prog, "VM_buf_loadfile: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), prog->name);
4348 PRVM_G_FLOAT(OFS_RETURN) = 0;
4352 // read file (append to the end of buffer)
4353 strindex = stringbuffer->num_strings;
4361 if (c == '\r' || c == '\n' || c < 0)
4363 if (end < VM_TEMPSTRING_MAXSIZE - 1)
4367 // remove \n following \r
4372 FS_UnGetc(file, (unsigned char)c);
4377 BufStr_Expand(prog, stringbuffer, strindex);
4378 stringbuffer->num_strings = max(stringbuffer->num_strings, strindex + 1);
4379 alloclen = strlen(string) + 1;
4380 stringbuffer->strings[strindex] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
4381 memcpy(stringbuffer->strings[strindex], string, alloclen);
4382 strindex = stringbuffer->num_strings;
4390 PRVM_G_FLOAT(OFS_RETURN) = 1;
4394 ========================
4396 writes stringbuffer to a file, returns 0 or 1
4397 float buf_writefile(float filehandle, float bufhandle, [, float startpos, float numstrings]) = #468;
4398 ========================
4401 void VM_buf_writefile(prvm_prog_t *prog)
4403 int filenum, strindex, strnum, strlength;
4404 prvm_stringbuffer_t *stringbuffer;
4406 VM_SAFEPARMCOUNTRANGE(2, 4, VM_buf_writefile);
4409 filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
4410 if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
4412 VM_Warning(prog, "VM_buf_writefile: invalid file handle %i used in %s\n", filenum, prog->name);
4415 if (prog->openfiles[filenum] == NULL)
4417 VM_Warning(prog, "VM_buf_writefile: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
4421 // get string buffer
4422 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM1));
4425 VM_Warning(prog, "VM_buf_writefile: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), prog->name);
4426 PRVM_G_FLOAT(OFS_RETURN) = 0;
4430 // get start and end parms
4433 strindex = (int)PRVM_G_FLOAT(OFS_PARM2);
4434 strnum = (int)PRVM_G_FLOAT(OFS_PARM3);
4436 else if (prog->argc > 2)
4438 strindex = (int)PRVM_G_FLOAT(OFS_PARM2);
4439 strnum = stringbuffer->num_strings - strindex;
4444 strnum = stringbuffer->num_strings;
4446 if (strindex < 0 || strindex >= stringbuffer->num_strings)
4448 VM_Warning(prog, "VM_buf_writefile: wrong start string index %i used in %s\n", strindex, prog->name);
4449 PRVM_G_FLOAT(OFS_RETURN) = 0;
4454 VM_Warning(prog, "VM_buf_writefile: wrong strings count %i used in %s\n", strnum, prog->name);
4455 PRVM_G_FLOAT(OFS_RETURN) = 0;
4460 while(strindex < stringbuffer->num_strings && strnum)
4462 if (stringbuffer->strings[strindex])
4464 if ((strlength = (int)strlen(stringbuffer->strings[strindex])))
4465 FS_Write(prog->openfiles[filenum], stringbuffer->strings[strindex], strlength);
4466 FS_Write(prog->openfiles[filenum], "\n", 1);
4472 PRVM_G_FLOAT(OFS_RETURN) = 1;
4475 #define MATCH_AUTO 0
4476 #define MATCH_WHOLE 1
4477 #define MATCH_LEFT 2
4478 #define MATCH_RIGHT 3
4479 #define MATCH_MIDDLE 4
4480 #define MATCH_PATTERN 5
4482 static const char *detect_match_rule(char *pattern, int *matchrule)
4487 patternlength = (int)strlen(pattern);
4488 ppos = strchr(pattern, '*');
4489 qpos = strchr(pattern, '?');
4493 *matchrule = MATCH_PATTERN;
4496 // has * - left, mid, right or pattern
4499 // starts with * - may be right/mid or pattern
4500 if ((ppos - pattern) == 0)
4502 ppos = strchr(pattern+1, '*');
4506 *matchrule = MATCH_RIGHT;
4510 if ((ppos - pattern) == patternlength)
4512 *matchrule = MATCH_MIDDLE;
4517 *matchrule = MATCH_PATTERN;
4520 // end with * - left
4521 if ((ppos - pattern) == patternlength)
4523 *matchrule = MATCH_LEFT;
4528 *matchrule = MATCH_PATTERN;
4531 // have no wildcards - whole string
4532 *matchrule = MATCH_WHOLE;
4536 // todo: support UTF8
4537 static qbool match_rule(const char *string, int max_string, const char *pattern, int patternlength, int rule)
4542 return !strncmp(string, pattern, max_string) ? true : false;
4544 return !strncmp(string, pattern, patternlength) ? true : false;
4547 mid = strstr(string, pattern);
4548 return mid && !*(mid+patternlength);
4551 return strstr(string, pattern) ? true : false;
4553 return matchpattern_with_separator(string, pattern, false, "", false) ? true : false;
4557 ========================
4559 find an index of bufstring matching rule
4560 float bufstr_find(float bufhandle, string match, float matchrule, float startpos, float step) = #468;
4561 ========================
4564 void VM_bufstr_find(prvm_prog_t *prog)
4566 prvm_stringbuffer_t *stringbuffer;
4567 char string[VM_TEMPSTRING_MAXSIZE];
4568 int matchrule, matchlen, i, step;
4571 VM_SAFEPARMCOUNTRANGE(3, 5, VM_bufstr_find);
4573 PRVM_G_FLOAT(OFS_RETURN) = -1;
4575 // get string buffer
4576 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4579 VM_Warning(prog, "VM_bufstr_find: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4584 matchrule = (int)PRVM_G_FLOAT(OFS_PARM2);
4585 if (matchrule < 0 || matchrule > 5)
4587 VM_Warning(prog, "VM_bufstr_find: invalid match rule %i in %s\n", matchrule, prog->name);
4591 match = PRVM_G_STRING(OFS_PARM1);
4594 dp_strlcpy(string, PRVM_G_STRING(OFS_PARM1), sizeof(string));
4595 match = detect_match_rule(string, &matchrule);
4597 matchlen = (int)strlen(match);
4600 i = (prog->argc > 3) ? (int)PRVM_G_FLOAT(OFS_PARM3) : 0;
4601 step = (prog->argc > 4) ? (int)PRVM_G_FLOAT(OFS_PARM4) : 1;
4602 while(i < stringbuffer->num_strings)
4604 if (stringbuffer->strings[i] && match_rule(stringbuffer->strings[i], VM_TEMPSTRING_MAXSIZE, match, matchlen, matchrule))
4606 PRVM_G_FLOAT(OFS_RETURN) = i;
4614 ========================
4616 float matchpattern(string s, string pattern, float matchrule, float startpos) = #468;
4617 ========================
4619 void VM_matchpattern(prvm_prog_t *prog)
4621 const char *s, *match;
4622 char string[VM_TEMPSTRING_MAXSIZE];
4625 VM_SAFEPARMCOUNTRANGE(2, 4, VM_matchpattern);
4627 s = PRVM_G_STRING(OFS_PARM0);
4630 matchrule = (int)PRVM_G_FLOAT(OFS_PARM2);
4631 if (matchrule < 0 || matchrule > 5)
4633 VM_Warning(prog, "VM_matchpattern: invalid match rule %i in %s\n", matchrule, prog->name);
4637 match = PRVM_G_STRING(OFS_PARM1);
4640 dp_strlcpy(string, PRVM_G_STRING(OFS_PARM1), sizeof(string));
4641 match = detect_match_rule(string, &matchrule);
4645 l = (int)strlen(match);
4647 s += max(0, min((unsigned int)PRVM_G_FLOAT(OFS_PARM3), strlen(s)-1));
4650 PRVM_G_FLOAT(OFS_RETURN) = match_rule(s, VM_TEMPSTRING_MAXSIZE, match, l, matchrule);
4654 ========================
4656 ========================
4659 void VM_buf_cvarlist(prvm_prog_t *prog)
4662 const char *partial, *antipartial;
4663 size_t len, antilen;
4665 qbool ispattern, antiispattern;
4667 prvm_stringbuffer_t *stringbuffer;
4668 VM_SAFEPARMCOUNTRANGE(2, 3, VM_buf_cvarlist);
4670 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4673 VM_Warning(prog, "VM_bufstr_free: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4677 partial = PRVM_G_STRING(OFS_PARM1);
4681 len = strlen(partial);
4684 antipartial = PRVM_G_STRING(OFS_PARM2);
4690 antilen = strlen(antipartial);
4692 for (n = 0;n < stringbuffer->num_strings;n++)
4693 if (stringbuffer->strings[n])
4694 Mem_Free(stringbuffer->strings[n]);
4695 if (stringbuffer->strings)
4696 Mem_Free(stringbuffer->strings);
4697 stringbuffer->strings = NULL;
4699 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
4700 antiispattern = antipartial && (strchr(antipartial, '*') || strchr(antipartial, '?'));
4703 for(cvar = prog->console_cmd->cvars->vars; cvar; cvar = cvar->next)
4705 if(len && (ispattern ? !matchpattern_with_separator(cvar->name, partial, false, "", false) : strncmp(partial, cvar->name, len)))
4708 if(antilen && (antiispattern ? matchpattern_with_separator(cvar->name, antipartial, false, "", false) : !strncmp(antipartial, cvar->name, antilen)))
4714 stringbuffer->max_strings = stringbuffer->num_strings = n;
4715 if (stringbuffer->max_strings)
4716 stringbuffer->strings = (char **)Mem_Alloc(prog->progs_mempool, sizeof(stringbuffer->strings[0]) * stringbuffer->max_strings);
4719 for(cvar = prog->console_cmd->cvars->vars; cvar; cvar = cvar->next)
4721 if(len && (ispattern ? !matchpattern_with_separator(cvar->name, partial, false, "", false) : strncmp(partial, cvar->name, len)))
4724 if(antilen && (antiispattern ? matchpattern_with_separator(cvar->name, antipartial, false, "", false) : !strncmp(antipartial, cvar->name, antilen)))
4727 alloclen = strlen(cvar->name) + 1;
4728 stringbuffer->strings[n] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
4729 memcpy(stringbuffer->strings[n], cvar->name, alloclen);
4744 This was a major timewaster in progs, so it was converted to C
4747 void VM_changeyaw (prvm_prog_t *prog)
4750 float ideal, current, move, speed;
4752 // this is called (VERY HACKISHLY) by VM_SV_MoveToGoal, so it can not use any
4753 // parameters because they are the parameters to VM_SV_MoveToGoal, not this
4754 //VM_SAFEPARMCOUNT(0, VM_changeyaw);
4756 ent = PRVM_PROG_TO_EDICT(PRVM_gameglobaledict(self));
4757 if (ent == prog->edicts)
4759 VM_Warning(prog, "changeyaw: can not modify world entity\n");
4764 VM_Warning(prog, "changeyaw: can not modify free entity\n");
4767 current = PRVM_gameedictvector(ent, angles)[1];
4768 current = ANGLEMOD(current);
4769 ideal = PRVM_gameedictfloat(ent, ideal_yaw);
4770 speed = PRVM_gameedictfloat(ent, yaw_speed);
4772 if (current == ideal)
4774 move = ideal - current;
4775 if (ideal > current)
4797 PRVM_gameedictvector(ent, angles)[1] = ANGLEMOD(current);
4805 void VM_changepitch (prvm_prog_t *prog)
4808 float ideal, current, move, speed;
4810 VM_SAFEPARMCOUNT(1, VM_changepitch);
4812 ent = PRVM_G_EDICT(OFS_PARM0);
4813 if (ent == prog->edicts)
4815 VM_Warning(prog, "changepitch: can not modify world entity\n");
4820 VM_Warning(prog, "changepitch: can not modify free entity\n");
4823 current = PRVM_gameedictvector(ent, angles)[0];
4824 current = ANGLEMOD(current);
4825 ideal = PRVM_gameedictfloat(ent, idealpitch);
4826 speed = PRVM_gameedictfloat(ent, pitch_speed);
4828 if (current == ideal)
4830 move = ideal - current;
4831 if (ideal > current)
4853 PRVM_gameedictvector(ent, angles)[0] = ANGLEMOD(current);
4857 void VM_uncolorstring (prvm_prog_t *prog)
4859 char szNewString[VM_TEMPSTRING_MAXSIZE];
4860 size_t szNewString_len;
4861 const char *szString;
4864 VM_SAFEPARMCOUNT(1, VM_uncolorstring);
4865 szString = PRVM_G_STRING(OFS_PARM0);
4866 szNewString_len = COM_StringDecolorize(szString, 0, szNewString, sizeof(szNewString), true);
4867 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString, szNewString_len);
4870 // #221 float(string str, string sub[, float startpos]) strstrofs (FTE_STRINGS)
4871 //strstr, without generating a new string. Use in conjunction with FRIK_FILE's substring for more similar strstr.
4872 void VM_strstrofs (prvm_prog_t *prog)
4874 const char *instr, *match;
4876 VM_SAFEPARMCOUNTRANGE(2, 3, VM_strstrofs);
4877 instr = PRVM_G_STRING(OFS_PARM0);
4878 match = PRVM_G_STRING(OFS_PARM1);
4879 firstofs = (prog->argc > 2)?(int)PRVM_G_FLOAT(OFS_PARM2):0;
4880 firstofs = (int)u8_bytelen(instr, firstofs);
4882 if (firstofs && (firstofs < 0 || firstofs > (int)strlen(instr)))
4884 PRVM_G_FLOAT(OFS_RETURN) = -1;
4888 match = strstr(instr+firstofs, match);
4890 PRVM_G_FLOAT(OFS_RETURN) = -1;
4892 PRVM_G_FLOAT(OFS_RETURN) = u8_strnlen(instr, match-instr);
4895 //#222 string(string s, float index) str2chr (FTE_STRINGS)
4896 void VM_str2chr (prvm_prog_t *prog)
4901 VM_SAFEPARMCOUNT(2, VM_str2chr);
4902 s = PRVM_G_STRING(OFS_PARM0);
4903 index = (int)u8_bytelen(s, (int)PRVM_G_FLOAT(OFS_PARM1));
4905 if((unsigned)index < strlen(s))
4907 if (utf8_enable.integer)
4908 ch = u8_getchar_noendptr(s + index);
4910 ch = (unsigned char)s[index];
4911 PRVM_G_FLOAT(OFS_RETURN) = ch;
4914 PRVM_G_FLOAT(OFS_RETURN) = 0;
4917 //#223 string(float c, ...) chr2str (FTE_STRINGS)
4918 void VM_chr2str (prvm_prog_t *prog)
4923 VM_SAFEPARMCOUNTRANGE(0, 8, VM_chr2str);
4924 for(i = 0;i < prog->argc && i < (int)sizeof(t) - 1;i++)
4925 t[i] = (unsigned char)PRVM_G_FLOAT(OFS_PARM0+i*3);
4927 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, t);
4933 VM_SAFEPARMCOUNTRANGE(0, 8, VM_chr2str);
4934 for(i = 0; i < prog->argc && len < sizeof(t)-1; ++i)
4935 len += u8_fromchar((Uchar)PRVM_G_FLOAT(OFS_PARM0+i*3), t + len, sizeof(t)-1);
4937 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, t, len);
4940 static int chrconv_number(int i, int base, int conv)
4965 static int chrconv_punct(int i, int base, int conv)
4983 static int chrchar_alpha(int i, int basec, int baset, int convc, int convt, int charnum)
4985 //convert case and colour seperatly...
5002 baset = 128*((charnum&1) == (convt-5));
5018 return i + basec + baset;
5020 // #224 string(float ccase, float calpha, float cnum, string s, ...) strconv (FTE_STRINGS)
5021 //bulk convert a string. change case or colouring.
5022 void VM_strconv (prvm_prog_t *prog)
5024 int ccase, redalpha, rednum;
5027 unsigned char resbuf[VM_TEMPSTRING_MAXSIZE];
5028 unsigned char *result = resbuf;
5030 VM_SAFEPARMCOUNTRANGE(3, 8, VM_strconv);
5032 ccase = (int) PRVM_G_FLOAT(OFS_PARM0); //0 same, 1 lower, 2 upper
5033 redalpha = (int) PRVM_G_FLOAT(OFS_PARM1); //0 same, 1 white, 2 red, 5 alternate, 6 alternate-alternate
5034 rednum = (int) PRVM_G_FLOAT(OFS_PARM2); //0 same, 1 white, 2 red, 3 redspecial, 4 whitespecial, 5 alternate, 6 alternate-alternate
5035 resbuf_len = VM_VarString(prog, 3, (char *) resbuf, sizeof(resbuf));
5037 for (i = 0; i < resbuf_len; i++, result++) //should this be done backwards?
5039 if (*result >= '0' && *result <= '9') //normal numbers...
5040 *result = chrconv_number(*result, '0', rednum);
5041 else if (*result >= '0'+128 && *result <= '9'+128)
5042 *result = chrconv_number(*result, '0'+128, rednum);
5043 else if (*result >= '0'+128-30 && *result <= '9'+128-30)
5044 *result = chrconv_number(*result, '0'+128-30, rednum);
5045 else if (*result >= '0'-30 && *result <= '9'-30)
5046 *result = chrconv_number(*result, '0'-30, rednum);
5048 else if (*result >= 'a' && *result <= 'z') //normal numbers...
5049 *result = chrchar_alpha(*result, 'a', 0, ccase, redalpha, i);
5050 else if (*result >= 'A' && *result <= 'Z') //normal numbers...
5051 *result = chrchar_alpha(*result, 'A', 0, ccase, redalpha, i);
5052 else if (*result >= 'a'+128 && *result <= 'z'+128) //normal numbers...
5053 *result = chrchar_alpha(*result, 'a', 128, ccase, redalpha, i);
5054 else if (*result >= 'A'+128 && *result <= 'Z'+128) //normal numbers...
5055 *result = chrchar_alpha(*result, 'A', 128, ccase, redalpha, i);
5057 else if ((*result & 127) < 16 || !redalpha) //special chars..
5059 else if (*result < 128)
5060 *result = chrconv_punct(*result, 0, redalpha);
5062 *result = chrconv_punct(*result, 128, redalpha);
5066 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, (char *)resbuf, result - resbuf);
5069 // #225 string(float chars, string s, ...) strpad (FTE_STRINGS)
5070 void VM_strpad (prvm_prog_t *prog)
5072 char src[VM_TEMPSTRING_MAXSIZE];
5073 char destbuf[VM_TEMPSTRING_MAXSIZE];
5077 VM_SAFEPARMCOUNTRANGE(1, 8, VM_strpad);
5078 pad = (int) PRVM_G_FLOAT(OFS_PARM0);
5079 VM_VarString(prog, 1, src, sizeof(src));
5081 // note: < 0 = left padding, > 0 = right padding,
5082 // this is reverse logic of printf!
5083 destbuf_len = dpsnprintf(destbuf, sizeof(destbuf), "%*s", -pad, src);
5085 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, destbuf, destbuf_len);
5088 // #226 string(string info, string key, string value, ...) infoadd (FTE_STRINGS)
5089 //uses qw style \key\value strings
5090 void VM_infoadd (prvm_prog_t *prog)
5092 const char *info, *key;
5093 char value[VM_TEMPSTRING_MAXSIZE];
5094 char temp[VM_TEMPSTRING_MAXSIZE];
5096 VM_SAFEPARMCOUNTRANGE(2, 8, VM_infoadd);
5097 info = PRVM_G_STRING(OFS_PARM0);
5098 key = PRVM_G_STRING(OFS_PARM1);
5099 VM_VarString(prog, 2, value, sizeof(value));
5101 dp_strlcpy(temp, info, VM_TEMPSTRING_MAXSIZE);
5103 InfoString_SetValue(temp, VM_TEMPSTRING_MAXSIZE, key, value);
5105 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, temp, strlen(temp));
5108 // #227 string(string info, string key) infoget (FTE_STRINGS)
5109 //uses qw style \key\value strings
5110 void VM_infoget (prvm_prog_t *prog)
5114 char value[VM_TEMPSTRING_MAXSIZE];
5116 VM_SAFEPARMCOUNT(2, VM_infoget);
5117 info = PRVM_G_STRING(OFS_PARM0);
5118 key = PRVM_G_STRING(OFS_PARM1);
5120 InfoString_GetValue(info, key, value, VM_TEMPSTRING_MAXSIZE);
5122 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, value, strlen(value));
5125 //#228 float(string s1, string s2, float len) strncmp (FTE_STRINGS)
5126 // also float(string s1, string s2) strcmp (FRIK_FILE)
5127 void VM_strncmp (prvm_prog_t *prog)
5129 const char *s1, *s2;
5130 VM_SAFEPARMCOUNTRANGE(2, 3, VM_strncmp);
5131 s1 = PRVM_G_STRING(OFS_PARM0);
5132 s2 = PRVM_G_STRING(OFS_PARM1);
5135 PRVM_G_FLOAT(OFS_RETURN) = strncmp(s1, s2, (size_t)PRVM_G_FLOAT(OFS_PARM2));
5139 PRVM_G_FLOAT(OFS_RETURN) = strcmp(s1, s2);
5143 // #229 float(string s1, string s2) strcasecmp (FTE_STRINGS)
5144 // #230 float(string s1, string s2, float len) strncasecmp (FTE_STRINGS)
5145 void VM_strncasecmp (prvm_prog_t *prog)
5147 const char *s1, *s2;
5148 VM_SAFEPARMCOUNTRANGE(2, 3, VM_strncasecmp);
5149 s1 = PRVM_G_STRING(OFS_PARM0);
5150 s2 = PRVM_G_STRING(OFS_PARM1);
5153 PRVM_G_FLOAT(OFS_RETURN) = strncasecmp(s1, s2, (size_t)PRVM_G_FLOAT(OFS_PARM2));
5157 PRVM_G_FLOAT(OFS_RETURN) = strcasecmp(s1, s2);
5161 // #494 float(float caseinsensitive, string s, ...) crc16
5162 void VM_crc16(prvm_prog_t *prog)
5165 char s[VM_TEMPSTRING_MAXSIZE];
5168 VM_SAFEPARMCOUNTRANGE(2, 8, VM_crc16);
5169 insensitive = PRVM_G_FLOAT(OFS_PARM0);
5170 slen = VM_VarString(prog, 1, s, sizeof(s));
5171 PRVM_G_FLOAT(OFS_RETURN) = (unsigned short) ((insensitive ? CRC_Block_CaseInsensitive : CRC_Block) ((unsigned char *) s, slen));
5174 // #639 float(string digest, string data, ...) digest_hex
5175 void VM_digest_hex(prvm_prog_t *prog)
5183 char s[VM_TEMPSTRING_MAXSIZE];
5186 VM_SAFEPARMCOUNTRANGE(2, 8, VM_digest_hex);
5187 digest = PRVM_G_STRING(OFS_PARM0);
5190 len = VM_VarString(prog, 1, s, sizeof(s));
5194 if(!strcmp(digest, "MD4"))
5197 mdfour((unsigned char *) out, (unsigned char *) s, len);
5199 else if(!strcmp(digest, "SHA256") && Crypto_Available())
5202 sha256((unsigned char *) out, (unsigned char *) s, len);
5204 // no warning needed on mismatch - we return string_null to QC
5209 static const char *hexmap = "0123456789abcdef";
5210 for(i = 0; i < outlen; ++i)
5212 outhex[2*i] = hexmap[(out[i] >> 4) & 15];
5213 outhex[2*i+1] = hexmap[(out[i] >> 0) & 15];
5216 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outhex, 2*i);
5219 PRVM_G_INT(OFS_RETURN) = 0;
5222 void VM_wasfreed (prvm_prog_t *prog)
5224 VM_SAFEPARMCOUNT(1, VM_wasfreed);
5225 PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_EDICT(OFS_PARM0)->free;
5228 void VM_SetTraceGlobals(prvm_prog_t *prog, const trace_t *trace)
5230 PRVM_gameglobalfloat(trace_allsolid) = trace->allsolid;
5231 PRVM_gameglobalfloat(trace_startsolid) = trace->startsolid;
5232 PRVM_gameglobalfloat(trace_fraction) = trace->fraction;
5233 PRVM_gameglobalfloat(trace_inwater) = trace->inwater;
5234 PRVM_gameglobalfloat(trace_inopen) = trace->inopen;
5235 VectorCopy(trace->endpos, PRVM_gameglobalvector(trace_endpos));
5236 VectorCopy(trace->plane.normal, PRVM_gameglobalvector(trace_plane_normal));
5237 PRVM_gameglobalfloat(trace_plane_dist) = trace->plane.dist;
5238 PRVM_gameglobaledict(trace_ent) = PRVM_EDICT_TO_PROG(trace->ent ? trace->ent : prog->edicts);
5239 PRVM_gameglobalfloat(trace_dpstartcontents) = trace->startsupercontents;
5240 PRVM_gameglobalfloat(trace_dphitcontents) = trace->hitsupercontents;
5241 PRVM_gameglobalfloat(trace_dphitq3surfaceflags) = trace->hitq3surfaceflags;
5242 PRVM_gameglobalstring(trace_dphittexturename) = trace->hittexture ? PRVM_SetTempString(prog, trace->hittexture->name, strlen(trace->hittexture->name)) : 0;
5245 void VM_ClearTraceGlobals(prvm_prog_t *prog)
5247 // clean up all trace globals when leaving the VM (anti-triggerbot safeguard)
5248 PRVM_gameglobalfloat(trace_allsolid) = 0;
5249 PRVM_gameglobalfloat(trace_startsolid) = 0;
5250 PRVM_gameglobalfloat(trace_fraction) = 0;
5251 PRVM_gameglobalfloat(trace_inwater) = 0;
5252 PRVM_gameglobalfloat(trace_inopen) = 0;
5253 VectorClear(PRVM_gameglobalvector(trace_endpos));
5254 VectorClear(PRVM_gameglobalvector(trace_plane_normal));
5255 PRVM_gameglobalfloat(trace_plane_dist) = 0;
5256 PRVM_gameglobaledict(trace_ent) = PRVM_EDICT_TO_PROG(prog->edicts);
5257 PRVM_gameglobalfloat(trace_dpstartcontents) = 0;
5258 PRVM_gameglobalfloat(trace_dphitcontents) = 0;
5259 PRVM_gameglobalfloat(trace_dphitq3surfaceflags) = 0;
5260 PRVM_gameglobalstring(trace_dphittexturename) = 0;
5265 void VM_Cmd_Init(prvm_prog_t *prog)
5267 // only init the stuff for the current prog
5268 VM_Files_Init(prog);
5269 VM_Search_Init(prog);
5272 static void animatemodel_reset(prvm_prog_t *prog);
5274 void VM_Cmd_Reset(prvm_prog_t *prog)
5276 CL_PurgeOwner( MENUOWNER );
5277 VM_Search_Reset(prog);
5278 VM_Files_CloseAll(prog);
5279 animatemodel_reset(prog);
5282 // #510 string(string input, ...) uri_escape (DP_QC_URI_ESCAPE)
5283 // does URI escaping on a string (replace evil stuff by %AB escapes)
5284 void VM_uri_escape (prvm_prog_t *prog)
5286 char src[VM_TEMPSTRING_MAXSIZE];
5287 char dest[VM_TEMPSTRING_MAXSIZE];
5289 static const char *hex = "0123456789ABCDEF";
5291 VM_SAFEPARMCOUNTRANGE(1, 8, VM_uri_escape);
5292 VM_VarString(prog, 0, src, sizeof(src));
5294 for(p = src, q = dest; *p && q < dest + sizeof(dest) - 3; ++p)
5296 if((*p >= 'A' && *p <= 'Z')
5297 || (*p >= 'a' && *p <= 'z')
5298 || (*p >= '0' && *p <= '9')
5299 || (*p == '-') || (*p == '_') || (*p == '.')
5300 || (*p == '!') || (*p == '~')
5301 || (*p == '\'') || (*p == '(') || (*p == ')'))
5306 *q++ = hex[(*(unsigned char *)p >> 4) & 0xF];
5307 *q++ = hex[ *(unsigned char *)p & 0xF];
5312 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, dest, q - dest);
5315 // #510 string(string input, ...) uri_unescape (DP_QC_URI_ESCAPE)
5316 // does URI unescaping on a string (get back the evil stuff)
5317 void VM_uri_unescape (prvm_prog_t *prog)
5319 char src[VM_TEMPSTRING_MAXSIZE];
5320 char dest[VM_TEMPSTRING_MAXSIZE];
5324 VM_SAFEPARMCOUNTRANGE(1, 8, VM_uri_unescape);
5325 VM_VarString(prog, 0, src, sizeof(src));
5327 for(p = src, q = dest; *p; ) // no need to check size, because unescape can't expand
5331 if(p[1] >= '0' && p[1] <= '9')
5333 else if(p[1] >= 'a' && p[1] <= 'f')
5334 hi = p[1] - 'a' + 10;
5335 else if(p[1] >= 'A' && p[1] <= 'F')
5336 hi = p[1] - 'A' + 10;
5339 if(p[2] >= '0' && p[2] <= '9')
5341 else if(p[2] >= 'a' && p[2] <= 'f')
5342 lo = p[2] - 'a' + 10;
5343 else if(p[2] >= 'A' && p[2] <= 'F')
5344 lo = p[2] - 'A' + 10;
5347 if(hi != 0 || lo != 0) // don't unescape NUL bytes
5348 *q++ = (char) (hi * 0x10 + lo);
5359 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, dest, q - dest);
5362 // #502 string(string filename) whichpack (DP_QC_WHICHPACK)
5363 // returns the name of the pack containing a file, or "" if it is not in any pack (but local or non-existant)
5364 void VM_whichpack (prvm_prog_t *prog)
5366 const char *fn, *pack;
5368 VM_SAFEPARMCOUNT(1, VM_whichpack);
5369 fn = PRVM_G_STRING(OFS_PARM0);
5370 pack = FS_WhichPack(fn);
5372 PRVM_G_INT(OFS_RETURN) = pack ? PRVM_SetTempString(prog, pack, strlen(pack)) : 0;
5380 char buffer[MAX_INPUTLINE];
5382 unsigned char *postdata; // free when uri_to_prog_t is freed
5384 char *sigdata; // free when uri_to_prog_t is freed
5389 static void uri_to_string_callback(int status, size_t length_received, unsigned char *buffer, void *cbdata)
5392 uri_to_prog_t *handle = (uri_to_prog_t *) cbdata;
5394 prog = handle->prog;
5397 // curl reply came too late... so just drop it
5398 if(handle->postdata)
5399 Z_Free(handle->postdata);
5401 Z_Free(handle->sigdata);
5406 if((prog->starttime == handle->starttime) && (PRVM_allfunction(URI_Get_Callback)))
5408 if(length_received >= sizeof(handle->buffer))
5409 length_received = sizeof(handle->buffer) - 1;
5410 handle->buffer[length_received] = '\0';
5412 PRVM_G_FLOAT(OFS_PARM0) = handle->id;
5413 PRVM_G_FLOAT(OFS_PARM1) = status;
5414 PRVM_G_INT(OFS_PARM2) = PRVM_SetTempString(prog, handle->buffer, length_received);
5415 prog->ExecuteProgram(prog, PRVM_allfunction(URI_Get_Callback), "QC function URI_Get_Callback is missing");
5418 if(handle->postdata)
5419 Z_Free(handle->postdata);
5421 Z_Free(handle->sigdata);
5425 // 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
5426 // 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
5427 void VM_uri_get (prvm_prog_t *prog)
5432 uri_to_prog_t *handle;
5433 const char *posttype = NULL;
5434 const char *postseparator = NULL;
5435 int poststringbuffer = -1;
5437 const char *query_string = NULL;
5440 if(!PRVM_allfunction(URI_Get_Callback))
5441 prog->error_cmd("uri_get called by %s without URI_Get_Callback defined", prog->name);
5443 VM_SAFEPARMCOUNTRANGE(2, 6, VM_uri_get);
5445 url = PRVM_G_STRING(OFS_PARM0);
5446 id = PRVM_G_FLOAT(OFS_PARM1);
5448 posttype = PRVM_G_STRING(OFS_PARM2);
5450 postseparator = PRVM_G_STRING(OFS_PARM3);
5452 poststringbuffer = PRVM_G_FLOAT(OFS_PARM4);
5454 postkeyid = PRVM_G_FLOAT(OFS_PARM5);
5455 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!
5457 query_string = strchr(url, '?');
5460 lq = query_string ? strlen(query_string) : 0;
5462 handle->prog = prog;
5463 handle->starttime = prog->starttime;
5465 if(postseparator && posttype && *posttype)
5467 size_t l = strlen(postseparator);
5468 if(poststringbuffer >= 0)
5473 prvm_stringbuffer_t *stringbuffer;
5474 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, poststringbuffer);
5477 VM_Warning(prog, "uri_get: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
5481 for(i = 0;i < stringbuffer->num_strings;i++)
5485 if(stringbuffer->strings[i])
5486 ltotal += strlen(stringbuffer->strings[i]);
5488 handle->postdata = (unsigned char *)Z_Malloc(ltotal + 1 + lq);
5489 handle->postlen = ltotal;
5491 for(i = 0;i < stringbuffer->num_strings;i++)
5495 memcpy(handle->postdata + ltotal, postseparator, l);
5498 if(stringbuffer->strings[i])
5500 memcpy(handle->postdata + ltotal, stringbuffer->strings[i], strlen(stringbuffer->strings[i]));
5501 ltotal += strlen(stringbuffer->strings[i]);
5504 if(ltotal != handle->postlen)
5505 prog->error_cmd("%s: string buffer content size mismatch, possible overrun", prog->name);
5509 handle->postdata = (unsigned char *)Z_Malloc(l + 1 + lq);
5510 handle->postlen = l;
5511 memcpy(handle->postdata, postseparator, l);
5513 handle->postdata[handle->postlen] = 0;
5515 memcpy(handle->postdata + handle->postlen + 1, query_string, lq);
5518 // POST: we sign postdata \0 query string
5520 handle->sigdata = (char *)Z_Malloc(8192);
5521 dp_strlcpy(handle->sigdata, "X-D0-Blind-ID-Detached-Signature: ", 8192);
5522 l = strlen(handle->sigdata);
5523 handle->siglen = Crypto_SignDataDetached(handle->postdata, handle->postlen + 1 + lq, postkeyid, handle->sigdata + l, 8192 - l);
5526 Z_Free(handle->sigdata);
5527 handle->sigdata = NULL;
5530 ll = base64_encode((unsigned char *) (handle->sigdata + l), handle->siglen, 8192 - l - 1);
5533 Z_Free(handle->sigdata);
5534 handle->sigdata = NULL;
5537 handle->siglen = l + ll;
5538 handle->sigdata[handle->siglen] = 0;
5541 dp_strlcpy(handle->posttype, posttype, sizeof(handle->posttype));
5542 ret = Curl_Begin_ToMemory_POST(url, handle->sigdata, 0, handle->posttype, handle->postdata, handle->postlen, (unsigned char *) handle->buffer, sizeof(handle->buffer), uri_to_string_callback, handle);
5546 if(postkeyid >= 0 && query_string)
5548 // GET: we sign JUST the query string
5550 handle->sigdata = (char *)Z_Malloc(8192);
5551 dp_strlcpy(handle->sigdata, "X-D0-Blind-ID-Detached-Signature: ", 8192);
5552 l = strlen(handle->sigdata);
5553 handle->siglen = Crypto_SignDataDetached(query_string, lq, postkeyid, handle->sigdata + l, 8192 - l);
5556 Z_Free(handle->sigdata);
5557 handle->sigdata = NULL;
5560 ll = base64_encode((unsigned char *) (handle->sigdata + l), handle->siglen, 8192 - l - 1);
5563 Z_Free(handle->sigdata);
5564 handle->sigdata = NULL;
5567 handle->siglen = l + ll;
5568 handle->sigdata[handle->siglen] = 0;
5571 handle->postdata = NULL;
5572 handle->postlen = 0;
5573 ret = Curl_Begin_ToMemory_POST(url, handle->sigdata, 0, NULL, NULL, 0, (unsigned char *) handle->buffer, sizeof(handle->buffer), uri_to_string_callback, handle);
5577 PRVM_G_INT(OFS_RETURN) = 1;
5581 if(handle->postdata)
5582 Z_Free(handle->postdata);
5584 Z_Free(handle->sigdata);
5586 PRVM_G_INT(OFS_RETURN) = 0;
5590 void VM_netaddress_resolve (prvm_prog_t *prog)
5593 char normalized[128];
5594 size_t normalized_len;
5596 lhnetaddress_t addr;
5598 VM_SAFEPARMCOUNTRANGE(1, 2, VM_netaddress_resolve);
5600 ip = PRVM_G_STRING(OFS_PARM0);
5603 port = (int) PRVM_G_FLOAT(OFS_PARM1);
5605 if(LHNETADDRESS_FromString(&addr, ip, port) && (normalized_len = LHNETADDRESS_ToString(&addr, normalized, sizeof(normalized), prog->argc > 1)))
5606 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, normalized, normalized_len);
5608 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
5611 //string(prvm_prog_t *prog) getextresponse = #624; // returns the next extResponse packet that was sent to this client
5612 void VM_CL_getextresponse (prvm_prog_t *prog)
5614 VM_SAFEPARMCOUNT(0,VM_argv);
5616 if (cl_net_extresponse_count <= 0)
5617 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
5621 --cl_net_extresponse_count;
5622 first = (cl_net_extresponse_last + NET_EXTRESPONSE_MAX - cl_net_extresponse_count) % NET_EXTRESPONSE_MAX;
5623 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, cl_net_extresponse[first], strlen(cl_net_extresponse[first]));
5627 void VM_SV_getextresponse (prvm_prog_t *prog)
5629 VM_SAFEPARMCOUNT(0,VM_argv);
5631 if (sv_net_extresponse_count <= 0)
5632 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
5636 --sv_net_extresponse_count;
5637 first = (sv_net_extresponse_last + NET_EXTRESPONSE_MAX - sv_net_extresponse_count) % NET_EXTRESPONSE_MAX;
5638 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, sv_net_extresponse[first], strlen(sv_net_extresponse[first]));
5642 // DP_QC_NUDGEOUTOFSOLID
5643 // float(entity ent) nudgeoutofsolid = #567;
5644 void VM_nudgeoutofsolid(prvm_prog_t *prog)
5648 VM_SAFEPARMCOUNTRANGE(1, 1, VM_nudgeoutofsolid);
5650 ent = PRVM_G_EDICT(OFS_PARM0);
5651 if (ent == prog->edicts)
5653 VM_Warning(prog, "nudgeoutofsolid: can not modify world entity\n");
5654 PRVM_G_FLOAT(OFS_RETURN) = 0;
5659 VM_Warning(prog, "nudgeoutofsolid: can not modify free entity\n");
5660 PRVM_G_FLOAT(OFS_RETURN) = 0;
5664 PRVM_G_FLOAT(OFS_RETURN) = PHYS_NudgeOutOfSolid(prog, ent);
5666 if (PRVM_G_FLOAT(OFS_RETURN) > 0)
5668 if (prog == SVVM_prog)
5670 else if (prog == CLVM_prog)
5673 Sys_Error("PHYS_NudgeOutOfSolid: cannot be called from %s VM\n", prog->name);
5679 Common functions between menu.dat and clsprogs
5683 //#349 float() isdemo
5684 void VM_CL_isdemo (prvm_prog_t *prog)
5686 VM_SAFEPARMCOUNT(0, VM_CL_isdemo);
5687 PRVM_G_FLOAT(OFS_RETURN) = cls.demoplayback;
5690 //#355 float() videoplaying
5691 void VM_CL_videoplaying (prvm_prog_t *prog)
5693 VM_SAFEPARMCOUNT(0, VM_CL_videoplaying);
5694 PRVM_G_FLOAT(OFS_RETURN) = cl_videoplaying;
5701 callfunction(...,string function_name)
5705 void VM_callfunction(prvm_prog_t *prog)
5710 VM_SAFEPARMCOUNTRANGE(1, 8, VM_callfunction);
5712 s = PRVM_G_STRING(OFS_PARM0+(prog->argc - 1)*3);
5714 VM_CheckEmptyString(prog, s);
5716 func = PRVM_ED_FindFunction(prog, s);
5719 prog->error_cmd("VM_callfunction: function %s not found !", s);
5720 else if (func->first_statement < 0)
5722 // negative statements are built in functions
5723 int builtinnumber = -func->first_statement;
5724 prog->xfunction->builtinsprofile++;
5725 if (builtinnumber < prog->numbuiltins && prog->builtins[builtinnumber])
5726 prog->builtins[builtinnumber](prog);
5728 prog->error_cmd("No such builtin #%i in %s; most likely cause: outdated engine build. Try updating!", builtinnumber, prog->name);
5730 else if(func - prog->functions > 0)
5733 prog->ExecuteProgram(prog, func - prog->functions,"");
5742 float isfunction(string function_name)
5745 void VM_isfunction(prvm_prog_t *prog)
5750 VM_SAFEPARMCOUNT(1, VM_isfunction);
5752 s = PRVM_G_STRING(OFS_PARM0);
5754 VM_CheckEmptyString(prog, s);
5756 func = PRVM_ED_FindFunction(prog, s);
5759 PRVM_G_FLOAT(OFS_RETURN) = false;
5761 PRVM_G_FLOAT(OFS_RETURN) = true;
5768 string sprintf(string format, ...)
5772 void VM_sprintf(prvm_prog_t *prog)
5775 char outbuf[MAX_INPUTLINE];
5776 char *o = outbuf, *end = outbuf + sizeof(outbuf), *err;
5779 int width, precision, thisarg, flags;
5783 static prvm_int_t dummyivec[3] = {0, 0, 0};
5784 static prvm_vec_t dummyvec[3] = {0, 0, 0};
5787 #define PRINTF_ALTERNATE 1
5788 #define PRINTF_ZEROPAD 2
5789 #define PRINTF_LEFT 4
5790 #define PRINTF_SPACEPOSITIVE 8
5791 #define PRINTF_SIGNPOSITIVE 16
5795 s = PRVM_G_STRING(OFS_PARM0);
5797 #define GETARG_FLOAT(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_FLOAT(OFS_PARM0 + 3 * (a))) : 0)
5798 #define GETARG_VECTOR(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_VECTOR(OFS_PARM0 + 3 * (a))) : dummyvec)
5799 #define GETARG_INT(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_INT(OFS_PARM0 + 3 * (a))) : 0)
5800 #define GETARG_INTVECTOR(a) (((a)>=1 && (a)<prog->argc) ? ((prvm_int_t*) PRVM_G_VECTOR(OFS_PARM0 + 3 * (a))) : dummyivec)
5801 #define GETARG_STRING(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_STRING(OFS_PARM0 + 3 * (a))) : "")
5816 // complete directive format:
5825 // is number following?
5826 if(*s >= '0' && *s <= '9')
5828 width = strtol(s, &err, 10);
5831 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
5844 flags |= PRINTF_ZEROPAD;
5846 width = -1; // it was just a flag
5858 case '#': flags |= PRINTF_ALTERNATE; break;
5859 case '0': flags |= PRINTF_ZEROPAD; break;
5860 case '-': flags |= PRINTF_LEFT; break;
5861 case ' ': flags |= PRINTF_SPACEPOSITIVE; break;
5862 case '+': flags |= PRINTF_SIGNPOSITIVE; break;
5872 if(*s >= '0' && *s <= '9')
5874 width = strtol(s, &err, 10);
5875 if(!err || *err != '$')
5877 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
5884 width = GETARG_FLOAT(width);
5887 flags |= PRINTF_LEFT;
5891 else if(*s >= '0' && *s <= '9')
5893 width = strtol(s, &err, 10);
5896 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
5902 flags |= PRINTF_LEFT;
5906 // otherwise width stays -1
5915 if(*s >= '0' && *s <= '9')
5917 precision = strtol(s, &err, 10);
5918 if(!err || *err != '$')
5920 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
5926 precision = argpos++;
5927 precision = GETARG_FLOAT(precision);
5929 else if(*s >= '0' && *s <= '9')
5931 precision = strtol(s, &err, 10);
5934 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
5941 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
5950 case 'h': isfloat = 1; break;
5951 case 'l': isfloat = 0; break;
5952 case 'L': isfloat = 0; break;
5963 // now s points to the final directive char and is no longer changed
5978 if(*s != 's' && *s != 'c')
5979 if(flags & PRINTF_ALTERNATE) *f++ = '#';
5980 if(flags & PRINTF_ZEROPAD) *f++ = '0';
5981 if(flags & PRINTF_LEFT) *f++ = '-';
5982 if(flags & PRINTF_SPACEPOSITIVE) *f++ = ' ';
5983 if(flags & PRINTF_SIGNPOSITIVE) *f++ = '+';
5990 if(*s == 'd' || *s == 'i' || *s == 'o' || *s == 'u' || *s == 'x' || *s == 'X')
5992 // make it use a good integer type
5993 for(p = INT_LOSSLESS_FORMAT_SIZE; *p; )
5999 if(width < 0) // not set
6005 if(precision < 0) // not set
6006 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? INT_LOSSLESS_FORMAT_CONVERT_S(GETARG_FLOAT(thisarg)) : INT_LOSSLESS_FORMAT_CONVERT_S(GETARG_INT(thisarg))));
6008 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? INT_LOSSLESS_FORMAT_CONVERT_S(GETARG_FLOAT(thisarg)) : INT_LOSSLESS_FORMAT_CONVERT_S(GETARG_INT(thisarg))));
6010 case 'o': case 'u': case 'x': case 'X':
6011 if(precision < 0) // not set
6012 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? INT_LOSSLESS_FORMAT_CONVERT_U(GETARG_FLOAT(thisarg)) : INT_LOSSLESS_FORMAT_CONVERT_U(GETARG_INT(thisarg))));
6014 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? INT_LOSSLESS_FORMAT_CONVERT_U(GETARG_FLOAT(thisarg)) : INT_LOSSLESS_FORMAT_CONVERT_U(GETARG_INT(thisarg))));
6016 case 'e': case 'E': case 'f': case 'F': case 'g': case 'G':
6017 if(precision < 0) // not set
6018 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? (double) GETARG_FLOAT(thisarg) : (double) GETARG_INT(thisarg)));
6020 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? (double) GETARG_FLOAT(thisarg) : (double) GETARG_INT(thisarg)));
6024 if(precision < 0) // not set
6025 o += dpsnprintf(o, end - o, va(vabuf, sizeof(vabuf), "%s %s %s", /* NESTED SPRINTF IS NESTED */ formatbuf, formatbuf, formatbuf),
6026 width, (isfloat ? (double) GETARG_VECTOR(thisarg)[0] : (double) GETARG_INTVECTOR(thisarg)[0]),
6027 width, (isfloat ? (double) GETARG_VECTOR(thisarg)[1] : (double) GETARG_INTVECTOR(thisarg)[1]),
6028 width, (isfloat ? (double) GETARG_VECTOR(thisarg)[2] : (double) GETARG_INTVECTOR(thisarg)[2])
6031 o += dpsnprintf(o, end - o, va(vabuf, sizeof(vabuf), "%s %s %s", /* NESTED SPRINTF IS NESTED */ formatbuf, formatbuf, formatbuf),
6032 width, precision, (isfloat ? (double) GETARG_VECTOR(thisarg)[0] : (double) GETARG_INTVECTOR(thisarg)[0]),
6033 width, precision, (isfloat ? (double) GETARG_VECTOR(thisarg)[1] : (double) GETARG_INTVECTOR(thisarg)[1]),
6034 width, precision, (isfloat ? (double) GETARG_VECTOR(thisarg)[2] : (double) GETARG_INTVECTOR(thisarg)[2])
6038 if(flags & PRINTF_ALTERNATE)
6040 if(precision < 0) // not set
6041 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg)));
6043 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg)));
6047 unsigned int c = (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg));
6049 const char *buf = u8_encodech(c, NULL, charbuf16);
6052 if(precision < 0) // not set
6053 precision = end - o - 1;
6054 o += u8_strpad(o, end - o, buf, (flags & PRINTF_LEFT) != 0, width, precision);
6057 //spike FIXME -- 'S' for quoted tokenize-safe-or-print escaping of strings so stuff can safely survive console commands.
6059 if(flags & PRINTF_ALTERNATE)
6061 if(precision < 0) // not set
6062 o += dpsnprintf(o, end - o, formatbuf, width, GETARG_STRING(thisarg));
6064 o += dpsnprintf(o, end - o, formatbuf, width, precision, GETARG_STRING(thisarg));
6068 if(precision < 0) // not set
6069 precision = end - o - 1;
6070 if(flags & PRINTF_SIGNPOSITIVE)
6071 o += u8_strpad(o, end - o, GETARG_STRING(thisarg), (flags & PRINTF_LEFT) != 0, width, precision);
6073 o += u8_strpad_colorcodes(o, end - o, GETARG_STRING(thisarg), (flags & PRINTF_LEFT) != 0, width, precision);
6077 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
6094 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outbuf, o - outbuf);
6100 static model_t *getmodel(prvm_prog_t *prog, prvm_edict_t *ed)
6102 if (prog == SVVM_prog)
6103 return SV_GetModelFromEdict(ed);
6104 else if (prog == CLVM_prog)
6105 return CL_GetModelFromEdict(ed);
6110 struct animatemodel_cache
6113 frameblend_t frameblend[MAX_FRAMEBLENDS];
6114 skeleton_t *skeleton_p;
6115 skeleton_t skeleton;
6116 float *data_vertex3f;
6117 float *data_svector3f;
6118 float *data_tvector3f;
6119 float *data_normal3f;
6121 float *buf_vertex3f;
6122 float *buf_svector3f;
6123 float *buf_tvector3f;
6124 float *buf_normal3f;
6127 static void animatemodel_reset(prvm_prog_t *prog)
6129 if (!prog->animatemodel_cache)
6131 if(prog->animatemodel_cache->buf_vertex3f) Mem_Free(prog->animatemodel_cache->buf_vertex3f);
6132 if(prog->animatemodel_cache->buf_svector3f) Mem_Free(prog->animatemodel_cache->buf_svector3f);
6133 if(prog->animatemodel_cache->buf_tvector3f) Mem_Free(prog->animatemodel_cache->buf_tvector3f);
6134 if(prog->animatemodel_cache->buf_normal3f) Mem_Free(prog->animatemodel_cache->buf_normal3f);
6135 Mem_Free(prog->animatemodel_cache);
6138 static void animatemodel(prvm_prog_t *prog, model_t *model, prvm_edict_t *ed)
6140 skeleton_t *skeleton;
6141 int skeletonindex = -1;
6143 struct animatemodel_cache *animatemodel_cache;
6144 if (!prog->animatemodel_cache)
6146 prog->animatemodel_cache = (struct animatemodel_cache *)Mem_Alloc(prog->progs_mempool, sizeof(struct animatemodel_cache));
6147 memset(prog->animatemodel_cache, 0, sizeof(struct animatemodel_cache));
6149 animatemodel_cache = prog->animatemodel_cache;
6150 if(!(model->surfmesh.isanimated && model->AnimateVertices))
6152 animatemodel_cache->data_vertex3f = model->surfmesh.data_vertex3f;
6153 animatemodel_cache->data_svector3f = model->surfmesh.data_svector3f;
6154 animatemodel_cache->data_tvector3f = model->surfmesh.data_tvector3f;
6155 animatemodel_cache->data_normal3f = model->surfmesh.data_normal3f;
6158 need |= (animatemodel_cache->model != model);
6159 VM_GenerateFrameGroupBlend(prog, ed->priv.server->framegroupblend, ed);
6160 VM_FrameBlendFromFrameGroupBlend(ed->priv.server->frameblend, ed->priv.server->framegroupblend, model, PRVM_serverglobalfloat(time));
6161 need |= (memcmp(&animatemodel_cache->frameblend, &ed->priv.server->frameblend, sizeof(ed->priv.server->frameblend))) != 0;
6162 skeletonindex = (int)PRVM_gameedictfloat(ed, skeletonindex) - 1;
6163 if (!(skeletonindex >= 0 && skeletonindex < MAX_EDICTS && (skeleton = prog->skeletons[skeletonindex]) && skeleton->model->num_bones == ed->priv.server->skeleton.model->num_bones))
6165 need |= (animatemodel_cache->skeleton_p != skeleton);
6167 need |= (memcmp(&animatemodel_cache->skeleton, skeleton, sizeof(ed->priv.server->skeleton))) != 0;
6170 if(model->surfmesh.num_vertices > animatemodel_cache->max_vertices)
6172 animatemodel_cache->max_vertices = model->surfmesh.num_vertices * 2;
6173 if(animatemodel_cache->buf_vertex3f) Mem_Free(animatemodel_cache->buf_vertex3f);
6174 if(animatemodel_cache->buf_svector3f) Mem_Free(animatemodel_cache->buf_svector3f);
6175 if(animatemodel_cache->buf_tvector3f) Mem_Free(animatemodel_cache->buf_tvector3f);
6176 if(animatemodel_cache->buf_normal3f) Mem_Free(animatemodel_cache->buf_normal3f);
6177 animatemodel_cache->buf_vertex3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache->max_vertices);
6178 animatemodel_cache->buf_svector3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache->max_vertices);
6179 animatemodel_cache->buf_tvector3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache->max_vertices);
6180 animatemodel_cache->buf_normal3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache->max_vertices);
6182 animatemodel_cache->data_vertex3f = animatemodel_cache->buf_vertex3f;
6183 animatemodel_cache->data_svector3f = animatemodel_cache->buf_svector3f;
6184 animatemodel_cache->data_tvector3f = animatemodel_cache->buf_tvector3f;
6185 animatemodel_cache->data_normal3f = animatemodel_cache->buf_normal3f;
6186 VM_UpdateEdictSkeleton(prog, ed, model, ed->priv.server->frameblend);
6187 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);
6188 animatemodel_cache->model = model;
6189 memcpy(&animatemodel_cache->frameblend, &ed->priv.server->frameblend, sizeof(ed->priv.server->frameblend));
6190 animatemodel_cache->skeleton_p = skeleton;
6192 memcpy(&animatemodel_cache->skeleton, skeleton, sizeof(ed->priv.server->skeleton));
6195 static void getmatrix(prvm_prog_t *prog, prvm_edict_t *ed, matrix4x4_t *out)
6197 if (prog == SVVM_prog)
6198 SV_GetEntityMatrix(prog, ed, out, false);
6199 else if (prog == CLVM_prog)
6200 CL_GetEntityMatrix(prog, ed, out, false);
6202 *out = identitymatrix;
6205 static void applytransform_forward(prvm_prog_t *prog, const vec3_t in, prvm_edict_t *ed, vec3_t out)
6208 getmatrix(prog, ed, &m);
6209 Matrix4x4_Transform(&m, in, out);
6212 static void applytransform_forward_direction(prvm_prog_t *prog, const vec3_t in, prvm_edict_t *ed, vec3_t out)
6215 getmatrix(prog, ed, &m);
6216 Matrix4x4_Transform3x3(&m, in, out);
6219 static void applytransform_inverted(prvm_prog_t *prog, const vec3_t in, prvm_edict_t *ed, vec3_t out)
6222 getmatrix(prog, ed, &m);
6223 Matrix4x4_Invert_Full(&n, &m);
6224 Matrix4x4_Transform3x3(&n, in, out);
6227 static void applytransform_forward_normal(prvm_prog_t *prog, const vec3_t in, prvm_edict_t *ed, vec3_t out)
6231 getmatrix(prog, ed, &m);
6232 Matrix4x4_TransformPositivePlane(&m, in[0], in[1], in[2], 0, p);
6236 static void clippointtosurface(prvm_prog_t *prog, prvm_edict_t *ed, model_t *model, msurface_t *surface, vec3_t p, vec3_t out)
6239 float *v[3], facenormal[3], edgenormal[3], sidenormal[3], temp[3], offsetdist, dist, bestdist;
6241 animatemodel(prog, model, ed);
6242 bestdist = 1000000000;
6244 for (i = 0, e = (model->surfmesh.data_element3i + 3 * surface->num_firsttriangle);i < surface->num_triangles;i++, e += 3)
6246 // clip original point to each triangle of the surface and find the
6247 // triangle that is closest
6248 v[0] = prog->animatemodel_cache->data_vertex3f + e[0] * 3;
6249 v[1] = prog->animatemodel_cache->data_vertex3f + e[1] * 3;
6250 v[2] = prog->animatemodel_cache->data_vertex3f + e[2] * 3;
6251 TriangleNormal(v[0], v[1], v[2], facenormal);
6252 VectorNormalize(facenormal);
6253 offsetdist = DotProduct(v[0], facenormal) - DotProduct(p, facenormal);
6254 VectorMA(p, offsetdist, facenormal, temp);
6255 for (j = 0, k = 2;j < 3;k = j, j++)
6257 VectorSubtract(v[k], v[j], edgenormal);
6258 CrossProduct(edgenormal, facenormal, sidenormal);
6259 VectorNormalize(sidenormal);
6260 offsetdist = DotProduct(v[k], sidenormal) - DotProduct(temp, sidenormal);
6262 VectorMA(temp, offsetdist, sidenormal, temp);
6264 dist = VectorDistance2(temp, p);
6265 if (bestdist > dist)
6268 VectorCopy(temp, out);
6273 static msurface_t *getsurface(model_t *model, int surfacenum)
6275 if (surfacenum < 0 || surfacenum >= model->submodelsurfaces_end - model->submodelsurfaces_start)
6277 return model->data_surfaces + surfacenum + model->submodelsurfaces_start;
6281 //PF_getsurfacenumpoints, // #434 float(entity e, float s) getsurfacenumpoints = #434;
6282 void VM_getsurfacenumpoints(prvm_prog_t *prog)
6285 msurface_t *surface;
6286 VM_SAFEPARMCOUNT(2, VM_getsurfacenumpoints);
6287 // return 0 if no such surface
6288 if (!(model = getmodel(prog, PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6290 PRVM_G_FLOAT(OFS_RETURN) = 0;
6294 // note: this (incorrectly) assumes it is a simple polygon
6295 PRVM_G_FLOAT(OFS_RETURN) = surface->num_vertices;
6297 //PF_getsurfacepoint, // #435 vector(entity e, float s, float n) getsurfacepoint = #435;
6298 void VM_getsurfacepoint(prvm_prog_t *prog)
6302 msurface_t *surface;
6305 VM_SAFEPARMCOUNT(3, VM_getsurfacepoint);
6306 VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6307 ed = PRVM_G_EDICT(OFS_PARM0);
6308 if (!(model = getmodel(prog, ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6310 // note: this (incorrectly) assumes it is a simple polygon
6311 pointnum = (int)PRVM_G_FLOAT(OFS_PARM2);
6312 if (pointnum < 0 || pointnum >= surface->num_vertices)
6314 animatemodel(prog, model, ed);
6315 applytransform_forward(prog, &(prog->animatemodel_cache->data_vertex3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, result);
6316 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6318 //PF_getsurfacepointattribute, // #486 vector(entity e, float s, float n, float a) getsurfacepointattribute = #486;
6319 // float SPA_POSITION = 0;
6320 // float SPA_S_AXIS = 1;
6321 // float SPA_T_AXIS = 2;
6322 // float SPA_R_AXIS = 3; // same as SPA_NORMAL
6323 // float SPA_TEXCOORDS0 = 4;
6324 // float SPA_LIGHTMAP0_TEXCOORDS = 5;
6325 // float SPA_LIGHTMAP0_COLOR = 6;
6326 void VM_getsurfacepointattribute(prvm_prog_t *prog)
6330 msurface_t *surface;
6335 VM_SAFEPARMCOUNT(4, VM_getsurfacepointattribute);
6336 VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6337 ed = PRVM_G_EDICT(OFS_PARM0);
6338 if (!(model = getmodel(prog, ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6340 pointnum = (int)PRVM_G_FLOAT(OFS_PARM2);
6341 if (pointnum < 0 || pointnum >= surface->num_vertices)
6343 attributetype = (int) PRVM_G_FLOAT(OFS_PARM3);
6345 animatemodel(prog, model, ed);
6347 switch( attributetype ) {
6348 // float SPA_POSITION = 0;
6350 applytransform_forward(prog, &(prog->animatemodel_cache->data_vertex3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, result);
6351 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6353 // float SPA_S_AXIS = 1;
6355 applytransform_forward_direction(prog, &(prog->animatemodel_cache->data_svector3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, result);
6356 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6358 // float SPA_T_AXIS = 2;
6360 applytransform_forward_direction(prog, &(prog->animatemodel_cache->data_tvector3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, result);
6361 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6363 // float SPA_R_AXIS = 3; // same as SPA_NORMAL
6365 applytransform_forward_direction(prog, &(prog->animatemodel_cache->data_normal3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, result);
6366 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6368 // float SPA_TEXCOORDS0 = 4;
6370 float *texcoord = &(model->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[pointnum * 2];
6371 result[0] = texcoord[0];
6372 result[1] = texcoord[1];
6374 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6377 // float SPA_LIGHTMAP0_TEXCOORDS = 5;
6379 float *texcoord = &(model->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[pointnum * 2];
6380 result[0] = texcoord[0];
6381 result[1] = texcoord[1];
6383 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6386 // float SPA_LIGHTMAP0_COLOR = 6;
6388 // ignore alpha for now..
6389 VectorCopy( &(model->surfmesh.data_lightmapcolor4f + 4 * surface->num_firstvertex)[pointnum * 4], PRVM_G_VECTOR(OFS_RETURN));
6392 VectorSet( PRVM_G_VECTOR(OFS_RETURN), 0.0f, 0.0f, 0.0f );
6396 //PF_getsurfacenormal, // #436 vector(entity e, float s) getsurfacenormal = #436;
6397 void VM_getsurfacenormal(prvm_prog_t *prog)
6400 msurface_t *surface;
6403 VM_SAFEPARMCOUNT(2, VM_getsurfacenormal);
6404 VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6405 if (!(model = getmodel(prog, PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6407 // note: this only returns the first triangle, so it doesn't work very
6408 // well for curved surfaces or arbitrary meshes
6409 animatemodel(prog, model, PRVM_G_EDICT(OFS_PARM0));
6410 TriangleNormal((prog->animatemodel_cache->data_vertex3f + 3 * surface->num_firstvertex), (prog->animatemodel_cache->data_vertex3f + 3 * surface->num_firstvertex) + 3, (prog->animatemodel_cache->data_vertex3f + 3 * surface->num_firstvertex) + 6, normal);
6411 applytransform_forward_normal(prog, normal, PRVM_G_EDICT(OFS_PARM0), result);
6412 VectorNormalize(result);
6413 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6415 //PF_getsurfacetexture, // #437 string(entity e, float s) getsurfacetexture = #437;
6416 void VM_getsurfacetexture(prvm_prog_t *prog)
6419 msurface_t *surface;
6421 VM_SAFEPARMCOUNT(2, VM_getsurfacetexture);
6422 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
6423 if (!(model = getmodel(prog, PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6425 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, surface->texture->name, strlen(surface->texture->name));
6427 //PF_getsurfacenearpoint, // #438 float(entity e, vector p) getsurfacenearpoint = #438;
6428 void VM_getsurfacenearpoint(prvm_prog_t *prog)
6430 int surfacenum, best;
6432 vec_t dist, bestdist;
6435 msurface_t *surface;
6437 VM_SAFEPARMCOUNT(2, VM_getsurfacenearpoint);
6438 PRVM_G_FLOAT(OFS_RETURN) = -1;
6439 ed = PRVM_G_EDICT(OFS_PARM0);
6440 VectorCopy(PRVM_G_VECTOR(OFS_PARM1), point);
6442 if (!ed || ed->free)
6444 model = getmodel(prog, ed);
6445 if (!model || !model->num_surfaces)
6448 animatemodel(prog, model, ed);
6450 applytransform_inverted(prog, point, ed, p);
6452 bestdist = 1000000000;
6453 for (surfacenum = model->submodelsurfaces_start;surfacenum < model->submodelsurfaces_end;surfacenum++)
6455 surface = model->data_surfaces + surfacenum;
6456 // first see if the nearest point on the surface's box is closer than the previous match
6457 clipped[0] = bound(surface->mins[0], p[0], surface->maxs[0]) - p[0];
6458 clipped[1] = bound(surface->mins[1], p[1], surface->maxs[1]) - p[1];
6459 clipped[2] = bound(surface->mins[2], p[2], surface->maxs[2]) - p[2];
6460 dist = VectorLength2(clipped);
6461 if (dist < bestdist)
6463 // it is, check the nearest point on the actual geometry
6464 clippointtosurface(prog, ed, model, surface, p, clipped);
6465 VectorSubtract(clipped, p, clipped);
6466 dist += VectorLength2(clipped);
6467 if (dist < bestdist)
6469 // that's closer too, store it as the best match
6470 best = surfacenum - model->submodelsurfaces_start;
6475 PRVM_G_FLOAT(OFS_RETURN) = best;
6477 //PF_getsurfaceclippedpoint, // #439 vector(entity e, float s, vector p) getsurfaceclippedpoint = #439;
6478 void VM_getsurfaceclippedpoint(prvm_prog_t *prog)
6482 msurface_t *surface;
6484 VM_SAFEPARMCOUNT(3, VM_getsurfaceclippedpoint);
6485 VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6486 ed = PRVM_G_EDICT(OFS_PARM0);
6487 if (!(model = getmodel(prog, ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6489 animatemodel(prog, model, ed);
6490 VectorCopy(PRVM_G_VECTOR(OFS_PARM2), inp);
6491 applytransform_inverted(prog, inp, ed, p);
6492 clippointtosurface(prog, ed, model, surface, p, out);
6493 VectorAdd(out, PRVM_serveredictvector(ed, origin), PRVM_G_VECTOR(OFS_RETURN));
6496 //PF_getsurfacenumtriangles, // #??? float(entity e, float s) getsurfacenumtriangles = #???;
6497 void VM_getsurfacenumtriangles(prvm_prog_t *prog)
6500 msurface_t *surface;
6501 VM_SAFEPARMCOUNT(2, VM_getsurfacenumtriangles);
6502 // return 0 if no such surface
6503 if (!(model = getmodel(prog, PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6505 PRVM_G_FLOAT(OFS_RETURN) = 0;
6509 PRVM_G_FLOAT(OFS_RETURN) = surface->num_triangles;
6511 //PF_getsurfacetriangle, // #??? vector(entity e, float s, float n) getsurfacetriangle = #???;
6512 void VM_getsurfacetriangle(prvm_prog_t *prog)
6514 const vec3_t d = {-1, -1, -1};
6517 msurface_t *surface;
6519 VM_SAFEPARMCOUNT(3, VM_getsurfacetriangle);
6520 VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6521 ed = PRVM_G_EDICT(OFS_PARM0);
6522 if (!(model = getmodel(prog, ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6524 trinum = (int)PRVM_G_FLOAT(OFS_PARM2);
6525 if (trinum < 0 || trinum >= surface->num_triangles)
6527 // FIXME: implement rotation/scaling
6528 VectorMA(&(model->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[trinum * 3], surface->num_firstvertex, d, PRVM_G_VECTOR(OFS_RETURN));
6536 #define VM_physics_ApplyCmd(ed,f) if (!ed->priv.server->ode_body) VM_physics_newstackfunction(prog, ed, f); else World_Physics_ApplyCmd(ed, f)
6538 static edict_odefunc_t *VM_physics_newstackfunction(prvm_prog_t *prog, prvm_edict_t *ed, edict_odefunc_t *f)
6540 edict_odefunc_t *newfunc, *func;
6542 newfunc = (edict_odefunc_t *)Mem_Alloc(prog->progs_mempool, sizeof(edict_odefunc_t));
6543 memcpy(newfunc, f, sizeof(edict_odefunc_t));
6544 newfunc->next = NULL;
6545 if (!ed->priv.server->ode_func)
6546 ed->priv.server->ode_func = newfunc;
6549 for (func = ed->priv.server->ode_func; func->next; func = func->next);
6550 func->next = newfunc;
6556 // void(entity e, float physics_enabled) physics_enable = #;
6557 void VM_physics_enable(prvm_prog_t *prog)
6563 VM_SAFEPARMCOUNT(2, VM_physics_enable);
6565 ed = PRVM_G_EDICT(OFS_PARM0);
6568 if (developer.integer > 0)
6569 VM_Warning(prog, "VM_physics_enable: null entity!\n");
6572 // entity should have MOVETYPE_PHYSICS already set, this can damage memory (making leaked allocation) so warn about this even if non-developer
6573 if (PRVM_serveredictfloat(ed, movetype) != MOVETYPE_PHYSICS)
6575 VM_Warning(prog, "VM_physics_enable: entity is not MOVETYPE_PHYSICS!\n");
6578 f.type = PRVM_G_FLOAT(OFS_PARM1) == 0 ? ODEFUNC_DISABLE : ODEFUNC_ENABLE;
6579 VM_physics_ApplyCmd(ed, &f);
6583 // void(entity e, vector force, vector relative_ofs) physics_addforce = #;
6584 void VM_physics_addforce(prvm_prog_t *prog)
6590 VM_SAFEPARMCOUNT(3, VM_physics_addforce);
6592 ed = PRVM_G_EDICT(OFS_PARM0);
6595 if (developer.integer > 0)
6596 VM_Warning(prog, "VM_physics_addforce: null entity!\n");
6599 // entity should have MOVETYPE_PHYSICS already set, this can damage memory (making leaked allocation) so warn about this even if non-developer
6600 if (PRVM_serveredictfloat(ed, movetype) != MOVETYPE_PHYSICS)
6602 VM_Warning(prog, "VM_physics_addforce: entity is not MOVETYPE_PHYSICS!\n");
6605 f.type = ODEFUNC_FORCE;
6606 VectorCopy(PRVM_G_VECTOR(OFS_PARM1), f.v1);
6607 VectorCopy(PRVM_G_VECTOR(OFS_PARM2), f.v2);
6608 VM_physics_ApplyCmd(ed, &f);
6612 // void(entity e, vector torque) physics_addtorque = #;
6613 void VM_physics_addtorque(prvm_prog_t *prog)
6619 VM_SAFEPARMCOUNT(2, VM_physics_addtorque);
6621 ed = PRVM_G_EDICT(OFS_PARM0);
6624 if (developer.integer > 0)
6625 VM_Warning(prog, "VM_physics_addtorque: null entity!\n");
6628 // entity should have MOVETYPE_PHYSICS already set, this can damage memory (making leaked allocation) so warn about this even if non-developer
6629 if (PRVM_serveredictfloat(ed, movetype) != MOVETYPE_PHYSICS)
6631 VM_Warning(prog, "VM_physics_addtorque: entity is not MOVETYPE_PHYSICS!\n");
6634 f.type = ODEFUNC_TORQUE;
6635 VectorCopy(PRVM_G_VECTOR(OFS_PARM1), f.v1);
6636 VM_physics_ApplyCmd(ed, &f);
6640 extern cvar_t prvm_coverage;
6641 void VM_coverage(prvm_prog_t *prog)
6643 VM_SAFEPARMCOUNT(0, VM_coverage);
6644 if (prog->explicit_profile[prog->xstatement]++ == 0 && (prvm_coverage.integer & 2))
6645 PRVM_ExplicitCoverageEvent(prog, prog->xfunction, prog->xstatement);