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