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