model_shared: Avoid Mod_MakeSortedSurfaces if dedicated. Fixes crash.
[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(cltime) = host.realtime; // Spike named it that way.
231                 PRVM_clientglobalfloat(frametime) = frametime;
232                 PRVM_clientglobalfloat(servercommandframe) = cls.servermovesequence;
233                 PRVM_clientglobalfloat(clientcommandframe) = cl.movecmd[0].sequence;
234                 VectorCopy(cl.viewangles, PRVM_clientglobalvector(input_angles));
235                 // // FIXME: this actually belongs into getinputstate().. [12/17/2007 Black]
236                 PRVM_clientglobalfloat(input_buttons) = cl.movecmd[0].buttons;
237                 VectorSet(PRVM_clientglobalvector(input_movevalues), cl.movecmd[0].forwardmove, cl.movecmd[0].sidemove, cl.movecmd[0].upmove);
238                 VectorCopy(cl.csqc_vieworiginfromengine, cl.csqc_vieworigin);
239                 VectorCopy(cl.csqc_viewanglesfromengine, cl.csqc_viewangles);
240
241                 // LadyHavoc: Spike says not to do this, but without pmove_org the
242                 // CSQC is useless as it can't alter the view origin without
243                 // completely replacing it
244                 Matrix4x4_OriginFromMatrix(&cl.entities[cl.viewentity].render.matrix, pmove_org);
245                 VectorCopy(pmove_org, PRVM_clientglobalvector(pmove_org));
246                 VectorCopy(cl.movement_velocity, PRVM_clientglobalvector(pmove_vel));
247                 PRVM_clientglobalfloat(pmove_onground) = cl.onground;
248                 PRVM_clientglobalfloat(pmove_inwater) = cl.inwater;
249
250                 VectorCopy(cl.viewangles, PRVM_clientglobalvector(view_angles));
251                 VectorCopy(cl.punchangle, PRVM_clientglobalvector(view_punchangle));
252                 VectorCopy(cl.punchvector, PRVM_clientglobalvector(view_punchvector));
253                 PRVM_clientglobalfloat(maxclients) = cl.maxclients;
254
255                 PRVM_clientglobalfloat(player_localentnum) = cl.viewentity;
256
257                 CSQC_R_RecalcView();
258         CSQC_END
259 }
260
261 void CSQC_Predraw (prvm_edict_t *ed)
262 {
263         prvm_prog_t *prog = CLVM_prog;
264         int b;
265         if(!PRVM_clientedictfunction(ed, predraw))
266                 return;
267         b = PRVM_clientglobaledict(self);
268         PRVM_clientglobaledict(self) = PRVM_EDICT_TO_PROG(ed);
269         prog->ExecuteProgram(prog, PRVM_clientedictfunction(ed, predraw), "CSQC_Predraw: NULL function\n");
270         PRVM_clientglobaledict(self) = b;
271 }
272
273 void CSQC_Think (prvm_edict_t *ed)
274 {
275         prvm_prog_t *prog = CLVM_prog;
276         int b;
277         if(PRVM_clientedictfunction(ed, think))
278         if(PRVM_clientedictfloat(ed, nextthink) && PRVM_clientedictfloat(ed, nextthink) <= PRVM_clientglobalfloat(time))
279         {
280                 PRVM_clientedictfloat(ed, nextthink) = 0;
281                 b = PRVM_clientglobaledict(self);
282                 PRVM_clientglobaledict(self) = PRVM_EDICT_TO_PROG(ed);
283                 prog->ExecuteProgram(prog, PRVM_clientedictfunction(ed, think), "CSQC_Think: NULL function\n");
284                 PRVM_clientglobaledict(self) = b;
285         }
286 }
287
288 extern cvar_t cl_noplayershadow;
289 qbool 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         model_t *model;
297         prvm_vec3_t modellight_origin;
298
299         model = CL_GetModelFromEdict(ed);
300         if (!model)
301                 return false;
302
303         if (edictnum)
304         {
305                 if (r_refdef.scene.numentities >= r_refdef.scene.maxentities)
306                         return false;
307                 entrender = cl.csqcrenderentities + edictnum;
308                 r_refdef.scene.entities[r_refdef.scene.numentities++] = entrender;
309                 entrender->entitynumber = edictnum + MAX_EDICTS;
310                 //entrender->shadertime = 0; // shadertime was set by spawn()
311                 entrender->flags = 0;
312                 entrender->effects = 0;
313                 entrender->alpha = 1;
314                 entrender->scale = 1;
315                 VectorSet(entrender->colormod, 1, 1, 1);
316                 VectorSet(entrender->glowmod, 1, 1, 1);
317                 entrender->allowdecals = true;
318         }
319         else
320         {
321                 entrender = CL_NewTempEntity(0);
322                 if (!entrender)
323                         return false;
324         }
325
326         entrender->userwavefunc_param[0] = PRVM_clientedictfloat(ed, userwavefunc_param0);
327         entrender->userwavefunc_param[1] = PRVM_clientedictfloat(ed, userwavefunc_param1);
328         entrender->userwavefunc_param[2] = PRVM_clientedictfloat(ed, userwavefunc_param2);
329         entrender->userwavefunc_param[3] = PRVM_clientedictfloat(ed, userwavefunc_param3);
330
331         entrender->model = model;
332         entrender->skinnum = (int)PRVM_clientedictfloat(ed, skin);
333         entrender->effects |= entrender->model->effects;
334         renderflags = (int)PRVM_clientedictfloat(ed, renderflags);
335         entrender->alpha = PRVM_clientedictfloat(ed, alpha);
336         entrender->scale = scale = PRVM_clientedictfloat(ed, scale);
337         VectorCopy(PRVM_clientedictvector(ed, colormod), entrender->colormod);
338         VectorCopy(PRVM_clientedictvector(ed, glowmod), entrender->glowmod);
339         if(PRVM_clientedictfloat(ed, effects))  entrender->effects |= (int)PRVM_clientedictfloat(ed, effects);
340         if (!entrender->alpha)
341                 entrender->alpha = 1.0f;
342         if (!entrender->scale)
343                 entrender->scale = scale = 1.0f;
344         if (!VectorLength2(entrender->colormod))
345                 VectorSet(entrender->colormod, 1, 1, 1);
346         if (!VectorLength2(entrender->glowmod))
347                 VectorSet(entrender->glowmod, 1, 1, 1);
348
349         // LadyHavoc: use the CL_GetTagMatrix function on self to ensure consistent behavior (duplicate code would be bad)
350         // this also sets the custommodellight_origin for us
351         CL_GetTagMatrix(prog, &entrender->matrix, ed, 0, modellight_origin);
352         VectorCopy(modellight_origin, entrender->custommodellight_origin);
353
354         // set up the animation data
355         VM_GenerateFrameGroupBlend(prog, ed->priv.server->framegroupblend, ed);
356         VM_FrameBlendFromFrameGroupBlend(ed->priv.server->frameblend, ed->priv.server->framegroupblend, model, cl.time);
357         VM_UpdateEdictSkeleton(prog, ed, model, ed->priv.server->frameblend);
358         if (PRVM_clientedictfloat(ed, shadertime)) // hack for csprogs.dat files that do not set shadertime, leaves the value at entity spawn time
359                 entrender->shadertime = PRVM_clientedictfloat(ed, shadertime);
360
361         // transparent offset
362         if (renderflags & RF_USETRANSPARENTOFFSET)
363                 entrender->transparent_offset = PRVM_clientglobalfloat(transparent_offset);
364
365         // model light
366         if (renderflags & RF_MODELLIGHT)
367         {
368                 if (PRVM_clientedictvector(ed, modellight_ambient)) VectorCopy(PRVM_clientedictvector(ed, modellight_ambient), entrender->custommodellight_ambient); else VectorClear(entrender->custommodellight_ambient);
369                 if (PRVM_clientedictvector(ed, modellight_diffuse)) VectorCopy(PRVM_clientedictvector(ed, modellight_diffuse), entrender->custommodellight_diffuse); else VectorClear(entrender->custommodellight_diffuse);
370                 if (PRVM_clientedictvector(ed, modellight_dir))     VectorCopy(PRVM_clientedictvector(ed, modellight_dir), entrender->custommodellight_lightdir);    else VectorClear(entrender->custommodellight_lightdir);
371                 entrender->flags |= RENDER_CUSTOMIZEDMODELLIGHT;
372         }
373
374         if(renderflags)
375         {
376                 if(renderflags & RF_VIEWMODEL) entrender->flags |= RENDER_VIEWMODEL | RENDER_NODEPTHTEST;
377                 if(renderflags & RF_EXTERNALMODEL) entrender->flags |= RENDER_EXTERIORMODEL;
378                 if(renderflags & RF_WORLDOBJECT) entrender->flags |= RENDER_WORLDOBJECT;
379                 if(renderflags & RF_DEPTHHACK) entrender->flags |= RENDER_NODEPTHTEST;
380                 if(renderflags & RF_ADDITIVE) entrender->flags |= RENDER_ADDITIVE;
381                 if(renderflags & RF_DYNAMICMODELLIGHT) entrender->flags |= RENDER_DYNAMICMODELLIGHT;
382         }
383
384         c = (int)PRVM_clientedictfloat(ed, colormap);
385         if (c <= 0)
386                 CL_SetEntityColormapColors(entrender, -1);
387         else if (c <= cl.maxclients && cl.scores != NULL)
388                 CL_SetEntityColormapColors(entrender, cl.scores[c-1].colors);
389         else
390                 CL_SetEntityColormapColors(entrender, c);
391
392         entrender->flags &= ~(RENDER_SHADOW | RENDER_LIGHT | RENDER_NOSELFSHADOW);
393         // either fullbright or lit
394         if(!r_fullbright.integer)
395         {
396                 if (!(entrender->effects & EF_FULLBRIGHT) && !(renderflags & RF_FULLBRIGHT))
397                         entrender->flags |= RENDER_LIGHT;
398         }
399         // hide player shadow during intermission or nehahra movie
400         if (!(entrender->effects & (EF_NOSHADOW | EF_ADDITIVE | EF_NODEPTHTEST))
401          &&  (entrender->alpha >= 1)
402          && !(renderflags & RF_NOSHADOW)
403          && !(entrender->flags & RENDER_VIEWMODEL)
404          && (!(entrender->flags & RENDER_EXTERIORMODEL) || (!cl.intermission && cls.protocol != PROTOCOL_NEHAHRAMOVIE && !cl_noplayershadow.integer)))
405                 entrender->flags |= RENDER_SHADOW;
406         if (entrender->flags & RENDER_VIEWMODEL)
407                 entrender->flags |= RENDER_NOSELFSHADOW;
408         if (entrender->effects & EF_NOSELFSHADOW)
409                 entrender->flags |= RENDER_NOSELFSHADOW;
410         if (entrender->effects & EF_NODEPTHTEST)
411                 entrender->flags |= RENDER_NODEPTHTEST;
412         if (entrender->effects & EF_ADDITIVE)
413                 entrender->flags |= RENDER_ADDITIVE;
414         if (entrender->effects & EF_DOUBLESIDED)
415                 entrender->flags |= RENDER_DOUBLESIDED;
416         if (entrender->effects & EF_DYNAMICMODELLIGHT)
417                 entrender->flags |= RENDER_DYNAMICMODELLIGHT;
418
419         // make the other useful stuff
420         memcpy(entrender->framegroupblend, ed->priv.server->framegroupblend, sizeof(ed->priv.server->framegroupblend));
421         CL_UpdateRenderEntity(entrender);
422
423         // override animation data with full control
424         memcpy(entrender->frameblend, ed->priv.server->frameblend, sizeof(ed->priv.server->frameblend));
425         if (ed->priv.server->skeleton.relativetransforms)
426                 entrender->skeleton = &ed->priv.server->skeleton;
427         else
428                 entrender->skeleton = NULL;
429
430         return true;
431 }
432
433 // 0 = keydown, key, character (EXT_CSQC)
434 // 1 = keyup, key, character (EXT_CSQC)
435 // 2 = mousemove relative, x, y (EXT_CSQC)
436 // 3 = mousemove absolute, x, y (DP_CSQC)
437 qbool CL_VM_InputEvent (int eventtype, float x, float y)
438 {
439         prvm_prog_t *prog = CLVM_prog;
440         qbool r;
441
442         if(!cl.csqc_loaded)
443                 return false;
444
445 CSQC_BEGIN
446         if (!PRVM_clientfunction(CSQC_InputEvent))
447                 r = false;
448         else
449         {
450                 PRVM_clientglobalfloat(time) = cl.time;
451                 PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[cl.playerentity];
452                 PRVM_G_FLOAT(OFS_PARM0) = eventtype;
453                 PRVM_G_FLOAT(OFS_PARM1) = x; // key or x
454                 PRVM_G_FLOAT(OFS_PARM2) = y; // ascii or y
455                 prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_InputEvent), "QC function CSQC_InputEvent is missing");
456                 r = CSQC_RETURNVAL != 0;
457         }
458 CSQC_END
459         return r;
460 }
461
462 extern r_refdef_view_t csqc_original_r_refdef_view;
463 extern r_refdef_view_t csqc_main_r_refdef_view;
464 qbool CL_VM_UpdateView (double frametime)
465 {
466         prvm_prog_t *prog = CLVM_prog;
467         vec3_t emptyvector;
468         emptyvector[0] = 0;
469         emptyvector[1] = 0;
470         emptyvector[2] = 0;
471 //      vec3_t oldangles;
472         if(!cl.csqc_loaded)
473                 return false;
474         R_TimeReport("pre-UpdateView");
475         CSQC_BEGIN
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                 // polygonbegin without draw2d arg has to guess
487                 prog->polygonbegin_guess2d = false;
488                 // free memory for resources that are no longer referenced
489                 PRVM_GarbageCollection(prog);
490                 // pass in width and height and menu/focus state as parameters (EXT_CSQC_1)
491                 PRVM_G_FLOAT(OFS_PARM0) = vid.width;
492                 PRVM_G_FLOAT(OFS_PARM1) = vid.height;
493                 /*
494                  * This should be fine for now but FTEQW uses flags for keydest
495                  * and checks that an array called "eyeoffset" is 0
496                  * 
497                  * Just a note in case there's compatibility problems later
498                  */
499                 PRVM_G_FLOAT(OFS_PARM2) = key_dest == key_game;
500                 prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_UpdateView), "QC function CSQC_UpdateView is missing");
501                 //VectorCopy(oldangles, cl.viewangles);
502                 // Dresk : Reset Dmg Globals Here
503                 CL_VM_UpdateDmgGlobals(0, 0, emptyvector);
504                 r_refdef.view = csqc_main_r_refdef_view;
505                 R_RenderView_UpdateViewVectors(); // we have to do this, as we undid the scene render doing this for us
506         CSQC_END
507
508         R_TimeReport("UpdateView");
509         return true;
510 }
511
512 qbool CL_VM_ConsoleCommand (const char *text)
513 {
514         prvm_prog_t *prog = CLVM_prog;
515         int restorevm_tempstringsbuf_cursize;
516         qbool r = false;
517         if(!cl.csqc_loaded)
518                 return false;
519         CSQC_BEGIN
520         if (PRVM_clientfunction(CSQC_ConsoleCommand))
521         {
522                 PRVM_clientglobalfloat(time) = cl.time;
523                 PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[cl.playerentity];
524                 restorevm_tempstringsbuf_cursize = prog->tempstringsbuf.cursize;
525                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(prog, text);
526                 prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_ConsoleCommand), "QC function CSQC_ConsoleCommand is missing");
527                 prog->tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
528                 r = CSQC_RETURNVAL != 0;
529         }
530         CSQC_END
531         return r;
532 }
533
534 qbool CL_VM_Parse_TempEntity (void)
535 {
536         prvm_prog_t *prog = CLVM_prog;
537         int                     t;
538         qbool   r = false;
539         if(!cl.csqc_loaded)
540                 return false;
541         CSQC_BEGIN
542         if(PRVM_clientfunction(CSQC_Parse_TempEntity))
543         {
544                 t = cl_message.readcount;
545                 PRVM_clientglobalfloat(time) = cl.time;
546                 PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[cl.playerentity];
547                 prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Parse_TempEntity), "QC function CSQC_Parse_TempEntity is missing");
548                 r = CSQC_RETURNVAL != 0;
549                 if(!r)
550                 {
551                         cl_message.readcount = t;
552                         cl_message.badread = false;
553                 }
554         }
555         CSQC_END
556         return r;
557 }
558
559 void CL_VM_Parse_StuffCmd (const char *msg)
560 {
561         prvm_prog_t *prog = CLVM_prog;
562         int restorevm_tempstringsbuf_cursize;
563         if(msg[0] == 'c')
564         if(msg[1] == 's')
565         if(msg[2] == 'q')
566         if(msg[3] == 'c')
567         {
568                 // if this is setting a csqc variable, deprotect csqc_progcrc
569                 // temporarily so that it can be set by the cvar command,
570                 // and then reprotect it afterwards
571                 int crcflags = csqc_progcrc.flags;
572                 csqc_progcrc.flags &= ~CF_READONLY;
573                 csqc_progsize.flags &= ~CF_READONLY;
574                 Cmd_ExecuteString(&cmd_client, msg, src_local, true);
575                 csqc_progcrc.flags = csqc_progsize.flags = crcflags;
576                 return;
577         }
578
579         if(cls.demoplayback)
580         if(!strncmp(msg, "curl --clear_autodownload\ncurl --pak --forthismap --as ", 55))
581         {
582                 // special handling for map download commands
583                 // run these commands IMMEDIATELY, instead of waiting for a client frame
584                 // that way, there is no black screen when playing back demos
585                 // I know this is a really ugly hack, but I can't think of any better way
586                 // FIXME find the actual CAUSE of this, and make demo playback WAIT
587                 // until all maps are loaded, then remove this hack
588
589                 char buf[MAX_INPUTLINE];
590                 const char *p, *q;
591                 size_t l;
592
593                 p = msg;
594
595                 for(;;)
596                 {
597                         q = strchr(p, '\n');
598                         if(q)
599                                 l = q - p;
600                         else
601                                 l = strlen(p);
602                         if(l > sizeof(buf) - 1)
603                                 l = sizeof(buf) - 1;
604                         strlcpy(buf, p, l + 1); // strlcpy needs a + 1 as it includes the newline!
605
606                         Cmd_ExecuteString(&cmd_client, buf, src_local, true);
607
608                         p += l;
609                         if(*p == '\n')
610                                 ++p; // skip the newline and continue
611                         else
612                                 break; // end of string or overflow
613                 }
614                 Cmd_ExecuteString(&cmd_client, "curl --clear_autodownload", src_local, true); // don't inhibit CSQC loading
615                 return;
616         }
617
618         if(!cl.csqc_loaded)
619         {
620                 Cbuf_AddText(&cmd_client, msg);
621                 return;
622         }
623         CSQC_BEGIN
624         if(PRVM_clientfunction(CSQC_Parse_StuffCmd))
625         {
626                 PRVM_clientglobalfloat(time) = cl.time;
627                 PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[cl.playerentity];
628                 restorevm_tempstringsbuf_cursize = prog->tempstringsbuf.cursize;
629                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(prog, msg);
630                 prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Parse_StuffCmd), "QC function CSQC_Parse_StuffCmd is missing");
631                 prog->tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
632         }
633         else
634                 Cbuf_AddText(&cmd_client, msg);
635         CSQC_END
636 }
637
638 static void CL_VM_Parse_Print (const char *msg)
639 {
640         prvm_prog_t *prog = CLVM_prog;
641         int restorevm_tempstringsbuf_cursize;
642         PRVM_clientglobalfloat(time) = cl.time;
643         PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[cl.playerentity];
644         restorevm_tempstringsbuf_cursize = prog->tempstringsbuf.cursize;
645         PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(prog, msg);
646         prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Parse_Print), "QC function CSQC_Parse_Print is missing");
647         prog->tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
648 }
649
650 void CSQC_AddPrintText (const char *msg)
651 {
652         prvm_prog_t *prog = CLVM_prog;
653         size_t i;
654         CSQC_BEGIN
655         if(cl.csqc_loaded && PRVM_clientfunction(CSQC_Parse_Print))
656         {
657                 // FIXME: is this bugged?
658                 i = strlen(msg)-1;
659                 if(msg[i] != '\n' && msg[i] != '\r')
660                 {
661                         if(strlen(cl.csqc_printtextbuf)+i >= MAX_INPUTLINE)
662                         {
663                                 CL_VM_Parse_Print(cl.csqc_printtextbuf);
664                                 cl.csqc_printtextbuf[0] = 0;
665                         }
666                         else
667                                 strlcat(cl.csqc_printtextbuf, msg, MAX_INPUTLINE);
668                         return;
669                 }
670                 strlcat(cl.csqc_printtextbuf, msg, MAX_INPUTLINE);
671                 CL_VM_Parse_Print(cl.csqc_printtextbuf);
672                 cl.csqc_printtextbuf[0] = 0;
673         }
674         else
675                 Con_Print(msg);
676         CSQC_END
677 }
678
679 void CL_VM_Parse_CenterPrint (const char *msg)
680 {
681         prvm_prog_t *prog = CLVM_prog;
682         int restorevm_tempstringsbuf_cursize;
683         CSQC_BEGIN
684         if(cl.csqc_loaded && PRVM_clientfunction(CSQC_Parse_CenterPrint))
685         {
686                 PRVM_clientglobalfloat(time) = cl.time;
687                 PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[cl.playerentity];
688                 restorevm_tempstringsbuf_cursize = prog->tempstringsbuf.cursize;
689                 PRVM_G_INT(OFS_PARM0) = PRVM_SetTempString(prog, msg);
690                 prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Parse_CenterPrint), "QC function CSQC_Parse_CenterPrint is missing");
691                 prog->tempstringsbuf.cursize = restorevm_tempstringsbuf_cursize;
692         }
693         else
694                 SCR_CenterPrint(msg);
695         CSQC_END
696 }
697
698 void CL_VM_UpdateIntermissionState (int intermission)
699 {
700         prvm_prog_t *prog = CLVM_prog;
701         if(cl.csqc_loaded)
702         {
703                 CSQC_BEGIN
704                 PRVM_clientglobalfloat(intermission) = intermission;
705                 CSQC_END
706         }
707 }
708 void CL_VM_UpdateShowingScoresState (int showingscores)
709 {
710         prvm_prog_t *prog = CLVM_prog;
711         if(cl.csqc_loaded)
712         {
713                 CSQC_BEGIN
714                 PRVM_clientglobalfloat(sb_showscores) = showingscores;
715                 CSQC_END
716         }
717 }
718 qbool CL_VM_Event_Sound(int sound_num, float fvolume, int channel, float attenuation, int ent, vec3_t pos, int flags, float speed)
719 {
720         prvm_prog_t *prog = CLVM_prog;
721         qbool r = false;
722         if(cl.csqc_loaded)
723         {
724                 CSQC_BEGIN
725                 if(PRVM_clientfunction(CSQC_Event_Sound))
726                 {
727                         PRVM_clientglobalfloat(time) = cl.time;
728                         PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[cl.playerentity];
729                         PRVM_G_FLOAT(OFS_PARM0) = ent;
730                         PRVM_G_FLOAT(OFS_PARM1) = CHAN_ENGINE2USER(channel);
731                         PRVM_G_INT(OFS_PARM2) = PRVM_SetTempString(prog, cl.sound_name[sound_num] );
732                         PRVM_G_FLOAT(OFS_PARM3) = fvolume;
733                         PRVM_G_FLOAT(OFS_PARM4) = attenuation;
734                         VectorCopy(pos, PRVM_G_VECTOR(OFS_PARM5) );
735                         PRVM_G_FLOAT(OFS_PARM6) = speed * 100.0f;
736                         PRVM_G_FLOAT(OFS_PARM7) = flags; // flags
737                         prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Event_Sound), "QC function CSQC_Event_Sound is missing");
738                         r = CSQC_RETURNVAL != 0;
739                 }
740                 CSQC_END
741         }
742
743         return r;
744 }
745 static void CL_VM_UpdateCoopDeathmatchGlobals (int gametype)
746 {
747         prvm_prog_t *prog = CLVM_prog;
748         // Avoid global names for clean(er) coding
749         int localcoop;
750         int localdeathmatch;
751
752         if(cl.csqc_loaded)
753         {
754                 if(gametype == GAME_COOP)
755                 {
756                         localcoop = 1;
757                         localdeathmatch = 0;
758                 }
759                 else
760                 if(gametype == GAME_DEATHMATCH)
761                 {
762                         localcoop = 0;
763                         localdeathmatch = 1;
764                 }
765                 else
766                 {
767                         // How did the ServerInfo send an unknown gametype?
768                         // Better just assign the globals as 0...
769                         localcoop = 0;
770                         localdeathmatch = 0;
771                 }
772                 CSQC_BEGIN
773                 PRVM_clientglobalfloat(coop) = localcoop;
774                 PRVM_clientglobalfloat(deathmatch) = localdeathmatch;
775                 CSQC_END
776         }
777 }
778 #if 0
779 static float CL_VM_Event (float event)          //[515]: needed ? I'd say "YES", but don't know for what :D
780 {
781         prvm_prog_t *prog = CLVM_prog;
782         float r = 0;
783         if(!cl.csqc_loaded)
784                 return 0;
785         CSQC_BEGIN
786         if(PRVM_clientfunction(CSQC_Event))
787         {
788                 PRVM_clientglobalfloat(time) = cl.time;
789                 PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[cl.playerentity];
790                 PRVM_G_FLOAT(OFS_PARM0) = event;
791                 prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Event), "QC function CSQC_Event is missing");
792                 r = CSQC_RETURNVAL;
793         }
794         CSQC_END
795         return r;
796 }
797 #endif
798
799 void CSQC_ReadEntities (void)
800 {
801         prvm_prog_t *prog = CLVM_prog;
802         unsigned short entnum, oldself, realentnum;
803         if(!cl.csqc_loaded)
804         {
805                 Host_Error ("CSQC_ReadEntities: CSQC is not loaded");
806                 return;
807         }
808
809         CSQC_BEGIN
810                 PRVM_clientglobalfloat(time) = cl.time;
811                 oldself = PRVM_clientglobaledict(self);
812                 while(1)
813                 {
814                         entnum = MSG_ReadShort(&cl_message);
815                         if(!entnum || cl_message.badread)
816                                 break;
817                         realentnum = entnum & 0x7FFF;
818                         PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[realentnum];
819                         if(entnum & 0x8000)
820                         {
821                                 if(PRVM_clientglobaledict(self))
822                                 {
823                                         prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Ent_Remove), "QC function CSQC_Ent_Remove is missing");
824                                         cl.csqc_server2csqcentitynumber[realentnum] = 0;
825                                 }
826                                 else
827                                 {
828                                         // LadyHavoc: removing an entity that is already gone on
829                                         // the csqc side is possible for legitimate reasons (such
830                                         // as a repeat of the remove message), so no warning is
831                                         // needed
832                                         //Con_Printf("Bad csqc_server2csqcentitynumber map\n"); //[515]: never happens ?
833                                 }
834                         }
835                         else
836                         {
837                                 if(!PRVM_clientglobaledict(self))
838                                 {
839                                         if(!PRVM_clientfunction(CSQC_Ent_Spawn))
840                                         {
841                                                 prvm_edict_t    *ed;
842                                                 ed = PRVM_ED_Alloc(prog);
843                                                 PRVM_clientedictfloat(ed, entnum) = realentnum;
844                                                 PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[realentnum] = PRVM_EDICT_TO_PROG(ed);
845                                         }
846                                         else
847                                         {
848                                                 // entity( float entnum ) CSQC_Ent_Spawn;
849                                                 // the qc function should set entnum, too (this way it also can return world [2/1/2008 Andreas]
850                                                 PRVM_G_FLOAT(OFS_PARM0) = (float) realentnum;
851                                                 // make sure no one gets wrong ideas
852                                                 PRVM_clientglobaledict(self) = 0;
853                                                 prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Ent_Spawn), "QC function CSQC_Ent_Spawn is missing");
854                                                 PRVM_clientglobaledict(self) = cl.csqc_server2csqcentitynumber[realentnum] = PRVM_EDICT( PRVM_G_INT( OFS_RETURN ) );
855                                         }
856                                         PRVM_G_FLOAT(OFS_PARM0) = 1;
857                                         prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Ent_Update), "QC function CSQC_Ent_Update is missing");
858                                 }
859                                 else {
860                                         PRVM_G_FLOAT(OFS_PARM0) = 0;
861                                         prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Ent_Update), "QC function CSQC_Ent_Update is missing");
862                                 }
863                         }
864                 }
865                 PRVM_clientglobaledict(self) = oldself;
866         CSQC_END
867 }
868
869 static void CLVM_begin_increase_edicts(prvm_prog_t *prog)
870 {
871         // links don't survive the transition, so unlink everything
872         World_UnlinkAll(&cl.world);
873 }
874
875 static void CLVM_end_increase_edicts(prvm_prog_t *prog)
876 {
877         int i;
878         prvm_edict_t *ent;
879
880         // link every entity except world
881         for (i = 1, ent = prog->edicts;i < prog->num_edicts;i++, ent++)
882                 if (!ent->priv.server->free && !VectorCompare(PRVM_clientedictvector(ent, absmin), PRVM_clientedictvector(ent, absmax)))
883                         CL_LinkEdict(ent);
884 }
885
886 static void CLVM_init_edict(prvm_prog_t *prog, prvm_edict_t *e)
887 {
888         int edictnum = PRVM_NUM_FOR_EDICT(e);
889         entity_render_t *entrender;
890         CL_ExpandCSQCRenderEntities(edictnum);
891         entrender = cl.csqcrenderentities + edictnum;
892         e->priv.server->move = false; // don't move on first frame
893         memset(entrender, 0, sizeof(*entrender));
894         entrender->shadertime = cl.time;
895 }
896
897 static void CLVM_free_edict(prvm_prog_t *prog, prvm_edict_t *ed)
898 {
899         entity_render_t *entrender = cl.csqcrenderentities + PRVM_NUM_FOR_EDICT(ed);
900         R_DecalSystem_Reset(&entrender->decalsystem);
901         memset(entrender, 0, sizeof(*entrender));
902         World_UnlinkEdict(ed);
903         memset(ed->fields.fp, 0, prog->entityfields * sizeof(prvm_vec_t));
904         VM_RemoveEdictSkeleton(prog, ed);
905         World_Physics_RemoveFromEntity(&cl.world, ed);
906         World_Physics_RemoveJointFromEntity(&cl.world, ed);
907 }
908
909 static void CLVM_count_edicts(prvm_prog_t *prog)
910 {
911         int             i;
912         prvm_edict_t    *ent;
913         int             active = 0, models = 0, solid = 0;
914
915         for (i=0 ; i<prog->num_edicts ; i++)
916         {
917                 ent = PRVM_EDICT_NUM(i);
918                 if (ent->priv.server->free)
919                         continue;
920                 active++;
921                 if (PRVM_clientedictfloat(ent, solid))
922                         solid++;
923                 if (PRVM_clientedictstring(ent, model))
924                         models++;
925         }
926
927         Con_Printf("num_edicts:%3i\n", prog->num_edicts);
928         Con_Printf("active    :%3i\n", active);
929         Con_Printf("view      :%3i\n", models);
930         Con_Printf("touch     :%3i\n", solid);
931 }
932
933 static qbool CLVM_load_edict(prvm_prog_t *prog, prvm_edict_t *ent)
934 {
935         return true;
936 }
937
938 // returns true if the packet is valid, false if end of file is reached
939 // used for dumping the CSQC download into demo files
940 qbool MakeDownloadPacket(const char *filename, unsigned char *data, size_t len, int crc, int cnt, sizebuf_t *buf, int protocol)
941 {
942         int packetsize = buf->maxsize - 7; // byte short long
943         int npackets = ((int)len + packetsize - 1) / (packetsize);
944         char vabuf[1024];
945
946         if(protocol == PROTOCOL_QUAKEWORLD)
947                 return false; // CSQC can't run in QW anyway
948
949         SZ_Clear(buf);
950         if(cnt == 0)
951         {
952                 MSG_WriteByte(buf, svc_stufftext);
953                 MSG_WriteString(buf, va(vabuf, sizeof(vabuf), "\ncl_downloadbegin %lu %s\n", (unsigned long)len, filename));
954                 return true;
955         }
956         else if(cnt >= 1 && cnt <= npackets)
957         {
958                 unsigned long thispacketoffset = (cnt - 1) * packetsize;
959                 int thispacketsize = (int)len - thispacketoffset;
960                 if(thispacketsize > packetsize)
961                         thispacketsize = packetsize;
962
963                 MSG_WriteByte(buf, svc_downloaddata);
964                 MSG_WriteLong(buf, thispacketoffset);
965                 MSG_WriteShort(buf, thispacketsize);
966                 SZ_Write(buf, data + thispacketoffset, thispacketsize);
967
968                 return true;
969         }
970         else if(cnt == npackets + 1)
971         {
972                 MSG_WriteByte(buf, svc_stufftext);
973                 MSG_WriteString(buf, va(vabuf, sizeof(vabuf), "\ncl_downloadfinished %lu %d\n", (unsigned long)len, crc));
974                 return true;
975         }
976         return false;
977 }
978
979 extern cvar_t csqc_usedemoprogs;
980 void CL_VM_Init (void)
981 {
982         prvm_prog_t *prog = CLVM_prog;
983         const char* csprogsfn = NULL;
984         unsigned char *csprogsdata = NULL;
985         fs_offset_t csprogsdatasize = 0;
986         int csprogsdatacrc, requiredcrc;
987         int requiredsize;
988         char vabuf[1024];
989
990         // reset csqc_progcrc after reading it, so that changing servers doesn't
991         // expect csqc on the next server
992         requiredcrc = csqc_progcrc.integer;
993         requiredsize = csqc_progsize.integer;
994         Cvar_SetValueQuick(&csqc_progcrc, -1);
995         Cvar_SetValueQuick(&csqc_progsize, -1);
996
997         // if the server is not requesting a csprogs, then we're done here
998         if (requiredcrc < 0)
999                 return;
1000
1001         // see if the requested csprogs.dat file matches the requested crc
1002         if (!cls.demoplayback || csqc_usedemoprogs.integer)
1003         {
1004                 csprogsfn = va(vabuf, sizeof(vabuf), "dlcache/%s.%i.%i", csqc_progname.string, requiredsize, requiredcrc);
1005                 if(cls.caughtcsprogsdata && cls.caughtcsprogsdatasize == requiredsize && CRC_Block(cls.caughtcsprogsdata, (size_t)cls.caughtcsprogsdatasize) == requiredcrc)
1006                 {
1007                         Con_DPrintf("Using buffered \"%s\"\n", csprogsfn);
1008                         csprogsdata = cls.caughtcsprogsdata;
1009                         csprogsdatasize = cls.caughtcsprogsdatasize;
1010                         cls.caughtcsprogsdata = NULL;
1011                         cls.caughtcsprogsdatasize = 0;
1012                 }
1013                 else
1014                 {
1015                         Con_DPrintf("Not using buffered \"%s\" (buffered: %p, %d)\n", csprogsfn, (void *)cls.caughtcsprogsdata, (int) cls.caughtcsprogsdatasize);
1016                         csprogsdata = FS_LoadFile(csprogsfn, tempmempool, true, &csprogsdatasize);
1017                 }
1018         }
1019         if (!csprogsdata)
1020         {
1021                 csprogsfn = csqc_progname.string;
1022                 csprogsdata = FS_LoadFile(csprogsfn, tempmempool, true, &csprogsdatasize);
1023         }
1024         if (csprogsdata)
1025         {
1026                 csprogsdatacrc = CRC_Block(csprogsdata, (size_t)csprogsdatasize);
1027                 if (csprogsdatacrc != requiredcrc || csprogsdatasize != requiredsize)
1028                 {
1029                         if (cls.demoplayback)
1030                         {
1031                                 Con_Printf(CON_WARN "Warning: 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);
1032                                 // Mem_Free(csprogsdata);
1033                                 // return;
1034                                 // We WANT to continue here, and play the demo with different csprogs!
1035                                 // After all, this is just a warning. Sure things may go wrong from here.
1036                         }
1037                         else
1038                         {
1039                                 Mem_Free(csprogsdata);
1040                                 Con_Printf(CON_ERROR "Your %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);
1041                                 CL_Disconnect();
1042                                 return;
1043                         }
1044                 }
1045         }
1046         else
1047         {
1048                 if (requiredcrc >= 0)
1049                 {
1050                         if (cls.demoplayback)
1051                                 Con_Printf(CON_ERROR "CL_VM_Init: demo requires CSQC, but \"%s\" wasn't found\n", csqc_progname.string);
1052                         else
1053                                 Con_Printf(CON_ERROR "CL_VM_Init: server requires CSQC, but \"%s\" wasn't found\n", csqc_progname.string);
1054                         CL_Disconnect();
1055                 }
1056                 return;
1057         }
1058
1059         PRVM_Prog_Init(prog, &cmd_client);
1060
1061         // allocate the mempools
1062         prog->progs_mempool = Mem_AllocPool(csqc_progname.string, 0, NULL);
1063         prog->edictprivate_size = 0; // no private struct used
1064         prog->name = "client";
1065         prog->num_edicts = 1;
1066         prog->max_edicts = 512;
1067         prog->limit_edicts = CL_MAX_EDICTS;
1068         prog->reserved_edicts = 0;
1069         prog->edictprivate_size = sizeof(edict_engineprivate_t);
1070         // TODO: add a shared extension string #define and add real support for csqc extension strings [12/5/2007 Black]
1071         prog->extensionstring = vm_sv_extensions;
1072         prog->builtins = vm_cl_builtins;
1073         prog->numbuiltins = vm_cl_numbuiltins;
1074
1075         // all callbacks must be defined (pointers are not checked before calling)
1076         prog->begin_increase_edicts = CLVM_begin_increase_edicts;
1077         prog->end_increase_edicts   = CLVM_end_increase_edicts;
1078         prog->init_edict            = CLVM_init_edict;
1079         prog->free_edict            = CLVM_free_edict;
1080         prog->count_edicts          = CLVM_count_edicts;
1081         prog->load_edict            = CLVM_load_edict;
1082         prog->init_cmd              = CLVM_init_cmd;
1083         prog->reset_cmd             = CLVM_reset_cmd;
1084         prog->error_cmd             = Host_Error;
1085         prog->ExecuteProgram        = CLVM_ExecuteProgram;
1086
1087         PRVM_Prog_Load(prog, csprogsfn, csprogsdata, csprogsdatasize, cl_numrequiredfunc, cl_required_func, CL_REQFIELDS, cl_reqfields, CL_REQGLOBALS, cl_reqglobals);
1088
1089         if (!prog->loaded)
1090         {
1091                 Host_Error("CSQC %s failed to load\n", csprogsfn);
1092                 if(!sv.active)
1093                         CL_Disconnect();
1094                 Mem_Free(csprogsdata);
1095                 return;
1096         }
1097
1098         if(cls.demorecording)
1099         {
1100                 if(cls.demo_lastcsprogssize != csprogsdatasize || cls.demo_lastcsprogscrc != csprogsdatacrc)
1101                 {
1102                         int i;
1103                         static char buf[NET_MAXMESSAGE];
1104                         sizebuf_t sb;
1105                         unsigned char *demobuf; fs_offset_t demofilesize;
1106
1107                         sb.data = (unsigned char *) buf;
1108                         sb.maxsize = sizeof(buf);
1109                         i = 0;
1110
1111                         CL_CutDemo(&demobuf, &demofilesize);
1112                         while(MakeDownloadPacket(csqc_progname.string, csprogsdata, (size_t)csprogsdatasize, csprogsdatacrc, i++, &sb, cls.protocol))
1113                                 CL_WriteDemoMessage(&sb);
1114                         CL_PasteDemo(&demobuf, &demofilesize);
1115
1116                         cls.demo_lastcsprogssize = csprogsdatasize;
1117                         cls.demo_lastcsprogscrc = csprogsdatacrc;
1118                 }
1119         }
1120         Mem_Free(csprogsdata);
1121
1122         // check if OP_STATE animation is possible in this dat file
1123         if (prog->fieldoffsets.nextthink >= 0 && prog->fieldoffsets.frame >= 0 && prog->fieldoffsets.think >= 0 && prog->globaloffsets.self >= 0)
1124                 prog->flag |= PRVM_OP_STATE;
1125
1126         // set time
1127         PRVM_clientglobalfloat(time) = cl.time;
1128         PRVM_clientglobaledict(self) = 0;
1129
1130         PRVM_clientglobalstring(mapname) = PRVM_SetEngineString(prog, cl.worldname);
1131         PRVM_clientglobalfloat(player_localnum) = cl.realplayerentity - 1;
1132         PRVM_clientglobalfloat(player_localentnum) = cl.viewentity;
1133
1134         // set map description (use world entity 0)
1135         PRVM_clientedictstring(prog->edicts, message) = PRVM_SetEngineString(prog, cl.worldmessage);
1136         VectorCopy(cl.world.mins, PRVM_clientedictvector(prog->edicts, mins));
1137         VectorCopy(cl.world.maxs, PRVM_clientedictvector(prog->edicts, maxs));
1138         VectorCopy(cl.world.mins, PRVM_clientedictvector(prog->edicts, absmin));
1139         VectorCopy(cl.world.maxs, PRVM_clientedictvector(prog->edicts, absmax));
1140
1141         // call the prog init
1142         prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Init), "QC function CSQC_Init is missing");
1143
1144         // Once CSQC_Init was called, we consider csqc code fully initialized.
1145         prog->inittime = host.realtime;
1146
1147         cl.csqc_loaded = true;
1148
1149         cl.csqc_vidvars.drawcrosshair = false;
1150         cl.csqc_vidvars.drawenginesbar = false;
1151
1152         // Update Coop and Deathmatch Globals (at this point the client knows them from ServerInfo)
1153         CL_VM_UpdateCoopDeathmatchGlobals(cl.gametype);
1154 }
1155
1156 void CL_VM_ShutDown (void)
1157 {
1158         prvm_prog_t *prog = CLVM_prog;
1159         Cmd_ClearCSQCCommands(&cmd_client);
1160         //Cvar_SetValueQuick(&csqc_progcrc, -1);
1161         //Cvar_SetValueQuick(&csqc_progsize, -1);
1162         if(!cl.csqc_loaded)
1163                 return;
1164 CSQC_BEGIN
1165         if (prog->loaded)
1166         {
1167                 PRVM_clientglobalfloat(time) = cl.time;
1168                 PRVM_clientglobaledict(self) = 0;
1169                 if (PRVM_clientfunction(CSQC_Shutdown))
1170                         prog->ExecuteProgram(prog, PRVM_clientfunction(CSQC_Shutdown), "QC function CSQC_Shutdown is missing");
1171         }
1172         PRVM_Prog_Reset(prog);
1173 CSQC_END
1174         Con_DPrint("CSQC ^1unloaded\n");
1175         cl.csqc_loaded = false;
1176 }
1177
1178 qbool CL_VM_GetEntitySoundOrigin(int entnum, vec3_t out)
1179 {
1180         prvm_prog_t *prog = CLVM_prog;
1181         prvm_edict_t *ed;
1182         model_t *mod;
1183         matrix4x4_t matrix;
1184         qbool r = 0;
1185
1186         CSQC_BEGIN;
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, NULL) == 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 qbool CL_VM_TransformView(int entnum, matrix4x4_t *viewmatrix, mplane_t *clipplane, vec3_t visorigin)
1207 {
1208         prvm_prog_t *prog = CLVM_prog;
1209         qbool 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_and_dist);
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 }