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