fix bug in last patch, fix RF_USEAXIS handling
[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 const 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                 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.view_punchangle)))
127                         VectorCopy(cl.punchangle, val->vector);
128                 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.view_punchvector)))
129                         VectorCopy(cl.punchvector, val->vector);
130                 prog->globals.client->maxclients = cl.maxclients;
131         CSQC_END
132 }
133
134 void CSQC_Predraw (prvm_edict_t *ed)
135 {
136         int b;
137         if(!ed->fields.client->predraw)
138                 return;
139         b = prog->globals.client->self;
140         prog->globals.client->self = PRVM_EDICT_TO_PROG(ed);
141         PRVM_ExecuteProgram(ed->fields.client->predraw, "CSQC_Predraw: NULL function\n");
142         prog->globals.client->self = b;
143 }
144
145 void CSQC_Think (prvm_edict_t *ed)
146 {
147         int b;
148         if(ed->fields.client->think)
149         if(ed->fields.client->nextthink && ed->fields.client->nextthink <= prog->globals.client->time)
150         {
151                 ed->fields.client->nextthink = 0;
152                 b = prog->globals.client->self;
153                 prog->globals.client->self = PRVM_EDICT_TO_PROG(ed);
154                 PRVM_ExecuteProgram(ed->fields.client->think, "CSQC_Think: NULL function\n");
155                 prog->globals.client->self = b;
156         }
157 }
158
159 extern cvar_t cl_noplayershadow;
160 extern cvar_t r_equalize_entities_fullbright;
161 qboolean CSQC_AddRenderEdict(prvm_edict_t *ed, int edictnum)
162 {
163         int renderflags;
164         int c;
165         float scale;
166         prvm_eval_t *val;
167         entity_render_t *entrender;
168         dp_model_t *model;
169
170         model = CL_GetModelFromEdict(ed);
171         if (!model)
172                 return false;
173
174         if (edictnum)
175         {
176                 if (r_refdef.scene.numentities >= r_refdef.scene.maxentities)
177                         return false;
178                 entrender = cl.csqcrenderentities + edictnum;
179                 r_refdef.scene.entities[r_refdef.scene.numentities++] = entrender;
180                 entrender->entitynumber = edictnum + MAX_EDICTS;
181                 //entrender->shadertime = 0; // shadertime was set by spawn()
182                 entrender->flags = 0;
183                 entrender->alpha = 1;
184                 entrender->scale = 1;
185                 VectorSet(entrender->colormod, 1, 1, 1);
186                 VectorSet(entrender->glowmod, 1, 1, 1);
187                 entrender->allowdecals = true;
188         }
189         else
190         {
191                 entrender = CL_NewTempEntity(0);
192                 if (!entrender)
193                         return false;
194         }
195
196         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.userwavefunc_param0)))    entrender->userwavefunc_param[0] = val->_float;
197         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.userwavefunc_param1)))    entrender->userwavefunc_param[1] = val->_float;
198         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.userwavefunc_param2)))    entrender->userwavefunc_param[2] = val->_float;
199         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.userwavefunc_param3)))    entrender->userwavefunc_param[3] = val->_float;
200
201         entrender->model = model;
202         entrender->skinnum = (int)ed->fields.client->skin;
203         entrender->effects |= entrender->model->effects;
204         scale = 1;
205         renderflags = 0;
206         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.renderflags)) && val->_float)     renderflags = (int)val->_float;
207         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.alpha)) && val->_float)           entrender->alpha = val->_float;
208         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.scale)) && val->_float)           entrender->scale = scale = val->_float;
209         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.colormod)) && VectorLength2(val->vector)) VectorCopy(val->vector, entrender->colormod);
210         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.glowmod)) && VectorLength2(val->vector))  VectorCopy(val->vector, entrender->glowmod);
211         if(ed->fields.client->effects)  entrender->effects |= (int)ed->fields.client->effects;
212         if (!VectorLength2(entrender->colormod))
213                 VectorSet(entrender->colormod, 1, 1, 1);
214         if (!VectorLength2(entrender->glowmod))
215                 VectorSet(entrender->glowmod, 1, 1, 1);
216
217         // LordHavoc: use the CL_GetTagMatrix function on self to ensure consistent behavior (duplicate code would be bad)
218         CL_GetTagMatrix(&entrender->matrix, ed, 0);
219
220         // set up the animation data
221         VM_GenerateFrameGroupBlend(ed->priv.server->framegroupblend, ed);
222         VM_FrameBlendFromFrameGroupBlend(ed->priv.server->frameblend, ed->priv.server->framegroupblend, model);
223         VM_UpdateEdictSkeleton(ed, model, ed->priv.server->frameblend);
224         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.shadertime))) entrender->shadertime = val->_float;
225
226         // transparent offset
227         if ((renderflags & RF_USETRANSPARENTOFFSET) && (val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.transparent_offset)))
228                 entrender->transparent_offset = val->_float;
229
230         if(renderflags)
231         {
232                 if(renderflags & RF_VIEWMODEL)  entrender->flags |= RENDER_VIEWMODEL | RENDER_NODEPTHTEST;
233                 if(renderflags & RF_EXTERNALMODEL)entrender->flags |= RENDER_EXTERIORMODEL;
234                 if(renderflags & RF_NOCULL)             entrender->flags |= RENDER_NOCULL;
235                 if(renderflags & RF_DEPTHHACK)  entrender->flags |= RENDER_NODEPTHTEST;
236                 if(renderflags & RF_ADDITIVE)           entrender->flags |= RENDER_ADDITIVE;
237         }
238
239         c = (int)ed->fields.client->colormap;
240         if (c <= 0)
241                 CL_SetEntityColormapColors(entrender, -1);
242         else if (c <= cl.maxclients && cl.scores != NULL)
243                 CL_SetEntityColormapColors(entrender, cl.scores[c-1].colors);
244         else
245                 CL_SetEntityColormapColors(entrender, c);
246
247         entrender->flags &= ~(RENDER_SHADOW | RENDER_LIGHT | RENDER_NOSELFSHADOW);
248         // either fullbright or lit
249         if(!r_fullbright.integer)
250         {
251                 if (!(entrender->effects & EF_FULLBRIGHT) && !(renderflags & RF_FULLBRIGHT))
252                         entrender->flags |= RENDER_LIGHT;
253                 else if(r_equalize_entities_fullbright.integer)
254                         entrender->flags |= RENDER_LIGHT | RENDER_EQUALIZE;
255         }
256         // hide player shadow during intermission or nehahra movie
257         if (!(entrender->effects & (EF_NOSHADOW | EF_ADDITIVE | EF_NODEPTHTEST))
258          &&  (entrender->alpha >= 1)
259          && !(renderflags & RF_NOSHADOW)
260          && !(entrender->flags & RENDER_VIEWMODEL)
261          && (!(entrender->flags & RENDER_EXTERIORMODEL) || (!cl.intermission && cls.protocol != PROTOCOL_NEHAHRAMOVIE && !cl_noplayershadow.integer)))
262                 entrender->flags |= RENDER_SHADOW;
263         if (entrender->flags & RENDER_VIEWMODEL)
264                 entrender->flags |= RENDER_NOSELFSHADOW;
265         if (entrender->effects & EF_NOSELFSHADOW)
266                 entrender->flags |= RENDER_NOSELFSHADOW;
267         if (entrender->effects & EF_NODEPTHTEST)
268                 entrender->flags |= RENDER_NODEPTHTEST;
269         if (entrender->effects & EF_ADDITIVE)
270                 entrender->flags |= RENDER_ADDITIVE;
271         if (entrender->effects & EF_DOUBLESIDED)
272                 entrender->flags |= RENDER_DOUBLESIDED;
273
274         // make the other useful stuff
275         memcpy(entrender->framegroupblend, ed->priv.server->framegroupblend, sizeof(ed->priv.server->framegroupblend));
276         CL_UpdateRenderEntity(entrender);
277         // override animation data with full control
278         memcpy(entrender->frameblend, ed->priv.server->frameblend, sizeof(ed->priv.server->frameblend));
279         if (ed->priv.server->skeleton.relativetransforms)
280                 entrender->skeleton = &ed->priv.server->skeleton;
281         else
282                 entrender->skeleton = NULL;
283
284         return true;
285 }
286
287 qboolean CL_VM_InputEvent (qboolean down, int key, int ascii)
288 {
289         qboolean r;
290
291         if(!cl.csqc_loaded)
292                 return false;
293
294         CSQC_BEGIN
295                 if (!prog->funcoffsets.CSQC_InputEvent)
296                         r = false;
297                 else
298                 {
299                         prog->globals.client->time = cl.time;
300                         prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
301                         PRVM_G_FLOAT(OFS_PARM0) = !down; // 0 is down, 1 is up
302                         PRVM_G_FLOAT(OFS_PARM1) = key;
303                         PRVM_G_FLOAT(OFS_PARM2) = ascii;
304                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_InputEvent, "QC function CSQC_InputEvent is missing");
305                         r = CSQC_RETURNVAL != 0;
306                 }
307         CSQC_END
308         return r;
309 }
310
311 qboolean CL_VM_UpdateView (void)
312 {
313         vec3_t emptyvector;
314         emptyvector[0] = 0;
315         emptyvector[1] = 0;
316         emptyvector[2] = 0;
317 //      vec3_t oldangles;
318         if(!cl.csqc_loaded)
319                 return false;
320         R_TimeReport("pre-UpdateView");
321         CSQC_BEGIN
322                 //VectorCopy(cl.viewangles, oldangles);
323                 prog->globals.client->time = cl.time;
324                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
325                 CSQC_SetGlobals();
326                 // clear renderable entity and light lists to prevent crashes if the
327                 // CSQC_UpdateView function does not call R_ClearScene as it should
328                 r_refdef.scene.numentities = 0;
329                 r_refdef.scene.numlights = 0;
330                 // pass in width and height as parameters (EXT_CSQC_1)
331                 PRVM_G_FLOAT(OFS_PARM0) = vid.width;
332                 PRVM_G_FLOAT(OFS_PARM1) = vid.height;
333                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_UpdateView, "QC function CSQC_UpdateView is missing");
334                 //VectorCopy(oldangles, cl.viewangles);
335                 // Dresk : Reset Dmg Globals Here
336                 CL_VM_UpdateDmgGlobals(0, 0, emptyvector);
337         CSQC_END
338         R_TimeReport("UpdateView");
339         return true;
340 }
341
342 extern sizebuf_t vm_tempstringsbuf;
343 qboolean CL_VM_ConsoleCommand (const char *cmd)
344 {
345         int restorevm_tempstringsbuf_cursize;
346         qboolean r = false;
347         if(!cl.csqc_loaded)
348                 return false;
349         CSQC_BEGIN
350         if (prog->funcoffsets.CSQC_ConsoleCommand)
351         {
352                 prog->globals.client->time = cl.time;
353                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
354                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
355                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(cmd);
356                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_ConsoleCommand, "QC function CSQC_ConsoleCommand is missing");
357                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
358                 r = CSQC_RETURNVAL != 0;
359         }
360         CSQC_END
361         return r;
362 }
363
364 qboolean CL_VM_Parse_TempEntity (void)
365 {
366         int                     t;
367         qboolean        r = false;
368         if(!cl.csqc_loaded)
369                 return false;
370         CSQC_BEGIN
371         if(prog->funcoffsets.CSQC_Parse_TempEntity)
372         {
373                 t = msg_readcount;
374                 prog->globals.client->time = cl.time;
375                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
376                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_TempEntity, "QC function CSQC_Parse_TempEntity is missing");
377                 r = CSQC_RETURNVAL != 0;
378                 if(!r)
379                 {
380                         msg_readcount = t;
381                         msg_badread = false;
382                 }
383         }
384         CSQC_END
385         return r;
386 }
387
388 void CL_VM_Parse_StuffCmd (const char *msg)
389 {
390         int restorevm_tempstringsbuf_cursize;
391         if(msg[0] == 'c')
392         if(msg[1] == 's')
393         if(msg[2] == 'q')
394         if(msg[3] == 'c')
395         {
396                 // if this is setting a csqc variable, deprotect csqc_progcrc
397                 // temporarily so that it can be set by the cvar command,
398                 // and then reprotect it afterwards
399                 int crcflags = csqc_progcrc.flags;
400                 int sizeflags = csqc_progcrc.flags;
401                 csqc_progcrc.flags &= ~CVAR_READONLY;
402                 csqc_progsize.flags &= ~CVAR_READONLY;
403                 Cmd_ExecuteString (msg, src_command);
404                 csqc_progcrc.flags = crcflags;
405                 csqc_progsize.flags = sizeflags;
406                 return;
407         }
408
409         if(cls.demoplayback)
410         if(!strncmp(msg, "curl --clear_autodownload\ncurl --pak --forthismap --as ", 55))
411         {
412                 // special handling for map download commands
413                 // run these commands IMMEDIATELY, instead of waiting for a client frame
414                 // that way, there is no black screen when playing back demos
415                 // I know this is a really ugly hack, but I can't think of any better way
416                 // FIXME find the actual CAUSE of this, and make demo playback WAIT
417                 // until all maps are loaded, then remove this hack
418
419                 char buf[MAX_INPUTLINE];
420                 const char *p, *q;
421                 size_t l;
422
423                 p = msg;
424
425                 for(;;)
426                 {
427                         q = strchr(p, '\n');
428                         if(q)
429                                 l = q - p;
430                         else
431                                 l = strlen(p);
432                         if(l > sizeof(buf) - 1)
433                                 l = sizeof(buf) - 1;
434                         strlcpy(buf, p, l + 1); // strlcpy needs a + 1 as it includes the newline!
435
436                         Cmd_ExecuteString(buf, src_command);
437
438                         p += l;
439                         if(*p == '\n')
440                                 ++p; // skip the newline and continue
441                         else
442                                 break; // end of string or overflow
443                 }
444                 Cmd_ExecuteString("curl --clear_autodownload", src_command); // don't inhibit CSQC loading
445                 return;
446         }
447
448         if(!cl.csqc_loaded)
449         {
450                 Cbuf_AddText(msg);
451                 return;
452         }
453         CSQC_BEGIN
454         if(prog->funcoffsets.CSQC_Parse_StuffCmd)
455         {
456                 prog->globals.client->time = cl.time;
457                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
458                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
459                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
460                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_StuffCmd, "QC function CSQC_Parse_StuffCmd is missing");
461                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
462         }
463         else
464                 Cbuf_AddText(msg);
465         CSQC_END
466 }
467
468 static void CL_VM_Parse_Print (const char *msg)
469 {
470         int restorevm_tempstringsbuf_cursize;
471         prog->globals.client->time = cl.time;
472         prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
473         restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
474         PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
475         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_Print, "QC function CSQC_Parse_Print is missing");
476         vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
477 }
478
479 void CSQC_AddPrintText (const char *msg)
480 {
481         size_t i;
482         if(!cl.csqc_loaded)
483         {
484                 Con_Print(msg);
485                 return;
486         }
487         CSQC_BEGIN
488         if(prog->funcoffsets.CSQC_Parse_Print)
489         {
490                 // FIXME: is this bugged?
491                 i = strlen(msg)-1;
492                 if(msg[i] != '\n' && msg[i] != '\r')
493                 {
494                         if(strlen(cl.csqc_printtextbuf)+i >= MAX_INPUTLINE)
495                         {
496                                 CL_VM_Parse_Print(cl.csqc_printtextbuf);
497                                 cl.csqc_printtextbuf[0] = 0;
498                         }
499                         else
500                                 strlcat(cl.csqc_printtextbuf, msg, MAX_INPUTLINE);
501                         return;
502                 }
503                 strlcat(cl.csqc_printtextbuf, msg, MAX_INPUTLINE);
504                 CL_VM_Parse_Print(cl.csqc_printtextbuf);
505                 cl.csqc_printtextbuf[0] = 0;
506         }
507         else
508                 Con_Print(msg);
509         CSQC_END
510 }
511
512 void CL_VM_Parse_CenterPrint (const char *msg)
513 {
514         int restorevm_tempstringsbuf_cursize;
515         if(!cl.csqc_loaded)
516         {
517                 SCR_CenterPrint(msg);
518                 return;
519         }
520         CSQC_BEGIN
521         if(prog->funcoffsets.CSQC_Parse_CenterPrint)
522         {
523                 prog->globals.client->time = cl.time;
524                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
525                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
526                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
527                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_CenterPrint, "QC function CSQC_Parse_CenterPrint is missing");
528                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
529         }
530         else
531                 SCR_CenterPrint(msg);
532         CSQC_END
533 }
534
535 void CL_VM_UpdateIntermissionState (int intermission)
536 {
537         prvm_eval_t *val;
538         if(cl.csqc_loaded)
539         {
540                 CSQC_BEGIN
541                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.intermission);
542                 if(val)
543                         val->_float = intermission;
544                 CSQC_END
545         }
546 }
547 void CL_VM_UpdateShowingScoresState (int showingscores)
548 {
549         prvm_eval_t *val;
550         if(cl.csqc_loaded)
551         {
552                 CSQC_BEGIN
553                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.sb_showscores);
554                 if(val)
555                         val->_float = showingscores;
556                 CSQC_END
557         }
558 }
559 qboolean CL_VM_Event_Sound(int sound_num, float volume, int channel, float attenuation, int ent, vec3_t pos)
560 {
561         qboolean r = false;
562         if(cl.csqc_loaded)
563         {
564                 CSQC_BEGIN
565                 if(prog->funcoffsets.CSQC_Event_Sound)
566                 {
567                         prog->globals.client->time = cl.time;
568                         prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
569                         PRVM_G_FLOAT(OFS_PARM0) = ent;
570                         PRVM_G_FLOAT(OFS_PARM1) = channel;
571                         PRVM_G_INT(OFS_PARM2) = PRVM_SetTempString(cl.sound_name[sound_num] );
572                         PRVM_G_FLOAT(OFS_PARM3) = volume;
573                         PRVM_G_FLOAT(OFS_PARM4) = attenuation;
574                         VectorCopy(pos, PRVM_G_VECTOR(OFS_PARM5) );
575                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Event_Sound, "QC function CSQC_Event_Sound is missing");
576                         r = CSQC_RETURNVAL != 0;
577                 }
578                 CSQC_END
579         }
580
581         return r;
582 }
583 void CL_VM_UpdateCoopDeathmatchGlobals (int gametype)
584 {
585         // Avoid global names for clean(er) coding
586         int localcoop;
587         int localdeathmatch;
588
589         prvm_eval_t *val;
590         if(cl.csqc_loaded)
591         {
592                 if(gametype == GAME_COOP)
593                 {
594                         localcoop = 1;
595                         localdeathmatch = 0;
596                 }
597                 else
598                 if(gametype == GAME_DEATHMATCH)
599                 {
600                         localcoop = 0;
601                         localdeathmatch = 1;
602                 }
603                 else
604                 {
605                         // How did the ServerInfo send an unknown gametype?
606                         // Better just assign the globals as 0...
607                         localcoop = 0;
608                         localdeathmatch = 0;
609                 }
610                 CSQC_BEGIN
611                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.coop);
612                 if(val)
613                         val->_float = localcoop;
614                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.deathmatch);
615                 if(val)
616                         val->_float = localdeathmatch;
617                 CSQC_END
618         }
619 }
620 float CL_VM_Event (float event)         //[515]: needed ? I'd say "YES", but don't know for what :D
621 {
622         float r = 0;
623         if(!cl.csqc_loaded)
624                 return 0;
625         CSQC_BEGIN
626         if(prog->funcoffsets.CSQC_Event)
627         {
628                 prog->globals.client->time = cl.time;
629                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
630                 PRVM_G_FLOAT(OFS_PARM0) = event;
631                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Event, "QC function CSQC_Event is missing");
632                 r = CSQC_RETURNVAL;
633         }
634         CSQC_END
635         return r;
636 }
637
638 void CSQC_ReadEntities (void)
639 {
640         unsigned short entnum, oldself, realentnum;
641         if(!cl.csqc_loaded)
642         {
643                 Host_Error ("CSQC_ReadEntities: CSQC is not loaded");
644                 return;
645         }
646
647         CSQC_BEGIN
648                 prog->globals.client->time = cl.time;
649                 oldself = prog->globals.client->self;
650                 while(1)
651                 {
652                         entnum = MSG_ReadShort();
653                         if(!entnum || msg_badread)
654                                 break;
655                         realentnum = entnum & 0x7FFF;
656                         prog->globals.client->self = cl.csqc_server2csqcentitynumber[realentnum];
657                         if(entnum & 0x8000)
658                         {
659                                 if(prog->globals.client->self)
660                                 {
661                                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Ent_Remove, "QC function CSQC_Ent_Remove is missing");
662                                         cl.csqc_server2csqcentitynumber[realentnum] = 0;
663                                 }
664                                 else
665                                 {
666                                         // LordHavoc: removing an entity that is already gone on
667                                         // the csqc side is possible for legitimate reasons (such
668                                         // as a repeat of the remove message), so no warning is
669                                         // needed
670                                         //Con_Printf("Bad csqc_server2csqcentitynumber map\n"); //[515]: never happens ?
671                                 }
672                         }
673                         else
674                         {
675                                 if(!prog->globals.client->self)
676                                 {
677                                         if(!prog->funcoffsets.CSQC_Ent_Spawn)
678                                         {
679                                                 prvm_edict_t    *ed;
680                                                 ed = PRVM_ED_Alloc();
681                                                 ed->fields.client->entnum = realentnum;
682                                                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[realentnum] = PRVM_EDICT_TO_PROG(ed);
683                                         }
684                                         else
685                                         {
686                                                 // entity( float entnum ) CSQC_Ent_Spawn;
687                                                 // the qc function should set entnum, too (this way it also can return world [2/1/2008 Andreas]
688                                                 PRVM_G_FLOAT(OFS_PARM0) = (float) realentnum;
689                                                 // make sure no one gets wrong ideas
690                                                 prog->globals.client->self = 0;
691                                                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Ent_Spawn, "QC function CSQC_Ent_Spawn is missing");
692                                                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[realentnum] = PRVM_EDICT( PRVM_G_INT( OFS_RETURN ) );
693                                         }
694                                         PRVM_G_FLOAT(OFS_PARM0) = 1;
695                                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Ent_Update, "QC function CSQC_Ent_Update is missing");
696                                 }
697                                 else {
698                                         PRVM_G_FLOAT(OFS_PARM0) = 0;
699                                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Ent_Update, "QC function CSQC_Ent_Update is missing");
700                                 }
701                         }
702                 }
703                 prog->globals.client->self = oldself;
704         CSQC_END
705 }
706
707 void CL_VM_CB_BeginIncreaseEdicts(void)
708 {
709         // links don't survive the transition, so unlink everything
710         World_UnlinkAll(&cl.world);
711 }
712
713 void CL_VM_CB_EndIncreaseEdicts(void)
714 {
715         int i;
716         prvm_edict_t *ent;
717
718         // link every entity except world
719         for (i = 1, ent = prog->edicts;i < prog->num_edicts;i++, ent++)
720                 if (!ent->priv.server->free)
721                         CL_LinkEdict(ent);
722 }
723
724 void CL_VM_CB_InitEdict(prvm_edict_t *e)
725 {
726         int edictnum = PRVM_NUM_FOR_EDICT(e);
727         entity_render_t *entrender;
728         CL_ExpandCSQCRenderEntities(edictnum);
729         entrender = cl.csqcrenderentities + edictnum;
730         e->priv.server->move = false; // don't move on first frame
731         memset(entrender, 0, sizeof(*entrender));
732         entrender->shadertime = cl.time;
733 }
734
735 extern void R_DecalSystem_Reset(decalsystem_t *decalsystem);
736
737 void CL_VM_CB_FreeEdict(prvm_edict_t *ed)
738 {
739         entity_render_t *entrender = cl.csqcrenderentities + PRVM_NUM_FOR_EDICT(ed);
740         R_DecalSystem_Reset(&entrender->decalsystem);
741         memset(entrender, 0, sizeof(*entrender));
742         World_UnlinkEdict(ed);
743         memset(ed->fields.client, 0, sizeof(*ed->fields.client));
744         VM_RemoveEdictSkeleton(ed);
745         World_Physics_RemoveFromEntity(&cl.world, ed);
746         World_Physics_RemoveJointFromEntity(&cl.world, ed);
747 }
748
749 void CL_VM_CB_CountEdicts(void)
750 {
751         int             i;
752         prvm_edict_t    *ent;
753         int             active = 0, models = 0, solid = 0;
754
755         for (i=0 ; i<prog->num_edicts ; i++)
756         {
757                 ent = PRVM_EDICT_NUM(i);
758                 if (ent->priv.server->free)
759                         continue;
760                 active++;
761                 if (ent->fields.client->solid)
762                         solid++;
763                 if (ent->fields.client->model)
764                         models++;
765         }
766
767         Con_Printf("num_edicts:%3i\n", prog->num_edicts);
768         Con_Printf("active    :%3i\n", active);
769         Con_Printf("view      :%3i\n", models);
770         Con_Printf("touch     :%3i\n", solid);
771 }
772
773 qboolean CL_VM_CB_LoadEdict(prvm_edict_t *ent)
774 {
775         return true;
776 }
777
778 void Cmd_ClearCsqcFuncs (void);
779
780 // returns true if the packet is valid, false if end of file is reached
781 // used for dumping the CSQC download into demo files
782 qboolean MakeDownloadPacket(const char *filename, unsigned char *data, size_t len, int crc, int cnt, sizebuf_t *buf, int protocol)
783 {
784         int packetsize = buf->maxsize - 7; // byte short long
785         int npackets = (len + packetsize - 1) / (packetsize);
786
787         if(protocol == PROTOCOL_QUAKEWORLD)
788                 return false; // CSQC can't run in QW anyway
789
790         SZ_Clear(buf);
791         if(cnt == 0)
792         {
793                 MSG_WriteByte(buf, svc_stufftext);
794                 MSG_WriteString(buf, va("\ncl_downloadbegin %lu %s\n", (unsigned long)len, filename));
795                 return true;
796         }
797         else if(cnt >= 1 && cnt <= npackets)
798         {
799                 unsigned long thispacketoffset = (cnt - 1) * packetsize;
800                 int thispacketsize = len - thispacketoffset;
801                 if(thispacketsize > packetsize)
802                         thispacketsize = packetsize;
803
804                 MSG_WriteByte(buf, svc_downloaddata);
805                 MSG_WriteLong(buf, thispacketoffset);
806                 MSG_WriteShort(buf, thispacketsize);
807                 SZ_Write(buf, data + thispacketoffset, thispacketsize);
808
809                 return true;
810         }
811         else if(cnt == npackets + 1)
812         {
813                 MSG_WriteByte(buf, svc_stufftext);
814                 MSG_WriteString(buf, va("\ncl_downloadfinished %lu %d\n", (unsigned long)len, crc));
815                 return true;
816         }
817         return false;
818 }
819
820 void CL_VM_Init (void)
821 {
822         const char* csprogsfn;
823         unsigned char *csprogsdata;
824         fs_offset_t csprogsdatasize;
825         int csprogsdatacrc, requiredcrc;
826         int requiredsize;
827         prvm_eval_t *val;
828
829         // reset csqc_progcrc after reading it, so that changing servers doesn't
830         // expect csqc on the next server
831         requiredcrc = csqc_progcrc.integer;
832         requiredsize = csqc_progsize.integer;
833         Cvar_SetValueQuick(&csqc_progcrc, -1);
834         Cvar_SetValueQuick(&csqc_progsize, -1);
835
836         // if the server is not requesting a csprogs, then we're done here
837         if (requiredcrc < 0)
838                 return;
839
840         // see if the requested csprogs.dat file matches the requested crc
841         csprogsdatacrc = -1;
842         csprogsfn = va("dlcache/%s.%i.%i", csqc_progname.string, requiredsize, requiredcrc);
843         csprogsdata = FS_LoadFile(csprogsfn, tempmempool, true, &csprogsdatasize);
844         if (!csprogsdata)
845         {
846                 csprogsfn = csqc_progname.string;
847                 csprogsdata = FS_LoadFile(csprogsfn, tempmempool, true, &csprogsdatasize);
848         }
849         if (csprogsdata)
850         {
851                 csprogsdatacrc = CRC_Block(csprogsdata, (size_t)csprogsdatasize);
852                 if (csprogsdatacrc != requiredcrc || csprogsdatasize != requiredsize)
853                 {
854                         if (cls.demoplayback)
855                         {
856                                 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);
857                                 // Mem_Free(csprogsdata);
858                                 // return;
859                                 // We WANT to continue here, and play the demo with different csprogs!
860                                 // After all, this is just a warning. Sure things may go wrong from here.
861                         }
862                         else
863                         {
864                                 Mem_Free(csprogsdata);
865                                 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);
866                                 CL_Disconnect();
867                                 return;
868                         }
869                 }
870         }
871         else
872         {
873                 if (requiredcrc >= 0)
874                 {
875                         if (cls.demoplayback)
876                                 Con_Printf("CL_VM_Init: demo requires CSQC, but \"%s\" wasn't found\n", csqc_progname.string);
877                         else
878                                 Con_Printf("CL_VM_Init: server requires CSQC, but \"%s\" wasn't found\n", csqc_progname.string);
879                         CL_Disconnect();
880                 }
881                 return;
882         }
883
884         PRVM_Begin;
885         PRVM_InitProg(PRVM_CLIENTPROG);
886
887         // allocate the mempools
888         prog->progs_mempool = Mem_AllocPool(csqc_progname.string, 0, NULL);
889         prog->headercrc = CL_PROGHEADER_CRC;
890         prog->edictprivate_size = 0; // no private struct used
891         prog->name = CL_NAME;
892         prog->num_edicts = 1;
893         prog->max_edicts = 512;
894         prog->limit_edicts = CL_MAX_EDICTS;
895         prog->reserved_edicts = 0;
896         prog->edictprivate_size = sizeof(edict_engineprivate_t);
897         // TODO: add a shared extension string #define and add real support for csqc extension strings [12/5/2007 Black]
898         prog->extensionstring = vm_sv_extensions;
899         prog->builtins = vm_cl_builtins;
900         prog->numbuiltins = vm_cl_numbuiltins;
901         prog->begin_increase_edicts = CL_VM_CB_BeginIncreaseEdicts;
902         prog->end_increase_edicts = CL_VM_CB_EndIncreaseEdicts;
903         prog->init_edict = CL_VM_CB_InitEdict;
904         prog->free_edict = CL_VM_CB_FreeEdict;
905         prog->count_edicts = CL_VM_CB_CountEdicts;
906         prog->load_edict = CL_VM_CB_LoadEdict;
907         prog->init_cmd = VM_CL_Cmd_Init;
908         prog->reset_cmd = VM_CL_Cmd_Reset;
909         prog->error_cmd = CL_VM_Error;
910         prog->ExecuteProgram = CLVM_ExecuteProgram;
911
912         PRVM_LoadProgs(csprogsfn, cl_numrequiredfunc, cl_required_func, 0, NULL, 0, NULL);
913
914         if (!prog->loaded)
915         {
916                 CL_VM_Error("CSQC %s ^2failed to load\n", csprogsfn);
917                 if(!sv.active)
918                         CL_Disconnect();
919                 Mem_Free(csprogsdata);
920                 return;
921         }
922
923         Con_DPrintf("CSQC %s ^5loaded (crc=%i, size=%i)\n", csprogsfn, csprogsdatacrc, (int)csprogsdatasize);
924
925         if(cls.demorecording)
926         {
927                 if(cls.demo_lastcsprogssize != csprogsdatasize || cls.demo_lastcsprogscrc != csprogsdatacrc)
928                 {
929                         int i;
930                         static char buf[NET_MAXMESSAGE];
931                         sizebuf_t sb;
932                         unsigned char *demobuf; fs_offset_t demofilesize;
933
934                         sb.data = (unsigned char *) buf;
935                         sb.maxsize = sizeof(buf);
936                         i = 0;
937
938                         CL_CutDemo(&demobuf, &demofilesize);
939                         while(MakeDownloadPacket(csqc_progname.string, csprogsdata, (size_t)csprogsdatasize, csprogsdatacrc, i++, &sb, cls.protocol))
940                                 CL_WriteDemoMessage(&sb);
941                         CL_PasteDemo(&demobuf, &demofilesize);
942
943                         cls.demo_lastcsprogssize = csprogsdatasize;
944                         cls.demo_lastcsprogscrc = csprogsdatacrc;
945                 }
946         }
947         Mem_Free(csprogsdata);
948
949         // check if OP_STATE animation is possible in this dat file
950         if (prog->fieldoffsets.nextthink >= 0 && prog->fieldoffsets.frame >= 0 && prog->fieldoffsets.think >= 0 && prog->globaloffsets.self >= 0)
951                 prog->flag |= PRVM_OP_STATE;
952
953         // set time
954         prog->globals.client->time = cl.time;
955         prog->globals.client->self = 0;
956
957         prog->globals.client->mapname = PRVM_SetEngineString(cl.worldname);
958         prog->globals.client->player_localentnum = cl.playerentity;
959
960         // set map description (use world entity 0)
961         val = PRVM_EDICTFIELDVALUE(prog->edicts, prog->fieldoffsets.message);
962         if(val)
963                 val->string = PRVM_SetEngineString(cl.worldmessage);
964         VectorCopy(cl.world.mins, prog->edicts->fields.client->mins);
965         VectorCopy(cl.world.maxs, prog->edicts->fields.client->maxs);
966
967         // call the prog init
968         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Init, "QC function CSQC_Init is missing");
969
970         PRVM_End;
971         cl.csqc_loaded = true;
972
973         cl.csqc_vidvars.drawcrosshair = false;
974         cl.csqc_vidvars.drawenginesbar = false;
975
976         // Update Coop and Deathmatch Globals (at this point the client knows them from ServerInfo)
977         CL_VM_UpdateCoopDeathmatchGlobals(cl.gametype);
978 }
979
980 void CL_VM_ShutDown (void)
981 {
982         Cmd_ClearCsqcFuncs();
983         //Cvar_SetValueQuick(&csqc_progcrc, -1);
984         //Cvar_SetValueQuick(&csqc_progsize, -1);
985         if(!cl.csqc_loaded)
986                 return;
987         CSQC_BEGIN
988                 prog->globals.client->time = cl.time;
989                 prog->globals.client->self = 0;
990                 if (prog->funcoffsets.CSQC_Shutdown)
991                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Shutdown, "QC function CSQC_Shutdown is missing");
992                 PRVM_ResetProg();
993         CSQC_END
994         Con_DPrint("CSQC ^1unloaded\n");
995         cl.csqc_loaded = false;
996 }
997
998 qboolean CL_VM_GetEntitySoundOrigin(int entnum, vec3_t out)
999 {
1000         prvm_edict_t *ed;
1001         dp_model_t *mod;
1002         matrix4x4_t matrix;
1003         qboolean r = 0;
1004
1005         CSQC_BEGIN;
1006
1007         // FIXME consider attachments here!
1008
1009         ed = PRVM_EDICT_NUM(entnum - MAX_EDICTS);
1010
1011         if(!ed->priv.required->free)
1012         {
1013                 mod = CL_GetModelFromEdict(ed);
1014                 VectorCopy(ed->fields.client->origin, out);
1015                 if(CL_GetTagMatrix (&matrix, ed, 0) == 0)
1016                         Matrix4x4_OriginFromMatrix(&matrix, out);
1017                 if (mod && mod->soundfromcenter)
1018                         VectorMAMAM(1.0f, out, 0.5f, mod->normalmins, 0.5f, mod->normalmaxs, out);
1019                 r = 1;
1020         }
1021
1022         CSQC_END;
1023
1024         return r;
1025 }
1026
1027 qboolean CL_VM_TransformView(int entnum, matrix4x4_t *viewmatrix, mplane_t *clipplane, vec3_t visorigin)
1028 {
1029         qboolean ret = false;
1030         prvm_edict_t *ed;
1031         prvm_eval_t *val, *valforward, *valright, *valup, *valendpos;
1032         vec3_t forward, left, up, origin, ang;
1033         matrix4x4_t mat, matq;
1034
1035         CSQC_BEGIN
1036                 ed = PRVM_EDICT_NUM(entnum);
1037                 // camera:
1038                 //   camera_transform
1039                 if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.camera_transform)) && val->function)
1040                 {
1041                         ret = true;
1042                         if(viewmatrix || clipplane || visorigin)
1043                         {
1044                                 valforward = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.v_forward);
1045                                 valright = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.v_right);
1046                                 valup = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.v_up);
1047                                 valendpos = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.trace_endpos);
1048                                 if(valforward && valright && valup && valendpos)
1049                                 {
1050                                         Matrix4x4_ToVectors(viewmatrix, forward, left, up, origin);
1051                                         AnglesFromVectors(ang, forward, up, false);
1052                                         prog->globals.client->time = cl.time;
1053                                         prog->globals.client->self = entnum;
1054                                         VectorCopy(origin, PRVM_G_VECTOR(OFS_PARM0));
1055                                         VectorCopy(ang, PRVM_G_VECTOR(OFS_PARM1));
1056                                         VectorCopy(forward, valforward->vector);
1057                                         VectorScale(left, -1, valright->vector);
1058                                         VectorCopy(up, valup->vector);
1059                                         VectorCopy(origin, valendpos->vector);
1060                                         PRVM_ExecuteProgram(val->function, "QC function e.camera_transform is missing");
1061                                         VectorCopy(PRVM_G_VECTOR(OFS_RETURN), origin);
1062                                         VectorCopy(valforward->vector, forward);
1063                                         VectorScale(valright->vector, -1, left);
1064                                         VectorCopy(valup->vector, up);
1065                                         VectorCopy(valendpos->vector, visorigin);
1066                                         Matrix4x4_Invert_Full(&mat, viewmatrix);
1067                                         Matrix4x4_FromVectors(viewmatrix, forward, left, up, origin);
1068                                         Matrix4x4_Concat(&matq, viewmatrix, &mat);
1069                                         Matrix4x4_TransformPositivePlane(&matq, clipplane->normal[0], clipplane->normal[1], clipplane->normal[2], clipplane->dist, &clipplane->normal[0]);
1070                                 }
1071                         }
1072                 }
1073         CSQC_END
1074
1075         return ret;
1076 }