Made CSQC_AddRenderEdict compute the tag matrix if a tag is set.
[divverent/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_t *e;
133         model_t *model;
134         matrix4x4_t tagmatrix, matrix2;
135
136         model = CL_GetModelFromEdict(ed);
137         if (!model)
138                 return false;
139
140         e = CL_NewTempEntity();
141         if (!e)
142                 return false;
143
144         e->render.model = model;
145         e->render.skinnum = (int)ed->fields.client->skin;
146         e->render.effects |= e->render.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)           e->render.alpha = val->_float;
151         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.scale)) && val->_float)           e->render.scale = scale = val->_float;
152         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.colormod)) && VectorLength2(val->vector)) VectorCopy(val->vector, e->render.colormod);
153         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.effects)) && val->_float) e->render.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 (e->render.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         e->render.frame1 = e->render.frame2 = ed->fields.client->frame;
191         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame2))) e->render.frame2 = val->_float;
192         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame1time))) e->render.frame2time = val->_float;
193         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame2time))) e->render.frame1time = val->_float;
194         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.lerpfrac))) e->render.framelerp = val->_float;
195
196         // concat the matrices to make the entity relative to its tag
197         Matrix4x4_Concat(&e->render.matrix, &tagmatrix, &matrix2);
198
199         if(renderflags)
200         {
201                 if(renderflags & RF_VIEWMODEL)  e->render.flags |= RENDER_VIEWMODEL;
202                 if(renderflags & RF_EXTERNALMODEL)e->render.flags |= RENDER_EXTERIORMODEL;
203                 if(renderflags & RF_DEPTHHACK)  e->render.effects |= EF_NODEPTHTEST;
204                 if(renderflags & RF_ADDITIVE)           e->render.effects |= EF_ADDITIVE;
205         }
206
207         c = (int)ed->fields.client->colormap;
208         if (c <= 0)
209                 CL_SetEntityColormapColors(&e->render, -1);
210         else if (c <= cl.maxclients && cl.scores != NULL)
211                 CL_SetEntityColormapColors(&e->render, cl.scores[c-1].colors);
212         else
213                 CL_SetEntityColormapColors(&e->render, c);
214
215         // either fullbright or lit
216         if (!(e->render.effects & EF_FULLBRIGHT) && !r_fullbright.integer)
217                 e->render.flags |= RENDER_LIGHT;
218         // hide player shadow during intermission or nehahra movie
219         if (!(e->render.effects & (EF_NOSHADOW | EF_ADDITIVE | EF_NODEPTHTEST))
220          &&  (e->render.alpha >= 1)
221          && !(e->render.flags & RENDER_VIEWMODEL)
222          && (!(e->render.flags & RENDER_EXTERIORMODEL) || (!cl.intermission && cls.protocol != PROTOCOL_NEHAHRAMOVIE && !cl_noplayershadow.integer)))
223                 e->render.flags |= RENDER_SHADOW;
224         if (e->render.flags & RENDER_VIEWMODEL)
225                 e->render.flags |= RENDER_NOSELFSHADOW;
226
227         // make the other useful stuff
228         CL_UpdateRenderEntity(&e->render);
229
230         return true;
231 }
232
233 qboolean CL_VM_InputEvent (qboolean down, int key)
234 {
235         qboolean r;
236         if(!cl.csqc_loaded)
237                 return false;
238         CSQC_BEGIN
239                 if (!prog->funcoffsets.CSQC_InputEvent)
240                         r = false;
241                 else
242                 {
243                         prog->globals.client->time = cl.time;
244                         PRVM_G_FLOAT(OFS_PARM0) = !down; // 0 is down, 1 is up
245                         PRVM_G_FLOAT(OFS_PARM1) = key;
246                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_InputEvent, "QC function CSQC_InputEvent is missing");
247                         r = CSQC_RETURNVAL;
248                 }
249         CSQC_END
250         return r;
251 }
252
253 qboolean CL_VM_UpdateView (void)
254 {
255         vec3_t emptyvector;
256         emptyvector[0] = 0;
257         emptyvector[1] = 0;
258         emptyvector[2] = 0;
259 //      vec3_t oldangles;
260         if(!cl.csqc_loaded)
261                 return false;
262         CSQC_BEGIN
263                 //VectorCopy(cl.viewangles, oldangles);
264                 prog->globals.client->time = cl.time;
265                 CSQC_SetGlobals();
266                 // clear renderable entity and light lists to prevent crashes if the
267                 // CSQC_UpdateView function does not call R_ClearScene as it should
268                 r_refdef.numentities = 0;
269                 r_refdef.numlights = 0;
270                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_UpdateView, "QC function CSQC_UpdateView is missing");
271                 //VectorCopy(oldangles, cl.viewangles);
272                 // Dresk : Reset Dmg Globals Here
273                 CL_VM_UpdateDmgGlobals(0, 0, emptyvector);
274         CSQC_END
275         return true;
276 }
277
278 extern sizebuf_t vm_tempstringsbuf;
279 qboolean CL_VM_ConsoleCommand (const char *cmd)
280 {
281         int restorevm_tempstringsbuf_cursize;
282         qboolean r = false;
283         if(!cl.csqc_loaded)
284                 return false;
285         CSQC_BEGIN
286         if (prog->funcoffsets.CSQC_ConsoleCommand)
287         {
288                 prog->globals.client->time = cl.time;
289                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
290                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(cmd);
291                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_ConsoleCommand, "QC function CSQC_ConsoleCommand is missing");
292                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
293                 r = CSQC_RETURNVAL;
294         }
295         CSQC_END
296         return r;
297 }
298
299 qboolean CL_VM_Parse_TempEntity (void)
300 {
301         int                     t;
302         qboolean        r = false;
303         if(!cl.csqc_loaded)
304                 return false;
305         CSQC_BEGIN
306         if(prog->funcoffsets.CSQC_Parse_TempEntity)
307         {
308                 t = msg_readcount;
309                 prog->globals.client->time = cl.time;
310                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_TempEntity, "QC function CSQC_Parse_TempEntity is missing");
311                 r = CSQC_RETURNVAL;
312                 if(!r)
313                 {
314                         msg_readcount = t;
315                         msg_badread = false;
316                 }
317         }
318         CSQC_END
319         return r;
320 }
321
322 void CL_VM_Parse_StuffCmd (const char *msg)
323 {
324         int restorevm_tempstringsbuf_cursize;
325         if(msg[0] == 'c')
326         if(msg[1] == 's')
327         if(msg[2] == 'q')
328         if(msg[3] == 'c')
329         {
330                 // if this is setting a csqc variable, deprotect csqc_progcrc
331                 // temporarily so that it can be set by the cvar command,
332                 // and then reprotect it afterwards
333                 int crcflags = csqc_progcrc.flags;
334                 int sizeflags = csqc_progcrc.flags;
335                 csqc_progcrc.flags &= ~CVAR_READONLY;
336                 csqc_progsize.flags &= ~CVAR_READONLY;
337                 Cmd_ExecuteString (msg, src_command);
338                 csqc_progcrc.flags = crcflags;
339                 csqc_progsize.flags = sizeflags;
340                 return;
341         }
342         if(!cl.csqc_loaded)
343         {
344                 Cbuf_AddText(msg);
345                 return;
346         }
347         CSQC_BEGIN
348         if(prog->funcoffsets.CSQC_Parse_StuffCmd)
349         {
350                 prog->globals.client->time = cl.time;
351                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
352                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
353                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_StuffCmd, "QC function CSQC_Parse_StuffCmd is missing");
354                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
355         }
356         else
357                 Cbuf_AddText(msg);
358         CSQC_END
359 }
360
361 static void CL_VM_Parse_Print (const char *msg)
362 {
363         int restorevm_tempstringsbuf_cursize;
364         prog->globals.client->time = cl.time;
365         restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
366         PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
367         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_Print, "QC function CSQC_Parse_Print is missing");
368         vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
369 }
370
371 void CSQC_AddPrintText (const char *msg)
372 {
373         size_t i;
374         if(!cl.csqc_loaded)
375         {
376                 Con_Print(msg);
377                 return;
378         }
379         CSQC_BEGIN
380         if(prog->funcoffsets.CSQC_Parse_Print)
381         {
382                 // FIXME: is this bugged?
383                 i = strlen(msg)-1;
384                 if(msg[i] != '\n' && msg[i] != '\r')
385                 {
386                         if(strlen(cl.csqc_printtextbuf)+i >= MAX_INPUTLINE)
387                         {
388                                 CL_VM_Parse_Print(cl.csqc_printtextbuf);
389                                 cl.csqc_printtextbuf[0] = 0;
390                         }
391                         else
392                                 strlcat(cl.csqc_printtextbuf, msg, MAX_INPUTLINE);
393                         return;
394                 }
395                 strlcat(cl.csqc_printtextbuf, msg, MAX_INPUTLINE);
396                 CL_VM_Parse_Print(cl.csqc_printtextbuf);
397                 cl.csqc_printtextbuf[0] = 0;
398         }
399         else
400                 Con_Print(msg);
401         CSQC_END
402 }
403
404 void CL_VM_Parse_CenterPrint (const char *msg)
405 {
406         int restorevm_tempstringsbuf_cursize;
407         if(!cl.csqc_loaded)
408         {
409                 SCR_CenterPrint((char*)msg);
410                 return;
411         }
412         CSQC_BEGIN
413         if(prog->funcoffsets.CSQC_Parse_CenterPrint)
414         {
415                 prog->globals.client->time = cl.time;
416                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
417                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
418                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_CenterPrint, "QC function CSQC_Parse_CenterPrint is missing");
419                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
420         }
421         else
422                 SCR_CenterPrint((char*)msg);
423         CSQC_END
424 }
425
426 void CL_VM_UpdateIntermissionState (int intermission)
427 {
428         prvm_eval_t *val;
429         if(cl.csqc_loaded)
430         {
431                 CSQC_BEGIN
432                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.intermission);
433                 if(val)
434                         val->_float = intermission;
435                 CSQC_END
436         }
437 }
438 void CL_VM_UpdateShowingScoresState (int showingscores)
439 {
440         prvm_eval_t *val;
441         if(cl.csqc_loaded)
442         {
443                 CSQC_BEGIN
444                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.sb_showscores);
445                 if(val)
446                         val->_float = showingscores;
447                 CSQC_END
448         }
449 }
450 qboolean CL_VM_Event_Sound(int sound_num, int volume, int channel, float attenuation, int ent, vec3_t pos)
451 {
452         qboolean r = false;
453         if(cl.csqc_loaded)
454         {
455                 CSQC_BEGIN
456                 if(prog->funcoffsets.CSQC_Event_Sound)
457                 {
458                         prog->globals.client->time = cl.time;
459                         PRVM_G_FLOAT(OFS_PARM0) = ent;
460                         PRVM_G_FLOAT(OFS_PARM1) = channel;
461                         PRVM_G_INT(OFS_PARM2) = PRVM_SetTempString(cl.sound_name[sound_num] );
462                         PRVM_G_FLOAT(OFS_PARM3) = volume;
463                         PRVM_G_FLOAT(OFS_PARM4) = attenuation;
464                         VectorCopy(pos, PRVM_G_VECTOR(OFS_PARM5) );
465                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Event_Sound, "QC function CSQC_Event_Sound is missing");
466                         r = CSQC_RETURNVAL;
467                 }
468                 CSQC_END
469         }
470
471         return r;
472 }
473 void CL_VM_UpdateCoopDeathmatchGlobals (int gametype)
474 {
475         // Avoid global names for clean(er) coding
476         int localcoop;
477         int localdeathmatch;
478
479         prvm_eval_t *val;
480         if(cl.csqc_loaded)
481         {
482                 if(gametype == GAME_COOP)
483                 {
484                         localcoop = 1;
485                         localdeathmatch = 0;
486                 }
487                 else
488                 if(gametype == GAME_DEATHMATCH)
489                 {
490                         localcoop = 0;
491                         localdeathmatch = 1;
492                 }
493                 else
494                 {
495                         // How did the ServerInfo send an unknown gametype?
496                         // Better just assign the globals as 0...
497                         localcoop = 0;
498                         localdeathmatch = 0;
499                 }
500                 CSQC_BEGIN
501                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.coop);
502                 if(val)
503                         val->_float = localcoop;
504                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.deathmatch);
505                 if(val)
506                         val->_float = localdeathmatch;
507                 CSQC_END
508         }
509 }
510 float CL_VM_Event (float event)         //[515]: needed ? I'd say "YES", but don't know for what :D
511 {
512         float r = 0;
513         if(!cl.csqc_loaded)
514                 return 0;
515         CSQC_BEGIN
516         if(prog->funcoffsets.CSQC_Event)
517         {
518                 prog->globals.client->time = cl.time;
519                 PRVM_G_FLOAT(OFS_PARM0) = event;
520                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Event, "QC function CSQC_Event is missing");
521                 r = CSQC_RETURNVAL;
522         }
523         CSQC_END
524         return r;
525 }
526
527 void CSQC_ReadEntities (void)
528 {
529         unsigned short entnum, oldself, realentnum;
530         if(!cl.csqc_loaded)
531         {
532                 Host_Error ("CSQC_ReadEntities: CSQC is not loaded");
533                 return;
534         }
535
536         CSQC_BEGIN
537                 prog->globals.client->time = cl.time;
538                 oldself = prog->globals.client->self;
539                 while(1)
540                 {
541                         entnum = MSG_ReadShort();
542                         if(!entnum || msg_badread)
543                                 return;
544                         realentnum = entnum & 0x7FFF;
545                         prog->globals.client->self = cl.csqc_server2csqcentitynumber[realentnum];
546                         if(entnum & 0x8000)
547                         {
548                                 if(prog->globals.client->self)
549                                 {
550                                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Ent_Remove, "QC function CSQC_Ent_Remove is missing");
551                                         cl.csqc_server2csqcentitynumber[realentnum] = 0;
552                                 }
553                                 else
554                                         Con_Printf("Smth bad happens in csqc...\n");    //[515]: never happens ?
555                         }
556                         else
557                         {
558                                 if(!prog->globals.client->self)
559                                 {
560                                         prvm_edict_t    *ed;
561                                         ed = PRVM_ED_Alloc();
562                                         ed->fields.client->entnum = realentnum;
563                                         prog->globals.client->self = cl.csqc_server2csqcentitynumber[realentnum] = PRVM_EDICT_TO_PROG(ed);
564                                         PRVM_G_FLOAT(OFS_PARM0) = 1;
565                                 }
566                                 else
567                                         PRVM_G_FLOAT(OFS_PARM0) = 0;
568                                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Ent_Update, "QC function CSQC_Ent_Update is missing");
569                         }
570                 }
571                 prog->globals.client->self = oldself;
572         CSQC_END
573 }
574
575 void CL_VM_CB_BeginIncreaseEdicts(void)
576 {
577         int i;
578         prvm_edict_t *ent;
579
580         // links don't survive the transition, so unlink everything
581         for (i = 0, ent = prog->edicts;i < prog->max_edicts;i++, ent++)
582         {
583                 if (!ent->priv.server->free)
584                         World_UnlinkEdict(prog->edicts + i);
585                 memset(&ent->priv.server->areagrid, 0, sizeof(ent->priv.server->areagrid));
586         }
587         World_Clear(&cl.world);
588 }
589
590 void CL_VM_CB_EndIncreaseEdicts(void)
591 {
592         int i;
593         prvm_edict_t *ent;
594
595         // link every entity except world
596         for (i = 1, ent = prog->edicts;i < prog->max_edicts;i++, ent++)
597                 if (!ent->priv.server->free)
598                         CL_LinkEdict(ent);
599 }
600
601 void CL_VM_CB_InitEdict(prvm_edict_t *e)
602 {
603         e->priv.server->move = false; // don't move on first frame
604 }
605
606 void CL_VM_CB_FreeEdict(prvm_edict_t *ed)
607 {
608         World_UnlinkEdict(ed);
609         memset(ed->fields.client, 0, sizeof(*ed->fields.client));
610 }
611
612 void CL_VM_CB_CountEdicts(void)
613 {
614         int             i;
615         prvm_edict_t    *ent;
616         int             active = 0, models = 0, solid = 0;
617
618         for (i=0 ; i<prog->num_edicts ; i++)
619         {
620                 ent = PRVM_EDICT_NUM(i);
621                 if (ent->priv.server->free)
622                         continue;
623                 active++;
624                 if (ent->fields.client->solid)
625                         solid++;
626                 if (ent->fields.client->model)
627                         models++;
628         }
629
630         Con_Printf("num_edicts:%3i\n", prog->num_edicts);
631         Con_Printf("active    :%3i\n", active);
632         Con_Printf("view      :%3i\n", models);
633         Con_Printf("touch     :%3i\n", solid);
634 }
635
636 qboolean CL_VM_CB_LoadEdict(prvm_edict_t *ent)
637 {
638         return true;
639 }
640
641 void Cmd_ClearCsqcFuncs (void);
642
643 void CL_VM_Init (void)
644 {
645         const char* csprogsfn;
646         unsigned char *csprogsdata;
647         fs_offset_t csprogsdatasize;
648         int csprogsdatacrc, requiredcrc;
649         int requiredsize;
650         prvm_eval_t *val;
651
652         // reset csqc_progcrc after reading it, so that changing servers doesn't
653         // expect csqc on the next server
654         requiredcrc = csqc_progcrc.integer;
655         requiredsize = csqc_progsize.integer;
656         Cvar_SetValueQuick(&csqc_progcrc, -1);
657         Cvar_SetValueQuick(&csqc_progsize, -1);
658
659         // if the server is not requesting a csprogs, then we're done here
660         if (requiredcrc < 0)
661                 return;
662
663         // see if the requested csprogs.dat file matches the requested crc
664         csprogsdatacrc = -1;
665         csprogsfn = va("dlcache/%s.%i.%i", csqc_progname.string, requiredsize, requiredcrc);
666         csprogsdata = FS_LoadFile(csprogsfn, tempmempool, true, &csprogsdatasize);
667         if (!csprogsdata)
668         {
669                 csprogsfn = csqc_progname.string;
670                 csprogsdata = FS_LoadFile(csprogsfn, tempmempool, true, &csprogsdatasize);
671         }
672         if (csprogsdata)
673         {
674                 csprogsdatacrc = CRC_Block(csprogsdata, csprogsdatasize);
675                 Mem_Free(csprogsdata);
676                 if (csprogsdatacrc != requiredcrc || csprogsdatasize != requiredsize)
677                 {
678                         if (cls.demoplayback)
679                         {
680                                 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);
681                                 return;
682                         }
683                         else
684                         {
685                                 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);
686                                 CL_Disconnect();
687                                 return;
688                         }
689                 }
690         }
691         else
692         {
693                 if (requiredcrc >= 0)
694                 {
695                         if (cls.demoplayback)
696                                 Con_Printf("CL_VM_Init: demo requires CSQC, but \"%s\" wasn't found\n", csqc_progname.string);
697                         else
698                                 Con_Printf("CL_VM_Init: server requires CSQC, but \"%s\" wasn't found\n", csqc_progname.string);
699                         CL_Disconnect();
700                 }
701                 return;
702         }
703
704         PRVM_Begin;
705         PRVM_InitProg(PRVM_CLIENTPROG);
706
707         // allocate the mempools
708         prog->progs_mempool = Mem_AllocPool(csqc_progname.string, 0, NULL);
709         prog->headercrc = CL_PROGHEADER_CRC;
710         prog->edictprivate_size = 0; // no private struct used
711         prog->name = CL_NAME;
712         prog->num_edicts = 1;
713         prog->max_edicts = 512;
714         prog->limit_edicts = CL_MAX_EDICTS;
715         prog->reserved_edicts = 0;
716         prog->edictprivate_size = sizeof(edict_engineprivate_t);
717         // TODO: add a shared extension string #define and add real support for csqc extension strings [12/5/2007 Black]
718         prog->extensionstring = vm_sv_extensions;
719         prog->builtins = vm_cl_builtins;
720         prog->numbuiltins = vm_cl_numbuiltins;
721         prog->begin_increase_edicts = CL_VM_CB_BeginIncreaseEdicts;
722         prog->end_increase_edicts = CL_VM_CB_EndIncreaseEdicts;
723         prog->init_edict = CL_VM_CB_InitEdict;
724         prog->free_edict = CL_VM_CB_FreeEdict;
725         prog->count_edicts = CL_VM_CB_CountEdicts;
726         prog->load_edict = CL_VM_CB_LoadEdict;
727         prog->init_cmd = VM_CL_Cmd_Init;
728         prog->reset_cmd = VM_CL_Cmd_Reset;
729         prog->error_cmd = CL_VM_Error;
730
731         PRVM_LoadProgs(csprogsfn, cl_numrequiredfunc, cl_required_func, 0, NULL, 0, NULL);
732
733         if (!prog->loaded)
734         {
735                 CL_VM_Error("CSQC %s ^2failed to load\n", csprogsfn);
736                 if(!sv.active)
737                         CL_Disconnect();
738                 return;
739         }
740
741         Con_Printf("CSQC %s ^5loaded (crc=%i, size=%i)\n", csprogsfn, csprogsdatacrc, (int)csprogsdatasize);
742
743         // check if OP_STATE animation is possible in this dat file
744         if (prog->fieldoffsets.nextthink >= 0 && prog->fieldoffsets.frame >= 0 && prog->fieldoffsets.think >= 0 && prog->globaloffsets.self >= 0)
745                 prog->flag |= PRVM_OP_STATE;
746
747         // set time
748         prog->globals.client->time = cl.time;
749
750         prog->globals.client->mapname = PRVM_SetEngineString(cl.worldmodel->name);
751         prog->globals.client->player_localentnum = cl.playerentity;
752
753         // set map description (use world entity 0)
754         val = PRVM_EDICTFIELDVALUE(prog->edicts, prog->fieldoffsets.message);
755         if(val)
756                 val->string = PRVM_SetEngineString(cl.levelname);
757
758         // call the prog init
759         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Init, "QC function CSQC_Init is missing");
760
761         PRVM_End;
762         cl.csqc_loaded = true;
763
764         cl.csqc_vidvars.drawcrosshair = false;
765         cl.csqc_vidvars.drawenginesbar = false;
766
767         // Update Coop and Deathmatch Globals (at this point the client knows them from ServerInfo)
768         CL_VM_UpdateCoopDeathmatchGlobals(cl.gametype);
769 }
770
771 void CL_VM_ShutDown (void)
772 {
773         Cmd_ClearCsqcFuncs();
774         Cvar_SetValueQuick(&csqc_progcrc, -1);
775         Cvar_SetValueQuick(&csqc_progsize, -1);
776         if(!cl.csqc_loaded)
777                 return;
778         CSQC_BEGIN
779                 prog->globals.client->time = cl.time;
780                 if (prog->funcoffsets.CSQC_Shutdown)
781                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Shutdown, "QC function CSQC_Shutdown is missing");
782                 PRVM_ResetProg();
783         CSQC_END
784         Con_Print("CSQC ^1unloaded\n");
785         cl.csqc_loaded = false;
786 }