Added support for assigning coop and deathmatch global float values to optional CSQC...
[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
7 //============================================================================
8 // Client prog handling
9 //[515]: omg !!! optimize it ! a lot of hacks here and there also :P
10
11 #define CSQC_RETURNVAL  prog->globals.generic[OFS_RETURN]
12 #define CSQC_BEGIN              csqc_tmpprog=prog;prog=0;PRVM_SetProg(PRVM_CLIENTPROG);
13 #define CSQC_END                prog=csqc_tmpprog;
14 static prvm_prog_t *csqc_tmpprog;
15
16 //[515]: these are required funcs
17 static char *cl_required_func[] =
18 {
19         "CSQC_Init",
20         "CSQC_InputEvent",
21         "CSQC_UpdateView",
22         "CSQC_ConsoleCommand",
23 };
24
25 static int cl_numrequiredfunc = sizeof(cl_required_func) / sizeof(char*);
26
27 void CL_VM_Error (const char *format, ...) DP_FUNC_PRINTF(1);
28 void CL_VM_Error (const char *format, ...)      //[515]: hope it will be never executed =)
29 {
30         char errorstring[4096];
31         va_list argptr;
32
33         va_start (argptr, format);
34         dpvsnprintf (errorstring, sizeof(errorstring), format, argptr);
35         va_end (argptr);
36 //      Con_Printf( "CL_VM_Error: %s\n", errorstring );
37
38         PRVM_Crash();
39         cl.csqc_loaded = false;
40
41         Cvar_SetValueQuick(&csqc_progcrc, -1);
42         Cvar_SetValueQuick(&csqc_progsize, -1);
43
44 //      Host_AbortCurrentFrame();       //[515]: hmmm... if server says it needs csqc then client MUST disconnect
45         Host_Error(va("CL_VM_Error: %s", errorstring));
46 }
47
48 //[515]: set globals before calling R_UpdateView, WEIRD CRAP
49 static void CSQC_SetGlobals (void)
50 {
51         prvm_eval_t *val;
52         CSQC_BEGIN
53                 prog->globals.client->time = cl.time;
54                 prog->globals.client->frametime = max(0, cl.time - cl.oldtime);
55                 prog->globals.client->servercommandframe = cls.servermovesequence;
56                 prog->globals.client->clientcommandframe = cl.movecmd[0].sequence;
57                 VectorCopy(cl.viewangles, prog->globals.client->input_angles);
58                 VectorCopy(cl.viewangles, cl.csqc_angles);
59                 prog->globals.client->input_buttons = cl.movecmd[0].buttons;
60                 VectorSet(prog->globals.client->input_movevalues, cl.movecmd[0].forwardmove, cl.movecmd[0].sidemove, cl.movecmd[0].upmove);
61                 //VectorCopy(cl.movement_origin, cl.csqc_origin);
62                 Matrix4x4_OriginFromMatrix(&cl.entities[cl.viewentity].render.matrix, cl.csqc_origin);
63                 if ((val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.view_angles)))
64                         VectorCopy(cl.viewangles, val->vector);
65                 prog->globals.client->maxclients = cl.maxclients;
66         CSQC_END
67 }
68
69 void CSQC_Predraw (prvm_edict_t *ed)
70 {
71         int b;
72         if(!ed->fields.client->predraw)
73                 return;
74         b = prog->globals.client->self;
75         prog->globals.client->self = PRVM_EDICT_TO_PROG(ed);
76         PRVM_ExecuteProgram(ed->fields.client->predraw, "CSQC_Predraw: NULL function\n");
77         prog->globals.client->self = b;
78 }
79
80 void CSQC_Think (prvm_edict_t *ed)
81 {
82         int b;
83         if(ed->fields.client->think)
84         if(ed->fields.client->nextthink && ed->fields.client->nextthink <= prog->globals.client->time)
85         {
86                 ed->fields.client->nextthink = 0;
87                 b = prog->globals.client->self;
88                 prog->globals.client->self = PRVM_EDICT_TO_PROG(ed);
89                 PRVM_ExecuteProgram(ed->fields.client->think, "CSQC_Think: NULL function\n");
90                 prog->globals.client->self = b;
91         }
92 }
93
94 extern cvar_t cl_noplayershadow;
95 qboolean CSQC_AddRenderEdict(prvm_edict_t *ed)
96 {
97         int renderflags;
98         float scale;
99         prvm_eval_t *val;
100         entity_t *e;
101         model_t *model;
102         matrix4x4_t tagmatrix, matrix2;
103
104         model = CL_GetModelFromEdict(ed);
105         if (!model)
106                 return false;
107
108         e = CL_NewTempEntity();
109         if (!e)
110                 return false;
111
112         e->render.model = model;
113         e->render.colormap = (int)ed->fields.client->colormap;
114         e->render.skinnum = (int)ed->fields.client->skin;
115         e->render.effects |= e->render.model->effects;
116         scale = 1;
117         renderflags = 0;
118         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.renderflags)) && val->_float)     renderflags = (int)val->_float;
119         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.alpha)) && val->_float)           e->render.alpha = val->_float;
120         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.scale)) && val->_float)           e->render.scale = scale = val->_float;
121         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.colormod)) && VectorLength2(val->vector)) VectorCopy(val->vector, e->render.colormod);
122         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.effects)) && val->_float) e->render.effects |= (int)val->_float;
123         if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.tag_entity)) && val->edict)
124         {
125                 int tagentity;
126                 int tagindex = 0;
127                 tagentity = val->edict;
128                 if((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.tag_index)) && val->_float)
129                         tagindex = (int)val->_float;
130                 // FIXME: calculate tag matrix
131                 Matrix4x4_CreateIdentity(&tagmatrix);
132         }
133         else
134                 Matrix4x4_CreateIdentity(&tagmatrix);
135
136         if (renderflags & RF_USEAXIS)
137         {
138                 vec3_t left;
139                 VectorNegate(prog->globals.client->v_right, left);
140                 Matrix4x4_FromVectors(&matrix2, prog->globals.client->v_forward, left, prog->globals.client->v_up, ed->fields.client->origin);
141                 Matrix4x4_Scale(&matrix2, scale, 1);
142         }
143         else
144         {
145                 vec3_t angles;
146                 VectorCopy(ed->fields.client->angles, angles);
147                 // if model is alias, reverse pitch direction
148                 if (e->render.model->type == mod_alias)
149                         angles[0] = -angles[0];
150
151                 // set up the render matrix
152                 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);
153         }
154
155         // set up the animation data
156         // self.frame is the interpolation target (new frame)
157         // self.frame1time is the animation base time for the interpolation target
158         // self.frame2 is the interpolation start (previous frame)
159         // self.frame2time is the animation base time for the interpolation start
160         e->render.frame1 = e->render.frame2 = ed->fields.client->frame;
161         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame2))) e->render.frame2 = val->_float;
162         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame1time))) e->render.frame2time = val->_float;
163         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.frame2time))) e->render.frame1time = val->_float;
164         if ((val = PRVM_EDICTFIELDVALUE(ed, prog->fieldoffsets.lerpfrac))) e->render.framelerp = val->_float;
165
166         // concat the matrices to make the entity relative to its tag
167         Matrix4x4_Concat(&e->render.matrix, &tagmatrix, &matrix2);
168         // make the other useful stuff
169         CL_UpdateRenderEntity(&e->render);
170
171         if(renderflags)
172         {
173                 if(renderflags & RF_VIEWMODEL)  e->render.flags |= RENDER_VIEWMODEL;
174                 if(renderflags & RF_EXTERNALMODEL)e->render.flags |= RENDER_EXTERIORMODEL;
175                 if(renderflags & RF_DEPTHHACK)  e->render.effects |= EF_NODEPTHTEST;
176                 if(renderflags & RF_ADDITIVE)           e->render.effects |= EF_ADDITIVE;
177         }
178
179         if ((e->render.colormap > 0 && e->render.colormap <= cl.maxclients) || e->render.colormap >= 1024)
180         {
181                 unsigned char *cbcolor;
182                 int palcol;
183                 if (e->render.colormap >= 1024)
184                         palcol = (unsigned char)(e->render.colormap-1024);
185                 else
186                         palcol = cl.scores[e->render.colormap-1].colors;
187
188                 cbcolor = (unsigned char *) (&palette_pantscolormap[palcol & 0xF]);
189                 e->render.colormap_pantscolor[0] = cbcolor[0] * (1.0f / 255.0f);
190                 e->render.colormap_pantscolor[1] = cbcolor[1] * (1.0f / 255.0f);
191                 e->render.colormap_pantscolor[2] = cbcolor[2] * (1.0f / 255.0f);
192                 cbcolor = (unsigned char *) (&palette_shirtcolormap[(palcol & 0xF0) >> 4]);
193                 e->render.colormap_shirtcolor[0] = cbcolor[0] * (1.0f / 255.0f);
194                 e->render.colormap_shirtcolor[1] = cbcolor[1] * (1.0f / 255.0f);
195                 e->render.colormap_shirtcolor[2] = cbcolor[2] * (1.0f / 255.0f);
196         }
197
198         // either fullbright or lit
199         if (!(e->render.effects & EF_FULLBRIGHT) && !r_fullbright.integer)
200                 e->render.flags |= RENDER_LIGHT;
201         // hide player shadow during intermission or nehahra movie
202         if (!(e->render.effects & (EF_NOSHADOW | EF_ADDITIVE | EF_NODEPTHTEST))
203          &&  (e->render.alpha >= 1)
204          && !(e->render.flags & RENDER_VIEWMODEL)
205          && (!(e->render.flags & RENDER_EXTERIORMODEL) || (!cl.intermission && cls.protocol != PROTOCOL_NEHAHRAMOVIE && !cl_noplayershadow.integer)))
206                 e->render.flags |= RENDER_SHADOW;
207         if (e->render.flags & RENDER_VIEWMODEL)
208                 e->render.flags |= RENDER_NOSELFSHADOW;
209
210         return true;
211 }
212
213 qboolean CL_VM_InputEvent (qboolean pressed, int key)
214 {
215         qboolean r;
216         if(!cl.csqc_loaded)
217                 return false;
218         CSQC_BEGIN
219                 if (!prog->funcoffsets.CSQC_InputEvent)
220                         r = false;
221                 else
222                 {
223                         prog->globals.client->time = cl.time;
224                         PRVM_G_FLOAT(OFS_PARM0) = pressed;
225                         PRVM_G_FLOAT(OFS_PARM1) = key;
226                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_InputEvent, "QC function CSQC_InputEvent is missing");
227                         r = CSQC_RETURNVAL;
228                 }
229         CSQC_END
230         return r;
231 }
232
233 qboolean CL_VM_UpdateView (void)
234 {
235 //      vec3_t oldangles;
236         if(!cl.csqc_loaded)
237                 return false;
238         CSQC_BEGIN
239                 //VectorCopy(cl.viewangles, oldangles);
240                 prog->globals.client->time = cl.time;
241                 CSQC_SetGlobals();
242                 // clear renderable entity and light lists to prevent crashes if the
243                 // CSQC_UpdateView function does not call R_ClearScene as it should
244                 r_refdef.numentities = 0;
245                 r_refdef.numlights = 0;
246                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_UpdateView, "QC function CSQC_UpdateView is missing");
247                 //VectorCopy(oldangles, cl.viewangles);
248         CSQC_END
249         return true;
250 }
251
252 extern sizebuf_t vm_tempstringsbuf;
253 qboolean CL_VM_ConsoleCommand (const char *cmd)
254 {
255         int restorevm_tempstringsbuf_cursize;
256         qboolean r = false;
257         if(!cl.csqc_loaded)
258                 return false;
259         CSQC_BEGIN
260         if (prog->funcoffsets.CSQC_ConsoleCommand)
261         {
262                 prog->globals.client->time = cl.time;
263                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
264                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(cmd);
265                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_ConsoleCommand, "QC function CSQC_ConsoleCommand is missing");
266                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
267                 r = CSQC_RETURNVAL;
268         }
269         CSQC_END
270         return r;
271 }
272
273 qboolean CL_VM_Parse_TempEntity (void)
274 {
275         int                     t;
276         qboolean        r = false;
277         if(!cl.csqc_loaded)
278                 return false;
279         CSQC_BEGIN
280         if(prog->funcoffsets.CSQC_Parse_TempEntity)
281         {
282                 t = msg_readcount;
283                 prog->globals.client->time = cl.time;
284                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_TempEntity, "QC function CSQC_Parse_TempEntity is missing");
285                 r = CSQC_RETURNVAL;
286                 if(!r)
287                 {
288                         msg_readcount = t;
289                         msg_badread = false;
290                 }
291         }
292         CSQC_END
293         return r;
294 }
295
296 void CL_VM_Parse_StuffCmd (const char *msg)
297 {
298         int restorevm_tempstringsbuf_cursize;
299         if(msg[0] == 'c')
300         if(msg[1] == 's')
301         if(msg[2] == 'q')
302         if(msg[3] == 'c')
303         {
304                 // if this is setting a csqc variable, deprotect csqc_progcrc
305                 // temporarily so that it can be set by the cvar command,
306                 // and then reprotect it afterwards
307                 int crcflags = csqc_progcrc.flags;
308                 int sizeflags = csqc_progcrc.flags;
309                 csqc_progcrc.flags &= ~CVAR_READONLY;
310                 csqc_progsize.flags &= ~CVAR_READONLY;
311                 Cmd_ExecuteString (msg, src_command);
312                 csqc_progcrc.flags = crcflags;
313                 csqc_progsize.flags = sizeflags;
314                 return;
315         }
316         if(!cl.csqc_loaded)
317         {
318                 Cbuf_AddText(msg);
319                 return;
320         }
321         CSQC_BEGIN
322         if(prog->funcoffsets.CSQC_Parse_StuffCmd)
323         {
324                 prog->globals.client->time = cl.time;
325                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
326                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
327                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_StuffCmd, "QC function CSQC_Parse_StuffCmd is missing");
328                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
329         }
330         else
331                 Cbuf_AddText(msg);
332         CSQC_END
333 }
334
335 static void CL_VM_Parse_Print (const char *msg)
336 {
337         int restorevm_tempstringsbuf_cursize;
338         prog->globals.client->time = cl.time;
339         restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
340         PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
341         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_Print, "QC function CSQC_Parse_Print is missing");
342         vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
343 }
344
345 void CSQC_AddPrintText (const char *msg)
346 {
347         size_t i;
348         if(!cl.csqc_loaded)
349         {
350                 Con_Print(msg);
351                 return;
352         }
353         CSQC_BEGIN
354         if(prog->funcoffsets.CSQC_Parse_Print)
355         {
356                 // FIXME: is this bugged?
357                 i = strlen(msg)-1;
358                 if(msg[i] != '\n' && msg[i] != '\r')
359                 {
360                         if(strlen(cl.csqc_printtextbuf)+i >= MAX_INPUTLINE)
361                         {
362                                 CL_VM_Parse_Print(cl.csqc_printtextbuf);
363                                 cl.csqc_printtextbuf[0] = 0;
364                         }
365                         else
366                                 strlcat(cl.csqc_printtextbuf, msg, MAX_INPUTLINE);
367                         return;
368                 }
369                 strlcat(cl.csqc_printtextbuf, msg, MAX_INPUTLINE);
370                 CL_VM_Parse_Print(cl.csqc_printtextbuf);
371                 cl.csqc_printtextbuf[0] = 0;
372         }
373         else
374                 Con_Print(msg);
375         CSQC_END
376 }
377
378 void CL_VM_Parse_CenterPrint (const char *msg)
379 {
380         int restorevm_tempstringsbuf_cursize;
381         if(!cl.csqc_loaded)
382         {
383                 SCR_CenterPrint((char*)msg);
384                 return;
385         }
386         CSQC_BEGIN
387         if(prog->funcoffsets.CSQC_Parse_CenterPrint)
388         {
389                 prog->globals.client->time = cl.time;
390                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
391                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
392                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Parse_CenterPrint, "QC function CSQC_Parse_CenterPrint is missing");
393                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
394         }
395         else
396                 SCR_CenterPrint((char*)msg);
397         CSQC_END
398 }
399
400 void CL_VM_UpdateIntermissionState (int intermission)
401 {
402         prvm_eval_t *val;
403         if(cl.csqc_loaded)
404         {
405                 CSQC_BEGIN
406                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.intermission);
407                 if(val)
408                         val->_float = intermission;
409                 CSQC_END
410         }
411 }
412 void CL_VM_UpdateCoopDeathmatchGlobals (int gametype)
413 {
414         // Avoid global names for clean(er) coding
415         int localcoop;
416         int localdeathmatch;
417
418         prvm_eval_t *val;
419         if(cl.csqc_loaded)
420         {
421                 if(gametype == GAME_COOP)
422                 {
423                         localcoop = 1;
424                         localdeathmatch = 0;
425                 }
426                 else
427                 if(gametype == GAME_DEATHMATCH)
428                 {
429                         localcoop = 0;
430                         localdeathmatch = 1;
431                 }
432                 else
433                 {
434                         // How did the ServerInfo send an unknown gametype?
435                         // Better just assign the globals as 0...
436                         localcoop = 0;
437                         localdeathmatch = 0;
438                 }
439                 CSQC_BEGIN
440                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.coop);
441                 if(val)
442                         val->_float = localcoop;
443                 val = PRVM_GLOBALFIELDVALUE(prog->globaloffsets.deathmatch);
444                 if(val)
445                         val->_float = localdeathmatch;
446                 CSQC_END
447         }
448 }
449
450 float CL_VM_Event (float event)         //[515]: needed ? I'd say "YES", but don't know for what :D
451 {
452         float r = 0;
453         if(!cl.csqc_loaded)
454                 return 0;
455         CSQC_BEGIN
456         if(prog->funcoffsets.CSQC_Event)
457         {
458                 prog->globals.client->time = cl.time;
459                 PRVM_G_FLOAT(OFS_PARM0) = event;
460                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Event, "QC function CSQC_Event is missing");
461                 r = CSQC_RETURNVAL;
462         }
463         CSQC_END
464         return r;
465 }
466
467 void CSQC_ReadEntities (void)
468 {
469         unsigned short entnum, oldself, realentnum;
470         if(!cl.csqc_loaded)
471         {
472                 Host_Error ("CSQC_ReadEntities: CSQC is not loaded");
473                 return;
474         }
475
476         CSQC_BEGIN
477                 prog->globals.client->time = cl.time;
478                 oldself = prog->globals.client->self;
479                 while(1)
480                 {
481                         entnum = MSG_ReadShort();
482                         if(!entnum || msg_badread)
483                                 return;
484                         realentnum = entnum & 0x7FFF;
485                         prog->globals.client->self = cl.csqc_server2csqcentitynumber[realentnum];
486                         if(entnum & 0x8000)
487                         {
488                                 if(prog->globals.client->self)
489                                 {
490                                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Ent_Remove, "QC function CSQC_Ent_Remove is missing");
491                                         cl.csqc_server2csqcentitynumber[realentnum] = 0;
492                                 }
493                                 else
494                                         Con_Printf("Smth bad happens in csqc...\n");    //[515]: never happens ?
495                         }
496                         else
497                         {
498                                 if(!prog->globals.client->self)
499                                 {
500                                         prvm_edict_t    *ed;
501                                         ed = PRVM_ED_Alloc();
502                                         ed->fields.client->entnum = realentnum;
503                                         prog->globals.client->self = cl.csqc_server2csqcentitynumber[realentnum] = PRVM_EDICT_TO_PROG(ed);
504                                         PRVM_G_FLOAT(OFS_PARM0) = 1;
505                                 }
506                                 else
507                                         PRVM_G_FLOAT(OFS_PARM0) = 0;
508                                 PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Ent_Update, "QC function CSQC_Ent_Update is missing");
509                         }
510                 }
511                 prog->globals.client->self = oldself;
512         CSQC_END
513 }
514
515 void CL_VM_CB_BeginIncreaseEdicts(void)
516 {
517         int i;
518         prvm_edict_t *ent;
519
520         // links don't survive the transition, so unlink everything
521         for (i = 0, ent = prog->edicts;i < prog->max_edicts;i++, ent++)
522         {
523                 if (!ent->priv.server->free)
524                         World_UnlinkEdict(prog->edicts + i);
525                 memset(&ent->priv.server->areagrid, 0, sizeof(ent->priv.server->areagrid));
526         }
527         World_Clear(&cl.world);
528 }
529
530 void CL_VM_CB_EndIncreaseEdicts(void)
531 {
532         int i;
533         prvm_edict_t *ent;
534
535         // link every entity except world
536         for (i = 1, ent = prog->edicts;i < prog->max_edicts;i++, ent++)
537                 if (!ent->priv.server->free)
538                         CL_LinkEdict(ent);
539 }
540
541 void CL_VM_CB_InitEdict(prvm_edict_t *e)
542 {
543         e->priv.server->move = false; // don't move on first frame
544 }
545
546 void CL_VM_CB_FreeEdict(prvm_edict_t *ed)
547 {
548         World_UnlinkEdict(ed);
549         memset(ed->fields.client, 0, sizeof(*ed->fields.client));
550 }
551
552 void CL_VM_CB_CountEdicts(void)
553 {
554         int             i;
555         prvm_edict_t    *ent;
556         int             active = 0, models = 0, solid = 0;
557
558         for (i=0 ; i<prog->num_edicts ; i++)
559         {
560                 ent = PRVM_EDICT_NUM(i);
561                 if (ent->priv.server->free)
562                         continue;
563                 active++;
564                 if (ent->fields.client->solid)
565                         solid++;
566                 if (ent->fields.client->model)
567                         models++;
568         }
569
570         Con_Printf("num_edicts:%3i\n", prog->num_edicts);
571         Con_Printf("active    :%3i\n", active);
572         Con_Printf("view      :%3i\n", models);
573         Con_Printf("touch     :%3i\n", solid);
574 }
575
576 qboolean CL_VM_CB_LoadEdict(prvm_edict_t *ent)
577 {
578         return true;
579 }
580
581 void Cmd_ClearCsqcFuncs (void);
582
583 void CL_VM_Init (void)
584 {
585         unsigned char *csprogsdata;
586         fs_offset_t csprogsdatasize;
587         int csprogsdatacrc, requiredcrc;
588         int requiredsize;
589         prvm_eval_t *val;
590
591         // reset csqc_progcrc after reading it, so that changing servers doesn't
592         // expect csqc on the next server
593         requiredcrc = csqc_progcrc.integer;
594         requiredsize = csqc_progsize.integer;
595         Cvar_SetValueQuick(&csqc_progcrc, -1);
596         Cvar_SetValueQuick(&csqc_progsize, -1);
597
598         // if the server is not requesting a csprogs, then we're done here
599         if (requiredcrc < 0)
600                 return;
601
602         // see if the requested csprogs.dat file matches the requested crc
603         csprogsdatacrc = -1;
604         csprogsdata = FS_LoadFile(va("dlcache/%s.%i.%i", csqc_progname.string, requiredsize, requiredcrc), tempmempool, true, &csprogsdatasize);
605         if (!csprogsdata)
606                 csprogsdata = FS_LoadFile(csqc_progname.string, tempmempool, true, &csprogsdatasize);
607         if (csprogsdata)
608         {
609                 csprogsdatacrc = CRC_Block(csprogsdata, csprogsdatasize);
610                 Mem_Free(csprogsdata);
611                 if (csprogsdatacrc != requiredcrc || csprogsdatasize != requiredsize)
612                 {
613                         if (cls.demoplayback)
614                         {
615                                 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);
616                                 return;
617                         }
618                         else
619                         {
620                                 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);
621                                 CL_Disconnect();
622                                 return;
623                         }
624                 }
625         }
626         else
627         {
628                 if (requiredcrc >= 0)
629                 {
630                         if (cls.demoplayback)
631                                 Con_Printf("CL_VM_Init: demo requires CSQC, but \"%s\" wasn't found\n", csqc_progname.string);
632                         else
633                                 Con_Printf("CL_VM_Init: server requires CSQC, but \"%s\" wasn't found\n", csqc_progname.string);
634                         CL_Disconnect();
635                 }
636                 return;
637         }
638
639         PRVM_Begin;
640         PRVM_InitProg(PRVM_CLIENTPROG);
641
642         // allocate the mempools
643         prog->progs_mempool = Mem_AllocPool(csqc_progname.string, 0, NULL);
644         prog->headercrc = CL_PROGHEADER_CRC;
645         prog->edictprivate_size = 0; // no private struct used
646         prog->name = CL_NAME;
647         prog->num_edicts = 1;
648         prog->max_edicts = 512;
649         prog->limit_edicts = CL_MAX_EDICTS;
650         prog->reserved_edicts = 0;
651         prog->edictprivate_size = sizeof(edict_engineprivate_t);
652         prog->extensionstring = vm_sv_extensions;
653         prog->builtins = vm_cl_builtins;
654         prog->numbuiltins = vm_cl_numbuiltins;
655         prog->begin_increase_edicts = CL_VM_CB_BeginIncreaseEdicts;
656         prog->end_increase_edicts = CL_VM_CB_EndIncreaseEdicts;
657         prog->init_edict = CL_VM_CB_InitEdict;
658         prog->free_edict = CL_VM_CB_FreeEdict;
659         prog->count_edicts = CL_VM_CB_CountEdicts;
660         prog->load_edict = CL_VM_CB_LoadEdict;
661         prog->init_cmd = VM_CL_Cmd_Init;
662         prog->reset_cmd = VM_CL_Cmd_Reset;
663         prog->error_cmd = CL_VM_Error;
664
665         PRVM_LoadProgs(csqc_progname.string, cl_numrequiredfunc, cl_required_func, 0, NULL, 0, NULL);
666
667         if (!prog->loaded)
668         {
669                 CL_VM_Error("CSQC ^2failed to load\n");
670                 if(!sv.active)
671                         CL_Disconnect();
672                 return;
673         }
674
675         Con_Printf("CSQC ^5loaded (crc=%i, size=%i)\n", csprogsdatacrc, (int)csprogsdatasize);
676
677         // check if OP_STATE animation is possible in this dat file
678         if (prog->fieldoffsets.nextthink >= 0 && prog->fieldoffsets.frame >= 0 && prog->fieldoffsets.think >= 0 && prog->globaloffsets.self >= 0)
679                 prog->flag |= PRVM_OP_STATE;
680
681         // set time
682         prog->globals.client->time = cl.time;
683
684         prog->globals.client->mapname = PRVM_SetEngineString(cl.worldmodel->name);
685         prog->globals.client->player_localentnum = cl.playerentity;
686
687         // set map description (use world entity 0)
688         val = PRVM_EDICTFIELDVALUE(prog->edicts, prog->fieldoffsets.message);
689         if(val)
690                 val->string = PRVM_SetEngineString(cl.levelname);
691
692         // call the prog init
693         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Init, "QC function CSQC_Init is missing");
694
695         PRVM_End;
696         cl.csqc_loaded = true;
697
698         cl.csqc_vidvars.drawcrosshair = false;
699         cl.csqc_vidvars.drawenginesbar = false;
700
701         // Update Coop and Deathmatch Globals (at this point the client knows them from ServerInfo)
702         CL_VM_UpdateCoopDeathmatchGlobals(cl.gametype);
703 }
704
705 void CL_VM_ShutDown (void)
706 {
707         Cmd_ClearCsqcFuncs();
708         Cvar_SetValueQuick(&csqc_progcrc, -1);
709         Cvar_SetValueQuick(&csqc_progsize, -1);
710         if(!cl.csqc_loaded)
711                 return;
712         CSQC_BEGIN
713                 prog->globals.client->time = cl.time;
714                 if (prog->funcoffsets.CSQC_Shutdown)
715                         PRVM_ExecuteProgram(prog->funcoffsets.CSQC_Shutdown, "QC function CSQC_Shutdown is missing");
716                 PRVM_ResetProg();
717         CSQC_END
718         Con_Print("CSQC ^1unloaded\n");
719         cl.csqc_loaded = false;
720 }