49eaafc679f5fe01c4038575c7d9c4fc78adcc5f
[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(va("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         // either fullbright or lit
216         if (!(entrender->effects & EF_FULLBRIGHT) && !r_fullbright.integer)
217                 entrender->flags |= RENDER_LIGHT;
218         // hide player shadow during intermission or nehahra movie
219         if (!(entrender->effects & (EF_NOSHADOW | EF_ADDITIVE | EF_NODEPTHTEST))
220          &&  (entrender->alpha >= 1)
221          && !(entrender->flags & RENDER_VIEWMODEL)
222          && (!(entrender->flags & RENDER_EXTERIORMODEL) || (!cl.intermission && cls.protocol != PROTOCOL_NEHAHRAMOVIE && !cl_noplayershadow.integer)))
223                 entrender->flags |= RENDER_SHADOW;
224         if (entrender->flags & RENDER_VIEWMODEL)
225                 entrender->flags |= RENDER_NOSELFSHADOW;
226
227         // make the other useful stuff
228         CL_UpdateRenderEntity(entrender);
229
230         return true;
231 }
232
233 qboolean CL_VM_InputEvent (qboolean down, int key, int ascii)
234 {
235         qboolean r;
236
237         if(!cl.csqc_loaded)
238                 return false;
239
240         CSQC_BEGIN
241                 if (!prog->funcoffsets.CSQC_InputEvent)
242                         r = false;
243                 else
244                 {
245                         prog->globals.client->time = cl.time;
246                         prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
247                         PRVM_G_FLOAT(OFS_PARM0) = !down; // 0 is down, 1 is up
248                         PRVM_G_FLOAT(OFS_PARM1) = key;
249                         PRVM_G_FLOAT(OFS_PARM2) = ascii;
250                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_InputEvent, "QC function CSQC_InputEvent is missing");
251                         r = CSQC_RETURNVAL;
252                 }
253         CSQC_END
254         return r;
255 }
256
257 qboolean CL_VM_UpdateView (void)
258 {
259         vec3_t emptyvector;
260         emptyvector[0] = 0;
261         emptyvector[1] = 0;
262         emptyvector[2] = 0;
263 //      vec3_t oldangles;
264         if(!cl.csqc_loaded)
265                 return false;
266         CSQC_BEGIN
267                 //VectorCopy(cl.viewangles, oldangles);
268                 prog->globals.client->time = cl.time;
269                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
270                 CSQC_SetGlobals();
271                 // clear renderable entity and light lists to prevent crashes if the
272                 // CSQC_UpdateView function does not call R_ClearScene as it should
273                 r_refdef.scene.numentities = 0;
274                 r_refdef.scene.numlights = 0;
275                 // pass in width and height as parameters (EXT_CSQC_1)
276                 PRVM_G_FLOAT(OFS_PARM0) = vid.width;
277                 PRVM_G_FLOAT(OFS_PARM1) = vid.height;
278                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_UpdateView, "QC function CSQC_UpdateView is missing");
279                 //VectorCopy(oldangles, cl.viewangles);
280                 // Dresk : Reset Dmg Globals Here
281                 CL_VM_UpdateDmgGlobals(0, 0, emptyvector);
282         CSQC_END
283         return true;
284 }
285
286 extern sizebuf_t vm_tempstringsbuf;
287 qboolean CL_VM_ConsoleCommand (const char *cmd)
288 {
289         int restorevm_tempstringsbuf_cursize;
290         qboolean r = false;
291         if(!cl.csqc_loaded)
292                 return false;
293         CSQC_BEGIN
294         if (prog->funcoffsets.CSQC_ConsoleCommand)
295         {
296                 prog->globals.client->time = cl.time;
297                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
298                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
299                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(cmd);
300                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_ConsoleCommand, "QC function CSQC_ConsoleCommand is missing");
301                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
302                 r = CSQC_RETURNVAL;
303         }
304         CSQC_END
305         return r;
306 }
307
308 qboolean CL_VM_Parse_TempEntity (void)
309 {
310         int                     t;
311         qboolean        r = false;
312         if(!cl.csqc_loaded)
313                 return false;
314         CSQC_BEGIN
315         if(prog->funcoffsets.CSQC_Parse_TempEntity)
316         {
317                 t = msg_readcount;
318                 prog->globals.client->time = cl.time;
319                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
320                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_TempEntity, "QC function CSQC_Parse_TempEntity is missing");
321                 r = CSQC_RETURNVAL;
322                 if(!r)
323                 {
324                         msg_readcount = t;
325                         msg_badread = false;
326                 }
327         }
328         CSQC_END
329         return r;
330 }
331
332 void CL_VM_Parse_StuffCmd (const char *msg)
333 {
334         int restorevm_tempstringsbuf_cursize;
335         if(msg[0] == 'c')
336         if(msg[1] == 's')
337         if(msg[2] == 'q')
338         if(msg[3] == 'c')
339         {
340                 // if this is setting a csqc variable, deprotect csqc_progcrc
341                 // temporarily so that it can be set by the cvar command,
342                 // and then reprotect it afterwards
343                 int crcflags = csqc_progcrc.flags;
344                 int sizeflags = csqc_progcrc.flags;
345                 csqc_progcrc.flags &= ~CVAR_READONLY;
346                 csqc_progsize.flags &= ~CVAR_READONLY;
347                 Cmd_ExecuteString (msg, src_command);
348                 csqc_progcrc.flags = crcflags;
349                 csqc_progsize.flags = sizeflags;
350                 return;
351         }
352         if(!cl.csqc_loaded)
353         {
354                 Cbuf_AddText(msg);
355                 return;
356         }
357         CSQC_BEGIN
358         if(prog->funcoffsets.CSQC_Parse_StuffCmd)
359         {
360                 prog->globals.client->time = cl.time;
361                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
362                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
363                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
364                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_StuffCmd, "QC function CSQC_Parse_StuffCmd is missing");
365                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
366         }
367         else
368                 Cbuf_AddText(msg);
369         CSQC_END
370 }
371
372 static void CL_VM_Parse_Print (const char *msg)
373 {
374         int restorevm_tempstringsbuf_cursize;
375         prog->globals.client->time = cl.time;
376         prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
377         restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
378         PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
379         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_Print, "QC function CSQC_Parse_Print is missing");
380         vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
381 }
382
383 void CSQC_AddPrintText (const char *msg)
384 {
385         size_t i;
386         if(!cl.csqc_loaded)
387         {
388                 Con_Print(msg);
389                 return;
390         }
391         CSQC_BEGIN
392         if(prog->funcoffsets.CSQC_Parse_Print)
393         {
394                 // FIXME: is this bugged?
395                 i = strlen(msg)-1;
396                 if(msg[i] != '\n' && msg[i] != '\r')
397                 {
398                         if(strlen(cl.csqc_printtextbuf)+i >= MAX_INPUTLINE)
399                         {
400                                 CL_VM_Parse_Print(cl.csqc_printtextbuf);
401                                 cl.csqc_printtextbuf[0] = 0;
402                         }
403                         else
404                                 strlcat(cl.csqc_printtextbuf, msg, MAX_INPUTLINE);
405                         return;
406                 }
407                 strlcat(cl.csqc_printtextbuf, msg, MAX_INPUTLINE);
408                 CL_VM_Parse_Print(cl.csqc_printtextbuf);
409                 cl.csqc_printtextbuf[0] = 0;
410         }
411         else
412                 Con_Print(msg);
413         CSQC_END
414 }
415
416 void CL_VM_Parse_CenterPrint (const char *msg)
417 {
418         int restorevm_tempstringsbuf_cursize;
419         if(!cl.csqc_loaded)
420         {
421                 SCR_CenterPrint(msg);
422                 return;
423         }
424         CSQC_BEGIN
425         if(prog->funcoffsets.CSQC_Parse_CenterPrint)
426         {
427                 prog->globals.client->time = cl.time;
428                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
429                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
430                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
431                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_CenterPrint, "QC function CSQC_Parse_CenterPrint is missing");
432                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
433         }
434         else
435                 SCR_CenterPrint(msg);
436         CSQC_END
437 }
438
439 void CL_VM_UpdateIntermissionState (int intermission)
440 {
441         prvm_eval_t *val;
442         if(cl.csqc_loaded)
443         {
444                 CSQC_BEGIN
445                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.intermission);
446                 if(val)
447                         val->_float = intermission;
448                 CSQC_END
449         }
450 }
451 void CL_VM_UpdateShowingScoresState (int showingscores)
452 {
453         prvm_eval_t *val;
454         if(cl.csqc_loaded)
455         {
456                 CSQC_BEGIN
457                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.sb_showscores);
458                 if(val)
459                         val->_float = showingscores;
460                 CSQC_END
461         }
462 }
463 qboolean CL_VM_Event_Sound(int sound_num, int volume, int channel, float attenuation, int ent, vec3_t pos)
464 {
465         qboolean r = false;
466         if(cl.csqc_loaded)
467         {
468                 CSQC_BEGIN
469                 if(prog->funcoffsets.CSQC_Event_Sound)
470                 {
471                         prog->globals.client->time = cl.time;
472                         prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
473                         PRVM_G_FLOAT(OFS_PARM0) = ent;
474                         PRVM_G_FLOAT(OFS_PARM1) = channel;
475                         PRVM_G_INT(OFS_PARM2) = PRVM_SetTempString(cl.sound_name[sound_num] );
476                         PRVM_G_FLOAT(OFS_PARM3) = volume;
477                         PRVM_G_FLOAT(OFS_PARM4) = attenuation;
478                         VectorCopy(pos, PRVM_G_VECTOR(OFS_PARM5) );
479                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Event_Sound, "QC function CSQC_Event_Sound is missing");
480                         r = CSQC_RETURNVAL;
481                 }
482                 CSQC_END
483         }
484
485         return r;
486 }
487 void CL_VM_UpdateCoopDeathmatchGlobals (int gametype)
488 {
489         // Avoid global names for clean(er) coding
490         int localcoop;
491         int localdeathmatch;
492
493         prvm_eval_t *val;
494         if(cl.csqc_loaded)
495         {
496                 if(gametype == GAME_COOP)
497                 {
498                         localcoop = 1;
499                         localdeathmatch = 0;
500                 }
501                 else
502                 if(gametype == GAME_DEATHMATCH)
503                 {
504                         localcoop = 0;
505                         localdeathmatch = 1;
506                 }
507                 else
508                 {
509                         // How did the ServerInfo send an unknown gametype?
510                         // Better just assign the globals as 0...
511                         localcoop = 0;
512                         localdeathmatch = 0;
513                 }
514                 CSQC_BEGIN
515                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.coop);
516                 if(val)
517                         val->_float = localcoop;
518                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.deathmatch);
519                 if(val)
520                         val->_float = localdeathmatch;
521                 CSQC_END
522         }
523 }
524 float CL_VM_Event (float event)         //[515]: needed ? I'd say "YES", but don't know for what :D
525 {
526         float r = 0;
527         if(!cl.csqc_loaded)
528                 return 0;
529         CSQC_BEGIN
530         if(prog->funcoffsets.CSQC_Event)
531         {
532                 prog->globals.client->time = cl.time;
533                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[cl.playerentity];
534                 PRVM_G_FLOAT(OFS_PARM0) = event;
535                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Event, "QC function CSQC_Event is missing");
536                 r = CSQC_RETURNVAL;
537         }
538         CSQC_END
539         return r;
540 }
541
542 void CSQC_ReadEntities (void)
543 {
544         unsigned short entnum, oldself, realentnum;
545         if(!cl.csqc_loaded)
546         {
547                 Host_Error ("CSQC_ReadEntities: CSQC is not loaded");
548                 return;
549         }
550
551         CSQC_BEGIN
552                 prog->globals.client->time = cl.time;
553                 oldself = prog->globals.client->self;
554                 while(1)
555                 {
556                         entnum = MSG_ReadShort();
557                         if(!entnum || msg_badread)
558                                 return;
559                         realentnum = entnum & 0x7FFF;
560                         prog->globals.client->self = cl.csqc_server2csqcentitynumber[realentnum];
561                         if(entnum & 0x8000)
562                         {
563                                 if(prog->globals.client->self)
564                                 {
565                                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Ent_Remove, "QC function CSQC_Ent_Remove is missing");
566                                         cl.csqc_server2csqcentitynumber[realentnum] = 0;
567                                 }
568                                 else
569                                 {
570                                         // LordHavoc: removing an entity that is already gone on
571                                         // the csqc side is possible for legitimate reasons (such
572                                         // as a repeat of the remove message), so no warning is
573                                         // needed
574                                         //Con_Printf("Bad csqc_server2csqcentitynumber map\n"); //[515]: never happens ?
575                                 }
576                         }
577                         else
578                         {
579                                 if(!prog->globals.client->self)
580                                 {
581                                         if(!prog->funcoffsets.CSQC_Ent_Spawn)
582                                         {
583                                                 prvm_edict_t    *ed;
584                                                 ed = PRVM_ED_Alloc();
585                                                 ed->fields.client->entnum = realentnum;
586                                                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[realentnum] = PRVM_EDICT_TO_PROG(ed);
587                                         }
588                                         else
589                                         {
590                                                 // entity( float entnum ) CSQC_Ent_Spawn;
591                                                 // the qc function should set entnum, too (this way it also can return world [2/1/2008 Andreas]
592                                                 PRVM_G_FLOAT(OFS_PARM0) = (float) realentnum;
593                                                 // make sure no one gets wrong ideas
594                                                 prog->globals.client->self = 0;
595                                                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Ent_Spawn, "QC function CSQC_Ent_Spawn is missing");
596                                                 prog->globals.client->self = cl.csqc_server2csqcentitynumber[realentnum] = PRVM_EDICT( PRVM_G_INT( OFS_RETURN ) );
597                                         }
598                                         PRVM_G_FLOAT(OFS_PARM0) = 1;
599                                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Ent_Update, "QC function CSQC_Ent_Update is missing");
600                                 }
601                                 else {
602                                         PRVM_G_FLOAT(OFS_PARM0) = 0;
603                                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Ent_Update, "QC function CSQC_Ent_Update is missing");
604                                 }
605                         }
606                 }
607                 prog->globals.client->self = oldself;
608         CSQC_END
609 }
610
611 void CL_VM_CB_BeginIncreaseEdicts(void)
612 {
613         // links don't survive the transition, so unlink everything
614         World_UnlinkAll(&cl.world);
615 }
616
617 void CL_VM_CB_EndIncreaseEdicts(void)
618 {
619         int i;
620         prvm_edict_t *ent;
621
622         // link every entity except world
623         for (i = 1, ent = prog->edicts;i < prog->max_edicts;i++, ent++)
624                 if (!ent->priv.server->free)
625                         CL_LinkEdict(ent);
626 }
627
628 void CL_VM_CB_InitEdict(prvm_edict_t *e)
629 {
630         e->priv.server->move = false; // don't move on first frame
631 }
632
633 void CL_VM_CB_FreeEdict(prvm_edict_t *ed)
634 {
635         World_UnlinkEdict(ed);
636         memset(ed->fields.client, 0, sizeof(*ed->fields.client));
637 }
638
639 void CL_VM_CB_CountEdicts(void)
640 {
641         int             i;
642         prvm_edict_t    *ent;
643         int             active = 0, models = 0, solid = 0;
644
645         for (i=0 ; i<prog->num_edicts ; i++)
646         {
647                 ent = PRVM_EDICT_NUM(i);
648                 if (ent->priv.server->free)
649                         continue;
650                 active++;
651                 if (ent->fields.client->solid)
652                         solid++;
653                 if (ent->fields.client->model)
654                         models++;
655         }
656
657         Con_Printf("num_edicts:%3i\n", prog->num_edicts);
658         Con_Printf("active    :%3i\n", active);
659         Con_Printf("view      :%3i\n", models);
660         Con_Printf("touch     :%3i\n", solid);
661 }
662
663 qboolean CL_VM_CB_LoadEdict(prvm_edict_t *ent)
664 {
665         return true;
666 }
667
668 void Cmd_ClearCsqcFuncs (void);
669
670 // returns true if the packet is valid, false if end of file is reached
671 // used for dumping the CSQC download into demo files
672 qboolean MakeDownloadPacket(const char *filename, unsigned char *data, unsigned long len, int crc, int cnt, sizebuf_t *buf, int protocol)
673 {
674         int packetsize = buf->maxsize - 7; // byte short long
675         int npackets = (len + packetsize - 1) / (packetsize);
676
677         if(protocol == PROTOCOL_QUAKEWORLD)
678                 return false; // CSQC can't run in QW anyway
679
680         SZ_Clear(buf);
681         if(cnt == 0)
682         {
683                 MSG_WriteByte(buf, svc_stufftext);
684                 MSG_WriteString(buf, va("\ncl_downloadbegin %lu %s\n", len, filename));
685                 return true;
686         }
687         else if(cnt >= 1 && cnt <= npackets)
688         {
689                 unsigned long thispacketoffset = (cnt - 1) * packetsize;
690                 int thispacketsize = len - thispacketoffset;
691                 if(thispacketsize > packetsize)
692                         thispacketsize = packetsize;
693
694                 MSG_WriteByte(buf, svc_downloaddata);
695                 MSG_WriteLong(buf, thispacketoffset);
696                 MSG_WriteShort(buf, thispacketsize);
697                 SZ_Write(buf, data + thispacketoffset, thispacketsize);
698
699                 return true;
700         }
701         else if(cnt == npackets + 1)
702         {
703                 MSG_WriteByte(buf, svc_stufftext);
704                 MSG_WriteString(buf, va("\ncl_downloadfinished %lu %d\n", len, crc));
705                 return true;
706         }
707         return false;
708 }
709
710 void CL_VM_Init (void)
711 {
712         const char* csprogsfn;
713         unsigned char *csprogsdata;
714         fs_offset_t csprogsdatasize;
715         int csprogsdatacrc, requiredcrc;
716         int requiredsize;
717         prvm_eval_t *val;
718
719         // reset csqc_progcrc after reading it, so that changing servers doesn't
720         // expect csqc on the next server
721         requiredcrc = csqc_progcrc.integer;
722         requiredsize = csqc_progsize.integer;
723         Cvar_SetValueQuick(&csqc_progcrc, -1);
724         Cvar_SetValueQuick(&csqc_progsize, -1);
725
726         // if the server is not requesting a csprogs, then we're done here
727         if (requiredcrc < 0)
728                 return;
729
730         // see if the requested csprogs.dat file matches the requested crc
731         csprogsdatacrc = -1;
732         csprogsfn = va("dlcache/%s.%i.%i", csqc_progname.string, requiredsize, requiredcrc);
733         csprogsdata = FS_LoadFile(csprogsfn, tempmempool, true, &csprogsdatasize);
734         if (!csprogsdata)
735         {
736                 csprogsfn = csqc_progname.string;
737                 csprogsdata = FS_LoadFile(csprogsfn, tempmempool, true, &csprogsdatasize);
738         }
739         if (csprogsdata)
740         {
741                 csprogsdatacrc = CRC_Block(csprogsdata, csprogsdatasize);
742                 if (csprogsdatacrc != requiredcrc || csprogsdatasize != requiredsize)
743                 {
744                         if (cls.demoplayback)
745                         {
746                                 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);
747                                 // Mem_Free(csprogsdata);
748                                 // return;
749                                 // We WANT to continue here, and play the demo with different csprogs!
750                                 // After all, this is just a warning. Sure things may go wrong from here.
751                         }
752                         else
753                         {
754                                 Mem_Free(csprogsdata);
755                                 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);
756                                 CL_Disconnect();
757                                 return;
758                         }
759                 }
760         }
761         else
762         {
763                 if (requiredcrc >= 0)
764                 {
765                         if (cls.demoplayback)
766                                 Con_Printf("CL_VM_Init: demo requires CSQC, but \"%s\" wasn't found\n", csqc_progname.string);
767                         else
768                                 Con_Printf("CL_VM_Init: server requires CSQC, but \"%s\" wasn't found\n", csqc_progname.string);
769                         CL_Disconnect();
770                 }
771                 return;
772         }
773
774         PRVM_Begin;
775         PRVM_InitProg(PRVM_CLIENTPROG);
776
777         // allocate the mempools
778         prog->progs_mempool = Mem_AllocPool(csqc_progname.string, 0, NULL);
779         prog->headercrc = CL_PROGHEADER_CRC;
780         prog->edictprivate_size = 0; // no private struct used
781         prog->name = CL_NAME;
782         prog->num_edicts = 1;
783         prog->max_edicts = 512;
784         prog->limit_edicts = CL_MAX_EDICTS;
785         prog->reserved_edicts = 0;
786         prog->edictprivate_size = sizeof(edict_engineprivate_t);
787         // TODO: add a shared extension string #define and add real support for csqc extension strings [12/5/2007 Black]
788         prog->extensionstring = vm_sv_extensions;
789         prog->builtins = vm_cl_builtins;
790         prog->numbuiltins = vm_cl_numbuiltins;
791         prog->begin_increase_edicts = CL_VM_CB_BeginIncreaseEdicts;
792         prog->end_increase_edicts = CL_VM_CB_EndIncreaseEdicts;
793         prog->init_edict = CL_VM_CB_InitEdict;
794         prog->free_edict = CL_VM_CB_FreeEdict;
795         prog->count_edicts = CL_VM_CB_CountEdicts;
796         prog->load_edict = CL_VM_CB_LoadEdict;
797         prog->init_cmd = VM_CL_Cmd_Init;
798         prog->reset_cmd = VM_CL_Cmd_Reset;
799         prog->error_cmd = CL_VM_Error;
800
801         PRVM_LoadProgs(csprogsfn, cl_numrequiredfunc, cl_required_func, 0, NULL, 0, NULL);
802
803         if (!prog->loaded)
804         {
805                 CL_VM_Error("CSQC %s ^2failed to load\n", csprogsfn);
806                 if(!sv.active)
807                         CL_Disconnect();
808                 Mem_Free(csprogsdata);
809                 return;
810         }
811
812         Con_Printf("CSQC %s ^5loaded (crc=%i, size=%i)\n", csprogsfn, csprogsdatacrc, (int)csprogsdatasize);
813
814         if(cls.demorecording)
815         {
816                 if(cls.demo_lastcsprogssize != csprogsdatasize || cls.demo_lastcsprogscrc != csprogsdatacrc)
817                 {
818                         int i;
819                         char buf[NET_MAXMESSAGE];
820                         sizebuf_t sb;
821                         unsigned char *demobuf; fs_offset_t demofilesize;
822
823                         sb.data = (void *) buf;
824                         sb.maxsize = sizeof(buf);
825                         i = 0;
826
827                         CL_CutDemo(&demobuf, &demofilesize);
828                         while(MakeDownloadPacket(csprogsfn, csprogsdata, csprogsdatasize, csprogsdatacrc, i++, &sb, cls.protocol))
829                                 CL_WriteDemoMessage(&sb);
830                         CL_PasteDemo(&demobuf, &demofilesize);
831
832                         cls.demo_lastcsprogssize = csprogsdatasize;
833                         cls.demo_lastcsprogscrc = csprogsdatacrc;
834                 }
835         }
836         Mem_Free(csprogsdata);
837
838         // check if OP_STATE animation is possible in this dat file
839         if (prog->fieldoffsets.nextthink >= 0 && prog->fieldoffsets.frame >= 0 && prog->fieldoffsets.think >= 0 && prog->globaloffsets.self >= 0)
840                 prog->flag |= PRVM_OP_STATE;
841
842         // set time
843         prog->globals.client->time = cl.time;
844         prog->globals.client->self = 0;
845
846         prog->globals.client->mapname = cl.worldmodel ? PRVM_SetEngineString(cl.worldmodel->name) : PRVM_SetEngineString("");
847         prog->globals.client->player_localentnum = cl.playerentity;
848
849         // set map description (use world entity 0)
850         val = PRVM_EDICTFIELDVALUE(prog->edicts, prog->fieldoffsets.message);
851         if(val)
852                 val->string = PRVM_SetEngineString(cl.levelname);
853         VectorCopy(cl.world.mins, prog->edicts->fields.client->mins);
854         VectorCopy(cl.world.maxs, prog->edicts->fields.client->maxs);
855
856         // call the prog init
857         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Init, "QC function CSQC_Init is missing");
858
859         PRVM_End;
860         cl.csqc_loaded = true;
861
862         cl.csqc_vidvars.drawcrosshair = false;
863         cl.csqc_vidvars.drawenginesbar = false;
864
865         // Update Coop and Deathmatch Globals (at this point the client knows them from ServerInfo)
866         CL_VM_UpdateCoopDeathmatchGlobals(cl.gametype);
867 }
868
869 void CL_VM_ShutDown (void)
870 {
871         Cmd_ClearCsqcFuncs();
872         //Cvar_SetValueQuick(&csqc_progcrc, -1);
873         //Cvar_SetValueQuick(&csqc_progsize, -1);
874         if(!cl.csqc_loaded)
875                 return;
876         CSQC_BEGIN
877                 prog->globals.client->time = cl.time;
878                 prog->globals.client->self = 0;
879                 if (prog->funcoffsets.CSQC_Shutdown)
880                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Shutdown, "QC function CSQC_Shutdown is missing");
881                 PRVM_ResetProg();
882         CSQC_END
883         Con_Print("CSQC ^1unloaded\n");
884         cl.csqc_loaded = false;
885 }