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