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