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