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