redesigned tempstring system, now uses a fixed size buffer based on the prvm_tempstri...
[xonotic/darkplaces.git] / csprogs.c
1 #include "quakedef.h"
2 #include "progsvm.h"
3 #include "clprogdefs.h"
4 #include "csprogs.h"
5
6 //============================================================================
7 // Client prog handling
8 //[515]: omg !!! optimize it ! a lot of hacks here and there also :P
9
10 #define CSQC_RETURNVAL  prog->globals.generic[OFS_RETURN]
11 #define CSQC_BEGIN              csqc_tmpprog=prog;prog=0;PRVM_SetProg(PRVM_CLIENTPROG);
12 #define CSQC_END                prog=csqc_tmpprog;
13 static prvm_prog_t *csqc_tmpprog;
14
15 //[515]: these are required funcs
16 #define CL_F_INIT                               "CSQC_Init"
17 #define CL_F_INPUTEVENT                 "CSQC_InputEvent"
18 #define CL_F_UPDATEVIEW                 "CSQC_UpdateView"
19 #define CL_F_CONSOLECOMMAND             "CSQC_ConsoleCommand"
20 #define CL_F_SHUTDOWN                   "CSQC_Shutdown"
21
22 //[515]: these are optional
23 #define CL_F_PARSE_TEMPENTITY   "CSQC_Parse_TempEntity" //[515]: very helpfull when you want to create your own particles/decals/etc for effects that allready exist
24 #define CL_F_PARSE_STUFFCMD             "CSQC_Parse_StuffCmd"
25 #define CL_F_PARSE_PRINT                "CSQC_Parse_Print"
26 #define CL_F_PARSE_CENTERPRINT  "CSQC_Parse_CenterPrint"
27 #define CL_F_ENT_UPDATE                 "CSQC_Ent_Update"
28 #define CL_F_ENT_REMOVE                 "CSQC_Ent_Remove"
29 #define CL_F_EVENT                              "CSQC_Event"    //[515]: engine call this for its own needs
30                                                                                                 //so csqc can do some things according to what engine it's running on
31                                                                                                 //example: to say about edicts increase, whatever...
32
33 #define CSQC_PRINTBUFFERLEN             8192    //[515]: enough ?
34
35 static char *cl_required_func[] =
36 {
37         CL_F_INIT,
38         CL_F_INPUTEVENT,
39         CL_F_UPDATEVIEW,
40         CL_F_CONSOLECOMMAND,
41         CL_F_SHUTDOWN
42 };
43
44 static int cl_numrequiredfunc = sizeof(cl_required_func) / sizeof(char*);
45
46 static char                             *csqc_printtextbuf = NULL;
47 static unsigned short   *csqc_sv2csqcents;      //[515]: server entities numbers on client side. FIXME : make pointers instead of numbers ?
48
49 static mfunction_t      *CSQC_Parse_TempEntity;
50 static mfunction_t      *CSQC_Parse_StuffCmd;
51 static mfunction_t      *CSQC_Parse_Print;
52 static mfunction_t      *CSQC_Parse_CenterPrint;
53 static mfunction_t      *CSQC_Ent_Update;
54 static mfunction_t      *CSQC_Ent_Remove;
55 static mfunction_t      *CSQC_Event;
56
57 static int csqc_fieldoff_alpha;
58 static int csqc_fieldoff_colormod;
59 static int csqc_fieldoff_effects;
60 int csqc_fieldoff_scale;
61 int csqc_fieldoff_renderflags;
62 int csqc_fieldoff_tag_entity;
63 int csqc_fieldoff_tag_index;
64 int csqc_fieldoff_dphitcontentsmask;
65
66 qboolean csqc_loaded = false;
67
68 vec3_t csqc_origin, csqc_angles;
69 static double csqc_frametime = 0;
70 int csqc_buttons;
71
72 static mempool_t *csqc_mempool;
73
74 static void CL_VM_FindEdictFieldOffsets (void)
75 {
76         csqc_fieldoff_alpha                     = PRVM_ED_FindFieldOffset("alpha");
77         csqc_fieldoff_scale                     = PRVM_ED_FindFieldOffset("scale");
78         csqc_fieldoff_colormod          = PRVM_ED_FindFieldOffset("colormod");
79         csqc_fieldoff_renderflags       = PRVM_ED_FindFieldOffset("renderflags");
80         csqc_fieldoff_effects           = PRVM_ED_FindFieldOffset("effects");
81         csqc_fieldoff_tag_entity        = PRVM_ED_FindFieldOffset("tag_entity");
82         csqc_fieldoff_tag_index         = PRVM_ED_FindFieldOffset("tag_index");
83
84         CSQC_Parse_TempEntity           = PRVM_ED_FindFunction (CL_F_PARSE_TEMPENTITY);
85         CSQC_Parse_StuffCmd                     = PRVM_ED_FindFunction (CL_F_PARSE_STUFFCMD);
86         CSQC_Parse_Print                        = PRVM_ED_FindFunction (CL_F_PARSE_PRINT);
87         CSQC_Parse_CenterPrint          = PRVM_ED_FindFunction (CL_F_PARSE_CENTERPRINT);
88         CSQC_Ent_Update                         = PRVM_ED_FindFunction (CL_F_ENT_UPDATE);
89         CSQC_Ent_Remove                         = PRVM_ED_FindFunction (CL_F_ENT_REMOVE);
90         CSQC_Event                                      = PRVM_ED_FindFunction (CL_F_EVENT);
91
92         if(CSQC_Parse_Print)
93         {
94                 csqc_printtextbuf = (char *)Mem_Alloc(csqc_mempool, CSQC_PRINTBUFFERLEN);
95                 csqc_printtextbuf[0] = 0;
96         }
97 }
98
99 void CL_VM_Error (const char *format, ...) DP_FUNC_PRINTF(1);
100 void CL_VM_Error (const char *format, ...)      //[515]: hope it will be never executed =)
101 {
102         char errorstring[4096];
103         va_list argptr;
104
105         va_start (argptr, format);
106         dpvsnprintf (errorstring, sizeof(errorstring), format, argptr);
107         va_end (argptr);
108 //      Con_Printf( "CL_VM_Error: %s\n", errorstring );
109
110         PRVM_Crash();
111         csqc_loaded = false;
112         Mem_FreePool(&csqc_mempool);
113
114         Cvar_SetValueQuick(&csqc_progcrc, -1);
115         Cvar_SetValueQuick(&csqc_progsize, -1);
116
117 //      Host_AbortCurrentFrame();       //[515]: hmmm... if server says it needs csqc then client MUST disconnect
118         Host_Error(va("CL_VM_Error: %s", errorstring));
119 }
120
121 model_t *CSQC_GetModelByIndex(int modelindex)
122 {
123         if(!modelindex)
124                 return NULL;
125         if (modelindex < 0)
126         {
127                 modelindex = -(modelindex+1);
128                 if (modelindex < MAX_MODELS)
129                         return cl.csqc_model_precache[modelindex];
130         }
131         else
132         {
133                 if(modelindex < MAX_MODELS)
134                         return cl.model_precache[modelindex];
135         }
136         return NULL;
137 }
138
139 model_t *CSQC_GetModelFromEntity(prvm_edict_t *ed)
140 {
141         if (!ed || ed->priv.server->free)
142                 return NULL;
143         return CSQC_GetModelByIndex((int)ed->fields.client->modelindex);
144 }
145
146 //[515]: set globals before calling R_UpdateView, WEIRD CRAP
147 static void CSQC_SetGlobals (void)
148 {
149         //extern cvar_t sv_accelerate, sv_friction, sv_gravity, sv_stopspeed, sv_maxspeed;
150
151         CSQC_BEGIN
152                 *prog->time = cl.time;
153                 prog->globals.client->frametime = cl.time - csqc_frametime;
154                 csqc_frametime = cl.time;
155                 prog->globals.client->servercommandframe = cl.servermovesequence;
156                 prog->globals.client->clientcommandframe = cl.movemessages;
157                 VectorCopy(cl.viewangles, prog->globals.client->input_angles);
158                 VectorCopy(cl.viewangles, csqc_angles);
159                 prog->globals.client->input_buttons = csqc_buttons;
160                 VectorSet(prog->globals.client->input_movevalues, cl.cmd.forwardmove, cl.cmd.sidemove, cl.cmd.upmove);
161                 //VectorCopy(cl.movement_origin, csqc_origin);
162                 Matrix4x4_OriginFromMatrix(&cl.entities[cl.viewentity].render.matrix, csqc_origin);
163                 VectorCopy(csqc_origin, prog->globals.client->pmove_org);
164                 prog->globals.client->maxclients = cl.maxclients;
165                 //VectorCopy(cl.movement_velocity, prog->globals.client->pmove_vel);
166                 VectorCopy(cl.velocity, prog->globals.client->pmove_vel);
167         CSQC_END
168 }
169
170 void CSQC_Predraw (prvm_edict_t *ed)
171 {
172         int b;
173         if(!ed->fields.client->predraw)
174                 return;
175         b = prog->globals.client->self;
176         prog->globals.client->self = PRVM_EDICT_TO_PROG(ed);
177         PRVM_ExecuteProgram(ed->fields.client->predraw, "CSQC_Predraw: NULL function\n");
178         prog->globals.client->self = b;
179 }
180
181 void CSQC_Think (prvm_edict_t *ed)
182 {
183         int b;
184         if(ed->fields.client->think)
185         if(ed->fields.client->nextthink && ed->fields.client->nextthink <= *prog->time)
186         {
187                 ed->fields.client->nextthink = 0;
188                 b = prog->globals.client->self;
189                 prog->globals.client->self = PRVM_EDICT_TO_PROG(ed);
190                 PRVM_ExecuteProgram(ed->fields.client->think, "CSQC_Think: NULL function\n");
191                 prog->globals.client->self = b;
192         }
193 }
194
195 extern cvar_t cl_noplayershadow;
196 qboolean CSQC_AddRenderEdict(prvm_edict_t *ed)
197 {
198         int i;
199         float scale;
200         prvm_eval_t *val;
201         entity_t *e;
202         model_t *model;
203         matrix4x4_t tagmatrix, matrix2;
204
205         model = CSQC_GetModelFromEntity(ed);
206         if (!model)
207                 return false;
208
209         e = CL_NewTempEntity();
210         if (!e)
211                 return false;
212
213         e->render.model = model;
214         e->render.colormap = (int)ed->fields.client->colormap;
215         e->render.frame = (int)ed->fields.client->frame;
216         e->render.skinnum = (int)ed->fields.client->skin;
217         e->render.effects |= e->render.model->flags2 & (EF_FULLBRIGHT | EF_ADDITIVE);
218         scale = 1;
219
220         if((val = PRVM_GETEDICTFIELDVALUE(ed, csqc_fieldoff_alpha)) && val->_float)             e->render.alpha = val->_float;
221         if((val = PRVM_GETEDICTFIELDVALUE(ed, csqc_fieldoff_scale)) && val->_float)             e->render.scale = scale = val->_float;
222         if((val = PRVM_GETEDICTFIELDVALUE(ed, csqc_fieldoff_colormod)) && VectorLength2(val->vector))   VectorCopy(val->vector, e->render.colormod);
223         if((val = PRVM_GETEDICTFIELDVALUE(ed, csqc_fieldoff_effects)) && val->_float)   e->render.effects = (int)val->_float;
224         if((val = PRVM_GETEDICTFIELDVALUE(ed, csqc_fieldoff_tag_entity)) && val->edict)
225         {
226                 int tagentity;
227                 int tagindex = 0;
228                 tagentity = val->edict;
229                 if((val = PRVM_GETEDICTFIELDVALUE(ed, csqc_fieldoff_tag_index)) && val->_float)
230                         tagindex = (int)val->_float;
231                 // FIXME: calculate tag matrix
232                 Matrix4x4_CreateIdentity(&tagmatrix);
233         }
234         else
235                 Matrix4x4_CreateIdentity(&tagmatrix);
236
237         if(i & RF_USEAXIS)      //FIXME!!!
238         {
239                 vec3_t left;
240                 VectorNegate(prog->globals.client->v_right, left);
241                 Matrix4x4_FromVectors(&matrix2, prog->globals.client->v_forward, left, prog->globals.client->v_up, ed->fields.client->origin);
242         }
243         else
244         {
245                 vec3_t angles;
246                 VectorCopy(ed->fields.client->angles, angles);
247                 // if model is alias, reverse pitch direction
248                 if (e->render.model->type == mod_alias)
249                         angles[0] = -angles[0];
250
251                 // set up the render matrix
252                 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);
253         }
254
255         // FIXME: csqc has frame1/frame2/frame1time/frame2time/lerpfrac but this implementation's cl_entvars_t lacks those fields
256         e->render.frame1 = e->render.frame = ed->fields.client->frame;
257         e->render.frame1time = e->render.frame2time = 0;
258         e->render.framelerp = 0;
259
260         // concat the matrices to make the entity relative to its tag
261         Matrix4x4_Concat(&e->render.matrix, &tagmatrix, &matrix2);
262         // make the other useful stuff
263         CL_UpdateRenderEntity(&e->render);
264
265         i = 0;
266         if((val = PRVM_GETEDICTFIELDVALUE(ed, csqc_fieldoff_renderflags)) && val->_float)
267         {
268                 i = (int)val->_float;
269                 if(i & RF_VIEWMODEL)    e->render.flags |= RENDER_VIEWMODEL;
270                 if(i & RF_EXTERNALMODEL)e->render.flags |= RENDER_EXTERIORMODEL;
271                 if(i & RF_DEPTHHACK)    e->render.effects |= EF_NODEPTHTEST;
272                 if(i & RF_ADDITIVE)             e->render.effects |= EF_ADDITIVE;
273         }
274
275         // transparent stuff can't be lit during the opaque stage
276         if (e->render.effects & (EF_ADDITIVE | EF_NODEPTHTEST) || e->render.alpha < 1)
277                 e->render.flags |= RENDER_TRANSPARENT;
278         // double sided rendering mode causes backfaces to be visible
279         // (mostly useful on transparent stuff)
280         if (e->render.effects & EF_DOUBLESIDED)
281                 e->render.flags |= RENDER_NOCULLFACE;
282         // either fullbright or lit
283         if (!(e->render.effects & EF_FULLBRIGHT) && !r_fullbright.integer)
284                 e->render.flags |= RENDER_LIGHT;
285         // hide player shadow during intermission or nehahra movie
286         if (!(e->render.effects & EF_NOSHADOW)
287          && !(e->render.flags & (RENDER_VIEWMODEL | RENDER_TRANSPARENT))
288          && (!(e->render.flags & RENDER_EXTERIORMODEL) || (!cl.intermission && cls.protocol != PROTOCOL_NEHAHRAMOVIE && !cl_noplayershadow.integer)))
289                 e->render.flags |= RENDER_SHADOW;
290
291         return true;
292 }
293
294 qboolean CL_VM_InputEvent (qboolean pressed, int key)
295 {
296         qboolean r;
297         if(!csqc_loaded)
298                 return false;
299         CSQC_BEGIN
300                 *prog->time = cl.time;
301                 PRVM_G_FLOAT(OFS_PARM0) = pressed;
302                 PRVM_G_FLOAT(OFS_PARM1) = key;
303                 PRVM_ExecuteProgram (prog->globals.client->CSQC_InputEvent, CL_F_INPUTEVENT);
304                 r = CSQC_RETURNVAL;
305         CSQC_END
306         return r;
307 }
308
309 qboolean CL_VM_UpdateView (void)
310 {
311 //      vec3_t oldangles;
312         if(!csqc_loaded)
313                 return false;
314         CSQC_BEGIN
315                 //VectorCopy(cl.viewangles, oldangles);
316                 *prog->time = cl.time;
317                 CSQC_SetGlobals();
318                 r_refdef.numentities = 0;
319                 PRVM_ExecuteProgram (prog->globals.client->CSQC_UpdateView, CL_F_UPDATEVIEW);
320                 //VectorCopy(oldangles, cl.viewangles);
321         CSQC_END
322         return true;
323 }
324
325 extern sizebuf_t vm_tempstringsbuf;
326 qboolean CL_VM_ConsoleCommand (const char *cmd)
327 {
328         int restorevm_tempstringsbuf_cursize;
329         qboolean r;
330         if(!csqc_loaded)
331                 return false;
332         CSQC_BEGIN
333                 *prog->time = cl.time;
334                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
335                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(cmd);
336                 PRVM_ExecuteProgram (prog->globals.client->CSQC_ConsoleCommand, CL_F_CONSOLECOMMAND);
337                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
338                 r = CSQC_RETURNVAL;
339         CSQC_END
340         return r;
341 }
342
343 qboolean CL_VM_Parse_TempEntity (void)
344 {
345         int                     t;
346         qboolean        r;
347         if(!csqc_loaded || !CSQC_Parse_TempEntity)
348                 return false;
349         t = msg_readcount;
350         CSQC_BEGIN
351                 *prog->time = cl.time;
352                 PRVM_ExecuteProgram ((func_t)(CSQC_Parse_TempEntity - prog->functions), CL_F_PARSE_TEMPENTITY);
353                 r = CSQC_RETURNVAL;
354         CSQC_END
355         if(!r)
356         {
357                 msg_readcount = t;
358                 msg_badread = false;
359         }
360         return r;
361 }
362
363 void CL_VM_Parse_StuffCmd (const char *msg)
364 {
365         int restorevm_tempstringsbuf_cursize;
366         if(msg[0] == 'c')
367         if(msg[1] == 's')
368         if(msg[2] == 'q')
369         if(msg[3] == 'c')
370         {
371                 // if this is setting a csqc variable, deprotect csqc_progcrc
372                 // temporarily so that it can be set by the cvar command,
373                 // and then reprotect it afterwards
374                 int crcflags = csqc_progcrc.flags;
375                 int sizeflags = csqc_progcrc.flags;
376                 csqc_progcrc.flags &= ~CVAR_READONLY;
377                 csqc_progsize.flags &= ~CVAR_READONLY;
378                 Cmd_ExecuteString (msg, src_command);
379                 csqc_progcrc.flags = crcflags;
380                 csqc_progsize.flags = sizeflags;
381                 return;
382         }
383         if(!csqc_loaded || !CSQC_Parse_StuffCmd)
384         {
385                 Cbuf_AddText(msg);
386                 return;
387         }
388         CSQC_BEGIN
389                 *prog->time = cl.time;
390                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
391                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
392                 PRVM_ExecuteProgram ((func_t)(CSQC_Parse_StuffCmd - prog->functions), CL_F_PARSE_STUFFCMD);
393                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
394         CSQC_END
395 }
396
397 static void CL_VM_Parse_Print (const char *msg)
398 {
399         int restorevm_tempstringsbuf_cursize;
400         CSQC_BEGIN
401                 *prog->time = cl.time;
402                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
403                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
404                 PRVM_ExecuteProgram ((func_t)(CSQC_Parse_Print - prog->functions), CL_F_PARSE_PRINT);
405                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
406         CSQC_END
407 }
408
409 void CSQC_AddPrintText (const char *msg)
410 {
411         size_t i;
412         if(!csqc_loaded || !CSQC_Parse_Print)
413         {
414                 Con_Print(msg);
415                 return;
416         }
417         // FIXME: is this bugged?
418         i = strlen(msg)-1;
419         if(msg[i] != '\n' && msg[i] != '\r')
420         {
421                 if(strlen(csqc_printtextbuf)+i >= CSQC_PRINTBUFFERLEN)
422                 {
423                         CL_VM_Parse_Print(csqc_printtextbuf);
424                         csqc_printtextbuf[0] = 0;
425                 }
426                 else
427                         strlcat(csqc_printtextbuf, msg, CSQC_PRINTBUFFERLEN);
428                 return;
429         }
430         strlcat(csqc_printtextbuf, msg, CSQC_PRINTBUFFERLEN);
431         CL_VM_Parse_Print(csqc_printtextbuf);
432         csqc_printtextbuf[0] = 0;
433 }
434
435 void CL_VM_Parse_CenterPrint (const char *msg)
436 {
437         int restorevm_tempstringsbuf_cursize;
438         if(!csqc_loaded || !CSQC_Parse_CenterPrint)
439         {
440                 SCR_CenterPrint((char*)msg);
441                 return;
442         }
443         CSQC_BEGIN
444                 *prog->time = cl.time;
445                 restorevm_tempstringsbuf_cursize = vm_tempstringsbuf.cursize;
446                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(msg);
447                 PRVM_ExecuteProgram ((func_t)(CSQC_Parse_CenterPrint - prog->functions), CL_F_PARSE_CENTERPRINT);
448                 vm_tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
449         CSQC_END
450 }
451
452 float CL_VM_Event (float event)         //[515]: needed ? I'd say "YES", but don't know for what :D
453 {
454         float r;
455         if(!csqc_loaded || !CSQC_Event)
456                 return 0;
457         CSQC_BEGIN
458                 *prog->time = cl.time;
459                 PRVM_G_FLOAT(OFS_PARM0) = event;
460                 PRVM_ExecuteProgram ((func_t)(CSQC_Event - prog->functions), CL_F_EVENT);
461                 r = CSQC_RETURNVAL;
462         CSQC_END
463         return r;
464 }
465
466 void CSQC_ReadEntities (void)
467 {
468         unsigned short entnum, oldself, realentnum;
469         CSQC_BEGIN
470                 *prog->time = cl.time;
471                 oldself = prog->globals.client->self;
472                 while(1)
473                 {
474                         entnum = MSG_ReadShort();
475                         if(!entnum)
476                                 return;
477                         realentnum = entnum & 0x7FFF;
478                         prog->globals.client->self = csqc_sv2csqcents[realentnum];
479                         if(entnum & 0x8000)
480                         {
481                                 if(prog->globals.client->self)
482                                 {
483                                         PRVM_ExecuteProgram((func_t)(CSQC_Ent_Remove - prog->functions), CL_F_ENT_REMOVE);
484                                         csqc_sv2csqcents[realentnum] = 0;
485                                 }
486                                 else
487                                         Con_Printf("Smth bad happens in csqc...\n");    //[515]: never happens ?
488                         }
489                         else
490                         {
491                                 if(!prog->globals.client->self)
492                                 {
493                                         prvm_edict_t    *ed;
494                                         ed = PRVM_ED_Alloc();
495                                         ed->fields.client->entnum = realentnum;
496                                         prog->globals.client->self = csqc_sv2csqcents[realentnum] = PRVM_EDICT_TO_PROG(ed);
497                                         PRVM_G_FLOAT(OFS_PARM0) = 1;
498                                 }
499                                 else
500                                         PRVM_G_FLOAT(OFS_PARM0) = 0;
501                                 PRVM_ExecuteProgram((func_t)(CSQC_Ent_Update - prog->functions), CL_F_ENT_UPDATE);
502                         }
503                 }
504                 prog->globals.client->self = oldself;
505         CSQC_END
506 }
507
508 void Cmd_ClearCsqcFuncs (void);
509
510 void CL_VM_Init (void)
511 {
512         unsigned char *csprogsdata;
513         fs_offset_t csprogsdatasize;
514         int csprogsdatacrc, requiredcrc;
515         int requiredsize;
516
517         // reset csqc_progcrc after reading it, so that changing servers doesn't
518         // expect csqc on the next server
519         requiredcrc = csqc_progcrc.integer;
520         requiredsize = csqc_progsize.integer;
521         Cvar_SetValueQuick(&csqc_progcrc, -1);
522         Cvar_SetValueQuick(&csqc_progsize, -1);
523
524         csqc_loaded = false;
525         memset(cl.csqc_model_precache, 0, sizeof(cl.csqc_model_precache));
526         memset(&cl.csqc_vidvars, true, sizeof(csqc_vidvars_t));
527
528         // if the server is not requesting a csprogs, then we're done here
529         if (requiredcrc < 0)
530                 return;
531
532         // see if the requested csprogs.dat file matches the requested crc
533         csprogsdatacrc = -1;
534         csprogsdata = FS_LoadFile(va("dlcache/%s.%i.%i", csqc_progname.string, requiredsize, requiredcrc), tempmempool, true, &csprogsdatasize);
535         if (!csprogsdata)
536                 csprogsdata = FS_LoadFile(csqc_progname.string, tempmempool, true, &csprogsdatasize);
537         if (csprogsdata)
538         {
539                 csprogsdatacrc = CRC_Block(csprogsdata, csprogsdatasize);
540                 Mem_Free(csprogsdata);
541                 if (csprogsdatacrc != requiredcrc || csprogsdatasize != requiredsize)
542                 {
543                         if (cls.demoplayback)
544                         {
545                                 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);
546                                 return;
547                         }
548                         else
549                         {
550                                 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);
551                                 CL_Disconnect();
552                                 return;
553                         }
554                 }
555         }
556         else
557         {
558                 if (requiredcrc >= 0)
559                 {
560                         if (cls.demoplayback)
561                                 Con_Printf("CL_VM_Init: demo requires CSQC, but \"%s\" wasn't found\n", csqc_progname.string);
562                         else
563                                 Con_Printf("CL_VM_Init: server requires CSQC, but \"%s\" wasn't found\n", csqc_progname.string);
564                         CL_Disconnect();
565                 }
566                 return;
567         }
568
569         PRVM_Begin;
570         PRVM_InitProg(PRVM_CLIENTPROG);
571
572         csqc_mempool = Mem_AllocPool("CSQC", 0, NULL);
573
574         // allocate the mempools
575         prog->progs_mempool = Mem_AllocPool(csqc_progname.string, 0, NULL);
576         prog->headercrc = CL_PROGHEADER_CRC;
577         prog->edictprivate_size = 0; // no private struct used
578         prog->name = CL_NAME;
579         prog->num_edicts = 1;
580         prog->limit_edicts = CL_MAX_EDICTS;
581         prog->extensionstring = vm_cl_extensions;
582         prog->builtins = vm_cl_builtins;
583         prog->numbuiltins = vm_cl_numbuiltins;
584         prog->init_cmd = VM_CL_Cmd_Init;
585         prog->reset_cmd = VM_CL_Cmd_Reset;
586         prog->error_cmd = CL_VM_Error;
587
588         PRVM_LoadProgs(csqc_progname.string, cl_numrequiredfunc, cl_required_func, 0, NULL);
589
590         if(prog->loaded)
591                 Con_Printf("CSQC ^5loaded (crc=%i, size=%i)\n", csprogsdatacrc, (int)csprogsdatasize);
592         else
593         {
594                 CL_VM_Error("CSQC ^2failed to load\n");
595                 if(!sv.active)
596                         CL_Disconnect();
597                 return;
598         }
599
600         //[515]: optional fields & funcs
601         CL_VM_FindEdictFieldOffsets();
602
603         // set time
604         *prog->time = cl.time;
605         csqc_frametime = 0;
606
607         prog->globals.client->mapname = PRVM_SetEngineString(cl.worldmodel->name);
608         prog->globals.client->player_localentnum = cl.playerentity;
609
610         // call the prog init
611         PRVM_ExecuteProgram((func_t) (PRVM_ED_FindFunction(CL_F_INIT) - prog->functions), CL_F_INIT);
612
613         PRVM_End;
614         csqc_loaded = true;
615
616         csqc_sv2csqcents = (unsigned short *)Mem_Alloc(csqc_mempool, MAX_EDICTS*sizeof(unsigned short));
617         memset(csqc_sv2csqcents, 0, MAX_EDICTS*sizeof(unsigned short));
618
619         cl.csqc_vidvars.drawcrosshair = false;
620         cl.csqc_vidvars.drawenginesbar = false;
621 }
622
623 void CL_VM_ShutDown (void)
624 {
625         Cmd_ClearCsqcFuncs();
626         Cvar_SetValueQuick(&csqc_progcrc, -1);
627         Cvar_SetValueQuick(&csqc_progsize, -1);
628         if(!csqc_loaded)
629                 return;
630         CSQC_BEGIN
631                 *prog->time = cl.time;
632                 PRVM_ExecuteProgram((func_t) (PRVM_ED_FindFunction(CL_F_SHUTDOWN) - prog->functions), CL_F_SHUTDOWN);
633                 PRVM_ResetProg();
634         CSQC_END
635         Con_Print("CSQC ^1unloaded\n");
636         csqc_loaded = false;
637         Mem_FreePool(&csqc_mempool);
638 }