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