]> git.xonotic.org Git - xonotic/darkplaces.git/blob - csprogs.c
-added game Blood Omnicide
[xonotic/darkplaces.git] / csprogs.c
1 #include "quakedef.h"
2 #include "progsvm.h"
3 #include "clprogdefs.h"
4 #include "csprogs.h"
5 #include "cl_collision.h"
6 #include "snd_main.h"
7 #include "clvm_cmds.h"
8 #include "prvm_cmds.h"
9
10 //============================================================================
11 // Client prog handling
12 //[515]: omg !!! optimize it ! a lot of hacks here and there also :P
13
14 #define CSQC_RETURNVAL  prog->globals.generic[OFS_RETURN]
15 #define CSQC_BEGIN              csqc_tmpprog=prog;prog=0;PRVM_SetProg(PRVM_CLIENTPROG);
16 #define CSQC_END                prog=csqc_tmpprog;
17
18 static prvm_prog_t *csqc_tmpprog;
19
20 void CL_VM_PreventInformationLeaks(void)
21 {
22         prvm_eval_t *val;
23         if(!cl.csqc_loaded)
24                 return;
25         CSQC_BEGIN
26                 VM_ClearTraceGlobals();
27                 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_networkentity)))
28                         val->_float = 0;
29         CSQC_END
30 }
31
32 //[515]: these are required funcs
33 static char *cl_required_func[] =
34 {
35         "CSQC_Init",
36         "CSQC_InputEvent",
37         "CSQC_UpdateView",
38         "CSQC_ConsoleCommand",
39 };
40
41 static int cl_numrequiredfunc = sizeof(cl_required_func) / sizeof(char*);
42
43 void CL_VM_Error (const char *format, ...) DP_FUNC_PRINTF(1);
44 void CL_VM_Error (const char *format, ...)      //[515]: hope it will be never executed =)
45 {
46         char errorstring[4096];
47         va_list argptr;
48
49         va_start (argptr, format);
50         dpvsnprintf (errorstring, sizeof(errorstring), format, argptr);
51         va_end (argptr);
52 //      Con_Printf( "CL_VM_Error: %s\n", errorstring );
53
54         PRVM_Crash();
55         cl.csqc_loaded = false;
56
57         Cvar_SetValueQuick(&csqc_progcrc, -1);
58         Cvar_SetValueQuick(&csqc_progsize, -1);
59
60 //      Host_AbortCurrentFrame();       //[515]: hmmm... if server says it needs csqc then client MUST disconnect
61         Host_Error("CL_VM_Error: %s", errorstring);
62 }
63 void CL_VM_UpdateDmgGlobals (int dmg_take, int dmg_save, vec3_t dmg_origin)
64 {
65         prvm_eval_t *val;
66         if(cl.csqc_loaded)
67         {
68                 CSQC_BEGIN
69                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.dmg_take);
70                 if(val)
71                         val->_float = dmg_take;
72                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.dmg_save);
73                 if(val)
74                         val->_float = dmg_save;
75                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.dmg_origin);
76                 if(val)
77                 {
78                         val->vector[0] = dmg_origin[0];
79                         val->vector[1] = dmg_origin[1];
80                         val->vector[2] = dmg_origin[2];
81                 }
82                 CSQC_END
83         }
84 }
85
86 void CSQC_UpdateNetworkTimes(double newtime, double oldtime)
87 {
88         prvm_eval_t *val;
89         if(!cl.csqc_loaded)
90                 return;
91         CSQC_BEGIN
92         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.servertime)))
93                 val->_float = newtime;
94         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.serverprevtime)))
95                 val->_float = oldtime;
96         if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.serverdeltatime)))
97                 val->_float = newtime - oldtime;
98         CSQC_END
99 }
100
101 //[515]: set globals before calling R_UpdateView, WEIRD CRAP
102 static void CSQC_SetGlobals (void)
103 {
104         prvm_eval_t *val;
105         CSQC_BEGIN
106                 prog->globals.client->time = cl.time;
107                 prog->globals.client->frametime = max(0, cl.time - cl.oldtime);
108                 prog->globals.client->servercommandframe = cls.servermovesequence;
109                 prog->globals.client->clientcommandframe = cl.movecmd[0].sequence;
110                 VectorCopy(cl.viewangles, prog->globals.client->input_angles);
111                 VectorCopy(cl.viewangles, cl.csqc_angles);
112                 // // FIXME: this actually belongs into getinputstate().. [12/17/2007 Black]
113                 prog->globals.client->input_buttons = cl.movecmd[0].buttons;
114                 VectorSet(prog->globals.client->input_movevalues, cl.movecmd[0].forwardmove, cl.movecmd[0].sidemove, cl.movecmd[0].upmove);
115                 //VectorCopy(cl.movement_origin, cl.csqc_origin);
116                 Matrix4x4_OriginFromMatrix(&cl.entities[cl.viewentity].render.matrix, cl.csqc_origin);
117
118                 // LordHavoc: Spike says not to do this, but without pmove_org the
119                 // CSQC is useless as it can't alter the view origin without
120                 // completely replacing it
121                 VectorCopy(cl.csqc_origin, prog->globals.client->pmove_org);
122                 VectorCopy(cl.movement_velocity, prog->globals.client->pmove_vel);
123
124                 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.view_angles)))
125                         VectorCopy(cl.viewangles, val->vector);
126                 prog->globals.client->maxclients = cl.maxclients;
127         CSQC_END
128 }
129
130 void CSQC_Predraw (prvm_edict_t *ed)
131 {
132         int b;
133         if(!ed->fields.client->predraw)
134                 return;
135         b = prog->globals.client->self;
136         prog->globals.client->self = PRVM_EDICT_TO_PROG(ed);
137         PRVM_ExecuteProgram(ed->fields.client->predraw, "CSQC_Predraw: NULL function\n");
138         prog->globals.client->self = b;
139 }
140
141 void CSQC_Think (prvm_edict_t *ed)
142 {
143         int b;
144         if(ed->fields.client->think)
145         if(ed->fields.client->nextthink && ed->fields.client->nextthink <= prog->globals.client->time)
146         {
147                 ed->fields.client->nextthink = 0;
148                 b = prog->globals.client->self;
149                 prog->globals.client->self = PRVM_EDICT_TO_PROG(ed);
150                 PRVM_ExecuteProgram(ed->fields.client->think, "CSQC_Think: NULL function\n");
151                 prog->globals.client->self = b;
152         }
153 }
154
155 extern cvar_t cl_noplayershadow;
156 qboolean CSQC_AddRenderEdict(prvm_edict_t *ed)
157 {
158         int renderflags;
159         int c;
160         float scale;
161         prvm_eval_t *val;
162         entity_render_t *entrender;
163         dp_model_t *model;
164         matrix4x4_t tagmatrix, matrix2;
165
166         model = CL_GetModelFromEdict(ed);
167         if (!model)
168                 return false;
169
170         entrender = CL_NewTempEntity(0);
171         if (!entrender)
172                 return false;
173
174         entrender->model = model;
175         entrender->skinnum = (int)ed->fields.client->skin;
176         entrender->effects |= entrender->model->effects;
177         scale = 1;
178         renderflags = 0;
179         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.renderflags)) && val->_float)     renderflags = (int)val->_float;
180         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.alpha)) && val->_float)           entrender->alpha = val->_float;
181         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.scale)) && val->_float)           entrender->scale = scale = val->_float;
182         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.colormod)) && VectorLength2(val->vector)) VectorCopy(val->vector, entrender->colormod);
183         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.glowmod)) && VectorLength2(val->vector))  VectorCopy(val->vector, entrender->glowmod);
184         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.effects)) && val->_float) entrender->effects |= (int)val->_float;
185         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.tag_entity)) && val->edict)
186         {
187                 int tagentity;
188                 int tagindex = 0;
189                 tagentity = val->edict;
190                 if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.tag_index)) && val->_float)
191                         tagindex = (int)val->_float;
192                 CL_GetTagMatrix (&tagmatrix, PRVM_PROG_TO_EDICT(tagentity), tagindex);
193         }
194         else
195                 Matrix4x4_CreateIdentity(&tagmatrix);
196         if (!VectorLength2(entrender->colormod))
197                 VectorSet(entrender->colormod, 1, 1, 1);
198         if (!VectorLength2(entrender->glowmod))
199                 VectorSet(entrender->glowmod, 1, 1, 1);
200
201         if (renderflags & RF_USEAXIS)
202         {
203                 vec3_t left;
204                 VectorNegate(prog->globals.client->v_right, left);
205                 Matrix4x4_FromVectors(&matrix2, prog->globals.client->v_forward, left, prog->globals.client->v_up, ed->fields.client->origin);
206                 Matrix4x4_Scale(&matrix2, scale, 1);
207         }
208         else
209         {
210                 vec3_t angles;
211                 VectorCopy(ed->fields.client->angles, angles);
212                 // if model is alias, reverse pitch direction
213                 if (entrender->model->type == mod_alias)
214                         angles[0] = -angles[0];
215
216                 // set up the render matrix
217                 Matrix4x4_CreateFromQuakeEntity(&matrix2, ed->fields.client->origin[0], ed->fields.client->origin[1], ed->fields.client->origin[2], angles[0], angles[1], angles[2], scale);
218         }
219
220         // set up the animation data
221         // self.frame is the interpolation target (new frame)
222         // self.frame1time is the animation base time for the interpolation target
223         // self.frame2 is the interpolation start (previous frame)
224         // self.frame2time is the animation base time for the interpolation start
225         // self.lerpfrac is the interpolation strength for self.frame
226         // 3+ are for additional blends (the main use for this feature is lerping
227         // pitch angle on a player model where the animator set up 5 sets of
228         // animations and the csqc simply lerps between sets)
229         entrender->framegroupblend[0].frame = entrender->framegroupblend[1].frame = (int) ed->fields.client->frame;
230         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame2))) entrender->framegroupblend[1].frame = (int) val->_float;
231         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame3))) entrender->framegroupblend[2].frame = (int) val->_float;
232         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame4))) entrender->framegroupblend[3].frame = (int) val->_float;
233         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame1time))) entrender->framegroupblend[0].start = val->_float;
234         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame2time))) entrender->framegroupblend[1].start = val->_float;
235         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame3time))) entrender->framegroupblend[2].start = val->_float;
236         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame4time))) entrender->framegroupblend[3].start = val->_float;
237         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.lerpfrac))) entrender->framegroupblend[0].lerp = val->_float;
238         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.lerpfrac3))) entrender->framegroupblend[2].lerp = val->_float;
239         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.lerpfrac4))) entrender->framegroupblend[3].lerp = val->_float;
240         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.shadertime))) entrender->shadertime = val->_float;
241         // assume that the (missing) lerpfrac2 is whatever remains after lerpfrac+lerpfrac3+lerpfrac4 are summed
242         entrender->framegroupblend[1].lerp = 1 - entrender->framegroupblend[0].lerp - entrender->framegroupblend[2].lerp - entrender->framegroupblend[3].lerp;
243
244         // concat the matrices to make the entity relative to its tag
245         Matrix4x4_Concat(&entrender->matrix, &tagmatrix, &matrix2);
246
247         // transparent offset
248         if ((renderflags & RF_USETRANSPARENTOFFSET) && (val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.transparent_offset)))
249                 entrender->transparent_offset = val->_float;
250
251         if(renderflags)
252         {
253                 if(renderflags & RF_VIEWMODEL)  entrender->flags |= RENDER_VIEWMODEL;
254                 if(renderflags & RF_EXTERNALMODEL)entrender->flags |= RENDER_EXTERIORMODEL;
255                 if(renderflags & RF_NOCULL)             entrender->flags |= RENDER_NOCULL;
256                 if(renderflags & RF_DEPTHHACK)  entrender->effects |= EF_NODEPTHTEST;
257                 if(renderflags & RF_ADDITIVE)           entrender->effects |= EF_ADDITIVE;
258
259         }
260
261         c = (int)ed->fields.client->colormap;
262         if (c <= 0)
263                 CL_SetEntityColormapColors(entrender, -1);
264         else if (c <= cl.maxclients && cl.scores != NULL)
265                 CL_SetEntityColormapColors(entrender, cl.scores[c-1].colors);
266         else
267                 CL_SetEntityColormapColors(entrender, c);
268
269         entrender->flags &= ~(RENDER_SHADOW | RENDER_LIGHT | RENDER_NOSELFSHADOW);
270         // either fullbright or lit
271         if (!(entrender->effects & EF_FULLBRIGHT) && !r_fullbright.integer)
272                 entrender->flags |= RENDER_LIGHT;
273         // hide player shadow during intermission or nehahra movie
274         if (!(entrender->effects & (EF_NOSHADOW | EF_ADDITIVE | EF_NODEPTHTEST))
275          &&  (entrender->alpha >= 1)
276          && !(entrender->flags & RENDER_VIEWMODEL)
277          && (!(entrender->flags & RENDER_EXTERIORMODEL) || (!cl.intermission && cls.protocol != PROTOCOL_NEHAHRAMOVIE && !cl_noplayershadow.integer)))
278                 entrender->flags |= RENDER_SHADOW;
279         if (entrender->flags & RENDER_VIEWMODEL)
280                 entrender->flags |= RENDER_NOSELFSHADOW;
281         if (entrender->effects & EF_NOSELFSHADOW)
282                 entrender->flags |= RENDER_NOSELFSHADOW;
283
284         // make the other useful stuff
285         CL_UpdateRenderEntity(entrender);
286
287         return true;
288 }
289
290 qboolean CL_VM_InputEvent (qboolean down, int key, int ascii)
291 {
292         qboolean r;
293
294         if(!cl.csqc_loaded)
295                 return false;
296
297         CSQC_BEGIN
298                 if (!prog->funcoffsets.CSQC_InputEvent)
299                         r = false;
300                 else
301                 {
302                         prog->globals.client->time = cl.time;
303                         prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
304                         PRVM_G_FLOAT(OFS_PARM0) = !down; // 0 is down, 1 is up
305                         PRVM_G_FLOAT(OFS_PARM1) = key;
306                         PRVM_G_FLOAT(OFS_PARM2) = ascii;
307                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_InputEvent, "QC function CSQC_InputEvent is missing");
308                         r = CSQC_RETURNVAL != 0;
309                 }
310         CSQC_END
311         return r;
312 }
313
314 qboolean CL_VM_UpdateView (void)
315 {
316         vec3_t emptyvector;
317         emptyvector[0] = 0;
318         emptyvector[1] = 0;
319         emptyvector[2] = 0;
320 //      vec3_t oldangles;
321         if(!cl.csqc_loaded)
322                 return false;
323         CSQC_BEGIN
324                 //VectorCopy(cl.viewangles, oldangles);
325                 prog->globals.client->time = cl.time;
326                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
327                 CSQC_SetGlobals();
328                 // clear renderable entity and light lists to prevent crashes if the
329                 // CSQC_UpdateView function does not call R_ClearScene as it should
330                 r_refdef.scene.numentities = 0;
331                 r_refdef.scene.numlights = 0;
332                 // pass in width and height as parameters (EXT_CSQC_1)
333                 PRVM_G_FLOAT(OFS_PARM0) = vid.width;
334                 PRVM_G_FLOAT(OFS_PARM1) = vid.height;
335                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_UpdateView, "QC function CSQC_UpdateView is missing");
336                 //VectorCopy(oldangles, cl.viewangles);
337                 // Dresk : Reset Dmg Globals Here
338                 CL_VM_UpdateDmgGlobals(0, 0, emptyvector);
339         CSQC_END
340         return true;
341 }
342
343 extern sizebuf_t vm_tempstringsbuf;
344 qboolean CL_VM_ConsoleCommand (const char *cmd)
345 {
346         int restorevm_tempstringsbuf_cursize;
347         qboolean r = false;
348         if(!cl.csqc_loaded)
349                 return false;
350         CSQC_BEGIN
351         if (prog->funcoffsets.CSQC_ConsoleCommand)
352         {
353                 prog->globals.client->time = cl.time;
354                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
355                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
356                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(cmd);
357                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_ConsoleCommand, "QC function CSQC_ConsoleCommand is missing");
358                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
359                 r = CSQC_RETURNVAL != 0;
360         }
361         CSQC_END
362         return r;
363 }
364
365 qboolean CL_VM_Parse_TempEntity (void)
366 {
367         int                     t;
368         qboolean        r = false;
369         if(!cl.csqc_loaded)
370                 return false;
371         CSQC_BEGIN
372         if(prog->funcoffsets.CSQC_Parse_TempEntity)
373         {
374                 t = msg_readcount;
375                 prog->globals.client->time = cl.time;
376                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
377                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_TempEntity, "QC function CSQC_Parse_TempEntity is missing");
378                 r = CSQC_RETURNVAL != 0;
379                 if(!r)
380                 {
381                         msg_readcount = t;
382                         msg_badread = false;
383                 }
384         }
385         CSQC_END
386         return r;
387 }
388
389 void CL_VM_Parse_StuffCmd (const char *msg)
390 {
391         int restorevm_tempstringsbuf_cursize;
392         if(msg[0] == 'c')
393         if(msg[1] == 's')
394         if(msg[2] == 'q')
395         if(msg[3] == 'c')
396         {
397                 // if this is setting a csqc variable, deprotect csqc_progcrc
398                 // temporarily so that it can be set by the cvar command,
399                 // and then reprotect it afterwards
400                 int crcflags = csqc_progcrc.flags;
401                 int sizeflags = csqc_progcrc.flags;
402                 csqc_progcrc.flags &= ~CVAR_READONLY;
403                 csqc_progsize.flags &= ~CVAR_READONLY;
404                 Cmd_ExecuteString (msg, src_command);
405                 csqc_progcrc.flags = crcflags;
406                 csqc_progsize.flags = sizeflags;
407                 return;
408         }
409
410         if(cls.demoplayback)
411         if(!strncmp(msg, "curl --clear_autodownload\ncurl --pak --forthismap --as ", 55))
412         {
413                 // special handling for map download commands
414                 // run these commands IMMEDIATELY, instead of waiting for a client frame
415                 // that way, there is no black screen when playing back demos
416                 // I know this is a really ugly hack, but I can't think of any better way
417                 // FIXME find the actual CAUSE of this, and make demo playback WAIT
418                 // until all maps are loaded, then remove this hack
419
420                 char buf[MAX_INPUTLINE];
421                 const char *p, *q;
422                 size_t l;
423
424                 p = msg;
425
426                 for(;;)
427                 {
428                         q = strchr(p, '\n');
429                         if(q)
430                                 l = q - p;
431                         else
432                                 l = strlen(p);
433                         if(l > sizeof(buf) - 1)
434                                 l = sizeof(buf) - 1;
435                         strlcpy(buf, p, l + 1); // strlcpy needs a + 1 as it includes the newline!
436
437                         Cmd_ExecuteString(buf, src_command);
438
439                         p += l;
440                         if(*p == '\n')
441                                 ++p; // skip the newline and continue
442                         else
443                                 break; // end of string or overflow
444                 }
445                 Cmd_ExecuteString("curl --clear_autodownload", src_command); // don't inhibit CSQC loading
446                 return;
447         }
448
449         if(!cl.csqc_loaded)
450         {
451                 Cbuf_AddText(msg);
452                 return;
453         }
454         CSQC_BEGIN
455         if(prog->funcoffsets.CSQC_Parse_StuffCmd)
456         {
457                 prog->globals.client->time = cl.time;
458                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
459                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
460                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
461                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_StuffCmd, "QC function CSQC_Parse_StuffCmd is missing");
462                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
463         }
464         else
465                 Cbuf_AddText(msg);
466         CSQC_END
467 }
468
469 static void CL_VM_Parse_Print (const char *msg)
470 {
471         int restorevm_tempstringsbuf_cursize;
472         prog->globals.client->time = cl.time;
473         prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
474         restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
475         PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
476         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_Print, "QC function CSQC_Parse_Print is missing");
477         vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
478 }
479
480 void CSQC_AddPrintText (const char *msg)
481 {
482         size_t i;
483         if(!cl.csqc_loaded)
484         {
485                 Con_Print(msg);
486                 return;
487         }
488         CSQC_BEGIN
489         if(prog->funcoffsets.CSQC_Parse_Print)
490         {
491                 // FIXME: is this bugged?
492                 i = strlen(msg)-1;
493                 if(msg[i] != '\n' && msg[i] != '\r')
494                 {
495                         if(strlen(cl.csqc_printtextbuf)+i >= MAX_INPUTLINE)
496                         {
497                                 CL_VM_Parse_Print(cl.csqc_printtextbuf);
498                                 cl.csqc_printtextbuf[0] = 0;
499                         }
500                         else
501                                 strlcat(cl.csqc_printtextbuf, msg, MAX_INPUTLINE);
502                         return;
503                 }
504                 strlcat(cl.csqc_printtextbuf, msg, MAX_INPUTLINE);
505                 CL_VM_Parse_Print(cl.csqc_printtextbuf);
506                 cl.csqc_printtextbuf[0] = 0;
507         }
508         else
509                 Con_Print(msg);
510         CSQC_END
511 }
512
513 void CL_VM_Parse_CenterPrint (const char *msg)
514 {
515         int restorevm_tempstringsbuf_cursize;
516         if(!cl.csqc_loaded)
517         {
518                 SCR_CenterPrint(msg);
519                 return;
520         }
521         CSQC_BEGIN
522         if(prog->funcoffsets.CSQC_Parse_CenterPrint)
523         {
524                 prog->globals.client->time = cl.time;
525                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
526                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
527                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
528                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_CenterPrint, "QC function CSQC_Parse_CenterPrint is missing");
529                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
530         }
531         else
532                 SCR_CenterPrint(msg);
533         CSQC_END
534 }
535
536 void CL_VM_UpdateIntermissionState (int intermission)
537 {
538         prvm_eval_t *val;
539         if(cl.csqc_loaded)
540         {
541                 CSQC_BEGIN
542                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.intermission);
543                 if(val)
544                         val->_float = intermission;
545                 CSQC_END
546         }
547 }
548 void CL_VM_UpdateShowingScoresState (int showingscores)
549 {
550         prvm_eval_t *val;
551         if(cl.csqc_loaded)
552         {
553                 CSQC_BEGIN
554                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.sb_showscores);
555                 if(val)
556                         val->_float = showingscores;
557                 CSQC_END
558         }
559 }
560 qboolean CL_VM_Event_Sound(int sound_num, float volume, int channel, float attenuation, int ent, vec3_t pos)
561 {
562         qboolean r = false;
563         if(cl.csqc_loaded)
564         {
565                 CSQC_BEGIN
566                 if(prog->funcoffsets.CSQC_Event_Sound)
567                 {
568                         prog->globals.client->time = cl.time;
569                         prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
570                         PRVM_G_FLOAT(OFS_PARM0) = ent;
571                         PRVM_G_FLOAT(OFS_PARM1) = channel;
572                         PRVM_G_INT(OFS_PARM2) = PRVM_SetTempString(cl.sound_name[sound_num] );
573                         PRVM_G_FLOAT(OFS_PARM3) = volume;
574                         PRVM_G_FLOAT(OFS_PARM4) = attenuation;
575                         VectorCopy(pos, PRVM_G_VECTOR(OFS_PARM5) );
576                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Event_Sound, "QC function CSQC_Event_Sound is missing");
577                         r = CSQC_RETURNVAL != 0;
578                 }
579                 CSQC_END
580         }
581
582         return r;
583 }
584 void CL_VM_UpdateCoopDeathmatchGlobals (int gametype)
585 {
586         // Avoid global names for clean(er) coding
587         int localcoop;
588         int localdeathmatch;
589
590         prvm_eval_t *val;
591         if(cl.csqc_loaded)
592         {
593                 if(gametype == GAME_COOP)
594                 {
595                         localcoop = 1;
596                         localdeathmatch = 0;
597                 }
598                 else
599                 if(gametype == GAME_DEATHMATCH)
600                 {
601                         localcoop = 0;
602                         localdeathmatch = 1;
603                 }
604                 else
605                 {
606                         // How did the ServerInfo send an unknown gametype?
607                         // Better just assign the globals as 0...
608                         localcoop = 0;
609                         localdeathmatch = 0;
610                 }
611                 CSQC_BEGIN
612                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.coop);
613                 if(val)
614                         val->_float = localcoop;
615                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.deathmatch);
616                 if(val)
617                         val->_float = localdeathmatch;
618                 CSQC_END
619         }
620 }
621 float CL_VM_Event (float event)         //[515]: needed ? I'd say "YES", but don't know for what :D
622 {
623         float r = 0;
624         if(!cl.csqc_loaded)
625                 return 0;
626         CSQC_BEGIN
627         if(prog->funcoffsets.CSQC_Event)
628         {
629                 prog->globals.client->time = cl.time;
630                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
631                 PRVM_G_FLOAT(OFS_PARM0) = event;
632                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Event, "QC function CSQC_Event is missing");
633                 r = CSQC_RETURNVAL;
634         }
635         CSQC_END
636         return r;
637 }
638
639 void CSQC_ReadEntities (void)
640 {
641         unsigned short entnum, oldself, realentnum;
642         if(!cl.csqc_loaded)
643         {
644                 Host_Error ("CSQC_ReadEntities: CSQC is not loaded");
645                 return;
646         }
647
648         CSQC_BEGIN
649                 prog->globals.client->time = cl.time;
650                 oldself = prog->globals.client->self;
651                 while(1)
652                 {
653                         entnum = MSG_ReadShort();
654                         if(!entnum || msg_badread)
655                                 return;
656                         realentnum = entnum & 0x7FFF;
657                         prog->globals.client->self = cl.csqc_server2csqcentitynumber[realentnum];
658                         if(entnum & 0x8000)
659                         {
660                                 if(prog->globals.client->self)
661                                 {
662                                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Ent_Remove, "QC function CSQC_Ent_Remove is missing");
663                                         cl.csqc_server2csqcentitynumber[realentnum] = 0;
664                                 }
665                                 else
666                                 {
667                                         // LordHavoc: removing an entity that is already gone on
668                                         // the csqc side is possible for legitimate reasons (such
669                                         // as a repeat of the remove message), so no warning is
670                                         // needed
671                                         //Con_Printf("Bad csqc_server2csqcentitynumber map\n"); //[515]: never happens ?
672                                 }
673                         }
674                         else
675                         {
676                                 if(!prog->globals.client->self)
677                                 {
678                                         if(!prog->funcoffsets.CSQC_Ent_Spawn)
679                                         {
680                                                 prvm_edict_t    *ed;
681                                                 ed = PRVM_ED_Alloc();
682                                                 ed->fields.client->entnum = realentnum;
683                                                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[realentnum] = PRVM_EDICT_TO_PROG(ed);
684                                         }
685                                         else
686                                         {
687                                                 // entity( float entnum ) CSQC_Ent_Spawn;
688                                                 // the qc function should set entnum, too (this way it also can return world [2/1/2008 Andreas]
689                                                 PRVM_G_FLOAT(OFS_PARM0) = (float) realentnum;
690                                                 // make sure no one gets wrong ideas
691                                                 prog->globals.client->self = 0;
692                                                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Ent_Spawn, "QC function CSQC_Ent_Spawn is missing");
693                                                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[realentnum] = PRVM_EDICT( PRVM_G_INT( OFS_RETURN ) );
694                                         }
695                                         PRVM_G_FLOAT(OFS_PARM0) = 1;
696                                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Ent_Update, "QC function CSQC_Ent_Update is missing");
697                                 }
698                                 else {
699                                         PRVM_G_FLOAT(OFS_PARM0) = 0;
700                                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Ent_Update, "QC function CSQC_Ent_Update is missing");
701                                 }
702                         }
703                 }
704                 prog->globals.client->self = oldself;
705         CSQC_END
706 }
707
708 void CL_VM_CB_BeginIncreaseEdicts(void)
709 {
710         // links don't survive the transition, so unlink everything
711         World_UnlinkAll(&cl.world);
712 }
713
714 void CL_VM_CB_EndIncreaseEdicts(void)
715 {
716         int i;
717         prvm_edict_t *ent;
718
719         // link every entity except world
720         for (i = 1, ent = prog->edicts;i < prog->max_edicts;i++, ent++)
721                 if (!ent->priv.server->free)
722                         CL_LinkEdict(ent);
723 }
724
725 void CL_VM_CB_InitEdict(prvm_edict_t *e)
726 {
727         e->priv.server->move = false; // don't move on first frame
728 }
729
730 void CL_VM_CB_FreeEdict(prvm_edict_t *ed)
731 {
732         World_UnlinkEdict(ed);
733         memset(ed->fields.client, 0, sizeof(*ed->fields.client));
734 }
735
736 void CL_VM_CB_CountEdicts(void)
737 {
738         int             i;
739         prvm_edict_t    *ent;
740         int             active = 0, models = 0, solid = 0;
741
742         for (i=0 ; i<prog->num_edicts ; i++)
743         {
744                 ent = PRVM_EDICT_NUM(i);
745                 if (ent->priv.server->free)
746                         continue;
747                 active++;
748                 if (ent->fields.client->solid)
749                         solid++;
750                 if (ent->fields.client->model)
751                         models++;
752         }
753
754         Con_Printf("num_edicts:%3i\n", prog->num_edicts);
755         Con_Printf("active    :%3i\n", active);
756         Con_Printf("view      :%3i\n", models);
757         Con_Printf("touch     :%3i\n", solid);
758 }
759
760 qboolean CL_VM_CB_LoadEdict(prvm_edict_t *ent)
761 {
762         return true;
763 }
764
765 void Cmd_ClearCsqcFuncs (void);
766
767 // returns true if the packet is valid, false if end of file is reached
768 // used for dumping the CSQC download into demo files
769 qboolean MakeDownloadPacket(const char *filename, unsigned char *data, unsigned long len, int crc, int cnt, sizebuf_t *buf, int protocol)
770 {
771         int packetsize = buf->maxsize - 7; // byte short long
772         int npackets = (len + packetsize - 1) / (packetsize);
773
774         if(protocol == PROTOCOL_QUAKEWORLD)
775                 return false; // CSQC can't run in QW anyway
776
777         SZ_Clear(buf);
778         if(cnt == 0)
779         {
780                 MSG_WriteByte(buf, svc_stufftext);
781                 MSG_WriteString(buf, va("\ncl_downloadbegin %lu %s\n", len, filename));
782                 return true;
783         }
784         else if(cnt >= 1 && cnt <= npackets)
785         {
786                 unsigned long thispacketoffset = (cnt - 1) * packetsize;
787                 int thispacketsize = len - thispacketoffset;
788                 if(thispacketsize > packetsize)
789                         thispacketsize = packetsize;
790
791                 MSG_WriteByte(buf, svc_downloaddata);
792                 MSG_WriteLong(buf, thispacketoffset);
793                 MSG_WriteShort(buf, thispacketsize);
794                 SZ_Write(buf, data + thispacketoffset, thispacketsize);
795
796                 return true;
797         }
798         else if(cnt == npackets + 1)
799         {
800                 MSG_WriteByte(buf, svc_stufftext);
801                 MSG_WriteString(buf, va("\ncl_downloadfinished %lu %d\n", len, crc));
802                 return true;
803         }
804         return false;
805 }
806
807 void CL_VM_Init (void)
808 {
809         const char* csprogsfn;
810         unsigned char *csprogsdata;
811         fs_offset_t csprogsdatasize;
812         int csprogsdatacrc, requiredcrc;
813         int requiredsize;
814         prvm_eval_t *val;
815
816         // reset csqc_progcrc after reading it, so that changing servers doesn't
817         // expect csqc on the next server
818         requiredcrc = csqc_progcrc.integer;
819         requiredsize = csqc_progsize.integer;
820         Cvar_SetValueQuick(&csqc_progcrc, -1);
821         Cvar_SetValueQuick(&csqc_progsize, -1);
822
823         // if the server is not requesting a csprogs, then we're done here
824         if (requiredcrc < 0)
825                 return;
826
827         // see if the requested csprogs.dat file matches the requested crc
828         csprogsdatacrc = -1;
829         csprogsfn = va("dlcache/%s.%i.%i", csqc_progname.string, requiredsize, requiredcrc);
830         csprogsdata = FS_LoadFile(csprogsfn, tempmempool, true, &csprogsdatasize);
831         if (!csprogsdata)
832         {
833                 csprogsfn = csqc_progname.string;
834                 csprogsdata = FS_LoadFile(csprogsfn, tempmempool, true, &csprogsdatasize);
835         }
836         if (csprogsdata)
837         {
838                 csprogsdatacrc = CRC_Block(csprogsdata, csprogsdatasize);
839                 if (csprogsdatacrc != requiredcrc || csprogsdatasize != requiredsize)
840                 {
841                         if (cls.demoplayback)
842                         {
843                                 Con_Printf("^1Warning: Your %s is not the same version as the demo was recorded with (CRC/size are %i/%i but should be %i/%i)\n", csqc_progname.string, csprogsdatacrc, (int)csprogsdatasize, requiredcrc, requiredsize);
844                                 // Mem_Free(csprogsdata);
845                                 // return;
846                                 // We WANT to continue here, and play the demo with different csprogs!
847                                 // After all, this is just a warning. Sure things may go wrong from here.
848                         }
849                         else
850                         {
851                                 Mem_Free(csprogsdata);
852                                 Con_Printf("^1Your %s is not the same version as the server (CRC is %i/%i but should be %i/%i)\n", csqc_progname.string, csprogsdatacrc, (int)csprogsdatasize, requiredcrc, requiredsize);
853                                 CL_Disconnect();
854                                 return;
855                         }
856                 }
857         }
858         else
859         {
860                 if (requiredcrc >= 0)
861                 {
862                         if (cls.demoplayback)
863                                 Con_Printf("CL_VM_Init: demo requires CSQC, but \"%s\" wasn't found\n", csqc_progname.string);
864                         else
865                                 Con_Printf("CL_VM_Init: server requires CSQC, but \"%s\" wasn't found\n", csqc_progname.string);
866                         CL_Disconnect();
867                 }
868                 return;
869         }
870
871         PRVM_Begin;
872         PRVM_InitProg(PRVM_CLIENTPROG);
873
874         // allocate the mempools
875         prog->progs_mempool = Mem_AllocPool(csqc_progname.string, 0, NULL);
876         prog->headercrc = CL_PROGHEADER_CRC;
877         prog->edictprivate_size = 0; // no private struct used
878         prog->name = CL_NAME;
879         prog->num_edicts = 1;
880         prog->max_edicts = 512;
881         prog->limit_edicts = CL_MAX_EDICTS;
882         prog->reserved_edicts = 0;
883         prog->edictprivate_size = sizeof(edict_engineprivate_t);
884         // TODO: add a shared extension string #define and add real support for csqc extension strings [12/5/2007 Black]
885         prog->extensionstring = vm_sv_extensions;
886         prog->builtins = vm_cl_builtins;
887         prog->numbuiltins = vm_cl_numbuiltins;
888         prog->begin_increase_edicts = CL_VM_CB_BeginIncreaseEdicts;
889         prog->end_increase_edicts = CL_VM_CB_EndIncreaseEdicts;
890         prog->init_edict = CL_VM_CB_InitEdict;
891         prog->free_edict = CL_VM_CB_FreeEdict;
892         prog->count_edicts = CL_VM_CB_CountEdicts;
893         prog->load_edict = CL_VM_CB_LoadEdict;
894         prog->init_cmd = VM_CL_Cmd_Init;
895         prog->reset_cmd = VM_CL_Cmd_Reset;
896         prog->error_cmd = CL_VM_Error;
897         prog->ExecuteProgram = CLVM_ExecuteProgram;
898
899         PRVM_LoadProgs(csprogsfn, cl_numrequiredfunc, cl_required_func, 0, NULL, 0, NULL);
900
901         if (!prog->loaded)
902         {
903                 CL_VM_Error("CSQC %s ^2failed to load\n", csprogsfn);
904                 if(!sv.active)
905                         CL_Disconnect();
906                 Mem_Free(csprogsdata);
907                 return;
908         }
909
910         Con_Printf("CSQC %s ^5loaded (crc=%i, size=%i)\n", csprogsfn, csprogsdatacrc, (int)csprogsdatasize);
911
912         if(cls.demorecording)
913         {
914                 if(cls.demo_lastcsprogssize != csprogsdatasize || cls.demo_lastcsprogscrc != csprogsdatacrc)
915                 {
916                         int i;
917                         char buf[NET_MAXMESSAGE];
918                         sizebuf_t sb;
919                         unsigned char *demobuf; fs_offset_t demofilesize;
920
921                         sb.data = (unsigned char *) buf;
922                         sb.maxsize = sizeof(buf);
923                         i = 0;
924
925                         CL_CutDemo(&demobuf, &demofilesize);
926                         while(MakeDownloadPacket(csqc_progname.string, csprogsdata, csprogsdatasize, csprogsdatacrc, i++, &sb, cls.protocol))
927                                 CL_WriteDemoMessage(&sb);
928                         CL_PasteDemo(&demobuf, &demofilesize);
929
930                         cls.demo_lastcsprogssize = csprogsdatasize;
931                         cls.demo_lastcsprogscrc = csprogsdatacrc;
932                 }
933         }
934         Mem_Free(csprogsdata);
935
936         // check if OP_STATE animation is possible in this dat file
937         if (prog->fieldoffsets.nextthink >= 0 && prog->fieldoffsets.frame >= 0 && prog->fieldoffsets.think >= 0 && prog->globaloffsets.self >= 0)
938                 prog->flag |= PRVM_OP_STATE;
939
940         // set time
941         prog->globals.client->time = cl.time;
942         prog->globals.client->self = 0;
943
944         prog->globals.client->mapname = cl.worldmodel ? PRVM_SetEngineString(cl.worldmodel->name) : PRVM_SetEngineString("");
945         prog->globals.client->player_localentnum = cl.playerentity;
946
947         // set map description (use world entity 0)
948         val = PRVM_EDICTFIELDVALUE(prog->edicts, prog->fieldoffsets.message);
949         if(val)
950                 val->string = PRVM_SetEngineString(cl.levelname);
951         VectorCopy(cl.world.mins, prog->edicts->fields.client->mins);
952         VectorCopy(cl.world.maxs, prog->edicts->fields.client->maxs);
953
954         // call the prog init
955         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Init, "QC function CSQC_Init is missing");
956
957         PRVM_End;
958         cl.csqc_loaded = true;
959
960         cl.csqc_vidvars.drawcrosshair = false;
961         cl.csqc_vidvars.drawenginesbar = false;
962
963         // Update Coop and Deathmatch Globals (at this point the client knows them from ServerInfo)
964         CL_VM_UpdateCoopDeathmatchGlobals(cl.gametype);
965 }
966
967 void CL_VM_ShutDown (void)
968 {
969         Cmd_ClearCsqcFuncs();
970         //Cvar_SetValueQuick(&csqc_progcrc, -1);
971         //Cvar_SetValueQuick(&csqc_progsize, -1);
972         if(!cl.csqc_loaded)
973                 return;
974         CSQC_BEGIN
975                 prog->globals.client->time = cl.time;
976                 prog->globals.client->self = 0;
977                 if (prog->funcoffsets.CSQC_Shutdown)
978                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Shutdown, "QC function CSQC_Shutdown is missing");
979                 PRVM_ResetProg();
980         CSQC_END
981         Con_Print("CSQC ^1unloaded\n");
982         cl.csqc_loaded = false;
983 }
984
985 qboolean CL_VM_GetEntitySoundOrigin(int entnum, vec3_t out)
986 {
987         prvm_edict_t *ed;
988         dp_model_t *mod;
989         matrix4x4_t matrix;
990         qboolean r = 0;
991
992         CSQC_BEGIN;
993
994         // FIXME consider attachments here!
995
996         ed = PRVM_EDICT_NUM(entnum - 32768);
997
998         if(!ed->priv.required->free)
999         {
1000                 mod = CL_GetModelFromEdict(ed);
1001                 VectorCopy(ed->fields.client->origin, out);
1002                 if(CL_GetTagMatrix (&matrix, ed, 0) == 0)
1003                         Matrix4x4_OriginFromMatrix(&matrix, out);
1004                 if (mod && mod->soundfromcenter)
1005                         VectorMAMAM(1.0f, out, 0.5f, mod->normalmins, 0.5f, mod->normalmaxs, out);
1006                 r = 1;
1007         }
1008
1009         CSQC_END;
1010
1011         return r;
1012 }