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