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, qbool prog_loaded, 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.
277 #pragma warning(disable : 4996)
279 size_t VM_VarString(prvm_prog_t *prog, int first, char *out, size_t outsize)
284 char *outend = out + outsize - 1;
286 // bones_was_here: && out < outend improves perf significantly in some tests that don't trigger the warning,
287 // which seems odd, surely it would only help when the warning is printed?
288 for (i = first;i < prog->argc && out < outend;i++)
290 s = PRVM_G_STRING((OFS_PARM0+i*3));
293 // like dp_stpecpy but with a VM_Warning for use with `prvm_backtraceforwarnings 1`
294 p = (char *)memccpy(out, s, '\0', (outend + 1) - out);
299 VM_Warning(prog, "%zu of %zu bytes available, will truncate %zu byte string \"%s\"\n", outend - out, outsize - 1, strlen(s), s);
308 return outsize - ((outend + 1) - out);
315 returns true if the extension is supported by the server
317 checkextension(extensionname)
321 // kind of helper function
322 static qbool checkextension(prvm_prog_t *prog, const char *name)
326 for (e = prog->extensionstring;*e;e++)
328 if(!strcasecmp(*e, name))
331 // special sheck for ODE
332 if (!strncasecmp("DP_PHYSICS_ODE", name, 14))
334 #ifndef LINK_TO_LIBODE
335 return ode_dll ? true : false;
337 #ifdef LINK_TO_LIBODE
346 // special sheck for d0_blind_id
347 if (!strcasecmp("DP_CRYPTO", name))
348 return Crypto_Available();
349 if (!strcasecmp("DP_QC_DIGEST_SHA256", name))
350 return Crypto_Available();
352 // special shreck for libcurl
353 if (!strcasecmp("DP_QC_URI_GET", name) || !strcasecmp("DP_QC_URI_POST", name))
354 return Curl_Available();
362 void VM_checkextension(prvm_prog_t *prog)
364 VM_SAFEPARMCOUNT(1,VM_checkextension);
366 PRVM_G_FLOAT(OFS_RETURN) = checkextension(prog, PRVM_G_STRING(OFS_PARM0));
373 This is a TERMINAL error, which will kill off the entire prog.
379 void VM_error(prvm_prog_t *prog)
382 char string[VM_TEMPSTRING_MAXSIZE];
384 VM_VarString(prog, 0, string, sizeof(string));
385 Con_Printf(CON_ERROR "======%s ERROR in %s:\n%s\n", prog->name, PRVM_GetString(prog, prog->xfunction->s_name), string);
386 ed = PRVM_PROG_TO_EDICT(PRVM_allglobaledict(self));
387 PRVM_ED_Print(prog, ed, NULL);
389 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);
396 Dumps out self, then an error message. The program is aborted and self is
397 removed, but the level can continue.
402 void VM_objerror(prvm_prog_t *prog)
405 char string[VM_TEMPSTRING_MAXSIZE];
407 VM_VarString(prog, 0, string, sizeof(string));
408 Con_Printf(CON_ERROR "======OBJECT ERROR======\n"); // , prog->name, PRVM_GetString(prog->xfunction->s_name), string); // or include them? FIXME
409 ed = PRVM_PROG_TO_EDICT(PRVM_allglobaledict(self));
410 PRVM_ED_Print(prog, ed, NULL);
411 PRVM_ED_Free (prog, ed);
412 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);
424 void VM_print(prvm_prog_t *prog)
426 char string[VM_TEMPSTRING_MAXSIZE];
428 VM_VarString(prog, 0, string, sizeof(string));
436 broadcast print to everyone on server
441 void VM_bprint(prvm_prog_t *prog)
443 char string[VM_TEMPSTRING_MAXSIZE];
447 VM_Warning(prog, "VM_bprint: game is not server(%s) !\n", prog->name);
451 VM_VarString(prog, 0, string, sizeof(string));
452 SV_BroadcastPrint(string);
457 VM_sprint (menu & client but only if server.active == true)
459 single print to a specific client
461 sprint(float clientnum,...[string])
464 void VM_sprint(prvm_prog_t *prog)
468 char string[VM_TEMPSTRING_MAXSIZE];
470 VM_SAFEPARMCOUNTRANGE(1, 8, VM_sprint);
472 //find client for this entity
473 clientnum = (int)PRVM_G_FLOAT(OFS_PARM0);
474 if (!sv.active || clientnum < 0 || clientnum >= svs.maxclients || !svs.clients[clientnum].active)
476 VM_Warning(prog, "VM_sprint: %s: invalid client or server is not active !\n", prog->name);
480 client = svs.clients + clientnum;
481 if (!client->netconnection)
484 VM_VarString(prog, 1, string, sizeof(string));
485 MSG_WriteChar(&client->netconnection->message,svc_print);
486 MSG_WriteString(&client->netconnection->message, string);
493 single print to the screen
498 void VM_centerprint(prvm_prog_t *prog)
500 char string[VM_TEMPSTRING_MAXSIZE];
502 VM_SAFEPARMCOUNTRANGE(1, 8, VM_centerprint);
503 VM_VarString(prog, 0, string, sizeof(string));
504 SCR_CenterPrint(string);
511 vector normalize(vector)
514 void VM_normalize(prvm_prog_t *prog)
520 VM_SAFEPARMCOUNT(1,VM_normalize);
522 value1 = PRVM_G_VECTOR(OFS_PARM0);
524 f = VectorLength2(value1);
528 VectorScale(value1, f, newvalue);
531 VectorClear(newvalue);
533 VectorCopy (newvalue, PRVM_G_VECTOR(OFS_RETURN));
543 void VM_vlen(prvm_prog_t *prog)
545 VM_SAFEPARMCOUNT(1,VM_vlen);
546 PRVM_G_FLOAT(OFS_RETURN) = VectorLength(PRVM_G_VECTOR(OFS_PARM0));
553 float vectoyaw(vector)
556 void VM_vectoyaw(prvm_prog_t *prog)
561 VM_SAFEPARMCOUNT(1,VM_vectoyaw);
563 value1 = PRVM_G_VECTOR(OFS_PARM0);
565 if (value1[1] == 0 && value1[0] == 0)
569 yaw = (int) (atan2(value1[1], value1[0]) * 180 / M_PI);
574 PRVM_G_FLOAT(OFS_RETURN) = yaw;
582 vector vectoangles(vector[, vector])
585 void VM_vectoangles(prvm_prog_t *prog)
587 vec3_t result, forward, up;
588 VM_SAFEPARMCOUNTRANGE(1, 2,VM_vectoangles);
590 VectorCopy(PRVM_G_VECTOR(OFS_PARM0), forward);
593 VectorCopy(PRVM_G_VECTOR(OFS_PARM1), up);
594 AnglesFromVectors(result, forward, up, true);
597 AnglesFromVectors(result, forward, NULL, true);
598 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
605 Returns a random number > 0 and < 1
610 void VM_random(prvm_prog_t *prog)
612 VM_SAFEPARMCOUNT(0,VM_random);
614 PRVM_G_FLOAT(OFS_RETURN) = lhrandom(0, 1);
621 localsound(string sample, float chan, float vol)
624 void VM_localsound(prvm_prog_t *prog)
629 VM_SAFEPARMCOUNTRANGE(1, 3,VM_localsound);
631 s = PRVM_G_STRING(OFS_PARM0);
634 chan = PRVM_G_FLOAT(OFS_PARM1);
635 vol = PRVM_G_FLOAT(OFS_PARM2) == 0 ? 1 : PRVM_G_FLOAT(OFS_PARM2);
636 if(!S_LocalSoundEx(s, chan, vol))
638 PRVM_G_FLOAT(OFS_RETURN) = -4;
639 VM_Warning(prog, "VM_localsound: Failed to play %s for %s !\n", s, prog->name);
643 else if(!S_LocalSound (s))
645 PRVM_G_FLOAT(OFS_RETURN) = -4;
646 VM_Warning(prog, "VM_localsound: Failed to play %s for %s !\n", s, prog->name);
650 PRVM_G_FLOAT(OFS_RETURN) = 1;
660 void VM_break(prvm_prog_t *prog)
662 prog->error_cmd("%s: break statement", prog->name);
665 //============================================================================
671 Sends text over to the client's execution buffer
673 [localcmd (string, ...) or]
677 void VM_localcmd_local(prvm_prog_t *prog)
679 char string[VM_TEMPSTRING_MAXSIZE];
680 VM_SAFEPARMCOUNTRANGE(1, 8, VM_localcmd_local);
681 VM_VarString(prog, 0, string, sizeof(string));
682 Cbuf_AddText(cmd_local, string);
689 Sends text over to the server's execution buffer
691 [localcmd (string, ...) or]
695 void VM_localcmd_server(prvm_prog_t *prog)
697 char string[VM_TEMPSTRING_MAXSIZE];
698 VM_SAFEPARMCOUNTRANGE(1, 8, VM_localcmd_server);
699 VM_VarString(prog, 0, string, sizeof(string));
700 Cbuf_AddText(cmd_local, string);
703 static qbool PRVM_Cvar_ReadOk(prvm_prog_t *prog, const char *string)
706 cvar = Cvar_FindVar(prog->console_cmd->cvars, string, prog->console_cmd->cvars_flagsmask);
707 return ((cvar) && ((cvar->flags & CF_PRIVATE) == 0));
717 void VM_cvar(prvm_prog_t *prog)
719 char string[VM_TEMPSTRING_MAXSIZE];
720 VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar);
721 VM_VarString(prog, 0, string, sizeof(string));
722 VM_CheckEmptyString(prog, string);
723 PRVM_G_FLOAT(OFS_RETURN) = PRVM_Cvar_ReadOk(prog, string) ? Cvar_VariableValue(prog->console_cmd->cvars, string, prog->console_cmd->cvars_flagsmask) : 0;
730 float cvar_type (string)
731 float CVAR_TYPEFLAG_EXISTS = 1;
732 float CVAR_TYPEFLAG_SAVED = 2;
733 float CVAR_TYPEFLAG_PRIVATE = 4;
734 float CVAR_TYPEFLAG_ENGINE = 8;
735 float CVAR_TYPEFLAG_HASDESCRIPTION = 16;
736 float CVAR_TYPEFLAG_READONLY = 32;
739 void VM_cvar_type(prvm_prog_t *prog)
741 char string[VM_TEMPSTRING_MAXSIZE];
745 VM_SAFEPARMCOUNTRANGE(1, 8, VM_cvar_type);
746 VM_VarString(prog, 0, string, sizeof(string));
747 VM_CheckEmptyString(prog, string);
748 cvar = Cvar_FindVar(prog->console_cmd->cvars, string, prog->console_cmd->cvars_flagsmask);
753 PRVM_G_FLOAT(OFS_RETURN) = 0;
754 return; // CVAR_TYPE_NONE
757 ret = 1; // CVAR_EXISTS
758 if(cvar->flags & CF_ARCHIVE)
759 ret |= 2; // CVAR_TYPE_SAVED
760 if(cvar->flags & CF_PRIVATE)
761 ret |= 4; // CVAR_TYPE_PRIVATE
762 if(!(cvar->flags & CF_ALLOCATED))
763 ret |= 8; // CVAR_TYPE_ENGINE
764 if(cvar->description != cvar_dummy_description)
765 ret |= 16; // CVAR_TYPE_HASDESCRIPTION
766 if(cvar->flags & CF_READONLY)
767 ret |= 32; // CVAR_TYPE_READONLY
769 PRVM_G_FLOAT(OFS_RETURN) = ret;
776 const string VM_cvar_string (string, ...)
779 void VM_cvar_string(prvm_prog_t *prog)
781 char cvar_name[VM_TEMPSTRING_MAXSIZE];
783 VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_string);
784 VM_VarString(prog, 0, cvar_name, sizeof(cvar_name));
785 VM_CheckEmptyString(prog, cvar_name);
786 if (PRVM_Cvar_ReadOk(prog, cvar_name))
788 const char *cvar_string = Cvar_VariableString(prog->console_cmd->cvars, cvar_name, prog->console_cmd->cvars_flagsmask);
789 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, cvar_string, strlen(cvar_string));
792 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
797 ========================
800 const string VM_cvar_defstring (string, ...)
801 ========================
803 void VM_cvar_defstring(prvm_prog_t *prog)
805 char cvar_name[VM_TEMPSTRING_MAXSIZE];
806 const char *cvar_defstring;
808 VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_defstring);
809 VM_VarString(prog, 0, cvar_name, sizeof(cvar_name));
810 VM_CheckEmptyString(prog, cvar_name);
811 cvar_defstring = Cvar_VariableDefString(prog->console_cmd->cvars, cvar_name, prog->console_cmd->cvars_flagsmask);
812 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, cvar_defstring, strlen(cvar_defstring));
816 ========================
819 const string VM_cvar_description (string, ...)
820 ========================
822 void VM_cvar_description(prvm_prog_t *prog)
824 char cvar_name[VM_TEMPSTRING_MAXSIZE];
825 const char *cvar_desc;
827 VM_SAFEPARMCOUNTRANGE(1,8,VM_cvar_description);
828 VM_VarString(prog, 0, cvar_name, sizeof(cvar_name));
829 VM_CheckEmptyString(prog, cvar_name);
830 cvar_desc = Cvar_VariableDescription(prog->console_cmd->cvars, cvar_name, prog->console_cmd->cvars_flagsmask);
831 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, cvar_desc, strlen(cvar_desc));
837 void cvar_set (string,string, ...)
840 void VM_cvar_set(prvm_prog_t *prog)
843 char value[VM_TEMPSTRING_MAXSIZE];
846 VM_SAFEPARMCOUNTRANGE(2,8,VM_cvar_set);
847 name = PRVM_G_STRING(OFS_PARM0);
848 VM_CheckEmptyString(prog, name);
849 cvar = Cvar_FindVar(prog->console_cmd->cvars, name, prog->console_cmd->cvars_flagsmask);
852 VM_Warning(prog, "VM_cvar_set: variable %s not found\n", name);
855 if (cvar->flags & CF_READONLY)
857 VM_Warning(prog, "VM_cvar_set: variable %s is read-only\n", cvar->name);
860 VM_VarString(prog, 1, value, sizeof(value));
861 Cvar_SetQuick(cvar, value);
871 void VM_dprint(prvm_prog_t *prog)
873 char string[VM_TEMPSTRING_MAXSIZE];
874 VM_SAFEPARMCOUNTRANGE(1, 8, VM_dprint);
875 VM_VarString(prog, 0, string, sizeof(string));
877 Con_DPrintf("%s", string);
879 Con_DPrintf("%s: %s", prog->name, string);
891 void VM_ftos(prvm_prog_t *prog)
897 VM_SAFEPARMCOUNT(1, VM_ftos);
899 v = PRVM_G_FLOAT(OFS_PARM0);
901 if ((prvm_vec_t)((prvm_int_t)v) == v)
902 slen = dpsnprintf(s, sizeof(s), "%.0f", v);
904 slen = dpsnprintf(s, sizeof(s), "%f", v);
905 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s, slen);
916 void VM_fabs(prvm_prog_t *prog)
920 VM_SAFEPARMCOUNT(1,VM_fabs);
922 v = PRVM_G_FLOAT(OFS_PARM0);
923 PRVM_G_FLOAT(OFS_RETURN) = fabs(v);
934 void VM_vtos(prvm_prog_t *prog)
939 VM_SAFEPARMCOUNT(1,VM_vtos);
941 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]);
942 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s, slen);
953 void VM_etos(prvm_prog_t *prog)
958 VM_SAFEPARMCOUNT(1, VM_etos);
960 slen = dpsnprintf(s, sizeof(s), "entity %i", PRVM_G_EDICTNUM(OFS_PARM0));
961 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s, slen);
968 float stof(...[string])
971 void VM_stof(prvm_prog_t *prog)
973 char string[VM_TEMPSTRING_MAXSIZE];
974 VM_SAFEPARMCOUNTRANGE(1, 8, VM_stof);
975 VM_VarString(prog, 0, string, sizeof(string));
976 PRVM_G_FLOAT(OFS_RETURN) = atof(string);
980 ========================
984 ========================
986 void VM_itof(prvm_prog_t *prog)
988 VM_SAFEPARMCOUNT(1, VM_itof);
989 PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
993 ========================
996 entity ftoe(float num)
997 ========================
999 void VM_ftoe(prvm_prog_t *prog)
1002 VM_SAFEPARMCOUNT(1, VM_ftoe);
1004 ent = (prvm_int_t)PRVM_G_FLOAT(OFS_PARM0);
1005 if (ent < 0 || ent >= prog->max_edicts || PRVM_PROG_TO_EDICT(ent)->free)
1006 ent = 0; // return world instead of a free or invalid entity
1008 PRVM_G_INT(OFS_RETURN) = ent;
1012 ========================
1015 float etof(entity ent)
1016 ========================
1018 void VM_etof(prvm_prog_t *prog)
1020 VM_SAFEPARMCOUNT(1, VM_etof);
1021 PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_EDICTNUM(OFS_PARM0);
1028 string strftime(float uselocaltime, string[, string ...])
1031 void VM_strftime(prvm_prog_t *prog)
1034 #if _MSC_VER >= 1400
1040 char fmt[VM_TEMPSTRING_MAXSIZE];
1041 char result[VM_TEMPSTRING_MAXSIZE];
1044 VM_SAFEPARMCOUNTRANGE(2, 8, VM_strftime);
1045 VM_VarString(prog, 1, fmt, sizeof(fmt));
1047 #if _MSC_VER >= 1400
1048 if (PRVM_G_FLOAT(OFS_PARM0))
1049 tmresult = localtime_s(&tm, &t);
1051 tmresult = gmtime_s(&tm, &t);
1054 if (PRVM_G_FLOAT(OFS_PARM0))
1061 PRVM_G_INT(OFS_RETURN) = 0;
1064 #if _MSC_VER >= 1400
1065 result_len = strftime(result, sizeof(result), fmt, &tm);
1067 result_len = strftime(result, sizeof(result), fmt, tm);
1069 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, result, result_len);
1080 void VM_spawn(prvm_prog_t *prog)
1083 VM_SAFEPARMCOUNT(0, VM_spawn);
1084 prog->xfunction->builtinsprofile += 20;
1085 ed = PRVM_ED_Alloc(prog);
1086 VM_RETURN_EDICT(ed);
1097 void VM_remove(prvm_prog_t *prog)
1100 prog->xfunction->builtinsprofile += 20;
1102 VM_SAFEPARMCOUNT(1, VM_remove);
1104 ed = PRVM_G_EDICT(OFS_PARM0);
1105 if( PRVM_NUM_FOR_EDICT(ed) <= prog->reserved_edicts )
1107 if (developer.integer > 0)
1108 VM_Warning(prog, "VM_remove: tried to remove the null entity or a reserved entity!\n" );
1112 if (developer.integer > 0)
1113 VM_Warning(prog, "VM_remove: tried to remove an already freed entity!\n" );
1116 PRVM_ED_Free (prog, ed);
1123 entity find(entity start, .string field, string match)
1127 void VM_find(prvm_prog_t *prog)
1134 VM_SAFEPARMCOUNT(3,VM_find);
1136 e = PRVM_G_EDICTNUM(OFS_PARM0);
1137 f = PRVM_G_INT(OFS_PARM1);
1138 s = PRVM_G_STRING(OFS_PARM2);
1140 // LadyHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
1141 // expects it to find all the monsters, so we must be careful to support
1144 for (e++ ; e < prog->num_edicts ; e++)
1146 prog->xfunction->builtinsprofile++;
1147 ed = PRVM_EDICT_NUM(e);
1150 t = PRVM_E_STRING(ed,f);
1155 VM_RETURN_EDICT(ed);
1160 VM_RETURN_EDICT(prog->edicts);
1167 entity findfloat(entity start, .float field, float match)
1168 entity findentity(entity start, .entity field, entity match)
1171 // LadyHavoc: added this for searching float, int, and entity reference fields
1172 void VM_findfloat(prvm_prog_t *prog)
1179 VM_SAFEPARMCOUNT(3,VM_findfloat);
1181 e = PRVM_G_EDICTNUM(OFS_PARM0);
1182 f = PRVM_G_INT(OFS_PARM1);
1183 s = PRVM_G_FLOAT(OFS_PARM2);
1185 for (e++ ; e < prog->num_edicts ; e++)
1187 prog->xfunction->builtinsprofile++;
1188 ed = PRVM_EDICT_NUM(e);
1191 if (PRVM_E_FLOAT(ed,f) == s)
1193 VM_RETURN_EDICT(ed);
1198 VM_RETURN_EDICT(prog->edicts);
1205 entity findchain(.string field, string match)
1208 // chained search for strings in entity fields
1209 // entity(.string field, string match) findchain = #402;
1210 void VM_findchain(prvm_prog_t *prog)
1215 prvm_edict_t *ent, *chain;
1218 VM_SAFEPARMCOUNTRANGE(2,3,VM_findchain);
1221 chainfield = PRVM_G_INT(OFS_PARM2);
1223 chainfield = prog->fieldoffsets.chain;
1225 prog->error_cmd("VM_findchain: %s doesnt have the specified chain field !", prog->name);
1227 chain = prog->edicts;
1229 f = PRVM_G_INT(OFS_PARM0);
1230 s = PRVM_G_STRING(OFS_PARM1);
1232 // LadyHavoc: apparently BloodMage does a find(world, weaponmodel, "") and
1233 // expects it to find all the monsters, so we must be careful to support
1236 ent = PRVM_NEXT_EDICT(prog->edicts);
1237 for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1239 prog->xfunction->builtinsprofile++;
1242 t = PRVM_E_STRING(ent,f);
1248 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_NUM_FOR_EDICT(chain);
1252 VM_RETURN_EDICT(chain);
1259 entity findchainfloat(.string field, float match)
1260 entity findchainentity(.string field, entity match)
1263 // LadyHavoc: chained search for float, int, and entity reference fields
1264 // entity(.string field, float match) findchainfloat = #403;
1265 void VM_findchainfloat(prvm_prog_t *prog)
1270 prvm_edict_t *ent, *chain;
1273 VM_SAFEPARMCOUNTRANGE(2, 3, VM_findchainfloat);
1276 chainfield = PRVM_G_INT(OFS_PARM2);
1278 chainfield = prog->fieldoffsets.chain;
1280 prog->error_cmd("VM_findchainfloat: %s doesnt have the specified chain field !", prog->name);
1282 chain = (prvm_edict_t *)prog->edicts;
1284 f = PRVM_G_INT(OFS_PARM0);
1285 s = PRVM_G_FLOAT(OFS_PARM1);
1287 ent = PRVM_NEXT_EDICT(prog->edicts);
1288 for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1290 prog->xfunction->builtinsprofile++;
1293 if (PRVM_E_FLOAT(ent,f) != s)
1296 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_EDICT_TO_PROG(chain);
1300 VM_RETURN_EDICT(chain);
1304 ========================
1307 entity findflags(entity start, .float field, float match)
1308 ========================
1310 // LadyHavoc: search for flags in float fields
1311 void VM_findflags(prvm_prog_t *prog)
1318 VM_SAFEPARMCOUNT(3, VM_findflags);
1321 e = PRVM_G_EDICTNUM(OFS_PARM0);
1322 f = PRVM_G_INT(OFS_PARM1);
1323 s = (prvm_int_t)PRVM_G_FLOAT(OFS_PARM2);
1325 for (e++ ; e < prog->num_edicts ; e++)
1327 prog->xfunction->builtinsprofile++;
1328 ed = PRVM_EDICT_NUM(e);
1331 if (!PRVM_E_FLOAT(ed,f))
1333 if ((prvm_int_t)PRVM_E_FLOAT(ed,f) & s)
1335 VM_RETURN_EDICT(ed);
1340 VM_RETURN_EDICT(prog->edicts);
1344 ========================
1347 entity findchainflags(.float field, float match)
1348 ========================
1350 // LadyHavoc: chained search for flags in float fields
1351 void VM_findchainflags(prvm_prog_t *prog)
1356 prvm_edict_t *ent, *chain;
1359 VM_SAFEPARMCOUNTRANGE(2, 3, VM_findchainflags);
1362 chainfield = PRVM_G_INT(OFS_PARM2);
1364 chainfield = prog->fieldoffsets.chain;
1366 prog->error_cmd("VM_findchainflags: %s doesnt have the specified chain field !", prog->name);
1368 chain = (prvm_edict_t *)prog->edicts;
1370 f = PRVM_G_INT(OFS_PARM0);
1371 s = (prvm_int_t)PRVM_G_FLOAT(OFS_PARM1);
1373 ent = PRVM_NEXT_EDICT(prog->edicts);
1374 for (i = 1;i < prog->num_edicts;i++, ent = PRVM_NEXT_EDICT(ent))
1376 prog->xfunction->builtinsprofile++;
1379 if (!PRVM_E_FLOAT(ent,f))
1381 if (!((prvm_int_t)PRVM_E_FLOAT(ent,f) & s))
1384 PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_EDICT_TO_PROG(chain);
1388 VM_RETURN_EDICT(chain);
1395 string precache_sound (string sample)
1398 void VM_precache_sound(prvm_prog_t *prog)
1402 VM_SAFEPARMCOUNT(1, VM_precache_sound);
1404 s = PRVM_G_STRING(OFS_PARM0);
1405 PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
1406 //VM_CheckEmptyString(prog, s);
1408 if(snd_initialized.integer && !S_PrecacheSound(s, true, true))
1410 VM_Warning(prog, "VM_precache_sound: Failed to load %s for %s\n", s, prog->name);
1419 returns the same string as output
1421 does nothing, only used by qcc to build .pak archives
1424 void VM_precache_file(prvm_prog_t *prog)
1426 VM_SAFEPARMCOUNT(1,VM_precache_file);
1427 // precache_file is only used to copy files with qcc, it does nothing
1428 PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
1438 void VM_coredump(prvm_prog_t *prog)
1440 VM_SAFEPARMCOUNT(0,VM_coredump);
1442 Cbuf_AddText(cmd_local, "prvm_edicts ");
1443 Cbuf_AddText(cmd_local, prog->name);
1444 Cbuf_AddText(cmd_local, "\n");
1454 void VM_stackdump(prvm_prog_t *prog)
1456 VM_SAFEPARMCOUNT(0, VM_stackdump);
1458 PRVM_StackTrace(prog);
1469 void VM_crash(prvm_prog_t *prog)
1471 VM_SAFEPARMCOUNT(0, VM_crash);
1473 prog->error_cmd("Crash called by %s",prog->name);
1483 void VM_traceon(prvm_prog_t *prog)
1485 VM_SAFEPARMCOUNT(0,VM_traceon);
1497 void VM_traceoff(prvm_prog_t *prog)
1499 VM_SAFEPARMCOUNT(0,VM_traceoff);
1501 prog->trace = false;
1511 void VM_eprint(prvm_prog_t *prog)
1513 VM_SAFEPARMCOUNT(1,VM_eprint);
1515 PRVM_ED_PrintNum (prog, PRVM_G_EDICTNUM(OFS_PARM0), NULL);
1525 void VM_rint(prvm_prog_t *prog)
1528 VM_SAFEPARMCOUNT(1,VM_rint);
1530 f = PRVM_G_FLOAT(OFS_PARM0);
1532 PRVM_G_FLOAT(OFS_RETURN) = floor(f + 0.5);
1534 PRVM_G_FLOAT(OFS_RETURN) = ceil(f - 0.5);
1544 void VM_floor(prvm_prog_t *prog)
1546 VM_SAFEPARMCOUNT(1,VM_floor);
1548 PRVM_G_FLOAT(OFS_RETURN) = floor(PRVM_G_FLOAT(OFS_PARM0));
1558 void VM_ceil(prvm_prog_t *prog)
1560 VM_SAFEPARMCOUNT(1,VM_ceil);
1562 PRVM_G_FLOAT(OFS_RETURN) = ceil(PRVM_G_FLOAT(OFS_PARM0));
1570 entity nextent(entity)
1573 void VM_nextent(prvm_prog_t *prog)
1578 VM_SAFEPARMCOUNT(1, VM_nextent);
1580 i = PRVM_G_EDICTNUM(OFS_PARM0);
1583 prog->xfunction->builtinsprofile++;
1585 if (i == prog->num_edicts)
1587 VM_RETURN_EDICT(prog->edicts);
1590 ent = PRVM_EDICT_NUM(i);
1593 VM_RETURN_EDICT(ent);
1599 //=============================================================================
1606 changelevel(string map)
1609 void VM_changelevel(prvm_prog_t *prog)
1612 VM_SAFEPARMCOUNT(1, VM_changelevel);
1616 VM_Warning(prog, "VM_changelevel: game is not server (%s)\n", prog->name);
1620 // make sure we don't issue two changelevels
1621 if (svs.changelevel_issued)
1623 svs.changelevel_issued = true;
1625 Cbuf_AddText(cmd_local, va(vabuf, sizeof(vabuf), "changelevel %s\n", PRVM_G_STRING(OFS_PARM0)));
1635 void VM_sin(prvm_prog_t *prog)
1637 VM_SAFEPARMCOUNT(1,VM_sin);
1638 PRVM_G_FLOAT(OFS_RETURN) = sin(PRVM_G_FLOAT(OFS_PARM0));
1647 void VM_cos(prvm_prog_t *prog)
1649 VM_SAFEPARMCOUNT(1,VM_cos);
1650 PRVM_G_FLOAT(OFS_RETURN) = cos(PRVM_G_FLOAT(OFS_PARM0));
1660 void VM_sqrt(prvm_prog_t *prog)
1662 VM_SAFEPARMCOUNT(1,VM_sqrt);
1663 PRVM_G_FLOAT(OFS_RETURN) = sqrt(PRVM_G_FLOAT(OFS_PARM0));
1673 void VM_asin(prvm_prog_t *prog)
1675 VM_SAFEPARMCOUNT(1,VM_asin);
1676 PRVM_G_FLOAT(OFS_RETURN) = asin(PRVM_G_FLOAT(OFS_PARM0));
1685 void VM_acos(prvm_prog_t *prog)
1687 VM_SAFEPARMCOUNT(1,VM_acos);
1688 PRVM_G_FLOAT(OFS_RETURN) = acos(PRVM_G_FLOAT(OFS_PARM0));
1697 void VM_atan(prvm_prog_t *prog)
1699 VM_SAFEPARMCOUNT(1,VM_atan);
1700 PRVM_G_FLOAT(OFS_RETURN) = atan(PRVM_G_FLOAT(OFS_PARM0));
1706 float atan2(float,float)
1709 void VM_atan2(prvm_prog_t *prog)
1711 VM_SAFEPARMCOUNT(2,VM_atan2);
1712 PRVM_G_FLOAT(OFS_RETURN) = atan2(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1721 void VM_tan(prvm_prog_t *prog)
1723 VM_SAFEPARMCOUNT(1,VM_tan);
1724 PRVM_G_FLOAT(OFS_RETURN) = tan(PRVM_G_FLOAT(OFS_PARM0));
1731 Returns a vector of length < 1 and > 0
1736 void VM_randomvec(prvm_prog_t *prog)
1739 VM_SAFEPARMCOUNT(0, VM_randomvec);
1741 VectorCopy(temp, PRVM_G_VECTOR(OFS_RETURN));
1744 //=============================================================================
1750 float registercvar (string name, string value[, float flags])
1753 void VM_registercvar(prvm_prog_t *prog)
1755 const char *name, *value;
1758 VM_SAFEPARMCOUNTRANGE(2, 3, VM_registercvar);
1760 name = PRVM_G_STRING(OFS_PARM0);
1761 value = PRVM_G_STRING(OFS_PARM1);
1762 flags = prog->argc >= 3 ? (int)PRVM_G_FLOAT(OFS_PARM2) : 0;
1763 PRVM_G_FLOAT(OFS_RETURN) = 0;
1765 if(flags > CF_MAXFLAGSVAL)
1768 // first check to see if it has already been defined
1769 if (Cvar_FindVar (prog->console_cmd->cvars, name, prog->console_cmd->cvars_flagsmask))
1772 // check for overlap with a command
1773 if (Cmd_Exists(cmd_local, name))
1775 VM_Warning(prog, "VM_registercvar: %s is a command\n", name);
1779 Cvar_Get(prog->console_cmd->cvars, name, value, prog->console_cmd->cvars_flagsmask | flags, NULL);
1781 PRVM_G_FLOAT(OFS_RETURN) = 1; // success
1789 returns the minimum of two supplied floats
1791 float min(float a, float b, ...[float])
1794 void VM_min(prvm_prog_t *prog)
1796 VM_SAFEPARMCOUNTRANGE(2, 8, VM_min);
1797 // LadyHavoc: 3+ argument enhancement suggested by FrikaC
1798 if (prog->argc >= 3)
1801 float f = PRVM_G_FLOAT(OFS_PARM0);
1802 for (i = 1;i < prog->argc;i++)
1803 if (f > PRVM_G_FLOAT((OFS_PARM0+i*3)))
1804 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1805 PRVM_G_FLOAT(OFS_RETURN) = f;
1808 PRVM_G_FLOAT(OFS_RETURN) = min(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1815 returns the maximum of two supplied floats
1817 float max(float a, float b, ...[float])
1820 void VM_max(prvm_prog_t *prog)
1822 VM_SAFEPARMCOUNTRANGE(2, 8, VM_max);
1823 // LadyHavoc: 3+ argument enhancement suggested by FrikaC
1824 if (prog->argc >= 3)
1827 float f = PRVM_G_FLOAT(OFS_PARM0);
1828 for (i = 1;i < prog->argc;i++)
1829 if (f < PRVM_G_FLOAT((OFS_PARM0+i*3)))
1830 f = PRVM_G_FLOAT((OFS_PARM0+i*3));
1831 PRVM_G_FLOAT(OFS_RETURN) = f;
1834 PRVM_G_FLOAT(OFS_RETURN) = max(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1841 returns number bounded by supplied range
1843 float bound(float min, float value, float max)
1846 void VM_bound(prvm_prog_t *prog)
1848 VM_SAFEPARMCOUNT(3,VM_bound);
1849 PRVM_G_FLOAT(OFS_RETURN) = bound(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1), PRVM_G_FLOAT(OFS_PARM2));
1856 returns a raised to power b
1858 float pow(float a, float b)
1861 void VM_pow(prvm_prog_t *prog)
1863 VM_SAFEPARMCOUNT(2,VM_pow);
1864 PRVM_G_FLOAT(OFS_RETURN) = pow(PRVM_G_FLOAT(OFS_PARM0), PRVM_G_FLOAT(OFS_PARM1));
1867 void VM_log(prvm_prog_t *prog)
1869 VM_SAFEPARMCOUNT(1,VM_log);
1870 PRVM_G_FLOAT(OFS_RETURN) = log(PRVM_G_FLOAT(OFS_PARM0));
1873 void VM_Files_Init(prvm_prog_t *prog)
1876 for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1877 prog->openfiles[i] = NULL;
1880 void VM_Files_CloseAll(prvm_prog_t *prog)
1883 for (i = 0;i < PRVM_MAX_OPENFILES;i++)
1885 if (prog->openfiles[i])
1886 FS_Close(prog->openfiles[i]);
1887 prog->openfiles[i] = NULL;
1891 static qfile_t *VM_GetFileHandle(prvm_prog_t *prog, int index)
1893 if (index < 0 || index >= PRVM_MAX_OPENFILES)
1895 Con_Printf("VM_GetFileHandle: invalid file handle %i used in %s\n", index, prog->name);
1898 if (prog->openfiles[index] == NULL)
1900 Con_Printf("VM_GetFileHandle: no such file handle %i (or file has been closed) in %s\n", index, prog->name);
1903 return prog->openfiles[index];
1910 float fopen(string filename, float mode)
1913 // float(string filename, float mode) fopen = #110;
1914 // opens a file inside quake/gamedir/data/ (mode is FILE_READ, FILE_APPEND, or FILE_WRITE),
1915 // returns fhandle >= 0 if successful, or fhandle < 0 if unable to open file for any reason
1916 void VM_fopen(prvm_prog_t *prog)
1919 const char *modestring, *filename;
1922 VM_SAFEPARMCOUNT(2,VM_fopen);
1924 for (filenum = 0;filenum < PRVM_MAX_OPENFILES;filenum++)
1925 if (prog->openfiles[filenum] == NULL)
1927 if (filenum >= PRVM_MAX_OPENFILES)
1929 PRVM_G_FLOAT(OFS_RETURN) = -2;
1930 VM_Warning(prog, "VM_fopen: %s ran out of file handles (%i)\n", prog->name, PRVM_MAX_OPENFILES);
1933 filename = PRVM_G_STRING(OFS_PARM0);
1934 mode = (int)PRVM_G_FLOAT(OFS_PARM1);
1937 case 0: // FILE_READ
1939 prog->openfiles[filenum] = FS_OpenVirtualFile(va(vabuf, sizeof(vabuf), "data/%s", filename), false);
1940 if (prog->openfiles[filenum] == NULL)
1941 prog->openfiles[filenum] = FS_OpenVirtualFile(va(vabuf, sizeof(vabuf), "%s", filename), false);
1943 case 1: // FILE_APPEND
1945 prog->openfiles[filenum] = FS_OpenRealFile(va(vabuf, sizeof(vabuf), "data/%s", filename), modestring, false);
1947 case 2: // FILE_WRITE
1949 prog->openfiles[filenum] = FS_OpenRealFile(va(vabuf, sizeof(vabuf), "data/%s", filename), modestring, false);
1952 PRVM_G_FLOAT(OFS_RETURN) = -3;
1953 VM_Warning(prog, "VM_fopen: %s: no such mode %i (valid: 0 = read, 1 = append, 2 = write)\n", prog->name, mode);
1957 if (prog->openfiles[filenum] == NULL)
1959 PRVM_G_FLOAT(OFS_RETURN) = -1;
1960 if (developer_extra.integer)
1961 VM_Warning(prog, "VM_fopen: %s: %s mode %s failed\n", prog->name, filename, modestring);
1965 PRVM_G_FLOAT(OFS_RETURN) = filenum;
1966 if (developer_extra.integer)
1967 Con_DPrintf("VM_fopen: %s: %s mode %s opened as #%i\n", prog->name, filename, modestring, filenum);
1968 prog->openfiles_origin[filenum] = PRVM_AllocationOrigin(prog);
1976 fclose(float fhandle)
1979 //void(float fhandle) fclose = #111; // closes a file
1980 void VM_fclose(prvm_prog_t *prog)
1984 VM_SAFEPARMCOUNT(1,VM_fclose);
1986 filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
1987 if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
1989 VM_Warning(prog, "VM_fclose: invalid file handle %i used in %s\n", filenum, prog->name);
1992 if (prog->openfiles[filenum] == NULL)
1994 VM_Warning(prog, "VM_fclose: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
1997 FS_Close(prog->openfiles[filenum]);
1998 prog->openfiles[filenum] = NULL;
1999 if(prog->openfiles_origin[filenum])
2000 PRVM_Free((char *)prog->openfiles_origin[filenum]);
2001 if (developer_extra.integer)
2002 Con_DPrintf("VM_fclose: %s: #%i closed\n", prog->name, filenum);
2009 string fgets(float fhandle)
2012 //string(float fhandle) fgets = #112; // reads a line of text from the file and returns as a tempstring
2013 void VM_fgets(prvm_prog_t *prog)
2016 char string[VM_TEMPSTRING_MAXSIZE];
2019 VM_SAFEPARMCOUNT(1,VM_fgets);
2021 // set the return value regardless of any possible errors
2022 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
2024 filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
2025 if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
2027 VM_Warning(prog, "VM_fgets: invalid file handle %i used in %s\n", filenum, prog->name);
2030 if (prog->openfiles[filenum] == NULL)
2032 VM_Warning(prog, "VM_fgets: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
2038 c = FS_Getc(prog->openfiles[filenum]);
2039 if (c == '\r' || c == '\n' || c < 0)
2041 if (end < VM_TEMPSTRING_MAXSIZE - 1)
2045 // remove \n following \r
2048 c = FS_Getc(prog->openfiles[filenum]);
2050 FS_UnGetc(prog->openfiles[filenum], (unsigned char)c);
2052 if (developer_extra.integer)
2053 Con_DPrintf("fgets: %s: %s\n", prog->name, string);
2055 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string, end);
2062 fputs(float fhandle, string s)
2065 //void(float fhandle, string s) fputs = #113; // writes a line of text to the end of the file
2066 void VM_fputs(prvm_prog_t *prog)
2068 size_t stringlength;
2069 char string[VM_TEMPSTRING_MAXSIZE];
2072 VM_SAFEPARMCOUNT(2,VM_fputs);
2074 filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
2075 if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
2077 VM_Warning(prog, "VM_fputs: invalid file handle %i used in %s\n", filenum, prog->name);
2080 if (prog->openfiles[filenum] == NULL)
2082 VM_Warning(prog, "VM_fputs: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
2085 stringlength = VM_VarString(prog, 1, string, sizeof(string));
2087 FS_Write(prog->openfiles[filenum], string, stringlength);
2088 if (developer_extra.integer)
2089 Con_DPrintf("fputs: %s: %s\n", prog->name, string);
2096 writetofile(float fhandle, entity ent)
2099 void VM_writetofile(prvm_prog_t *prog)
2104 VM_SAFEPARMCOUNT(2, VM_writetofile);
2106 file = VM_GetFileHandle(prog, (int)PRVM_G_FLOAT(OFS_PARM0));
2109 VM_Warning(prog, "VM_writetofile: invalid or closed file handle\n");
2113 ent = PRVM_G_EDICT(OFS_PARM1);
2116 VM_Warning(prog, "VM_writetofile: %s: entity %i is free !\n", prog->name, PRVM_NUM_FOR_EDICT(ent));
2120 PRVM_ED_Write (prog, file, ent);
2123 // KrimZon - DP_QC_ENTITYDATA
2128 float() numentityfields
2129 Return the number of entity fields - NOT offsets
2132 void VM_numentityfields(prvm_prog_t *prog)
2134 PRVM_G_FLOAT(OFS_RETURN) = prog->numfielddefs;
2137 // KrimZon - DP_QC_ENTITYDATA
2142 string(float fieldnum) entityfieldname
2143 Return name of the specified field as a string, or empty if the field is invalid (warning)
2146 void VM_entityfieldname(prvm_prog_t *prog)
2149 int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2151 if (i < 0 || i >= prog->numfielddefs)
2153 VM_Warning(prog, "VM_entityfieldname: %s: field index out of bounds\n", prog->name);
2154 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
2158 d = &prog->fielddefs[i];
2159 PRVM_G_INT(OFS_RETURN) = d->s_name; // presuming that s_name points to a string already
2162 // KrimZon - DP_QC_ENTITYDATA
2167 float(float fieldnum) entityfieldtype
2170 void VM_entityfieldtype(prvm_prog_t *prog)
2173 int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2175 if (i < 0 || i >= prog->numfielddefs)
2177 VM_Warning(prog, "VM_entityfieldtype: %s: field index out of bounds\n", prog->name);
2178 PRVM_G_FLOAT(OFS_RETURN) = -1.0;
2182 d = &prog->fielddefs[i];
2183 PRVM_G_FLOAT(OFS_RETURN) = (prvm_vec_t)d->type;
2186 // KrimZon - DP_QC_ENTITYDATA
2189 VM_getentityfieldstring
2191 string(float fieldnum, entity ent) getentityfieldstring
2194 void VM_getentityfieldstring(prvm_prog_t *prog)
2196 // put the data into a string
2201 int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2202 char valuebuf[MAX_INPUTLINE];
2204 if (i < 0 || i >= prog->numfielddefs)
2206 VM_Warning(prog, "VM_entityfielddata: %s: field index out of bounds\n", prog->name);
2207 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
2211 d = &prog->fielddefs[i];
2214 ent = PRVM_G_EDICT(OFS_PARM1);
2217 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
2218 VM_Warning(prog, "VM_entityfielddata: %s: entity %i is free !\n", prog->name, PRVM_NUM_FOR_EDICT(ent));
2221 val = (prvm_eval_t *)(ent->fields.fp + d->ofs);
2223 // if it's 0 or blank, return an empty string
2224 type = d->type & ~DEF_SAVEGLOBAL;
2225 for (j=0 ; j<prvm_type_size[type] ; j++)
2226 if (val->ivector[j])
2228 if (j == prvm_type_size[type])
2230 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
2234 PRVM_UglyValueString(prog, (etype_t)d->type, val, valuebuf, sizeof(valuebuf));
2235 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, valuebuf, strlen(valuebuf));
2238 // KrimZon - DP_QC_ENTITYDATA
2241 VM_putentityfieldstring
2243 float(float fieldnum, entity ent, string s) putentityfieldstring
2246 void VM_putentityfieldstring(prvm_prog_t *prog)
2250 int i = (int)PRVM_G_FLOAT(OFS_PARM0);
2252 if (i < 0 || i >= prog->numfielddefs)
2254 VM_Warning(prog, "VM_entityfielddata: %s: field index out of bounds\n", prog->name);
2255 PRVM_G_FLOAT(OFS_RETURN) = 0.0f;
2259 d = &prog->fielddefs[i];
2262 ent = PRVM_G_EDICT(OFS_PARM1);
2265 VM_Warning(prog, "VM_entityfielddata: %s: entity %i is free !\n", prog->name, PRVM_NUM_FOR_EDICT(ent));
2266 PRVM_G_FLOAT(OFS_RETURN) = 0.0f;
2270 // parse the string into the value
2271 PRVM_G_FLOAT(OFS_RETURN) = ( PRVM_ED_ParseEpair(prog, ent, d, PRVM_G_STRING(OFS_PARM2), false) ) ? 1.0f : 0.0f;
2278 float strlen(string s)
2281 //float(string s) strlen = #114; // returns how many characters are in a string
2282 void VM_strlen(prvm_prog_t *prog)
2284 VM_SAFEPARMCOUNT(1,VM_strlen);
2286 //PRVM_G_FLOAT(OFS_RETURN) = strlen(PRVM_G_STRING(OFS_PARM0));
2287 PRVM_G_FLOAT(OFS_RETURN) = u8_strlen(PRVM_G_STRING(OFS_PARM0));
2290 // DRESK - Decolorized String
2295 string strdecolorize(string s)
2298 // string (string s) strdecolorize = #472; // returns the passed in string with color codes stripped
2299 void VM_strdecolorize(prvm_prog_t *prog)
2301 char szNewString[VM_TEMPSTRING_MAXSIZE];
2302 size_t szNewString_len;
2303 const char *szString;
2306 VM_SAFEPARMCOUNT(1,VM_strdecolorize);
2307 szString = PRVM_G_STRING(OFS_PARM0);
2308 szNewString_len = COM_StringDecolorize(szString, 0, szNewString, sizeof(szNewString), true);
2309 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString, szNewString_len);
2312 // DRESK - String Length (not counting color codes)
2317 float strlennocol(string s)
2320 // float(string s) strlennocol = #471; // returns how many characters are in a string not including color codes
2321 // For example, ^2Dresk returns a length of 5
2322 void VM_strlennocol(prvm_prog_t *prog)
2324 const char *szString;
2327 VM_SAFEPARMCOUNT(1,VM_strlennocol);
2329 szString = PRVM_G_STRING(OFS_PARM0);
2331 //nCnt = (int)COM_StringLengthNoColors(szString, 0, NULL);
2332 nCnt = (int)u8_COM_StringLengthNoColors(szString, 0, NULL);
2334 PRVM_G_FLOAT(OFS_RETURN) = nCnt;
2337 // DRESK - String to Uppercase and Lowercase
2342 string strtolower(string s)
2345 // string (string s) strtolower = #480; // returns passed in string in lowercase form
2346 void VM_strtolower(prvm_prog_t *prog)
2348 char szNewString[VM_TEMPSTRING_MAXSIZE];
2349 size_t szNewString_len;
2350 const char *szString;
2353 VM_SAFEPARMCOUNT(1,VM_strtolower);
2354 szString = PRVM_G_STRING(OFS_PARM0);
2356 szNewString_len = COM_ToLowerString(szString, szNewString, sizeof(szNewString) );
2358 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString, szNewString_len);
2365 string strtoupper(string s)
2368 // string (string s) strtoupper = #481; // returns passed in string in uppercase form
2369 void VM_strtoupper(prvm_prog_t *prog)
2371 char szNewString[VM_TEMPSTRING_MAXSIZE];
2372 size_t szNewString_len;
2373 const char *szString;
2376 VM_SAFEPARMCOUNT(1,VM_strtoupper);
2377 szString = PRVM_G_STRING(OFS_PARM0);
2379 szNewString_len = COM_ToUpperString(szString, szNewString, sizeof(szNewString) );
2381 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString, szNewString_len);
2388 string strcat(string s, string...)
2391 //string(string s, string...) strcat = #115;
2392 // concatenates strings (for example "abc", "def" would return "abcdef")
2393 // and returns as a tempstring
2394 void VM_strcat(prvm_prog_t *prog)
2396 char s[VM_TEMPSTRING_MAXSIZE];
2399 VM_SAFEPARMCOUNTRANGE(1, 8, VM_strcat);
2401 slen = VM_VarString(prog, 0, s, sizeof(s));
2402 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, s, slen);
2409 string substring(string s, float start, float length)
2412 // string(string s, float start, float length) substring = #116;
2413 // returns a section of a string as a tempstring
2414 void VM_substring(prvm_prog_t *prog)
2417 int u_slength = 0, u_start;
2420 char string[VM_TEMPSTRING_MAXSIZE];
2422 VM_SAFEPARMCOUNT(3,VM_substring);
2425 s = PRVM_G_STRING(OFS_PARM0);
2426 start = (int)PRVM_G_FLOAT(OFS_PARM1);
2427 length = (int)PRVM_G_FLOAT(OFS_PARM2);
2428 slength = strlen(s);
2430 if (start < 0) // FTE_STRINGS feature
2432 start = bound(0, start, slength);
2434 if (length < 0) // FTE_STRINGS feature
2435 length += slength - start + 1;
2436 maxlen = min((int)sizeof(string) - 1, slength - start);
2437 length = bound(0, length, maxlen);
2439 memcpy(string, s + start, length);
2441 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string);
2444 s = PRVM_G_STRING(OFS_PARM0);
2445 start = (int)PRVM_G_FLOAT(OFS_PARM1);
2446 length = (int)PRVM_G_FLOAT(OFS_PARM2);
2448 if (start < 0) // FTE_STRINGS feature
2450 u_slength = (int)u8_strlen(s);
2452 start = bound(0, start, u_slength);
2455 if (length < 0) // FTE_STRINGS feature
2457 if (!u_slength) // it's not calculated when it's not needed above
2458 u_slength = (int)u8_strlen(s);
2459 length += u_slength - start + 1;
2462 // positive start, positive length
2463 u_start = u8_byteofs(s, start, NULL);
2466 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
2469 u_length = u8_bytelen(s + u_start, length);
2470 if (u_length >= sizeof(string)-1)
2471 u_length = sizeof(string)-1;
2473 memcpy(string, s + u_start, u_length);
2474 string[u_length] = '\0';
2475 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string, u_length);
2482 string(string search, string replace, string subject) strreplace = #484;
2485 // replaces all occurrences of search with replace in the string subject, and returns the result
2486 void VM_strreplace(prvm_prog_t *prog)
2489 const char *search, *replace, *subject;
2490 char string[VM_TEMPSTRING_MAXSIZE];
2491 int search_len, replace_len, subject_len;
2493 VM_SAFEPARMCOUNT(3,VM_strreplace);
2495 search = PRVM_G_STRING(OFS_PARM0);
2496 replace = PRVM_G_STRING(OFS_PARM1);
2497 subject = PRVM_G_STRING(OFS_PARM2);
2499 search_len = (int)strlen(search);
2500 replace_len = (int)strlen(replace);
2501 subject_len = (int)strlen(subject);
2504 for (i = 0; i <= subject_len - search_len; i++)
2506 for (j = 0; j < search_len; j++) // thus, i+j < subject_len
2507 if (subject[i+j] != search[j])
2509 if (j == search_len)
2511 // NOTE: if search_len == 0, we always hit THIS case, and never the other
2512 // found it at offset 'i'
2513 for (j = 0; j < replace_len && si < (int)sizeof(string) - 1; j++)
2514 string[si++] = replace[j];
2517 i += search_len - 1;
2521 // the above would subtract 1 from i... so we
2522 // don't do that, but instead output the next
2524 if (si < (int)sizeof(string) - 1)
2525 string[si++] = subject[i];
2530 // in THIS case, we know search_len > 0, thus i < subject_len
2532 if (si < (int)sizeof(string) - 1)
2533 string[si++] = subject[i];
2536 // remaining chars (these cannot match)
2537 for (; i < subject_len; i++)
2538 if (si < (int)sizeof(string) - 1)
2539 string[si++] = subject[i];
2542 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string, si);
2549 string(string search, string replace, string subject) strireplace = #485;
2552 // case-insensitive version of strreplace
2553 void VM_strireplace(prvm_prog_t *prog)
2556 const char *search, *replace, *subject;
2557 char string[VM_TEMPSTRING_MAXSIZE];
2558 int search_len, replace_len, subject_len;
2560 VM_SAFEPARMCOUNT(3, VM_strireplace);
2562 search = PRVM_G_STRING(OFS_PARM0);
2563 replace = PRVM_G_STRING(OFS_PARM1);
2564 subject = PRVM_G_STRING(OFS_PARM2);
2566 search_len = (int)strlen(search);
2567 replace_len = (int)strlen(replace);
2568 subject_len = (int)strlen(subject);
2571 for (i = 0; i <= subject_len - search_len; i++)
2573 for (j = 0; j < search_len; j++) // thus, i+j < subject_len
2574 if (tolower(subject[i+j]) != tolower(search[j]))
2576 if (j == search_len)
2578 // NOTE: if search_len == 0, we always hit THIS case, and never the other
2579 // found it at offset 'i'
2580 for (j = 0; j < replace_len && si < (int)sizeof(string) - 1; j++)
2581 string[si++] = replace[j];
2584 i += search_len - 1;
2588 // the above would subtract 1 from i... so we
2589 // don't do that, but instead output the next
2591 if (si < (int)sizeof(string) - 1)
2592 string[si++] = subject[i];
2597 // in THIS case, we know search_len > 0, thus i < subject_len
2599 if (si < (int)sizeof(string) - 1)
2600 string[si++] = subject[i];
2603 // remaining chars (these cannot match)
2604 for (; i < subject_len; i++)
2605 if (si < (int)sizeof(string) - 1)
2606 string[si++] = subject[i];
2609 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string, si);
2616 vector stov(string s)
2619 //vector(string s) stov = #117; // returns vector value from a string
2620 void VM_stov(prvm_prog_t *prog)
2622 char string[VM_TEMPSTRING_MAXSIZE];
2624 VM_SAFEPARMCOUNT(1,VM_stov);
2626 VM_VarString(prog, 0, string, sizeof(string));
2627 Math_atov(string, PRVM_G_VECTOR(OFS_RETURN));
2634 string strzone(string s)
2637 //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)
2638 void VM_strzone(prvm_prog_t *prog)
2641 char string[VM_TEMPSTRING_MAXSIZE];
2644 VM_SAFEPARMCOUNT(1,VM_strzone);
2646 alloclen = VM_VarString(prog, 0, string, sizeof(string)) + 1;
2647 PRVM_G_INT(OFS_RETURN) = PRVM_AllocString(prog, alloclen, &out);
2648 memcpy(out, string, alloclen);
2658 //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!!!)
2659 void VM_strunzone(prvm_prog_t *prog)
2661 VM_SAFEPARMCOUNT(1,VM_strunzone);
2662 PRVM_FreeString(prog, PRVM_G_INT(OFS_PARM0));
2669 float tokenize(string s)
2672 //float(string s) tokenize = #441; // takes apart a string into individal words (access them with argv), returns how many
2673 //this function originally written by KrimZon, made shorter by LadyHavoc
2674 //20040203: rewritten by LadyHavoc (no longer uses allocations)
2675 static int num_tokens = 0;
2676 static int tokens[VM_TEMPSTRING_MAXSIZE / 2];
2677 static int tokens_startpos[VM_TEMPSTRING_MAXSIZE / 2];
2678 static int tokens_endpos[VM_TEMPSTRING_MAXSIZE / 2];
2679 static char tokenize_string[VM_TEMPSTRING_MAXSIZE];
2680 void VM_tokenize (prvm_prog_t *prog)
2684 VM_SAFEPARMCOUNT(1,VM_tokenize);
2686 dp_strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2687 p = tokenize_string;
2692 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
2695 // skip whitespace here to find token start pos
2696 while(*p && ISWHITESPACE(*p))
2699 tokens_startpos[num_tokens] = p - tokenize_string;
2700 if(!COM_ParseToken_VM_Tokenize(&p, false))
2702 tokens_endpos[num_tokens] = p - tokenize_string;
2703 tokens[num_tokens] = PRVM_SetTempString(prog, com_token, com_token_len);
2707 PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2710 //float(string s) tokenize = #514; // takes apart a string into individal words (access them with argv), returns how many
2711 void VM_tokenize_console (prvm_prog_t *prog)
2715 VM_SAFEPARMCOUNT(1, VM_tokenize_console);
2717 dp_strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2718 p = tokenize_string;
2723 if (num_tokens >= (int)(sizeof(tokens)/sizeof(tokens[0])))
2726 // skip whitespace here to find token start pos
2727 while(*p && ISWHITESPACE(*p))
2730 tokens_startpos[num_tokens] = p - tokenize_string;
2731 if(!COM_ParseToken_Console(&p))
2733 tokens_endpos[num_tokens] = p - tokenize_string;
2734 tokens[num_tokens] = PRVM_SetTempString(prog, com_token, com_token_len);
2738 PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2743 VM_tokenizebyseparator
2745 float tokenizebyseparator(string s, string separator1, ...)
2748 //float(string s, string separator1, ...) tokenizebyseparator = #479; // takes apart a string into individal words (access them with argv), returns how many
2749 //this function returns the token preceding each instance of a separator (of
2750 //which there can be multiple), and the text following the last separator
2751 //useful for parsing certain kinds of data like IP addresses
2753 //numnumbers = tokenizebyseparator("10.1.2.3", ".");
2754 //returns 4 and the tokens "10" "1" "2" "3".
2755 void VM_tokenizebyseparator (prvm_prog_t *prog)
2759 int separatorlen[7];
2760 const char *separators[7];
2763 char tokentext[MAX_INPUTLINE];
2765 VM_SAFEPARMCOUNTRANGE(2, 8,VM_tokenizebyseparator);
2767 dp_strlcpy(tokenize_string, PRVM_G_STRING(OFS_PARM0), sizeof(tokenize_string));
2768 p = tokenize_string;
2771 for (j = 1;j < prog->argc;j++)
2773 // skip any blank separator strings
2774 const char *s = PRVM_G_STRING(OFS_PARM0+j*3);
2777 separators[numseparators] = s;
2778 separatorlen[numseparators] = (int)strlen(s);
2785 while (num_tokens < (int)(sizeof(tokens)/sizeof(tokens[0])))
2787 token = tokentext + j;
2788 tokens_startpos[num_tokens] = p - tokenize_string;
2792 for (k = 0;k < numseparators;k++)
2794 if (!strncmp(p, separators[k], separatorlen[k]))
2796 p += separatorlen[k];
2800 if (k < numseparators)
2802 if (j < (int)sizeof(tokentext)-1)
2803 tokentext[j++] = *p;
2807 tokens_endpos[num_tokens] = p0 - tokenize_string;
2808 if (j >= (int)sizeof(tokentext))
2810 tokentext[j++] = '\0';
2811 tokens[num_tokens++] = PRVM_SetTempString(prog, token, j - 1);
2816 PRVM_G_FLOAT(OFS_RETURN) = num_tokens;
2819 //string(float n) argv = #442; // returns a word from the tokenized string (returns nothing for an invalid index)
2820 //this function originally written by KrimZon, made shorter by LadyHavoc
2821 void VM_argv (prvm_prog_t *prog)
2825 VM_SAFEPARMCOUNT(1,VM_argv);
2827 token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2830 token_num += num_tokens;
2832 if (token_num >= 0 && token_num < num_tokens)
2833 PRVM_G_INT(OFS_RETURN) = tokens[token_num];
2835 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
2838 //float(float n) argv_start_index = #515; // returns the start index of a token
2839 void VM_argv_start_index (prvm_prog_t *prog)
2843 VM_SAFEPARMCOUNT(1,VM_argv);
2845 token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2848 token_num += num_tokens;
2850 if (token_num >= 0 && token_num < num_tokens)
2851 PRVM_G_FLOAT(OFS_RETURN) = tokens_startpos[token_num];
2853 PRVM_G_FLOAT(OFS_RETURN) = -1;
2856 //float(float n) argv_end_index = #516; // returns the end index of a token
2857 void VM_argv_end_index (prvm_prog_t *prog)
2861 VM_SAFEPARMCOUNT(1,VM_argv);
2863 token_num = (int)PRVM_G_FLOAT(OFS_PARM0);
2866 token_num += num_tokens;
2868 if (token_num >= 0 && token_num < num_tokens)
2869 PRVM_G_FLOAT(OFS_RETURN) = tokens_endpos[token_num];
2871 PRVM_G_FLOAT(OFS_RETURN) = -1;
2881 void VM_isserver(prvm_prog_t *prog)
2883 VM_SAFEPARMCOUNT(0, VM_isserver);
2885 PRVM_G_FLOAT(OFS_RETURN) = sv.active;
2895 void VM_clientcount(prvm_prog_t *prog)
2897 VM_SAFEPARMCOUNT(0,VM_clientcount);
2899 PRVM_G_FLOAT(OFS_RETURN) = svs.maxclients;
2909 void VM_clientstate(prvm_prog_t *prog)
2911 VM_SAFEPARMCOUNT(0,VM_clientstate);
2914 switch( cls.state ) {
2915 case ca_uninitialized:
2917 PRVM_G_FLOAT(OFS_RETURN) = 0;
2919 case ca_disconnected:
2920 PRVM_G_FLOAT(OFS_RETURN) = 1;
2923 PRVM_G_FLOAT(OFS_RETURN) = 2;
2926 // should never be reached!
2935 float getostype(prvm_prog_t *prog)
2937 */ // not used at the moment -> not included in the common list
2938 void VM_getostype(prvm_prog_t *prog)
2940 VM_SAFEPARMCOUNT(0,VM_getostype);
2945 OS_MAC - not supported
2949 PRVM_G_FLOAT(OFS_RETURN) = 0;
2950 #elif defined(MACOSX)
2951 PRVM_G_FLOAT(OFS_RETURN) = 2;
2953 PRVM_G_FLOAT(OFS_RETURN) = 1;
2961 float gettime(prvm_prog_t *prog)
2964 float CDAudio_GetPosition(void);
2965 void VM_gettime(prvm_prog_t *prog)
2969 VM_SAFEPARMCOUNTRANGE(0,1,VM_gettime);
2973 PRVM_G_FLOAT(OFS_RETURN) = (prvm_vec_t) host.realtime;
2977 timer_index = (int) PRVM_G_FLOAT(OFS_PARM0);
2980 case 0: // GETTIME_FRAMESTART
2981 PRVM_G_FLOAT(OFS_RETURN) = host.realtime;
2983 case 1: // GETTIME_REALTIME
2984 PRVM_G_FLOAT(OFS_RETURN) = Sys_DirtyTime();
2986 case 2: // GETTIME_HIRES
2987 PRVM_G_FLOAT(OFS_RETURN) = (Sys_DirtyTime() - host.dirtytime);
2989 case 3: // GETTIME_UPTIME
2990 PRVM_G_FLOAT(OFS_RETURN) = host.realtime;
2992 case 4: // GETTIME_CDTRACK
2993 PRVM_G_FLOAT(OFS_RETURN) = CDAudio_GetPosition();
2996 VM_Warning(prog, "VM_gettime: %s: unsupported timer specified, returning realtime\n", prog->name);
2997 PRVM_G_FLOAT(OFS_RETURN) = host.realtime;
3007 float getsoundtime(prvm_prog_t *prog)
3011 void VM_getsoundtime (prvm_prog_t *prog)
3013 int entnum, entchannel;
3014 VM_SAFEPARMCOUNT(2,VM_getsoundtime);
3016 if (prog == SVVM_prog)
3017 entnum = PRVM_NUM_FOR_EDICT(PRVM_G_EDICT(OFS_PARM0));
3018 else if (prog == CLVM_prog)
3019 entnum = MAX_EDICTS + PRVM_NUM_FOR_EDICT(PRVM_G_EDICT(OFS_PARM0));
3022 VM_Warning(prog, "VM_getsoundtime: %s: not supported on this progs\n", prog->name);
3023 PRVM_G_FLOAT(OFS_RETURN) = -1;
3026 entchannel = (int)PRVM_G_FLOAT(OFS_PARM1);
3027 entchannel = CHAN_USER2ENGINE(entchannel);
3028 if (!IS_CHAN(entchannel))
3029 VM_Warning(prog, "VM_getsoundtime: %s: bad channel %i\n", prog->name, entchannel);
3030 PRVM_G_FLOAT(OFS_RETURN) = (prvm_vec_t)S_GetEntChannelPosition(entnum, entchannel);
3037 string soundlength (string sample)
3040 void VM_soundlength (prvm_prog_t *prog)
3044 VM_SAFEPARMCOUNT(1, VM_soundlength);
3046 s = PRVM_G_STRING(OFS_PARM0);
3047 PRVM_G_FLOAT(OFS_RETURN) = S_SoundLength(s);
3054 loadfromdata(string data)
3057 void VM_loadfromdata(prvm_prog_t *prog)
3059 VM_SAFEPARMCOUNT(1, VM_loadfromdata);
3061 PRVM_ED_LoadFromFile(prog, PRVM_G_STRING(OFS_PARM0));
3065 ========================
3068 parseentitydata(entity ent, string data)
3069 ========================
3071 void VM_parseentitydata(prvm_prog_t *prog)
3076 VM_SAFEPARMCOUNT(2, VM_parseentitydata);
3078 // get edict and test it
3079 ent = PRVM_G_EDICT(OFS_PARM0);
3081 prog->error_cmd("VM_parseentitydata: %s: Can only set already spawned entities (entity %i is free)!", prog->name, PRVM_NUM_FOR_EDICT(ent));
3083 data = PRVM_G_STRING(OFS_PARM1);
3085 // parse the opening brace
3086 if (!COM_ParseToken_Simple(&data, false, false, true) || com_token[0] != '{' )
3087 prog->error_cmd("VM_parseentitydata: %s: Couldn't parse entity data:\n%s", prog->name, data );
3089 PRVM_ED_ParseEdict (prog, data, ent);
3096 loadfromfile(string file)
3099 void VM_loadfromfile(prvm_prog_t *prog)
3101 const char *filename;
3104 VM_SAFEPARMCOUNT(1,VM_loadfromfile);
3106 filename = PRVM_G_STRING(OFS_PARM0);
3107 if (FS_CheckNastyPath(filename, false))
3109 PRVM_G_FLOAT(OFS_RETURN) = -4;
3110 VM_Warning(prog, "VM_loadfromfile: %s dangerous or non-portable filename \"%s\" not allowed. (contains : or \\ or begins with .. or /)\n", prog->name, filename);
3114 // not conform with VM_fopen
3115 data = (char *)FS_LoadFile(filename, tempmempool, false, NULL);
3117 PRVM_G_FLOAT(OFS_RETURN) = -1;
3119 PRVM_ED_LoadFromFile(prog, data);
3130 float mod(float val, float m)
3133 void VM_modulo(prvm_prog_t *prog)
3137 VM_SAFEPARMCOUNT(2, VM_modulo);
3139 val = PRVM_G_FLOAT(OFS_PARM0);
3140 m = PRVM_G_FLOAT(OFS_PARM1);
3142 // matches how gmqcc implements % when mod() builtin isn't defined, and FTEQW mod()
3144 PRVM_G_FLOAT(OFS_RETURN) = val - m * (prvm_int_t)(val / m);
3147 VM_Warning(prog, "Attempted modulo of %f by zero\n", val);
3148 PRVM_G_FLOAT(OFS_RETURN) = 0;
3152 static void VM_Search_Init(prvm_prog_t *prog)
3155 for (i = 0;i < PRVM_MAX_OPENSEARCHES;i++)
3156 prog->opensearches[i] = NULL;
3159 static void VM_Search_Reset(prvm_prog_t *prog)
3162 // reset the fssearch list
3163 for(i = 0; i < PRVM_MAX_OPENSEARCHES; i++)
3165 if(prog->opensearches[i])
3166 FS_FreeSearch(prog->opensearches[i]);
3167 prog->opensearches[i] = NULL;
3175 float search_begin(string pattern, float caseinsensitive, float quiet[, string packfile])
3178 void VM_search_begin(prvm_prog_t *prog)
3181 const char *packfile = NULL, *pattern;
3182 int caseinsens, quiet;
3184 VM_SAFEPARMCOUNTRANGE(3, 4, VM_search_begin);
3186 pattern = PRVM_G_STRING(OFS_PARM0);
3188 VM_CheckEmptyString(prog, pattern);
3190 caseinsens = (int)PRVM_G_FLOAT(OFS_PARM1);
3191 quiet = (int)PRVM_G_FLOAT(OFS_PARM2);
3193 // optional packfile parameter (DP_QC_FS_SEARCH_PACKFILE)
3195 packfile = PRVM_G_STRING(OFS_PARM3);
3197 for(handle = 0; handle < PRVM_MAX_OPENSEARCHES; handle++)
3198 if(!prog->opensearches[handle])
3201 if(handle >= PRVM_MAX_OPENSEARCHES)
3203 PRVM_G_FLOAT(OFS_RETURN) = -2;
3204 VM_Warning(prog, "VM_search_begin: %s ran out of search handles (%i)\n", prog->name, PRVM_MAX_OPENSEARCHES);
3208 if(!(prog->opensearches[handle] = FS_Search(pattern,caseinsens, quiet, packfile)))
3209 PRVM_G_FLOAT(OFS_RETURN) = -1;
3212 prog->opensearches_origin[handle] = PRVM_AllocationOrigin(prog);
3213 PRVM_G_FLOAT(OFS_RETURN) = handle;
3221 void search_end(float handle)
3224 void VM_search_end(prvm_prog_t *prog)
3227 VM_SAFEPARMCOUNT(1, VM_search_end);
3229 handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3231 if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3233 VM_Warning(prog, "VM_search_end: invalid handle %i used in %s\n", handle, prog->name);
3236 if(prog->opensearches[handle] == NULL)
3238 VM_Warning(prog, "VM_search_end: no such handle %i in %s\n", handle, prog->name);
3242 FS_FreeSearch(prog->opensearches[handle]);
3243 prog->opensearches[handle] = NULL;
3244 if(prog->opensearches_origin[handle])
3245 PRVM_Free((char *)prog->opensearches_origin[handle]);
3252 float search_getsize(float handle)
3255 void VM_search_getsize(prvm_prog_t *prog)
3258 VM_SAFEPARMCOUNT(1, VM_search_getsize);
3260 handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3262 if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3264 VM_Warning(prog, "VM_search_getsize: invalid handle %i used in %s\n", handle, prog->name);
3267 if(prog->opensearches[handle] == NULL)
3269 VM_Warning(prog, "VM_search_getsize: no such handle %i in %s\n", handle, prog->name);
3273 PRVM_G_FLOAT(OFS_RETURN) = prog->opensearches[handle]->numfilenames;
3278 VM_search_getfilename
3280 string search_getfilename(float handle, float num)
3283 void VM_search_getfilename(prvm_prog_t *prog)
3285 int handle, filenum;
3287 VM_SAFEPARMCOUNT(2, VM_search_getfilename);
3289 handle = (int)PRVM_G_FLOAT(OFS_PARM0);
3290 filenum = (int)PRVM_G_FLOAT(OFS_PARM1);
3292 if(handle < 0 || handle >= PRVM_MAX_OPENSEARCHES)
3294 VM_Warning(prog, "VM_search_getfilename: invalid handle %i used in %s\n", handle, prog->name);
3297 if(prog->opensearches[handle] == NULL)
3299 VM_Warning(prog, "VM_search_getfilename: no such handle %i in %s\n", handle, prog->name);
3302 if(filenum < 0 || filenum >= prog->opensearches[handle]->numfilenames)
3304 VM_Warning(prog, "VM_search_getfilename: invalid filenum %i in %s\n", filenum, prog->name);
3308 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog,
3309 prog->opensearches[handle]->filenames[filenum],
3310 strlen(prog->opensearches[handle]->filenames[filenum]));
3317 string chr(float ascii)
3320 void VM_chr(prvm_prog_t *prog)
3324 VM_SAFEPARMCOUNT(1, VM_chr);
3326 tmp[0] = (unsigned char) PRVM_G_FLOAT(OFS_PARM0);
3329 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, tmp);
3335 VM_SAFEPARMCOUNT(1, VM_chr);
3336 len = u8_fromchar((Uchar)PRVM_G_FLOAT(OFS_PARM0), tmp, sizeof(tmp));
3338 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, tmp, len);
3345 string keynumtostring(float keynum)
3348 void VM_keynumtostring (prvm_prog_t *prog)
3350 char tinystr[TINYSTR_LEN];
3351 const char *str; // Key_KeynumToString doesn't always return tinystr
3353 VM_SAFEPARMCOUNT(1, VM_keynumtostring);
3354 str = Key_KeynumToString((int)PRVM_G_FLOAT(OFS_PARM0), tinystr, sizeof(tinystr));
3355 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, str, strlen(str));
3360 VM_findkeysforcommand
3362 string findkeysforcommand(string command, float bindmap)
3364 the returned string is an altstring
3367 #define FKFC_NUMKEYS 5
3368 void M_FindKeysForCommand(const char *command, int *keys);
3369 void VM_findkeysforcommand(prvm_prog_t *prog)
3372 char ret[VM_TEMPSTRING_MAXSIZE];
3374 int keys[FKFC_NUMKEYS];
3379 VM_SAFEPARMCOUNTRANGE(1, 2, VM_findkeysforcommand);
3381 cmd = PRVM_G_STRING(OFS_PARM0);
3383 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM1), MAX_BINDMAPS-1);
3385 bindmap = 0; // consistent to "bind"
3387 VM_CheckEmptyString(prog, cmd);
3389 Key_FindKeysForCommand(cmd, keys, FKFC_NUMKEYS, bindmap);
3392 for(i = 0; i < FKFC_NUMKEYS; i++)
3393 ret_len = dp_strlcat(ret, va(vabuf, sizeof(vabuf), " \'%i\'", keys[i]), sizeof(ret));
3395 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, ret, ret_len);
3402 float stringtokeynum(string key)
3405 void VM_stringtokeynum (prvm_prog_t *prog)
3407 VM_SAFEPARMCOUNT( 1, VM_stringtokeynum );
3409 PRVM_G_FLOAT(OFS_RETURN) = Key_StringToKeynum(PRVM_G_STRING(OFS_PARM0));
3416 string getkeybind(float key, float bindmap)
3419 void VM_getkeybind (prvm_prog_t *prog)
3424 VM_SAFEPARMCOUNTRANGE(1, 2, VM_getkeybind);
3426 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM1), MAX_BINDMAPS-1);
3428 bindmap = 0; // consistent to "bind"
3429 bind = Key_GetBind((int)PRVM_G_FLOAT(OFS_PARM0), bindmap);
3430 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, bind, strlen(bind));
3437 float setkeybind(float key, string cmd, float bindmap)
3440 void VM_setkeybind (prvm_prog_t *prog)
3443 VM_SAFEPARMCOUNTRANGE(2, 3, VM_setkeybind);
3445 bindmap = bound(-1, PRVM_G_FLOAT(OFS_PARM2), MAX_BINDMAPS-1);
3447 bindmap = 0; // consistent to "bind"
3449 PRVM_G_FLOAT(OFS_RETURN) = 0;
3450 if(Key_SetBinding((int)PRVM_G_FLOAT(OFS_PARM0), bindmap, PRVM_G_STRING(OFS_PARM1)))
3451 PRVM_G_FLOAT(OFS_RETURN) = 1;
3458 vector getbindmaps()
3461 void VM_getbindmaps (prvm_prog_t *prog)
3464 VM_SAFEPARMCOUNT(0, VM_getbindmaps);
3465 Key_GetBindMap(&fg, &bg);
3466 PRVM_G_VECTOR(OFS_RETURN)[0] = fg;
3467 PRVM_G_VECTOR(OFS_RETURN)[1] = bg;
3468 PRVM_G_VECTOR(OFS_RETURN)[2] = 0;
3475 float setbindmaps(vector bindmap)
3478 void VM_setbindmaps (prvm_prog_t *prog)
3480 VM_SAFEPARMCOUNT(1, VM_setbindmaps);
3481 PRVM_G_FLOAT(OFS_RETURN) = 0;
3482 if(PRVM_G_VECTOR(OFS_PARM0)[2] == 0)
3483 if(Key_SetBindMap((int)PRVM_G_VECTOR(OFS_PARM0)[0], (int)PRVM_G_VECTOR(OFS_PARM0)[1]))
3484 PRVM_G_FLOAT(OFS_RETURN) = 1;
3488 ========================
3491 float[bool] gecko_create( string name )
3492 ========================
3494 void VM_gecko_create(prvm_prog_t *prog) {
3496 PRVM_G_FLOAT( OFS_RETURN ) = 0;
3500 ========================
3503 void gecko_destroy( string name )
3504 ========================
3506 void VM_gecko_destroy(prvm_prog_t *prog) {
3511 ========================
3514 void gecko_navigate( string name, string URI )
3515 ========================
3517 void VM_gecko_navigate(prvm_prog_t *prog) {
3522 ========================
3525 float[bool] gecko_keyevent( string name, float key, float eventtype )
3526 ========================
3528 void VM_gecko_keyevent(prvm_prog_t *prog) {
3530 PRVM_G_FLOAT( OFS_RETURN ) = 0;
3534 ========================
3537 void gecko_mousemove( string name, float x, float y )
3538 ========================
3540 void VM_gecko_movemouse(prvm_prog_t *prog) {
3546 ========================
3549 void gecko_resize( string name, float w, float h )
3550 ========================
3552 void VM_gecko_resize(prvm_prog_t *prog) {
3558 ========================
3559 VM_gecko_get_texture_extent
3561 vector gecko_get_texture_extent( string name )
3562 ========================
3564 void VM_gecko_get_texture_extent(prvm_prog_t *prog) {
3566 PRVM_G_VECTOR(OFS_RETURN)[0] = 0;
3567 PRVM_G_VECTOR(OFS_RETURN)[1] = 0;
3576 Writes new values for v_forward, v_up, and v_right based on angles
3577 void makevectors(vector angle)
3580 void VM_makevectors (prvm_prog_t *prog)
3582 vec3_t angles, forward, right, up;
3583 VM_SAFEPARMCOUNT(1, VM_makevectors);
3584 VectorCopy(PRVM_G_VECTOR(OFS_PARM0), angles);
3585 AngleVectors(angles, forward, right, up);
3586 VectorCopy(forward, PRVM_gameglobalvector(v_forward));
3587 VectorCopy(right, PRVM_gameglobalvector(v_right));
3588 VectorCopy(up, PRVM_gameglobalvector(v_up));
3595 Writes new values for v_forward, v_up, and v_right based on the given forward vector
3596 vectorvectors(vector)
3599 void VM_vectorvectors (prvm_prog_t *prog)
3601 vec3_t forward, right, up;
3602 VM_SAFEPARMCOUNT(1, VM_vectorvectors);
3603 VectorNormalize2(PRVM_G_VECTOR(OFS_PARM0), forward);
3604 VectorVectors(forward, right, up);
3605 VectorCopy(forward, PRVM_gameglobalvector(v_forward));
3606 VectorCopy(right, PRVM_gameglobalvector(v_right));
3607 VectorCopy(up, PRVM_gameglobalvector(v_up));
3610 // float(float number, float quantity) bitshift (EXT_BITSHIFT)
3611 void VM_bitshift (prvm_prog_t *prog)
3614 VM_SAFEPARMCOUNT(2, VM_bitshift);
3616 n1 = (prvm_int_t)fabs((prvm_vec_t)((prvm_int_t)PRVM_G_FLOAT(OFS_PARM0)));
3617 n2 = (prvm_int_t)PRVM_G_FLOAT(OFS_PARM1);
3619 PRVM_G_FLOAT(OFS_RETURN) = n1;
3622 PRVM_G_FLOAT(OFS_RETURN) = (n1 >> -n2);
3624 PRVM_G_FLOAT(OFS_RETURN) = (n1 << n2);
3627 ////////////////////////////////////////
3628 // AltString functions
3629 ////////////////////////////////////////
3632 ========================
3635 float altstr_count(string)
3636 ========================
3638 void VM_altstr_count(prvm_prog_t *prog)
3640 const char *altstr, *pos;
3643 VM_SAFEPARMCOUNT( 1, VM_altstr_count );
3645 altstr = PRVM_G_STRING( OFS_PARM0 );
3646 //VM_CheckEmptyString(prog, altstr );
3648 for( count = 0, pos = altstr ; *pos ; pos++ ) {
3649 if( *pos == '\\' ) {
3653 } else if( *pos == '\'' ) {
3658 PRVM_G_FLOAT( OFS_RETURN ) = (prvm_vec_t) (count / 2);
3662 ========================
3665 string altstr_prepare(string)
3666 ========================
3668 void VM_altstr_prepare(prvm_prog_t *prog)
3670 const char *instr, *in;
3671 char outstr[VM_TEMPSTRING_MAXSIZE];
3674 VM_SAFEPARMCOUNT( 1, VM_altstr_prepare );
3676 instr = PRVM_G_STRING( OFS_PARM0 );
3678 for (in = instr, outpos = 0; *in && outpos < sizeof(outstr) - 1; ++in)
3680 if (*in == '\'' && outpos < sizeof(outstr) - 2)
3682 outstr[outpos++] = '\\';
3683 outstr[outpos++] = '\'';
3686 outstr[outpos++] = *in;
3689 outstr[outpos] = '\0';
3690 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outstr, outpos);
3694 ========================
3697 string altstr_get(string, float)
3698 ========================
3700 void VM_altstr_get(prvm_prog_t *prog)
3702 const char *altstr, *pos;
3705 char outstr[VM_TEMPSTRING_MAXSIZE];
3707 VM_SAFEPARMCOUNT( 2, VM_altstr_get );
3709 altstr = PRVM_G_STRING( OFS_PARM0 );
3711 count = (int)PRVM_G_FLOAT( OFS_PARM1 );
3712 count = count * 2 + 1;
3714 for( pos = altstr ; *pos && count ; pos++ )
3715 if( *pos == '\\' ) {
3718 } else if( *pos == '\'' )
3722 PRVM_G_INT( OFS_RETURN ) = 0;
3726 for( out = outstr, size = sizeof(outstr) - 1 ; size && *pos ; size--, pos++, out++ )
3727 if( *pos == '\\' ) {
3732 } else if( *pos == '\'' )
3738 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outstr, out - outstr);
3742 ========================
3745 string altstr_set(string altstr, float num, string set)
3746 ========================
3748 void VM_altstr_set(prvm_prog_t *prog)
3751 const char *altstr, *str;
3754 char outstr[VM_TEMPSTRING_MAXSIZE];
3756 VM_SAFEPARMCOUNT( 3, VM_altstr_set );
3758 altstr = PRVM_G_STRING( OFS_PARM0 );
3760 num = (int)PRVM_G_FLOAT( OFS_PARM1 );
3762 str = PRVM_G_STRING( OFS_PARM2 );
3765 for( num = num * 2 + 1, in = altstr; *in && num; *out++ = *in++ )
3770 } else if( *in == '\'' ) {
3775 for( ; *str; *out++ = *str++ );
3776 // now jump over the old content
3778 if( *in == '\'' || (*in == '\\' && !*++in) )
3781 out += dp_strlcpy(out, in, outstr + sizeof(outstr) - out);
3782 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outstr, out - outstr);
3786 ========================
3789 string altstr_ins(string altstr, float num, string set)
3790 ========================
3792 void VM_altstr_ins(prvm_prog_t *prog)
3798 char outstr[VM_TEMPSTRING_MAXSIZE];
3800 VM_SAFEPARMCOUNT(3, VM_altstr_ins);
3802 in = PRVM_G_STRING( OFS_PARM0 );
3803 num = (int)PRVM_G_FLOAT( OFS_PARM1 );
3804 set = PRVM_G_STRING( OFS_PARM2 );
3807 for( num = num * 2 + 2 ; *in && num > 0 ; *out++ = *in++ )
3812 } else if( *in == '\'' ) {
3817 for( ; *set ; *out++ = *set++ );
3820 out += dp_strlcpy(out, in, outstr + sizeof(outstr) - out);
3821 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outstr, out - outstr);
3825 ////////////////////////////////////////
3826 // BufString functions
3827 ////////////////////////////////////////
3828 //[515]: string buffers support
3830 static size_t stringbuffers_sortlength;
3832 static void BufStr_Expand(prvm_prog_t *prog, prvm_stringbuffer_t *stringbuffer, int strindex)
3834 if (stringbuffer->max_strings <= strindex)
3836 char **oldstrings = stringbuffer->strings;
3837 stringbuffer->max_strings = max(stringbuffer->max_strings * 2, 128);
3838 while (stringbuffer->max_strings <= strindex)
3839 stringbuffer->max_strings *= 2;
3840 stringbuffer->strings = (char **) Mem_Alloc(prog->progs_mempool, stringbuffer->max_strings * sizeof(stringbuffer->strings[0]));
3841 if (stringbuffer->num_strings > 0)
3842 memcpy(stringbuffer->strings, oldstrings, stringbuffer->num_strings * sizeof(stringbuffer->strings[0]));
3844 Mem_Free(oldstrings);
3848 static void BufStr_Shrink(prvm_prog_t *prog, prvm_stringbuffer_t *stringbuffer)
3850 // reduce num_strings if there are empty string slots at the end
3851 while (stringbuffer->num_strings > 0 && stringbuffer->strings[stringbuffer->num_strings - 1] == NULL)
3852 stringbuffer->num_strings--;
3854 // if empty, free the string pointer array
3855 if (stringbuffer->num_strings == 0)
3857 stringbuffer->max_strings = 0;
3858 if (stringbuffer->strings)
3859 Mem_Free(stringbuffer->strings);
3860 stringbuffer->strings = NULL;
3864 static int BufStr_SortStringsUP (const void *in1, const void *in2)
3867 a = *((const char **) in1);
3868 b = *((const char **) in2);
3869 if(!a || !a[0]) return 1;
3870 if(!b || !b[0]) return -1;
3871 return strncmp(a, b, stringbuffers_sortlength);
3874 static int BufStr_SortStringsDOWN (const void *in1, const void *in2)
3877 a = *((const char **) in1);
3878 b = *((const char **) in2);
3879 if(!a || !a[0]) return 1;
3880 if(!b || !b[0]) return -1;
3881 return strncmp(b, a, stringbuffers_sortlength);
3884 prvm_stringbuffer_t *BufStr_FindCreateReplace (prvm_prog_t *prog, int bufindex, int flags, const char *format)
3886 prvm_stringbuffer_t *stringbuffer;
3892 // find buffer with wanted index
3893 if (bufindex < (int)Mem_ExpandableArray_IndexRange(&prog->stringbuffersarray))
3895 if ( (stringbuffer = (prvm_stringbuffer_t*) Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, bufindex)) )
3897 if (stringbuffer->flags & STRINGBUFFER_TEMP)
3898 stringbuffer->flags = flags; // created but has not been used yet
3899 return stringbuffer;
3904 // allocate new buffer with wanted index
3907 stringbuffer = (prvm_stringbuffer_t *) Mem_ExpandableArray_AllocRecord(&prog->stringbuffersarray);
3908 stringbuffer->flags = STRINGBUFFER_TEMP;
3909 for (i = 0;stringbuffer != Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, i);i++);
3912 stringbuffer->flags = flags; // mark as used
3916 return stringbuffer;
3919 void BufStr_Set(prvm_prog_t *prog, prvm_stringbuffer_t *stringbuffer, int strindex, const char *str)
3923 if (!stringbuffer || strindex < 0)
3926 BufStr_Expand(prog, stringbuffer, strindex);
3927 stringbuffer->num_strings = max(stringbuffer->num_strings, strindex + 1);
3928 if (stringbuffer->strings[strindex])
3929 Mem_Free(stringbuffer->strings[strindex]);
3930 stringbuffer->strings[strindex] = NULL;
3934 // not the NULL string!
3935 alloclen = strlen(str) + 1;
3936 stringbuffer->strings[strindex] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
3937 memcpy(stringbuffer->strings[strindex], str, alloclen);
3940 BufStr_Shrink(prog, stringbuffer);
3943 void BufStr_Del(prvm_prog_t *prog, prvm_stringbuffer_t *stringbuffer)
3950 for (i = 0;i < stringbuffer->num_strings;i++)
3951 if (stringbuffer->strings[i])
3952 Mem_Free(stringbuffer->strings[i]);
3953 if (stringbuffer->strings)
3954 Mem_Free(stringbuffer->strings);
3955 if(stringbuffer->origin)
3956 PRVM_Free((char *)stringbuffer->origin);
3957 Mem_ExpandableArray_FreeRecord(&prog->stringbuffersarray, stringbuffer);
3960 void BufStr_Flush(prvm_prog_t *prog)
3962 prvm_stringbuffer_t *stringbuffer;
3965 numbuffers = (int)Mem_ExpandableArray_IndexRange(&prog->stringbuffersarray);
3966 for (i = 0; i < numbuffers; i++)
3967 if ( (stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, i)) )
3968 BufStr_Del(prog, stringbuffer);
3969 Mem_ExpandableArray_NewArray(&prog->stringbuffersarray, prog->progs_mempool, sizeof(prvm_stringbuffer_t), 64);
3973 ========================
3975 creates new buffer, and returns it's index, returns -1 if failed
3976 float buf_create(prvm_prog_t *prog) = #460;
3977 float newbuf(string format, float flags) = #460;
3978 ========================
3981 void VM_buf_create (prvm_prog_t *prog)
3983 prvm_stringbuffer_t *stringbuffer;
3986 VM_SAFEPARMCOUNTRANGE(0, 2, VM_buf_create);
3988 // VorteX: optional parm1 (buffer format) is unfinished, to keep intact with future databuffers extension must be set to "string"
3989 if(prog->argc >= 1 && strcmp(PRVM_G_STRING(OFS_PARM0), "string"))
3991 PRVM_G_FLOAT(OFS_RETURN) = -1;
3994 stringbuffer = (prvm_stringbuffer_t *) Mem_ExpandableArray_AllocRecord(&prog->stringbuffersarray);
3995 for (i = 0;stringbuffer != Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, i);i++);
3996 stringbuffer->origin = PRVM_AllocationOrigin(prog);
3997 // optional flags parm
3998 if (prog->argc >= 2)
3999 stringbuffer->flags = (int)PRVM_G_FLOAT(OFS_PARM1) & STRINGBUFFER_QCFLAGS;
4000 PRVM_G_FLOAT(OFS_RETURN) = i;
4006 ========================
4008 deletes buffer and all strings in it
4009 void buf_del(float bufhandle) = #461;
4010 ========================
4012 void VM_buf_del (prvm_prog_t *prog)
4014 prvm_stringbuffer_t *stringbuffer;
4015 VM_SAFEPARMCOUNT(1, VM_buf_del);
4016 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4018 BufStr_Del(prog, stringbuffer);
4021 VM_Warning(prog, "VM_buf_del: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4027 ========================
4029 how many strings are stored in buffer
4030 float buf_getsize(float bufhandle) = #462;
4031 ========================
4033 void VM_buf_getsize (prvm_prog_t *prog)
4035 prvm_stringbuffer_t *stringbuffer;
4036 VM_SAFEPARMCOUNT(1, VM_buf_getsize);
4038 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4041 PRVM_G_FLOAT(OFS_RETURN) = -1;
4042 VM_Warning(prog, "VM_buf_getsize: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4046 PRVM_G_FLOAT(OFS_RETURN) = stringbuffer->num_strings;
4050 ========================
4052 copy all content from one buffer to another, make sure it exists
4053 void buf_copy(float bufhandle_from, float bufhandle_to) = #463;
4054 ========================
4056 void VM_buf_copy (prvm_prog_t *prog)
4058 prvm_stringbuffer_t *srcstringbuffer, *dststringbuffer;
4060 VM_SAFEPARMCOUNT(2, VM_buf_copy);
4062 srcstringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4063 if(!srcstringbuffer)
4065 VM_Warning(prog, "VM_buf_copy: invalid source buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4068 i = (int)PRVM_G_FLOAT(OFS_PARM1);
4069 if(i == (int)PRVM_G_FLOAT(OFS_PARM0))
4071 VM_Warning(prog, "VM_buf_copy: source == destination (%i) in %s\n", i, prog->name);
4074 dststringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4075 if(!dststringbuffer)
4077 VM_Warning(prog, "VM_buf_copy: invalid destination buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), prog->name);
4081 for (i = 0;i < dststringbuffer->num_strings;i++)
4082 if (dststringbuffer->strings[i])
4083 Mem_Free(dststringbuffer->strings[i]);
4084 if (dststringbuffer->strings)
4085 Mem_Free(dststringbuffer->strings);
4086 *dststringbuffer = *srcstringbuffer;
4087 if (dststringbuffer->max_strings)
4088 dststringbuffer->strings = (char **)Mem_Alloc(prog->progs_mempool, sizeof(dststringbuffer->strings[0]) * dststringbuffer->max_strings);
4090 for (i = 0;i < dststringbuffer->num_strings;i++)
4092 if (srcstringbuffer->strings[i])
4095 stringlen = strlen(srcstringbuffer->strings[i]) + 1;
4096 dststringbuffer->strings[i] = (char *)Mem_Alloc(prog->progs_mempool, stringlen);
4097 memcpy(dststringbuffer->strings[i], srcstringbuffer->strings[i], stringlen);
4103 ========================
4105 sort buffer by beginnings of strings (cmplength defaults it's length)
4106 "backward == true" means that sorting goes upside-down
4107 void buf_sort(float bufhandle, float cmplength, float backward) = #464;
4108 ========================
4110 void VM_buf_sort (prvm_prog_t *prog)
4112 prvm_stringbuffer_t *stringbuffer;
4113 VM_SAFEPARMCOUNT(3, VM_buf_sort);
4115 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4118 VM_Warning(prog, "VM_buf_sort: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4121 if(stringbuffer->num_strings <= 0)
4123 VM_Warning(prog, "VM_buf_sort: tried to sort empty buffer %i in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4126 stringbuffers_sortlength = (int)PRVM_G_FLOAT(OFS_PARM1);
4127 if(stringbuffers_sortlength <= 0)
4128 stringbuffers_sortlength = 0x7FFFFFFF;
4130 if(!PRVM_G_FLOAT(OFS_PARM2))
4131 qsort(stringbuffer->strings, stringbuffer->num_strings, sizeof(char*), BufStr_SortStringsUP);
4133 qsort(stringbuffer->strings, stringbuffer->num_strings, sizeof(char*), BufStr_SortStringsDOWN);
4135 BufStr_Shrink(prog, stringbuffer);
4139 ========================
4141 concantenates all buffer string into one with "glue" separator and returns it as tempstring
4142 string buf_implode(float bufhandle, string glue) = #465;
4143 ========================
4145 void VM_buf_implode (prvm_prog_t *prog)
4147 prvm_stringbuffer_t *stringbuffer;
4148 char k[VM_TEMPSTRING_MAXSIZE];
4154 VM_SAFEPARMCOUNT(2, VM_buf_implode);
4156 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4157 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
4160 VM_Warning(prog, "VM_buf_implode: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4163 if(!stringbuffer->num_strings)
4165 sep = PRVM_G_STRING(OFS_PARM1);
4168 for(l = i = 0;i < stringbuffer->num_strings;i++)
4170 if(stringbuffer->strings[i])
4172 l += (i > 0 ? strlen(sep) : 0) + strlen(stringbuffer->strings[i]);
4173 if (l >= sizeof(k) - 1)
4175 dp_strlcat(k, sep, sizeof(k));
4176 k_len = dp_strlcat(k, stringbuffer->strings[i], sizeof(k));
4179 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, k, k_len);
4183 ========================
4185 get a string from buffer, returns tempstring, dont str_unzone it!
4186 string bufstr_get(float bufhandle, float string_index) = #465;
4187 ========================
4189 void VM_bufstr_get (prvm_prog_t *prog)
4191 prvm_stringbuffer_t *stringbuffer;
4193 VM_SAFEPARMCOUNT(2, VM_bufstr_get);
4195 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
4196 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4199 VM_Warning(prog, "VM_bufstr_get: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4202 strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
4205 // VM_Warning(prog, "VM_bufstr_get: invalid string index %i used in %s\n", strindex, prog->name);
4208 if (strindex < stringbuffer->num_strings && stringbuffer->strings[strindex])
4209 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, stringbuffer->strings[strindex], strlen(stringbuffer->strings[strindex]));
4213 ========================
4215 copies a string into selected slot of buffer
4216 void bufstr_set(float bufhandle, float string_index, string str) = #466;
4217 ========================
4219 void VM_bufstr_set (prvm_prog_t *prog)
4222 prvm_stringbuffer_t *stringbuffer;
4225 VM_SAFEPARMCOUNT(3, VM_bufstr_set);
4227 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4230 VM_Warning(prog, "VM_bufstr_set: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4233 strindex = (int)PRVM_G_FLOAT(OFS_PARM1);
4234 if(strindex < 0 || strindex >= 1000000) // huge number of strings
4236 VM_Warning(prog, "VM_bufstr_set: invalid string index %i used in %s\n", strindex, prog->name);
4240 news = PRVM_G_STRING(OFS_PARM2);
4241 BufStr_Set(prog, stringbuffer, strindex, news);
4245 ========================
4247 adds string to buffer in first free slot and returns its index
4248 "order == true" means that string will be added after last "full" slot
4249 float bufstr_add(float bufhandle, string str, float order) = #467;
4250 ========================
4252 void VM_bufstr_add (prvm_prog_t *prog)
4254 int order, strindex;
4255 prvm_stringbuffer_t *stringbuffer;
4259 VM_SAFEPARMCOUNT(3, VM_bufstr_add);
4261 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4262 PRVM_G_FLOAT(OFS_RETURN) = -1;
4265 VM_Warning(prog, "VM_bufstr_add: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4268 if(!PRVM_G_INT(OFS_PARM1)) // NULL string
4270 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);
4273 string = PRVM_G_STRING(OFS_PARM1);
4274 order = (int)PRVM_G_FLOAT(OFS_PARM2);
4276 strindex = stringbuffer->num_strings;
4278 for (strindex = 0;strindex < stringbuffer->num_strings;strindex++)
4279 if (stringbuffer->strings[strindex] == NULL)
4282 BufStr_Expand(prog, stringbuffer, strindex);
4284 stringbuffer->num_strings = max(stringbuffer->num_strings, strindex + 1);
4285 alloclen = strlen(string) + 1;
4286 stringbuffer->strings[strindex] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
4287 memcpy(stringbuffer->strings[strindex], string, alloclen);
4289 PRVM_G_FLOAT(OFS_RETURN) = strindex;
4293 ========================
4295 delete string from buffer
4296 void bufstr_free(float bufhandle, float string_index) = #468;
4297 ========================
4299 void VM_bufstr_free (prvm_prog_t *prog)
4302 prvm_stringbuffer_t *stringbuffer;
4303 VM_SAFEPARMCOUNT(2, VM_bufstr_free);
4305 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4308 VM_Warning(prog, "VM_bufstr_free: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4311 i = (int)PRVM_G_FLOAT(OFS_PARM1);
4314 VM_Warning(prog, "VM_bufstr_free: invalid string index %i used in %s\n", i, prog->name);
4318 if (i < stringbuffer->num_strings)
4320 if(stringbuffer->strings[i])
4321 Mem_Free(stringbuffer->strings[i]);
4322 stringbuffer->strings[i] = NULL;
4325 BufStr_Shrink(prog, stringbuffer);
4329 ========================
4331 load a file into string buffer, return 0 or 1
4332 float buf_loadfile(string filename, float bufhandle) = #535;
4333 ========================
4335 void VM_buf_loadfile(prvm_prog_t *prog)
4338 prvm_stringbuffer_t *stringbuffer;
4339 char string[VM_TEMPSTRING_MAXSIZE];
4340 int strindex, c, end;
4341 const char *filename;
4345 VM_SAFEPARMCOUNT(2, VM_buf_loadfile);
4348 filename = PRVM_G_STRING(OFS_PARM0);
4349 file = FS_OpenVirtualFile(va(vabuf, sizeof(vabuf), "data/%s", filename), false);
4351 file = FS_OpenVirtualFile(va(vabuf, sizeof(vabuf), "%s", filename), false);
4354 if (developer_extra.integer)
4355 VM_Warning(prog, "VM_buf_loadfile: failed to open file %s in %s\n", filename, prog->name);
4356 PRVM_G_FLOAT(OFS_RETURN) = 0;
4360 // get string buffer
4361 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM1));
4364 VM_Warning(prog, "VM_buf_loadfile: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), prog->name);
4365 PRVM_G_FLOAT(OFS_RETURN) = 0;
4369 // read file (append to the end of buffer)
4370 strindex = stringbuffer->num_strings;
4378 if (c == '\r' || c == '\n' || c < 0)
4380 if (end < VM_TEMPSTRING_MAXSIZE - 1)
4384 // remove \n following \r
4389 FS_UnGetc(file, (unsigned char)c);
4394 BufStr_Expand(prog, stringbuffer, strindex);
4395 stringbuffer->num_strings = max(stringbuffer->num_strings, strindex + 1);
4396 alloclen = strlen(string) + 1;
4397 stringbuffer->strings[strindex] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
4398 memcpy(stringbuffer->strings[strindex], string, alloclen);
4399 strindex = stringbuffer->num_strings;
4407 PRVM_G_FLOAT(OFS_RETURN) = 1;
4411 ========================
4413 writes stringbuffer to a file, returns 0 or 1
4414 float buf_writefile(float filehandle, float bufhandle, [, float startpos, float numstrings]) = #468;
4415 ========================
4418 void VM_buf_writefile(prvm_prog_t *prog)
4420 int filenum, strindex, strnum, strlength;
4421 prvm_stringbuffer_t *stringbuffer;
4423 VM_SAFEPARMCOUNTRANGE(2, 4, VM_buf_writefile);
4426 filenum = (int)PRVM_G_FLOAT(OFS_PARM0);
4427 if (filenum < 0 || filenum >= PRVM_MAX_OPENFILES)
4429 VM_Warning(prog, "VM_buf_writefile: invalid file handle %i used in %s\n", filenum, prog->name);
4432 if (prog->openfiles[filenum] == NULL)
4434 VM_Warning(prog, "VM_buf_writefile: no such file handle %i (or file has been closed) in %s\n", filenum, prog->name);
4438 // get string buffer
4439 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM1));
4442 VM_Warning(prog, "VM_buf_writefile: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM1), prog->name);
4443 PRVM_G_FLOAT(OFS_RETURN) = 0;
4447 // get start and end parms
4450 strindex = (int)PRVM_G_FLOAT(OFS_PARM2);
4451 strnum = (int)PRVM_G_FLOAT(OFS_PARM3);
4453 else if (prog->argc > 2)
4455 strindex = (int)PRVM_G_FLOAT(OFS_PARM2);
4456 strnum = stringbuffer->num_strings - strindex;
4461 strnum = stringbuffer->num_strings;
4463 if (strindex < 0 || strindex >= stringbuffer->num_strings)
4465 VM_Warning(prog, "VM_buf_writefile: wrong start string index %i used in %s\n", strindex, prog->name);
4466 PRVM_G_FLOAT(OFS_RETURN) = 0;
4471 VM_Warning(prog, "VM_buf_writefile: wrong strings count %i used in %s\n", strnum, prog->name);
4472 PRVM_G_FLOAT(OFS_RETURN) = 0;
4477 while(strindex < stringbuffer->num_strings && strnum)
4479 if (stringbuffer->strings[strindex])
4481 if ((strlength = (int)strlen(stringbuffer->strings[strindex])))
4482 FS_Write(prog->openfiles[filenum], stringbuffer->strings[strindex], strlength);
4483 FS_Write(prog->openfiles[filenum], "\n", 1);
4489 PRVM_G_FLOAT(OFS_RETURN) = 1;
4492 #define MATCH_AUTO 0
4493 #define MATCH_WHOLE 1
4494 #define MATCH_LEFT 2
4495 #define MATCH_RIGHT 3
4496 #define MATCH_MIDDLE 4
4497 #define MATCH_PATTERN 5
4499 static const char *detect_match_rule(char *pattern, int *matchrule)
4504 patternlength = (int)strlen(pattern);
4505 ppos = strchr(pattern, '*');
4506 qpos = strchr(pattern, '?');
4510 *matchrule = MATCH_PATTERN;
4513 // has * - left, mid, right or pattern
4516 // starts with * - may be right/mid or pattern
4517 if ((ppos - pattern) == 0)
4519 ppos = strchr(pattern+1, '*');
4523 *matchrule = MATCH_RIGHT;
4527 if ((ppos - pattern) == patternlength)
4529 *matchrule = MATCH_MIDDLE;
4534 *matchrule = MATCH_PATTERN;
4537 // end with * - left
4538 if ((ppos - pattern) == patternlength)
4540 *matchrule = MATCH_LEFT;
4545 *matchrule = MATCH_PATTERN;
4548 // have no wildcards - whole string
4549 *matchrule = MATCH_WHOLE;
4553 // todo: support UTF8
4554 static qbool match_rule(const char *string, int max_string, const char *pattern, int patternlength, int rule)
4559 return !strncmp(string, pattern, max_string) ? true : false;
4561 return !strncmp(string, pattern, patternlength) ? true : false;
4564 mid = strstr(string, pattern);
4565 return mid && !*(mid+patternlength);
4568 return strstr(string, pattern) ? true : false;
4570 return matchpattern_with_separator(string, pattern, false, "", false) ? true : false;
4574 ========================
4576 find an index of bufstring matching rule
4577 float bufstr_find(float bufhandle, string match, float matchrule, float startpos, float step) = #468;
4578 ========================
4581 void VM_bufstr_find(prvm_prog_t *prog)
4583 prvm_stringbuffer_t *stringbuffer;
4584 char string[VM_TEMPSTRING_MAXSIZE];
4585 int matchrule, matchlen, i, step;
4588 VM_SAFEPARMCOUNTRANGE(3, 5, VM_bufstr_find);
4590 PRVM_G_FLOAT(OFS_RETURN) = -1;
4592 // get string buffer
4593 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4596 VM_Warning(prog, "VM_bufstr_find: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4601 matchrule = (int)PRVM_G_FLOAT(OFS_PARM2);
4602 if (matchrule < 0 || matchrule > 5)
4604 VM_Warning(prog, "VM_bufstr_find: invalid match rule %i in %s\n", matchrule, prog->name);
4608 match = PRVM_G_STRING(OFS_PARM1);
4611 dp_strlcpy(string, PRVM_G_STRING(OFS_PARM1), sizeof(string));
4612 match = detect_match_rule(string, &matchrule);
4614 matchlen = (int)strlen(match);
4617 i = (prog->argc > 3) ? (int)PRVM_G_FLOAT(OFS_PARM3) : 0;
4618 step = (prog->argc > 4) ? (int)PRVM_G_FLOAT(OFS_PARM4) : 1;
4619 while(i < stringbuffer->num_strings)
4621 if (stringbuffer->strings[i] && match_rule(stringbuffer->strings[i], VM_TEMPSTRING_MAXSIZE, match, matchlen, matchrule))
4623 PRVM_G_FLOAT(OFS_RETURN) = i;
4631 ========================
4633 float matchpattern(string s, string pattern, float matchrule, float startpos) = #468;
4634 ========================
4636 void VM_matchpattern(prvm_prog_t *prog)
4638 const char *s, *match;
4639 char string[VM_TEMPSTRING_MAXSIZE];
4642 VM_SAFEPARMCOUNTRANGE(2, 4, VM_matchpattern);
4644 s = PRVM_G_STRING(OFS_PARM0);
4647 matchrule = (int)PRVM_G_FLOAT(OFS_PARM2);
4648 if (matchrule < 0 || matchrule > 5)
4650 VM_Warning(prog, "VM_matchpattern: invalid match rule %i in %s\n", matchrule, prog->name);
4654 match = PRVM_G_STRING(OFS_PARM1);
4657 dp_strlcpy(string, PRVM_G_STRING(OFS_PARM1), sizeof(string));
4658 match = detect_match_rule(string, &matchrule);
4662 l = (int)strlen(match);
4664 s += max(0, min((unsigned int)PRVM_G_FLOAT(OFS_PARM3), strlen(s)-1));
4667 PRVM_G_FLOAT(OFS_RETURN) = match_rule(s, VM_TEMPSTRING_MAXSIZE, match, l, matchrule);
4671 ========================
4673 ========================
4676 void VM_buf_cvarlist(prvm_prog_t *prog)
4679 const char *partial, *antipartial;
4680 size_t len, antilen;
4682 qbool ispattern, antiispattern;
4684 prvm_stringbuffer_t *stringbuffer;
4685 VM_SAFEPARMCOUNTRANGE(2, 3, VM_buf_cvarlist);
4687 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, (int)PRVM_G_FLOAT(OFS_PARM0));
4690 VM_Warning(prog, "VM_bufstr_free: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
4694 partial = PRVM_G_STRING(OFS_PARM1);
4698 len = strlen(partial);
4701 antipartial = PRVM_G_STRING(OFS_PARM2);
4707 antilen = strlen(antipartial);
4709 for (n = 0;n < stringbuffer->num_strings;n++)
4710 if (stringbuffer->strings[n])
4711 Mem_Free(stringbuffer->strings[n]);
4712 if (stringbuffer->strings)
4713 Mem_Free(stringbuffer->strings);
4714 stringbuffer->strings = NULL;
4716 ispattern = partial && (strchr(partial, '*') || strchr(partial, '?'));
4717 antiispattern = antipartial && (strchr(antipartial, '*') || strchr(antipartial, '?'));
4720 for(cvar = prog->console_cmd->cvars->vars; cvar; cvar = cvar->next)
4722 if(len && (ispattern ? !matchpattern_with_separator(cvar->name, partial, false, "", false) : strncmp(partial, cvar->name, len)))
4725 if(antilen && (antiispattern ? matchpattern_with_separator(cvar->name, antipartial, false, "", false) : !strncmp(antipartial, cvar->name, antilen)))
4731 stringbuffer->max_strings = stringbuffer->num_strings = n;
4732 if (stringbuffer->max_strings)
4733 stringbuffer->strings = (char **)Mem_Alloc(prog->progs_mempool, sizeof(stringbuffer->strings[0]) * stringbuffer->max_strings);
4736 for(cvar = prog->console_cmd->cvars->vars; cvar; cvar = cvar->next)
4738 if(len && (ispattern ? !matchpattern_with_separator(cvar->name, partial, false, "", false) : strncmp(partial, cvar->name, len)))
4741 if(antilen && (antiispattern ? matchpattern_with_separator(cvar->name, antipartial, false, "", false) : !strncmp(antipartial, cvar->name, antilen)))
4744 alloclen = strlen(cvar->name) + 1;
4745 stringbuffer->strings[n] = (char *)Mem_Alloc(prog->progs_mempool, alloclen);
4746 memcpy(stringbuffer->strings[n], cvar->name, alloclen);
4761 This was a major timewaster in progs, so it was converted to C
4764 void VM_changeyaw (prvm_prog_t *prog)
4767 float ideal, current, move, speed;
4769 // this is called (VERY HACKISHLY) by VM_SV_MoveToGoal, so it can not use any
4770 // parameters because they are the parameters to VM_SV_MoveToGoal, not this
4771 //VM_SAFEPARMCOUNT(0, VM_changeyaw);
4773 ent = PRVM_PROG_TO_EDICT(PRVM_gameglobaledict(self));
4774 if (ent == prog->edicts)
4776 VM_Warning(prog, "changeyaw: can not modify world entity\n");
4781 VM_Warning(prog, "changeyaw: can not modify free entity\n");
4784 current = PRVM_gameedictvector(ent, angles)[1];
4785 current = ANGLEMOD(current);
4786 ideal = PRVM_gameedictfloat(ent, ideal_yaw);
4787 speed = PRVM_gameedictfloat(ent, yaw_speed);
4789 if (current == ideal)
4791 move = ideal - current;
4792 if (ideal > current)
4814 PRVM_gameedictvector(ent, angles)[1] = ANGLEMOD(current);
4822 void VM_changepitch (prvm_prog_t *prog)
4825 float ideal, current, move, speed;
4827 VM_SAFEPARMCOUNT(1, VM_changepitch);
4829 ent = PRVM_G_EDICT(OFS_PARM0);
4830 if (ent == prog->edicts)
4832 VM_Warning(prog, "changepitch: can not modify world entity\n");
4837 VM_Warning(prog, "changepitch: can not modify free entity\n");
4840 current = PRVM_gameedictvector(ent, angles)[0];
4841 current = ANGLEMOD(current);
4842 ideal = PRVM_gameedictfloat(ent, idealpitch);
4843 speed = PRVM_gameedictfloat(ent, pitch_speed);
4845 if (current == ideal)
4847 move = ideal - current;
4848 if (ideal > current)
4870 PRVM_gameedictvector(ent, angles)[0] = ANGLEMOD(current);
4874 void VM_uncolorstring (prvm_prog_t *prog)
4876 char szNewString[VM_TEMPSTRING_MAXSIZE];
4877 size_t szNewString_len;
4878 const char *szString;
4881 VM_SAFEPARMCOUNT(1, VM_uncolorstring);
4882 szString = PRVM_G_STRING(OFS_PARM0);
4883 szNewString_len = COM_StringDecolorize(szString, 0, szNewString, sizeof(szNewString), true);
4884 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, szNewString, szNewString_len);
4887 // #221 float(string str, string sub[, float startpos]) strstrofs (FTE_STRINGS)
4888 //strstr, without generating a new string. Use in conjunction with FRIK_FILE's substring for more similar strstr.
4889 void VM_strstrofs (prvm_prog_t *prog)
4891 const char *instr, *match;
4893 VM_SAFEPARMCOUNTRANGE(2, 3, VM_strstrofs);
4894 instr = PRVM_G_STRING(OFS_PARM0);
4895 match = PRVM_G_STRING(OFS_PARM1);
4896 firstofs = (prog->argc > 2)?(int)PRVM_G_FLOAT(OFS_PARM2):0;
4897 firstofs = (int)u8_bytelen(instr, firstofs);
4899 if (firstofs && (firstofs < 0 || firstofs > (int)strlen(instr)))
4901 PRVM_G_FLOAT(OFS_RETURN) = -1;
4905 match = strstr(instr+firstofs, match);
4907 PRVM_G_FLOAT(OFS_RETURN) = -1;
4909 PRVM_G_FLOAT(OFS_RETURN) = u8_strnlen(instr, match-instr);
4912 //#222 string(string s, float index) str2chr (FTE_STRINGS)
4913 void VM_str2chr (prvm_prog_t *prog)
4918 VM_SAFEPARMCOUNT(2, VM_str2chr);
4919 s = PRVM_G_STRING(OFS_PARM0);
4920 index = (int)u8_bytelen(s, (int)PRVM_G_FLOAT(OFS_PARM1));
4922 if((unsigned)index < strlen(s))
4924 if (utf8_enable.integer)
4925 ch = u8_getchar_noendptr(s + index);
4927 ch = (unsigned char)s[index];
4928 PRVM_G_FLOAT(OFS_RETURN) = ch;
4931 PRVM_G_FLOAT(OFS_RETURN) = 0;
4934 //#223 string(float c, ...) chr2str (FTE_STRINGS)
4935 void VM_chr2str (prvm_prog_t *prog)
4940 VM_SAFEPARMCOUNTRANGE(0, 8, VM_chr2str);
4941 for(i = 0;i < prog->argc && i < (int)sizeof(t) - 1;i++)
4942 t[i] = (unsigned char)PRVM_G_FLOAT(OFS_PARM0+i*3);
4944 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, t);
4950 VM_SAFEPARMCOUNTRANGE(0, 8, VM_chr2str);
4951 for(i = 0; i < prog->argc && len < sizeof(t)-1; ++i)
4952 len += u8_fromchar((Uchar)PRVM_G_FLOAT(OFS_PARM0+i*3), t + len, sizeof(t)-1);
4954 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, t, len);
4957 static int chrconv_number(int i, int base, int conv)
4982 static int chrconv_punct(int i, int base, int conv)
5000 static int chrchar_alpha(int i, int basec, int baset, int convc, int convt, int charnum)
5002 //convert case and colour seperatly...
5019 baset = 128*((charnum&1) == (convt-5));
5035 return i + basec + baset;
5037 // #224 string(float ccase, float calpha, float cnum, string s, ...) strconv (FTE_STRINGS)
5038 //bulk convert a string. change case or colouring.
5039 void VM_strconv (prvm_prog_t *prog)
5041 int ccase, redalpha, rednum;
5044 unsigned char resbuf[VM_TEMPSTRING_MAXSIZE];
5045 unsigned char *result = resbuf;
5047 VM_SAFEPARMCOUNTRANGE(3, 8, VM_strconv);
5049 ccase = (int) PRVM_G_FLOAT(OFS_PARM0); //0 same, 1 lower, 2 upper
5050 redalpha = (int) PRVM_G_FLOAT(OFS_PARM1); //0 same, 1 white, 2 red, 5 alternate, 6 alternate-alternate
5051 rednum = (int) PRVM_G_FLOAT(OFS_PARM2); //0 same, 1 white, 2 red, 3 redspecial, 4 whitespecial, 5 alternate, 6 alternate-alternate
5052 resbuf_len = VM_VarString(prog, 3, (char *) resbuf, sizeof(resbuf));
5054 for (i = 0; i < resbuf_len; i++, result++) //should this be done backwards?
5056 if (*result >= '0' && *result <= '9') //normal numbers...
5057 *result = chrconv_number(*result, '0', rednum);
5058 else if (*result >= '0'+128 && *result <= '9'+128)
5059 *result = chrconv_number(*result, '0'+128, rednum);
5060 else if (*result >= '0'+128-30 && *result <= '9'+128-30)
5061 *result = chrconv_number(*result, '0'+128-30, rednum);
5062 else if (*result >= '0'-30 && *result <= '9'-30)
5063 *result = chrconv_number(*result, '0'-30, rednum);
5065 else if (*result >= 'a' && *result <= 'z') //normal numbers...
5066 *result = chrchar_alpha(*result, 'a', 0, ccase, redalpha, i);
5067 else if (*result >= 'A' && *result <= 'Z') //normal numbers...
5068 *result = chrchar_alpha(*result, 'A', 0, ccase, redalpha, i);
5069 else if (*result >= 'a'+128 && *result <= 'z'+128) //normal numbers...
5070 *result = chrchar_alpha(*result, 'a', 128, ccase, redalpha, i);
5071 else if (*result >= 'A'+128 && *result <= 'Z'+128) //normal numbers...
5072 *result = chrchar_alpha(*result, 'A', 128, ccase, redalpha, i);
5074 else if ((*result & 127) < 16 || !redalpha) //special chars..
5076 else if (*result < 128)
5077 *result = chrconv_punct(*result, 0, redalpha);
5079 *result = chrconv_punct(*result, 128, redalpha);
5083 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, (char *)resbuf, result - resbuf);
5086 // #225 string(float chars, string s, ...) strpad (FTE_STRINGS)
5087 void VM_strpad (prvm_prog_t *prog)
5089 char src[VM_TEMPSTRING_MAXSIZE];
5090 char destbuf[VM_TEMPSTRING_MAXSIZE];
5094 VM_SAFEPARMCOUNTRANGE(1, 8, VM_strpad);
5095 pad = (int) PRVM_G_FLOAT(OFS_PARM0);
5096 VM_VarString(prog, 1, src, sizeof(src));
5098 // note: < 0 = left padding, > 0 = right padding,
5099 // this is reverse logic of printf!
5100 destbuf_len = dpsnprintf(destbuf, sizeof(destbuf), "%*s", -pad, src);
5102 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, destbuf, destbuf_len);
5105 // #226 string(string info, string key, string value, ...) infoadd (FTE_STRINGS)
5106 //uses qw style \key\value strings
5107 void VM_infoadd (prvm_prog_t *prog)
5109 const char *info, *key;
5110 char value[VM_TEMPSTRING_MAXSIZE];
5111 char temp[VM_TEMPSTRING_MAXSIZE];
5113 VM_SAFEPARMCOUNTRANGE(2, 8, VM_infoadd);
5114 info = PRVM_G_STRING(OFS_PARM0);
5115 key = PRVM_G_STRING(OFS_PARM1);
5116 VM_VarString(prog, 2, value, sizeof(value));
5118 dp_strlcpy(temp, info, VM_TEMPSTRING_MAXSIZE);
5120 InfoString_SetValue(temp, VM_TEMPSTRING_MAXSIZE, key, value);
5122 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, temp, strlen(temp));
5125 // #227 string(string info, string key) infoget (FTE_STRINGS)
5126 //uses qw style \key\value strings
5127 void VM_infoget (prvm_prog_t *prog)
5131 char value[VM_TEMPSTRING_MAXSIZE];
5133 VM_SAFEPARMCOUNT(2, VM_infoget);
5134 info = PRVM_G_STRING(OFS_PARM0);
5135 key = PRVM_G_STRING(OFS_PARM1);
5137 InfoString_GetValue(info, key, value, VM_TEMPSTRING_MAXSIZE);
5139 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, value, strlen(value));
5142 //#228 float(string s1, string s2, float len) strncmp (FTE_STRINGS)
5143 // also float(string s1, string s2) strcmp (FRIK_FILE)
5144 void VM_strncmp (prvm_prog_t *prog)
5146 const char *s1, *s2;
5147 VM_SAFEPARMCOUNTRANGE(2, 3, VM_strncmp);
5148 s1 = PRVM_G_STRING(OFS_PARM0);
5149 s2 = PRVM_G_STRING(OFS_PARM1);
5152 PRVM_G_FLOAT(OFS_RETURN) = strncmp(s1, s2, (size_t)PRVM_G_FLOAT(OFS_PARM2));
5156 PRVM_G_FLOAT(OFS_RETURN) = strcmp(s1, s2);
5160 // #229 float(string s1, string s2) strcasecmp (FTE_STRINGS)
5161 // #230 float(string s1, string s2, float len) strncasecmp (FTE_STRINGS)
5162 void VM_strncasecmp (prvm_prog_t *prog)
5164 const char *s1, *s2;
5165 VM_SAFEPARMCOUNTRANGE(2, 3, VM_strncasecmp);
5166 s1 = PRVM_G_STRING(OFS_PARM0);
5167 s2 = PRVM_G_STRING(OFS_PARM1);
5170 PRVM_G_FLOAT(OFS_RETURN) = strncasecmp(s1, s2, (size_t)PRVM_G_FLOAT(OFS_PARM2));
5174 PRVM_G_FLOAT(OFS_RETURN) = strcasecmp(s1, s2);
5178 // #494 float(float caseinsensitive, string s, ...) crc16
5179 void VM_crc16(prvm_prog_t *prog)
5182 char s[VM_TEMPSTRING_MAXSIZE];
5185 VM_SAFEPARMCOUNTRANGE(2, 8, VM_crc16);
5186 insensitive = PRVM_G_FLOAT(OFS_PARM0);
5187 slen = VM_VarString(prog, 1, s, sizeof(s));
5188 PRVM_G_FLOAT(OFS_RETURN) = (unsigned short) ((insensitive ? CRC_Block_CaseInsensitive : CRC_Block) ((unsigned char *) s, slen));
5191 // #639 float(string digest, string data, ...) digest_hex
5192 void VM_digest_hex(prvm_prog_t *prog)
5200 char s[VM_TEMPSTRING_MAXSIZE];
5203 VM_SAFEPARMCOUNTRANGE(2, 8, VM_digest_hex);
5204 digest = PRVM_G_STRING(OFS_PARM0);
5207 len = VM_VarString(prog, 1, s, sizeof(s));
5211 if(!strcmp(digest, "MD4"))
5214 mdfour((unsigned char *) out, (unsigned char *) s, len);
5216 else if(!strcmp(digest, "SHA256") && Crypto_Available())
5219 sha256((unsigned char *) out, (unsigned char *) s, len);
5221 // no warning needed on mismatch - we return string_null to QC
5226 static const char *hexmap = "0123456789abcdef";
5227 for(i = 0; i < outlen; ++i)
5229 outhex[2*i] = hexmap[(out[i] >> 4) & 15];
5230 outhex[2*i+1] = hexmap[(out[i] >> 0) & 15];
5233 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outhex, 2*i);
5236 PRVM_G_INT(OFS_RETURN) = 0;
5239 void VM_wasfreed (prvm_prog_t *prog)
5241 VM_SAFEPARMCOUNT(1, VM_wasfreed);
5242 PRVM_G_FLOAT(OFS_RETURN) = PRVM_G_EDICT(OFS_PARM0)->free;
5245 void VM_SetTraceGlobals(prvm_prog_t *prog, const trace_t *trace)
5247 PRVM_gameglobalfloat(trace_allsolid) = trace->allsolid;
5248 PRVM_gameglobalfloat(trace_startsolid) = trace->startsolid;
5249 PRVM_gameglobalfloat(trace_fraction) = trace->fraction;
5250 PRVM_gameglobalfloat(trace_inwater) = trace->inwater;
5251 PRVM_gameglobalfloat(trace_inopen) = trace->inopen;
5252 VectorCopy(trace->endpos, PRVM_gameglobalvector(trace_endpos));
5253 VectorCopy(trace->plane.normal, PRVM_gameglobalvector(trace_plane_normal));
5254 PRVM_gameglobalfloat(trace_plane_dist) = trace->plane.dist;
5255 PRVM_gameglobaledict(trace_ent) = PRVM_EDICT_TO_PROG(trace->ent ? trace->ent : prog->edicts);
5256 PRVM_gameglobalfloat(trace_dpstartcontents) = trace->startsupercontents;
5257 PRVM_gameglobalfloat(trace_dphitcontents) = trace->hitsupercontents;
5258 PRVM_gameglobalfloat(trace_dphitq3surfaceflags) = trace->hitq3surfaceflags;
5259 PRVM_gameglobalstring(trace_dphittexturename) = trace->hittexture ? PRVM_SetTempString(prog, trace->hittexture->name, strlen(trace->hittexture->name)) : 0;
5262 void VM_ClearTraceGlobals(prvm_prog_t *prog)
5264 // clean up all trace globals when leaving the VM (anti-triggerbot safeguard)
5265 PRVM_gameglobalfloat(trace_allsolid) = 0;
5266 PRVM_gameglobalfloat(trace_startsolid) = 0;
5267 PRVM_gameglobalfloat(trace_fraction) = 0;
5268 PRVM_gameglobalfloat(trace_inwater) = 0;
5269 PRVM_gameglobalfloat(trace_inopen) = 0;
5270 VectorClear(PRVM_gameglobalvector(trace_endpos));
5271 VectorClear(PRVM_gameglobalvector(trace_plane_normal));
5272 PRVM_gameglobalfloat(trace_plane_dist) = 0;
5273 PRVM_gameglobaledict(trace_ent) = PRVM_EDICT_TO_PROG(prog->edicts);
5274 PRVM_gameglobalfloat(trace_dpstartcontents) = 0;
5275 PRVM_gameglobalfloat(trace_dphitcontents) = 0;
5276 PRVM_gameglobalfloat(trace_dphitq3surfaceflags) = 0;
5277 PRVM_gameglobalstring(trace_dphittexturename) = 0;
5282 void VM_Cmd_Init(prvm_prog_t *prog)
5284 // only init the stuff for the current prog
5285 VM_Files_Init(prog);
5286 VM_Search_Init(prog);
5289 static void animatemodel_reset(prvm_prog_t *prog);
5291 void VM_Cmd_Reset(prvm_prog_t *prog)
5293 CL_PurgeOwner( MENUOWNER );
5294 VM_Search_Reset(prog);
5295 VM_Files_CloseAll(prog);
5296 animatemodel_reset(prog);
5299 // #510 string(string input, ...) uri_escape (DP_QC_URI_ESCAPE)
5300 // does URI escaping on a string (replace evil stuff by %AB escapes)
5301 void VM_uri_escape (prvm_prog_t *prog)
5303 char src[VM_TEMPSTRING_MAXSIZE];
5304 char dest[VM_TEMPSTRING_MAXSIZE];
5306 static const char *hex = "0123456789ABCDEF";
5308 VM_SAFEPARMCOUNTRANGE(1, 8, VM_uri_escape);
5309 VM_VarString(prog, 0, src, sizeof(src));
5311 for(p = src, q = dest; *p && q < dest + sizeof(dest) - 3; ++p)
5313 if((*p >= 'A' && *p <= 'Z')
5314 || (*p >= 'a' && *p <= 'z')
5315 || (*p >= '0' && *p <= '9')
5316 || (*p == '-') || (*p == '_') || (*p == '.')
5317 || (*p == '!') || (*p == '~')
5318 || (*p == '\'') || (*p == '(') || (*p == ')'))
5323 *q++ = hex[(*(unsigned char *)p >> 4) & 0xF];
5324 *q++ = hex[ *(unsigned char *)p & 0xF];
5329 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, dest, q - dest);
5332 // #510 string(string input, ...) uri_unescape (DP_QC_URI_ESCAPE)
5333 // does URI unescaping on a string (get back the evil stuff)
5334 void VM_uri_unescape (prvm_prog_t *prog)
5336 char src[VM_TEMPSTRING_MAXSIZE];
5337 char dest[VM_TEMPSTRING_MAXSIZE];
5341 VM_SAFEPARMCOUNTRANGE(1, 8, VM_uri_unescape);
5342 VM_VarString(prog, 0, src, sizeof(src));
5344 for(p = src, q = dest; *p; ) // no need to check size, because unescape can't expand
5348 if(p[1] >= '0' && p[1] <= '9')
5350 else if(p[1] >= 'a' && p[1] <= 'f')
5351 hi = p[1] - 'a' + 10;
5352 else if(p[1] >= 'A' && p[1] <= 'F')
5353 hi = p[1] - 'A' + 10;
5356 if(p[2] >= '0' && p[2] <= '9')
5358 else if(p[2] >= 'a' && p[2] <= 'f')
5359 lo = p[2] - 'a' + 10;
5360 else if(p[2] >= 'A' && p[2] <= 'F')
5361 lo = p[2] - 'A' + 10;
5364 if(hi != 0 || lo != 0) // don't unescape NUL bytes
5365 *q++ = (char) (hi * 0x10 + lo);
5376 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, dest, q - dest);
5379 // #502 string(string filename) whichpack (DP_QC_WHICHPACK)
5380 // returns the name of the pack containing a file, or "" if it is not in any pack (but local or non-existant)
5381 void VM_whichpack (prvm_prog_t *prog)
5383 const char *fn, *pack;
5385 VM_SAFEPARMCOUNT(1, VM_whichpack);
5386 fn = PRVM_G_STRING(OFS_PARM0);
5387 pack = FS_WhichPack(fn);
5389 PRVM_G_INT(OFS_RETURN) = pack ? PRVM_SetTempString(prog, pack, strlen(pack)) : 0;
5397 char buffer[MAX_INPUTLINE];
5399 unsigned char *postdata; // free when uri_to_prog_t is freed
5401 char *sigdata; // free when uri_to_prog_t is freed
5406 static void uri_to_string_callback(int status, size_t length_received, unsigned char *buffer, void *cbdata)
5409 uri_to_prog_t *handle = (uri_to_prog_t *) cbdata;
5411 prog = handle->prog;
5414 // curl reply came too late... so just drop it
5415 if(handle->postdata)
5416 Z_Free(handle->postdata);
5418 Z_Free(handle->sigdata);
5423 if((prog->starttime == handle->starttime) && (PRVM_allfunction(URI_Get_Callback)))
5425 if(length_received >= sizeof(handle->buffer))
5426 length_received = sizeof(handle->buffer) - 1;
5427 handle->buffer[length_received] = '\0';
5429 PRVM_G_FLOAT(OFS_PARM0) = handle->id;
5430 PRVM_G_FLOAT(OFS_PARM1) = status;
5431 PRVM_G_INT(OFS_PARM2) = PRVM_SetTempString(prog, handle->buffer, length_received);
5432 prog->ExecuteProgram(prog, PRVM_allfunction(URI_Get_Callback), "QC function URI_Get_Callback is missing");
5435 if(handle->postdata)
5436 Z_Free(handle->postdata);
5438 Z_Free(handle->sigdata);
5442 // 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
5443 // 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
5444 void VM_uri_get (prvm_prog_t *prog)
5449 uri_to_prog_t *handle;
5450 const char *posttype = NULL;
5451 const char *postseparator = NULL;
5452 int poststringbuffer = -1;
5454 const char *query_string = NULL;
5457 if(!PRVM_allfunction(URI_Get_Callback))
5458 prog->error_cmd("uri_get called by %s without URI_Get_Callback defined", prog->name);
5460 VM_SAFEPARMCOUNTRANGE(2, 6, VM_uri_get);
5462 url = PRVM_G_STRING(OFS_PARM0);
5463 id = PRVM_G_FLOAT(OFS_PARM1);
5465 posttype = PRVM_G_STRING(OFS_PARM2);
5467 postseparator = PRVM_G_STRING(OFS_PARM3);
5469 poststringbuffer = PRVM_G_FLOAT(OFS_PARM4);
5471 postkeyid = PRVM_G_FLOAT(OFS_PARM5);
5472 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!
5474 query_string = strchr(url, '?');
5477 lq = query_string ? strlen(query_string) : 0;
5479 handle->prog = prog;
5480 handle->starttime = prog->starttime;
5482 if(postseparator && posttype && *posttype)
5484 size_t l = strlen(postseparator);
5485 if(poststringbuffer >= 0)
5490 prvm_stringbuffer_t *stringbuffer;
5491 stringbuffer = (prvm_stringbuffer_t *)Mem_ExpandableArray_RecordAtIndex(&prog->stringbuffersarray, poststringbuffer);
5494 VM_Warning(prog, "uri_get: invalid buffer %i used in %s\n", (int)PRVM_G_FLOAT(OFS_PARM0), prog->name);
5498 for(i = 0;i < stringbuffer->num_strings;i++)
5502 if(stringbuffer->strings[i])
5503 ltotal += strlen(stringbuffer->strings[i]);
5505 handle->postdata = (unsigned char *)Z_Malloc(ltotal + 1 + lq);
5506 handle->postlen = ltotal;
5508 for(i = 0;i < stringbuffer->num_strings;i++)
5512 memcpy(handle->postdata + ltotal, postseparator, l);
5515 if(stringbuffer->strings[i])
5517 memcpy(handle->postdata + ltotal, stringbuffer->strings[i], strlen(stringbuffer->strings[i]));
5518 ltotal += strlen(stringbuffer->strings[i]);
5521 if(ltotal != handle->postlen)
5522 prog->error_cmd("%s: string buffer content size mismatch, possible overrun", prog->name);
5526 handle->postdata = (unsigned char *)Z_Malloc(l + 1 + lq);
5527 handle->postlen = l;
5528 memcpy(handle->postdata, postseparator, l);
5530 handle->postdata[handle->postlen] = 0;
5532 memcpy(handle->postdata + handle->postlen + 1, query_string, lq);
5535 // POST: we sign postdata \0 query string
5537 handle->sigdata = (char *)Z_Malloc(8192);
5538 dp_strlcpy(handle->sigdata, "X-D0-Blind-ID-Detached-Signature: ", 8192);
5539 l = strlen(handle->sigdata);
5540 handle->siglen = Crypto_SignDataDetached(handle->postdata, handle->postlen + 1 + lq, postkeyid, handle->sigdata + l, 8192 - l);
5543 Z_Free(handle->sigdata);
5544 handle->sigdata = NULL;
5547 ll = base64_encode((unsigned char *) (handle->sigdata + l), handle->siglen, 8192 - l - 1);
5550 Z_Free(handle->sigdata);
5551 handle->sigdata = NULL;
5554 handle->siglen = l + ll;
5555 handle->sigdata[handle->siglen] = 0;
5558 dp_strlcpy(handle->posttype, posttype, sizeof(handle->posttype));
5559 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);
5563 if(postkeyid >= 0 && query_string)
5565 // GET: we sign JUST the query string
5567 handle->sigdata = (char *)Z_Malloc(8192);
5568 dp_strlcpy(handle->sigdata, "X-D0-Blind-ID-Detached-Signature: ", 8192);
5569 l = strlen(handle->sigdata);
5570 handle->siglen = Crypto_SignDataDetached(query_string, lq, postkeyid, handle->sigdata + l, 8192 - l);
5573 Z_Free(handle->sigdata);
5574 handle->sigdata = NULL;
5577 ll = base64_encode((unsigned char *) (handle->sigdata + l), handle->siglen, 8192 - l - 1);
5580 Z_Free(handle->sigdata);
5581 handle->sigdata = NULL;
5584 handle->siglen = l + ll;
5585 handle->sigdata[handle->siglen] = 0;
5588 handle->postdata = NULL;
5589 handle->postlen = 0;
5590 ret = Curl_Begin_ToMemory_POST(url, handle->sigdata, 0, NULL, NULL, 0, (unsigned char *) handle->buffer, sizeof(handle->buffer), uri_to_string_callback, handle);
5594 PRVM_G_INT(OFS_RETURN) = 1;
5598 if(handle->postdata)
5599 Z_Free(handle->postdata);
5601 Z_Free(handle->sigdata);
5603 PRVM_G_INT(OFS_RETURN) = 0;
5607 void VM_netaddress_resolve (prvm_prog_t *prog)
5610 char normalized[128];
5611 size_t normalized_len;
5613 lhnetaddress_t addr;
5615 VM_SAFEPARMCOUNTRANGE(1, 2, VM_netaddress_resolve);
5617 ip = PRVM_G_STRING(OFS_PARM0);
5620 port = (int) PRVM_G_FLOAT(OFS_PARM1);
5622 if(LHNETADDRESS_FromString(&addr, ip, port) && (normalized_len = LHNETADDRESS_ToString(&addr, normalized, sizeof(normalized), prog->argc > 1)))
5623 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, normalized, normalized_len);
5625 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, "", 0);
5628 //string(prvm_prog_t *prog) getextresponse = #624; // returns the next extResponse packet that was sent to this client
5629 void VM_CL_getextresponse (prvm_prog_t *prog)
5631 VM_SAFEPARMCOUNT(0,VM_argv);
5633 if (cl_net_extresponse_count <= 0)
5634 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
5638 --cl_net_extresponse_count;
5639 first = (cl_net_extresponse_last + NET_EXTRESPONSE_MAX - cl_net_extresponse_count) % NET_EXTRESPONSE_MAX;
5640 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, cl_net_extresponse[first], strlen(cl_net_extresponse[first]));
5644 void VM_SV_getextresponse (prvm_prog_t *prog)
5646 VM_SAFEPARMCOUNT(0,VM_argv);
5648 if (sv_net_extresponse_count <= 0)
5649 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
5653 --sv_net_extresponse_count;
5654 first = (sv_net_extresponse_last + NET_EXTRESPONSE_MAX - sv_net_extresponse_count) % NET_EXTRESPONSE_MAX;
5655 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, sv_net_extresponse[first], strlen(sv_net_extresponse[first]));
5659 // DP_QC_NUDGEOUTOFSOLID
5660 // float(entity ent) nudgeoutofsolid = #567;
5661 void VM_nudgeoutofsolid(prvm_prog_t *prog)
5665 VM_SAFEPARMCOUNTRANGE(1, 1, VM_nudgeoutofsolid);
5667 ent = PRVM_G_EDICT(OFS_PARM0);
5668 if (ent == prog->edicts)
5670 VM_Warning(prog, "nudgeoutofsolid: can not modify world entity\n");
5671 PRVM_G_FLOAT(OFS_RETURN) = 0;
5676 VM_Warning(prog, "nudgeoutofsolid: can not modify free entity\n");
5677 PRVM_G_FLOAT(OFS_RETURN) = 0;
5681 PRVM_G_FLOAT(OFS_RETURN) = PHYS_NudgeOutOfSolid(prog, ent);
5683 if (PRVM_G_FLOAT(OFS_RETURN) > 0)
5685 if (prog == SVVM_prog)
5687 else if (prog == CLVM_prog)
5690 Sys_Error("PHYS_NudgeOutOfSolid: cannot be called from %s VM\n", prog->name);
5696 Common functions between menu.dat and clsprogs
5700 //#349 float() isdemo
5701 void VM_CL_isdemo (prvm_prog_t *prog)
5703 VM_SAFEPARMCOUNT(0, VM_CL_isdemo);
5704 PRVM_G_FLOAT(OFS_RETURN) = cls.demoplayback;
5707 //#355 float() videoplaying
5708 void VM_CL_videoplaying (prvm_prog_t *prog)
5710 VM_SAFEPARMCOUNT(0, VM_CL_videoplaying);
5711 PRVM_G_FLOAT(OFS_RETURN) = cl_videoplaying;
5718 callfunction(...,string function_name)
5722 void VM_callfunction(prvm_prog_t *prog)
5727 VM_SAFEPARMCOUNTRANGE(1, 8, VM_callfunction);
5729 s = PRVM_G_STRING(OFS_PARM0+(prog->argc - 1)*3);
5731 VM_CheckEmptyString(prog, s);
5733 func = PRVM_ED_FindFunction(prog, s);
5736 prog->error_cmd("VM_callfunction: function %s not found !", s);
5737 else if (func->first_statement < 0)
5739 // negative statements are built in functions
5740 int builtinnumber = -func->first_statement;
5741 prog->xfunction->builtinsprofile++;
5742 if (builtinnumber < prog->numbuiltins && prog->builtins[builtinnumber])
5743 prog->builtins[builtinnumber](prog);
5745 prog->error_cmd("No such builtin #%i in %s; most likely cause: outdated engine build. Try updating!", builtinnumber, prog->name);
5747 else if(func - prog->functions > 0)
5750 prog->ExecuteProgram(prog, func - prog->functions,"");
5759 float isfunction(string function_name)
5762 void VM_isfunction(prvm_prog_t *prog)
5767 VM_SAFEPARMCOUNT(1, VM_isfunction);
5769 s = PRVM_G_STRING(OFS_PARM0);
5771 VM_CheckEmptyString(prog, s);
5773 func = PRVM_ED_FindFunction(prog, s);
5776 PRVM_G_FLOAT(OFS_RETURN) = false;
5778 PRVM_G_FLOAT(OFS_RETURN) = true;
5785 string sprintf(string format, ...)
5789 void VM_sprintf(prvm_prog_t *prog)
5792 char outbuf[MAX_INPUTLINE];
5793 char *o = outbuf, *end = outbuf + sizeof(outbuf), *err;
5796 int width, precision, thisarg, flags;
5800 static prvm_int_t dummyivec[3] = {0, 0, 0};
5801 static prvm_vec_t dummyvec[3] = {0, 0, 0};
5804 #define PRINTF_ALTERNATE 1
5805 #define PRINTF_ZEROPAD 2
5806 #define PRINTF_LEFT 4
5807 #define PRINTF_SPACEPOSITIVE 8
5808 #define PRINTF_SIGNPOSITIVE 16
5812 s = PRVM_G_STRING(OFS_PARM0);
5814 #define GETARG_FLOAT(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_FLOAT(OFS_PARM0 + 3 * (a))) : 0)
5815 #define GETARG_VECTOR(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_VECTOR(OFS_PARM0 + 3 * (a))) : dummyvec)
5816 #define GETARG_INT(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_INT(OFS_PARM0 + 3 * (a))) : 0)
5817 #define GETARG_INTVECTOR(a) (((a)>=1 && (a)<prog->argc) ? ((prvm_int_t*) PRVM_G_VECTOR(OFS_PARM0 + 3 * (a))) : dummyivec)
5818 #define GETARG_STRING(a) (((a)>=1 && (a)<prog->argc) ? (PRVM_G_STRING(OFS_PARM0 + 3 * (a))) : "")
5833 // complete directive format:
5842 // is number following?
5843 if(*s >= '0' && *s <= '9')
5845 width = strtol(s, &err, 10);
5848 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
5861 flags |= PRINTF_ZEROPAD;
5863 width = -1; // it was just a flag
5875 case '#': flags |= PRINTF_ALTERNATE; break;
5876 case '0': flags |= PRINTF_ZEROPAD; break;
5877 case '-': flags |= PRINTF_LEFT; break;
5878 case ' ': flags |= PRINTF_SPACEPOSITIVE; break;
5879 case '+': flags |= PRINTF_SIGNPOSITIVE; break;
5889 if(*s >= '0' && *s <= '9')
5891 width = strtol(s, &err, 10);
5892 if(!err || *err != '$')
5894 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
5901 width = GETARG_FLOAT(width);
5904 flags |= PRINTF_LEFT;
5908 else if(*s >= '0' && *s <= '9')
5910 width = strtol(s, &err, 10);
5913 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
5919 flags |= PRINTF_LEFT;
5923 // otherwise width stays -1
5932 if(*s >= '0' && *s <= '9')
5934 precision = strtol(s, &err, 10);
5935 if(!err || *err != '$')
5937 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
5943 precision = argpos++;
5944 precision = GETARG_FLOAT(precision);
5946 else if(*s >= '0' && *s <= '9')
5948 precision = strtol(s, &err, 10);
5951 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
5958 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
5967 case 'h': isfloat = 1; break;
5968 case 'l': isfloat = 0; break;
5969 case 'L': isfloat = 0; break;
5980 // now s points to the final directive char and is no longer changed
5995 if(*s != 's' && *s != 'c')
5996 if(flags & PRINTF_ALTERNATE) *f++ = '#';
5997 if(flags & PRINTF_ZEROPAD) *f++ = '0';
5998 if(flags & PRINTF_LEFT) *f++ = '-';
5999 if(flags & PRINTF_SPACEPOSITIVE) *f++ = ' ';
6000 if(flags & PRINTF_SIGNPOSITIVE) *f++ = '+';
6007 if(*s == 'd' || *s == 'i' || *s == 'o' || *s == 'u' || *s == 'x' || *s == 'X')
6009 // make it use a good integer type
6010 for(p = INT_LOSSLESS_FORMAT_SIZE; *p; )
6016 if(width < 0) // not set
6022 if(precision < 0) // not set
6023 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? INT_LOSSLESS_FORMAT_CONVERT_S(GETARG_FLOAT(thisarg)) : INT_LOSSLESS_FORMAT_CONVERT_S(GETARG_INT(thisarg))));
6025 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))));
6027 case 'o': case 'u': case 'x': case 'X':
6028 if(precision < 0) // not set
6029 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? INT_LOSSLESS_FORMAT_CONVERT_U(GETARG_FLOAT(thisarg)) : INT_LOSSLESS_FORMAT_CONVERT_U(GETARG_INT(thisarg))));
6031 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))));
6033 case 'e': case 'E': case 'f': case 'F': case 'g': case 'G':
6034 if(precision < 0) // not set
6035 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? (double) GETARG_FLOAT(thisarg) : (double) GETARG_INT(thisarg)));
6037 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? (double) GETARG_FLOAT(thisarg) : (double) GETARG_INT(thisarg)));
6041 if(precision < 0) // not set
6042 o += dpsnprintf(o, end - o, va(vabuf, sizeof(vabuf), "%s %s %s", /* NESTED SPRINTF IS NESTED */ formatbuf, formatbuf, formatbuf),
6043 width, (isfloat ? (double) GETARG_VECTOR(thisarg)[0] : (double) GETARG_INTVECTOR(thisarg)[0]),
6044 width, (isfloat ? (double) GETARG_VECTOR(thisarg)[1] : (double) GETARG_INTVECTOR(thisarg)[1]),
6045 width, (isfloat ? (double) GETARG_VECTOR(thisarg)[2] : (double) GETARG_INTVECTOR(thisarg)[2])
6048 o += dpsnprintf(o, end - o, va(vabuf, sizeof(vabuf), "%s %s %s", /* NESTED SPRINTF IS NESTED */ formatbuf, formatbuf, formatbuf),
6049 width, precision, (isfloat ? (double) GETARG_VECTOR(thisarg)[0] : (double) GETARG_INTVECTOR(thisarg)[0]),
6050 width, precision, (isfloat ? (double) GETARG_VECTOR(thisarg)[1] : (double) GETARG_INTVECTOR(thisarg)[1]),
6051 width, precision, (isfloat ? (double) GETARG_VECTOR(thisarg)[2] : (double) GETARG_INTVECTOR(thisarg)[2])
6055 if(flags & PRINTF_ALTERNATE)
6057 if(precision < 0) // not set
6058 o += dpsnprintf(o, end - o, formatbuf, width, (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg)));
6060 o += dpsnprintf(o, end - o, formatbuf, width, precision, (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg)));
6064 unsigned int c = (isfloat ? (unsigned int) GETARG_FLOAT(thisarg) : (unsigned int) GETARG_INT(thisarg));
6066 const char *buf = u8_encodech(c, NULL, charbuf16);
6069 if(precision < 0) // not set
6070 precision = end - o - 1;
6071 o += u8_strpad(o, end - o, buf, (flags & PRINTF_LEFT) != 0, width, precision);
6074 //spike FIXME -- 'S' for quoted tokenize-safe-or-print escaping of strings so stuff can safely survive console commands.
6076 if(flags & PRINTF_ALTERNATE)
6078 if(precision < 0) // not set
6079 o += dpsnprintf(o, end - o, formatbuf, width, GETARG_STRING(thisarg));
6081 o += dpsnprintf(o, end - o, formatbuf, width, precision, GETARG_STRING(thisarg));
6085 if(precision < 0) // not set
6086 precision = end - o - 1;
6087 if(flags & PRINTF_SIGNPOSITIVE)
6088 o += u8_strpad(o, end - o, GETARG_STRING(thisarg), (flags & PRINTF_LEFT) != 0, width, precision);
6090 o += u8_strpad_colorcodes(o, end - o, GETARG_STRING(thisarg), (flags & PRINTF_LEFT) != 0, width, precision);
6094 VM_Warning(prog, "VM_sprintf: invalid directive in %s: %s\n", prog->name, s0);
6111 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, outbuf, o - outbuf);
6117 static model_t *getmodel(prvm_prog_t *prog, prvm_edict_t *ed)
6119 if (prog == SVVM_prog)
6120 return SV_GetModelFromEdict(ed);
6121 else if (prog == CLVM_prog)
6122 return CL_GetModelFromEdict(ed);
6127 struct animatemodel_cache
6130 frameblend_t frameblend[MAX_FRAMEBLENDS];
6131 skeleton_t *skeleton_p;
6132 skeleton_t skeleton;
6133 float *data_vertex3f;
6134 float *data_svector3f;
6135 float *data_tvector3f;
6136 float *data_normal3f;
6138 float *buf_vertex3f;
6139 float *buf_svector3f;
6140 float *buf_tvector3f;
6141 float *buf_normal3f;
6144 static void animatemodel_reset(prvm_prog_t *prog)
6146 if (!prog->animatemodel_cache)
6148 if(prog->animatemodel_cache->buf_vertex3f) Mem_Free(prog->animatemodel_cache->buf_vertex3f);
6149 if(prog->animatemodel_cache->buf_svector3f) Mem_Free(prog->animatemodel_cache->buf_svector3f);
6150 if(prog->animatemodel_cache->buf_tvector3f) Mem_Free(prog->animatemodel_cache->buf_tvector3f);
6151 if(prog->animatemodel_cache->buf_normal3f) Mem_Free(prog->animatemodel_cache->buf_normal3f);
6152 Mem_Free(prog->animatemodel_cache);
6155 static void animatemodel(prvm_prog_t *prog, model_t *model, prvm_edict_t *ed)
6157 skeleton_t *skeleton;
6158 int skeletonindex = -1;
6160 struct animatemodel_cache *animatemodel_cache;
6161 if (!prog->animatemodel_cache)
6163 prog->animatemodel_cache = (struct animatemodel_cache *)Mem_Alloc(prog->progs_mempool, sizeof(struct animatemodel_cache));
6164 memset(prog->animatemodel_cache, 0, sizeof(struct animatemodel_cache));
6166 animatemodel_cache = prog->animatemodel_cache;
6167 if(!(model->surfmesh.isanimated && model->AnimateVertices))
6169 animatemodel_cache->data_vertex3f = model->surfmesh.data_vertex3f;
6170 animatemodel_cache->data_svector3f = model->surfmesh.data_svector3f;
6171 animatemodel_cache->data_tvector3f = model->surfmesh.data_tvector3f;
6172 animatemodel_cache->data_normal3f = model->surfmesh.data_normal3f;
6175 need |= (animatemodel_cache->model != model);
6176 VM_GenerateFrameGroupBlend(prog, ed->priv.server->framegroupblend, ed);
6177 VM_FrameBlendFromFrameGroupBlend(ed->priv.server->frameblend, ed->priv.server->framegroupblend, model, PRVM_serverglobalfloat(time));
6178 need |= (memcmp(&animatemodel_cache->frameblend, &ed->priv.server->frameblend, sizeof(ed->priv.server->frameblend))) != 0;
6179 skeletonindex = (int)PRVM_gameedictfloat(ed, skeletonindex) - 1;
6180 if (!(skeletonindex >= 0 && skeletonindex < MAX_EDICTS && (skeleton = prog->skeletons[skeletonindex]) && skeleton->model->num_bones == ed->priv.server->skeleton.model->num_bones))
6182 need |= (animatemodel_cache->skeleton_p != skeleton);
6184 need |= (memcmp(&animatemodel_cache->skeleton, skeleton, sizeof(ed->priv.server->skeleton))) != 0;
6187 if(model->surfmesh.num_vertices > animatemodel_cache->max_vertices)
6189 animatemodel_cache->max_vertices = model->surfmesh.num_vertices * 2;
6190 if(animatemodel_cache->buf_vertex3f) Mem_Free(animatemodel_cache->buf_vertex3f);
6191 if(animatemodel_cache->buf_svector3f) Mem_Free(animatemodel_cache->buf_svector3f);
6192 if(animatemodel_cache->buf_tvector3f) Mem_Free(animatemodel_cache->buf_tvector3f);
6193 if(animatemodel_cache->buf_normal3f) Mem_Free(animatemodel_cache->buf_normal3f);
6194 animatemodel_cache->buf_vertex3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache->max_vertices);
6195 animatemodel_cache->buf_svector3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache->max_vertices);
6196 animatemodel_cache->buf_tvector3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache->max_vertices);
6197 animatemodel_cache->buf_normal3f = (float *)Mem_Alloc(prog->progs_mempool, sizeof(float[3]) * animatemodel_cache->max_vertices);
6199 animatemodel_cache->data_vertex3f = animatemodel_cache->buf_vertex3f;
6200 animatemodel_cache->data_svector3f = animatemodel_cache->buf_svector3f;
6201 animatemodel_cache->data_tvector3f = animatemodel_cache->buf_tvector3f;
6202 animatemodel_cache->data_normal3f = animatemodel_cache->buf_normal3f;
6203 VM_UpdateEdictSkeleton(prog, ed, model, ed->priv.server->frameblend);
6204 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);
6205 animatemodel_cache->model = model;
6206 memcpy(&animatemodel_cache->frameblend, &ed->priv.server->frameblend, sizeof(ed->priv.server->frameblend));
6207 animatemodel_cache->skeleton_p = skeleton;
6209 memcpy(&animatemodel_cache->skeleton, skeleton, sizeof(ed->priv.server->skeleton));
6212 static void getmatrix(prvm_prog_t *prog, prvm_edict_t *ed, matrix4x4_t *out)
6214 if (prog == SVVM_prog)
6215 SV_GetEntityMatrix(prog, ed, out, false);
6216 else if (prog == CLVM_prog)
6217 CL_GetEntityMatrix(prog, ed, out, false);
6219 *out = identitymatrix;
6222 static void applytransform_forward(prvm_prog_t *prog, const vec3_t in, prvm_edict_t *ed, vec3_t out)
6225 getmatrix(prog, ed, &m);
6226 Matrix4x4_Transform(&m, in, out);
6229 static void applytransform_forward_direction(prvm_prog_t *prog, const vec3_t in, prvm_edict_t *ed, vec3_t out)
6232 getmatrix(prog, ed, &m);
6233 Matrix4x4_Transform3x3(&m, in, out);
6236 static void applytransform_inverted(prvm_prog_t *prog, const vec3_t in, prvm_edict_t *ed, vec3_t out)
6239 getmatrix(prog, ed, &m);
6240 Matrix4x4_Invert_Full(&n, &m);
6241 Matrix4x4_Transform3x3(&n, in, out);
6244 static void applytransform_forward_normal(prvm_prog_t *prog, const vec3_t in, prvm_edict_t *ed, vec3_t out)
6248 getmatrix(prog, ed, &m);
6249 Matrix4x4_TransformPositivePlane(&m, in[0], in[1], in[2], 0, p);
6253 static void clippointtosurface(prvm_prog_t *prog, prvm_edict_t *ed, model_t *model, msurface_t *surface, vec3_t p, vec3_t out)
6256 float *v[3], facenormal[3], edgenormal[3], sidenormal[3], temp[3], offsetdist, dist, bestdist;
6258 animatemodel(prog, model, ed);
6259 bestdist = 1000000000;
6261 for (i = 0, e = (model->surfmesh.data_element3i + 3 * surface->num_firsttriangle);i < surface->num_triangles;i++, e += 3)
6263 // clip original point to each triangle of the surface and find the
6264 // triangle that is closest
6265 v[0] = prog->animatemodel_cache->data_vertex3f + e[0] * 3;
6266 v[1] = prog->animatemodel_cache->data_vertex3f + e[1] * 3;
6267 v[2] = prog->animatemodel_cache->data_vertex3f + e[2] * 3;
6268 TriangleNormal(v[0], v[1], v[2], facenormal);
6269 VectorNormalize(facenormal);
6270 offsetdist = DotProduct(v[0], facenormal) - DotProduct(p, facenormal);
6271 VectorMA(p, offsetdist, facenormal, temp);
6272 for (j = 0, k = 2;j < 3;k = j, j++)
6274 VectorSubtract(v[k], v[j], edgenormal);
6275 CrossProduct(edgenormal, facenormal, sidenormal);
6276 VectorNormalize(sidenormal);
6277 offsetdist = DotProduct(v[k], sidenormal) - DotProduct(temp, sidenormal);
6279 VectorMA(temp, offsetdist, sidenormal, temp);
6281 dist = VectorDistance2(temp, p);
6282 if (bestdist > dist)
6285 VectorCopy(temp, out);
6290 static msurface_t *getsurface(model_t *model, int surfacenum)
6292 if (surfacenum < 0 || surfacenum >= model->submodelsurfaces_end - model->submodelsurfaces_start)
6294 return model->data_surfaces + surfacenum + model->submodelsurfaces_start;
6298 //PF_getsurfacenumpoints, // #434 float(entity e, float s) getsurfacenumpoints = #434;
6299 void VM_getsurfacenumpoints(prvm_prog_t *prog)
6302 msurface_t *surface;
6303 VM_SAFEPARMCOUNT(2, VM_getsurfacenumpoints);
6304 // return 0 if no such surface
6305 if (!(model = getmodel(prog, PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6307 PRVM_G_FLOAT(OFS_RETURN) = 0;
6311 // note: this (incorrectly) assumes it is a simple polygon
6312 PRVM_G_FLOAT(OFS_RETURN) = surface->num_vertices;
6314 //PF_getsurfacepoint, // #435 vector(entity e, float s, float n) getsurfacepoint = #435;
6315 void VM_getsurfacepoint(prvm_prog_t *prog)
6319 msurface_t *surface;
6322 VM_SAFEPARMCOUNT(3, VM_getsurfacepoint);
6323 VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6324 ed = PRVM_G_EDICT(OFS_PARM0);
6325 if (!(model = getmodel(prog, ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6327 // note: this (incorrectly) assumes it is a simple polygon
6328 pointnum = (int)PRVM_G_FLOAT(OFS_PARM2);
6329 if (pointnum < 0 || pointnum >= surface->num_vertices)
6331 animatemodel(prog, model, ed);
6332 applytransform_forward(prog, &(prog->animatemodel_cache->data_vertex3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, result);
6333 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6335 //PF_getsurfacepointattribute, // #486 vector(entity e, float s, float n, float a) getsurfacepointattribute = #486;
6336 // float SPA_POSITION = 0;
6337 // float SPA_S_AXIS = 1;
6338 // float SPA_T_AXIS = 2;
6339 // float SPA_R_AXIS = 3; // same as SPA_NORMAL
6340 // float SPA_TEXCOORDS0 = 4;
6341 // float SPA_LIGHTMAP0_TEXCOORDS = 5;
6342 // float SPA_LIGHTMAP0_COLOR = 6;
6343 void VM_getsurfacepointattribute(prvm_prog_t *prog)
6347 msurface_t *surface;
6352 VM_SAFEPARMCOUNT(4, VM_getsurfacepointattribute);
6353 VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6354 ed = PRVM_G_EDICT(OFS_PARM0);
6355 if (!(model = getmodel(prog, ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6357 pointnum = (int)PRVM_G_FLOAT(OFS_PARM2);
6358 if (pointnum < 0 || pointnum >= surface->num_vertices)
6360 attributetype = (int) PRVM_G_FLOAT(OFS_PARM3);
6362 animatemodel(prog, model, ed);
6364 switch( attributetype ) {
6365 // float SPA_POSITION = 0;
6367 applytransform_forward(prog, &(prog->animatemodel_cache->data_vertex3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, result);
6368 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6370 // float SPA_S_AXIS = 1;
6372 applytransform_forward_direction(prog, &(prog->animatemodel_cache->data_svector3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, result);
6373 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6375 // float SPA_T_AXIS = 2;
6377 applytransform_forward_direction(prog, &(prog->animatemodel_cache->data_tvector3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, result);
6378 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6380 // float SPA_R_AXIS = 3; // same as SPA_NORMAL
6382 applytransform_forward_direction(prog, &(prog->animatemodel_cache->data_normal3f + 3 * surface->num_firstvertex)[pointnum * 3], ed, result);
6383 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6385 // float SPA_TEXCOORDS0 = 4;
6387 float *texcoord = &(model->surfmesh.data_texcoordtexture2f + 2 * surface->num_firstvertex)[pointnum * 2];
6388 result[0] = texcoord[0];
6389 result[1] = texcoord[1];
6391 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6394 // float SPA_LIGHTMAP0_TEXCOORDS = 5;
6396 float *texcoord = &(model->surfmesh.data_texcoordlightmap2f + 2 * surface->num_firstvertex)[pointnum * 2];
6397 result[0] = texcoord[0];
6398 result[1] = texcoord[1];
6400 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6403 // float SPA_LIGHTMAP0_COLOR = 6;
6405 // ignore alpha for now..
6406 VectorCopy( &(model->surfmesh.data_lightmapcolor4f + 4 * surface->num_firstvertex)[pointnum * 4], PRVM_G_VECTOR(OFS_RETURN));
6409 VectorSet( PRVM_G_VECTOR(OFS_RETURN), 0.0f, 0.0f, 0.0f );
6413 //PF_getsurfacenormal, // #436 vector(entity e, float s) getsurfacenormal = #436;
6414 void VM_getsurfacenormal(prvm_prog_t *prog)
6417 msurface_t *surface;
6420 VM_SAFEPARMCOUNT(2, VM_getsurfacenormal);
6421 VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6422 if (!(model = getmodel(prog, PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6424 // note: this only returns the first triangle, so it doesn't work very
6425 // well for curved surfaces or arbitrary meshes
6426 animatemodel(prog, model, PRVM_G_EDICT(OFS_PARM0));
6427 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);
6428 applytransform_forward_normal(prog, normal, PRVM_G_EDICT(OFS_PARM0), result);
6429 VectorNormalize(result);
6430 VectorCopy(result, PRVM_G_VECTOR(OFS_RETURN));
6432 //PF_getsurfacetexture, // #437 string(entity e, float s) getsurfacetexture = #437;
6433 void VM_getsurfacetexture(prvm_prog_t *prog)
6436 msurface_t *surface;
6438 VM_SAFEPARMCOUNT(2, VM_getsurfacetexture);
6439 PRVM_G_INT(OFS_RETURN) = OFS_NULL;
6440 if (!(model = getmodel(prog, PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6442 PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, surface->texture->name, strlen(surface->texture->name));
6444 //PF_getsurfacenearpoint, // #438 float(entity e, vector p) getsurfacenearpoint = #438;
6445 void VM_getsurfacenearpoint(prvm_prog_t *prog)
6447 int surfacenum, best;
6449 vec_t dist, bestdist;
6452 msurface_t *surface;
6454 VM_SAFEPARMCOUNT(2, VM_getsurfacenearpoint);
6455 PRVM_G_FLOAT(OFS_RETURN) = -1;
6456 ed = PRVM_G_EDICT(OFS_PARM0);
6457 VectorCopy(PRVM_G_VECTOR(OFS_PARM1), point);
6459 if (!ed || ed->free)
6461 model = getmodel(prog, ed);
6462 if (!model || !model->num_surfaces)
6465 animatemodel(prog, model, ed);
6467 applytransform_inverted(prog, point, ed, p);
6469 bestdist = 1000000000;
6470 for (surfacenum = model->submodelsurfaces_start;surfacenum < model->submodelsurfaces_end;surfacenum++)
6472 surface = model->data_surfaces + surfacenum;
6473 // first see if the nearest point on the surface's box is closer than the previous match
6474 clipped[0] = bound(surface->mins[0], p[0], surface->maxs[0]) - p[0];
6475 clipped[1] = bound(surface->mins[1], p[1], surface->maxs[1]) - p[1];
6476 clipped[2] = bound(surface->mins[2], p[2], surface->maxs[2]) - p[2];
6477 dist = VectorLength2(clipped);
6478 if (dist < bestdist)
6480 // it is, check the nearest point on the actual geometry
6481 clippointtosurface(prog, ed, model, surface, p, clipped);
6482 VectorSubtract(clipped, p, clipped);
6483 dist += VectorLength2(clipped);
6484 if (dist < bestdist)
6486 // that's closer too, store it as the best match
6487 best = surfacenum - model->submodelsurfaces_start;
6492 PRVM_G_FLOAT(OFS_RETURN) = best;
6494 //PF_getsurfaceclippedpoint, // #439 vector(entity e, float s, vector p) getsurfaceclippedpoint = #439;
6495 void VM_getsurfaceclippedpoint(prvm_prog_t *prog)
6499 msurface_t *surface;
6501 VM_SAFEPARMCOUNT(3, VM_getsurfaceclippedpoint);
6502 VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6503 ed = PRVM_G_EDICT(OFS_PARM0);
6504 if (!(model = getmodel(prog, ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6506 animatemodel(prog, model, ed);
6507 VectorCopy(PRVM_G_VECTOR(OFS_PARM2), inp);
6508 applytransform_inverted(prog, inp, ed, p);
6509 clippointtosurface(prog, ed, model, surface, p, out);
6510 VectorAdd(out, PRVM_serveredictvector(ed, origin), PRVM_G_VECTOR(OFS_RETURN));
6513 //PF_getsurfacenumtriangles, // #??? float(entity e, float s) getsurfacenumtriangles = #???;
6514 void VM_getsurfacenumtriangles(prvm_prog_t *prog)
6517 msurface_t *surface;
6518 VM_SAFEPARMCOUNT(2, VM_getsurfacenumtriangles);
6519 // return 0 if no such surface
6520 if (!(model = getmodel(prog, PRVM_G_EDICT(OFS_PARM0))) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6522 PRVM_G_FLOAT(OFS_RETURN) = 0;
6526 PRVM_G_FLOAT(OFS_RETURN) = surface->num_triangles;
6528 //PF_getsurfacetriangle, // #??? vector(entity e, float s, float n) getsurfacetriangle = #???;
6529 void VM_getsurfacetriangle(prvm_prog_t *prog)
6531 const vec3_t d = {-1, -1, -1};
6534 msurface_t *surface;
6536 VM_SAFEPARMCOUNT(3, VM_getsurfacetriangle);
6537 VectorClear(PRVM_G_VECTOR(OFS_RETURN));
6538 ed = PRVM_G_EDICT(OFS_PARM0);
6539 if (!(model = getmodel(prog, ed)) || !(surface = getsurface(model, (int)PRVM_G_FLOAT(OFS_PARM1))))
6541 trinum = (int)PRVM_G_FLOAT(OFS_PARM2);
6542 if (trinum < 0 || trinum >= surface->num_triangles)
6544 // FIXME: implement rotation/scaling
6545 VectorMA(&(model->surfmesh.data_element3i + 3 * surface->num_firsttriangle)[trinum * 3], surface->num_firstvertex, d, PRVM_G_VECTOR(OFS_RETURN));
6553 #define VM_physics_ApplyCmd(ed,f) if (!ed->priv.server->ode_body) VM_physics_newstackfunction(prog, ed, f); else World_Physics_ApplyCmd(ed, f)
6555 static edict_odefunc_t *VM_physics_newstackfunction(prvm_prog_t *prog, prvm_edict_t *ed, edict_odefunc_t *f)
6557 edict_odefunc_t *newfunc, *func;
6559 newfunc = (edict_odefunc_t *)Mem_Alloc(prog->progs_mempool, sizeof(edict_odefunc_t));
6560 memcpy(newfunc, f, sizeof(edict_odefunc_t));
6561 newfunc->next = NULL;
6562 if (!ed->priv.server->ode_func)
6563 ed->priv.server->ode_func = newfunc;
6566 for (func = ed->priv.server->ode_func; func->next; func = func->next);
6567 func->next = newfunc;
6573 // void(entity e, float physics_enabled) physics_enable = #;
6574 void VM_physics_enable(prvm_prog_t *prog)
6580 VM_SAFEPARMCOUNT(2, VM_physics_enable);
6582 ed = PRVM_G_EDICT(OFS_PARM0);
6585 if (developer.integer > 0)
6586 VM_Warning(prog, "VM_physics_enable: null entity!\n");
6589 // entity should have MOVETYPE_PHYSICS already set, this can damage memory (making leaked allocation) so warn about this even if non-developer
6590 if (PRVM_serveredictfloat(ed, movetype) != MOVETYPE_PHYSICS)
6592 VM_Warning(prog, "VM_physics_enable: entity is not MOVETYPE_PHYSICS!\n");
6595 f.type = PRVM_G_FLOAT(OFS_PARM1) == 0 ? ODEFUNC_DISABLE : ODEFUNC_ENABLE;
6596 VM_physics_ApplyCmd(ed, &f);
6600 // void(entity e, vector force, vector relative_ofs) physics_addforce = #;
6601 void VM_physics_addforce(prvm_prog_t *prog)
6607 VM_SAFEPARMCOUNT(3, VM_physics_addforce);
6609 ed = PRVM_G_EDICT(OFS_PARM0);
6612 if (developer.integer > 0)
6613 VM_Warning(prog, "VM_physics_addforce: null entity!\n");
6616 // entity should have MOVETYPE_PHYSICS already set, this can damage memory (making leaked allocation) so warn about this even if non-developer
6617 if (PRVM_serveredictfloat(ed, movetype) != MOVETYPE_PHYSICS)
6619 VM_Warning(prog, "VM_physics_addforce: entity is not MOVETYPE_PHYSICS!\n");
6622 f.type = ODEFUNC_FORCE;
6623 VectorCopy(PRVM_G_VECTOR(OFS_PARM1), f.v1);
6624 VectorCopy(PRVM_G_VECTOR(OFS_PARM2), f.v2);
6625 VM_physics_ApplyCmd(ed, &f);
6629 // void(entity e, vector torque) physics_addtorque = #;
6630 void VM_physics_addtorque(prvm_prog_t *prog)
6636 VM_SAFEPARMCOUNT(2, VM_physics_addtorque);
6638 ed = PRVM_G_EDICT(OFS_PARM0);
6641 if (developer.integer > 0)
6642 VM_Warning(prog, "VM_physics_addtorque: null entity!\n");
6645 // entity should have MOVETYPE_PHYSICS already set, this can damage memory (making leaked allocation) so warn about this even if non-developer
6646 if (PRVM_serveredictfloat(ed, movetype) != MOVETYPE_PHYSICS)
6648 VM_Warning(prog, "VM_physics_addtorque: entity is not MOVETYPE_PHYSICS!\n");
6651 f.type = ODEFUNC_TORQUE;
6652 VectorCopy(PRVM_G_VECTOR(OFS_PARM1), f.v1);
6653 VM_physics_ApplyCmd(ed, &f);
6657 extern cvar_t prvm_coverage;
6658 void VM_coverage(prvm_prog_t *prog)
6660 VM_SAFEPARMCOUNT(0, VM_coverage);
6661 if (prog->explicit_profile[prog->xstatement]++ == 0 && (prvm_coverage.integer & 2))
6662 PRVM_ExplicitCoverageEvent(prog, prog->xfunction, prog->xstatement);