fixed lingering entities in quake protocol (off by one error in the entity removal...
[divverent/darkplaces.git] / protocol.c
1
2 #include "quakedef.h"
3
4 // this is 80 bytes
5 entity_state_t defaultstate =
6 {
7         // ! means this is not sent to client
8         0,//double time; // ! time this state was built (used on client for interpolation)
9         {0,0,0},//float origin[3];
10         {0,0,0},//float angles[3];
11         0,//int number; // entity number this state is for
12         0,//int effects;
13         0,//unsigned short modelindex;
14         0,//unsigned short frame;
15         0,//unsigned short tagentity;
16         0,//unsigned short specialvisibilityradius; // ! larger if it has effects/light
17         0,//unsigned short viewmodelforclient; // !
18         0,//unsigned short exteriormodelforclient; // ! not shown if first person viewing from this entity, shown in all other cases
19         0,//unsigned short nodrawtoclient; // !
20         0,//unsigned short drawonlytoclient; // !
21         {0,0,0,0},//unsigned short light[4]; // color*256 (0.00 to 255.996), and radius*1
22         0,//unsigned char active; // true if a valid state
23         0,//unsigned char lightstyle;
24         0,//unsigned char lightpflags;
25         0,//unsigned char colormap;
26         0,//unsigned char skin; // also chooses cubemap for rtlights if lightpflags & LIGHTPFLAGS_FULLDYNAMIC
27         255,//unsigned char alpha;
28         16,//unsigned char scale;
29         0,//unsigned char glowsize;
30         254,//unsigned char glowcolor;
31         0,//unsigned char flags;
32         0,//unsigned char tagindex;
33         255,//unsigned char colormod;
34         // padding to a multiple of 8 bytes (to align the double time)
35         {0,0,0,0}//unsigned char unused[4]; // !
36 };
37
38 // keep track of quake entities because they need to be killed if they get stale
39 int cl_lastquakeentity = 0;
40 qbyte cl_isquakeentity[MAX_EDICTS];
41
42 void EntityFrameQuake_ReadEntity(int bits)
43 {
44         int num;
45         entity_t *ent;
46         entity_state_t s;
47
48         if (bits & U_MOREBITS)
49                 bits |= (MSG_ReadByte()<<8);
50         if ((bits & U_EXTEND1) && cl.protocol != PROTOCOL_NEHAHRAMOVIE)
51         {
52                 bits |= MSG_ReadByte() << 16;
53                 if (bits & U_EXTEND2)
54                         bits |= MSG_ReadByte() << 24;
55         }
56
57         if (bits & U_LONGENTITY)
58                 num = (unsigned short) MSG_ReadShort ();
59         else
60                 num = MSG_ReadByte ();
61
62         if (num >= MAX_EDICTS)
63                 Host_Error("EntityFrameQuake_ReadEntity: entity number (%i) >= MAX_EDICTS (%i)\n", num, MAX_EDICTS);
64         if (num < 1)
65                 Host_Error("EntityFrameQuake_ReadEntity: invalid entity number (%i)\n", num);
66
67         ent = cl_entities + num;
68
69         // note: this inherits the 'active' state of the baseline chosen
70         // (state_baseline is always active, state_current may not be active if
71         // the entity was missing in the last frame)
72         if (bits & U_DELTA)
73                 s = ent->state_current;
74         else
75         {
76                 s = ent->state_baseline;
77                 s.active = true;
78         }
79
80         cl_isquakeentity[num] = true;
81         if (cl_lastquakeentity < num)
82                 cl_lastquakeentity = num;
83         s.number = num;
84         s.time = cl.mtime[0];
85         s.flags = 0;
86         if (bits & U_MODEL)             s.modelindex = (s.modelindex & 0xFF00) | MSG_ReadByte();
87         if (bits & U_FRAME)             s.frame = (s.frame & 0xFF00) | MSG_ReadByte();
88         if (bits & U_COLORMAP)  s.colormap = MSG_ReadByte();
89         if (bits & U_SKIN)              s.skin = MSG_ReadByte();
90         if (bits & U_EFFECTS)   s.effects = (s.effects & 0xFF00) | MSG_ReadByte();
91         if (bits & U_ORIGIN1)   s.origin[0] = MSG_ReadCoord(cl.protocol);
92         if (bits & U_ANGLE1)    s.angles[0] = MSG_ReadAngle(cl.protocol);
93         if (bits & U_ORIGIN2)   s.origin[1] = MSG_ReadCoord(cl.protocol);
94         if (bits & U_ANGLE2)    s.angles[1] = MSG_ReadAngle(cl.protocol);
95         if (bits & U_ORIGIN3)   s.origin[2] = MSG_ReadCoord(cl.protocol);
96         if (bits & U_ANGLE3)    s.angles[2] = MSG_ReadAngle(cl.protocol);
97         if (bits & U_STEP)              s.flags |= RENDER_STEP;
98         if (bits & U_ALPHA)             s.alpha = MSG_ReadByte();
99         if (bits & U_SCALE)             s.scale = MSG_ReadByte();
100         if (bits & U_EFFECTS2)  s.effects = (s.effects & 0x00FF) | (MSG_ReadByte() << 8);
101         if (bits & U_GLOWSIZE)  s.glowsize = MSG_ReadByte();
102         if (bits & U_GLOWCOLOR) s.glowcolor = MSG_ReadByte();
103         if (bits & U_COLORMOD)  s.colormod = MSG_ReadByte();
104         if (bits & U_GLOWTRAIL) s.flags |= RENDER_GLOWTRAIL;
105         if (bits & U_FRAME2)    s.frame = (s.frame & 0x00FF) | (MSG_ReadByte() << 8);
106         if (bits & U_MODEL2)    s.modelindex = (s.modelindex & 0x00FF) | (MSG_ReadByte() << 8);
107         if (bits & U_VIEWMODEL) s.flags |= RENDER_VIEWMODEL;
108         if (bits & U_EXTERIORMODEL)     s.flags |= RENDER_EXTERIORMODEL;
109
110         // LordHavoc: to allow playback of the Nehahra movie
111         if (cl.protocol == PROTOCOL_NEHAHRAMOVIE && (bits & U_EXTEND1))
112         {
113                 // LordHavoc: evil format
114                 int i = MSG_ReadFloat();
115                 int j = MSG_ReadFloat() * 255.0f;
116                 if (i == 2)
117                 {
118                         i = MSG_ReadFloat();
119                         if (i)
120                                 s.effects |= EF_FULLBRIGHT;
121                 }
122                 if (j < 0)
123                         s.alpha = 0;
124                 else if (j == 0 || j >= 255)
125                         s.alpha = 255;
126                 else
127                         s.alpha = j;
128         }
129
130         ent->state_previous = ent->state_current;
131         ent->state_current = s;
132         if (ent->state_current.active)
133         {
134                 CL_MoveLerpEntityStates(ent);
135                 cl_entities_active[ent->state_current.number] = true;
136         }
137
138         if (msg_badread)
139                 Host_Error("EntityFrameQuake_ReadEntity: read error\n");
140 }
141
142 void EntityFrameQuake_ISeeDeadEntities(void)
143 {
144         int num, lastentity;
145         if (cl_lastquakeentity == 0)
146                 return;
147         lastentity = cl_lastquakeentity;
148         cl_lastquakeentity = 0;
149         for (num = 0;num <= lastentity;num++)
150         {
151                 if (cl_isquakeentity[num])
152                 {
153                         if (cl_entities_active[num] && cl_entities[num].state_current.time == cl.mtime[0])
154                         {
155                                 cl_isquakeentity[num] = true;
156                                 cl_lastquakeentity = num;
157                         }
158                         else
159                         {
160                                 cl_isquakeentity[num] = false;
161                                 cl_entities_active[num] = false;
162                                 cl_entities[num].state_current = defaultstate;
163                                 cl_entities[num].state_current.number = num;
164                         }
165                 }
166         }
167 }
168
169 void EntityFrameQuake_WriteFrame(sizebuf_t *msg, int numstates, const entity_state_t *states)
170 {
171         const entity_state_t *s;
172         entity_state_t baseline;
173         int i, bits;
174         sizebuf_t buf;
175         qbyte data[128];
176
177         // prepare the buffer
178         memset(&buf, 0, sizeof(buf));
179         buf.data = data;
180         buf.maxsize = sizeof(data);
181
182         for (i = 0, s = states;i < numstates;i++, s++)
183         {
184                 // prepare the buffer
185                 SZ_Clear(&buf);
186
187 // send an update
188                 bits = 0;
189                 if (s->number >= 256)
190                         bits |= U_LONGENTITY;
191                 if (s->flags & RENDER_STEP)
192                         bits |= U_STEP;
193                 if (s->flags & RENDER_VIEWMODEL)
194                         bits |= U_VIEWMODEL;
195                 if (s->flags & RENDER_GLOWTRAIL)
196                         bits |= U_GLOWTRAIL;
197                 if (s->flags & RENDER_EXTERIORMODEL)
198                         bits |= U_EXTERIORMODEL;
199
200                 // LordHavoc: old stuff, but rewritten to have more exact tolerances
201                 baseline = sv.edicts[s->number].e->baseline;
202                 if (baseline.origin[0] != s->origin[0])
203                         bits |= U_ORIGIN1;
204                 if (baseline.origin[1] != s->origin[1])
205                         bits |= U_ORIGIN2;
206                 if (baseline.origin[2] != s->origin[2])
207                         bits |= U_ORIGIN3;
208                 if (baseline.angles[0] != s->angles[0])
209                         bits |= U_ANGLE1;
210                 if (baseline.angles[1] != s->angles[1])
211                         bits |= U_ANGLE2;
212                 if (baseline.angles[2] != s->angles[2])
213                         bits |= U_ANGLE3;
214                 if (baseline.colormap != s->colormap)
215                         bits |= U_COLORMAP;
216                 if (baseline.skin != s->skin)
217                         bits |= U_SKIN;
218                 if (baseline.frame != s->frame)
219                 {
220                         bits |= U_FRAME;
221                         if (s->frame & 0xFF00)
222                                 bits |= U_FRAME2;
223                 }
224                 if (baseline.effects != s->effects)
225                 {
226                         bits |= U_EFFECTS;
227                         if (s->effects & 0xFF00)
228                                 bits |= U_EFFECTS2;
229                 }
230                 if (baseline.modelindex != s->modelindex)
231                 {
232                         bits |= U_MODEL;
233                         if (s->modelindex & 0xFF00)
234                                 bits |= U_MODEL2;
235                 }
236                 if (baseline.alpha != s->alpha)
237                         bits |= U_ALPHA;
238                 if (baseline.scale != s->scale)
239                         bits |= U_SCALE;
240                 if (baseline.glowsize != s->glowsize)
241                         bits |= U_GLOWSIZE;
242                 if (baseline.glowcolor != s->glowcolor)
243                         bits |= U_GLOWCOLOR;
244
245                 // if extensions are disabled, clear the relevant update flags
246                 if (sv.netquakecompatible)
247                         bits &= 0x7FFF;
248
249                 // write the message
250                 if (bits >= 16777216)
251                         bits |= U_EXTEND2;
252                 if (bits >= 65536)
253                         bits |= U_EXTEND1;
254                 if (bits >= 256)
255                         bits |= U_MOREBITS;
256                 bits |= U_SIGNAL;
257
258                 MSG_WriteByte (&buf, bits);
259                 if (bits & U_MOREBITS)          MSG_WriteByte(&buf, bits>>8);
260                 if (bits & U_EXTEND1)           MSG_WriteByte(&buf, bits>>16);
261                 if (bits & U_EXTEND2)           MSG_WriteByte(&buf, bits>>24);
262                 if (bits & U_LONGENTITY)        MSG_WriteShort(&buf, s->number);
263                 else                                            MSG_WriteByte(&buf, s->number);
264
265                 if (bits & U_MODEL)                     MSG_WriteByte(&buf, s->modelindex);
266                 if (bits & U_FRAME)                     MSG_WriteByte(&buf, s->frame);
267                 if (bits & U_COLORMAP)          MSG_WriteByte(&buf, s->colormap);
268                 if (bits & U_SKIN)                      MSG_WriteByte(&buf, s->skin);
269                 if (bits & U_EFFECTS)           MSG_WriteByte(&buf, s->effects);
270                 if (bits & U_ORIGIN1)           MSG_WriteCoord(&buf, s->origin[0], sv.protocol);
271                 if (bits & U_ANGLE1)            MSG_WriteAngle(&buf, s->angles[0], sv.protocol);
272                 if (bits & U_ORIGIN2)           MSG_WriteCoord(&buf, s->origin[1], sv.protocol);
273                 if (bits & U_ANGLE2)            MSG_WriteAngle(&buf, s->angles[1], sv.protocol);
274                 if (bits & U_ORIGIN3)           MSG_WriteCoord(&buf, s->origin[2], sv.protocol);
275                 if (bits & U_ANGLE3)            MSG_WriteAngle(&buf, s->angles[2], sv.protocol);
276                 if (bits & U_ALPHA)                     MSG_WriteByte(&buf, s->alpha);
277                 if (bits & U_SCALE)                     MSG_WriteByte(&buf, s->scale);
278                 if (bits & U_EFFECTS2)          MSG_WriteByte(&buf, s->effects >> 8);
279                 if (bits & U_GLOWSIZE)          MSG_WriteByte(&buf, s->glowsize);
280                 if (bits & U_GLOWCOLOR)         MSG_WriteByte(&buf, s->glowcolor);
281                 if (bits & U_COLORMOD)          MSG_WriteByte(&buf, s->colormod);
282                 if (bits & U_FRAME2)            MSG_WriteByte(&buf, s->frame >> 8);
283                 if (bits & U_MODEL2)            MSG_WriteByte(&buf, s->modelindex >> 8);
284
285                 // if the commit is full, we're done this frame
286                 if (msg->cursize + buf.cursize > msg->maxsize)
287                 {
288                         // next frame we will continue where we left off
289                         break;
290                 }
291                 // write the message to the packet
292                 SZ_Write(msg, buf.data, buf.cursize);
293         }
294 }
295
296 int EntityState_DeltaBits(const entity_state_t *o, const entity_state_t *n)
297 {
298         unsigned int bits;
299         // if o is not active, delta from default
300         if (!o->active)
301                 o = &defaultstate;
302         bits = 0;
303         if (fabs(n->origin[0] - o->origin[0]) > (1.0f / 256.0f))
304                 bits |= E_ORIGIN1;
305         if (fabs(n->origin[1] - o->origin[1]) > (1.0f / 256.0f))
306                 bits |= E_ORIGIN2;
307         if (fabs(n->origin[2] - o->origin[2]) > (1.0f / 256.0f))
308                 bits |= E_ORIGIN3;
309         if ((qbyte) (n->angles[0] * (256.0f / 360.0f)) != (qbyte) (o->angles[0] * (256.0f / 360.0f)))
310                 bits |= E_ANGLE1;
311         if ((qbyte) (n->angles[1] * (256.0f / 360.0f)) != (qbyte) (o->angles[1] * (256.0f / 360.0f)))
312                 bits |= E_ANGLE2;
313         if ((qbyte) (n->angles[2] * (256.0f / 360.0f)) != (qbyte) (o->angles[2] * (256.0f / 360.0f)))
314                 bits |= E_ANGLE3;
315         if ((n->modelindex ^ o->modelindex) & 0x00FF)
316                 bits |= E_MODEL1;
317         if ((n->modelindex ^ o->modelindex) & 0xFF00)
318                 bits |= E_MODEL2;
319         if ((n->frame ^ o->frame) & 0x00FF)
320                 bits |= E_FRAME1;
321         if ((n->frame ^ o->frame) & 0xFF00)
322                 bits |= E_FRAME2;
323         if ((n->effects ^ o->effects) & 0x00FF)
324                 bits |= E_EFFECTS1;
325         if ((n->effects ^ o->effects) & 0xFF00)
326                 bits |= E_EFFECTS2;
327         if (n->colormap != o->colormap)
328                 bits |= E_COLORMAP;
329         if (n->skin != o->skin)
330                 bits |= E_SKIN;
331         if (n->alpha != o->alpha)
332                 bits |= E_ALPHA;
333         if (n->scale != o->scale)
334                 bits |= E_SCALE;
335         if (n->glowsize != o->glowsize)
336                 bits |= E_GLOWSIZE;
337         if (n->glowcolor != o->glowcolor)
338                 bits |= E_GLOWCOLOR;
339         if (n->flags != o->flags)
340                 bits |= E_FLAGS;
341         if (n->tagindex != o->tagindex || n->tagentity != o->tagentity)
342                 bits |= E_TAGATTACHMENT;
343         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])
344                 bits |= E_LIGHT;
345         if (n->lightstyle != o->lightstyle)
346                 bits |= E_LIGHTSTYLE;
347         if (n->lightpflags != o->lightpflags)
348                 bits |= E_LIGHTPFLAGS;
349
350         if (bits)
351         {
352                 if (bits &  0xFF000000)
353                         bits |= 0x00800000;
354                 if (bits &  0x00FF0000)
355                         bits |= 0x00008000;
356                 if (bits &  0x0000FF00)
357                         bits |= 0x00000080;
358         }
359         return bits;
360 }
361
362 void EntityState_WriteExtendBits(sizebuf_t *msg, unsigned int bits)
363 {
364         MSG_WriteByte(msg, bits & 0xFF);
365         if (bits & 0x00000080)
366         {
367                 MSG_WriteByte(msg, (bits >> 8) & 0xFF);
368                 if (bits & 0x00008000)
369                 {
370                         MSG_WriteByte(msg, (bits >> 16) & 0xFF);
371                         if (bits & 0x00800000)
372                                 MSG_WriteByte(msg, (bits >> 24) & 0xFF);
373                 }
374         }
375 }
376
377 void EntityState_WriteFields(const entity_state_t *ent, sizebuf_t *msg, unsigned int bits)
378 {
379         if (sv.protocol == PROTOCOL_DARKPLACES2)
380         {
381                 if (bits & E_ORIGIN1)
382                         MSG_WriteCoord16i(msg, ent->origin[0]);
383                 if (bits & E_ORIGIN2)
384                         MSG_WriteCoord16i(msg, ent->origin[1]);
385                 if (bits & E_ORIGIN3)
386                         MSG_WriteCoord16i(msg, ent->origin[2]);
387         }
388         else if (sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4 || sv.protocol == PROTOCOL_DARKPLACES5)
389         {
390                 // LordHavoc: have to write flags first, as they can modify protocol
391                 if (bits & E_FLAGS)
392                         MSG_WriteByte(msg, ent->flags);
393                 if (ent->flags & RENDER_LOWPRECISION)
394                 {
395                         if (bits & E_ORIGIN1)
396                                 MSG_WriteCoord16i(msg, ent->origin[0]);
397                         if (bits & E_ORIGIN2)
398                                 MSG_WriteCoord16i(msg, ent->origin[1]);
399                         if (bits & E_ORIGIN3)
400                                 MSG_WriteCoord16i(msg, ent->origin[2]);
401                 }
402                 else
403                 {
404                         if (bits & E_ORIGIN1)
405                                 MSG_WriteCoord32f(msg, ent->origin[0]);
406                         if (bits & E_ORIGIN2)
407                                 MSG_WriteCoord32f(msg, ent->origin[1]);
408                         if (bits & E_ORIGIN3)
409                                 MSG_WriteCoord32f(msg, ent->origin[2]);
410                 }
411         }
412         if (sv.protocol == PROTOCOL_DARKPLACES5 && !(ent->flags & RENDER_LOWPRECISION))
413         {
414                 if (bits & E_ANGLE1)
415                         MSG_WriteAngle16i(msg, ent->angles[0]);
416                 if (bits & E_ANGLE2)
417                         MSG_WriteAngle16i(msg, ent->angles[1]);
418                 if (bits & E_ANGLE3)
419                         MSG_WriteAngle16i(msg, ent->angles[2]);
420         }
421         else
422         {
423                 if (bits & E_ANGLE1)
424                         MSG_WriteAngle8i(msg, ent->angles[0]);
425                 if (bits & E_ANGLE2)
426                         MSG_WriteAngle8i(msg, ent->angles[1]);
427                 if (bits & E_ANGLE3)
428                         MSG_WriteAngle8i(msg, ent->angles[2]);
429         }
430         if (bits & E_MODEL1)
431                 MSG_WriteByte(msg, ent->modelindex & 0xFF);
432         if (bits & E_MODEL2)
433                 MSG_WriteByte(msg, (ent->modelindex >> 8) & 0xFF);
434         if (bits & E_FRAME1)
435                 MSG_WriteByte(msg, ent->frame & 0xFF);
436         if (bits & E_FRAME2)
437                 MSG_WriteByte(msg, (ent->frame >> 8) & 0xFF);
438         if (bits & E_EFFECTS1)
439                 MSG_WriteByte(msg, ent->effects & 0xFF);
440         if (bits & E_EFFECTS2)
441                 MSG_WriteByte(msg, (ent->effects >> 8) & 0xFF);
442         if (bits & E_COLORMAP)
443                 MSG_WriteByte(msg, ent->colormap);
444         if (bits & E_SKIN)
445                 MSG_WriteByte(msg, ent->skin);
446         if (bits & E_ALPHA)
447                 MSG_WriteByte(msg, ent->alpha);
448         if (bits & E_SCALE)
449                 MSG_WriteByte(msg, ent->scale);
450         if (bits & E_GLOWSIZE)
451                 MSG_WriteByte(msg, ent->glowsize);
452         if (bits & E_GLOWCOLOR)
453                 MSG_WriteByte(msg, ent->glowcolor);
454         if (sv.protocol == PROTOCOL_DARKPLACES2)
455                 if (bits & E_FLAGS)
456                         MSG_WriteByte(msg, ent->flags);
457         if (bits & E_TAGATTACHMENT)
458         {
459                 MSG_WriteShort(msg, ent->tagentity);
460                 MSG_WriteByte(msg, ent->tagindex);
461         }
462         if (bits & E_LIGHT)
463         {
464                 MSG_WriteShort(msg, ent->light[0]);
465                 MSG_WriteShort(msg, ent->light[1]);
466                 MSG_WriteShort(msg, ent->light[2]);
467                 MSG_WriteShort(msg, ent->light[3]);
468         }
469         if (bits & E_LIGHTSTYLE)
470                 MSG_WriteByte(msg, ent->lightstyle);
471         if (bits & E_LIGHTPFLAGS)
472                 MSG_WriteByte(msg, ent->lightpflags);
473 }
474
475 void EntityState_WriteUpdate(const entity_state_t *ent, sizebuf_t *msg, const entity_state_t *delta)
476 {
477         unsigned int bits;
478         if (ent->active)
479         {
480                 // entity is active, check for changes from the delta
481                 if ((bits = EntityState_DeltaBits(delta, ent)))
482                 {
483                         // write the update number, bits, and fields
484                         MSG_WriteShort(msg, ent->number);
485                         EntityState_WriteExtendBits(msg, bits);
486                         EntityState_WriteFields(ent, msg, bits);
487                 }
488         }
489         else
490         {
491                 // entity is inactive, check if the delta was active
492                 if (delta->active)
493                 {
494                         // write the remove number
495                         MSG_WriteShort(msg, ent->number | 0x8000);
496                 }
497         }
498 }
499
500 int EntityState_ReadExtendBits(void)
501 {
502         unsigned int bits;
503         bits = MSG_ReadByte();
504         if (bits & 0x00000080)
505         {
506                 bits |= MSG_ReadByte() << 8;
507                 if (bits & 0x00008000)
508                 {
509                         bits |= MSG_ReadByte() << 16;
510                         if (bits & 0x00800000)
511                                 bits |= MSG_ReadByte() << 24;
512                 }
513         }
514         return bits;
515 }
516
517 void EntityState_ReadFields(entity_state_t *e, unsigned int bits)
518 {
519         if (cl.protocol == PROTOCOL_DARKPLACES2)
520         {
521                 if (bits & E_ORIGIN1)
522                         e->origin[0] = MSG_ReadCoord16i();
523                 if (bits & E_ORIGIN2)
524                         e->origin[1] = MSG_ReadCoord16i();
525                 if (bits & E_ORIGIN3)
526                         e->origin[2] = MSG_ReadCoord16i();
527         }
528         else if (cl.protocol == PROTOCOL_DARKPLACES1 || cl.protocol == PROTOCOL_DARKPLACES3 || cl.protocol == PROTOCOL_DARKPLACES4 || cl.protocol == PROTOCOL_DARKPLACES5)
529         {
530                 if (bits & E_FLAGS)
531                         e->flags = MSG_ReadByte();
532                 if (e->flags & RENDER_LOWPRECISION)
533                 {
534                         if (bits & E_ORIGIN1)
535                                 e->origin[0] = MSG_ReadCoord16i();
536                         if (bits & E_ORIGIN2)
537                                 e->origin[1] = MSG_ReadCoord16i();
538                         if (bits & E_ORIGIN3)
539                                 e->origin[2] = MSG_ReadCoord16i();
540                 }
541                 else
542                 {
543                         if (bits & E_ORIGIN1)
544                                 e->origin[0] = MSG_ReadCoord32f();
545                         if (bits & E_ORIGIN2)
546                                 e->origin[1] = MSG_ReadCoord32f();
547                         if (bits & E_ORIGIN3)
548                                 e->origin[2] = MSG_ReadCoord32f();
549                 }
550         }
551         if (cl.protocol == PROTOCOL_DARKPLACES5 && !(e->flags & RENDER_LOWPRECISION))
552         {
553                 if (bits & E_ANGLE1)
554                         e->angles[0] = MSG_ReadAngle16i();
555                 if (bits & E_ANGLE2)
556                         e->angles[1] = MSG_ReadAngle16i();
557                 if (bits & E_ANGLE3)
558                         e->angles[2] = MSG_ReadAngle16i();
559         }
560         else
561         {
562                 if (bits & E_ANGLE1)
563                         e->angles[0] = MSG_ReadAngle8i();
564                 if (bits & E_ANGLE2)
565                         e->angles[1] = MSG_ReadAngle8i();
566                 if (bits & E_ANGLE3)
567                         e->angles[2] = MSG_ReadAngle8i();
568         }
569         if (bits & E_MODEL1)
570                 e->modelindex = (e->modelindex & 0xFF00) | (unsigned int) MSG_ReadByte();
571         if (bits & E_MODEL2)
572                 e->modelindex = (e->modelindex & 0x00FF) | ((unsigned int) MSG_ReadByte() << 8);
573         if (bits & E_FRAME1)
574                 e->frame = (e->frame & 0xFF00) | (unsigned int) MSG_ReadByte();
575         if (bits & E_FRAME2)
576                 e->frame = (e->frame & 0x00FF) | ((unsigned int) MSG_ReadByte() << 8);
577         if (bits & E_EFFECTS1)
578                 e->effects = (e->effects & 0xFF00) | (unsigned int) MSG_ReadByte();
579         if (bits & E_EFFECTS2)
580                 e->effects = (e->effects & 0x00FF) | ((unsigned int) MSG_ReadByte() << 8);
581         if (bits & E_COLORMAP)
582                 e->colormap = MSG_ReadByte();
583         if (bits & E_SKIN)
584                 e->skin = MSG_ReadByte();
585         if (bits & E_ALPHA)
586                 e->alpha = MSG_ReadByte();
587         if (bits & E_SCALE)
588                 e->scale = MSG_ReadByte();
589         if (bits & E_GLOWSIZE)
590                 e->glowsize = MSG_ReadByte();
591         if (bits & E_GLOWCOLOR)
592                 e->glowcolor = MSG_ReadByte();
593         if (cl.protocol == PROTOCOL_DARKPLACES2)
594                 if (bits & E_FLAGS)
595                         e->flags = MSG_ReadByte();
596         if (bits & E_TAGATTACHMENT)
597         {
598                 e->tagentity = (unsigned short) MSG_ReadShort();
599                 e->tagindex = MSG_ReadByte();
600         }
601         if (bits & E_LIGHT)
602         {
603                 e->light[0] = (unsigned short) MSG_ReadShort();
604                 e->light[1] = (unsigned short) MSG_ReadShort();
605                 e->light[2] = (unsigned short) MSG_ReadShort();
606                 e->light[3] = (unsigned short) MSG_ReadShort();
607         }
608         if (bits & E_LIGHTSTYLE)
609                 e->lightstyle = MSG_ReadByte();
610         if (bits & E_LIGHTPFLAGS)
611                 e->lightpflags = MSG_ReadByte();
612
613         if (developer_networkentities.integer >= 2)
614         {
615                 Con_Printf("ReadFields e%i", e->number);
616
617                 if (bits & E_ORIGIN1)
618                         Con_Printf(" E_ORIGIN1 %f", e->origin[0]);
619                 if (bits & E_ORIGIN2)
620                         Con_Printf(" E_ORIGIN2 %f", e->origin[1]);
621                 if (bits & E_ORIGIN3)
622                         Con_Printf(" E_ORIGIN3 %f", e->origin[2]);
623                 if (bits & E_ANGLE1)
624                         Con_Printf(" E_ANGLE1 %f", e->angles[0]);
625                 if (bits & E_ANGLE2)
626                         Con_Printf(" E_ANGLE2 %f", e->angles[1]);
627                 if (bits & E_ANGLE3)
628                         Con_Printf(" E_ANGLE3 %f", e->angles[2]);
629                 if (bits & (E_MODEL1 | E_MODEL2))
630                         Con_Printf(" E_MODEL %i", e->modelindex);
631
632                 if (bits & (E_FRAME1 | E_FRAME2))
633                         Con_Printf(" E_FRAME %i", e->frame);
634                 if (bits & (E_EFFECTS1 | E_EFFECTS2))
635                         Con_Printf(" E_EFFECTS %i", e->effects);
636                 if (bits & E_ALPHA)
637                         Con_Printf(" E_ALPHA %f", e->alpha / 255.0f);
638                 if (bits & E_SCALE)
639                         Con_Printf(" E_SCALE %f", e->scale / 16.0f);
640                 if (bits & E_COLORMAP)
641                         Con_Printf(" E_COLORMAP %i", e->colormap);
642                 if (bits & E_SKIN)
643                         Con_Printf(" E_SKIN %i", e->skin);
644
645                 if (bits & E_GLOWSIZE)
646                         Con_Printf(" E_GLOWSIZE %i", e->glowsize * 4);
647                 if (bits & E_GLOWCOLOR)
648                         Con_Printf(" E_GLOWCOLOR %i", e->glowcolor);
649                 
650                 if (bits & E_LIGHT)
651                         Con_Printf(" E_LIGHT %i:%i:%i:%i", e->light[0], e->light[1], e->light[2], e->light[3]);
652                 if (bits & E_LIGHTPFLAGS)                       
653                         Con_Printf(" E_LIGHTPFLAGS %i", e->lightpflags);
654
655                 if (bits & E_TAGATTACHMENT)
656                         Con_Printf(" E_TAGATTACHMENT e%i:%i", e->tagentity, e->tagindex);
657                 if (bits & E_LIGHTSTYLE)
658                         Con_Printf(" E_LIGHTSTYLE %i", e->lightstyle);
659                 Con_Print("\n");
660         }
661 }
662
663 // (client and server) allocates a new empty database
664 entityframe_database_t *EntityFrame_AllocDatabase(mempool_t *mempool)
665 {
666         return Mem_Alloc(mempool, sizeof(entityframe_database_t));
667 }
668
669 // (client and server) frees the database
670 void EntityFrame_FreeDatabase(entityframe_database_t *d)
671 {
672         Mem_Free(d);
673 }
674
675 // (server) clears the database to contain no frames (thus delta compression compresses against nothing)
676 void EntityFrame_ClearDatabase(entityframe_database_t *d)
677 {
678         memset(d, 0, sizeof(*d));
679 }
680
681 // (server and client) removes frames older than 'frame' from database
682 void EntityFrame_AckFrame(entityframe_database_t *d, int frame)
683 {
684         int i;
685         if (d->ackframenum < frame)
686                 d->ackframenum = frame;
687         for (i = 0;i < d->numframes && d->frames[i].framenum < frame;i++);
688         // ignore outdated frame acks (out of order packets)
689         if (i == 0)
690                 return;
691         d->numframes -= i;
692         // if some queue is left, slide it down to beginning of array
693         if (d->numframes)
694                 memmove(&d->frames[0], &d->frames[i], sizeof(d->frames[0]) * d->numframes);
695 }
696
697 // (server) clears frame, to prepare for adding entities
698 void EntityFrame_Clear(entity_frame_t *f, vec3_t eye, int framenum)
699 {
700         f->time = 0;
701         f->framenum = framenum;
702         f->numentities = 0;
703         if (eye == NULL)
704                 VectorClear(f->eye);
705         else
706                 VectorCopy(eye, f->eye);
707 }
708
709 // (server and client) reads a frame from the database
710 void EntityFrame_FetchFrame(entityframe_database_t *d, int framenum, entity_frame_t *f)
711 {
712         int i, n;
713         EntityFrame_Clear(f, NULL, -1);
714         for (i = 0;i < d->numframes && d->frames[i].framenum < framenum;i++);
715         if (i < d->numframes && framenum == d->frames[i].framenum)
716         {
717                 f->framenum = framenum;
718                 f->numentities = d->frames[i].endentity - d->frames[i].firstentity;
719                 n = MAX_ENTITY_DATABASE - (d->frames[i].firstentity % MAX_ENTITY_DATABASE);
720                 if (n > f->numentities)
721                         n = f->numentities;
722                 memcpy(f->entitydata, d->entitydata + d->frames[i].firstentity % MAX_ENTITY_DATABASE, sizeof(*f->entitydata) * n);
723                 if (f->numentities > n)
724                         memcpy(f->entitydata + n, d->entitydata, sizeof(*f->entitydata) * (f->numentities - n));
725                 VectorCopy(d->eye, f->eye);
726         }
727 }
728
729 // (server and client) adds a entity_frame to the database, for future reference
730 void EntityFrame_AddFrame(entityframe_database_t *d, vec3_t eye, int framenum, int numentities, const entity_state_t *entitydata)
731 {
732         int n, e;
733         entity_frameinfo_t *info;
734
735         VectorCopy(eye, d->eye);
736
737         // figure out how many entity slots are used already
738         if (d->numframes)
739         {
740                 n = d->frames[d->numframes - 1].endentity - d->frames[0].firstentity;
741                 if (n + numentities > MAX_ENTITY_DATABASE || d->numframes >= MAX_ENTITY_HISTORY)
742                 {
743                         // ran out of room, dump database
744                         EntityFrame_ClearDatabase(d);
745                 }
746         }
747
748         info = &d->frames[d->numframes];
749         info->framenum = framenum;
750         e = -1000;
751         // make sure we check the newly added frame as well, but we haven't incremented numframes yet
752         for (n = 0;n <= d->numframes;n++)
753         {
754                 if (e >= d->frames[n].framenum)
755                 {
756                         if (e == framenum)
757                                 Con_Print("EntityFrame_AddFrame: tried to add out of sequence frame to database\n");
758                         else
759                                 Con_Print("EntityFrame_AddFrame: out of sequence frames in database\n");
760                         return;
761                 }
762                 e = d->frames[n].framenum;
763         }
764         // if database still has frames after that...
765         if (d->numframes)
766                 info->firstentity = d->frames[d->numframes - 1].endentity;
767         else
768                 info->firstentity = 0;
769         info->endentity = info->firstentity + numentities;
770         d->numframes++;
771
772         n = info->firstentity % MAX_ENTITY_DATABASE;
773         e = MAX_ENTITY_DATABASE - n;
774         if (e > numentities)
775                 e = numentities;
776         memcpy(d->entitydata + n, entitydata, sizeof(entity_state_t) * e);
777         if (numentities > e)
778                 memcpy(d->entitydata, entitydata + e, sizeof(entity_state_t) * (numentities - e));
779 }
780
781 // (server) writes a frame to network stream
782 static entity_frame_t deltaframe; // FIXME?
783 void EntityFrame_WriteFrame(sizebuf_t *msg, entityframe_database_t *d, int numstates, const entity_state_t *states, int viewentnum)
784 {
785         int i, onum, number;
786         entity_frame_t *o = &deltaframe;
787         const entity_state_t *ent, *delta;
788         vec3_t eye;
789
790         d->latestframenum++;
791
792         VectorClear(eye);
793         for (i = 0;i < numstates;i++)
794         {
795                 if (states[i].number == viewentnum)
796                 {
797                         VectorSet(eye, states[i].origin[0], states[i].origin[1], states[i].origin[2] + 22);
798                         break;
799                 }
800         }
801
802         EntityFrame_AddFrame(d, eye, d->latestframenum, numstates, states);
803
804         EntityFrame_FetchFrame(d, d->ackframenum > 0 ? d->ackframenum : -1, o);
805
806         MSG_WriteByte (msg, svc_entities);
807         MSG_WriteLong (msg, o->framenum);
808         MSG_WriteLong (msg, d->latestframenum);
809         MSG_WriteFloat (msg, eye[0]);
810         MSG_WriteFloat (msg, eye[1]);
811         MSG_WriteFloat (msg, eye[2]);
812
813         onum = 0;
814         for (i = 0;i < numstates;i++)
815         {
816                 ent = states + i;
817                 number = ent->number;
818                 for (;onum < o->numentities && o->entitydata[onum].number < number;onum++)
819                 {
820                         // write remove message
821                         MSG_WriteShort(msg, o->entitydata[onum].number | 0x8000);
822                 }
823                 if (onum < o->numentities && (o->entitydata[onum].number == number))
824                 {
825                         // delta from previous frame
826                         delta = o->entitydata + onum;
827                         // advance to next entity in delta frame
828                         onum++;
829                 }
830                 else
831                 {
832                         // delta from defaults
833                         delta = &defaultstate;
834                 }
835                 EntityState_WriteUpdate(ent, msg, delta);
836         }
837         for (;onum < o->numentities;onum++)
838         {
839                 // write remove message
840                 MSG_WriteShort(msg, o->entitydata[onum].number | 0x8000);
841         }
842         MSG_WriteShort(msg, 0xFFFF);
843 }
844
845 // (client) reads a frame from network stream
846 static entity_frame_t framedata; // FIXME?
847 void EntityFrame_CL_ReadFrame(void)
848 {
849         int i, number, removed;
850         entity_frame_t *f = &framedata, *delta = &deltaframe;
851         entity_state_t *e, *old, *oldend;
852         entity_t *ent;
853         entityframe_database_t *d;
854         if (!cl.entitydatabase)
855                 cl.entitydatabase = EntityFrame_AllocDatabase(cl_entities_mempool);
856         d = cl.entitydatabase;
857
858         EntityFrame_Clear(f, NULL, -1);
859
860         // read the frame header info
861         f->time = cl.mtime[0];
862         number = MSG_ReadLong();
863         cl.latestframenum = f->framenum = MSG_ReadLong();
864         f->eye[0] = MSG_ReadFloat();
865         f->eye[1] = MSG_ReadFloat();
866         f->eye[2] = MSG_ReadFloat();
867         EntityFrame_AckFrame(d, number);
868         EntityFrame_FetchFrame(d, number, delta);
869         old = delta->entitydata;
870         oldend = old + delta->numentities;
871         // read entities until we hit the magic 0xFFFF end tag
872         while ((number = (unsigned short) MSG_ReadShort()) != 0xFFFF && !msg_badread)
873         {
874                 if (msg_badread)
875                         Host_Error("EntityFrame_Read: read error\n");
876                 removed = number & 0x8000;
877                 number &= 0x7FFF;
878                 if (number >= MAX_EDICTS)
879                         Host_Error("EntityFrame_Read: number (%i) >= MAX_EDICTS (%i)\n", number, MAX_EDICTS);
880
881                 // seek to entity, while copying any skipped entities (assume unchanged)
882                 while (old < oldend && old->number < number)
883                 {
884                         if (f->numentities >= MAX_ENTITY_DATABASE)
885                                 Host_Error("EntityFrame_Read: entity list too big\n");
886                         f->entitydata[f->numentities] = *old++;
887                         f->entitydata[f->numentities++].time = cl.mtime[0];
888                 }
889                 if (removed)
890                 {
891                         if (old < oldend && old->number == number)
892                                 old++;
893                         else
894                                 Con_Printf("EntityFrame_Read: REMOVE on unused entity %i\n", number);
895                 }
896                 else
897                 {
898                         if (f->numentities >= MAX_ENTITY_DATABASE)
899                                 Host_Error("EntityFrame_Read: entity list too big\n");
900
901                         // reserve this slot
902                         e = f->entitydata + f->numentities++;
903
904                         if (old < oldend && old->number == number)
905                         {
906                                 // delta from old entity
907                                 *e = *old++;
908                         }
909                         else
910                         {
911                                 // delta from defaults
912                                 *e = defaultstate;
913                         }
914
915                         cl_entities_active[number] = true;
916                         e->active = true;
917                         e->time = cl.mtime[0];
918                         e->number = number;
919                         EntityState_ReadFields(e, EntityState_ReadExtendBits());
920                 }
921         }
922         while (old < oldend)
923         {
924                 if (f->numentities >= MAX_ENTITY_DATABASE)
925                         Host_Error("EntityFrame_Read: entity list too big\n");
926                 f->entitydata[f->numentities] = *old++;
927                 f->entitydata[f->numentities++].time = cl.mtime[0];
928         }
929         EntityFrame_AddFrame(d, f->eye, f->framenum, f->numentities, f->entitydata);
930
931         memset(cl_entities_active, 0, cl_max_entities * sizeof(qbyte));
932         number = 1;
933         for (i = 0;i < f->numentities;i++)
934         {
935                 for (;number < f->entitydata[i].number;number++)
936                 {
937                         if (cl_entities_active[number])
938                         {
939                                 cl_entities_active[number] = false;
940                                 cl_entities[number].state_current.active = false;
941                         }
942                 }
943                 // update the entity
944                 ent = &cl_entities[number];
945                 ent->state_previous = ent->state_current;
946                 ent->state_current = f->entitydata[i];
947                 CL_MoveLerpEntityStates(ent);
948                 // the entity lives again...
949                 cl_entities_active[number] = true;
950                 number++;
951         }
952         for (;number < cl_max_entities;number++)
953         {
954                 if (cl_entities_active[number])
955                 {
956                         cl_entities_active[number] = false;
957                         cl_entities[number].state_current.active = false;
958                 }
959         }
960 }
961
962
963 // (client) returns the frame number of the most recent frame recieved
964 int EntityFrame_MostRecentlyRecievedFrameNum(entityframe_database_t *d)
965 {
966         if (d->numframes)
967                 return d->frames[d->numframes - 1].framenum;
968         else
969                 return -1;
970 }
971
972
973
974
975
976
977 entity_state_t *EntityFrame4_GetReferenceEntity(entityframe4_database_t *d, int number)
978 {
979         if (d->maxreferenceentities <= number)
980         {
981                 int oldmax = d->maxreferenceentities;
982                 entity_state_t *oldentity = d->referenceentity;
983                 d->maxreferenceentities = (number + 15) & ~7;
984                 d->referenceentity = Mem_Alloc(d->mempool, d->maxreferenceentities * sizeof(*d->referenceentity));
985                 if (oldentity)
986                 {
987                         memcpy(d->referenceentity, oldentity, oldmax * sizeof(*d->referenceentity));
988                         Mem_Free(oldentity);
989                 }
990                 // clear the newly created entities
991                 for (;oldmax < d->maxreferenceentities;oldmax++)
992                 {
993                         d->referenceentity[oldmax] = defaultstate;
994                         d->referenceentity[oldmax].number = oldmax;
995                 }
996         }
997         return d->referenceentity + number;
998 }
999
1000 void EntityFrame4_AddCommitEntity(entityframe4_database_t *d, const entity_state_t *s)
1001 {
1002         // resize commit's entity list if full
1003         if (d->currentcommit->maxentities <= d->currentcommit->numentities)
1004         {
1005                 entity_state_t *oldentity = d->currentcommit->entity;
1006                 d->currentcommit->maxentities += 8;
1007                 d->currentcommit->entity = Mem_Alloc(d->mempool, d->currentcommit->maxentities * sizeof(*d->currentcommit->entity));
1008                 if (oldentity)
1009                 {
1010                         memcpy(d->currentcommit->entity, oldentity, d->currentcommit->numentities * sizeof(*d->currentcommit->entity));
1011                         Mem_Free(oldentity);
1012                 }
1013         }
1014         d->currentcommit->entity[d->currentcommit->numentities++] = *s;
1015 }
1016
1017 entityframe4_database_t *EntityFrame4_AllocDatabase(mempool_t *pool)
1018 {
1019         entityframe4_database_t *d;
1020         d = Mem_Alloc(pool, sizeof(*d));
1021         d->mempool = pool;
1022         EntityFrame4_ResetDatabase(d);
1023         d->ackframenum = -1;
1024         return d;
1025 }
1026
1027 void EntityFrame4_FreeDatabase(entityframe4_database_t *d)
1028 {
1029         int i;
1030         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1031                 if (d->commit[i].entity)
1032                         Mem_Free(d->commit[i].entity);
1033         if (d->referenceentity)
1034                 Mem_Free(d->referenceentity);
1035         Mem_Free(d);
1036 }
1037
1038 void EntityFrame4_ResetDatabase(entityframe4_database_t *d)
1039 {
1040         int i;
1041         d->ackframenum = -1;
1042         d->referenceframenum = -1;
1043         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1044                 d->commit[i].numentities = 0;
1045         for (i = 0;i < d->maxreferenceentities;i++)
1046                 d->referenceentity[i] = defaultstate;
1047 }
1048
1049 int EntityFrame4_AckFrame(entityframe4_database_t *d, int framenum, int servermode)
1050 {
1051         int i, j, found;
1052         entity_database4_commit_t *commit;
1053         if (framenum == -1)
1054         {
1055                 // reset reference, but leave commits alone
1056                 d->referenceframenum = -1;
1057                 for (i = 0;i < d->maxreferenceentities;i++)
1058                         d->referenceentity[i] = defaultstate;
1059                 // if this is the server, remove commits
1060                         for (i = 0, commit = d->commit;i < MAX_ENTITY_HISTORY;i++, commit++)
1061                                 commit->numentities = 0;
1062                 found = true;
1063         }
1064         else if (d->referenceframenum == framenum)
1065                 found = true;
1066         else
1067         {
1068                 found = false;
1069                 for (i = 0, commit = d->commit;i < MAX_ENTITY_HISTORY;i++, commit++)
1070                 {
1071                         if (commit->numentities && commit->framenum <= framenum)
1072                         {
1073                                 if (commit->framenum == framenum)
1074                                 {
1075                                         found = true;
1076                                         d->referenceframenum = framenum;
1077                                         if (developer_networkentities.integer >= 3)
1078                                         {
1079                                                 for (j = 0;j < commit->numentities;j++)
1080                                                 {
1081                                                         entity_state_t *s = EntityFrame4_GetReferenceEntity(d, commit->entity[j].number);
1082                                                         if (commit->entity[j].active != s->active)
1083                                                         {
1084                                                                 if (commit->entity[j].active)
1085                                                                         Con_Printf("commit entity %i has become active (modelindex %i)\n", commit->entity[j].number, commit->entity[j].modelindex);
1086                                                                 else
1087                                                                         Con_Printf("commit entity %i has become inactive (modelindex %i)\n", commit->entity[j].number, commit->entity[j].modelindex);
1088                                                         }
1089                                                         *s = commit->entity[j];
1090                                                 }
1091                                         }
1092                                         else
1093                                                 for (j = 0;j < commit->numentities;j++)
1094                                                         *EntityFrame4_GetReferenceEntity(d, commit->entity[j].number) = commit->entity[j];
1095                                 }
1096                                 commit->numentities = 0;
1097                         }
1098                 }
1099         }
1100         if (developer_networkentities.integer >= 1)
1101         {
1102                 Con_Printf("ack ref:%i database updated to: ref:%i commits:", framenum, d->referenceframenum);
1103                 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1104                         if (d->commit[i].numentities)
1105                                 Con_Printf(" %i", d->commit[i].framenum);
1106                 Con_Print("\n");
1107         }
1108         return found;
1109 }
1110
1111 void EntityFrame4_CL_ReadFrame(void)
1112 {
1113         int i, n, cnumber, referenceframenum, framenum, enumber, done, stopnumber, skip = false;
1114         entity_state_t *s;
1115         entityframe4_database_t *d;
1116         if (!cl.entitydatabase4)
1117                 cl.entitydatabase4 = EntityFrame4_AllocDatabase(cl_entities_mempool);
1118         d = cl.entitydatabase4;
1119         // read the number of the frame this refers to
1120         referenceframenum = MSG_ReadLong();
1121         // read the number of this frame
1122         cl.latestframenum = framenum = MSG_ReadLong();
1123         // read the start number
1124         enumber = (unsigned short) MSG_ReadShort();
1125         if (developer_networkentities.integer >= 1)
1126         {
1127                 Con_Printf("recv svc_entities num:%i ref:%i database: ref:%i commits:", framenum, referenceframenum, d->referenceframenum);
1128                 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1129                         if (d->commit[i].numentities)
1130                                 Con_Printf(" %i", d->commit[i].framenum);
1131                 Con_Print("\n");
1132         }
1133         if (!EntityFrame4_AckFrame(d, referenceframenum, false))
1134         {
1135                 Con_Print("EntityFrame4_CL_ReadFrame: reference frame invalid (VERY BAD ERROR), this update will be skipped\n");
1136                 skip = true;
1137         }
1138         d->currentcommit = NULL;
1139         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1140         {
1141                 if (!d->commit[i].numentities)
1142                 {
1143                         d->currentcommit = d->commit + i;
1144                         d->currentcommit->framenum = d->ackframenum = framenum;
1145                         d->currentcommit->numentities = 0;
1146                 }
1147         }
1148         if (d->currentcommit == NULL)
1149         {
1150                 Con_Printf("EntityFrame4_CL_ReadFrame: error while decoding frame %i: database full, reading but not storing this update\n", framenum);
1151                 skip = true;
1152         }
1153         done = false;
1154         while (!done && !msg_badread)
1155         {
1156                 // read the number of the modified entity
1157                 // (gaps will be copied unmodified)
1158                 n = (unsigned short)MSG_ReadShort();
1159                 if (n == 0x8000)
1160                 {
1161                         // no more entities in this update, but we still need to copy the
1162                         // rest of the reference entities (final gap)
1163                         done = true;
1164                         // read end of range number, then process normally
1165                         n = (unsigned short)MSG_ReadShort();
1166                 }
1167                 // high bit means it's a remove message
1168                 cnumber = n & 0x7FFF;
1169                 // add one (the changed one) if not done
1170                 stopnumber = cnumber + !done;
1171                 // process entities in range from the last one to the changed one
1172                 for (;enumber < stopnumber;enumber++)
1173                 {
1174                         if (skip)
1175                         {
1176                                 if (enumber == cnumber && (n & 0x8000) == 0)
1177                                 {
1178                                         entity_state_t tempstate;
1179                                         EntityState_ReadFields(&tempstate, EntityState_ReadExtendBits());
1180                                 }
1181                                 continue;
1182                         }
1183                         // slide the current into the previous slot
1184                         cl_entities[enumber].state_previous = cl_entities[enumber].state_current;
1185                         // copy a new current from reference database
1186                         cl_entities[enumber].state_current = *EntityFrame4_GetReferenceEntity(d, enumber);
1187                         s = &cl_entities[enumber].state_current;
1188                         // if this is the one to modify, read more data...
1189                         if (enumber == cnumber)
1190                         {
1191                                 if (n & 0x8000)
1192                                 {
1193                                         // simply removed
1194                                         if (developer_networkentities.integer >= 2)
1195                                                 Con_Printf("entity %i: remove\n", enumber);
1196                                         *s = defaultstate;
1197                                 }
1198                                 else
1199                                 {
1200                                         // read the changes
1201                                         if (developer_networkentities.integer >= 2)
1202                                                 Con_Printf("entity %i: update\n", enumber);
1203                                         s->active = true;
1204                                         EntityState_ReadFields(s, EntityState_ReadExtendBits());
1205                                 }
1206                         }
1207                         else if (developer_networkentities.integer >= 4)
1208                                 Con_Printf("entity %i: copy\n", enumber);
1209                         // set the cl_entities_active flag
1210                         cl_entities_active[enumber] = s->active;
1211                         // set the update time
1212                         s->time = cl.mtime[0];
1213                         // fix the number (it gets wiped occasionally by copying from defaultstate)
1214                         s->number = enumber;
1215                         // check if we need to update the lerp stuff
1216                         if (s->active)
1217                                 CL_MoveLerpEntityStates(&cl_entities[enumber]);
1218                         // add this to the commit entry whether it is modified or not
1219                         if (d->currentcommit)
1220                                 EntityFrame4_AddCommitEntity(d, &cl_entities[enumber].state_current);
1221                         // print extra messages if desired
1222                         if (developer_networkentities.integer >= 2 && cl_entities[enumber].state_current.active != cl_entities[enumber].state_previous.active)
1223                         {
1224                                 if (cl_entities[enumber].state_current.active)
1225                                         Con_Printf("entity #%i has become active\n", enumber);
1226                                 else if (cl_entities[enumber].state_previous.active)
1227                                         Con_Printf("entity #%i has become inactive\n", enumber);
1228                         }
1229                 }
1230         }
1231         d->currentcommit = NULL;
1232         if (skip)
1233                 EntityFrame4_ResetDatabase(d);
1234 }
1235
1236 void EntityFrame4_WriteFrame(sizebuf_t *msg, entityframe4_database_t *d, int numstates, const entity_state_t *states)
1237 {
1238         const entity_state_t *e, *s;
1239         entity_state_t inactiveentitystate;
1240         int i, n, startnumber;
1241         sizebuf_t buf;
1242         qbyte data[128];
1243
1244         // if there isn't enough space to accomplish anything, skip it
1245         if (msg->cursize + 24 > msg->maxsize)
1246                 return;
1247
1248         // prepare the buffer
1249         memset(&buf, 0, sizeof(buf));
1250         buf.data = data;
1251         buf.maxsize = sizeof(data);
1252
1253         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1254                 if (!d->commit[i].numentities)
1255                         break;
1256         // if commit buffer full, just don't bother writing an update this frame
1257         if (i == MAX_ENTITY_HISTORY)
1258                 return;
1259         d->currentcommit = d->commit + i;
1260
1261         // this state's number gets played around with later
1262         inactiveentitystate = defaultstate;
1263
1264         d->currentcommit->numentities = 0;
1265         d->currentcommit->framenum = ++d->latestframenumber;
1266         MSG_WriteByte(msg, svc_entities);
1267         MSG_WriteLong(msg, d->referenceframenum);
1268         MSG_WriteLong(msg, d->currentcommit->framenum);
1269         if (developer_networkentities.integer >= 1)
1270         {
1271                 Con_Printf("send svc_entities num:%i ref:%i (database: ref:%i commits:", d->currentcommit->framenum, d->referenceframenum, d->referenceframenum);
1272                 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1273                         if (d->commit[i].numentities)
1274                                 Con_Printf(" %i", d->commit[i].framenum);
1275                 Con_Print(")\n");
1276         }
1277         if (d->currententitynumber >= sv.max_edicts)
1278                 startnumber = 1;
1279         else
1280                 startnumber = bound(1, d->currententitynumber, sv.max_edicts - 1);
1281         MSG_WriteShort(msg, startnumber);
1282         // reset currententitynumber so if the loop does not break it we will
1283         // start at beginning next frame (if it does break, it will set it)
1284         d->currententitynumber = 1;
1285         for (i = 0, n = startnumber;n < sv.max_edicts;n++)
1286         {
1287                 // find the old state to delta from
1288                 e = EntityFrame4_GetReferenceEntity(d, n);
1289                 // prepare the buffer
1290                 SZ_Clear(&buf);
1291                 // entity exists, build an update (if empty there is no change)
1292                 // find the state in the list
1293                 for (;i < numstates && states[i].number < n;i++);
1294                 // make the message
1295                 s = states + i;
1296                 if (s->number == n)
1297                 {
1298                         // build the update
1299                         EntityState_WriteUpdate(s, &buf, e);
1300                 }
1301                 else
1302                 {
1303                         inactiveentitystate.number = n;
1304                         s = &inactiveentitystate;
1305                         if (e->active)
1306                         {
1307                                 // entity used to exist but doesn't anymore, send remove
1308                                 MSG_WriteShort(&buf, n | 0x8000);
1309                         }
1310                 }
1311                 // if the commit is full, we're done this frame
1312                 if (msg->cursize + buf.cursize > msg->maxsize - 4)
1313                 {
1314                         // next frame we will continue where we left off
1315                         break;
1316                 }
1317                 // add the entity to the commit
1318                 EntityFrame4_AddCommitEntity(d, s);
1319                 // if the message is empty, skip out now
1320                 if (buf.cursize)
1321                 {
1322                         // write the message to the packet
1323                         SZ_Write(msg, buf.data, buf.cursize);
1324                 }
1325         }
1326         d->currententitynumber = n;
1327
1328         // remove world message (invalid, and thus a good terminator)
1329         MSG_WriteShort(msg, 0x8000);
1330         // write the number of the end entity
1331         MSG_WriteShort(msg, d->currententitynumber);
1332         // just to be sure
1333         d->currentcommit = NULL;
1334 }
1335
1336
1337
1338
1339 #define E5_PROTOCOL_PRIORITYLEVELS 32
1340
1341 entityframe5_database_t *EntityFrame5_AllocDatabase(mempool_t *pool)
1342 {
1343         entityframe5_database_t *d;
1344         d = Mem_Alloc(pool, sizeof(*d));
1345         EntityFrame5_ResetDatabase(d);
1346         return d;
1347 }
1348
1349 void EntityFrame5_FreeDatabase(entityframe5_database_t *d)
1350 {
1351         Mem_Free(d);
1352 }
1353
1354 void EntityFrame5_ResetDatabase(entityframe5_database_t *d)
1355 {
1356         int i;
1357         memset(d, 0, sizeof(*d));
1358         d->latestframenum = 0;
1359         d->ackframenum = -1;
1360         for (i = 0;i < MAX_EDICTS;i++)
1361                 d->states[i] = defaultstate;
1362 }
1363
1364
1365 int EntityState5_Priority(entityframe5_database_t *d, entity_state_t *view, entity_state_t *s, int changedbits, int age)
1366 {
1367         int lowprecision, limit, priority;
1368         double distance;
1369         if (!changedbits)
1370                 return 0;
1371         if (!s->active/* && changedbits & E5_FULLUPDATE*/)
1372                 return E5_PROTOCOL_PRIORITYLEVELS - 1;
1373         // check whole attachment chain to judge relevance to player
1374         lowprecision = false;
1375         for (limit = 0;limit < 256;limit++)
1376         {
1377                 if (s == view)
1378                         return E5_PROTOCOL_PRIORITYLEVELS - 1;
1379                 if (s->flags & RENDER_VIEWMODEL)
1380                         return E5_PROTOCOL_PRIORITYLEVELS - 1;
1381                 if (s->flags & RENDER_LOWPRECISION)
1382                         lowprecision = true;
1383                 if (!s->tagentity)
1384                 {
1385                         if (VectorCompare(s->origin, view->origin))
1386                                 return E5_PROTOCOL_PRIORITYLEVELS - 1;
1387                         break;
1388                 }
1389                 s = d->states + s->tagentity;
1390         }
1391         if (limit >= 256)
1392                 Con_Printf("Protocol: Runaway loop recursing tagentity links on entity %i\n", s->number);
1393         // it's not a viewmodel for this client
1394         distance = VectorDistance(view->origin, s->origin);
1395         priority = (E5_PROTOCOL_PRIORITYLEVELS / 2) + age - (int)(distance * (E5_PROTOCOL_PRIORITYLEVELS / 16384.0f));
1396         if (lowprecision)
1397                 priority -= (E5_PROTOCOL_PRIORITYLEVELS / 4);
1398         //if (changedbits & E5_FULLUPDATE)
1399         //      priority += 4;
1400         //if (changedbits & (E5_ATTACHMENT | E5_MODEL | E5_FLAGS | E5_COLORMAP))
1401         //      priority += 4;
1402         return (int) bound(1, priority, E5_PROTOCOL_PRIORITYLEVELS - 1);
1403 }
1404
1405 void EntityState5_WriteUpdate(int number, const entity_state_t *s, int changedbits, sizebuf_t *msg)
1406 {
1407         unsigned int bits = 0;
1408         if (!s->active)
1409                 MSG_WriteShort(msg, number | 0x8000);
1410         else
1411         {
1412                 bits = changedbits;
1413                 if ((bits & E5_ORIGIN) && (s->origin[0] < -4096 || s->origin[0] >= 4096 || s->origin[1] < -4096 || s->origin[1] >= 4096 || s->origin[2] < -4096 || s->origin[2] >= 4096))
1414                         bits |= E5_ORIGIN32;
1415                 if ((bits & E5_ANGLES) && !(s->flags & RENDER_LOWPRECISION))
1416                         bits |= E5_ANGLES16;
1417                 if ((bits & E5_MODEL) && s->modelindex >= 256)
1418                         bits |= E5_MODEL16;
1419                 if ((bits & E5_FRAME) && s->frame >= 256)
1420                         bits |= E5_FRAME16;
1421                 if (bits & E5_EFFECTS)
1422                 {
1423                         if (s->effects >= 65536)
1424                                 bits |= E5_EFFECTS32;
1425                         else if (s->effects >= 256)
1426                                 bits |= E5_EFFECTS16;
1427                 }
1428                 if (bits >= 256)
1429                         bits |= E5_EXTEND1;
1430                 if (bits >= 65536)
1431                         bits |= E5_EXTEND2;
1432                 if (bits >= 16777216)
1433                         bits |= E5_EXTEND3;
1434                 MSG_WriteShort(msg, number);
1435                 MSG_WriteByte(msg, bits & 0xFF);
1436                 if (bits & E5_EXTEND1)
1437                         MSG_WriteByte(msg, (bits >> 8) & 0xFF);
1438                 if (bits & E5_EXTEND2)
1439                         MSG_WriteByte(msg, (bits >> 16) & 0xFF);
1440                 if (bits & E5_EXTEND3)
1441                         MSG_WriteByte(msg, (bits >> 24) & 0xFF);
1442                 if (bits & E5_FLAGS)
1443                         MSG_WriteByte(msg, s->flags);
1444                 if (bits & E5_ORIGIN)
1445                 {
1446                         if (bits & E5_ORIGIN32)
1447                         {
1448                                 MSG_WriteCoord32f(msg, s->origin[0]);
1449                                 MSG_WriteCoord32f(msg, s->origin[1]);
1450                                 MSG_WriteCoord32f(msg, s->origin[2]);
1451                         }
1452                         else
1453                         {
1454                                 MSG_WriteCoord13i(msg, s->origin[0]);
1455                                 MSG_WriteCoord13i(msg, s->origin[1]);
1456                                 MSG_WriteCoord13i(msg, s->origin[2]);
1457                         }
1458                 }
1459                 if (bits & E5_ANGLES)
1460                 {
1461                         if (bits & E5_ANGLES16)
1462                         {
1463                                 MSG_WriteAngle16i(msg, s->angles[0]);
1464                                 MSG_WriteAngle16i(msg, s->angles[1]);
1465                                 MSG_WriteAngle16i(msg, s->angles[2]);
1466                         }
1467                         else
1468                         {
1469                                 MSG_WriteAngle8i(msg, s->angles[0]);
1470                                 MSG_WriteAngle8i(msg, s->angles[1]);
1471                                 MSG_WriteAngle8i(msg, s->angles[2]);
1472                         }
1473                 }
1474                 if (bits & E5_MODEL)
1475                 {
1476                         if (bits & E5_MODEL16)
1477                                 MSG_WriteShort(msg, s->modelindex);
1478                         else
1479                                 MSG_WriteByte(msg, s->modelindex);
1480                 }
1481                 if (bits & E5_FRAME)
1482                 {
1483                         if (bits & E5_FRAME16)
1484                                 MSG_WriteShort(msg, s->frame);
1485                         else
1486                                 MSG_WriteByte(msg, s->frame);
1487                 }
1488                 if (bits & E5_SKIN)
1489                         MSG_WriteByte(msg, s->skin);
1490                 if (bits & E5_EFFECTS)
1491                 {
1492                         if (bits & E5_EFFECTS32)
1493                                 MSG_WriteLong(msg, s->effects);
1494                         else if (bits & E5_EFFECTS16)
1495                                 MSG_WriteShort(msg, s->effects);
1496                         else
1497                                 MSG_WriteByte(msg, s->effects);
1498                 }
1499                 if (bits & E5_ALPHA)
1500                         MSG_WriteByte(msg, s->alpha);
1501                 if (bits & E5_SCALE)
1502                         MSG_WriteByte(msg, s->scale);
1503                 if (bits & E5_COLORMAP)
1504                         MSG_WriteByte(msg, s->colormap);
1505                 if (bits & E5_ATTACHMENT)
1506                 {
1507                         MSG_WriteShort(msg, s->tagentity);
1508                         MSG_WriteByte(msg, s->tagindex);
1509                 }
1510                 if (bits & E5_LIGHT)
1511                 {
1512                         MSG_WriteShort(msg, s->light[0]);
1513                         MSG_WriteShort(msg, s->light[1]);
1514                         MSG_WriteShort(msg, s->light[2]);
1515                         MSG_WriteShort(msg, s->light[3]);
1516                         MSG_WriteByte(msg, s->lightstyle);
1517                         MSG_WriteByte(msg, s->lightpflags);
1518                 }
1519                 if (bits & E5_GLOW)
1520                 {
1521                         MSG_WriteByte(msg, s->glowsize);
1522                         MSG_WriteByte(msg, s->glowcolor);
1523                 }
1524         }
1525 }
1526
1527 void EntityState5_ReadUpdate(entity_state_t *s)
1528 {
1529         int bits;
1530         bits = MSG_ReadByte();
1531         if (bits & E5_EXTEND1)
1532         {
1533                 bits |= MSG_ReadByte() << 8;
1534                 if (bits & E5_EXTEND2)
1535                 {
1536                         bits |= MSG_ReadByte() << 16;
1537                         if (bits & E5_EXTEND3)
1538                                 bits |= MSG_ReadByte() << 24;
1539                 }
1540         }
1541         if (bits & E5_FULLUPDATE)
1542         {
1543                 *s = defaultstate;
1544                 s->active = true;
1545         }
1546         if (bits & E5_FLAGS)
1547                 s->flags = MSG_ReadByte();
1548         if (bits & E5_ORIGIN)
1549         {
1550                 if (bits & E5_ORIGIN32)
1551                 {
1552                         s->origin[0] = MSG_ReadCoord32f();
1553                         s->origin[1] = MSG_ReadCoord32f();
1554                         s->origin[2] = MSG_ReadCoord32f();
1555                 }
1556                 else
1557                 {
1558                         s->origin[0] = MSG_ReadCoord13i();
1559                         s->origin[1] = MSG_ReadCoord13i();
1560                         s->origin[2] = MSG_ReadCoord13i();
1561                 }
1562         }
1563         if (bits & E5_ANGLES)
1564         {
1565                 if (bits & E5_ANGLES16)
1566                 {
1567                         s->angles[0] = MSG_ReadAngle16i(); 
1568                         s->angles[1] = MSG_ReadAngle16i(); 
1569                         s->angles[2] = MSG_ReadAngle16i(); 
1570                 }
1571                 else
1572                 {
1573                         s->angles[0] = MSG_ReadAngle8i(); 
1574                         s->angles[1] = MSG_ReadAngle8i(); 
1575                         s->angles[2] = MSG_ReadAngle8i(); 
1576                 }
1577         }
1578         if (bits & E5_MODEL)
1579         {
1580                 if (bits & E5_MODEL16)
1581                         s->modelindex = (unsigned short) MSG_ReadShort();
1582                 else
1583                         s->modelindex = MSG_ReadByte();
1584         }
1585         if (bits & E5_FRAME)
1586         {
1587                 if (bits & E5_FRAME16)
1588                         s->frame = (unsigned short) MSG_ReadShort();
1589                 else
1590                         s->frame = MSG_ReadByte();
1591         }
1592         if (bits & E5_SKIN)
1593                 s->skin = MSG_ReadByte();
1594         if (bits & E5_EFFECTS)
1595         {
1596                 if (bits & E5_EFFECTS32)
1597                         s->effects = (unsigned int) MSG_ReadLong();
1598                 else if (bits & E5_EFFECTS16)
1599                         s->effects = (unsigned short) MSG_ReadShort();
1600                 else
1601                         s->effects = MSG_ReadByte();
1602         }
1603         if (bits & E5_ALPHA)
1604                 s->alpha = MSG_ReadByte();
1605         if (bits & E5_SCALE)
1606                 s->scale = MSG_ReadByte();
1607         if (bits & E5_COLORMAP)
1608                 s->colormap = MSG_ReadByte();
1609         if (bits & E5_ATTACHMENT)
1610         {
1611                 s->tagentity = (unsigned short) MSG_ReadShort();
1612                 s->tagindex = MSG_ReadByte();
1613         }
1614         if (bits & E5_LIGHT)
1615         {
1616                 s->light[0] = (unsigned short) MSG_ReadShort();
1617                 s->light[1] = (unsigned short) MSG_ReadShort();
1618                 s->light[2] = (unsigned short) MSG_ReadShort();
1619                 s->light[3] = (unsigned short) MSG_ReadShort();
1620                 s->lightstyle = MSG_ReadByte();
1621                 s->lightpflags = MSG_ReadByte();
1622         }
1623         if (bits & E5_GLOW)
1624         {
1625                 s->glowsize = MSG_ReadByte();
1626                 s->glowcolor = MSG_ReadByte();
1627         }
1628
1629
1630         if (developer_networkentities.integer >= 2)
1631         {
1632                 Con_Printf("ReadFields e%i", s->number);
1633
1634                 if (bits & E5_ORIGIN)
1635                         Con_Printf(" E5_ORIGIN %f %f %f", s->origin[0], s->origin[1], s->origin[2]);
1636                 if (bits & E5_ANGLES)
1637                         Con_Printf(" E5_ANGLES %f %f %f", s->angles[0], s->angles[1], s->angles[2]);
1638                 if (bits & E5_MODEL)
1639                         Con_Printf(" E5_MODEL %i", s->modelindex);
1640                 if (bits & E5_FRAME)
1641                         Con_Printf(" E5_FRAME %i", s->frame);
1642                 if (bits & E5_SKIN)
1643                         Con_Printf(" E5_SKIN %i", s->skin);
1644                 if (bits & E5_EFFECTS)
1645                         Con_Printf(" E5_EFFECTS %i", s->effects);
1646                 if (bits & E5_FLAGS)
1647                 {
1648                         Con_Printf(" E5_FLAGS %i (", s->flags);
1649                         if (s->flags & RENDER_STEP)
1650                                 Con_Print(" STEP");
1651                         if (s->flags & RENDER_GLOWTRAIL)
1652                                 Con_Print(" GLOWTRAIL");
1653                         if (s->flags & RENDER_VIEWMODEL)
1654                                 Con_Print(" VIEWMODEL");
1655                         if (s->flags & RENDER_EXTERIORMODEL)
1656                                 Con_Print(" EXTERIORMODEL");
1657                         if (s->flags & RENDER_LOWPRECISION)
1658                                 Con_Print(" LOWPRECISION");
1659                         if (s->flags & RENDER_COLORMAPPED)
1660                                 Con_Print(" COLORMAPPED");
1661                         if (s->flags & RENDER_SHADOW)
1662                                 Con_Print(" SHADOW");
1663                         if (s->flags & RENDER_LIGHT)
1664                                 Con_Print(" LIGHT");
1665                         Con_Print(")");
1666                 }
1667                 if (bits & E5_ALPHA)
1668                         Con_Printf(" E5_ALPHA %f", s->alpha / 255.0f);
1669                 if (bits & E5_SCALE)
1670                         Con_Printf(" E5_SCALE %f", s->scale / 16.0f);
1671                 if (bits & E5_COLORMAP)
1672                         Con_Printf(" E5_COLORMAP %i", s->colormap);
1673                 if (bits & E5_ATTACHMENT)
1674                         Con_Printf(" E5_ATTACHMENT e%i:%i", s->tagentity, s->tagindex);
1675                 if (bits & E5_LIGHT)
1676                         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);
1677                 if (bits & E5_GLOW)
1678                         Con_Printf(" E5_GLOW %i:%i", s->glowsize * 4, s->glowcolor);
1679                 Con_Print("\n");
1680         }
1681 }
1682
1683 int EntityState5_DeltaBits(const entity_state_t *o, const entity_state_t *n)
1684 {
1685         unsigned int bits = 0;
1686         if (n->active)
1687         {
1688                 if (!o->active)
1689                         bits |= E5_FULLUPDATE;
1690                 if (!VectorCompare(o->origin, n->origin))
1691                         bits |= E5_ORIGIN;
1692                 if (!VectorCompare(o->angles, n->angles))
1693                         bits |= E5_ANGLES;
1694                 if (o->modelindex != n->modelindex)
1695                         bits |= E5_MODEL;
1696                 if (o->frame != n->frame)
1697                         bits |= E5_FRAME;
1698                 if (o->skin != n->skin)
1699                         bits |= E5_SKIN;
1700                 if (o->effects != n->effects)
1701                         bits |= E5_EFFECTS;
1702                 if (o->flags != n->flags)
1703                         bits |= E5_FLAGS;
1704                 if (o->alpha != n->alpha)
1705                         bits |= E5_ALPHA;
1706                 if (o->scale != n->scale)
1707                         bits |= E5_SCALE;
1708                 if (o->colormap != n->colormap)
1709                         bits |= E5_COLORMAP;
1710                 if (o->tagentity != n->tagentity || o->tagindex != n->tagindex)
1711                         bits |= E5_ATTACHMENT;
1712                 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)
1713                         bits |= E5_LIGHT;
1714                 if (o->glowsize != n->glowsize || o->glowcolor != n->glowcolor)
1715                         bits |= E5_GLOW;
1716         }
1717         else
1718                 if (o->active)
1719                         bits |= E5_FULLUPDATE;
1720         return bits;
1721 }
1722
1723 void EntityFrame5_CL_ReadFrame(void)
1724 {
1725         int n, enumber;
1726         entity_t *ent;
1727         entity_state_t *s;
1728         // read the number of this frame to echo back in next input packet
1729         cl.latestframenum = MSG_ReadLong();
1730         // read entity numbers until we find a 0x8000
1731         // (which would be remove world entity, but is actually a terminator)
1732         while ((n = (unsigned short)MSG_ReadShort()) != 0x8000 && !msg_badread)
1733         {
1734                 // get the entity number and look it up
1735                 enumber = n & 0x7FFF;
1736                 ent = cl_entities + enumber;
1737                 // slide the current into the previous slot
1738                 ent->state_previous = ent->state_current;
1739                 // read the update
1740                 s = &ent->state_current;
1741                 if (n & 0x8000)
1742                 {
1743                         // remove entity
1744                         *s = defaultstate;
1745                 }
1746                 else
1747                 {
1748                         // update entity
1749                         EntityState5_ReadUpdate(s);
1750                 }
1751                 // set the cl_entities_active flag
1752                 cl_entities_active[enumber] = s->active;
1753                 // set the update time
1754                 s->time = cl.mtime[0];
1755                 // fix the number (it gets wiped occasionally by copying from defaultstate)
1756                 s->number = enumber;
1757                 // check if we need to update the lerp stuff
1758                 if (s->active)
1759                         CL_MoveLerpEntityStates(&cl_entities[enumber]);
1760                 // print extra messages if desired
1761                 if (developer_networkentities.integer >= 2 && cl_entities[enumber].state_current.active != cl_entities[enumber].state_previous.active)
1762                 {
1763                         if (cl_entities[enumber].state_current.active)
1764                                 Con_Printf("entity #%i has become active\n", enumber);
1765                         else if (cl_entities[enumber].state_previous.active)
1766                                 Con_Printf("entity #%i has become inactive\n", enumber);
1767                 }
1768         }
1769 }
1770
1771 void EntityFrame5_AckFrame(entityframe5_database_t *d, int framenum, int viewentnum)
1772 {
1773         int i, j, k, l, bits;
1774         entityframe5_changestate_t *s, *s2;
1775         entityframe5_packetlog_t *p, *p2;
1776         if (framenum <= d->ackframenum)
1777                 return;
1778         d->ackframenum = framenum;
1779         // scan for packets made obsolete by this ack
1780         for (i = 0, p = d->packetlog;i < ENTITYFRAME5_MAXPACKETLOGS;i++, p++)
1781         {
1782                 // skip packets that are empty or in the future
1783                 if (p->packetnumber == 0 || p->packetnumber > framenum)
1784                         continue;
1785                 // if the packetnumber matches it is deleted without any processing 
1786                 // (since it was received).
1787                 // if the packet number is less than this ack it was lost and its
1788                 // important information will be repeated in this update if it is not
1789                 // already obsolete due to a later update.
1790                 if (p->packetnumber < framenum)
1791                 {
1792                         // packet was lost - merge deltabits into the main array so they
1793                         // will be re-sent, but only if there is no newer update of that
1794                         // bit in the logs (as those will arrive before this update)
1795                         for (j = 0, s = p->states;j < p->numstates;j++, s++)
1796                         {
1797                                 // check for any newer updates to this entity and mask off any
1798                                 // overlapping bits (we don't need to send something again if
1799                                 // it has already been sent more recently)
1800                                 bits = s->bits & ~d->deltabits[s->number];
1801                                 for (k = 0, p2 = d->packetlog;k < ENTITYFRAME5_MAXPACKETLOGS && bits;k++, p2++)
1802                                 {
1803                                         if (p2->packetnumber > framenum)
1804                                         {
1805                                                 for (l = 0, s2 = p2->states;l < p2->numstates;l++, p2++)
1806                                                 {
1807                                                         if (s2->number == s->number)
1808                                                         {
1809                                                                 bits &= ~s2->bits;
1810                                                                 break;
1811                                                         }
1812                                                 }
1813                                         }
1814                                 }
1815                                 // if the bits haven't all been cleared, there were some bits
1816                                 // lost with this packet, so set them again now
1817                                 if (bits)
1818                                 {
1819                                         d->deltabits[s->number] |= bits;
1820                                         d->priorities[s->number] = EntityState5_Priority(d, d->states + viewentnum, d->states + s->number, d->deltabits[s->number], d->latestframenum - d->updateframenum[s->number]);
1821                                 }
1822                         }
1823                 }
1824                 // delete this packet log as it is now obsolete
1825                 p->packetnumber = 0;
1826         }
1827 }
1828
1829 int entityframe5_prioritychaincounts[E5_PROTOCOL_PRIORITYLEVELS];
1830 unsigned short entityframe5_prioritychains[E5_PROTOCOL_PRIORITYLEVELS][ENTITYFRAME5_MAXSTATES];
1831
1832 void EntityFrame5_WriteFrame(sizebuf_t *msg, entityframe5_database_t *d, int numstates, const entity_state_t *states, int viewentnum)
1833 {
1834         const entity_state_t *n;
1835         int i, num, l, framenum, packetlognumber, priority;
1836         sizebuf_t buf;
1837         qbyte data[128];
1838         entityframe5_packetlog_t *packetlog;
1839
1840         framenum = d->latestframenum + 1;
1841
1842         // prepare the buffer
1843         memset(&buf, 0, sizeof(buf));
1844         buf.data = data;
1845         buf.maxsize = sizeof(data);
1846
1847         // detect changes in states
1848         num = 0;
1849         for (i = 0, n = states;i < numstates;i++, n++)
1850         {
1851                 // mark gaps in entity numbering as removed entities
1852                 for (;num < n->number;num++)
1853                 {
1854                         // if the entity used to exist, clear it
1855                         if (CHECKPVSBIT(d->visiblebits, num))
1856                         {
1857                                 CLEARPVSBIT(d->visiblebits, num);
1858                                 d->deltabits[num] = E5_FULLUPDATE;
1859                                 d->priorities[num] = EntityState5_Priority(d, d->states + viewentnum, d->states + num, d->deltabits[num], framenum - d->updateframenum[num]);
1860                                 d->states[num] = defaultstate;
1861                                 d->states[num].number = num;
1862                         }
1863                 }
1864                 // update the entity state data
1865                 if (!CHECKPVSBIT(d->visiblebits, num))
1866                 {
1867                         // entity just spawned in, don't let it completely hog priority
1868                         // because of being ancient on the first frame
1869                         d->updateframenum[num] = framenum;
1870                 }
1871                 SETPVSBIT(d->visiblebits, num);
1872                 d->deltabits[num] |= EntityState5_DeltaBits(d->states + num, n);
1873                 d->priorities[num] = EntityState5_Priority(d, d->states + viewentnum, d->states + num, d->deltabits[num], framenum - d->updateframenum[num]);
1874                 d->states[num] = *n;
1875                 d->states[num].number = num;
1876                 // advance to next entity so the next iteration doesn't immediately remove it
1877                 num++;
1878         }
1879         // all remaining entities are dead
1880         for (;num < MAX_EDICTS;num++)
1881         {
1882                 if (CHECKPVSBIT(d->visiblebits, num))
1883                 {
1884                         CLEARPVSBIT(d->visiblebits, num);
1885                         d->deltabits[num] = E5_FULLUPDATE;
1886                         d->priorities[num] = EntityState5_Priority(d, d->states + viewentnum, d->states + num, d->deltabits[num], framenum - d->updateframenum[num]);
1887                         d->states[num] = defaultstate;
1888                         d->states[num].number = num;
1889                 }
1890         }
1891
1892         // build lists of entities by priority level
1893         memset(entityframe5_prioritychaincounts, 0, sizeof(entityframe5_prioritychaincounts));
1894         l = 0;
1895         for (num = 0;num < MAX_EDICTS;num++)
1896         {
1897                 if (d->priorities[num])
1898                 {
1899                         l = num;
1900                         priority = d->priorities[num];
1901                         if (entityframe5_prioritychaincounts[priority] < ENTITYFRAME5_MAXSTATES)
1902                                 entityframe5_prioritychains[priority][entityframe5_prioritychaincounts[priority]++] = num;
1903                 }
1904         }
1905
1906         // return early if there are no entities to send this time
1907         if (l == 0)
1908                 return;
1909
1910         d->latestframenum = framenum;
1911         MSG_WriteByte(msg, svc_entities);
1912         MSG_WriteLong(msg, framenum);
1913
1914         // if packet log is full, an empty update is still written
1915         // (otherwise the client might have nothing to ack to remove packetlogs)
1916         for (packetlognumber = 0, packetlog = d->packetlog;packetlognumber < ENTITYFRAME5_MAXPACKETLOGS;packetlognumber++, packetlog++)
1917                 if (packetlog->packetnumber == 0)
1918                         break;
1919         if (packetlognumber < ENTITYFRAME5_MAXPACKETLOGS)
1920         {
1921                 // write to packet and log
1922                 packetlog->packetnumber = framenum;
1923                 packetlog->numstates = 0;
1924                 for (priority = E5_PROTOCOL_PRIORITYLEVELS - 1;priority >= 0 && packetlog->numstates < ENTITYFRAME5_MAXSTATES;priority--)
1925                 {
1926                         for (i = 0;i < entityframe5_prioritychaincounts[priority] && packetlog->numstates < ENTITYFRAME5_MAXSTATES;i++)
1927                         {
1928                                 num = entityframe5_prioritychains[priority][i];
1929                                 n = d->states + num;
1930                                 if (d->deltabits[num] & E5_FULLUPDATE)
1931                                         d->deltabits[num] = E5_FULLUPDATE | EntityState5_DeltaBits(&defaultstate, n);
1932                                 buf.cursize = 0;
1933                                 EntityState5_WriteUpdate(num, n, d->deltabits[num], &buf);
1934                                 // if the entity won't fit, try the next one
1935                                 if (msg->cursize + buf.cursize + 2 > msg->maxsize)
1936                                         continue;
1937                                 // write entity to the packet
1938                                 SZ_Write(msg, buf.data, buf.cursize);
1939                                 // mark age on entity for prioritization
1940                                 d->updateframenum[num] = framenum;
1941                                 // log entity so deltabits can be restored later if lost
1942                                 packetlog->states[packetlog->numstates].number = num;
1943                                 packetlog->states[packetlog->numstates].bits = d->deltabits[num];
1944                                 packetlog->numstates++;
1945                                 // clear deltabits and priority so it won't be sent again
1946                                 d->deltabits[num] = 0;
1947                                 d->priorities[num] = 0;
1948                         }
1949                 }
1950         }
1951
1952         MSG_WriteShort(msg, 0x8000);
1953 }
1954