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