]> git.xonotic.org Git - xonotic/darkplaces.git/blob - protocol.c
ENTITYSIZEPROFILING: also log entity number and sendflags.
[xonotic/darkplaces.git] / protocol.c
1 #include "quakedef.h"
2
3 #define ENTITYSIZEPROFILING_START(msg, num, flags) \
4         int entityprofiling_startsize = msg->cursize
5
6 #define ENTITYSIZEPROFILING_END(msg, num, flags) \
7         if(developer_networkentities.integer >= 2) \
8         { \
9                 prvm_edict_t *ed = prog->edicts + num; \
10                 Con_Printf("sent entity update of size %u for %d classname %s flags %d\n", (msg->cursize - entityprofiling_startsize), num, PRVM_serveredictstring(ed, classname) ? PRVM_GetString(prog, PRVM_serveredictstring(ed, classname)) : "(no classname)", flags); \
11         }
12
13 // this is 88 bytes (must match entity_state_t in protocol.h)
14 entity_state_t defaultstate =
15 {
16         // ! means this is not sent to client
17         0,//double time; // ! time this state was built (used on client for interpolation)
18         {0,0,0},//float netcenter[3]; // ! for network prioritization, this is the center of the bounding box (which may differ from the origin)
19         {0,0,0},//float origin[3];
20         {0,0,0},//float angles[3];
21         0,//int effects;
22         0,//unsigned int customizeentityforclient; // !
23         0,//unsigned short number; // entity number this state is for
24         0,//unsigned short modelindex;
25         0,//unsigned short frame;
26         0,//unsigned short tagentity;
27         0,//unsigned short specialvisibilityradius; // ! larger if it has effects/light
28         0,//unsigned short viewmodelforclient; // !
29         0,//unsigned short exteriormodelforclient; // ! not shown if first person viewing from this entity, shown in all other cases
30         0,//unsigned short nodrawtoclient; // !
31         0,//unsigned short drawonlytoclient; // !
32         0,//unsigned short traileffectnum;
33         {0,0,0,0},//unsigned short light[4]; // color*256 (0.00 to 255.996), and radius*1
34         ACTIVE_NOT,//unsigned char active; // true if a valid state
35         0,//unsigned char lightstyle;
36         0,//unsigned char lightpflags;
37         0,//unsigned char colormap;
38         0,//unsigned char skin; // also chooses cubemap for rtlights if lightpflags & LIGHTPFLAGS_FULLDYNAMIC
39         255,//unsigned char alpha;
40         16,//unsigned char scale;
41         0,//unsigned char glowsize;
42         254,//unsigned char glowcolor;
43         0,//unsigned char flags;
44         0,//unsigned char internaleffects; // INTEF_FLAG1QW and so on
45         0,//unsigned char tagindex;
46         {32, 32, 32},//unsigned char colormod[3];
47         {32, 32, 32},//unsigned char glowmod[3];
48 };
49
50 // LordHavoc: I own protocol ranges 96, 97, 3500-3599
51
52 struct protocolversioninfo_s
53 {
54         int number;
55         protocolversion_t version;
56         const char *name;
57 }
58 protocolversioninfo[] =
59 {
60         { 3504, PROTOCOL_DARKPLACES7 , "DP7"},
61         { 3503, PROTOCOL_DARKPLACES6 , "DP6"},
62         { 3502, PROTOCOL_DARKPLACES5 , "DP5"},
63         { 3501, PROTOCOL_DARKPLACES4 , "DP4"},
64         { 3500, PROTOCOL_DARKPLACES3 , "DP3"},
65         {   97, PROTOCOL_DARKPLACES2 , "DP2"},
66         {   96, PROTOCOL_DARKPLACES1 , "DP1"},
67         {   15, PROTOCOL_QUAKEDP     , "QUAKEDP"},
68         {   15, PROTOCOL_QUAKE       , "QUAKE"},
69         {   28, PROTOCOL_QUAKEWORLD  , "QW"},
70         {  250, PROTOCOL_NEHAHRAMOVIE, "NEHAHRAMOVIE"},
71         {10000, PROTOCOL_NEHAHRABJP  , "NEHAHRABJP"},
72         {10001, PROTOCOL_NEHAHRABJP2 , "NEHAHRABJP2"},
73         {10002, PROTOCOL_NEHAHRABJP3 , "NEHAHRABJP3"},
74         {    0, PROTOCOL_UNKNOWN     , NULL}
75 };
76
77 protocolversion_t Protocol_EnumForName(const char *s)
78 {
79         int i;
80         for (i = 0;protocolversioninfo[i].name;i++)
81                 if (!strcasecmp(s, protocolversioninfo[i].name))
82                         return protocolversioninfo[i].version;
83         return PROTOCOL_UNKNOWN;
84 }
85
86 const char *Protocol_NameForEnum(protocolversion_t p)
87 {
88         int i;
89         for (i = 0;protocolversioninfo[i].name;i++)
90                 if (protocolversioninfo[i].version == p)
91                         return protocolversioninfo[i].name;
92         return "UNKNOWN";
93 }
94
95 protocolversion_t Protocol_EnumForNumber(int n)
96 {
97         int i;
98         for (i = 0;protocolversioninfo[i].name;i++)
99                 if (protocolversioninfo[i].number == n)
100                         return protocolversioninfo[i].version;
101         return PROTOCOL_UNKNOWN;
102 }
103
104 int Protocol_NumberForEnum(protocolversion_t p)
105 {
106         int i;
107         for (i = 0;protocolversioninfo[i].name;i++)
108                 if (protocolversioninfo[i].version == p)
109                         return protocolversioninfo[i].number;
110         return 0;
111 }
112
113 void Protocol_Names(char *buffer, size_t buffersize)
114 {
115         int i;
116         if (buffersize < 1)
117                 return;
118         buffer[0] = 0;
119         for (i = 0;protocolversioninfo[i].name;i++)
120         {
121                 if (i > 1)
122                         strlcat(buffer, " ", buffersize);
123                 strlcat(buffer, protocolversioninfo[i].name, buffersize);
124         }
125 }
126
127 void EntityFrameQuake_ReadEntity(int bits)
128 {
129         int num;
130         entity_t *ent;
131         entity_state_t s;
132
133         if (bits & U_MOREBITS)
134                 bits |= (MSG_ReadByte(&cl_message)<<8);
135         if ((bits & U_EXTEND1) && cls.protocol != PROTOCOL_NEHAHRAMOVIE)
136         {
137                 bits |= MSG_ReadByte(&cl_message) << 16;
138                 if (bits & U_EXTEND2)
139                         bits |= MSG_ReadByte(&cl_message) << 24;
140         }
141
142         if (bits & U_LONGENTITY)
143                 num = (unsigned short) MSG_ReadShort(&cl_message);
144         else
145                 num = MSG_ReadByte(&cl_message);
146
147         if (num >= MAX_EDICTS)
148                 Host_Error("EntityFrameQuake_ReadEntity: entity number (%i) >= MAX_EDICTS (%i)", num, MAX_EDICTS);
149         if (num < 1)
150                 Host_Error("EntityFrameQuake_ReadEntity: invalid entity number (%i)", num);
151
152         if (cl.num_entities <= num)
153         {
154                 cl.num_entities = num + 1;
155                 if (num >= cl.max_entities)
156                         CL_ExpandEntities(num);
157         }
158
159         ent = cl.entities + num;
160
161         // note: this inherits the 'active' state of the baseline chosen
162         // (state_baseline is always active, state_current may not be active if
163         // the entity was missing in the last frame)
164         if (bits & U_DELTA)
165                 s = ent->state_current;
166         else
167         {
168                 s = ent->state_baseline;
169                 s.active = ACTIVE_NETWORK;
170         }
171
172         cl.isquakeentity[num] = true;
173         if (cl.lastquakeentity < num)
174                 cl.lastquakeentity = num;
175         s.number = num;
176         s.time = cl.mtime[0];
177         s.flags = 0;
178         if (bits & U_MODEL)
179         {
180                 if (cls.protocol == PROTOCOL_NEHAHRABJP || cls.protocol == PROTOCOL_NEHAHRABJP2 || cls.protocol == PROTOCOL_NEHAHRABJP3)
181                                                         s.modelindex = (unsigned short) MSG_ReadShort(&cl_message);
182                 else
183                                                         s.modelindex = (s.modelindex & 0xFF00) | MSG_ReadByte(&cl_message);
184         }
185         if (bits & U_FRAME)             s.frame = (s.frame & 0xFF00) | MSG_ReadByte(&cl_message);
186         if (bits & U_COLORMAP)  s.colormap = MSG_ReadByte(&cl_message);
187         if (bits & U_SKIN)              s.skin = MSG_ReadByte(&cl_message);
188         if (bits & U_EFFECTS)   s.effects = (s.effects & 0xFF00) | MSG_ReadByte(&cl_message);
189         if (bits & U_ORIGIN1)   s.origin[0] = MSG_ReadCoord(&cl_message, cls.protocol);
190         if (bits & U_ANGLE1)    s.angles[0] = MSG_ReadAngle(&cl_message, cls.protocol);
191         if (bits & U_ORIGIN2)   s.origin[1] = MSG_ReadCoord(&cl_message, cls.protocol);
192         if (bits & U_ANGLE2)    s.angles[1] = MSG_ReadAngle(&cl_message, cls.protocol);
193         if (bits & U_ORIGIN3)   s.origin[2] = MSG_ReadCoord(&cl_message, cls.protocol);
194         if (bits & U_ANGLE3)    s.angles[2] = MSG_ReadAngle(&cl_message, cls.protocol);
195         if (bits & U_STEP)              s.flags |= RENDER_STEP;
196         if (bits & U_ALPHA)             s.alpha = MSG_ReadByte(&cl_message);
197         if (bits & U_SCALE)             s.scale = MSG_ReadByte(&cl_message);
198         if (bits & U_EFFECTS2)  s.effects = (s.effects & 0x00FF) | (MSG_ReadByte(&cl_message) << 8);
199         if (bits & U_GLOWSIZE)  s.glowsize = MSG_ReadByte(&cl_message);
200         if (bits & U_GLOWCOLOR) s.glowcolor = MSG_ReadByte(&cl_message);
201         if (bits & U_COLORMOD)  {int c = MSG_ReadByte(&cl_message);s.colormod[0] = (unsigned char)(((c >> 5) & 7) * (32.0f / 7.0f));s.colormod[1] = (unsigned char)(((c >> 2) & 7) * (32.0f / 7.0f));s.colormod[2] = (unsigned char)((c & 3) * (32.0f / 3.0f));}
202         if (bits & U_GLOWTRAIL) s.flags |= RENDER_GLOWTRAIL;
203         if (bits & U_FRAME2)    s.frame = (s.frame & 0x00FF) | (MSG_ReadByte(&cl_message) << 8);
204         if (bits & U_MODEL2)    s.modelindex = (s.modelindex & 0x00FF) | (MSG_ReadByte(&cl_message) << 8);
205         if (bits & U_VIEWMODEL) s.flags |= RENDER_VIEWMODEL;
206         if (bits & U_EXTERIORMODEL)     s.flags |= RENDER_EXTERIORMODEL;
207
208         // LordHavoc: to allow playback of the Nehahra movie
209         if (cls.protocol == PROTOCOL_NEHAHRAMOVIE && (bits & U_EXTEND1))
210         {
211                 // LordHavoc: evil format
212                 int i = (int)MSG_ReadFloat(&cl_message);
213                 int j = (int)(MSG_ReadFloat(&cl_message) * 255.0f);
214                 if (i == 2)
215                 {
216                         i = (int)MSG_ReadFloat(&cl_message);
217                         if (i)
218                                 s.effects |= EF_FULLBRIGHT;
219                 }
220                 if (j < 0)
221                         s.alpha = 0;
222                 else if (j == 0 || j >= 255)
223                         s.alpha = 255;
224                 else
225                         s.alpha = j;
226         }
227
228         ent->state_previous = ent->state_current;
229         ent->state_current = s;
230         if (ent->state_current.active == ACTIVE_NETWORK)
231         {
232                 CL_MoveLerpEntityStates(ent);
233                 cl.entities_active[ent->state_current.number] = true;
234         }
235
236         if (cl_message.badread)
237                 Host_Error("EntityFrameQuake_ReadEntity: read error");
238 }
239
240 void EntityFrameQuake_ISeeDeadEntities(void)
241 {
242         int num, lastentity;
243         if (cl.lastquakeentity == 0)
244                 return;
245         lastentity = cl.lastquakeentity;
246         cl.lastquakeentity = 0;
247         for (num = 0;num <= lastentity;num++)
248         {
249                 if (cl.isquakeentity[num])
250                 {
251                         if (cl.entities_active[num] && cl.entities[num].state_current.time == cl.mtime[0])
252                         {
253                                 cl.isquakeentity[num] = true;
254                                 cl.lastquakeentity = num;
255                         }
256                         else
257                         {
258                                 cl.isquakeentity[num] = false;
259                                 cl.entities_active[num] = ACTIVE_NOT;
260                                 cl.entities[num].state_current = defaultstate;
261                                 cl.entities[num].state_current.number = num;
262                         }
263                 }
264         }
265 }
266
267 // NOTE: this only works with DP5 protocol and upwards. For lower protocols
268 // (including QUAKE), no packet loss handling for CSQC is done, which makes
269 // CSQC basically useless.
270 // Always use the DP5 protocol, or a higher one, when using CSQC entities.
271 static void EntityFrameCSQC_LostAllFrames(client_t *client)
272 {
273         prvm_prog_t *prog = SVVM_prog;
274         // mark ALL csqc entities as requiring a FULL resend!
275         // I know this is a bad workaround, but better than nothing.
276         int i, n;
277         prvm_edict_t *ed;
278
279         n = client->csqcnumedicts;
280         for(i = 0; i < n; ++i)
281         {
282                 if(client->csqcentityglobalhistory[i])
283                 {
284                         ed = prog->edicts + i;
285                         if (PRVM_serveredictfunction(ed, SendEntity))
286                                 client->csqcentitysendflags[i] |= 0xFFFFFF; // FULL RESEND
287                         else // if it was ever sent to that client as a CSQC entity
288                         {
289                                 client->csqcentityscope[i] = 1; // REMOVE
290                                 client->csqcentitysendflags[i] |= 0xFFFFFF;
291                         }
292                 }
293         }
294 }
295 void EntityFrameCSQC_LostFrame(client_t *client, int framenum)
296 {
297         // marks a frame as lost
298         int i, j;
299         qboolean valid;
300         int ringfirst, ringlast;
301         static int recoversendflags[MAX_EDICTS]; // client only
302         csqcentityframedb_t *d;
303
304         if(client->csqcentityframe_lastreset < 0)
305                 return;
306         if(framenum < client->csqcentityframe_lastreset)
307                 return; // no action required, as we resent that data anyway
308
309         // is our frame out of history?
310         ringfirst = client->csqcentityframehistory_next; // oldest entry
311         ringlast = (ringfirst + NUM_CSQCENTITYDB_FRAMES - 1) % NUM_CSQCENTITYDB_FRAMES; // most recently added entry
312
313         valid = false;
314         
315         for(j = 0; j < NUM_CSQCENTITYDB_FRAMES; ++j)
316         {
317                 d = &client->csqcentityframehistory[(ringfirst + j) % NUM_CSQCENTITYDB_FRAMES];
318                 if(d->framenum < 0)
319                         continue;
320                 if(d->framenum == framenum)
321                         break;
322                 else if(d->framenum < framenum)
323                         valid = true;
324         }
325         if(j == NUM_CSQCENTITYDB_FRAMES)
326         {
327                 if(valid) // got beaten, i.e. there is a frame < framenum
328                 {
329                         // a non-csqc frame got lost... great
330                         return;
331                 }
332                 else
333                 {
334                         // a too old frame got lost... sorry, cannot handle this
335                         Con_DPrintf("CSQC entity DB: lost a frame too early to do any handling (resending ALL)...\n");
336                         Con_DPrintf("Lost frame = %d\n", framenum);
337                         Con_DPrintf("Entity DB = %d to %d\n", client->csqcentityframehistory[ringfirst].framenum, client->csqcentityframehistory[ringlast].framenum);
338                         EntityFrameCSQC_LostAllFrames(client);
339                         client->csqcentityframe_lastreset = -1;
340                 }
341                 return;
342         }
343
344         // so j is the frame that got lost
345         // ringlast is the frame that we have to go to
346         ringfirst = (ringfirst + j) % NUM_CSQCENTITYDB_FRAMES;
347         if(ringlast < ringfirst)
348                 ringlast += NUM_CSQCENTITYDB_FRAMES;
349         
350         memset(recoversendflags, 0, sizeof(recoversendflags));
351
352         for(j = ringfirst; j <= ringlast; ++j)
353         {
354                 d = &client->csqcentityframehistory[j % NUM_CSQCENTITYDB_FRAMES];
355                 if(d->framenum < 0)
356                 {
357                         // deleted frame
358                 }
359                 else if(d->framenum < framenum)
360                 {
361                         // a frame in the past... should never happen
362                         Con_Printf("CSQC entity DB encountered a frame from the past when recovering from PL...?\n");
363                 }
364                 else if(d->framenum == framenum)
365                 {
366                         // handling the actually lost frame now
367                         for(i = 0; i < d->num; ++i)
368                         {
369                                 int sf = d->sendflags[i];
370                                 int ent = d->entno[i];
371                                 if(sf < 0) // remove
372                                         recoversendflags[ent] |= -1; // all bits, including sign
373                                 else if(sf > 0)
374                                         recoversendflags[ent] |= sf;
375                         }
376                 }
377                 else
378                 {
379                         // handling the frames that followed it now
380                         for(i = 0; i < d->num; ++i)
381                         {
382                                 int sf = d->sendflags[i];
383                                 int ent = d->entno[i];
384                                 if(sf < 0) // remove
385                                 {
386                                         recoversendflags[ent] = 0; // no need to update, we got a more recent remove (and will fix it THEN)
387                                         break; // no flags left to remove...
388                                 }
389                                 else if(sf > 0)
390                                         recoversendflags[ent] &= ~sf; // no need to update these bits, we already got them later
391                         }
392                 }
393         }
394
395         for(i = 0; i < client->csqcnumedicts; ++i)
396         {
397                 if(recoversendflags[i] < 0)
398                 {
399                         // a remove got lost, then either send a remove or - if it was
400                         // recreated later - a FULL update to make totally sure
401                         client->csqcentityscope[i] = 1;
402                         client->csqcentitysendflags[i] = 0xFFFFFF;
403                 }
404                 else
405                         client->csqcentitysendflags[i] |= recoversendflags[i];
406         }
407 }
408 static int EntityFrameCSQC_AllocFrame(client_t *client, int framenum)
409 {
410         int ringfirst = client->csqcentityframehistory_next; // oldest entry
411         client->csqcentityframehistory_next += 1;
412         client->csqcentityframehistory_next %= NUM_CSQCENTITYDB_FRAMES;
413         client->csqcentityframehistory[ringfirst].framenum = framenum;
414         client->csqcentityframehistory[ringfirst].num = 0;
415         return ringfirst;
416 }
417 static void EntityFrameCSQC_DeallocFrame(client_t *client, int framenum)
418 {
419         int ringfirst = client->csqcentityframehistory_next; // oldest entry
420         int ringlast = (ringfirst + NUM_CSQCENTITYDB_FRAMES - 1) % NUM_CSQCENTITYDB_FRAMES; // most recently added entry
421         if(framenum == client->csqcentityframehistory[ringlast].framenum)
422         {
423                 client->csqcentityframehistory[ringlast].framenum = -1;
424                 client->csqcentityframehistory[ringlast].num = 0;
425                 client->csqcentityframehistory_next = ringlast;
426         }
427         else
428                 Con_Printf("Trying to dealloc the wrong entity frame\n");
429 }
430
431 //[515]: we use only one array per-client for SendEntity feature
432 // TODO: add some handling for entity send priorities, to better deal with huge
433 // amounts of csqc networked entities
434 qboolean EntityFrameCSQC_WriteFrame (sizebuf_t *msg, int maxsize, int numnumbers, const unsigned short *numbers, int framenum)
435 {
436         prvm_prog_t *prog = SVVM_prog;
437         int num, number, end, sendflags;
438         qboolean sectionstarted = false;
439         const unsigned short *n;
440         prvm_edict_t *ed;
441         client_t *client = svs.clients + sv.writeentitiestoclient_clientnumber;
442         int dbframe = EntityFrameCSQC_AllocFrame(client, framenum);
443         csqcentityframedb_t *db = &client->csqcentityframehistory[dbframe];
444
445         if(client->csqcentityframe_lastreset < 0)
446                 client->csqcentityframe_lastreset = framenum;
447
448         maxsize -= 24; // always fit in an empty svc_entities message (for packet loss detection!)
449
450         // make sure there is enough room to store the svc_csqcentities byte,
451         // the terminator (0x0000) and at least one entity update
452         if (msg->cursize + 32 >= maxsize)
453                 return false;
454
455         if (client->csqcnumedicts < prog->num_edicts)
456                 client->csqcnumedicts = prog->num_edicts;
457
458         number = 1;
459         for (num = 0, n = numbers;num < numnumbers;num++, n++)
460         {
461                 end = *n;
462                 for (;number < end;number++)
463                 {
464                         if (client->csqcentityscope[number])
465                         {
466                                 client->csqcentityscope[number] = 1;
467                                 client->csqcentitysendflags[number] = 0xFFFFFF;
468                         }
469                 }
470                 ed = prog->edicts + number;
471                 if (PRVM_serveredictfunction(ed, SendEntity))
472                         client->csqcentityscope[number] = 2;
473                 else if (client->csqcentityscope[number])
474                 {
475                         client->csqcentityscope[number] = 1;
476                         client->csqcentitysendflags[number] = 0xFFFFFF;
477                 }
478                 number++;
479         }
480         end = client->csqcnumedicts;
481         for (;number < end;number++)
482         {
483                 if (client->csqcentityscope[number])
484                 {
485                         client->csqcentityscope[number] = 1;
486                         client->csqcentitysendflags[number] = 0xFFFFFF;
487                 }
488         }
489
490         /*
491         // mark all scope entities as remove
492         for (number = 1;number < client->csqcnumedicts;number++)
493                 if (client->csqcentityscope[number])
494                         client->csqcentityscope[number] = 1;
495         // keep visible entities
496         for (i = 0, n = numbers;i < numnumbers;i++, n++)
497         {
498                 number = *n;
499                 ed = prog->edicts + number;
500                 if (PRVM_serveredictfunction(ed, SendEntity))
501                         client->csqcentityscope[number] = 2;
502         }
503         */
504
505         // now try to emit the entity updates
506         // (FIXME: prioritize by distance?)
507         end = client->csqcnumedicts;
508         for (number = 1;number < end;number++)
509         {
510                 if (!client->csqcentityscope[number])
511                         continue;
512                 sendflags = client->csqcentitysendflags[number];
513                 if (!sendflags)
514                         continue;
515                 if(db->num >= NUM_CSQCENTITIES_PER_FRAME)
516                         break;
517                 ed = prog->edicts + number;
518                 // entity scope is either update (2) or remove (1)
519                 if (client->csqcentityscope[number] == 1)
520                 {
521                         // write a remove message
522                         // first write the message identifier if needed
523                         if(!sectionstarted)
524                         {
525                                 sectionstarted = 1;
526                                 MSG_WriteByte(msg, svc_csqcentities);
527                         }
528                         // write the remove message
529                         {
530                                 ENTITYSIZEPROFILING_START(msg, number, 0);
531                                 MSG_WriteShort(msg, (unsigned short)number | 0x8000);
532                                 client->csqcentityscope[number] = 0;
533                                 client->csqcentitysendflags[number] = 0xFFFFFF; // resend completely if it becomes active again
534                                 db->entno[db->num] = number;
535                                 db->sendflags[db->num] = -1;
536                                 db->num += 1;
537                                 client->csqcentityglobalhistory[number] = 1;
538                                 ENTITYSIZEPROFILING_END(msg, number, 0);
539                         }
540                         if (msg->cursize + 17 >= maxsize)
541                                 break;
542                 }
543                 else
544                 {
545                         // write an update
546                         // save the cursize value in case we overflow and have to rollback
547                         int oldcursize = msg->cursize;
548                         client->csqcentityscope[number] = 1;
549                         if (PRVM_serveredictfunction(ed, SendEntity))
550                         {
551                                 if(!sectionstarted)
552                                         MSG_WriteByte(msg, svc_csqcentities);
553                                 {
554                                         ENTITYSIZEPROFILING_START(msg, number, sendflags);
555                                         MSG_WriteShort(msg, number);
556                                         msg->allowoverflow = true;
557                                         PRVM_G_INT(OFS_PARM0) = sv.writeentitiestoclient_cliententitynumber;
558                                         PRVM_G_FLOAT(OFS_PARM1) = sendflags;
559                                         PRVM_serverglobaledict(self) = number;
560                                         prog->ExecuteProgram(prog, PRVM_serveredictfunction(ed, SendEntity), "Null SendEntity\n");
561                                         msg->allowoverflow = false;
562                                         if(PRVM_G_FLOAT(OFS_RETURN) && msg->cursize + 2 <= maxsize)
563                                         {
564                                                 // an update has been successfully written
565                                                 client->csqcentitysendflags[number] = 0;
566                                                 db->entno[db->num] = number;
567                                                 db->sendflags[db->num] = sendflags;
568                                                 db->num += 1;
569                                                 client->csqcentityglobalhistory[number] = 1;
570                                                 // and take note that we have begun the svc_csqcentities
571                                                 // section of the packet
572                                                 sectionstarted = 1;
573                                                 ENTITYSIZEPROFILING_END(msg, number, sendflags);
574                                                 if (msg->cursize + 17 >= maxsize)
575                                                         break;
576                                                 continue;
577                                         }
578                                 }
579                         }
580                         // self.SendEntity returned false (or does not exist) or the
581                         // update was too big for this packet - rollback the buffer to its
582                         // state before the writes occurred, we'll try again next frame
583                         msg->cursize = oldcursize;
584                         msg->overflowed = false;
585                 }
586         }
587         if (sectionstarted)
588         {
589                 // write index 0 to end the update (0 is never used by real entities)
590                 MSG_WriteShort(msg, 0);
591         }
592
593         if(db->num == 0)
594                 // if no single ent got added, remove the frame from the DB again, to allow
595                 // for a larger history
596                 EntityFrameCSQC_DeallocFrame(client, framenum);
597         
598         return sectionstarted;
599 }
600
601 void Protocol_UpdateClientStats(const int *stats)
602 {
603         int i;
604         // update the stats array and set deltabits for any changed stats
605         for (i = 0;i < MAX_CL_STATS;i++)
606         {
607                 if (host_client->stats[i] != stats[i])
608                 {
609                         host_client->statsdeltabits[i >> 3] |= 1 << (i & 7);
610                         host_client->stats[i] = stats[i];
611                 }
612         }
613 }
614
615 // only a few stats are within the 32 stat limit of Quake, and most of them
616 // are sent every frame in svc_clientdata messages, so we only send the
617 // remaining ones here
618 static const int sendquakestats[] =
619 {
620 // quake did not send these secrets/monsters stats in this way, but doing so
621 // allows a mod to increase STAT_TOTALMONSTERS during the game, and ensures
622 // that STAT_SECRETS and STAT_MONSTERS are always correct (even if a client
623 // didn't receive an svc_foundsecret or svc_killedmonster), which may be most
624 // valuable if randomly seeking around in a demo
625 STAT_TOTALSECRETS, // never changes during game
626 STAT_TOTALMONSTERS, // changes in some mods
627 STAT_SECRETS, // this makes svc_foundsecret unnecessary
628 STAT_MONSTERS, // this makes svc_killedmonster unnecessary
629 STAT_VIEWHEIGHT, // sent just for FTEQW clients
630 STAT_VIEWZOOM, // this rarely changes
631 -1,
632 };
633
634 void Protocol_WriteStatsReliable(void)
635 {
636         int i, j;
637         if (!host_client->netconnection)
638                 return;
639         // detect changes in stats and write reliable messages
640         // this only deals with 32 stats because the older protocols which use
641         // this function can only cope with 32 stats,
642         // they also do not support svc_updatestatubyte which was introduced in
643         // DP6 protocol (except for QW)
644         for (j = 0;sendquakestats[j] >= 0;j++)
645         {
646                 i = sendquakestats[j];
647                 // check if this bit is set
648                 if (host_client->statsdeltabits[i >> 3] & (1 << (i & 7)))
649                 {
650                         host_client->statsdeltabits[i >> 3] -= (1 << (i & 7));
651                         // send the stat as a byte if possible
652                         if (sv.protocol == PROTOCOL_QUAKEWORLD)
653                         {
654                                 if (host_client->stats[i] >= 0 && host_client->stats[i] < 256)
655                                 {
656                                         MSG_WriteByte(&host_client->netconnection->message, qw_svc_updatestat);
657                                         MSG_WriteByte(&host_client->netconnection->message, i);
658                                         MSG_WriteByte(&host_client->netconnection->message, host_client->stats[i]);
659                                 }
660                                 else
661                                 {
662                                         MSG_WriteByte(&host_client->netconnection->message, qw_svc_updatestatlong);
663                                         MSG_WriteByte(&host_client->netconnection->message, i);
664                                         MSG_WriteLong(&host_client->netconnection->message, host_client->stats[i]);
665                                 }
666                         }
667                         else
668                         {
669                                 // this could make use of svc_updatestatubyte in DP6 and later
670                                 // protocols but those protocols do not use this function
671                                 MSG_WriteByte(&host_client->netconnection->message, svc_updatestat);
672                                 MSG_WriteByte(&host_client->netconnection->message, i);
673                                 MSG_WriteLong(&host_client->netconnection->message, host_client->stats[i]);
674                         }
675                 }
676         }
677 }
678
679
680 qboolean EntityFrameQuake_WriteFrame(sizebuf_t *msg, int maxsize, int numstates, const entity_state_t **states)
681 {
682         prvm_prog_t *prog = SVVM_prog;
683         const entity_state_t *s;
684         entity_state_t baseline;
685         int i, bits;
686         sizebuf_t buf;
687         unsigned char data[128];
688         qboolean success = false;
689
690         // prepare the buffer
691         memset(&buf, 0, sizeof(buf));
692         buf.data = data;
693         buf.maxsize = sizeof(data);
694
695         for (i = 0;i < numstates;i++)
696         {
697                 s = states[i];
698                 if(PRVM_serveredictfunction((&prog->edicts[s->number]), SendEntity))
699                         continue;
700
701                 // prepare the buffer
702                 SZ_Clear(&buf);
703
704 // send an update
705                 bits = 0;
706                 if (s->number >= 256)
707                         bits |= U_LONGENTITY;
708                 if (s->flags & RENDER_STEP)
709                         bits |= U_STEP;
710                 if (s->flags & RENDER_VIEWMODEL)
711                         bits |= U_VIEWMODEL;
712                 if (s->flags & RENDER_GLOWTRAIL)
713                         bits |= U_GLOWTRAIL;
714                 if (s->flags & RENDER_EXTERIORMODEL)
715                         bits |= U_EXTERIORMODEL;
716
717                 // LordHavoc: old stuff, but rewritten to have more exact tolerances
718                 baseline = prog->edicts[s->number].priv.server->baseline;
719                 if (baseline.origin[0] != s->origin[0])
720                         bits |= U_ORIGIN1;
721                 if (baseline.origin[1] != s->origin[1])
722                         bits |= U_ORIGIN2;
723                 if (baseline.origin[2] != s->origin[2])
724                         bits |= U_ORIGIN3;
725                 if (baseline.angles[0] != s->angles[0])
726                         bits |= U_ANGLE1;
727                 if (baseline.angles[1] != s->angles[1])
728                         bits |= U_ANGLE2;
729                 if (baseline.angles[2] != s->angles[2])
730                         bits |= U_ANGLE3;
731                 if (baseline.colormap != s->colormap)
732                         bits |= U_COLORMAP;
733                 if (baseline.skin != s->skin)
734                         bits |= U_SKIN;
735                 if (baseline.frame != s->frame)
736                 {
737                         bits |= U_FRAME;
738                         if (s->frame & 0xFF00)
739                                 bits |= U_FRAME2;
740                 }
741                 if (baseline.effects != s->effects)
742                 {
743                         bits |= U_EFFECTS;
744                         if (s->effects & 0xFF00)
745                                 bits |= U_EFFECTS2;
746                 }
747                 if (baseline.modelindex != s->modelindex)
748                 {
749                         bits |= U_MODEL;
750                         if ((s->modelindex & 0xFF00) && sv.protocol != PROTOCOL_NEHAHRABJP && sv.protocol != PROTOCOL_NEHAHRABJP2 && sv.protocol != PROTOCOL_NEHAHRABJP3)
751                                 bits |= U_MODEL2;
752                 }
753                 if (baseline.alpha != s->alpha)
754                         bits |= U_ALPHA;
755                 if (baseline.scale != s->scale)
756                         bits |= U_SCALE;
757                 if (baseline.glowsize != s->glowsize)
758                         bits |= U_GLOWSIZE;
759                 if (baseline.glowcolor != s->glowcolor)
760                         bits |= U_GLOWCOLOR;
761                 if (!VectorCompare(baseline.colormod, s->colormod))
762                         bits |= U_COLORMOD;
763
764                 // if extensions are disabled, clear the relevant update flags
765                 if (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_NEHAHRAMOVIE)
766                         bits &= 0x7FFF;
767                 if (sv.protocol == PROTOCOL_NEHAHRAMOVIE)
768                         if (s->alpha != 255 || s->effects & EF_FULLBRIGHT)
769                                 bits |= U_EXTEND1;
770
771                 // write the message
772                 if (bits >= 16777216)
773                         bits |= U_EXTEND2;
774                 if (bits >= 65536)
775                         bits |= U_EXTEND1;
776                 if (bits >= 256)
777                         bits |= U_MOREBITS;
778                 bits |= U_SIGNAL;
779
780                 {
781                         ENTITYSIZEPROFILING_START(msg, states[i]->number, bits);
782
783                         MSG_WriteByte (&buf, bits);
784                         if (bits & U_MOREBITS)          MSG_WriteByte(&buf, bits>>8);
785                         if (sv.protocol != PROTOCOL_NEHAHRAMOVIE)
786                         {
787                                 if (bits & U_EXTEND1)   MSG_WriteByte(&buf, bits>>16);
788                                 if (bits & U_EXTEND2)   MSG_WriteByte(&buf, bits>>24);
789                         }
790                         if (bits & U_LONGENTITY)        MSG_WriteShort(&buf, s->number);
791                         else                                            MSG_WriteByte(&buf, s->number);
792
793                         if (bits & U_MODEL)
794                         {
795                                 if (sv.protocol == PROTOCOL_NEHAHRABJP || sv.protocol == PROTOCOL_NEHAHRABJP2 || sv.protocol == PROTOCOL_NEHAHRABJP3)
796                                         MSG_WriteShort(&buf, s->modelindex);
797                                 else
798                                         MSG_WriteByte(&buf, s->modelindex);
799                         }
800                         if (bits & U_FRAME)                     MSG_WriteByte(&buf, s->frame);
801                         if (bits & U_COLORMAP)          MSG_WriteByte(&buf, s->colormap);
802                         if (bits & U_SKIN)                      MSG_WriteByte(&buf, s->skin);
803                         if (bits & U_EFFECTS)           MSG_WriteByte(&buf, s->effects);
804                         if (bits & U_ORIGIN1)           MSG_WriteCoord(&buf, s->origin[0], sv.protocol);
805                         if (bits & U_ANGLE1)            MSG_WriteAngle(&buf, s->angles[0], sv.protocol);
806                         if (bits & U_ORIGIN2)           MSG_WriteCoord(&buf, s->origin[1], sv.protocol);
807                         if (bits & U_ANGLE2)            MSG_WriteAngle(&buf, s->angles[1], sv.protocol);
808                         if (bits & U_ORIGIN3)           MSG_WriteCoord(&buf, s->origin[2], sv.protocol);
809                         if (bits & U_ANGLE3)            MSG_WriteAngle(&buf, s->angles[2], sv.protocol);
810                         if (bits & U_ALPHA)                     MSG_WriteByte(&buf, s->alpha);
811                         if (bits & U_SCALE)                     MSG_WriteByte(&buf, s->scale);
812                         if (bits & U_EFFECTS2)          MSG_WriteByte(&buf, s->effects >> 8);
813                         if (bits & U_GLOWSIZE)          MSG_WriteByte(&buf, s->glowsize);
814                         if (bits & U_GLOWCOLOR)         MSG_WriteByte(&buf, s->glowcolor);
815                         if (bits & U_COLORMOD)          {int c = ((int)bound(0, s->colormod[0] * (7.0f / 32.0f), 7) << 5) | ((int)bound(0, s->colormod[1] * (7.0f / 32.0f), 7) << 2) | ((int)bound(0, s->colormod[2] * (3.0f / 32.0f), 3) << 0);MSG_WriteByte(&buf, c);}
816                         if (bits & U_FRAME2)            MSG_WriteByte(&buf, s->frame >> 8);
817                         if (bits & U_MODEL2)            MSG_WriteByte(&buf, s->modelindex >> 8);
818
819                         // the nasty protocol
820                         if ((bits & U_EXTEND1) && sv.protocol == PROTOCOL_NEHAHRAMOVIE)
821                         {
822                                 if (s->effects & EF_FULLBRIGHT)
823                                 {
824                                         MSG_WriteFloat(&buf, 2); // QSG protocol version
825                                         MSG_WriteFloat(&buf, s->alpha <= 0 ? 0 : (s->alpha >= 255 ? 1 : s->alpha * (1.0f / 255.0f))); // alpha
826                                         MSG_WriteFloat(&buf, 1); // fullbright
827                                 }
828                                 else
829                                 {
830                                         MSG_WriteFloat(&buf, 1); // QSG protocol version
831                                         MSG_WriteFloat(&buf, s->alpha <= 0 ? 0 : (s->alpha >= 255 ? 1 : s->alpha * (1.0f / 255.0f))); // alpha
832                                 }
833                         }
834
835                         // if the commit is full, we're done this frame
836                         if (msg->cursize + buf.cursize > maxsize)
837                         {
838                                 // next frame we will continue where we left off
839                                 break;
840                         }
841                         // write the message to the packet
842                         SZ_Write(msg, buf.data, buf.cursize);
843                         success = true;
844                         ENTITYSIZEPROFILING_END(msg, s->number, bits);
845                 }
846         }
847         return success;
848 }
849
850 int EntityState_DeltaBits(const entity_state_t *o, const entity_state_t *n)
851 {
852         unsigned int bits;
853         // if o is not active, delta from default
854         if (o->active != ACTIVE_NETWORK)
855                 o = &defaultstate;
856         bits = 0;
857         if (fabs(n->origin[0] - o->origin[0]) > (1.0f / 256.0f))
858                 bits |= E_ORIGIN1;
859         if (fabs(n->origin[1] - o->origin[1]) > (1.0f / 256.0f))
860                 bits |= E_ORIGIN2;
861         if (fabs(n->origin[2] - o->origin[2]) > (1.0f / 256.0f))
862                 bits |= E_ORIGIN3;
863         if ((unsigned char) (n->angles[0] * (256.0f / 360.0f)) != (unsigned char) (o->angles[0] * (256.0f / 360.0f)))
864                 bits |= E_ANGLE1;
865         if ((unsigned char) (n->angles[1] * (256.0f / 360.0f)) != (unsigned char) (o->angles[1] * (256.0f / 360.0f)))
866                 bits |= E_ANGLE2;
867         if ((unsigned char) (n->angles[2] * (256.0f / 360.0f)) != (unsigned char) (o->angles[2] * (256.0f / 360.0f)))
868                 bits |= E_ANGLE3;
869         if ((n->modelindex ^ o->modelindex) & 0x00FF)
870                 bits |= E_MODEL1;
871         if ((n->modelindex ^ o->modelindex) & 0xFF00)
872                 bits |= E_MODEL2;
873         if ((n->frame ^ o->frame) & 0x00FF)
874                 bits |= E_FRAME1;
875         if ((n->frame ^ o->frame) & 0xFF00)
876                 bits |= E_FRAME2;
877         if ((n->effects ^ o->effects) & 0x00FF)
878                 bits |= E_EFFECTS1;
879         if ((n->effects ^ o->effects) & 0xFF00)
880                 bits |= E_EFFECTS2;
881         if (n->colormap != o->colormap)
882                 bits |= E_COLORMAP;
883         if (n->skin != o->skin)
884                 bits |= E_SKIN;
885         if (n->alpha != o->alpha)
886                 bits |= E_ALPHA;
887         if (n->scale != o->scale)
888                 bits |= E_SCALE;
889         if (n->glowsize != o->glowsize)
890                 bits |= E_GLOWSIZE;
891         if (n->glowcolor != o->glowcolor)
892                 bits |= E_GLOWCOLOR;
893         if (n->flags != o->flags)
894                 bits |= E_FLAGS;
895         if (n->tagindex != o->tagindex || n->tagentity != o->tagentity)
896                 bits |= E_TAGATTACHMENT;
897         if (n->light[0] != o->light[0] || n->light[1] != o->light[1] || n->light[2] != o->light[2] || n->light[3] != o->light[3])
898                 bits |= E_LIGHT;
899         if (n->lightstyle != o->lightstyle)
900                 bits |= E_LIGHTSTYLE;
901         if (n->lightpflags != o->lightpflags)
902                 bits |= E_LIGHTPFLAGS;
903
904         if (bits)
905         {
906                 if (bits &  0xFF000000)
907                         bits |= 0x00800000;
908                 if (bits &  0x00FF0000)
909                         bits |= 0x00008000;
910                 if (bits &  0x0000FF00)
911                         bits |= 0x00000080;
912         }
913         return bits;
914 }
915
916 void EntityState_WriteExtendBits(sizebuf_t *msg, unsigned int bits)
917 {
918         MSG_WriteByte(msg, bits & 0xFF);
919         if (bits & 0x00000080)
920         {
921                 MSG_WriteByte(msg, (bits >> 8) & 0xFF);
922                 if (bits & 0x00008000)
923                 {
924                         MSG_WriteByte(msg, (bits >> 16) & 0xFF);
925                         if (bits & 0x00800000)
926                                 MSG_WriteByte(msg, (bits >> 24) & 0xFF);
927                 }
928         }
929 }
930
931 void EntityState_WriteFields(const entity_state_t *ent, sizebuf_t *msg, unsigned int bits)
932 {
933         if (sv.protocol == PROTOCOL_DARKPLACES2)
934         {
935                 if (bits & E_ORIGIN1)
936                         MSG_WriteCoord16i(msg, ent->origin[0]);
937                 if (bits & E_ORIGIN2)
938                         MSG_WriteCoord16i(msg, ent->origin[1]);
939                 if (bits & E_ORIGIN3)
940                         MSG_WriteCoord16i(msg, ent->origin[2]);
941         }
942         else
943         {
944                 // LordHavoc: have to write flags first, as they can modify protocol
945                 if (bits & E_FLAGS)
946                         MSG_WriteByte(msg, ent->flags);
947                 if (ent->flags & RENDER_LOWPRECISION)
948                 {
949                         if (bits & E_ORIGIN1)
950                                 MSG_WriteCoord16i(msg, ent->origin[0]);
951                         if (bits & E_ORIGIN2)
952                                 MSG_WriteCoord16i(msg, ent->origin[1]);
953                         if (bits & E_ORIGIN3)
954                                 MSG_WriteCoord16i(msg, ent->origin[2]);
955                 }
956                 else
957                 {
958                         if (bits & E_ORIGIN1)
959                                 MSG_WriteCoord32f(msg, ent->origin[0]);
960                         if (bits & E_ORIGIN2)
961                                 MSG_WriteCoord32f(msg, ent->origin[1]);
962                         if (bits & E_ORIGIN3)
963                                 MSG_WriteCoord32f(msg, ent->origin[2]);
964                 }
965         }
966         if ((sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4) && (ent->flags & RENDER_LOWPRECISION))
967         {
968                 if (bits & E_ANGLE1)
969                         MSG_WriteAngle8i(msg, ent->angles[0]);
970                 if (bits & E_ANGLE2)
971                         MSG_WriteAngle8i(msg, ent->angles[1]);
972                 if (bits & E_ANGLE3)
973                         MSG_WriteAngle8i(msg, ent->angles[2]);
974         }
975         else
976         {
977                 if (bits & E_ANGLE1)
978                         MSG_WriteAngle16i(msg, ent->angles[0]);
979                 if (bits & E_ANGLE2)
980                         MSG_WriteAngle16i(msg, ent->angles[1]);
981                 if (bits & E_ANGLE3)
982                         MSG_WriteAngle16i(msg, ent->angles[2]);
983         }
984         if (bits & E_MODEL1)
985                 MSG_WriteByte(msg, ent->modelindex & 0xFF);
986         if (bits & E_MODEL2)
987                 MSG_WriteByte(msg, (ent->modelindex >> 8) & 0xFF);
988         if (bits & E_FRAME1)
989                 MSG_WriteByte(msg, ent->frame & 0xFF);
990         if (bits & E_FRAME2)
991                 MSG_WriteByte(msg, (ent->frame >> 8) & 0xFF);
992         if (bits & E_EFFECTS1)
993                 MSG_WriteByte(msg, ent->effects & 0xFF);
994         if (bits & E_EFFECTS2)
995                 MSG_WriteByte(msg, (ent->effects >> 8) & 0xFF);
996         if (bits & E_COLORMAP)
997                 MSG_WriteByte(msg, ent->colormap);
998         if (bits & E_SKIN)
999                 MSG_WriteByte(msg, ent->skin);
1000         if (bits & E_ALPHA)
1001                 MSG_WriteByte(msg, ent->alpha);
1002         if (bits & E_SCALE)
1003                 MSG_WriteByte(msg, ent->scale);
1004         if (bits & E_GLOWSIZE)
1005                 MSG_WriteByte(msg, ent->glowsize);
1006         if (bits & E_GLOWCOLOR)
1007                 MSG_WriteByte(msg, ent->glowcolor);
1008         if (sv.protocol == PROTOCOL_DARKPLACES2)
1009                 if (bits & E_FLAGS)
1010                         MSG_WriteByte(msg, ent->flags);
1011         if (bits & E_TAGATTACHMENT)
1012         {
1013                 MSG_WriteShort(msg, ent->tagentity);
1014                 MSG_WriteByte(msg, ent->tagindex);
1015         }
1016         if (bits & E_LIGHT)
1017         {
1018                 MSG_WriteShort(msg, ent->light[0]);
1019                 MSG_WriteShort(msg, ent->light[1]);
1020                 MSG_WriteShort(msg, ent->light[2]);
1021                 MSG_WriteShort(msg, ent->light[3]);
1022         }
1023         if (bits & E_LIGHTSTYLE)
1024                 MSG_WriteByte(msg, ent->lightstyle);
1025         if (bits & E_LIGHTPFLAGS)
1026                 MSG_WriteByte(msg, ent->lightpflags);
1027 }
1028
1029 void EntityState_WriteUpdate(const entity_state_t *ent, sizebuf_t *msg, const entity_state_t *delta)
1030 {
1031         prvm_prog_t *prog = SVVM_prog;
1032         unsigned int bits;
1033         if (ent->active == ACTIVE_NETWORK)
1034         {
1035                 // entity is active, check for changes from the delta
1036                 if ((bits = EntityState_DeltaBits(delta, ent)))
1037                 {
1038                         // write the update number, bits, and fields
1039                         ENTITYSIZEPROFILING_START(msg, ent->number, bits);
1040                         MSG_WriteShort(msg, ent->number);
1041                         EntityState_WriteExtendBits(msg, bits);
1042                         EntityState_WriteFields(ent, msg, bits);
1043                         ENTITYSIZEPROFILING_END(msg, ent->number, bits);
1044                 }
1045         }
1046         else
1047         {
1048                 // entity is inactive, check if the delta was active
1049                 if (delta->active == ACTIVE_NETWORK)
1050                 {
1051                         // write the remove number
1052                         ENTITYSIZEPROFILING_START(msg, ent->number, 0);
1053                         MSG_WriteShort(msg, ent->number | 0x8000);
1054                         ENTITYSIZEPROFILING_END(msg, ent->number, 0);
1055                 }
1056         }
1057 }
1058
1059 int EntityState_ReadExtendBits(void)
1060 {
1061         unsigned int bits;
1062         bits = MSG_ReadByte(&cl_message);
1063         if (bits & 0x00000080)
1064         {
1065                 bits |= MSG_ReadByte(&cl_message) << 8;
1066                 if (bits & 0x00008000)
1067                 {
1068                         bits |= MSG_ReadByte(&cl_message) << 16;
1069                         if (bits & 0x00800000)
1070                                 bits |= MSG_ReadByte(&cl_message) << 24;
1071                 }
1072         }
1073         return bits;
1074 }
1075
1076 void EntityState_ReadFields(entity_state_t *e, unsigned int bits)
1077 {
1078         if (cls.protocol == PROTOCOL_DARKPLACES2)
1079         {
1080                 if (bits & E_ORIGIN1)
1081                         e->origin[0] = MSG_ReadCoord16i(&cl_message);
1082                 if (bits & E_ORIGIN2)
1083                         e->origin[1] = MSG_ReadCoord16i(&cl_message);
1084                 if (bits & E_ORIGIN3)
1085                         e->origin[2] = MSG_ReadCoord16i(&cl_message);
1086         }
1087         else
1088         {
1089                 if (bits & E_FLAGS)
1090                         e->flags = MSG_ReadByte(&cl_message);
1091                 if (e->flags & RENDER_LOWPRECISION)
1092                 {
1093                         if (bits & E_ORIGIN1)
1094                                 e->origin[0] = MSG_ReadCoord16i(&cl_message);
1095                         if (bits & E_ORIGIN2)
1096                                 e->origin[1] = MSG_ReadCoord16i(&cl_message);
1097                         if (bits & E_ORIGIN3)
1098                                 e->origin[2] = MSG_ReadCoord16i(&cl_message);
1099                 }
1100                 else
1101                 {
1102                         if (bits & E_ORIGIN1)
1103                                 e->origin[0] = MSG_ReadCoord32f(&cl_message);
1104                         if (bits & E_ORIGIN2)
1105                                 e->origin[1] = MSG_ReadCoord32f(&cl_message);
1106                         if (bits & E_ORIGIN3)
1107                                 e->origin[2] = MSG_ReadCoord32f(&cl_message);
1108                 }
1109         }
1110         if ((cls.protocol == PROTOCOL_DARKPLACES5 || cls.protocol == PROTOCOL_DARKPLACES6) && !(e->flags & RENDER_LOWPRECISION))
1111         {
1112                 if (bits & E_ANGLE1)
1113                         e->angles[0] = MSG_ReadAngle16i(&cl_message);
1114                 if (bits & E_ANGLE2)
1115                         e->angles[1] = MSG_ReadAngle16i(&cl_message);
1116                 if (bits & E_ANGLE3)
1117                         e->angles[2] = MSG_ReadAngle16i(&cl_message);
1118         }
1119         else
1120         {
1121                 if (bits & E_ANGLE1)
1122                         e->angles[0] = MSG_ReadAngle8i(&cl_message);
1123                 if (bits & E_ANGLE2)
1124                         e->angles[1] = MSG_ReadAngle8i(&cl_message);
1125                 if (bits & E_ANGLE3)
1126                         e->angles[2] = MSG_ReadAngle8i(&cl_message);
1127         }
1128         if (bits & E_MODEL1)
1129                 e->modelindex = (e->modelindex & 0xFF00) | (unsigned int) MSG_ReadByte(&cl_message);
1130         if (bits & E_MODEL2)
1131                 e->modelindex = (e->modelindex & 0x00FF) | ((unsigned int) MSG_ReadByte(&cl_message) << 8);
1132         if (bits & E_FRAME1)
1133                 e->frame = (e->frame & 0xFF00) | (unsigned int) MSG_ReadByte(&cl_message);
1134         if (bits & E_FRAME2)
1135                 e->frame = (e->frame & 0x00FF) | ((unsigned int) MSG_ReadByte(&cl_message) << 8);
1136         if (bits & E_EFFECTS1)
1137                 e->effects = (e->effects & 0xFF00) | (unsigned int) MSG_ReadByte(&cl_message);
1138         if (bits & E_EFFECTS2)
1139                 e->effects = (e->effects & 0x00FF) | ((unsigned int) MSG_ReadByte(&cl_message) << 8);
1140         if (bits & E_COLORMAP)
1141                 e->colormap = MSG_ReadByte(&cl_message);
1142         if (bits & E_SKIN)
1143                 e->skin = MSG_ReadByte(&cl_message);
1144         if (bits & E_ALPHA)
1145                 e->alpha = MSG_ReadByte(&cl_message);
1146         if (bits & E_SCALE)
1147                 e->scale = MSG_ReadByte(&cl_message);
1148         if (bits & E_GLOWSIZE)
1149                 e->glowsize = MSG_ReadByte(&cl_message);
1150         if (bits & E_GLOWCOLOR)
1151                 e->glowcolor = MSG_ReadByte(&cl_message);
1152         if (cls.protocol == PROTOCOL_DARKPLACES2)
1153                 if (bits & E_FLAGS)
1154                         e->flags = MSG_ReadByte(&cl_message);
1155         if (bits & E_TAGATTACHMENT)
1156         {
1157                 e->tagentity = (unsigned short) MSG_ReadShort(&cl_message);
1158                 e->tagindex = MSG_ReadByte(&cl_message);
1159         }
1160         if (bits & E_LIGHT)
1161         {
1162                 e->light[0] = (unsigned short) MSG_ReadShort(&cl_message);
1163                 e->light[1] = (unsigned short) MSG_ReadShort(&cl_message);
1164                 e->light[2] = (unsigned short) MSG_ReadShort(&cl_message);
1165                 e->light[3] = (unsigned short) MSG_ReadShort(&cl_message);
1166         }
1167         if (bits & E_LIGHTSTYLE)
1168                 e->lightstyle = MSG_ReadByte(&cl_message);
1169         if (bits & E_LIGHTPFLAGS)
1170                 e->lightpflags = MSG_ReadByte(&cl_message);
1171
1172         if (developer_networkentities.integer >= 2)
1173         {
1174                 Con_Printf("ReadFields e%i", e->number);
1175
1176                 if (bits & E_ORIGIN1)
1177                         Con_Printf(" E_ORIGIN1 %f", e->origin[0]);
1178                 if (bits & E_ORIGIN2)
1179                         Con_Printf(" E_ORIGIN2 %f", e->origin[1]);
1180                 if (bits & E_ORIGIN3)
1181                         Con_Printf(" E_ORIGIN3 %f", e->origin[2]);
1182                 if (bits & E_ANGLE1)
1183                         Con_Printf(" E_ANGLE1 %f", e->angles[0]);
1184                 if (bits & E_ANGLE2)
1185                         Con_Printf(" E_ANGLE2 %f", e->angles[1]);
1186                 if (bits & E_ANGLE3)
1187                         Con_Printf(" E_ANGLE3 %f", e->angles[2]);
1188                 if (bits & (E_MODEL1 | E_MODEL2))
1189                         Con_Printf(" E_MODEL %i", e->modelindex);
1190
1191                 if (bits & (E_FRAME1 | E_FRAME2))
1192                         Con_Printf(" E_FRAME %i", e->frame);
1193                 if (bits & (E_EFFECTS1 | E_EFFECTS2))
1194                         Con_Printf(" E_EFFECTS %i", e->effects);
1195                 if (bits & E_ALPHA)
1196                         Con_Printf(" E_ALPHA %f", e->alpha / 255.0f);
1197                 if (bits & E_SCALE)
1198                         Con_Printf(" E_SCALE %f", e->scale / 16.0f);
1199                 if (bits & E_COLORMAP)
1200                         Con_Printf(" E_COLORMAP %i", e->colormap);
1201                 if (bits & E_SKIN)
1202                         Con_Printf(" E_SKIN %i", e->skin);
1203
1204                 if (bits & E_GLOWSIZE)
1205                         Con_Printf(" E_GLOWSIZE %i", e->glowsize * 4);
1206                 if (bits & E_GLOWCOLOR)
1207                         Con_Printf(" E_GLOWCOLOR %i", e->glowcolor);
1208
1209                 if (bits & E_LIGHT)
1210                         Con_Printf(" E_LIGHT %i:%i:%i:%i", e->light[0], e->light[1], e->light[2], e->light[3]);
1211                 if (bits & E_LIGHTPFLAGS)
1212                         Con_Printf(" E_LIGHTPFLAGS %i", e->lightpflags);
1213
1214                 if (bits & E_TAGATTACHMENT)
1215                         Con_Printf(" E_TAGATTACHMENT e%i:%i", e->tagentity, e->tagindex);
1216                 if (bits & E_LIGHTSTYLE)
1217                         Con_Printf(" E_LIGHTSTYLE %i", e->lightstyle);
1218                 Con_Print("\n");
1219         }
1220 }
1221
1222 // (client and server) allocates a new empty database
1223 entityframe_database_t *EntityFrame_AllocDatabase(mempool_t *mempool)
1224 {
1225         return (entityframe_database_t *)Mem_Alloc(mempool, sizeof(entityframe_database_t));
1226 }
1227
1228 // (client and server) frees the database
1229 void EntityFrame_FreeDatabase(entityframe_database_t *d)
1230 {
1231         Mem_Free(d);
1232 }
1233
1234 // (server) clears the database to contain no frames (thus delta compression compresses against nothing)
1235 void EntityFrame_ClearDatabase(entityframe_database_t *d)
1236 {
1237         memset(d, 0, sizeof(*d));
1238 }
1239
1240 // (server and client) removes frames older than 'frame' from database
1241 void EntityFrame_AckFrame(entityframe_database_t *d, int frame)
1242 {
1243         int i;
1244         d->ackframenum = frame;
1245         for (i = 0;i < d->numframes && d->frames[i].framenum < frame;i++);
1246         // ignore outdated frame acks (out of order packets)
1247         if (i == 0)
1248                 return;
1249         d->numframes -= i;
1250         // if some queue is left, slide it down to beginning of array
1251         if (d->numframes)
1252                 memmove(&d->frames[0], &d->frames[i], sizeof(d->frames[0]) * d->numframes);
1253 }
1254
1255 // (server) clears frame, to prepare for adding entities
1256 void EntityFrame_Clear(entity_frame_t *f, vec3_t eye, int framenum)
1257 {
1258         f->time = 0;
1259         f->framenum = framenum;
1260         f->numentities = 0;
1261         if (eye == NULL)
1262                 VectorClear(f->eye);
1263         else
1264                 VectorCopy(eye, f->eye);
1265 }
1266
1267 // (server and client) reads a frame from the database
1268 void EntityFrame_FetchFrame(entityframe_database_t *d, int framenum, entity_frame_t *f)
1269 {
1270         int i, n;
1271         EntityFrame_Clear(f, NULL, -1);
1272         for (i = 0;i < d->numframes && d->frames[i].framenum < framenum;i++);
1273         if (i < d->numframes && framenum == d->frames[i].framenum)
1274         {
1275                 f->framenum = framenum;
1276                 f->numentities = d->frames[i].endentity - d->frames[i].firstentity;
1277                 n = MAX_ENTITY_DATABASE - (d->frames[i].firstentity % MAX_ENTITY_DATABASE);
1278                 if (n > f->numentities)
1279                         n = f->numentities;
1280                 memcpy(f->entitydata, d->entitydata + d->frames[i].firstentity % MAX_ENTITY_DATABASE, sizeof(*f->entitydata) * n);
1281                 if (f->numentities > n)
1282                         memcpy(f->entitydata + n, d->entitydata, sizeof(*f->entitydata) * (f->numentities - n));
1283                 VectorCopy(d->eye, f->eye);
1284         }
1285 }
1286
1287 // (client) adds a entity_frame to the database, for future reference
1288 void EntityFrame_AddFrame_Client(entityframe_database_t *d, vec3_t eye, int framenum, int numentities, const entity_state_t *entitydata)
1289 {
1290         int n, e;
1291         entity_frameinfo_t *info;
1292
1293         VectorCopy(eye, d->eye);
1294
1295         // figure out how many entity slots are used already
1296         if (d->numframes)
1297         {
1298                 n = d->frames[d->numframes - 1].endentity - d->frames[0].firstentity;
1299                 if (n + numentities > MAX_ENTITY_DATABASE || d->numframes >= MAX_ENTITY_HISTORY)
1300                 {
1301                         // ran out of room, dump database
1302                         EntityFrame_ClearDatabase(d);
1303                 }
1304         }
1305
1306         info = &d->frames[d->numframes];
1307         info->framenum = framenum;
1308         e = -1000;
1309         // make sure we check the newly added frame as well, but we haven't incremented numframes yet
1310         for (n = 0;n <= d->numframes;n++)
1311         {
1312                 if (e >= d->frames[n].framenum)
1313                 {
1314                         if (e == framenum)
1315                                 Con_Print("EntityFrame_AddFrame: tried to add out of sequence frame to database\n");
1316                         else
1317                                 Con_Print("EntityFrame_AddFrame: out of sequence frames in database\n");
1318                         return;
1319                 }
1320                 e = d->frames[n].framenum;
1321         }
1322         // if database still has frames after that...
1323         if (d->numframes)
1324                 info->firstentity = d->frames[d->numframes - 1].endentity;
1325         else
1326                 info->firstentity = 0;
1327         info->endentity = info->firstentity + numentities;
1328         d->numframes++;
1329
1330         n = info->firstentity % MAX_ENTITY_DATABASE;
1331         e = MAX_ENTITY_DATABASE - n;
1332         if (e > numentities)
1333                 e = numentities;
1334         memcpy(d->entitydata + n, entitydata, sizeof(entity_state_t) * e);
1335         if (numentities > e)
1336                 memcpy(d->entitydata, entitydata + e, sizeof(entity_state_t) * (numentities - e));
1337 }
1338
1339 // (server) adds a entity_frame to the database, for future reference
1340 void EntityFrame_AddFrame_Server(entityframe_database_t *d, vec3_t eye, int framenum, int numentities, const entity_state_t **entitydata)
1341 {
1342         int n, e;
1343         entity_frameinfo_t *info;
1344
1345         VectorCopy(eye, d->eye);
1346
1347         // figure out how many entity slots are used already
1348         if (d->numframes)
1349         {
1350                 n = d->frames[d->numframes - 1].endentity - d->frames[0].firstentity;
1351                 if (n + numentities > MAX_ENTITY_DATABASE || d->numframes >= MAX_ENTITY_HISTORY)
1352                 {
1353                         // ran out of room, dump database
1354                         EntityFrame_ClearDatabase(d);
1355                 }
1356         }
1357
1358         info = &d->frames[d->numframes];
1359         info->framenum = framenum;
1360         e = -1000;
1361         // make sure we check the newly added frame as well, but we haven't incremented numframes yet
1362         for (n = 0;n <= d->numframes;n++)
1363         {
1364                 if (e >= d->frames[n].framenum)
1365                 {
1366                         if (e == framenum)
1367                                 Con_Print("EntityFrame_AddFrame: tried to add out of sequence frame to database\n");
1368                         else
1369                                 Con_Print("EntityFrame_AddFrame: out of sequence frames in database\n");
1370                         return;
1371                 }
1372                 e = d->frames[n].framenum;
1373         }
1374         // if database still has frames after that...
1375         if (d->numframes)
1376                 info->firstentity = d->frames[d->numframes - 1].endentity;
1377         else
1378                 info->firstentity = 0;
1379         info->endentity = info->firstentity + numentities;
1380         d->numframes++;
1381
1382         n = info->firstentity % MAX_ENTITY_DATABASE;
1383         e = MAX_ENTITY_DATABASE - n;
1384         if (e > numentities)
1385                 e = numentities;
1386         memcpy(d->entitydata + n, entitydata, sizeof(entity_state_t) * e);
1387         if (numentities > e)
1388                 memcpy(d->entitydata, entitydata + e, sizeof(entity_state_t) * (numentities - e));
1389 }
1390
1391 // (server) writes a frame to network stream
1392 qboolean EntityFrame_WriteFrame(sizebuf_t *msg, int maxsize, entityframe_database_t *d, int numstates, const entity_state_t **states, int viewentnum)
1393 {
1394         prvm_prog_t *prog = SVVM_prog;
1395         int i, onum, number;
1396         entity_frame_t *o = &d->deltaframe;
1397         const entity_state_t *ent, *delta;
1398         vec3_t eye;
1399
1400         d->latestframenum++;
1401
1402         VectorClear(eye);
1403         for (i = 0;i < numstates;i++)
1404         {
1405                 ent = states[i];
1406                 if (ent->number == viewentnum)
1407                 {
1408                         VectorSet(eye, ent->origin[0], ent->origin[1], ent->origin[2] + 22);
1409                         break;
1410                 }
1411         }
1412
1413         EntityFrame_AddFrame_Server(d, eye, d->latestframenum, numstates, states);
1414
1415         EntityFrame_FetchFrame(d, d->ackframenum, o);
1416
1417         MSG_WriteByte (msg, svc_entities);
1418         MSG_WriteLong (msg, o->framenum);
1419         MSG_WriteLong (msg, d->latestframenum);
1420         MSG_WriteFloat (msg, eye[0]);
1421         MSG_WriteFloat (msg, eye[1]);
1422         MSG_WriteFloat (msg, eye[2]);
1423
1424         onum = 0;
1425         for (i = 0;i < numstates;i++)
1426         {
1427                 ent = states[i];
1428                 number = ent->number;
1429
1430                 if (PRVM_serveredictfunction((&prog->edicts[number]), SendEntity))
1431                         continue;
1432                 for (;onum < o->numentities && o->entitydata[onum].number < number;onum++)
1433                 {
1434                         // write remove message
1435                         MSG_WriteShort(msg, o->entitydata[onum].number | 0x8000);
1436                 }
1437                 if (onum < o->numentities && (o->entitydata[onum].number == number))
1438                 {
1439                         // delta from previous frame
1440                         delta = o->entitydata + onum;
1441                         // advance to next entity in delta frame
1442                         onum++;
1443                 }
1444                 else
1445                 {
1446                         // delta from defaults
1447                         delta = &defaultstate;
1448                 }
1449                 EntityState_WriteUpdate(ent, msg, delta);
1450         }
1451         for (;onum < o->numentities;onum++)
1452         {
1453                 // write remove message
1454                 MSG_WriteShort(msg, o->entitydata[onum].number | 0x8000);
1455         }
1456         MSG_WriteShort(msg, 0xFFFF);
1457
1458         return true;
1459 }
1460
1461 // (client) reads a frame from network stream
1462 void EntityFrame_CL_ReadFrame(void)
1463 {
1464         int i, number, removed;
1465         entity_frame_t *f, *delta;
1466         entity_state_t *e, *old, *oldend;
1467         entity_t *ent;
1468         entityframe_database_t *d;
1469         if (!cl.entitydatabase)
1470                 cl.entitydatabase = EntityFrame_AllocDatabase(cls.levelmempool);
1471         d = cl.entitydatabase;
1472         f = &d->framedata;
1473         delta = &d->deltaframe;
1474
1475         EntityFrame_Clear(f, NULL, -1);
1476
1477         // read the frame header info
1478         f->time = cl.mtime[0];
1479         number = MSG_ReadLong(&cl_message);
1480         f->framenum = MSG_ReadLong(&cl_message);
1481         CL_NewFrameReceived(f->framenum);
1482         f->eye[0] = MSG_ReadFloat(&cl_message);
1483         f->eye[1] = MSG_ReadFloat(&cl_message);
1484         f->eye[2] = MSG_ReadFloat(&cl_message);
1485         EntityFrame_AckFrame(d, number);
1486         EntityFrame_FetchFrame(d, number, delta);
1487         old = delta->entitydata;
1488         oldend = old + delta->numentities;
1489         // read entities until we hit the magic 0xFFFF end tag
1490         while ((number = (unsigned short) MSG_ReadShort(&cl_message)) != 0xFFFF && !cl_message.badread)
1491         {
1492                 if (cl_message.badread)
1493                         Host_Error("EntityFrame_Read: read error");
1494                 removed = number & 0x8000;
1495                 number &= 0x7FFF;
1496                 if (number >= MAX_EDICTS)
1497                         Host_Error("EntityFrame_Read: number (%i) >= MAX_EDICTS (%i)", number, MAX_EDICTS);
1498
1499                 // seek to entity, while copying any skipped entities (assume unchanged)
1500                 while (old < oldend && old->number < number)
1501                 {
1502                         if (f->numentities >= MAX_ENTITY_DATABASE)
1503                                 Host_Error("EntityFrame_Read: entity list too big");
1504                         f->entitydata[f->numentities] = *old++;
1505                         f->entitydata[f->numentities++].time = cl.mtime[0];
1506                 }
1507                 if (removed)
1508                 {
1509                         if (old < oldend && old->number == number)
1510                                 old++;
1511                         else
1512                                 Con_Printf("EntityFrame_Read: REMOVE on unused entity %i\n", number);
1513                 }
1514                 else
1515                 {
1516                         if (f->numentities >= MAX_ENTITY_DATABASE)
1517                                 Host_Error("EntityFrame_Read: entity list too big");
1518
1519                         // reserve this slot
1520                         e = f->entitydata + f->numentities++;
1521
1522                         if (old < oldend && old->number == number)
1523                         {
1524                                 // delta from old entity
1525                                 *e = *old++;
1526                         }
1527                         else
1528                         {
1529                                 // delta from defaults
1530                                 *e = defaultstate;
1531                         }
1532
1533                         if (cl.num_entities <= number)
1534                         {
1535                                 cl.num_entities = number + 1;
1536                                 if (number >= cl.max_entities)
1537                                         CL_ExpandEntities(number);
1538                         }
1539                         cl.entities_active[number] = true;
1540                         e->active = ACTIVE_NETWORK;
1541                         e->time = cl.mtime[0];
1542                         e->number = number;
1543                         EntityState_ReadFields(e, EntityState_ReadExtendBits());
1544                 }
1545         }
1546         while (old < oldend)
1547         {
1548                 if (f->numentities >= MAX_ENTITY_DATABASE)
1549                         Host_Error("EntityFrame_Read: entity list too big");
1550                 f->entitydata[f->numentities] = *old++;
1551                 f->entitydata[f->numentities++].time = cl.mtime[0];
1552         }
1553         EntityFrame_AddFrame_Client(d, f->eye, f->framenum, f->numentities, f->entitydata);
1554
1555         memset(cl.entities_active, 0, cl.num_entities * sizeof(unsigned char));
1556         number = 1;
1557         for (i = 0;i < f->numentities;i++)
1558         {
1559                 for (;number < f->entitydata[i].number && number < cl.num_entities;number++)
1560                 {
1561                         if (cl.entities_active[number])
1562                         {
1563                                 cl.entities_active[number] = false;
1564                                 cl.entities[number].state_current.active = ACTIVE_NOT;
1565                         }
1566                 }
1567                 if (number >= cl.num_entities)
1568                         break;
1569                 // update the entity
1570                 ent = &cl.entities[number];
1571                 ent->state_previous = ent->state_current;
1572                 ent->state_current = f->entitydata[i];
1573                 CL_MoveLerpEntityStates(ent);
1574                 // the entity lives again...
1575                 cl.entities_active[number] = true;
1576                 number++;
1577         }
1578         for (;number < cl.num_entities;number++)
1579         {
1580                 if (cl.entities_active[number])
1581                 {
1582                         cl.entities_active[number] = false;
1583                         cl.entities[number].state_current.active = ACTIVE_NOT;
1584                 }
1585         }
1586 }
1587
1588
1589 // (client) returns the frame number of the most recent frame recieved
1590 int EntityFrame_MostRecentlyRecievedFrameNum(entityframe_database_t *d)
1591 {
1592         if (d->numframes)
1593                 return d->frames[d->numframes - 1].framenum;
1594         else
1595                 return -1;
1596 }
1597
1598
1599
1600
1601
1602
1603 entity_state_t *EntityFrame4_GetReferenceEntity(entityframe4_database_t *d, int number)
1604 {
1605         if (d->maxreferenceentities <= number)
1606         {
1607                 int oldmax = d->maxreferenceentities;
1608                 entity_state_t *oldentity = d->referenceentity;
1609                 d->maxreferenceentities = (number + 15) & ~7;
1610                 d->referenceentity = (entity_state_t *)Mem_Alloc(d->mempool, d->maxreferenceentities * sizeof(*d->referenceentity));
1611                 if (oldentity)
1612                 {
1613                         memcpy(d->referenceentity, oldentity, oldmax * sizeof(*d->referenceentity));
1614                         Mem_Free(oldentity);
1615                 }
1616                 // clear the newly created entities
1617                 for (;oldmax < d->maxreferenceentities;oldmax++)
1618                 {
1619                         d->referenceentity[oldmax] = defaultstate;
1620                         d->referenceentity[oldmax].number = oldmax;
1621                 }
1622         }
1623         return d->referenceentity + number;
1624 }
1625
1626 void EntityFrame4_AddCommitEntity(entityframe4_database_t *d, const entity_state_t *s)
1627 {
1628         // resize commit's entity list if full
1629         if (d->currentcommit->maxentities <= d->currentcommit->numentities)
1630         {
1631                 entity_state_t *oldentity = d->currentcommit->entity;
1632                 d->currentcommit->maxentities += 8;
1633                 d->currentcommit->entity = (entity_state_t *)Mem_Alloc(d->mempool, d->currentcommit->maxentities * sizeof(*d->currentcommit->entity));
1634                 if (oldentity)
1635                 {
1636                         memcpy(d->currentcommit->entity, oldentity, d->currentcommit->numentities * sizeof(*d->currentcommit->entity));
1637                         Mem_Free(oldentity);
1638                 }
1639         }
1640         d->currentcommit->entity[d->currentcommit->numentities++] = *s;
1641 }
1642
1643 entityframe4_database_t *EntityFrame4_AllocDatabase(mempool_t *pool)
1644 {
1645         entityframe4_database_t *d;
1646         d = (entityframe4_database_t *)Mem_Alloc(pool, sizeof(*d));
1647         d->mempool = pool;
1648         EntityFrame4_ResetDatabase(d);
1649         return d;
1650 }
1651
1652 void EntityFrame4_FreeDatabase(entityframe4_database_t *d)
1653 {
1654         int i;
1655         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1656                 if (d->commit[i].entity)
1657                         Mem_Free(d->commit[i].entity);
1658         if (d->referenceentity)
1659                 Mem_Free(d->referenceentity);
1660         Mem_Free(d);
1661 }
1662
1663 void EntityFrame4_ResetDatabase(entityframe4_database_t *d)
1664 {
1665         int i;
1666         d->referenceframenum = -1;
1667         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1668                 d->commit[i].numentities = 0;
1669         for (i = 0;i < d->maxreferenceentities;i++)
1670                 d->referenceentity[i] = defaultstate;
1671 }
1672
1673 int EntityFrame4_AckFrame(entityframe4_database_t *d, int framenum, int servermode)
1674 {
1675         int i, j, found;
1676         entity_database4_commit_t *commit;
1677         if (framenum == -1)
1678         {
1679                 // reset reference, but leave commits alone
1680                 d->referenceframenum = -1;
1681                 for (i = 0;i < d->maxreferenceentities;i++)
1682                         d->referenceentity[i] = defaultstate;
1683                 // if this is the server, remove commits
1684                         for (i = 0, commit = d->commit;i < MAX_ENTITY_HISTORY;i++, commit++)
1685                                 commit->numentities = 0;
1686                 found = true;
1687         }
1688         else if (d->referenceframenum == framenum)
1689                 found = true;
1690         else
1691         {
1692                 found = false;
1693                 for (i = 0, commit = d->commit;i < MAX_ENTITY_HISTORY;i++, commit++)
1694                 {
1695                         if (commit->numentities && commit->framenum <= framenum)
1696                         {
1697                                 if (commit->framenum == framenum)
1698                                 {
1699                                         found = true;
1700                                         d->referenceframenum = framenum;
1701                                         if (developer_networkentities.integer >= 3)
1702                                         {
1703                                                 for (j = 0;j < commit->numentities;j++)
1704                                                 {
1705                                                         entity_state_t *s = EntityFrame4_GetReferenceEntity(d, commit->entity[j].number);
1706                                                         if (commit->entity[j].active != s->active)
1707                                                         {
1708                                                                 if (commit->entity[j].active == ACTIVE_NETWORK)
1709                                                                         Con_Printf("commit entity %i has become active (modelindex %i)\n", commit->entity[j].number, commit->entity[j].modelindex);
1710                                                                 else
1711                                                                         Con_Printf("commit entity %i has become inactive (modelindex %i)\n", commit->entity[j].number, commit->entity[j].modelindex);
1712                                                         }
1713                                                         *s = commit->entity[j];
1714                                                 }
1715                                         }
1716                                         else
1717                                                 for (j = 0;j < commit->numentities;j++)
1718                                                         *EntityFrame4_GetReferenceEntity(d, commit->entity[j].number) = commit->entity[j];
1719                                 }
1720                                 commit->numentities = 0;
1721                         }
1722                 }
1723         }
1724         if (developer_networkentities.integer >= 1)
1725         {
1726                 Con_Printf("ack ref:%i database updated to: ref:%i commits:", framenum, d->referenceframenum);
1727                 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1728                         if (d->commit[i].numentities)
1729                                 Con_Printf(" %i", d->commit[i].framenum);
1730                 Con_Print("\n");
1731         }
1732         return found;
1733 }
1734
1735 void EntityFrame4_CL_ReadFrame(void)
1736 {
1737         int i, n, cnumber, referenceframenum, framenum, enumber, done, stopnumber, skip = false;
1738         entity_state_t *s;
1739         entityframe4_database_t *d;
1740         if (!cl.entitydatabase4)
1741                 cl.entitydatabase4 = EntityFrame4_AllocDatabase(cls.levelmempool);
1742         d = cl.entitydatabase4;
1743         // read the number of the frame this refers to
1744         referenceframenum = MSG_ReadLong(&cl_message);
1745         // read the number of this frame
1746         framenum = MSG_ReadLong(&cl_message);
1747         CL_NewFrameReceived(framenum);
1748         // read the start number
1749         enumber = (unsigned short) MSG_ReadShort(&cl_message);
1750         if (developer_networkentities.integer >= 10)
1751         {
1752                 Con_Printf("recv svc_entities num:%i ref:%i database: ref:%i commits:", framenum, referenceframenum, d->referenceframenum);
1753                 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1754                         if (d->commit[i].numentities)
1755                                 Con_Printf(" %i", d->commit[i].framenum);
1756                 Con_Print("\n");
1757         }
1758         if (!EntityFrame4_AckFrame(d, referenceframenum, false))
1759         {
1760                 Con_Print("EntityFrame4_CL_ReadFrame: reference frame invalid (VERY BAD ERROR), this update will be skipped\n");
1761                 skip = true;
1762         }
1763         d->currentcommit = NULL;
1764         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1765         {
1766                 if (!d->commit[i].numentities)
1767                 {
1768                         d->currentcommit = d->commit + i;
1769                         d->currentcommit->framenum = framenum;
1770                         d->currentcommit->numentities = 0;
1771                 }
1772         }
1773         if (d->currentcommit == NULL)
1774         {
1775                 Con_Printf("EntityFrame4_CL_ReadFrame: error while decoding frame %i: database full, reading but not storing this update\n", framenum);
1776                 skip = true;
1777         }
1778         done = false;
1779         while (!done && !cl_message.badread)
1780         {
1781                 // read the number of the modified entity
1782                 // (gaps will be copied unmodified)
1783                 n = (unsigned short)MSG_ReadShort(&cl_message);
1784                 if (n == 0x8000)
1785                 {
1786                         // no more entities in this update, but we still need to copy the
1787                         // rest of the reference entities (final gap)
1788                         done = true;
1789                         // read end of range number, then process normally
1790                         n = (unsigned short)MSG_ReadShort(&cl_message);
1791                 }
1792                 // high bit means it's a remove message
1793                 cnumber = n & 0x7FFF;
1794                 // if this is a live entity we may need to expand the array
1795                 if (cl.num_entities <= cnumber && !(n & 0x8000))
1796                 {
1797                         cl.num_entities = cnumber + 1;
1798                         if (cnumber >= cl.max_entities)
1799                                 CL_ExpandEntities(cnumber);
1800                 }
1801                 // add one (the changed one) if not done
1802                 stopnumber = cnumber + !done;
1803                 // process entities in range from the last one to the changed one
1804                 for (;enumber < stopnumber;enumber++)
1805                 {
1806                         if (skip || enumber >= cl.num_entities)
1807                         {
1808                                 if (enumber == cnumber && (n & 0x8000) == 0)
1809                                 {
1810                                         entity_state_t tempstate;
1811                                         EntityState_ReadFields(&tempstate, EntityState_ReadExtendBits());
1812                                 }
1813                                 continue;
1814                         }
1815                         // slide the current into the previous slot
1816                         cl.entities[enumber].state_previous = cl.entities[enumber].state_current;
1817                         // copy a new current from reference database
1818                         cl.entities[enumber].state_current = *EntityFrame4_GetReferenceEntity(d, enumber);
1819                         s = &cl.entities[enumber].state_current;
1820                         // if this is the one to modify, read more data...
1821                         if (enumber == cnumber)
1822                         {
1823                                 if (n & 0x8000)
1824                                 {
1825                                         // simply removed
1826                                         if (developer_networkentities.integer >= 2)
1827                                                 Con_Printf("entity %i: remove\n", enumber);
1828                                         *s = defaultstate;
1829                                 }
1830                                 else
1831                                 {
1832                                         // read the changes
1833                                         if (developer_networkentities.integer >= 2)
1834                                                 Con_Printf("entity %i: update\n", enumber);
1835                                         s->active = ACTIVE_NETWORK;
1836                                         EntityState_ReadFields(s, EntityState_ReadExtendBits());
1837                                 }
1838                         }
1839                         else if (developer_networkentities.integer >= 4)
1840                                 Con_Printf("entity %i: copy\n", enumber);
1841                         // set the cl.entities_active flag
1842                         cl.entities_active[enumber] = (s->active == ACTIVE_NETWORK);
1843                         // set the update time
1844                         s->time = cl.mtime[0];
1845                         // fix the number (it gets wiped occasionally by copying from defaultstate)
1846                         s->number = enumber;
1847                         // check if we need to update the lerp stuff
1848                         if (s->active == ACTIVE_NETWORK)
1849                                 CL_MoveLerpEntityStates(&cl.entities[enumber]);
1850                         // add this to the commit entry whether it is modified or not
1851                         if (d->currentcommit)
1852                                 EntityFrame4_AddCommitEntity(d, &cl.entities[enumber].state_current);
1853                         // print extra messages if desired
1854                         if (developer_networkentities.integer >= 2 && cl.entities[enumber].state_current.active != cl.entities[enumber].state_previous.active)
1855                         {
1856                                 if (cl.entities[enumber].state_current.active == ACTIVE_NETWORK)
1857                                         Con_Printf("entity #%i has become active\n", enumber);
1858                                 else if (cl.entities[enumber].state_previous.active)
1859                                         Con_Printf("entity #%i has become inactive\n", enumber);
1860                         }
1861                 }
1862         }
1863         d->currentcommit = NULL;
1864         if (skip)
1865                 EntityFrame4_ResetDatabase(d);
1866 }
1867
1868 qboolean EntityFrame4_WriteFrame(sizebuf_t *msg, int maxsize, entityframe4_database_t *d, int numstates, const entity_state_t **states)
1869 {
1870         prvm_prog_t *prog = SVVM_prog;
1871         const entity_state_t *e, *s;
1872         entity_state_t inactiveentitystate;
1873         int i, n, startnumber;
1874         sizebuf_t buf;
1875         unsigned char data[128];
1876
1877         // if there isn't enough space to accomplish anything, skip it
1878         if (msg->cursize + 24 > maxsize)
1879                 return false;
1880
1881         // prepare the buffer
1882         memset(&buf, 0, sizeof(buf));
1883         buf.data = data;
1884         buf.maxsize = sizeof(data);
1885
1886         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1887                 if (!d->commit[i].numentities)
1888                         break;
1889         // if commit buffer full, just don't bother writing an update this frame
1890         if (i == MAX_ENTITY_HISTORY)
1891                 return false;
1892         d->currentcommit = d->commit + i;
1893
1894         // this state's number gets played around with later
1895         inactiveentitystate = defaultstate;
1896
1897         d->currentcommit->numentities = 0;
1898         d->currentcommit->framenum = ++d->latestframenumber;
1899         MSG_WriteByte(msg, svc_entities);
1900         MSG_WriteLong(msg, d->referenceframenum);
1901         MSG_WriteLong(msg, d->currentcommit->framenum);
1902         if (developer_networkentities.integer >= 10)
1903         {
1904                 Con_Printf("send svc_entities num:%i ref:%i (database: ref:%i commits:", d->currentcommit->framenum, d->referenceframenum, d->referenceframenum);
1905                 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1906                         if (d->commit[i].numentities)
1907                                 Con_Printf(" %i", d->commit[i].framenum);
1908                 Con_Print(")\n");
1909         }
1910         if (d->currententitynumber >= prog->max_edicts)
1911                 startnumber = 1;
1912         else
1913                 startnumber = bound(1, d->currententitynumber, prog->max_edicts - 1);
1914         MSG_WriteShort(msg, startnumber);
1915         // reset currententitynumber so if the loop does not break it we will
1916         // start at beginning next frame (if it does break, it will set it)
1917         d->currententitynumber = 1;
1918         for (i = 0, n = startnumber;n < prog->max_edicts;n++)
1919         {
1920                 if (PRVM_serveredictfunction((&prog->edicts[n]), SendEntity))
1921                         continue;
1922                 // find the old state to delta from
1923                 e = EntityFrame4_GetReferenceEntity(d, n);
1924                 // prepare the buffer
1925                 SZ_Clear(&buf);
1926                 // entity exists, build an update (if empty there is no change)
1927                 // find the state in the list
1928                 for (;i < numstates && states[i]->number < n;i++);
1929                 // make the message
1930                 s = states[i];
1931                 if (s->number == n)
1932                 {
1933                         // build the update
1934                         EntityState_WriteUpdate(s, &buf, e);
1935                 }
1936                 else
1937                 {
1938                         inactiveentitystate.number = n;
1939                         s = &inactiveentitystate;
1940                         if (e->active == ACTIVE_NETWORK)
1941                         {
1942                                 // entity used to exist but doesn't anymore, send remove
1943                                 MSG_WriteShort(&buf, n | 0x8000);
1944                         }
1945                 }
1946                 // if the commit is full, we're done this frame
1947                 if (msg->cursize + buf.cursize > maxsize - 4)
1948                 {
1949                         // next frame we will continue where we left off
1950                         break;
1951                 }
1952                 // add the entity to the commit
1953                 EntityFrame4_AddCommitEntity(d, s);
1954                 // if the message is empty, skip out now
1955                 if (buf.cursize)
1956                 {
1957                         // write the message to the packet
1958                         SZ_Write(msg, buf.data, buf.cursize);
1959                 }
1960         }
1961         d->currententitynumber = n;
1962
1963         // remove world message (invalid, and thus a good terminator)
1964         MSG_WriteShort(msg, 0x8000);
1965         // write the number of the end entity
1966         MSG_WriteShort(msg, d->currententitynumber);
1967         // just to be sure
1968         d->currentcommit = NULL;
1969
1970         return true;
1971 }
1972
1973
1974
1975
1976 entityframe5_database_t *EntityFrame5_AllocDatabase(mempool_t *pool)
1977 {
1978         int i;
1979         entityframe5_database_t *d;
1980         d = (entityframe5_database_t *)Mem_Alloc(pool, sizeof(*d));
1981         d->latestframenum = 0;
1982         for (i = 0;i < d->maxedicts;i++)
1983                 d->states[i] = defaultstate;
1984         return d;
1985 }
1986
1987 void EntityFrame5_FreeDatabase(entityframe5_database_t *d)
1988 {
1989         // all the [maxedicts] memory is allocated at once, so there's only one
1990         // thing to free
1991         if (d->maxedicts)
1992                 Mem_Free(d->deltabits);
1993         Mem_Free(d);
1994 }
1995
1996 static void EntityFrame5_ExpandEdicts(entityframe5_database_t *d, int newmax)
1997 {
1998         if (d->maxedicts < newmax)
1999         {
2000                 unsigned char *data;
2001                 int oldmaxedicts = d->maxedicts;
2002                 int *olddeltabits = d->deltabits;
2003                 unsigned char *oldpriorities = d->priorities;
2004                 int *oldupdateframenum = d->updateframenum;
2005                 entity_state_t *oldstates = d->states;
2006                 unsigned char *oldvisiblebits = d->visiblebits;
2007                 d->maxedicts = newmax;
2008                 data = (unsigned char *)Mem_Alloc(sv_mempool, d->maxedicts * sizeof(int) + d->maxedicts * sizeof(unsigned char) + d->maxedicts * sizeof(int) + d->maxedicts * sizeof(entity_state_t) + (d->maxedicts+7)/8 * sizeof(unsigned char));
2009                 d->deltabits = (int *)data;data += d->maxedicts * sizeof(int);
2010                 d->priorities = (unsigned char *)data;data += d->maxedicts * sizeof(unsigned char);
2011                 d->updateframenum = (int *)data;data += d->maxedicts * sizeof(int);
2012                 d->states = (entity_state_t *)data;data += d->maxedicts * sizeof(entity_state_t);
2013                 d->visiblebits = (unsigned char *)data;data += (d->maxedicts+7)/8 * sizeof(unsigned char);
2014                 if (oldmaxedicts)
2015                 {
2016                         memcpy(d->deltabits, olddeltabits, oldmaxedicts * sizeof(int));
2017                         memcpy(d->priorities, oldpriorities, oldmaxedicts * sizeof(unsigned char));
2018                         memcpy(d->updateframenum, oldupdateframenum, oldmaxedicts * sizeof(int));
2019                         memcpy(d->states, oldstates, oldmaxedicts * sizeof(entity_state_t));
2020                         memcpy(d->visiblebits, oldvisiblebits, (oldmaxedicts+7)/8 * sizeof(unsigned char));
2021                         // the previous buffers were a single allocation, so just one free
2022                         Mem_Free(olddeltabits);
2023                 }
2024         }
2025 }
2026
2027 static int EntityState5_Priority(entityframe5_database_t *d, int stateindex)
2028 {
2029         int limit, priority;
2030         entity_state_t *s = NULL; // hush compiler warning by initializing this
2031         // if it is the player, update urgently
2032         if (stateindex == d->viewentnum)
2033                 return ENTITYFRAME5_PRIORITYLEVELS - 1;
2034         // priority increases each frame no matter what happens
2035         priority = d->priorities[stateindex] + 1;
2036         // players get an extra priority boost
2037         if (stateindex <= svs.maxclients)
2038                 priority++;
2039         // remove dead entities very quickly because they are just 2 bytes
2040         if (d->states[stateindex].active != ACTIVE_NETWORK)
2041         {
2042                 priority++;
2043                 return bound(1, priority, ENTITYFRAME5_PRIORITYLEVELS - 1);
2044         }
2045         // certain changes are more noticable than others
2046         if (d->deltabits[stateindex] & (E5_FULLUPDATE | E5_ATTACHMENT | E5_MODEL | E5_FLAGS | E5_COLORMAP))
2047                 priority++;
2048         // find the root entity this one is attached to, and judge relevance by it
2049         for (limit = 0;limit < 256;limit++)
2050         {
2051                 s = d->states + stateindex;
2052                 if (s->flags & RENDER_VIEWMODEL)
2053                         stateindex = d->viewentnum;
2054                 else if (s->tagentity)
2055                         stateindex = s->tagentity;
2056                 else
2057                         break;
2058                 if (d->maxedicts < stateindex)
2059                         EntityFrame5_ExpandEdicts(d, (stateindex+256)&~255);
2060         }
2061         if (limit >= 256)
2062                 Con_DPrintf("Protocol: Runaway loop recursing tagentity links on entity %i\n", stateindex);
2063         // now that we have the parent entity we can make some decisions based on
2064         // distance from the player
2065         if (VectorDistance(d->states[d->viewentnum].netcenter, s->netcenter) < 1024.0f)
2066                 priority++;
2067         return bound(1, priority, ENTITYFRAME5_PRIORITYLEVELS - 1);
2068 }
2069
2070 static double anim_reducetime(double t, double frameduration, double maxtime)
2071 {
2072         if(t < 0) // clamp to non-negative
2073                 return 0;
2074         if(t <= maxtime) // time can be represented normally
2075                 return t;
2076         if(frameduration == 0) // don't like dividing by zero
2077                 return t;
2078         if(maxtime <= 2 * frameduration) // if two frames don't fit, we better not do this
2079                 return t;
2080         t -= frameduration * ceil((t - maxtime) / frameduration);
2081         // now maxtime - frameduration < t <= maxtime
2082         return t;
2083 }
2084
2085 // see VM_SV_frameduration
2086 static double anim_frameduration(dp_model_t *model, int framenum)
2087 {
2088         if (!model || !model->animscenes || framenum < 0 || framenum >= model->numframes)
2089                 return 0;
2090         if(model->animscenes[framenum].framerate)
2091                 return model->animscenes[framenum].framecount / model->animscenes[framenum].framerate;
2092         return 0;
2093 }
2094
2095 void EntityState5_WriteUpdate(int number, const entity_state_t *s, int changedbits, sizebuf_t *msg)
2096 {
2097         prvm_prog_t *prog = SVVM_prog;
2098         unsigned int bits = 0;
2099         //dp_model_t *model;
2100
2101         if (s->active != ACTIVE_NETWORK)
2102         {
2103                 ENTITYSIZEPROFILING_START(msg, s->number, 0);
2104                 MSG_WriteShort(msg, number | 0x8000);
2105                 ENTITYSIZEPROFILING_END(msg, s->number, 0);
2106         }
2107         else
2108         {
2109                 if (PRVM_serveredictfunction((&prog->edicts[s->number]), SendEntity))
2110                         return;
2111
2112                 bits = changedbits;
2113                 if ((bits & E5_ORIGIN) && (!(s->flags & RENDER_LOWPRECISION) || s->exteriormodelforclient || s->tagentity || s->viewmodelforclient || (s->number >= 1 && s->number <= svs.maxclients) || s->origin[0] <= -4096.0625 || s->origin[0] >= 4095.9375 || s->origin[1] <= -4096.0625 || s->origin[1] >= 4095.9375 || s->origin[2] <= -4096.0625 || s->origin[2] >= 4095.9375))
2114                 // maybe also add: ((model = SV_GetModelByIndex(s->modelindex)) != NULL && model->name[0] == '*')
2115                         bits |= E5_ORIGIN32;
2116                         // possible values:
2117                         //   negative origin:
2118                         //     (int)(f * 8 - 0.5) >= -32768
2119                         //          (f * 8 - 0.5) >  -32769
2120                         //           f            >  -4096.0625
2121                         //   positive origin:
2122                         //     (int)(f * 8 + 0.5) <=  32767
2123                         //          (f * 8 + 0.5) <   32768
2124                         //           f * 8 + 0.5) <   4095.9375
2125                 if ((bits & E5_ANGLES) && !(s->flags & RENDER_LOWPRECISION))
2126                         bits |= E5_ANGLES16;
2127                 if ((bits & E5_MODEL) && s->modelindex >= 256)
2128                         bits |= E5_MODEL16;
2129                 if ((bits & E5_FRAME) && s->frame >= 256)
2130                         bits |= E5_FRAME16;
2131                 if (bits & E5_EFFECTS)
2132                 {
2133                         if (s->effects & 0xFFFF0000)
2134                                 bits |= E5_EFFECTS32;
2135                         else if (s->effects & 0xFFFFFF00)
2136                                 bits |= E5_EFFECTS16;
2137                 }
2138                 if (bits >= 256)
2139                         bits |= E5_EXTEND1;
2140                 if (bits >= 65536)
2141                         bits |= E5_EXTEND2;
2142                 if (bits >= 16777216)
2143                         bits |= E5_EXTEND3;
2144                 {
2145                         ENTITYSIZEPROFILING_START(msg, s->number, bits);
2146                         MSG_WriteShort(msg, number);
2147                         MSG_WriteByte(msg, bits & 0xFF);
2148                         if (bits & E5_EXTEND1)
2149                                 MSG_WriteByte(msg, (bits >> 8) & 0xFF);
2150                         if (bits & E5_EXTEND2)
2151                                 MSG_WriteByte(msg, (bits >> 16) & 0xFF);
2152                         if (bits & E5_EXTEND3)
2153                                 MSG_WriteByte(msg, (bits >> 24) & 0xFF);
2154                         if (bits & E5_FLAGS)
2155                                 MSG_WriteByte(msg, s->flags);
2156                         if (bits & E5_ORIGIN)
2157                         {
2158                                 if (bits & E5_ORIGIN32)
2159                                 {
2160                                         MSG_WriteCoord32f(msg, s->origin[0]);
2161                                         MSG_WriteCoord32f(msg, s->origin[1]);
2162                                         MSG_WriteCoord32f(msg, s->origin[2]);
2163                                 }
2164                                 else
2165                                 {
2166                                         MSG_WriteCoord13i(msg, s->origin[0]);
2167                                         MSG_WriteCoord13i(msg, s->origin[1]);
2168                                         MSG_WriteCoord13i(msg, s->origin[2]);
2169                                 }
2170                         }
2171                         if (bits & E5_ANGLES)
2172                         {
2173                                 if (bits & E5_ANGLES16)
2174                                 {
2175                                         MSG_WriteAngle16i(msg, s->angles[0]);
2176                                         MSG_WriteAngle16i(msg, s->angles[1]);
2177                                         MSG_WriteAngle16i(msg, s->angles[2]);
2178                                 }
2179                                 else
2180                                 {
2181                                         MSG_WriteAngle8i(msg, s->angles[0]);
2182                                         MSG_WriteAngle8i(msg, s->angles[1]);
2183                                         MSG_WriteAngle8i(msg, s->angles[2]);
2184                                 }
2185                         }
2186                         if (bits & E5_MODEL)
2187                         {
2188                                 if (bits & E5_MODEL16)
2189                                         MSG_WriteShort(msg, s->modelindex);
2190                                 else
2191                                         MSG_WriteByte(msg, s->modelindex);
2192                         }
2193                         if (bits & E5_FRAME)
2194                         {
2195                                 if (bits & E5_FRAME16)
2196                                         MSG_WriteShort(msg, s->frame);
2197                                 else
2198                                         MSG_WriteByte(msg, s->frame);
2199                         }
2200                         if (bits & E5_SKIN)
2201                                 MSG_WriteByte(msg, s->skin);
2202                         if (bits & E5_EFFECTS)
2203                         {
2204                                 if (bits & E5_EFFECTS32)
2205                                         MSG_WriteLong(msg, s->effects);
2206                                 else if (bits & E5_EFFECTS16)
2207                                         MSG_WriteShort(msg, s->effects);
2208                                 else
2209                                         MSG_WriteByte(msg, s->effects);
2210                         }
2211                         if (bits & E5_ALPHA)
2212                                 MSG_WriteByte(msg, s->alpha);
2213                         if (bits & E5_SCALE)
2214                                 MSG_WriteByte(msg, s->scale);
2215                         if (bits & E5_COLORMAP)
2216                                 MSG_WriteByte(msg, s->colormap);
2217                         if (bits & E5_ATTACHMENT)
2218                         {
2219                                 MSG_WriteShort(msg, s->tagentity);
2220                                 MSG_WriteByte(msg, s->tagindex);
2221                         }
2222                         if (bits & E5_LIGHT)
2223                         {
2224                                 MSG_WriteShort(msg, s->light[0]);
2225                                 MSG_WriteShort(msg, s->light[1]);
2226                                 MSG_WriteShort(msg, s->light[2]);
2227                                 MSG_WriteShort(msg, s->light[3]);
2228                                 MSG_WriteByte(msg, s->lightstyle);
2229                                 MSG_WriteByte(msg, s->lightpflags);
2230                         }
2231                         if (bits & E5_GLOW)
2232                         {
2233                                 MSG_WriteByte(msg, s->glowsize);
2234                                 MSG_WriteByte(msg, s->glowcolor);
2235                         }
2236                         if (bits & E5_COLORMOD)
2237                         {
2238                                 MSG_WriteByte(msg, s->colormod[0]);
2239                                 MSG_WriteByte(msg, s->colormod[1]);
2240                                 MSG_WriteByte(msg, s->colormod[2]);
2241                         }
2242                         if (bits & E5_GLOWMOD)
2243                         {
2244                                 MSG_WriteByte(msg, s->glowmod[0]);
2245                                 MSG_WriteByte(msg, s->glowmod[1]);
2246                                 MSG_WriteByte(msg, s->glowmod[2]);
2247                         }
2248                         if (bits & E5_COMPLEXANIMATION)
2249                         {
2250                                 if (s->skeletonobject.model && s->skeletonobject.relativetransforms)
2251                                 {
2252                                         int numbones = s->skeletonobject.model->num_bones;
2253                                         int bonenum;
2254                                         short pose7s[7];
2255                                         MSG_WriteByte(msg, 4);
2256                                         MSG_WriteShort(msg, s->modelindex);
2257                                         MSG_WriteByte(msg, numbones);
2258                                         for (bonenum = 0;bonenum < numbones;bonenum++)
2259                                         {
2260                                                 Matrix4x4_ToBonePose7s(s->skeletonobject.relativetransforms + bonenum, 64, pose7s);
2261                                                 MSG_WriteShort(msg, pose7s[0]);
2262                                                 MSG_WriteShort(msg, pose7s[1]);
2263                                                 MSG_WriteShort(msg, pose7s[2]);
2264                                                 MSG_WriteShort(msg, pose7s[3]);
2265                                                 MSG_WriteShort(msg, pose7s[4]);
2266                                                 MSG_WriteShort(msg, pose7s[5]);
2267                                                 MSG_WriteShort(msg, pose7s[6]);
2268                                         }
2269                                 }
2270                                 else
2271                                 {
2272                                         dp_model_t *model = SV_GetModelByIndex(s->modelindex);
2273                                         if (s->framegroupblend[3].lerp > 0)
2274                                         {
2275                                                 MSG_WriteByte(msg, 3);
2276                                                 MSG_WriteShort(msg, s->framegroupblend[0].frame);
2277                                                 MSG_WriteShort(msg, s->framegroupblend[1].frame);
2278                                                 MSG_WriteShort(msg, s->framegroupblend[2].frame);
2279                                                 MSG_WriteShort(msg, s->framegroupblend[3].frame);
2280                                                 MSG_WriteShort(msg, (int)(anim_reducetime(sv.time - s->framegroupblend[0].start, anim_frameduration(model, s->framegroupblend[0].frame), 65.535) * 1000.0));
2281                                                 MSG_WriteShort(msg, (int)(anim_reducetime(sv.time - s->framegroupblend[1].start, anim_frameduration(model, s->framegroupblend[1].frame), 65.535) * 1000.0));
2282                                                 MSG_WriteShort(msg, (int)(anim_reducetime(sv.time - s->framegroupblend[2].start, anim_frameduration(model, s->framegroupblend[2].frame), 65.535) * 1000.0));
2283                                                 MSG_WriteShort(msg, (int)(anim_reducetime(sv.time - s->framegroupblend[3].start, anim_frameduration(model, s->framegroupblend[3].frame), 65.535) * 1000.0));
2284                                                 MSG_WriteByte(msg, s->framegroupblend[0].lerp * 255.0f);
2285                                                 MSG_WriteByte(msg, s->framegroupblend[1].lerp * 255.0f);
2286                                                 MSG_WriteByte(msg, s->framegroupblend[2].lerp * 255.0f);
2287                                                 MSG_WriteByte(msg, s->framegroupblend[3].lerp * 255.0f);
2288                                         }
2289                                         else if (s->framegroupblend[2].lerp > 0)
2290                                         {
2291                                                 MSG_WriteByte(msg, 2);
2292                                                 MSG_WriteShort(msg, s->framegroupblend[0].frame);
2293                                                 MSG_WriteShort(msg, s->framegroupblend[1].frame);
2294                                                 MSG_WriteShort(msg, s->framegroupblend[2].frame);
2295                                                 MSG_WriteShort(msg, (int)(anim_reducetime(sv.time - s->framegroupblend[0].start, anim_frameduration(model, s->framegroupblend[0].frame), 65.535) * 1000.0));
2296                                                 MSG_WriteShort(msg, (int)(anim_reducetime(sv.time - s->framegroupblend[1].start, anim_frameduration(model, s->framegroupblend[1].frame), 65.535) * 1000.0));
2297                                                 MSG_WriteShort(msg, (int)(anim_reducetime(sv.time - s->framegroupblend[2].start, anim_frameduration(model, s->framegroupblend[2].frame), 65.535) * 1000.0));
2298                                                 MSG_WriteByte(msg, s->framegroupblend[0].lerp * 255.0f);
2299                                                 MSG_WriteByte(msg, s->framegroupblend[1].lerp * 255.0f);
2300                                                 MSG_WriteByte(msg, s->framegroupblend[2].lerp * 255.0f);
2301                                         }
2302                                         else if (s->framegroupblend[1].lerp > 0)
2303                                         {
2304                                                 MSG_WriteByte(msg, 1);
2305                                                 MSG_WriteShort(msg, s->framegroupblend[0].frame);
2306                                                 MSG_WriteShort(msg, s->framegroupblend[1].frame);
2307                                                 MSG_WriteShort(msg, (int)(anim_reducetime(sv.time - s->framegroupblend[0].start, anim_frameduration(model, s->framegroupblend[0].frame), 65.535) * 1000.0));
2308                                                 MSG_WriteShort(msg, (int)(anim_reducetime(sv.time - s->framegroupblend[1].start, anim_frameduration(model, s->framegroupblend[1].frame), 65.535) * 1000.0));
2309                                                 MSG_WriteByte(msg, s->framegroupblend[0].lerp * 255.0f);
2310                                                 MSG_WriteByte(msg, s->framegroupblend[1].lerp * 255.0f);
2311                                         }
2312                                         else
2313                                         {
2314                                                 MSG_WriteByte(msg, 0);
2315                                                 MSG_WriteShort(msg, s->framegroupblend[0].frame);
2316                                                 MSG_WriteShort(msg, (int)(anim_reducetime(sv.time - s->framegroupblend[0].start, anim_frameduration(model, s->framegroupblend[0].frame), 65.535) * 1000.0));
2317                                         }
2318                                 }
2319                         }
2320                         if (bits & E5_TRAILEFFECTNUM)
2321                                 MSG_WriteShort(msg, s->traileffectnum);
2322                         ENTITYSIZEPROFILING_END(msg, s->number, bits);
2323                 }
2324         }
2325 }
2326
2327 static void EntityState5_ReadUpdate(entity_state_t *s, int number)
2328 {
2329         int bits;
2330         int startoffset = cl_message.readcount;
2331         int bytes = 0;
2332         bits = MSG_ReadByte(&cl_message);
2333         if (bits & E5_EXTEND1)
2334         {
2335                 bits |= MSG_ReadByte(&cl_message) << 8;
2336                 if (bits & E5_EXTEND2)
2337                 {
2338                         bits |= MSG_ReadByte(&cl_message) << 16;
2339                         if (bits & E5_EXTEND3)
2340                                 bits |= MSG_ReadByte(&cl_message) << 24;
2341                 }
2342         }
2343         if (bits & E5_FULLUPDATE)
2344         {
2345                 *s = defaultstate;
2346                 s->active = ACTIVE_NETWORK;
2347         }
2348         if (bits & E5_FLAGS)
2349                 s->flags = MSG_ReadByte(&cl_message);
2350         if (bits & E5_ORIGIN)
2351         {
2352                 if (bits & E5_ORIGIN32)
2353                 {
2354                         s->origin[0] = MSG_ReadCoord32f(&cl_message);
2355                         s->origin[1] = MSG_ReadCoord32f(&cl_message);
2356                         s->origin[2] = MSG_ReadCoord32f(&cl_message);
2357                 }
2358                 else
2359                 {
2360                         s->origin[0] = MSG_ReadCoord13i(&cl_message);
2361                         s->origin[1] = MSG_ReadCoord13i(&cl_message);
2362                         s->origin[2] = MSG_ReadCoord13i(&cl_message);
2363                 }
2364         }
2365         if (bits & E5_ANGLES)
2366         {
2367                 if (bits & E5_ANGLES16)
2368                 {
2369                         s->angles[0] = MSG_ReadAngle16i(&cl_message);
2370                         s->angles[1] = MSG_ReadAngle16i(&cl_message);
2371                         s->angles[2] = MSG_ReadAngle16i(&cl_message);
2372                 }
2373                 else
2374                 {
2375                         s->angles[0] = MSG_ReadAngle8i(&cl_message);
2376                         s->angles[1] = MSG_ReadAngle8i(&cl_message);
2377                         s->angles[2] = MSG_ReadAngle8i(&cl_message);
2378                 }
2379         }
2380         if (bits & E5_MODEL)
2381         {
2382                 if (bits & E5_MODEL16)
2383                         s->modelindex = (unsigned short) MSG_ReadShort(&cl_message);
2384                 else
2385                         s->modelindex = MSG_ReadByte(&cl_message);
2386         }
2387         if (bits & E5_FRAME)
2388         {
2389                 if (bits & E5_FRAME16)
2390                         s->frame = (unsigned short) MSG_ReadShort(&cl_message);
2391                 else
2392                         s->frame = MSG_ReadByte(&cl_message);
2393         }
2394         if (bits & E5_SKIN)
2395                 s->skin = MSG_ReadByte(&cl_message);
2396         if (bits & E5_EFFECTS)
2397         {
2398                 if (bits & E5_EFFECTS32)
2399                         s->effects = (unsigned int) MSG_ReadLong(&cl_message);
2400                 else if (bits & E5_EFFECTS16)
2401                         s->effects = (unsigned short) MSG_ReadShort(&cl_message);
2402                 else
2403                         s->effects = MSG_ReadByte(&cl_message);
2404         }
2405         if (bits & E5_ALPHA)
2406                 s->alpha = MSG_ReadByte(&cl_message);
2407         if (bits & E5_SCALE)
2408                 s->scale = MSG_ReadByte(&cl_message);
2409         if (bits & E5_COLORMAP)
2410                 s->colormap = MSG_ReadByte(&cl_message);
2411         if (bits & E5_ATTACHMENT)
2412         {
2413                 s->tagentity = (unsigned short) MSG_ReadShort(&cl_message);
2414                 s->tagindex = MSG_ReadByte(&cl_message);
2415         }
2416         if (bits & E5_LIGHT)
2417         {
2418                 s->light[0] = (unsigned short) MSG_ReadShort(&cl_message);
2419                 s->light[1] = (unsigned short) MSG_ReadShort(&cl_message);
2420                 s->light[2] = (unsigned short) MSG_ReadShort(&cl_message);
2421                 s->light[3] = (unsigned short) MSG_ReadShort(&cl_message);
2422                 s->lightstyle = MSG_ReadByte(&cl_message);
2423                 s->lightpflags = MSG_ReadByte(&cl_message);
2424         }
2425         if (bits & E5_GLOW)
2426         {
2427                 s->glowsize = MSG_ReadByte(&cl_message);
2428                 s->glowcolor = MSG_ReadByte(&cl_message);
2429         }
2430         if (bits & E5_COLORMOD)
2431         {
2432                 s->colormod[0] = MSG_ReadByte(&cl_message);
2433                 s->colormod[1] = MSG_ReadByte(&cl_message);
2434                 s->colormod[2] = MSG_ReadByte(&cl_message);
2435         }
2436         if (bits & E5_GLOWMOD)
2437         {
2438                 s->glowmod[0] = MSG_ReadByte(&cl_message);
2439                 s->glowmod[1] = MSG_ReadByte(&cl_message);
2440                 s->glowmod[2] = MSG_ReadByte(&cl_message);
2441         }
2442         if (bits & E5_COMPLEXANIMATION)
2443         {
2444                 skeleton_t *skeleton;
2445                 const dp_model_t *model;
2446                 int modelindex;
2447                 int type;
2448                 int bonenum;
2449                 int numbones;
2450                 short pose7s[7];
2451                 type = MSG_ReadByte(&cl_message);
2452                 switch(type)
2453                 {
2454                 case 0:
2455                         s->framegroupblend[0].frame = MSG_ReadShort(&cl_message);
2456                         s->framegroupblend[1].frame = 0;
2457                         s->framegroupblend[2].frame = 0;
2458                         s->framegroupblend[3].frame = 0;
2459                         s->framegroupblend[0].start = cl.time - (unsigned short)MSG_ReadShort(&cl_message) * (1.0f / 1000.0f);
2460                         s->framegroupblend[1].start = 0;
2461                         s->framegroupblend[2].start = 0;
2462                         s->framegroupblend[3].start = 0;
2463                         s->framegroupblend[0].lerp = 1;
2464                         s->framegroupblend[1].lerp = 0;
2465                         s->framegroupblend[2].lerp = 0;
2466                         s->framegroupblend[3].lerp = 0;
2467                         break;
2468                 case 1:
2469                         s->framegroupblend[0].frame = MSG_ReadShort(&cl_message);
2470                         s->framegroupblend[1].frame = MSG_ReadShort(&cl_message);
2471                         s->framegroupblend[2].frame = 0;
2472                         s->framegroupblend[3].frame = 0;
2473                         s->framegroupblend[0].start = cl.time - (unsigned short)MSG_ReadShort(&cl_message) * (1.0f / 1000.0f);
2474                         s->framegroupblend[1].start = cl.time - (unsigned short)MSG_ReadShort(&cl_message) * (1.0f / 1000.0f);
2475                         s->framegroupblend[2].start = 0;
2476                         s->framegroupblend[3].start = 0;
2477                         s->framegroupblend[0].lerp = MSG_ReadByte(&cl_message) * (1.0f / 255.0f);
2478                         s->framegroupblend[1].lerp = MSG_ReadByte(&cl_message) * (1.0f / 255.0f);
2479                         s->framegroupblend[2].lerp = 0;
2480                         s->framegroupblend[3].lerp = 0;
2481                         break;
2482                 case 2:
2483                         s->framegroupblend[0].frame = MSG_ReadShort(&cl_message);
2484                         s->framegroupblend[1].frame = MSG_ReadShort(&cl_message);
2485                         s->framegroupblend[2].frame = MSG_ReadShort(&cl_message);
2486                         s->framegroupblend[3].frame = 0;
2487                         s->framegroupblend[0].start = cl.time - (unsigned short)MSG_ReadShort(&cl_message) * (1.0f / 1000.0f);
2488                         s->framegroupblend[1].start = cl.time - (unsigned short)MSG_ReadShort(&cl_message) * (1.0f / 1000.0f);
2489                         s->framegroupblend[2].start = cl.time - (unsigned short)MSG_ReadShort(&cl_message) * (1.0f / 1000.0f);
2490                         s->framegroupblend[3].start = 0;
2491                         s->framegroupblend[0].lerp = MSG_ReadByte(&cl_message) * (1.0f / 255.0f);
2492                         s->framegroupblend[1].lerp = MSG_ReadByte(&cl_message) * (1.0f / 255.0f);
2493                         s->framegroupblend[2].lerp = MSG_ReadByte(&cl_message) * (1.0f / 255.0f);
2494                         s->framegroupblend[3].lerp = 0;
2495                         break;
2496                 case 3:
2497                         s->framegroupblend[0].frame = MSG_ReadShort(&cl_message);
2498                         s->framegroupblend[1].frame = MSG_ReadShort(&cl_message);
2499                         s->framegroupblend[2].frame = MSG_ReadShort(&cl_message);
2500                         s->framegroupblend[3].frame = MSG_ReadShort(&cl_message);
2501                         s->framegroupblend[0].start = cl.time - (unsigned short)MSG_ReadShort(&cl_message) * (1.0f / 1000.0f);
2502                         s->framegroupblend[1].start = cl.time - (unsigned short)MSG_ReadShort(&cl_message) * (1.0f / 1000.0f);
2503                         s->framegroupblend[2].start = cl.time - (unsigned short)MSG_ReadShort(&cl_message) * (1.0f / 1000.0f);
2504                         s->framegroupblend[3].start = cl.time - (unsigned short)MSG_ReadShort(&cl_message) * (1.0f / 1000.0f);
2505                         s->framegroupblend[0].lerp = MSG_ReadByte(&cl_message) * (1.0f / 255.0f);
2506                         s->framegroupblend[1].lerp = MSG_ReadByte(&cl_message) * (1.0f / 255.0f);
2507                         s->framegroupblend[2].lerp = MSG_ReadByte(&cl_message) * (1.0f / 255.0f);
2508                         s->framegroupblend[3].lerp = MSG_ReadByte(&cl_message) * (1.0f / 255.0f);
2509                         break;
2510                 case 4:
2511                         if (!cl.engineskeletonobjects)
2512                                 cl.engineskeletonobjects = (skeleton_t *) Mem_Alloc(cls.levelmempool, sizeof(*cl.engineskeletonobjects) * MAX_EDICTS);
2513                         skeleton = &cl.engineskeletonobjects[number];
2514                         modelindex = MSG_ReadShort(&cl_message);
2515                         model = CL_GetModelByIndex(modelindex);
2516                         numbones = MSG_ReadByte(&cl_message);
2517                         if (model && numbones != model->num_bones)
2518                                 Host_Error("E5_COMPLEXANIMATION: model has different number of bones than network packet describes\n");
2519                         if (!skeleton->relativetransforms || skeleton->model != model)
2520                         {
2521                                 skeleton->model = model;
2522                                 skeleton->relativetransforms = (matrix4x4_t *) Mem_Realloc(cls.levelmempool, skeleton->relativetransforms, sizeof(*skeleton->relativetransforms) * skeleton->model->num_bones);
2523                                 for (bonenum = 0;bonenum < model->num_bones;bonenum++)
2524                                         skeleton->relativetransforms[bonenum] = identitymatrix;
2525                         }
2526                         for (bonenum = 0;bonenum < numbones;bonenum++)
2527                         {
2528                                 pose7s[0] = (short)MSG_ReadShort(&cl_message);
2529                                 pose7s[1] = (short)MSG_ReadShort(&cl_message);
2530                                 pose7s[2] = (short)MSG_ReadShort(&cl_message);
2531                                 pose7s[3] = (short)MSG_ReadShort(&cl_message);
2532                                 pose7s[4] = (short)MSG_ReadShort(&cl_message);
2533                                 pose7s[5] = (short)MSG_ReadShort(&cl_message);
2534                                 pose7s[6] = (short)MSG_ReadShort(&cl_message);
2535                                 Matrix4x4_FromBonePose7s(skeleton->relativetransforms + bonenum, 1.0f / 64.0f, pose7s);
2536                         }
2537                         s->skeletonobject = *skeleton;
2538                         break;
2539                 default:
2540                         Host_Error("E5_COMPLEXANIMATION: Parse error - unknown type %i\n", type);
2541                         break;
2542                 }
2543         }
2544         if (bits & E5_TRAILEFFECTNUM)
2545                 s->traileffectnum = (unsigned short) MSG_ReadShort(&cl_message);
2546
2547
2548         bytes = cl_message.readcount - startoffset;
2549         if (developer_networkentities.integer >= 2)
2550         {
2551                 Con_Printf("ReadFields e%i (%i bytes)", number, bytes);
2552
2553                 if (bits & E5_ORIGIN)
2554                         Con_Printf(" E5_ORIGIN %f %f %f", s->origin[0], s->origin[1], s->origin[2]);
2555                 if (bits & E5_ANGLES)
2556                         Con_Printf(" E5_ANGLES %f %f %f", s->angles[0], s->angles[1], s->angles[2]);
2557                 if (bits & E5_MODEL)
2558                         Con_Printf(" E5_MODEL %i", s->modelindex);
2559                 if (bits & E5_FRAME)
2560                         Con_Printf(" E5_FRAME %i", s->frame);
2561                 if (bits & E5_SKIN)
2562                         Con_Printf(" E5_SKIN %i", s->skin);
2563                 if (bits & E5_EFFECTS)
2564                         Con_Printf(" E5_EFFECTS %i", s->effects);
2565                 if (bits & E5_FLAGS)
2566                 {
2567                         Con_Printf(" E5_FLAGS %i (", s->flags);
2568                         if (s->flags & RENDER_STEP)
2569                                 Con_Print(" STEP");
2570                         if (s->flags & RENDER_GLOWTRAIL)
2571                                 Con_Print(" GLOWTRAIL");
2572                         if (s->flags & RENDER_VIEWMODEL)
2573                                 Con_Print(" VIEWMODEL");
2574                         if (s->flags & RENDER_EXTERIORMODEL)
2575                                 Con_Print(" EXTERIORMODEL");
2576                         if (s->flags & RENDER_LOWPRECISION)
2577                                 Con_Print(" LOWPRECISION");
2578                         if (s->flags & RENDER_COLORMAPPED)
2579                                 Con_Print(" COLORMAPPED");
2580                         if (s->flags & RENDER_SHADOW)
2581                                 Con_Print(" SHADOW");
2582                         if (s->flags & RENDER_LIGHT)
2583                                 Con_Print(" LIGHT");
2584                         if (s->flags & RENDER_NOSELFSHADOW)
2585                                 Con_Print(" NOSELFSHADOW");
2586                         Con_Print(")");
2587                 }
2588                 if (bits & E5_ALPHA)
2589                         Con_Printf(" E5_ALPHA %f", s->alpha / 255.0f);
2590                 if (bits & E5_SCALE)
2591                         Con_Printf(" E5_SCALE %f", s->scale / 16.0f);
2592                 if (bits & E5_COLORMAP)
2593                         Con_Printf(" E5_COLORMAP %i", s->colormap);
2594                 if (bits & E5_ATTACHMENT)
2595                         Con_Printf(" E5_ATTACHMENT e%i:%i", s->tagentity, s->tagindex);
2596                 if (bits & E5_LIGHT)
2597                         Con_Printf(" E5_LIGHT %i:%i:%i:%i %i:%i", s->light[0], s->light[1], s->light[2], s->light[3], s->lightstyle, s->lightpflags);
2598                 if (bits & E5_GLOW)
2599                         Con_Printf(" E5_GLOW %i:%i", s->glowsize * 4, s->glowcolor);
2600                 if (bits & E5_COLORMOD)
2601                         Con_Printf(" E5_COLORMOD %f:%f:%f", s->colormod[0] / 32.0f, s->colormod[1] / 32.0f, s->colormod[2] / 32.0f);
2602                 if (bits & E5_GLOWMOD)
2603                         Con_Printf(" E5_GLOWMOD %f:%f:%f", s->glowmod[0] / 32.0f, s->glowmod[1] / 32.0f, s->glowmod[2] / 32.0f);
2604                 if (bits & E5_COMPLEXANIMATION)
2605                         Con_Printf(" E5_COMPLEXANIMATION");
2606                 if (bits & E5_TRAILEFFECTNUM)
2607                         Con_Printf(" E5_TRAILEFFECTNUM %i", s->traileffectnum);
2608                 Con_Print("\n");
2609         }
2610 }
2611
2612 static int EntityState5_DeltaBits(const entity_state_t *o, const entity_state_t *n)
2613 {
2614         unsigned int bits = 0;
2615         if (n->active == ACTIVE_NETWORK)
2616         {
2617                 if (o->active != ACTIVE_NETWORK)
2618                         bits |= E5_FULLUPDATE;
2619                 if (!VectorCompare(o->origin, n->origin))
2620                         bits |= E5_ORIGIN;
2621                 if (!VectorCompare(o->angles, n->angles))
2622                         bits |= E5_ANGLES;
2623                 if (o->modelindex != n->modelindex)
2624                         bits |= E5_MODEL;
2625                 if (o->frame != n->frame)
2626                         bits |= E5_FRAME;
2627                 if (o->skin != n->skin)
2628                         bits |= E5_SKIN;
2629                 if (o->effects != n->effects)
2630                         bits |= E5_EFFECTS;
2631                 if (o->flags != n->flags)
2632                         bits |= E5_FLAGS;
2633                 if (o->alpha != n->alpha)
2634                         bits |= E5_ALPHA;
2635                 if (o->scale != n->scale)
2636                         bits |= E5_SCALE;
2637                 if (o->colormap != n->colormap)
2638                         bits |= E5_COLORMAP;
2639                 if (o->tagentity != n->tagentity || o->tagindex != n->tagindex)
2640                         bits |= E5_ATTACHMENT;
2641                 if (o->light[0] != n->light[0] || o->light[1] != n->light[1] || o->light[2] != n->light[2] || o->light[3] != n->light[3] || o->lightstyle != n->lightstyle || o->lightpflags != n->lightpflags)
2642                         bits |= E5_LIGHT;
2643                 if (o->glowsize != n->glowsize || o->glowcolor != n->glowcolor)
2644                         bits |= E5_GLOW;
2645                 if (o->colormod[0] != n->colormod[0] || o->colormod[1] != n->colormod[1] || o->colormod[2] != n->colormod[2])
2646                         bits |= E5_COLORMOD;
2647                 if (o->glowmod[0] != n->glowmod[0] || o->glowmod[1] != n->glowmod[1] || o->glowmod[2] != n->glowmod[2])
2648                         bits |= E5_GLOWMOD;
2649                 if (n->flags & RENDER_COMPLEXANIMATION)
2650                 {
2651                         if ((o->skeletonobject.model && o->skeletonobject.relativetransforms) != (n->skeletonobject.model && n->skeletonobject.relativetransforms))
2652                         {
2653                                 bits |= E5_COMPLEXANIMATION;
2654                         }
2655                         else if (o->skeletonobject.model && o->skeletonobject.relativetransforms)
2656                         {
2657                                 if(o->modelindex != n->modelindex)
2658                                         bits |= E5_COMPLEXANIMATION;
2659                                 else if(o->skeletonobject.model->num_bones != n->skeletonobject.model->num_bones)
2660                                         bits |= E5_COMPLEXANIMATION;
2661                                 else if(memcmp(o->skeletonobject.relativetransforms, n->skeletonobject.relativetransforms, o->skeletonobject.model->num_bones * sizeof(*o->skeletonobject.relativetransforms)))
2662                                         bits |= E5_COMPLEXANIMATION;
2663                         }
2664                         else if (memcmp(o->framegroupblend, n->framegroupblend, sizeof(o->framegroupblend)))
2665                         {
2666                                 bits |= E5_COMPLEXANIMATION;
2667                         }
2668                 }
2669                 if (o->traileffectnum != n->traileffectnum)
2670                         bits |= E5_TRAILEFFECTNUM;
2671         }
2672         else
2673                 if (o->active == ACTIVE_NETWORK)
2674                         bits |= E5_FULLUPDATE;
2675         return bits;
2676 }
2677
2678 void EntityFrame5_CL_ReadFrame(void)
2679 {
2680         int n, enumber, framenum;
2681         entity_t *ent;
2682         entity_state_t *s;
2683         // read the number of this frame to echo back in next input packet
2684         framenum = MSG_ReadLong(&cl_message);
2685         CL_NewFrameReceived(framenum);
2686         if (cls.protocol != PROTOCOL_QUAKE && cls.protocol != PROTOCOL_QUAKEDP && cls.protocol != PROTOCOL_NEHAHRAMOVIE && cls.protocol != PROTOCOL_DARKPLACES1 && cls.protocol != PROTOCOL_DARKPLACES2 && cls.protocol != PROTOCOL_DARKPLACES3 && cls.protocol != PROTOCOL_DARKPLACES4 && cls.protocol != PROTOCOL_DARKPLACES5 && cls.protocol != PROTOCOL_DARKPLACES6)
2687                 cls.servermovesequence = MSG_ReadLong(&cl_message);
2688         // read entity numbers until we find a 0x8000
2689         // (which would be remove world entity, but is actually a terminator)
2690         while ((n = (unsigned short)MSG_ReadShort(&cl_message)) != 0x8000 && !cl_message.badread)
2691         {
2692                 // get the entity number
2693                 enumber = n & 0x7FFF;
2694                 // we may need to expand the array
2695                 if (cl.num_entities <= enumber)
2696                 {
2697                         cl.num_entities = enumber + 1;
2698                         if (enumber >= cl.max_entities)
2699                                 CL_ExpandEntities(enumber);
2700                 }
2701                 // look up the entity
2702                 ent = cl.entities + enumber;
2703                 // slide the current into the previous slot
2704                 ent->state_previous = ent->state_current;
2705                 // read the update
2706                 s = &ent->state_current;
2707                 if (n & 0x8000)
2708                 {
2709                         // remove entity
2710                         *s = defaultstate;
2711                 }
2712                 else
2713                 {
2714                         // update entity
2715                         EntityState5_ReadUpdate(s, enumber);
2716                 }
2717                 // set the cl.entities_active flag
2718                 cl.entities_active[enumber] = (s->active == ACTIVE_NETWORK);
2719                 // set the update time
2720                 s->time = cl.mtime[0];
2721                 // fix the number (it gets wiped occasionally by copying from defaultstate)
2722                 s->number = enumber;
2723                 // check if we need to update the lerp stuff
2724                 if (s->active == ACTIVE_NETWORK)
2725                         CL_MoveLerpEntityStates(&cl.entities[enumber]);
2726                 // print extra messages if desired
2727                 if (developer_networkentities.integer >= 2 && cl.entities[enumber].state_current.active != cl.entities[enumber].state_previous.active)
2728                 {
2729                         if (cl.entities[enumber].state_current.active == ACTIVE_NETWORK)
2730                                 Con_Printf("entity #%i has become active\n", enumber);
2731                         else if (cl.entities[enumber].state_previous.active)
2732                                 Con_Printf("entity #%i has become inactive\n", enumber);
2733                 }
2734         }
2735 }
2736
2737 static int packetlog5cmp(const void *a_, const void *b_)
2738 {
2739         const entityframe5_packetlog_t *a = (const entityframe5_packetlog_t *) a_;
2740         const entityframe5_packetlog_t *b = (const entityframe5_packetlog_t *) b_;
2741         return a->packetnumber - b->packetnumber;
2742 }
2743
2744 void EntityFrame5_LostFrame(entityframe5_database_t *d, int framenum)
2745 {
2746         int i, j, l, bits;
2747         entityframe5_changestate_t *s;
2748         entityframe5_packetlog_t *p;
2749         static unsigned char statsdeltabits[(MAX_CL_STATS+7)/8];
2750         static int deltabits[MAX_EDICTS];
2751         entityframe5_packetlog_t *packetlogs[ENTITYFRAME5_MAXPACKETLOGS];
2752
2753         for (i = 0, p = d->packetlog;i < ENTITYFRAME5_MAXPACKETLOGS;i++, p++)
2754                 packetlogs[i] = p;
2755         qsort(packetlogs, sizeof(*packetlogs), ENTITYFRAME5_MAXPACKETLOGS, packetlog5cmp);
2756
2757         memset(deltabits, 0, sizeof(deltabits));
2758         memset(statsdeltabits, 0, sizeof(statsdeltabits));
2759         for (i = 0; i < ENTITYFRAME5_MAXPACKETLOGS; i++)
2760         {
2761                 p = packetlogs[i];
2762
2763                 if (!p->packetnumber)
2764                         continue;
2765
2766                 if (p->packetnumber <= framenum)
2767                 {
2768                         for (j = 0, s = p->states;j < p->numstates;j++, s++)
2769                                 deltabits[s->number] |= s->bits;
2770
2771                         for (l = 0;l < (MAX_CL_STATS+7)/8;l++)
2772                                 statsdeltabits[l] |= p->statsdeltabits[l];
2773
2774                         p->packetnumber = 0;
2775                 }
2776                 else
2777                 {
2778                         for (j = 0, s = p->states;j < p->numstates;j++, s++)
2779                                 deltabits[s->number] &= ~s->bits;
2780                         for (l = 0;l < (MAX_CL_STATS+7)/8;l++)
2781                                 statsdeltabits[l] &= ~p->statsdeltabits[l];
2782                 }
2783         }
2784
2785         for(i = 0; i < d->maxedicts; ++i)
2786         {
2787                 bits = deltabits[i] & ~d->deltabits[i];
2788                 if(bits)
2789                 {
2790                         d->deltabits[i] |= bits;
2791                         // if it was a very important update, set priority higher
2792                         if (bits & (E5_FULLUPDATE | E5_ATTACHMENT | E5_MODEL | E5_COLORMAP))
2793                                 d->priorities[i] = max(d->priorities[i], 4);
2794                         else
2795                                 d->priorities[i] = max(d->priorities[i], 1);
2796                 }
2797         }
2798
2799         for (l = 0;l < (MAX_CL_STATS+7)/8;l++)
2800                 host_client->statsdeltabits[l] |= statsdeltabits[l];
2801                 // no need to mask out the already-set bits here, as we do not
2802                 // do that priorities stuff
2803 }
2804
2805 void EntityFrame5_AckFrame(entityframe5_database_t *d, int framenum)
2806 {
2807         int i;
2808         // scan for packets made obsolete by this ack and delete them
2809         for (i = 0;i < ENTITYFRAME5_MAXPACKETLOGS;i++)
2810                 if (d->packetlog[i].packetnumber <= framenum)
2811                         d->packetlog[i].packetnumber = 0;
2812 }
2813
2814 qboolean EntityFrame5_WriteFrame(sizebuf_t *msg, int maxsize, entityframe5_database_t *d, int numstates, const entity_state_t **states, int viewentnum, int movesequence, qboolean need_empty)
2815 {
2816         prvm_prog_t *prog = SVVM_prog;
2817         const entity_state_t *n;
2818         int i, num, l, framenum, packetlognumber, priority;
2819         sizebuf_t buf;
2820         unsigned char data[128];
2821         entityframe5_packetlog_t *packetlog;
2822
2823         if (prog->max_edicts > d->maxedicts)
2824                 EntityFrame5_ExpandEdicts(d, prog->max_edicts);
2825
2826         framenum = d->latestframenum + 1;
2827         d->viewentnum = viewentnum;
2828
2829         // if packet log is full, mark all frames as lost, this will cause
2830         // it to send the lost data again
2831         for (packetlognumber = 0;packetlognumber < ENTITYFRAME5_MAXPACKETLOGS;packetlognumber++)
2832                 if (d->packetlog[packetlognumber].packetnumber == 0)
2833                         break;
2834         if (packetlognumber == ENTITYFRAME5_MAXPACKETLOGS)
2835         {
2836                 Con_DPrintf("EntityFrame5_WriteFrame: packetlog overflow for a client, resetting\n");
2837                 EntityFrame5_LostFrame(d, framenum);
2838                 packetlognumber = 0;
2839         }
2840
2841         // prepare the buffer
2842         memset(&buf, 0, sizeof(buf));
2843         buf.data = data;
2844         buf.maxsize = sizeof(data);
2845
2846         // detect changes in states
2847         num = 1;
2848         for (i = 0;i < numstates;i++)
2849         {
2850                 n = states[i];
2851                 // mark gaps in entity numbering as removed entities
2852                 for (;num < n->number;num++)
2853                 {
2854                         // if the entity used to exist, clear it
2855                         if (CHECKPVSBIT(d->visiblebits, num))
2856                         {
2857                                 CLEARPVSBIT(d->visiblebits, num);
2858                                 d->deltabits[num] = E5_FULLUPDATE;
2859                                 d->priorities[num] = max(d->priorities[num], 8); // removal is cheap
2860                                 d->states[num] = defaultstate;
2861                                 d->states[num].number = num;
2862                         }
2863                 }
2864                 // update the entity state data
2865                 if (!CHECKPVSBIT(d->visiblebits, num))
2866                 {
2867                         // entity just spawned in, don't let it completely hog priority
2868                         // because of being ancient on the first frame
2869                         d->updateframenum[num] = framenum;
2870                         // initial priority is a bit high to make projectiles send on the
2871                         // first frame, among other things
2872                         d->priorities[num] = max(d->priorities[num], 4);
2873                 }
2874                 SETPVSBIT(d->visiblebits, num);
2875                 d->deltabits[num] |= EntityState5_DeltaBits(d->states + num, n);
2876                 d->priorities[num] = max(d->priorities[num], 1);
2877                 d->states[num] = *n;
2878                 d->states[num].number = num;
2879                 // advance to next entity so the next iteration doesn't immediately remove it
2880                 num++;
2881         }
2882         // all remaining entities are dead
2883         for (;num < d->maxedicts;num++)
2884         {
2885                 if (CHECKPVSBIT(d->visiblebits, num))
2886                 {
2887                         CLEARPVSBIT(d->visiblebits, num);
2888                         d->deltabits[num] = E5_FULLUPDATE;
2889                         d->priorities[num] = max(d->priorities[num], 8); // removal is cheap
2890                         d->states[num] = defaultstate;
2891                         d->states[num].number = num;
2892                 }
2893         }
2894
2895         // if there isn't at least enough room for an empty svc_entities,
2896         // don't bother trying...
2897         if (buf.cursize + 11 > buf.maxsize)
2898                 return false;
2899
2900         // build lists of entities by priority level
2901         memset(d->prioritychaincounts, 0, sizeof(d->prioritychaincounts));
2902         l = 0;
2903         for (num = 0;num < d->maxedicts;num++)
2904         {
2905                 if (d->priorities[num])
2906                 {
2907                         if (d->deltabits[num])
2908                         {
2909                                 if (d->priorities[num] < (ENTITYFRAME5_PRIORITYLEVELS - 1))
2910                                         d->priorities[num] = EntityState5_Priority(d, num);
2911                                 l = num;
2912                                 priority = d->priorities[num];
2913                                 if (d->prioritychaincounts[priority] < ENTITYFRAME5_MAXSTATES)
2914                                         d->prioritychains[priority][d->prioritychaincounts[priority]++] = num;
2915                         }
2916                         else
2917                                 d->priorities[num] = 0;
2918                 }
2919         }
2920
2921         packetlog = NULL;
2922         // write stat updates
2923         if (sv.protocol != PROTOCOL_QUAKE && sv.protocol != PROTOCOL_QUAKEDP && sv.protocol != PROTOCOL_NEHAHRAMOVIE && sv.protocol != PROTOCOL_NEHAHRABJP && sv.protocol != PROTOCOL_NEHAHRABJP2 && sv.protocol != PROTOCOL_NEHAHRABJP3 && sv.protocol != PROTOCOL_DARKPLACES1 && sv.protocol != PROTOCOL_DARKPLACES2 && sv.protocol != PROTOCOL_DARKPLACES3 && sv.protocol != PROTOCOL_DARKPLACES4 && sv.protocol != PROTOCOL_DARKPLACES5)
2924         {
2925                 for (i = 0;i < MAX_CL_STATS && msg->cursize + 6 + 11 <= maxsize;i++)
2926                 {
2927                         if (host_client->statsdeltabits[i>>3] & (1<<(i&7)))
2928                         {
2929                                 host_client->statsdeltabits[i>>3] &= ~(1<<(i&7));
2930                                 // add packetlog entry now that we have something for it
2931                                 if (!packetlog)
2932                                 {
2933                                         packetlog = d->packetlog + packetlognumber;
2934                                         packetlog->packetnumber = framenum;
2935                                         packetlog->numstates = 0;
2936                                         memset(packetlog->statsdeltabits, 0, sizeof(packetlog->statsdeltabits));
2937                                 }
2938                                 packetlog->statsdeltabits[i>>3] |= (1<<(i&7));
2939                                 if (host_client->stats[i] >= 0 && host_client->stats[i] < 256)
2940                                 {
2941                                         MSG_WriteByte(msg, svc_updatestatubyte);
2942                                         MSG_WriteByte(msg, i);
2943                                         MSG_WriteByte(msg, host_client->stats[i]);
2944                                         l = 1;
2945                                 }
2946                                 else
2947                                 {
2948                                         MSG_WriteByte(msg, svc_updatestat);
2949                                         MSG_WriteByte(msg, i);
2950                                         MSG_WriteLong(msg, host_client->stats[i]);
2951                                         l = 1;
2952                                 }
2953                         }
2954                 }
2955         }
2956
2957         // only send empty svc_entities frame if needed
2958         if(!l && !need_empty)
2959                 return false;
2960
2961         // add packetlog entry now that we have something for it
2962         if (!packetlog)
2963         {
2964                 packetlog = d->packetlog + packetlognumber;
2965                 packetlog->packetnumber = framenum;
2966                 packetlog->numstates = 0;
2967                 memset(packetlog->statsdeltabits, 0, sizeof(packetlog->statsdeltabits));
2968         }
2969
2970         // write state updates
2971         if (developer_networkentities.integer >= 10)
2972                 Con_Printf("send: svc_entities %i\n", framenum);
2973         d->latestframenum = framenum;
2974         MSG_WriteByte(msg, svc_entities);
2975         MSG_WriteLong(msg, framenum);
2976         if (sv.protocol != PROTOCOL_QUAKE && sv.protocol != PROTOCOL_QUAKEDP && sv.protocol != PROTOCOL_NEHAHRAMOVIE && sv.protocol != PROTOCOL_DARKPLACES1 && sv.protocol != PROTOCOL_DARKPLACES2 && sv.protocol != PROTOCOL_DARKPLACES3 && sv.protocol != PROTOCOL_DARKPLACES4 && sv.protocol != PROTOCOL_DARKPLACES5 && sv.protocol != PROTOCOL_DARKPLACES6)
2977                 MSG_WriteLong(msg, movesequence);
2978         for (priority = ENTITYFRAME5_PRIORITYLEVELS - 1;priority >= 0 && packetlog->numstates < ENTITYFRAME5_MAXSTATES;priority--)
2979         {
2980                 for (i = 0;i < d->prioritychaincounts[priority] && packetlog->numstates < ENTITYFRAME5_MAXSTATES;i++)
2981                 {
2982                         num = d->prioritychains[priority][i];
2983                         n = d->states + num;
2984                         if (d->deltabits[num] & E5_FULLUPDATE)
2985                                 d->deltabits[num] = E5_FULLUPDATE | EntityState5_DeltaBits(&defaultstate, n);
2986                         buf.cursize = 0;
2987                         EntityState5_WriteUpdate(num, n, d->deltabits[num], &buf);
2988                         // if the entity won't fit, try the next one
2989                         if (msg->cursize + buf.cursize + 2 > maxsize)
2990                                 continue;
2991                         // write entity to the packet
2992                         SZ_Write(msg, buf.data, buf.cursize);
2993                         // mark age on entity for prioritization
2994                         d->updateframenum[num] = framenum;
2995                         // log entity so deltabits can be restored later if lost
2996                         packetlog->states[packetlog->numstates].number = num;
2997                         packetlog->states[packetlog->numstates].bits = d->deltabits[num];
2998                         packetlog->numstates++;
2999                         // clear deltabits and priority so it won't be sent again
3000                         d->deltabits[num] = 0;
3001                         d->priorities[num] = 0;
3002                 }
3003         }
3004         MSG_WriteShort(msg, 0x8000);
3005
3006         return true;
3007 }
3008
3009
3010 static void QW_TranslateEffects(entity_state_t *s, int qweffects)
3011 {
3012         s->effects = 0;
3013         s->internaleffects = 0;
3014         if (qweffects & QW_EF_BRIGHTFIELD)
3015                 s->effects |= EF_BRIGHTFIELD;
3016         if (qweffects & QW_EF_MUZZLEFLASH)
3017                 s->effects |= EF_MUZZLEFLASH;
3018         if (qweffects & QW_EF_FLAG1)
3019         {
3020                 // mimic FTEQW's interpretation of EF_FLAG1 as EF_NODRAW on non-player entities
3021                 if (s->number > cl.maxclients)
3022                         s->effects |= EF_NODRAW;
3023                 else
3024                         s->internaleffects |= INTEF_FLAG1QW;
3025         }
3026         if (qweffects & QW_EF_FLAG2)
3027         {
3028                 // mimic FTEQW's interpretation of EF_FLAG2 as EF_ADDITIVE on non-player entities
3029                 if (s->number > cl.maxclients)
3030                         s->effects |= EF_ADDITIVE;
3031                 else
3032                         s->internaleffects |= INTEF_FLAG2QW;
3033         }
3034         if (qweffects & QW_EF_RED)
3035         {
3036                 if (qweffects & QW_EF_BLUE)
3037                         s->effects |= EF_RED | EF_BLUE;
3038                 else
3039                         s->effects |= EF_RED;
3040         }
3041         else if (qweffects & QW_EF_BLUE)
3042                 s->effects |= EF_BLUE;
3043         else if (qweffects & QW_EF_BRIGHTLIGHT)
3044                 s->effects |= EF_BRIGHTLIGHT;
3045         else if (qweffects & QW_EF_DIMLIGHT)
3046                 s->effects |= EF_DIMLIGHT;
3047 }
3048
3049 void EntityStateQW_ReadPlayerUpdate(void)
3050 {
3051         int slot = MSG_ReadByte(&cl_message);
3052         int enumber = slot + 1;
3053         int weaponframe;
3054         int msec;
3055         int playerflags;
3056         int bits;
3057         entity_state_t *s;
3058         // look up the entity
3059         entity_t *ent = cl.entities + enumber;
3060         vec3_t viewangles;
3061         vec3_t velocity;
3062
3063         // slide the current state into the previous
3064         ent->state_previous = ent->state_current;
3065
3066         // read the update
3067         s = &ent->state_current;
3068         *s = defaultstate;
3069         s->active = ACTIVE_NETWORK;
3070         s->number = enumber;
3071         s->colormap = enumber;
3072         playerflags = MSG_ReadShort(&cl_message);
3073         MSG_ReadVector(&cl_message, s->origin, cls.protocol);
3074         s->frame = MSG_ReadByte(&cl_message);
3075
3076         VectorClear(viewangles);
3077         VectorClear(velocity);
3078
3079         if (playerflags & QW_PF_MSEC)
3080         {
3081                 // time difference between last update this player sent to the server,
3082                 // and last input we sent to the server (this packet is in response to
3083                 // our input, so msec is how long ago the last update of this player
3084                 // entity occurred, compared to our input being received)
3085                 msec = MSG_ReadByte(&cl_message);
3086         }
3087         else
3088                 msec = 0;
3089         if (playerflags & QW_PF_COMMAND)
3090         {
3091                 bits = MSG_ReadByte(&cl_message);
3092                 if (bits & QW_CM_ANGLE1)
3093                         viewangles[0] = MSG_ReadAngle16i(&cl_message); // cmd->angles[0]
3094                 if (bits & QW_CM_ANGLE2)
3095                         viewangles[1] = MSG_ReadAngle16i(&cl_message); // cmd->angles[1]
3096                 if (bits & QW_CM_ANGLE3)
3097                         viewangles[2] = MSG_ReadAngle16i(&cl_message); // cmd->angles[2]
3098                 if (bits & QW_CM_FORWARD)
3099                         MSG_ReadShort(&cl_message); // cmd->forwardmove
3100                 if (bits & QW_CM_SIDE)
3101                         MSG_ReadShort(&cl_message); // cmd->sidemove
3102                 if (bits & QW_CM_UP)
3103                         MSG_ReadShort(&cl_message); // cmd->upmove
3104                 if (bits & QW_CM_BUTTONS)
3105                         (void) MSG_ReadByte(&cl_message); // cmd->buttons
3106                 if (bits & QW_CM_IMPULSE)
3107                         (void) MSG_ReadByte(&cl_message); // cmd->impulse
3108                 (void) MSG_ReadByte(&cl_message); // cmd->msec
3109         }
3110         if (playerflags & QW_PF_VELOCITY1)
3111                 velocity[0] = MSG_ReadShort(&cl_message);
3112         if (playerflags & QW_PF_VELOCITY2)
3113                 velocity[1] = MSG_ReadShort(&cl_message);
3114         if (playerflags & QW_PF_VELOCITY3)
3115                 velocity[2] = MSG_ReadShort(&cl_message);
3116         if (playerflags & QW_PF_MODEL)
3117                 s->modelindex = MSG_ReadByte(&cl_message);
3118         else
3119                 s->modelindex = cl.qw_modelindex_player;
3120         if (playerflags & QW_PF_SKINNUM)
3121                 s->skin = MSG_ReadByte(&cl_message);
3122         if (playerflags & QW_PF_EFFECTS)
3123                 QW_TranslateEffects(s, MSG_ReadByte(&cl_message));
3124         if (playerflags & QW_PF_WEAPONFRAME)
3125                 weaponframe = MSG_ReadByte(&cl_message);
3126         else
3127                 weaponframe = 0;
3128
3129         if (enumber == cl.playerentity)
3130         {
3131                 // if this is an update on our player, update the angles
3132                 VectorCopy(cl.viewangles, viewangles);
3133         }
3134
3135         // calculate the entity angles from the viewangles
3136         s->angles[0] = viewangles[0] * -0.0333;
3137         s->angles[1] = viewangles[1];
3138         s->angles[2] = 0;
3139         s->angles[2] = V_CalcRoll(s->angles, velocity)*4;
3140
3141         // if this is an update on our player, update interpolation state
3142         if (enumber == cl.playerentity)
3143         {
3144                 VectorCopy (cl.mpunchangle[0], cl.mpunchangle[1]);
3145                 VectorCopy (cl.mpunchvector[0], cl.mpunchvector[1]);
3146                 VectorCopy (cl.mvelocity[0], cl.mvelocity[1]);
3147                 cl.mviewzoom[1] = cl.mviewzoom[0];
3148
3149                 cl.idealpitch = 0;
3150                 cl.mpunchangle[0][0] = 0;
3151                 cl.mpunchangle[0][1] = 0;
3152                 cl.mpunchangle[0][2] = 0;
3153                 cl.mpunchvector[0][0] = 0;
3154                 cl.mpunchvector[0][1] = 0;
3155                 cl.mpunchvector[0][2] = 0;
3156                 cl.mvelocity[0][0] = 0;
3157                 cl.mvelocity[0][1] = 0;
3158                 cl.mvelocity[0][2] = 0;
3159                 cl.mviewzoom[0] = 1;
3160
3161                 VectorCopy(velocity, cl.mvelocity[0]);
3162                 cl.stats[STAT_WEAPONFRAME] = weaponframe;
3163                 if (playerflags & QW_PF_GIB)
3164                         cl.stats[STAT_VIEWHEIGHT] = 8;
3165                 else if (playerflags & QW_PF_DEAD)
3166                         cl.stats[STAT_VIEWHEIGHT] = -16;
3167                 else
3168                         cl.stats[STAT_VIEWHEIGHT] = 22;
3169         }
3170
3171         // set the cl.entities_active flag
3172         cl.entities_active[enumber] = (s->active == ACTIVE_NETWORK);
3173         // set the update time
3174         s->time = cl.mtime[0] - msec * 0.001; // qw has no clock
3175         // check if we need to update the lerp stuff
3176         if (s->active == ACTIVE_NETWORK)
3177                 CL_MoveLerpEntityStates(&cl.entities[enumber]);
3178 }
3179
3180 static void EntityStateQW_ReadEntityUpdate(entity_state_t *s, int bits)
3181 {
3182         int qweffects = 0;
3183         s->active = ACTIVE_NETWORK;
3184         s->number = bits & 511;
3185         bits &= ~511;
3186         if (bits & QW_U_MOREBITS)
3187                 bits |= MSG_ReadByte(&cl_message);
3188
3189         // store the QW_U_SOLID bit here?
3190
3191         if (bits & QW_U_MODEL)
3192                 s->modelindex = MSG_ReadByte(&cl_message);
3193         if (bits & QW_U_FRAME)
3194                 s->frame = MSG_ReadByte(&cl_message);
3195         if (bits & QW_U_COLORMAP)
3196                 s->colormap = MSG_ReadByte(&cl_message);
3197         if (bits & QW_U_SKIN)
3198                 s->skin = MSG_ReadByte(&cl_message);
3199         if (bits & QW_U_EFFECTS)
3200                 QW_TranslateEffects(s, qweffects = MSG_ReadByte(&cl_message));
3201         if (bits & QW_U_ORIGIN1)
3202                 s->origin[0] = MSG_ReadCoord13i(&cl_message);
3203         if (bits & QW_U_ANGLE1)
3204                 s->angles[0] = MSG_ReadAngle8i(&cl_message);
3205         if (bits & QW_U_ORIGIN2)
3206                 s->origin[1] = MSG_ReadCoord13i(&cl_message);
3207         if (bits & QW_U_ANGLE2)
3208                 s->angles[1] = MSG_ReadAngle8i(&cl_message);
3209         if (bits & QW_U_ORIGIN3)
3210                 s->origin[2] = MSG_ReadCoord13i(&cl_message);
3211         if (bits & QW_U_ANGLE3)
3212                 s->angles[2] = MSG_ReadAngle8i(&cl_message);
3213
3214         if (developer_networkentities.integer >= 2)
3215         {
3216                 Con_Printf("ReadFields e%i", s->number);
3217                 if (bits & QW_U_MODEL)
3218                         Con_Printf(" U_MODEL %i", s->modelindex);
3219                 if (bits & QW_U_FRAME)
3220                         Con_Printf(" U_FRAME %i", s->frame);
3221                 if (bits & QW_U_COLORMAP)
3222                         Con_Printf(" U_COLORMAP %i", s->colormap);
3223                 if (bits & QW_U_SKIN)
3224                         Con_Printf(" U_SKIN %i", s->skin);
3225                 if (bits & QW_U_EFFECTS)
3226                         Con_Printf(" U_EFFECTS %i", qweffects);
3227                 if (bits & QW_U_ORIGIN1)
3228                         Con_Printf(" U_ORIGIN1 %f", s->origin[0]);
3229                 if (bits & QW_U_ANGLE1)
3230                         Con_Printf(" U_ANGLE1 %f", s->angles[0]);
3231                 if (bits & QW_U_ORIGIN2)
3232                         Con_Printf(" U_ORIGIN2 %f", s->origin[1]);
3233                 if (bits & QW_U_ANGLE2)
3234                         Con_Printf(" U_ANGLE2 %f", s->angles[1]);
3235                 if (bits & QW_U_ORIGIN3)
3236                         Con_Printf(" U_ORIGIN3 %f", s->origin[2]);
3237                 if (bits & QW_U_ANGLE3)
3238                         Con_Printf(" U_ANGLE3 %f", s->angles[2]);
3239                 if (bits & QW_U_SOLID)
3240                         Con_Printf(" U_SOLID");
3241                 Con_Print("\n");
3242         }
3243 }
3244
3245 entityframeqw_database_t *EntityFrameQW_AllocDatabase(mempool_t *pool)
3246 {
3247         entityframeqw_database_t *d;
3248         d = (entityframeqw_database_t *)Mem_Alloc(pool, sizeof(*d));
3249         return d;
3250 }
3251
3252 void EntityFrameQW_FreeDatabase(entityframeqw_database_t *d)
3253 {
3254         Mem_Free(d);
3255 }
3256
3257 void EntityFrameQW_CL_ReadFrame(qboolean delta)
3258 {
3259         qboolean invalid = false;
3260         int number, oldsnapindex, newsnapindex, oldindex, newindex, oldnum, newnum;
3261         entity_t *ent;
3262         entityframeqw_database_t *d;
3263         entityframeqw_snapshot_t *oldsnap, *newsnap;
3264
3265         if (!cl.entitydatabaseqw)
3266                 cl.entitydatabaseqw = EntityFrameQW_AllocDatabase(cls.levelmempool);
3267         d = cl.entitydatabaseqw;
3268
3269         // there is no cls.netcon in demos, so this reading code can't access
3270         // cls.netcon-> at all...  so cls.qw_incoming_sequence and
3271         // cls.qw_outgoing_sequence are updated every time the corresponding
3272         // cls.netcon->qw. variables are updated
3273         // read the number of this frame to echo back in next input packet
3274         cl.qw_validsequence = cls.qw_incoming_sequence;
3275         newsnapindex = cl.qw_validsequence & QW_UPDATE_MASK;
3276         newsnap = d->snapshot + newsnapindex;
3277         memset(newsnap, 0, sizeof(*newsnap));
3278         oldsnap = NULL;
3279         if (delta)
3280         {
3281                 number = MSG_ReadByte(&cl_message);
3282                 oldsnapindex = cl.qw_deltasequence[newsnapindex];
3283                 if ((number & QW_UPDATE_MASK) != (oldsnapindex & QW_UPDATE_MASK))
3284                         Con_DPrintf("WARNING: from mismatch\n");
3285                 if (oldsnapindex != -1)
3286                 {
3287                         if (cls.qw_outgoing_sequence - oldsnapindex >= QW_UPDATE_BACKUP-1)
3288                         {
3289                                 Con_DPrintf("delta update too old\n");
3290                                 newsnap->invalid = invalid = true; // too old
3291                                 delta = false;
3292                         }
3293                         oldsnap = d->snapshot + (oldsnapindex & QW_UPDATE_MASK);
3294                 }
3295                 else
3296                         delta = false;
3297         }
3298
3299         // if we can't decode this frame properly, report that to the server
3300         if (invalid)
3301                 cl.qw_validsequence = 0;
3302
3303         // read entity numbers until we find a 0x0000
3304         // (which would be an empty update on world entity, but is actually a terminator)
3305         newsnap->num_entities = 0;
3306         oldindex = 0;
3307         for (;;)
3308         {
3309                 int word = (unsigned short)MSG_ReadShort(&cl_message);
3310                 if (cl_message.badread)
3311                         return; // just return, the main parser will print an error
3312                 newnum = word == 0 ? 512 : (word & 511);
3313                 oldnum = delta ? (oldindex >= oldsnap->num_entities ? 9999 : oldsnap->entities[oldindex].number) : 9999;
3314
3315                 // copy unmodified oldsnap entities
3316                 while (newnum > oldnum) // delta only
3317                 {
3318                         if (developer_networkentities.integer >= 2)
3319                                 Con_Printf("copy %i\n", oldnum);
3320                         // copy one of the old entities
3321                         if (newsnap->num_entities >= QW_MAX_PACKET_ENTITIES)
3322                                 Host_Error("EntityFrameQW_CL_ReadFrame: newsnap->num_entities == MAX_PACKETENTITIES");
3323                         newsnap->entities[newsnap->num_entities] = oldsnap->entities[oldindex++];
3324                         newsnap->num_entities++;
3325                         oldnum = oldindex >= oldsnap->num_entities ? 9999 : oldsnap->entities[oldindex].number;
3326                 }
3327
3328                 if (word == 0)
3329                         break;
3330
3331                 if (developer_networkentities.integer >= 2)
3332                 {
3333                         if (word & QW_U_REMOVE)
3334                                 Con_Printf("remove %i\n", newnum);
3335                         else if (newnum == oldnum)
3336                                 Con_Printf("delta %i\n", newnum);
3337                         else
3338                                 Con_Printf("baseline %i\n", newnum);
3339                 }
3340
3341                 if (word & QW_U_REMOVE)
3342                 {
3343                         if (newnum != oldnum && !delta && !invalid)
3344                         {
3345                                 cl.qw_validsequence = 0;
3346                                 Con_Printf("WARNING: U_REMOVE %i on full update\n", newnum);
3347                         }
3348                 }
3349                 else
3350                 {
3351                         if (newsnap->num_entities >= QW_MAX_PACKET_ENTITIES)
3352                                 Host_Error("EntityFrameQW_CL_ReadFrame: newsnap->num_entities == MAX_PACKETENTITIES");
3353                         newsnap->entities[newsnap->num_entities] = (newnum == oldnum) ? oldsnap->entities[oldindex] : cl.entities[newnum].state_baseline;
3354                         EntityStateQW_ReadEntityUpdate(newsnap->entities + newsnap->num_entities, word);
3355                         newsnap->num_entities++;
3356                 }
3357
3358                 if (newnum == oldnum)
3359                         oldindex++;
3360         }
3361
3362         // expand cl.num_entities to include every entity we've seen this game
3363         newnum = newsnap->num_entities ? newsnap->entities[newsnap->num_entities - 1].number : 1;
3364         if (cl.num_entities <= newnum)
3365         {
3366                 cl.num_entities = newnum + 1;
3367                 if (cl.max_entities < newnum + 1)
3368                         CL_ExpandEntities(newnum);
3369         }
3370
3371         // now update the non-player entities from the snapshot states
3372         number = cl.maxclients + 1;
3373         for (newindex = 0;;newindex++)
3374         {
3375                 newnum = newindex >= newsnap->num_entities ? cl.num_entities : newsnap->entities[newindex].number;
3376                 // kill any missing entities
3377                 for (;number < newnum;number++)
3378                 {
3379                         if (cl.entities_active[number])
3380                         {
3381                                 cl.entities_active[number] = false;
3382                                 cl.entities[number].state_current.active = ACTIVE_NOT;
3383                         }
3384                 }
3385                 if (number >= cl.num_entities)
3386                         break;
3387                 // update the entity
3388                 ent = &cl.entities[number];
3389                 ent->state_previous = ent->state_current;
3390                 ent->state_current = newsnap->entities[newindex];
3391                 ent->state_current.time = cl.mtime[0];
3392                 CL_MoveLerpEntityStates(ent);
3393                 // the entity lives again...
3394                 cl.entities_active[number] = true;
3395                 number++;
3396         }
3397 }