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