In prog reset functions, do not call functions unless prog->loaded.
[xonotic/darkplaces.git] / csprogs.c
1 #include "quakedef.h"
2 #include "progsvm.h"
3 #include "clprogdefs.h"
4 #include "csprogs.h"
5 #include "cl_collision.h"
6 #include "snd_main.h"
7 #include "clvm_cmds.h"
8 #include "prvm_cmds.h"
9
10 //============================================================================
11 // Client prog handling
12 //[515]: omg !!! optimize it ! a lot of hacks here and there also :P
13
14 #define CSQC_RETURNVAL  prog->globals.fp[OFS_RETURN]
15 #define CSQC_BEGIN
16 #define CSQC_END
17
18 void CL_VM_PreventInformationLeaks(void)
19 {
20         prvm_prog_t *prog = CLVM_prog;
21         if(!cl.csqc_loaded)
22                 return;
23         CSQC_BEGIN
24                 VM_ClearTraceGlobals(prog);
25                 PRVM_clientglobalfloat(trace_networkentity) = 0;
26         CSQC_END
27 }
28
29 //[515]: these are required funcs
30 static const char *cl_required_func[] =
31 {
32         "CSQC_Init",
33         "CSQC_InputEvent",
34         "CSQC_UpdateView",
35         "CSQC_ConsoleCommand",
36 };
37
38 static int cl_numrequiredfunc = sizeof(cl_required_func) / sizeof(char*);
39
40 #define CL_REQFIELDS (sizeof(cl_reqfields) / sizeof(prvm_required_field_t))
41
42 prvm_required_field_t cl_reqfields[] =
43 {
44 #define PRVM_DECLARE_serverglobalfloat(x)
45 #define PRVM_DECLARE_serverglobalvector(x)
46 #define PRVM_DECLARE_serverglobalstring(x)
47 #define PRVM_DECLARE_serverglobaledict(x)
48 #define PRVM_DECLARE_serverglobalfunction(x)
49 #define PRVM_DECLARE_clientglobalfloat(x)
50 #define PRVM_DECLARE_clientglobalvector(x)
51 #define PRVM_DECLARE_clientglobalstring(x)
52 #define PRVM_DECLARE_clientglobaledict(x)
53 #define PRVM_DECLARE_clientglobalfunction(x)
54 #define PRVM_DECLARE_menuglobalfloat(x)
55 #define PRVM_DECLARE_menuglobalvector(x)
56 #define PRVM_DECLARE_menuglobalstring(x)
57 #define PRVM_DECLARE_menuglobaledict(x)
58 #define PRVM_DECLARE_menuglobalfunction(x)
59 #define PRVM_DECLARE_serverfieldfloat(x)
60 #define PRVM_DECLARE_serverfieldvector(x)
61 #define PRVM_DECLARE_serverfieldstring(x)
62 #define PRVM_DECLARE_serverfieldedict(x)
63 #define PRVM_DECLARE_serverfieldfunction(x)
64 #define PRVM_DECLARE_clientfieldfloat(x) {ev_float, #x },
65 #define PRVM_DECLARE_clientfieldvector(x) {ev_vector, #x },
66 #define PRVM_DECLARE_clientfieldstring(x) {ev_string, #x },
67 #define PRVM_DECLARE_clientfieldedict(x) {ev_entity, #x },
68 #define PRVM_DECLARE_clientfieldfunction(x) {ev_function, #x },
69 #define PRVM_DECLARE_menufieldfloat(x)
70 #define PRVM_DECLARE_menufieldvector(x)
71 #define PRVM_DECLARE_menufieldstring(x)
72 #define PRVM_DECLARE_menufieldedict(x)
73 #define PRVM_DECLARE_menufieldfunction(x)
74 #define PRVM_DECLARE_serverfunction(x)
75 #define PRVM_DECLARE_clientfunction(x)
76 #define PRVM_DECLARE_menufunction(x)
77 #define PRVM_DECLARE_field(x)
78 #define PRVM_DECLARE_global(x)
79 #define PRVM_DECLARE_function(x)
80 #include "prvm_offsets.h"
81 #undef PRVM_DECLARE_serverglobalfloat
82 #undef PRVM_DECLARE_serverglobalvector
83 #undef PRVM_DECLARE_serverglobalstring
84 #undef PRVM_DECLARE_serverglobaledict
85 #undef PRVM_DECLARE_serverglobalfunction
86 #undef PRVM_DECLARE_clientglobalfloat
87 #undef PRVM_DECLARE_clientglobalvector
88 #undef PRVM_DECLARE_clientglobalstring
89 #undef PRVM_DECLARE_clientglobaledict
90 #undef PRVM_DECLARE_clientglobalfunction
91 #undef PRVM_DECLARE_menuglobalfloat
92 #undef PRVM_DECLARE_menuglobalvector
93 #undef PRVM_DECLARE_menuglobalstring
94 #undef PRVM_DECLARE_menuglobaledict
95 #undef PRVM_DECLARE_menuglobalfunction
96 #undef PRVM_DECLARE_serverfieldfloat
97 #undef PRVM_DECLARE_serverfieldvector
98 #undef PRVM_DECLARE_serverfieldstring
99 #undef PRVM_DECLARE_serverfieldedict
100 #undef PRVM_DECLARE_serverfieldfunction
101 #undef PRVM_DECLARE_clientfieldfloat
102 #undef PRVM_DECLARE_clientfieldvector
103 #undef PRVM_DECLARE_clientfieldstring
104 #undef PRVM_DECLARE_clientfieldedict
105 #undef PRVM_DECLARE_clientfieldfunction
106 #undef PRVM_DECLARE_menufieldfloat
107 #undef PRVM_DECLARE_menufieldvector
108 #undef PRVM_DECLARE_menufieldstring
109 #undef PRVM_DECLARE_menufieldedict
110 #undef PRVM_DECLARE_menufieldfunction
111 #undef PRVM_DECLARE_serverfunction
112 #undef PRVM_DECLARE_clientfunction
113 #undef PRVM_DECLARE_menufunction
114 #undef PRVM_DECLARE_field
115 #undef PRVM_DECLARE_global
116 #undef PRVM_DECLARE_function
117 };
118
119 #define CL_REQGLOBALS (sizeof(cl_reqglobals) / sizeof(prvm_required_field_t))
120
121 prvm_required_field_t cl_reqglobals[] =
122 {
123 #define PRVM_DECLARE_serverglobalfloat(x)
124 #define PRVM_DECLARE_serverglobalvector(x)
125 #define PRVM_DECLARE_serverglobalstring(x)
126 #define PRVM_DECLARE_serverglobaledict(x)
127 #define PRVM_DECLARE_serverglobalfunction(x)
128 #define PRVM_DECLARE_clientglobalfloat(x) {ev_float, #x},
129 #define PRVM_DECLARE_clientglobalvector(x) {ev_vector, #x},
130 #define PRVM_DECLARE_clientglobalstring(x) {ev_string, #x},
131 #define PRVM_DECLARE_clientglobaledict(x) {ev_entity, #x},
132 #define PRVM_DECLARE_clientglobalfunction(x) {ev_function, #x},
133 #define PRVM_DECLARE_menuglobalfloat(x)
134 #define PRVM_DECLARE_menuglobalvector(x)
135 #define PRVM_DECLARE_menuglobalstring(x)
136 #define PRVM_DECLARE_menuglobaledict(x)
137 #define PRVM_DECLARE_menuglobalfunction(x)
138 #define PRVM_DECLARE_serverfieldfloat(x)
139 #define PRVM_DECLARE_serverfieldvector(x)
140 #define PRVM_DECLARE_serverfieldstring(x)
141 #define PRVM_DECLARE_serverfieldedict(x)
142 #define PRVM_DECLARE_serverfieldfunction(x)
143 #define PRVM_DECLARE_clientfieldfloat(x)
144 #define PRVM_DECLARE_clientfieldvector(x)
145 #define PRVM_DECLARE_clientfieldstring(x)
146 #define PRVM_DECLARE_clientfieldedict(x)
147 #define PRVM_DECLARE_clientfieldfunction(x)
148 #define PRVM_DECLARE_menufieldfloat(x)
149 #define PRVM_DECLARE_menufieldvector(x)
150 #define PRVM_DECLARE_menufieldstring(x)
151 #define PRVM_DECLARE_menufieldedict(x)
152 #define PRVM_DECLARE_menufieldfunction(x)
153 #define PRVM_DECLARE_serverfunction(x)
154 #define PRVM_DECLARE_clientfunction(x)
155 #define PRVM_DECLARE_menufunction(x)
156 #define PRVM_DECLARE_field(x)
157 #define PRVM_DECLARE_global(x)
158 #define PRVM_DECLARE_function(x)
159 #include "prvm_offsets.h"
160 #undef PRVM_DECLARE_serverglobalfloat
161 #undef PRVM_DECLARE_serverglobalvector
162 #undef PRVM_DECLARE_serverglobalstring
163 #undef PRVM_DECLARE_serverglobaledict
164 #undef PRVM_DECLARE_serverglobalfunction
165 #undef PRVM_DECLARE_clientglobalfloat
166 #undef PRVM_DECLARE_clientglobalvector
167 #undef PRVM_DECLARE_clientglobalstring
168 #undef PRVM_DECLARE_clientglobaledict
169 #undef PRVM_DECLARE_clientglobalfunction
170 #undef PRVM_DECLARE_menuglobalfloat
171 #undef PRVM_DECLARE_menuglobalvector
172 #undef PRVM_DECLARE_menuglobalstring
173 #undef PRVM_DECLARE_menuglobaledict
174 #undef PRVM_DECLARE_menuglobalfunction
175 #undef PRVM_DECLARE_serverfieldfloat
176 #undef PRVM_DECLARE_serverfieldvector
177 #undef PRVM_DECLARE_serverfieldstring
178 #undef PRVM_DECLARE_serverfieldedict
179 #undef PRVM_DECLARE_serverfieldfunction
180 #undef PRVM_DECLARE_clientfieldfloat
181 #undef PRVM_DECLARE_clientfieldvector
182 #undef PRVM_DECLARE_clientfieldstring
183 #undef PRVM_DECLARE_clientfieldedict
184 #undef PRVM_DECLARE_clientfieldfunction
185 #undef PRVM_DECLARE_menufieldfloat
186 #undef PRVM_DECLARE_menufieldvector
187 #undef PRVM_DECLARE_menufieldstring
188 #undef PRVM_DECLARE_menufieldedict
189 #undef PRVM_DECLARE_menufieldfunction
190 #undef PRVM_DECLARE_serverfunction
191 #undef PRVM_DECLARE_clientfunction
192 #undef PRVM_DECLARE_menufunction
193 #undef PRVM_DECLARE_field
194 #undef PRVM_DECLARE_global
195 #undef PRVM_DECLARE_function
196 };
197
198 void CL_VM_UpdateDmgGlobals (int dmg_take, int dmg_save, vec3_t dmg_origin)
199 {
200         prvm_prog_t *prog = CLVM_prog;
201         if(cl.csqc_loaded)
202         {
203                 CSQC_BEGIN
204                 PRVM_clientglobalfloat(dmg_take) = dmg_take;
205                 PRVM_clientglobalfloat(dmg_save) = dmg_save;
206                 VectorCopy(dmg_origin, PRVM_clientglobalvector(dmg_origin));
207                 CSQC_END
208         }
209 }
210
211 void CSQC_UpdateNetworkTimes(double newtime, double oldtime)
212 {
213         prvm_prog_t *prog = CLVM_prog;
214         if(!cl.csqc_loaded)
215                 return;
216         CSQC_BEGIN
217         PRVM_clientglobalfloat(servertime) = newtime;
218         PRVM_clientglobalfloat(serverprevtime) = oldtime;
219         PRVM_clientglobalfloat(serverdeltatime) = newtime - oldtime;
220         CSQC_END
221 }
222
223 //[515]: set globals before calling R_UpdateView, WEIRD CRAP
224 static void CSQC_SetGlobals (double frametime)
225 {
226         vec3_t pmove_org;
227         prvm_prog_t *prog = CLVM_prog;
228         CSQC_BEGIN
229                 PRVM_clientglobalfloat(time) = cl.time;
230                 PRVM_clientglobalfloat(frametime) = frametime;
231                 PRVM_clientglobalfloat(servercommandframe) = cls.servermovesequence;
232                 PRVM_clientglobalfloat(clientcommandframe) = cl.movecmd[0].sequence;
233                 VectorCopy(cl.viewangles, PRVM_clientglobalvector(input_angles));
234                 // // FIXME: this actually belongs into getinputstate().. [12/17/2007 Black]
235                 PRVM_clientglobalfloat(input_buttons) = cl.movecmd[0].buttons;
236                 VectorSet(PRVM_clientglobalvector(input_movevalues), cl.movecmd[0].forwardmove, cl.movecmd[0].sidemove, cl.movecmd[0].upmove);
237                 VectorCopy(cl.csqc_vieworiginfromengine, cl.csqc_vieworigin);
238                 VectorCopy(cl.csqc_viewanglesfromengine, cl.csqc_viewangles);
239
240                 // LordHavoc: Spike says not to do this, but without pmove_org the
241                 // CSQC is useless as it can't alter the view origin without
242                 // completely replacing it
243                 Matrix4x4_OriginFromMatrix(&cl.entities[cl.viewentity].render.matrix, pmove_org);
244                 VectorCopy(pmove_org, PRVM_clientglobalvector(pmove_org));
245                 VectorCopy(cl.movement_velocity, PRVM_clientglobalvector(pmove_vel));
246                 PRVM_clientglobalfloat(pmove_onground) = cl.onground;
247                 PRVM_clientglobalfloat(pmove_inwater) = cl.inwater;
248
249                 VectorCopy(cl.viewangles, PRVM_clientglobalvector(view_angles));
250                 VectorCopy(cl.punchangle, PRVM_clientglobalvector(view_punchangle));
251                 VectorCopy(cl.punchvector, PRVM_clientglobalvector(view_punchvector));
252                 PRVM_clientglobalfloat(maxclients) = cl.maxclients;
253
254                 PRVM_clientglobalfloat(player_localentnum) = cl.viewentity;
255
256                 CSQC_R_RecalcView();
257         CSQC_END
258 }
259
260 void CSQC_Predraw (prvm_edict_t *ed)
261 {
262         prvm_prog_t *prog = CLVM_prog;
263         int b;
264         if(!PRVM_clientedictfunction(ed, predraw))
265                 return;
266         b = PRVM_clientglobaledict(self);
267         PRVM_clientglobaledict(self) = PRVM_EDICT_TO_PROG(ed);
268         prog->ExecuteProgram(prog, PRVM_clientedictfunction(ed, predraw), "CSQC_Predraw: NULL function\n");
269         PRVM_clientglobaledict(self) = b;
270 }
271
272 void CSQC_Think (prvm_edict_t *ed)
273 {
274         prvm_prog_t *prog = CLVM_prog;
275         int b;
276         if(PRVM_clientedictfunction(ed, think))
277         if(PRVM_clientedictfloat(ed, nextthink) && PRVM_clientedictfloat(ed, nextthink) <= PRVM_clientglobalfloat(time))
278         {
279                 PRVM_clientedictfloat(ed, nextthink) = 0;
280                 b = PRVM_clientglobaledict(self);
281                 PRVM_clientglobaledict(self) = PRVM_EDICT_TO_PROG(ed);
282                 prog->ExecuteProgram(prog, PRVM_clientedictfunction(ed, think), "CSQC_Think: NULL function\n");
283                 PRVM_clientglobaledict(self) = b;
284         }
285 }
286
287 extern cvar_t cl_noplayershadow;
288 extern cvar_t r_equalize_entities_fullbright;
289 qboolean CSQC_AddRenderEdict(prvm_edict_t *ed, int edictnum)
290 {
291         prvm_prog_t *prog = CLVM_prog;
292         int renderflags;
293         int c;
294         float scale;
295         entity_render_t *entrender;
296         dp_model_t *model;
297
298         model = CL_GetModelFromEdict(ed);
299         if (!model)
300                 return false;
301
302         if (edictnum)
303         {
304                 if (r_refdef.scene.numentities >= r_refdef.scene.maxentities)
305                         return false;
306                 entrender = cl.csqcrenderentities + edictnum;
307                 r_refdef.scene.entities[r_refdef.scene.numentities++] = entrender;
308                 entrender->entitynumber = edictnum + MAX_EDICTS;
309                 //entrender->shadertime = 0; // shadertime was set by spawn()
310                 entrender->flags = 0;
311                 entrender->effects = 0;
312                 entrender->alpha = 1;
313                 entrender->scale = 1;
314                 VectorSet(entrender->colormod, 1, 1, 1);
315                 VectorSet(entrender->glowmod, 1, 1, 1);
316                 entrender->allowdecals = true;
317         }
318         else
319         {
320                 entrender = CL_NewTempEntity(0);
321                 if (!entrender)
322                         return false;
323         }
324
325         entrender->userwavefunc_param[0] = PRVM_clientedictfloat(ed, userwavefunc_param0);
326         entrender->userwavefunc_param[1] = PRVM_clientedictfloat(ed, userwavefunc_param1);
327         entrender->userwavefunc_param[2] = PRVM_clientedictfloat(ed, userwavefunc_param2);
328         entrender->userwavefunc_param[3] = PRVM_clientedictfloat(ed, userwavefunc_param3);
329
330         entrender->model = model;
331         entrender->skinnum = (int)PRVM_clientedictfloat(ed, skin);
332         entrender->effects |= entrender->model->effects;
333         renderflags = (int)PRVM_clientedictfloat(ed, renderflags);
334         entrender->alpha = PRVM_clientedictfloat(ed, alpha);
335         entrender->scale = scale = PRVM_clientedictfloat(ed, scale);
336         VectorCopy(PRVM_clientedictvector(ed, colormod), entrender->colormod);
337         VectorCopy(PRVM_clientedictvector(ed, glowmod), entrender->glowmod);
338         if(PRVM_clientedictfloat(ed, effects))  entrender->effects |= (int)PRVM_clientedictfloat(ed, effects);
339         if (!entrender->alpha)
340                 entrender->alpha = 1.0f;
341         if (!entrender->scale)
342                 entrender->scale = scale = 1.0f;
343         if (!VectorLength2(entrender->colormod))
344                 VectorSet(entrender->colormod, 1, 1, 1);
345         if (!VectorLength2(entrender->glowmod))
346                 VectorSet(entrender->glowmod, 1, 1, 1);
347
348         // LordHavoc: use the CL_GetTagMatrix function on self to ensure consistent behavior (duplicate code would be bad)
349         CL_GetTagMatrix(prog, &entrender->matrix, ed, 0);
350
351         // set up the animation data
352         VM_GenerateFrameGroupBlend(prog, ed->priv.server->framegroupblend, ed);
353         VM_FrameBlendFromFrameGroupBlend(ed->priv.server->frameblend, ed->priv.server->framegroupblend, model, cl.time);
354         VM_UpdateEdictSkeleton(prog, ed, model, ed->priv.server->frameblend);
355         if (PRVM_clientedictfloat(ed, shadertime)) // hack for csprogs.dat files that do not set shadertime, leaves the value at entity spawn time
356                 entrender->shadertime = PRVM_clientedictfloat(ed, shadertime);
357
358         // transparent offset
359         if (renderflags & RF_USETRANSPARENTOFFSET)
360                 entrender->transparent_offset = PRVM_clientglobalfloat(transparent_offset);
361
362         // model light
363         if (renderflags & RF_MODELLIGHT)
364         {
365                 if (PRVM_clientedictvector(ed, modellight_ambient)) VectorCopy(PRVM_clientedictvector(ed, modellight_ambient), entrender->modellight_ambient); else VectorClear(entrender->modellight_ambient);
366                 if (PRVM_clientedictvector(ed, modellight_diffuse)) VectorCopy(PRVM_clientedictvector(ed, modellight_diffuse), entrender->modellight_diffuse); else VectorClear(entrender->modellight_diffuse);
367                 if (PRVM_clientedictvector(ed, modellight_dir))     VectorCopy(PRVM_clientedictvector(ed, modellight_dir), entrender->modellight_lightdir);    else VectorClear(entrender->modellight_lightdir);
368                 entrender->flags |= RENDER_CUSTOMIZEDMODELLIGHT;
369         }
370
371         if(renderflags)
372         {
373                 if(renderflags & RF_VIEWMODEL) entrender->flags |= RENDER_VIEWMODEL | RENDER_NODEPTHTEST;
374                 if(renderflags & RF_EXTERNALMODEL) entrender->flags |= RENDER_EXTERIORMODEL;
375                 if(renderflags & RF_WORLDOBJECT) entrender->flags |= RENDER_WORLDOBJECT;
376                 if(renderflags & RF_DEPTHHACK) entrender->flags |= RENDER_NODEPTHTEST;
377                 if(renderflags & RF_ADDITIVE) entrender->flags |= RENDER_ADDITIVE;
378                 if(renderflags & RF_DYNAMICMODELLIGHT) entrender->flags |= RENDER_DYNAMICMODELLIGHT;
379         }
380
381         c = (int)PRVM_clientedictfloat(ed, colormap);
382         if (c <= 0)
383                 CL_SetEntityColormapColors(entrender, -1);
384         else if (c <= cl.maxclients && cl.scores != NULL)
385                 CL_SetEntityColormapColors(entrender, cl.scores[c-1].colors);
386         else
387                 CL_SetEntityColormapColors(entrender, c);
388
389         entrender->flags &= ~(RENDER_SHADOW | RENDER_LIGHT | RENDER_NOSELFSHADOW);
390         // either fullbright or lit
391         if(!r_fullbright.integer)
392         {
393                 if (!(entrender->effects & EF_FULLBRIGHT) && !(renderflags & RF_FULLBRIGHT))
394                         entrender->flags |= RENDER_LIGHT;
395                 else if(r_equalize_entities_fullbright.integer)
396                         entrender->flags |= RENDER_LIGHT | RENDER_EQUALIZE;
397         }
398         // hide player shadow during intermission or nehahra movie
399         if (!(entrender->effects & (EF_NOSHADOW | EF_ADDITIVE | EF_NODEPTHTEST))
400          &&  (entrender->alpha >= 1)
401          && !(renderflags & RF_NOSHADOW)
402          && !(entrender->flags & RENDER_VIEWMODEL)
403          && (!(entrender->flags & RENDER_EXTERIORMODEL) || (!cl.intermission && cls.protocol != PROTOCOL_NEHAHRAMOVIE && !cl_noplayershadow.integer)))
404                 entrender->flags |= RENDER_SHADOW;
405         if (entrender->flags & RENDER_VIEWMODEL)
406                 entrender->flags |= RENDER_NOSELFSHADOW;
407         if (entrender->effects & EF_NOSELFSHADOW)
408                 entrender->flags |= RENDER_NOSELFSHADOW;
409         if (entrender->effects & EF_NODEPTHTEST)
410                 entrender->flags |= RENDER_NODEPTHTEST;
411         if (entrender->effects & EF_ADDITIVE)
412                 entrender->flags |= RENDER_ADDITIVE;
413         if (entrender->effects & EF_DOUBLESIDED)
414                 entrender->flags |= RENDER_DOUBLESIDED;
415         if (entrender->effects & EF_DYNAMICMODELLIGHT)
416                 entrender->flags |= RENDER_DYNAMICMODELLIGHT;
417
418         // make the other useful stuff
419         memcpy(entrender->framegroupblend, ed->priv.server->framegroupblend, sizeof(ed->priv.server->framegroupblend));
420         CL_UpdateRenderEntity(entrender);
421
422         // override animation data with full control
423         memcpy(entrender->frameblend, ed->priv.server->frameblend, sizeof(ed->priv.server->frameblend));
424         if (ed->priv.server->skeleton.relativetransforms)
425                 entrender->skeleton = &ed->priv.server->skeleton;
426         else
427                 entrender->skeleton = NULL;
428
429         return true;
430 }
431
432 // 0 = keydown, key, character (EXT_CSQC)
433 // 1 = keyup, key, character (EXT_CSQC)
434 // 2 = mousemove relative, x, y (EXT_CSQC)
435 // 3 = mousemove absolute, x, y (DP_CSQC)
436 qboolean CL_VM_InputEvent (int eventtype, int x, int y)
437 {
438         prvm_prog_t *prog = CLVM_prog;
439         qboolean r;
440
441         if(!cl.csqc_loaded)
442                 return false;
443
444         CSQC_BEGIN
445                 if (!PRVM_clientfunction(CSQC_InputEvent))
446                         r = false;
447                 else
448                 {
449                         PRVM_clientglobalfloat(time) = cl.time;
450                         PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[cl.playerentity];
451                         PRVM_G_FLOAT(OFS_PARM0) = eventtype;
452                         PRVM_G_FLOAT(OFS_PARM1) = x; // key or x
453                         PRVM_G_FLOAT(OFS_PARM2) = y; // ascii or y
454                         prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_InputEvent), "QC function CSQC_InputEvent is missing");
455                         r = CSQC_RETURNVAL != 0;
456                 }
457         CSQC_END
458         return r;
459 }
460
461 extern r_refdef_view_t csqc_original_r_refdef_view;
462 extern r_refdef_view_t csqc_main_r_refdef_view;
463 qboolean CL_VM_UpdateView (double frametime)
464 {
465         prvm_prog_t *prog = CLVM_prog;
466         vec3_t emptyvector;
467         emptyvector[0] = 0;
468         emptyvector[1] = 0;
469         emptyvector[2] = 0;
470 //      vec3_t oldangles;
471         if(!cl.csqc_loaded)
472                 return false;
473         R_TimeReport("pre-UpdateView");
474         CSQC_BEGIN
475                 r_refdef.view.ismain = true;
476                 csqc_original_r_refdef_view = r_refdef.view;
477                 csqc_main_r_refdef_view = r_refdef.view;
478                 //VectorCopy(cl.viewangles, oldangles);
479                 PRVM_clientglobalfloat(time) = cl.time;
480                 PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[cl.playerentity];
481                 CSQC_SetGlobals(frametime);
482                 // clear renderable entity and light lists to prevent crashes if the
483                 // CSQC_UpdateView function does not call R_ClearScene as it should
484                 r_refdef.scene.numentities = 0;
485                 r_refdef.scene.numlights = 0;
486                 // pass in width and height as parameters (EXT_CSQC_1)
487                 PRVM_G_FLOAT(OFS_PARM0) = vid.width;
488                 PRVM_G_FLOAT(OFS_PARM1) = vid.height;
489                 prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_UpdateView), "QC function CSQC_UpdateView is missing");
490                 //VectorCopy(oldangles, cl.viewangles);
491                 // Dresk : Reset Dmg Globals Here
492                 CL_VM_UpdateDmgGlobals(0, 0, emptyvector);
493                 r_refdef.view = csqc_main_r_refdef_view;
494                 R_RenderView_UpdateViewVectors(); // we have to do this, as we undid the scene render doing this for us
495         CSQC_END
496
497         R_TimeReport("UpdateView");
498         return true;
499 }
500
501 qboolean CL_VM_ConsoleCommand (const char *cmd)
502 {
503         prvm_prog_t *prog = CLVM_prog;
504         int restorevm_tempstringsbuf_cursize;
505         qboolean r = false;
506         if(!cl.csqc_loaded)
507                 return false;
508         CSQC_BEGIN
509         if (PRVM_clientfunction(CSQC_ConsoleCommand))
510         {
511                 PRVM_clientglobalfloat(time) = cl.time;
512                 PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[cl.playerentity];
513                 restorevm_tempstringsbuf_cursize = prog->tempstringsbuf.cursize;
514                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(prog, cmd);
515                 prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_ConsoleCommand), "QC function CSQC_ConsoleCommand is missing");
516                 prog->tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
517                 r = CSQC_RETURNVAL != 0;
518         }
519         CSQC_END
520         return r;
521 }
522
523 qboolean CL_VM_Parse_TempEntity (void)
524 {
525         prvm_prog_t *prog = CLVM_prog;
526         int                     t;
527         qboolean        r = false;
528         if(!cl.csqc_loaded)
529                 return false;
530         CSQC_BEGIN
531         if(PRVM_clientfunction(CSQC_Parse_TempEntity))
532         {
533                 t = cl_message.readcount;
534                 PRVM_clientglobalfloat(time) = cl.time;
535                 PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[cl.playerentity];
536                 prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Parse_TempEntity), "QC function CSQC_Parse_TempEntity is missing");
537                 r = CSQC_RETURNVAL != 0;
538                 if(!r)
539                 {
540                         cl_message.readcount = t;
541                         cl_message.badread = false;
542                 }
543         }
544         CSQC_END
545         return r;
546 }
547
548 void CL_VM_Parse_StuffCmd (const char *msg)
549 {
550         prvm_prog_t *prog = CLVM_prog;
551         int restorevm_tempstringsbuf_cursize;
552         if(msg[0] == 'c')
553         if(msg[1] == 's')
554         if(msg[2] == 'q')
555         if(msg[3] == 'c')
556         {
557                 // if this is setting a csqc variable, deprotect csqc_progcrc
558                 // temporarily so that it can be set by the cvar command,
559                 // and then reprotect it afterwards
560                 int crcflags = csqc_progcrc.flags;
561                 int sizeflags = csqc_progcrc.flags;
562                 csqc_progcrc.flags &= ~CVAR_READONLY;
563                 csqc_progsize.flags &= ~CVAR_READONLY;
564                 Cmd_ExecuteString (msg, src_command, true);
565                 csqc_progcrc.flags = crcflags;
566                 csqc_progsize.flags = sizeflags;
567                 return;
568         }
569
570         if(cls.demoplayback)
571         if(!strncmp(msg, "curl --clear_autodownload\ncurl --pak --forthismap --as ", 55))
572         {
573                 // special handling for map download commands
574                 // run these commands IMMEDIATELY, instead of waiting for a client frame
575                 // that way, there is no black screen when playing back demos
576                 // I know this is a really ugly hack, but I can't think of any better way
577                 // FIXME find the actual CAUSE of this, and make demo playback WAIT
578                 // until all maps are loaded, then remove this hack
579
580                 char buf[MAX_INPUTLINE];
581                 const char *p, *q;
582                 size_t l;
583
584                 p = msg;
585
586                 for(;;)
587                 {
588                         q = strchr(p, '\n');
589                         if(q)
590                                 l = q - p;
591                         else
592                                 l = strlen(p);
593                         if(l > sizeof(buf) - 1)
594                                 l = sizeof(buf) - 1;
595                         strlcpy(buf, p, l + 1); // strlcpy needs a + 1 as it includes the newline!
596
597                         Cmd_ExecuteString(buf, src_command, true);
598
599                         p += l;
600                         if(*p == '\n')
601                                 ++p; // skip the newline and continue
602                         else
603                                 break; // end of string or overflow
604                 }
605                 Cmd_ExecuteString("curl --clear_autodownload", src_command, true); // don't inhibit CSQC loading
606                 return;
607         }
608
609         if(!cl.csqc_loaded)
610         {
611                 Cbuf_AddText(msg);
612                 return;
613         }
614         CSQC_BEGIN
615         if(PRVM_clientfunction(CSQC_Parse_StuffCmd))
616         {
617                 PRVM_clientglobalfloat(time) = cl.time;
618                 PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[cl.playerentity];
619                 restorevm_tempstringsbuf_cursize = prog->tempstringsbuf.cursize;
620                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(prog, msg);
621                 prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Parse_StuffCmd), "QC function CSQC_Parse_StuffCmd is missing");
622                 prog->tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
623         }
624         else
625                 Cbuf_AddText(msg);
626         CSQC_END
627 }
628
629 static void CL_VM_Parse_Print (const char *msg)
630 {
631         prvm_prog_t *prog = CLVM_prog;
632         int restorevm_tempstringsbuf_cursize;
633         PRVM_clientglobalfloat(time) = cl.time;
634         PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[cl.playerentity];
635         restorevm_tempstringsbuf_cursize = prog->tempstringsbuf.cursize;
636         PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(prog, msg);
637         prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Parse_Print), "QC function CSQC_Parse_Print is missing");
638         prog->tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
639 }
640
641 void CSQC_AddPrintText (const char *msg)
642 {
643         prvm_prog_t *prog = CLVM_prog;
644         size_t i;
645         if(!cl.csqc_loaded)
646         {
647                 Con_Print(msg);
648                 return;
649         }
650         CSQC_BEGIN
651         if(PRVM_clientfunction(CSQC_Parse_Print))
652         {
653                 // FIXME: is this bugged?
654                 i = strlen(msg)-1;
655                 if(msg[i] != '\n' && msg[i] != '\r')
656                 {
657                         if(strlen(cl.csqc_printtextbuf)+i >= MAX_INPUTLINE)
658                         {
659                                 CL_VM_Parse_Print(cl.csqc_printtextbuf);
660                                 cl.csqc_printtextbuf[0] = 0;
661                         }
662                         else
663                                 strlcat(cl.csqc_printtextbuf, msg, MAX_INPUTLINE);
664                         return;
665                 }
666                 strlcat(cl.csqc_printtextbuf, msg, MAX_INPUTLINE);
667                 CL_VM_Parse_Print(cl.csqc_printtextbuf);
668                 cl.csqc_printtextbuf[0] = 0;
669         }
670         else
671                 Con_Print(msg);
672         CSQC_END
673 }
674
675 void CL_VM_Parse_CenterPrint (const char *msg)
676 {
677         prvm_prog_t *prog = CLVM_prog;
678         int restorevm_tempstringsbuf_cursize;
679         if(!cl.csqc_loaded)
680         {
681                 SCR_CenterPrint(msg);
682                 return;
683         }
684         CSQC_BEGIN
685         if(PRVM_clientfunction(CSQC_Parse_CenterPrint))
686         {
687                 PRVM_clientglobalfloat(time) = cl.time;
688                 PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[cl.playerentity];
689                 restorevm_tempstringsbuf_cursize = prog->tempstringsbuf.cursize;
690                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(prog, msg);
691                 prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Parse_CenterPrint), "QC function CSQC_Parse_CenterPrint is missing");
692                 prog->tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
693         }
694         else
695                 SCR_CenterPrint(msg);
696         CSQC_END
697 }
698
699 void CL_VM_UpdateIntermissionState (int intermission)
700 {
701         prvm_prog_t *prog = CLVM_prog;
702         if(cl.csqc_loaded)
703         {
704                 CSQC_BEGIN
705                 PRVM_clientglobalfloat(intermission) = intermission;
706                 CSQC_END
707         }
708 }
709 void CL_VM_UpdateShowingScoresState (int showingscores)
710 {
711         prvm_prog_t *prog = CLVM_prog;
712         if(cl.csqc_loaded)
713         {
714                 CSQC_BEGIN
715                 PRVM_clientglobalfloat(sb_showscores) = showingscores;
716                 CSQC_END
717         }
718 }
719 qboolean CL_VM_Event_Sound(int sound_num, float volume, int channel, float attenuation, int ent, vec3_t pos, int flags, float speed)
720 {
721         prvm_prog_t *prog = CLVM_prog;
722         qboolean r = false;
723         if(cl.csqc_loaded)
724         {
725                 CSQC_BEGIN
726                 if(PRVM_clientfunction(CSQC_Event_Sound))
727                 {
728                         PRVM_clientglobalfloat(time) = cl.time;
729                         PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[cl.playerentity];
730                         PRVM_G_FLOAT(OFS_PARM0) = ent;
731                         PRVM_G_FLOAT(OFS_PARM1) = CHAN_ENGINE2USER(channel);
732                         PRVM_G_INT(OFS_PARM2) = PRVM_SetTempString(prog, cl.sound_name[sound_num] );
733                         PRVM_G_FLOAT(OFS_PARM3) = volume;
734                         PRVM_G_FLOAT(OFS_PARM4) = attenuation;
735                         VectorCopy(pos, PRVM_G_VECTOR(OFS_PARM5) );
736                         PRVM_G_FLOAT(OFS_PARM6) = speed * 100.0f;
737                         PRVM_G_FLOAT(OFS_PARM7) = flags; // flags
738                         prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Event_Sound), "QC function CSQC_Event_Sound is missing");
739                         r = CSQC_RETURNVAL != 0;
740                 }
741                 CSQC_END
742         }
743
744         return r;
745 }
746 static void CL_VM_UpdateCoopDeathmatchGlobals (int gametype)
747 {
748         prvm_prog_t *prog = CLVM_prog;
749         // Avoid global names for clean(er) coding
750         int localcoop;
751         int localdeathmatch;
752
753         if(cl.csqc_loaded)
754         {
755                 if(gametype == GAME_COOP)
756                 {
757                         localcoop = 1;
758                         localdeathmatch = 0;
759                 }
760                 else
761                 if(gametype == GAME_DEATHMATCH)
762                 {
763                         localcoop = 0;
764                         localdeathmatch = 1;
765                 }
766                 else
767                 {
768                         // How did the ServerInfo send an unknown gametype?
769                         // Better just assign the globals as 0...
770                         localcoop = 0;
771                         localdeathmatch = 0;
772                 }
773                 CSQC_BEGIN
774                 PRVM_clientglobalfloat(coop) = localcoop;
775                 PRVM_clientglobalfloat(deathmatch) = localdeathmatch;
776                 CSQC_END
777         }
778 }
779 #if 0
780 static float CL_VM_Event (float event)          //[515]: needed ? I'd say "YES", but don't know for what :D
781 {
782         prvm_prog_t *prog = CLVM_prog;
783         float r = 0;
784         if(!cl.csqc_loaded)
785                 return 0;
786         CSQC_BEGIN
787         if(PRVM_clientfunction(CSQC_Event))
788         {
789                 PRVM_clientglobalfloat(time) = cl.time;
790                 PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[cl.playerentity];
791                 PRVM_G_FLOAT(OFS_PARM0) = event;
792                 prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Event), "QC function CSQC_Event is missing");
793                 r = CSQC_RETURNVAL;
794         }
795         CSQC_END
796         return r;
797 }
798 #endif
799
800 void CSQC_ReadEntities (void)
801 {
802         prvm_prog_t *prog = CLVM_prog;
803         unsigned short entnum, oldself, realentnum;
804         if(!cl.csqc_loaded)
805         {
806                 Host_Error ("CSQC_ReadEntities: CSQC is not loaded");
807                 return;
808         }
809
810         CSQC_BEGIN
811                 PRVM_clientglobalfloat(time) = cl.time;
812                 oldself = PRVM_clientglobaledict(self);
813                 while(1)
814                 {
815                         entnum = MSG_ReadShort(&cl_message);
816                         if(!entnum || cl_message.badread)
817                                 break;
818                         realentnum = entnum & 0x7FFF;
819                         PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[realentnum];
820                         if(entnum & 0x8000)
821                         {
822                                 if(PRVM_clientglobaledict(self))
823                                 {
824                                         prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Ent_Remove), "QC function CSQC_Ent_Remove is missing");
825                                         cl.csqc_server2csqcentitynumber[realentnum] = 0;
826                                 }
827                                 else
828                                 {
829                                         // LordHavoc: removing an entity that is already gone on
830                                         // the csqc side is possible for legitimate reasons (such
831                                         // as a repeat of the remove message), so no warning is
832                                         // needed
833                                         //Con_Printf("Bad csqc_server2csqcentitynumber map\n"); //[515]: never happens ?
834                                 }
835                         }
836                         else
837                         {
838                                 if(!PRVM_clientglobaledict(self))
839                                 {
840                                         if(!PRVM_clientfunction(CSQC_Ent_Spawn))
841                                         {
842                                                 prvm_edict_t    *ed;
843                                                 ed = PRVM_ED_Alloc(prog);
844                                                 PRVM_clientedictfloat(ed, entnum) = realentnum;
845                                                 PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[realentnum] = PRVM_EDICT_TO_PROG(ed);
846                                         }
847                                         else
848                                         {
849                                                 // entity( float entnum ) CSQC_Ent_Spawn;
850                                                 // the qc function should set entnum, too (this way it also can return world [2/1/2008 Andreas]
851                                                 PRVM_G_FLOAT(OFS_PARM0) = (float) realentnum;
852                                                 // make sure no one gets wrong ideas
853                                                 PRVM_clientglobaledict(self) = 0;
854                                                 prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Ent_Spawn), "QC function CSQC_Ent_Spawn is missing");
855                                                 PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[realentnum] = PRVM_EDICT( PRVM_G_INT( OFS_RETURN ) );
856                                         }
857                                         PRVM_G_FLOAT(OFS_PARM0) = 1;
858                                         prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Ent_Update), "QC function CSQC_Ent_Update is missing");
859                                 }
860                                 else {
861                                         PRVM_G_FLOAT(OFS_PARM0) = 0;
862                                         prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Ent_Update), "QC function CSQC_Ent_Update is missing");
863                                 }
864                         }
865                 }
866                 PRVM_clientglobaledict(self) = oldself;
867         CSQC_END
868 }
869
870 static void CLVM_begin_increase_edicts(prvm_prog_t *prog)
871 {
872         // links don't survive the transition, so unlink everything
873         World_UnlinkAll(&cl.world);
874 }
875
876 static void CLVM_end_increase_edicts(prvm_prog_t *prog)
877 {
878         int i;
879         prvm_edict_t *ent;
880
881         // link every entity except world
882         for (i = 1, ent = prog->edicts;i < prog->num_edicts;i++, ent++)
883                 if (!ent->priv.server->free)
884                         CL_LinkEdict(ent);
885 }
886
887 static void CLVM_init_edict(prvm_prog_t *prog, prvm_edict_t *e)
888 {
889         int edictnum = PRVM_NUM_FOR_EDICT(e);
890         entity_render_t *entrender;
891         CL_ExpandCSQCRenderEntities(edictnum);
892         entrender = cl.csqcrenderentities + edictnum;
893         e->priv.server->move = false; // don't move on first frame
894         memset(entrender, 0, sizeof(*entrender));
895         entrender->shadertime = cl.time;
896 }
897
898 static void CLVM_free_edict(prvm_prog_t *prog, prvm_edict_t *ed)
899 {
900         entity_render_t *entrender = cl.csqcrenderentities + PRVM_NUM_FOR_EDICT(ed);
901         R_DecalSystem_Reset(&entrender->decalsystem);
902         memset(entrender, 0, sizeof(*entrender));
903         World_UnlinkEdict(ed);
904         memset(ed->fields.fp, 0, prog->entityfields * sizeof(prvm_vec_t));
905         VM_RemoveEdictSkeleton(prog, ed);
906         World_Physics_RemoveFromEntity(&cl.world, ed);
907         World_Physics_RemoveJointFromEntity(&cl.world, ed);
908 }
909
910 static void CLVM_count_edicts(prvm_prog_t *prog)
911 {
912         int             i;
913         prvm_edict_t    *ent;
914         int             active = 0, models = 0, solid = 0;
915
916         for (i=0 ; i<prog->num_edicts ; i++)
917         {
918                 ent = PRVM_EDICT_NUM(i);
919                 if (ent->priv.server->free)
920                         continue;
921                 active++;
922                 if (PRVM_clientedictfloat(ent, solid))
923                         solid++;
924                 if (PRVM_clientedictstring(ent, model))
925                         models++;
926         }
927
928         Con_Printf("num_edicts:%3i\n", prog->num_edicts);
929         Con_Printf("active    :%3i\n", active);
930         Con_Printf("view      :%3i\n", models);
931         Con_Printf("touch     :%3i\n", solid);
932 }
933
934 static qboolean CLVM_load_edict(prvm_prog_t *prog, prvm_edict_t *ent)
935 {
936         return true;
937 }
938
939 // returns true if the packet is valid, false if end of file is reached
940 // used for dumping the CSQC download into demo files
941 qboolean MakeDownloadPacket(const char *filename, unsigned char *data, size_t len, int crc, int cnt, sizebuf_t *buf, int protocol)
942 {
943         int packetsize = buf->maxsize - 7; // byte short long
944         int npackets = (len + packetsize - 1) / (packetsize);
945         char vabuf[1024];
946
947         if(protocol == PROTOCOL_QUAKEWORLD)
948                 return false; // CSQC can't run in QW anyway
949
950         SZ_Clear(buf);
951         if(cnt == 0)
952         {
953                 MSG_WriteByte(buf, svc_stufftext);
954                 MSG_WriteString(buf, va(vabuf, sizeof(vabuf), "\ncl_downloadbegin %lu %s\n", (unsigned long)len, filename));
955                 return true;
956         }
957         else if(cnt >= 1 && cnt <= npackets)
958         {
959                 unsigned long thispacketoffset = (cnt - 1) * packetsize;
960                 int thispacketsize = len - thispacketoffset;
961                 if(thispacketsize > packetsize)
962                         thispacketsize = packetsize;
963
964                 MSG_WriteByte(buf, svc_downloaddata);
965                 MSG_WriteLong(buf, thispacketoffset);
966                 MSG_WriteShort(buf, thispacketsize);
967                 SZ_Write(buf, data + thispacketoffset, thispacketsize);
968
969                 return true;
970         }
971         else if(cnt == npackets + 1)
972         {
973                 MSG_WriteByte(buf, svc_stufftext);
974                 MSG_WriteString(buf, va(vabuf, sizeof(vabuf), "\ncl_downloadfinished %lu %d\n", (unsigned long)len, crc));
975                 return true;
976         }
977         return false;
978 }
979
980 extern cvar_t csqc_usedemoprogs;
981 void CL_VM_Init (void)
982 {
983         prvm_prog_t *prog = CLVM_prog;
984         const char* csprogsfn = NULL;
985         unsigned char *csprogsdata = NULL;
986         fs_offset_t csprogsdatasize = 0;
987         int csprogsdatacrc, requiredcrc;
988         int requiredsize;
989         char vabuf[1024];
990
991         // reset csqc_progcrc after reading it, so that changing servers doesn't
992         // expect csqc on the next server
993         requiredcrc = csqc_progcrc.integer;
994         requiredsize = csqc_progsize.integer;
995         Cvar_SetValueQuick(&csqc_progcrc, -1);
996         Cvar_SetValueQuick(&csqc_progsize, -1);
997
998         // if the server is not requesting a csprogs, then we're done here
999         if (requiredcrc < 0)
1000                 return;
1001
1002         // see if the requested csprogs.dat file matches the requested crc
1003         if (!cls.demoplayback || csqc_usedemoprogs.integer)
1004         {
1005                 csprogsfn = va(vabuf, sizeof(vabuf), "dlcache/%s.%i.%i", csqc_progname.string, requiredsize, requiredcrc);
1006                 if(cls.caughtcsprogsdata && cls.caughtcsprogsdatasize == requiredsize && CRC_Block(cls.caughtcsprogsdata, (size_t)cls.caughtcsprogsdatasize) == requiredcrc)
1007                 {
1008                         Con_DPrintf("Using buffered \"%s\"\n", csprogsfn);
1009                         csprogsdata = cls.caughtcsprogsdata;
1010                         csprogsdatasize = cls.caughtcsprogsdatasize;
1011                         cls.caughtcsprogsdata = NULL;
1012                         cls.caughtcsprogsdatasize = 0;
1013                 }
1014                 else
1015                 {
1016                         Con_DPrintf("Not using buffered \"%s\" (buffered: %p, %d)\n", csprogsfn, cls.caughtcsprogsdata, (int) cls.caughtcsprogsdatasize);
1017                         csprogsdata = FS_LoadFile(csprogsfn, tempmempool, true, &csprogsdatasize);
1018                 }
1019         }
1020         if (!csprogsdata)
1021         {
1022                 csprogsfn = csqc_progname.string;
1023                 csprogsdata = FS_LoadFile(csprogsfn, tempmempool, true, &csprogsdatasize);
1024         }
1025         if (csprogsdata)
1026         {
1027                 csprogsdatacrc = CRC_Block(csprogsdata, (size_t)csprogsdatasize);
1028                 if (csprogsdatacrc != requiredcrc || csprogsdatasize != requiredsize)
1029                 {
1030                         if (cls.demoplayback)
1031                         {
1032                                 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);
1033                                 // Mem_Free(csprogsdata);
1034                                 // return;
1035                                 // We WANT to continue here, and play the demo with different csprogs!
1036                                 // After all, this is just a warning. Sure things may go wrong from here.
1037                         }
1038                         else
1039                         {
1040                                 Mem_Free(csprogsdata);
1041                                 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);
1042                                 CL_Disconnect();
1043                                 return;
1044                         }
1045                 }
1046         }
1047         else
1048         {
1049                 if (requiredcrc >= 0)
1050                 {
1051                         if (cls.demoplayback)
1052                                 Con_Printf("CL_VM_Init: demo requires CSQC, but \"%s\" wasn't found\n", csqc_progname.string);
1053                         else
1054                                 Con_Printf("CL_VM_Init: server requires CSQC, but \"%s\" wasn't found\n", csqc_progname.string);
1055                         CL_Disconnect();
1056                 }
1057                 return;
1058         }
1059
1060         PRVM_Prog_Init(prog);
1061
1062         // allocate the mempools
1063         prog->progs_mempool = Mem_AllocPool(csqc_progname.string, 0, NULL);
1064         prog->edictprivate_size = 0; // no private struct used
1065         prog->name = "client";
1066         prog->num_edicts = 1;
1067         prog->max_edicts = 512;
1068         prog->limit_edicts = CL_MAX_EDICTS;
1069         prog->reserved_edicts = 0;
1070         prog->edictprivate_size = sizeof(edict_engineprivate_t);
1071         // TODO: add a shared extension string #define and add real support for csqc extension strings [12/5/2007 Black]
1072         prog->extensionstring = vm_sv_extensions;
1073         prog->builtins = vm_cl_builtins;
1074         prog->numbuiltins = vm_cl_numbuiltins;
1075
1076         // all callbacks must be defined (pointers are not checked before calling)
1077         prog->begin_increase_edicts = CLVM_begin_increase_edicts;
1078         prog->end_increase_edicts   = CLVM_end_increase_edicts;
1079         prog->init_edict            = CLVM_init_edict;
1080         prog->free_edict            = CLVM_free_edict;
1081         prog->count_edicts          = CLVM_count_edicts;
1082         prog->load_edict            = CLVM_load_edict;
1083         prog->init_cmd              = CLVM_init_cmd;
1084         prog->reset_cmd             = CLVM_reset_cmd;
1085         prog->error_cmd             = Host_Error;
1086         prog->ExecuteProgram        = CLVM_ExecuteProgram;
1087
1088         PRVM_Prog_Load(prog, csprogsfn, csprogsdata, csprogsdatasize, cl_numrequiredfunc, cl_required_func, CL_REQFIELDS, cl_reqfields, CL_REQGLOBALS, cl_reqglobals);
1089
1090         if (!prog->loaded)
1091         {
1092                 Host_Error("CSQC %s ^2failed to load\n", csprogsfn);
1093                 if(!sv.active)
1094                         CL_Disconnect();
1095                 Mem_Free(csprogsdata);
1096                 return;
1097         }
1098
1099         Con_DPrintf("CSQC %s ^5loaded (crc=%i, size=%i)\n", csprogsfn, csprogsdatacrc, (int)csprogsdatasize);
1100
1101         if(cls.demorecording)
1102         {
1103                 if(cls.demo_lastcsprogssize != csprogsdatasize || cls.demo_lastcsprogscrc != csprogsdatacrc)
1104                 {
1105                         int i;
1106                         static char buf[NET_MAXMESSAGE];
1107                         sizebuf_t sb;
1108                         unsigned char *demobuf; fs_offset_t demofilesize;
1109
1110                         sb.data = (unsigned char *) buf;
1111                         sb.maxsize = sizeof(buf);
1112                         i = 0;
1113
1114                         CL_CutDemo(&demobuf, &demofilesize);
1115                         while(MakeDownloadPacket(csqc_progname.string, csprogsdata, (size_t)csprogsdatasize, csprogsdatacrc, i++, &sb, cls.protocol))
1116                                 CL_WriteDemoMessage(&sb);
1117                         CL_PasteDemo(&demobuf, &demofilesize);
1118
1119                         cls.demo_lastcsprogssize = csprogsdatasize;
1120                         cls.demo_lastcsprogscrc = csprogsdatacrc;
1121                 }
1122         }
1123         Mem_Free(csprogsdata);
1124
1125         // check if OP_STATE animation is possible in this dat file
1126         if (prog->fieldoffsets.nextthink >= 0 && prog->fieldoffsets.frame >= 0 && prog->fieldoffsets.think >= 0 && prog->globaloffsets.self >= 0)
1127                 prog->flag |= PRVM_OP_STATE;
1128
1129         // set time
1130         PRVM_clientglobalfloat(time) = cl.time;
1131         PRVM_clientglobaledict(self) = 0;
1132
1133         PRVM_clientglobalstring(mapname) = PRVM_SetEngineString(prog, cl.worldname);
1134         PRVM_clientglobalfloat(player_localnum) = cl.realplayerentity - 1;
1135         PRVM_clientglobalfloat(player_localentnum) = cl.viewentity;
1136
1137         // set map description (use world entity 0)
1138         PRVM_clientedictstring(prog->edicts, message) = PRVM_SetEngineString(prog, cl.worldmessage);
1139         VectorCopy(cl.world.mins, PRVM_clientedictvector(prog->edicts, mins));
1140         VectorCopy(cl.world.maxs, PRVM_clientedictvector(prog->edicts, maxs));
1141
1142         // call the prog init
1143         prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Init), "QC function CSQC_Init is missing");
1144
1145         cl.csqc_loaded = true;
1146
1147         cl.csqc_vidvars.drawcrosshair = false;
1148         cl.csqc_vidvars.drawenginesbar = false;
1149
1150         // Update Coop and Deathmatch Globals (at this point the client knows them from ServerInfo)
1151         CL_VM_UpdateCoopDeathmatchGlobals(cl.gametype);
1152 }
1153
1154 void CL_VM_ShutDown (void)
1155 {
1156         prvm_prog_t *prog = CLVM_prog;
1157         Cmd_ClearCsqcFuncs();
1158         //Cvar_SetValueQuick(&csqc_progcrc, -1);
1159         //Cvar_SetValueQuick(&csqc_progsize, -1);
1160         if(!cl.csqc_loaded)
1161                 return;
1162         CSQC_BEGIN
1163                 if (prog->loaded)
1164                 {
1165                         PRVM_clientglobalfloat(time) = cl.time;
1166                         PRVM_clientglobaledict(self) = 0;
1167                         if (PRVM_clientfunction(CSQC_Shutdown))
1168                                 prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Shutdown), "QC function CSQC_Shutdown is missing");
1169                 }
1170                 PRVM_Prog_Reset(prog);
1171         CSQC_END
1172         Con_DPrint("CSQC ^1unloaded\n");
1173         cl.csqc_loaded = false;
1174 }
1175
1176 qboolean CL_VM_GetEntitySoundOrigin(int entnum, vec3_t out)
1177 {
1178         prvm_prog_t *prog = CLVM_prog;
1179         prvm_edict_t *ed;
1180         dp_model_t *mod;
1181         matrix4x4_t matrix;
1182         qboolean r = 0;
1183
1184         CSQC_BEGIN;
1185
1186         // FIXME consider attachments here!
1187
1188         ed = PRVM_EDICT_NUM(entnum - MAX_EDICTS);
1189
1190         if(!ed->priv.required->free)
1191         {
1192                 mod = CL_GetModelFromEdict(ed);
1193                 VectorCopy(PRVM_clientedictvector(ed, origin), out);
1194                 if(CL_GetTagMatrix(prog, &matrix, ed, 0) == 0)
1195                         Matrix4x4_OriginFromMatrix(&matrix, out);
1196                 if (mod && mod->soundfromcenter)
1197                         VectorMAMAM(1.0f, out, 0.5f, mod->normalmins, 0.5f, mod->normalmaxs, out);
1198                 r = 1;
1199         }
1200
1201         CSQC_END;
1202
1203         return r;
1204 }
1205
1206 qboolean CL_VM_TransformView(int entnum, matrix4x4_t *viewmatrix, mplane_t *clipplane, vec3_t visorigin)
1207 {
1208         prvm_prog_t *prog = CLVM_prog;
1209         qboolean ret = false;
1210         prvm_edict_t *ed;
1211         vec3_t forward, left, up, origin, ang;
1212         matrix4x4_t mat, matq;
1213
1214         CSQC_BEGIN
1215                 ed = PRVM_EDICT_NUM(entnum);
1216                 // camera:
1217                 //   camera_transform
1218                 if(PRVM_clientedictfunction(ed, camera_transform))
1219                 {
1220                         ret = true;
1221                         if(viewmatrix || clipplane || visorigin)
1222                         {
1223                                 Matrix4x4_ToVectors(viewmatrix, forward, left, up, origin);
1224                                 AnglesFromVectors(ang, forward, up, false);
1225                                 PRVM_clientglobalfloat(time) = cl.time;
1226                                 PRVM_clientglobaledict(self) = entnum;
1227                                 VectorCopy(origin, PRVM_G_VECTOR(OFS_PARM0));
1228                                 VectorCopy(ang, PRVM_G_VECTOR(OFS_PARM1));
1229                                 VectorCopy(forward, PRVM_clientglobalvector(v_forward));
1230                                 VectorScale(left, -1, PRVM_clientglobalvector(v_right));
1231                                 VectorCopy(up, PRVM_clientglobalvector(v_up));
1232                                 VectorCopy(origin, PRVM_clientglobalvector(trace_endpos));
1233                                 prog->ExecuteProgram(prog, PRVM_clientedictfunction(ed, camera_transform), "QC function e.camera_transform is missing");
1234                                 VectorCopy(PRVM_G_VECTOR(OFS_RETURN), origin);
1235                                 VectorCopy(PRVM_clientglobalvector(v_forward), forward);
1236                                 VectorScale(PRVM_clientglobalvector(v_right), -1, left);
1237                                 VectorCopy(PRVM_clientglobalvector(v_up), up);
1238                                 VectorCopy(PRVM_clientglobalvector(trace_endpos), visorigin);
1239                                 Matrix4x4_Invert_Full(&mat, viewmatrix);
1240                                 Matrix4x4_FromVectors(viewmatrix, forward, left, up, origin);
1241                                 Matrix4x4_Concat(&matq, viewmatrix, &mat);
1242                                 Matrix4x4_TransformPositivePlane(&matq, clipplane->normal[0], clipplane->normal[1], clipplane->normal[2], clipplane->dist, &clipplane->normal[0]);
1243                         }
1244                 }
1245         CSQC_END
1246
1247         return ret;
1248 }
1249
1250 int CL_VM_GetViewEntity(void)
1251 {
1252         if(cl.csqc_server2csqcentitynumber[cl.viewentity])
1253                 return cl.csqc_server2csqcentitynumber[cl.viewentity] + MAX_EDICTS;
1254         return cl.viewentity;
1255 }