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