]> icculus.org git repositories - divverent/darkplaces.git/blob - protocol.c
added support for PROTOCOL_NEHAHRAMOVIE in more places, so now nehahra works again...
[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         else
552                 Host_Error("EntityState_ReadFields: unknown cl.protocol %i\n", cl.protocol);
553         if (cl.protocol == PROTOCOL_DARKPLACES5 && !(e->flags & RENDER_LOWPRECISION))
554         {
555                 if (bits & E_ANGLE1)
556                         e->angles[0] = MSG_ReadAngle16i();
557                 if (bits & E_ANGLE2)
558                         e->angles[1] = MSG_ReadAngle16i();
559                 if (bits & E_ANGLE3)
560                         e->angles[2] = MSG_ReadAngle16i();
561         }
562         else
563         {
564                 if (bits & E_ANGLE1)
565                         e->angles[0] = MSG_ReadAngle8i();
566                 if (bits & E_ANGLE2)
567                         e->angles[1] = MSG_ReadAngle8i();
568                 if (bits & E_ANGLE3)
569                         e->angles[2] = MSG_ReadAngle8i();
570         }
571         if (bits & E_MODEL1)
572                 e->modelindex = (e->modelindex & 0xFF00) | (unsigned int) MSG_ReadByte();
573         if (bits & E_MODEL2)
574                 e->modelindex = (e->modelindex & 0x00FF) | ((unsigned int) MSG_ReadByte() << 8);
575         if (bits & E_FRAME1)
576                 e->frame = (e->frame & 0xFF00) | (unsigned int) MSG_ReadByte();
577         if (bits & E_FRAME2)
578                 e->frame = (e->frame & 0x00FF) | ((unsigned int) MSG_ReadByte() << 8);
579         if (bits & E_EFFECTS1)
580                 e->effects = (e->effects & 0xFF00) | (unsigned int) MSG_ReadByte();
581         if (bits & E_EFFECTS2)
582                 e->effects = (e->effects & 0x00FF) | ((unsigned int) MSG_ReadByte() << 8);
583         if (bits & E_COLORMAP)
584                 e->colormap = MSG_ReadByte();
585         if (bits & E_SKIN)
586                 e->skin = MSG_ReadByte();
587         if (bits & E_ALPHA)
588                 e->alpha = MSG_ReadByte();
589         if (bits & E_SCALE)
590                 e->scale = MSG_ReadByte();
591         if (bits & E_GLOWSIZE)
592                 e->glowsize = MSG_ReadByte();
593         if (bits & E_GLOWCOLOR)
594                 e->glowcolor = MSG_ReadByte();
595         if (cl.protocol == PROTOCOL_DARKPLACES2)
596                 if (bits & E_FLAGS)
597                         e->flags = MSG_ReadByte();
598         if (bits & E_TAGATTACHMENT)
599         {
600                 e->tagentity = (unsigned short) MSG_ReadShort();
601                 e->tagindex = MSG_ReadByte();
602         }
603         if (bits & E_LIGHT)
604         {
605                 e->light[0] = (unsigned short) MSG_ReadShort();
606                 e->light[1] = (unsigned short) MSG_ReadShort();
607                 e->light[2] = (unsigned short) MSG_ReadShort();
608                 e->light[3] = (unsigned short) MSG_ReadShort();
609         }
610         if (bits & E_LIGHTSTYLE)
611                 e->lightstyle = MSG_ReadByte();
612         if (bits & E_LIGHTPFLAGS)
613                 e->lightpflags = MSG_ReadByte();
614
615         if (developer_networkentities.integer >= 2)
616         {
617                 Con_Printf("ReadFields e%i", e->number);
618
619                 if (bits & E_ORIGIN1)
620                         Con_Printf(" E_ORIGIN1 %f", e->origin[0]);
621                 if (bits & E_ORIGIN2)
622                         Con_Printf(" E_ORIGIN2 %f", e->origin[1]);
623                 if (bits & E_ORIGIN3)
624                         Con_Printf(" E_ORIGIN3 %f", e->origin[2]);
625                 if (bits & E_ANGLE1)
626                         Con_Printf(" E_ANGLE1 %f", e->angles[0]);
627                 if (bits & E_ANGLE2)
628                         Con_Printf(" E_ANGLE2 %f", e->angles[1]);
629                 if (bits & E_ANGLE3)
630                         Con_Printf(" E_ANGLE3 %f", e->angles[2]);
631                 if (bits & (E_MODEL1 | E_MODEL2))
632                         Con_Printf(" E_MODEL %i", e->modelindex);
633
634                 if (bits & (E_FRAME1 | E_FRAME2))
635                         Con_Printf(" E_FRAME %i", e->frame);
636                 if (bits & (E_EFFECTS1 | E_EFFECTS2))
637                         Con_Printf(" E_EFFECTS %i", e->effects);
638                 if (bits & E_ALPHA)
639                         Con_Printf(" E_ALPHA %f", e->alpha / 255.0f);
640                 if (bits & E_SCALE)
641                         Con_Printf(" E_SCALE %f", e->scale / 16.0f);
642                 if (bits & E_COLORMAP)
643                         Con_Printf(" E_COLORMAP %i", e->colormap);
644                 if (bits & E_SKIN)
645                         Con_Printf(" E_SKIN %i", e->skin);
646
647                 if (bits & E_GLOWSIZE)
648                         Con_Printf(" E_GLOWSIZE %i", e->glowsize * 4);
649                 if (bits & E_GLOWCOLOR)
650                         Con_Printf(" E_GLOWCOLOR %i", e->glowcolor);
651                 
652                 if (bits & E_LIGHT)
653                         Con_Printf(" E_LIGHT %i:%i:%i:%i", e->light[0], e->light[1], e->light[2], e->light[3]);
654                 if (bits & E_LIGHTPFLAGS)                       
655                         Con_Printf(" E_LIGHTPFLAGS %i", e->lightpflags);
656
657                 if (bits & E_TAGATTACHMENT)
658                         Con_Printf(" E_TAGATTACHMENT e%i:%i", e->tagentity, e->tagindex);
659                 if (bits & E_LIGHTSTYLE)
660                         Con_Printf(" E_LIGHTSTYLE %i", e->lightstyle);
661                 Con_Print("\n");
662         }
663 }
664
665 // (client and server) allocates a new empty database
666 entityframe_database_t *EntityFrame_AllocDatabase(mempool_t *mempool)
667 {
668         return Mem_Alloc(mempool, sizeof(entityframe_database_t));
669 }
670
671 // (client and server) frees the database
672 void EntityFrame_FreeDatabase(entityframe_database_t *d)
673 {
674         Mem_Free(d);
675 }
676
677 // (server) clears the database to contain no frames (thus delta compression compresses against nothing)
678 void EntityFrame_ClearDatabase(entityframe_database_t *d)
679 {
680         memset(d, 0, sizeof(*d));
681 }
682
683 // (server and client) removes frames older than 'frame' from database
684 void EntityFrame_AckFrame(entityframe_database_t *d, int frame)
685 {
686         int i;
687         d->ackframenum = frame;
688         for (i = 0;i < d->numframes && d->frames[i].framenum < frame;i++);
689         // ignore outdated frame acks (out of order packets)
690         if (i == 0)
691                 return;
692         d->numframes -= i;
693         // if some queue is left, slide it down to beginning of array
694         if (d->numframes)
695                 memmove(&d->frames[0], &d->frames[i], sizeof(d->frames[0]) * d->numframes);
696 }
697
698 // (server) clears frame, to prepare for adding entities
699 void EntityFrame_Clear(entity_frame_t *f, vec3_t eye, int framenum)
700 {
701         f->time = 0;
702         f->framenum = framenum;
703         f->numentities = 0;
704         if (eye == NULL)
705                 VectorClear(f->eye);
706         else
707                 VectorCopy(eye, f->eye);
708 }
709
710 // (server and client) reads a frame from the database
711 void EntityFrame_FetchFrame(entityframe_database_t *d, int framenum, entity_frame_t *f)
712 {
713         int i, n;
714         EntityFrame_Clear(f, NULL, -1);
715         for (i = 0;i < d->numframes && d->frames[i].framenum < framenum;i++);
716         if (i < d->numframes && framenum == d->frames[i].framenum)
717         {
718                 f->framenum = framenum;
719                 f->numentities = d->frames[i].endentity - d->frames[i].firstentity;
720                 n = MAX_ENTITY_DATABASE - (d->frames[i].firstentity % MAX_ENTITY_DATABASE);
721                 if (n > f->numentities)
722                         n = f->numentities;
723                 memcpy(f->entitydata, d->entitydata + d->frames[i].firstentity % MAX_ENTITY_DATABASE, sizeof(*f->entitydata) * n);
724                 if (f->numentities > n)
725                         memcpy(f->entitydata + n, d->entitydata, sizeof(*f->entitydata) * (f->numentities - n));
726                 VectorCopy(d->eye, f->eye);
727         }
728 }
729
730 // (server and client) adds a entity_frame to the database, for future reference
731 void EntityFrame_AddFrame(entityframe_database_t *d, vec3_t eye, int framenum, int numentities, const entity_state_t *entitydata)
732 {
733         int n, e;
734         entity_frameinfo_t *info;
735
736         VectorCopy(eye, d->eye);
737
738         // figure out how many entity slots are used already
739         if (d->numframes)
740         {
741                 n = d->frames[d->numframes - 1].endentity - d->frames[0].firstentity;
742                 if (n + numentities > MAX_ENTITY_DATABASE || d->numframes >= MAX_ENTITY_HISTORY)
743                 {
744                         // ran out of room, dump database
745                         EntityFrame_ClearDatabase(d);
746                 }
747         }
748
749         info = &d->frames[d->numframes];
750         info->framenum = framenum;
751         e = -1000;
752         // make sure we check the newly added frame as well, but we haven't incremented numframes yet
753         for (n = 0;n <= d->numframes;n++)
754         {
755                 if (e >= d->frames[n].framenum)
756                 {
757                         if (e == framenum)
758                                 Con_Print("EntityFrame_AddFrame: tried to add out of sequence frame to database\n");
759                         else
760                                 Con_Print("EntityFrame_AddFrame: out of sequence frames in database\n");
761                         return;
762                 }
763                 e = d->frames[n].framenum;
764         }
765         // if database still has frames after that...
766         if (d->numframes)
767                 info->firstentity = d->frames[d->numframes - 1].endentity;
768         else
769                 info->firstentity = 0;
770         info->endentity = info->firstentity + numentities;
771         d->numframes++;
772
773         n = info->firstentity % MAX_ENTITY_DATABASE;
774         e = MAX_ENTITY_DATABASE - n;
775         if (e > numentities)
776                 e = numentities;
777         memcpy(d->entitydata + n, entitydata, sizeof(entity_state_t) * e);
778         if (numentities > e)
779                 memcpy(d->entitydata, entitydata + e, sizeof(entity_state_t) * (numentities - e));
780 }
781
782 // (server) writes a frame to network stream
783 static entity_frame_t deltaframe; // FIXME?
784 void EntityFrame_WriteFrame(sizebuf_t *msg, entityframe_database_t *d, int numstates, const entity_state_t *states, int viewentnum)
785 {
786         int i, onum, number;
787         entity_frame_t *o = &deltaframe;
788         const entity_state_t *ent, *delta;
789         vec3_t eye;
790
791         d->latestframenum++;
792
793         VectorClear(eye);
794         for (i = 0;i < numstates;i++)
795         {
796                 if (states[i].number == viewentnum)
797                 {
798                         VectorSet(eye, states[i].origin[0], states[i].origin[1], states[i].origin[2] + 22);
799                         break;
800                 }
801         }
802
803         EntityFrame_AddFrame(d, eye, d->latestframenum, numstates, states);
804
805         EntityFrame_FetchFrame(d, d->ackframenum, o);
806
807         MSG_WriteByte (msg, svc_entities);
808         MSG_WriteLong (msg, o->framenum);
809         MSG_WriteLong (msg, d->latestframenum);
810         MSG_WriteFloat (msg, eye[0]);
811         MSG_WriteFloat (msg, eye[1]);
812         MSG_WriteFloat (msg, eye[2]);
813
814         onum = 0;
815         for (i = 0;i < numstates;i++)
816         {
817                 ent = states + i;
818                 number = ent->number;
819                 for (;onum < o->numentities && o->entitydata[onum].number < number;onum++)
820                 {
821                         // write remove message
822                         MSG_WriteShort(msg, o->entitydata[onum].number | 0x8000);
823                 }
824                 if (onum < o->numentities && (o->entitydata[onum].number == number))
825                 {
826                         // delta from previous frame
827                         delta = o->entitydata + onum;
828                         // advance to next entity in delta frame
829                         onum++;
830                 }
831                 else
832                 {
833                         // delta from defaults
834                         delta = &defaultstate;
835                 }
836                 EntityState_WriteUpdate(ent, msg, delta);
837         }
838         for (;onum < o->numentities;onum++)
839         {
840                 // write remove message
841                 MSG_WriteShort(msg, o->entitydata[onum].number | 0x8000);
842         }
843         MSG_WriteShort(msg, 0xFFFF);
844 }
845
846 // (client) reads a frame from network stream
847 static entity_frame_t framedata; // FIXME?
848 void EntityFrame_CL_ReadFrame(void)
849 {
850         int i, number, removed;
851         entity_frame_t *f = &framedata, *delta = &deltaframe;
852         entity_state_t *e, *old, *oldend;
853         entity_t *ent;
854         entityframe_database_t *d;
855         if (!cl.entitydatabase)
856                 cl.entitydatabase = EntityFrame_AllocDatabase(cl_entities_mempool);
857         d = cl.entitydatabase;
858
859         EntityFrame_Clear(f, NULL, -1);
860
861         // read the frame header info
862         f->time = cl.mtime[0];
863         number = MSG_ReadLong();
864         cl.latestframenum = f->framenum = MSG_ReadLong();
865         f->eye[0] = MSG_ReadFloat();
866         f->eye[1] = MSG_ReadFloat();
867         f->eye[2] = MSG_ReadFloat();
868         EntityFrame_AckFrame(d, number);
869         EntityFrame_FetchFrame(d, number, delta);
870         old = delta->entitydata;
871         oldend = old + delta->numentities;
872         // read entities until we hit the magic 0xFFFF end tag
873         while ((number = (unsigned short) MSG_ReadShort()) != 0xFFFF && !msg_badread)
874         {
875                 if (msg_badread)
876                         Host_Error("EntityFrame_Read: read error\n");
877                 removed = number & 0x8000;
878                 number &= 0x7FFF;
879                 if (number >= MAX_EDICTS)
880                         Host_Error("EntityFrame_Read: number (%i) >= MAX_EDICTS (%i)\n", number, MAX_EDICTS);
881
882                 // seek to entity, while copying any skipped entities (assume unchanged)
883                 while (old < oldend && old->number < number)
884                 {
885                         if (f->numentities >= MAX_ENTITY_DATABASE)
886                                 Host_Error("EntityFrame_Read: entity list too big\n");
887                         f->entitydata[f->numentities] = *old++;
888                         f->entitydata[f->numentities++].time = cl.mtime[0];
889                 }
890                 if (removed)
891                 {
892                         if (old < oldend && old->number == number)
893                                 old++;
894                         else
895                                 Con_Printf("EntityFrame_Read: REMOVE on unused entity %i\n", number);
896                 }
897                 else
898                 {
899                         if (f->numentities >= MAX_ENTITY_DATABASE)
900                                 Host_Error("EntityFrame_Read: entity list too big\n");
901
902                         // reserve this slot
903                         e = f->entitydata + f->numentities++;
904
905                         if (old < oldend && old->number == number)
906                         {
907                                 // delta from old entity
908                                 *e = *old++;
909                         }
910                         else
911                         {
912                                 // delta from defaults
913                                 *e = defaultstate;
914                         }
915
916                         cl_entities_active[number] = true;
917                         e->active = true;
918                         e->time = cl.mtime[0];
919                         e->number = number;
920                         EntityState_ReadFields(e, EntityState_ReadExtendBits());
921                 }
922         }
923         while (old < oldend)
924         {
925                 if (f->numentities >= MAX_ENTITY_DATABASE)
926                         Host_Error("EntityFrame_Read: entity list too big\n");
927                 f->entitydata[f->numentities] = *old++;
928                 f->entitydata[f->numentities++].time = cl.mtime[0];
929         }
930         EntityFrame_AddFrame(d, f->eye, f->framenum, f->numentities, f->entitydata);
931
932         memset(cl_entities_active, 0, cl_max_entities * sizeof(qbyte));
933         number = 1;
934         for (i = 0;i < f->numentities;i++)
935         {
936                 for (;number < f->entitydata[i].number;number++)
937                 {
938                         if (cl_entities_active[number])
939                         {
940                                 cl_entities_active[number] = false;
941                                 cl_entities[number].state_current.active = false;
942                         }
943                 }
944                 // update the entity
945                 ent = &cl_entities[number];
946                 ent->state_previous = ent->state_current;
947                 ent->state_current = f->entitydata[i];
948                 CL_MoveLerpEntityStates(ent);
949                 // the entity lives again...
950                 cl_entities_active[number] = true;
951                 number++;
952         }
953         for (;number < cl_max_entities;number++)
954         {
955                 if (cl_entities_active[number])
956                 {
957                         cl_entities_active[number] = false;
958                         cl_entities[number].state_current.active = false;
959                 }
960         }
961 }
962
963
964 // (client) returns the frame number of the most recent frame recieved
965 int EntityFrame_MostRecentlyRecievedFrameNum(entityframe_database_t *d)
966 {
967         if (d->numframes)
968                 return d->frames[d->numframes - 1].framenum;
969         else
970                 return -1;
971 }
972
973
974
975
976
977
978 entity_state_t *EntityFrame4_GetReferenceEntity(entityframe4_database_t *d, int number)
979 {
980         if (d->maxreferenceentities <= number)
981         {
982                 int oldmax = d->maxreferenceentities;
983                 entity_state_t *oldentity = d->referenceentity;
984                 d->maxreferenceentities = (number + 15) & ~7;
985                 d->referenceentity = Mem_Alloc(d->mempool, d->maxreferenceentities * sizeof(*d->referenceentity));
986                 if (oldentity)
987                 {
988                         memcpy(d->referenceentity, oldentity, oldmax * sizeof(*d->referenceentity));
989                         Mem_Free(oldentity);
990                 }
991                 // clear the newly created entities
992                 for (;oldmax < d->maxreferenceentities;oldmax++)
993                 {
994                         d->referenceentity[oldmax] = defaultstate;
995                         d->referenceentity[oldmax].number = oldmax;
996                 }
997         }
998         return d->referenceentity + number;
999 }
1000
1001 void EntityFrame4_AddCommitEntity(entityframe4_database_t *d, const entity_state_t *s)
1002 {
1003         // resize commit's entity list if full
1004         if (d->currentcommit->maxentities <= d->currentcommit->numentities)
1005         {
1006                 entity_state_t *oldentity = d->currentcommit->entity;
1007                 d->currentcommit->maxentities += 8;
1008                 d->currentcommit->entity = Mem_Alloc(d->mempool, d->currentcommit->maxentities * sizeof(*d->currentcommit->entity));
1009                 if (oldentity)
1010                 {
1011                         memcpy(d->currentcommit->entity, oldentity, d->currentcommit->numentities * sizeof(*d->currentcommit->entity));
1012                         Mem_Free(oldentity);
1013                 }
1014         }
1015         d->currentcommit->entity[d->currentcommit->numentities++] = *s;
1016 }
1017
1018 entityframe4_database_t *EntityFrame4_AllocDatabase(mempool_t *pool)
1019 {
1020         entityframe4_database_t *d;
1021         d = Mem_Alloc(pool, sizeof(*d));
1022         d->mempool = pool;
1023         EntityFrame4_ResetDatabase(d);
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->referenceframenum = -1;
1042         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1043                 d->commit[i].numentities = 0;
1044         for (i = 0;i < d->maxreferenceentities;i++)
1045                 d->referenceentity[i] = defaultstate;
1046 }
1047
1048 int EntityFrame4_AckFrame(entityframe4_database_t *d, int framenum, int servermode)
1049 {
1050         int i, j, found;
1051         entity_database4_commit_t *commit;
1052         if (framenum == -1)
1053         {
1054                 // reset reference, but leave commits alone
1055                 d->referenceframenum = -1;
1056                 for (i = 0;i < d->maxreferenceentities;i++)
1057                         d->referenceentity[i] = defaultstate;
1058                 // if this is the server, remove commits
1059                         for (i = 0, commit = d->commit;i < MAX_ENTITY_HISTORY;i++, commit++)
1060                                 commit->numentities = 0;
1061                 found = true;
1062         }
1063         else if (d->referenceframenum == framenum)
1064                 found = true;
1065         else
1066         {
1067                 found = false;
1068                 for (i = 0, commit = d->commit;i < MAX_ENTITY_HISTORY;i++, commit++)
1069                 {
1070                         if (commit->numentities && commit->framenum <= framenum)
1071                         {
1072                                 if (commit->framenum == framenum)
1073                                 {
1074                                         found = true;
1075                                         d->referenceframenum = framenum;
1076                                         if (developer_networkentities.integer >= 3)
1077                                         {
1078                                                 for (j = 0;j < commit->numentities;j++)
1079                                                 {
1080                                                         entity_state_t *s = EntityFrame4_GetReferenceEntity(d, commit->entity[j].number);
1081                                                         if (commit->entity[j].active != s->active)
1082                                                         {
1083                                                                 if (commit->entity[j].active)
1084                                                                         Con_Printf("commit entity %i has become active (modelindex %i)\n", commit->entity[j].number, commit->entity[j].modelindex);
1085                                                                 else
1086                                                                         Con_Printf("commit entity %i has become inactive (modelindex %i)\n", commit->entity[j].number, commit->entity[j].modelindex);
1087                                                         }
1088                                                         *s = commit->entity[j];
1089                                                 }
1090                                         }
1091                                         else
1092                                                 for (j = 0;j < commit->numentities;j++)
1093                                                         *EntityFrame4_GetReferenceEntity(d, commit->entity[j].number) = commit->entity[j];
1094                                 }
1095                                 commit->numentities = 0;
1096                         }
1097                 }
1098         }
1099         if (developer_networkentities.integer >= 1)
1100         {
1101                 Con_Printf("ack ref:%i database updated to: ref:%i commits:", framenum, d->referenceframenum);
1102                 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1103                         if (d->commit[i].numentities)
1104                                 Con_Printf(" %i", d->commit[i].framenum);
1105                 Con_Print("\n");
1106         }
1107         return found;
1108 }
1109
1110 void EntityFrame4_CL_ReadFrame(void)
1111 {
1112         int i, n, cnumber, referenceframenum, framenum, enumber, done, stopnumber, skip = false;
1113         entity_state_t *s;
1114         entityframe4_database_t *d;
1115         if (!cl.entitydatabase4)
1116                 cl.entitydatabase4 = EntityFrame4_AllocDatabase(cl_entities_mempool);
1117         d = cl.entitydatabase4;
1118         // read the number of the frame this refers to
1119         referenceframenum = MSG_ReadLong();
1120         // read the number of this frame
1121         cl.latestframenum = framenum = MSG_ReadLong();
1122         // read the start number
1123         enumber = (unsigned short) MSG_ReadShort();
1124         if (developer_networkentities.integer >= 1)
1125         {
1126                 Con_Printf("recv svc_entities num:%i ref:%i database: ref:%i commits:", framenum, referenceframenum, d->referenceframenum);
1127                 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1128                         if (d->commit[i].numentities)
1129                                 Con_Printf(" %i", d->commit[i].framenum);
1130                 Con_Print("\n");
1131         }
1132         if (!EntityFrame4_AckFrame(d, referenceframenum, false))
1133         {
1134                 Con_Print("EntityFrame4_CL_ReadFrame: reference frame invalid (VERY BAD ERROR), this update will be skipped\n");
1135                 skip = true;
1136         }
1137         d->currentcommit = NULL;
1138         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1139         {
1140                 if (!d->commit[i].numentities)
1141                 {
1142                         d->currentcommit = d->commit + i;
1143                         d->currentcommit->framenum = framenum;
1144                         d->currentcommit->numentities = 0;
1145                 }
1146         }
1147         if (d->currentcommit == NULL)
1148         {
1149                 Con_Printf("EntityFrame4_CL_ReadFrame: error while decoding frame %i: database full, reading but not storing this update\n", framenum);
1150                 skip = true;
1151         }
1152         done = false;
1153         while (!done && !msg_badread)
1154         {
1155                 // read the number of the modified entity
1156                 // (gaps will be copied unmodified)
1157                 n = (unsigned short)MSG_ReadShort();
1158                 if (n == 0x8000)
1159                 {
1160                         // no more entities in this update, but we still need to copy the
1161                         // rest of the reference entities (final gap)
1162                         done = true;
1163                         // read end of range number, then process normally
1164                         n = (unsigned short)MSG_ReadShort();
1165                 }
1166                 // high bit means it's a remove message
1167                 cnumber = n & 0x7FFF;
1168                 // add one (the changed one) if not done
1169                 stopnumber = cnumber + !done;
1170                 // process entities in range from the last one to the changed one
1171                 for (;enumber < stopnumber;enumber++)
1172                 {
1173                         if (skip)
1174                         {
1175                                 if (enumber == cnumber && (n & 0x8000) == 0)
1176                                 {
1177                                         entity_state_t tempstate;
1178                                         EntityState_ReadFields(&tempstate, EntityState_ReadExtendBits());
1179                                 }
1180                                 continue;
1181                         }
1182                         // slide the current into the previous slot
1183                         cl_entities[enumber].state_previous = cl_entities[enumber].state_current;
1184                         // copy a new current from reference database
1185                         cl_entities[enumber].state_current = *EntityFrame4_GetReferenceEntity(d, enumber);
1186                         s = &cl_entities[enumber].state_current;
1187                         // if this is the one to modify, read more data...
1188                         if (enumber == cnumber)
1189                         {
1190                                 if (n & 0x8000)
1191                                 {
1192                                         // simply removed
1193                                         if (developer_networkentities.integer >= 2)
1194                                                 Con_Printf("entity %i: remove\n", enumber);
1195                                         *s = defaultstate;
1196                                 }
1197                                 else
1198                                 {
1199                                         // read the changes
1200                                         if (developer_networkentities.integer >= 2)
1201                                                 Con_Printf("entity %i: update\n", enumber);
1202                                         s->active = true;
1203                                         EntityState_ReadFields(s, EntityState_ReadExtendBits());
1204                                 }
1205                         }
1206                         else if (developer_networkentities.integer >= 4)
1207                                 Con_Printf("entity %i: copy\n", enumber);
1208                         // set the cl_entities_active flag
1209                         cl_entities_active[enumber] = s->active;
1210                         // set the update time
1211                         s->time = cl.mtime[0];
1212                         // fix the number (it gets wiped occasionally by copying from defaultstate)
1213                         s->number = enumber;
1214                         // check if we need to update the lerp stuff
1215                         if (s->active)
1216                                 CL_MoveLerpEntityStates(&cl_entities[enumber]);
1217                         // add this to the commit entry whether it is modified or not
1218                         if (d->currentcommit)
1219                                 EntityFrame4_AddCommitEntity(d, &cl_entities[enumber].state_current);
1220                         // print extra messages if desired
1221                         if (developer_networkentities.integer >= 2 && cl_entities[enumber].state_current.active != cl_entities[enumber].state_previous.active)
1222                         {
1223                                 if (cl_entities[enumber].state_current.active)
1224                                         Con_Printf("entity #%i has become active\n", enumber);
1225                                 else if (cl_entities[enumber].state_previous.active)
1226                                         Con_Printf("entity #%i has become inactive\n", enumber);
1227                         }
1228                 }
1229         }
1230         d->currentcommit = NULL;
1231         if (skip)
1232                 EntityFrame4_ResetDatabase(d);
1233 }
1234
1235 void EntityFrame4_WriteFrame(sizebuf_t *msg, entityframe4_database_t *d, int numstates, const entity_state_t *states)
1236 {
1237         const entity_state_t *e, *s;
1238         entity_state_t inactiveentitystate;
1239         int i, n, startnumber;
1240         sizebuf_t buf;
1241         qbyte data[128];
1242
1243         // if there isn't enough space to accomplish anything, skip it
1244         if (msg->cursize + 24 > msg->maxsize)
1245                 return;
1246
1247         // prepare the buffer
1248         memset(&buf, 0, sizeof(buf));
1249         buf.data = data;
1250         buf.maxsize = sizeof(data);
1251
1252         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1253                 if (!d->commit[i].numentities)
1254                         break;
1255         // if commit buffer full, just don't bother writing an update this frame
1256         if (i == MAX_ENTITY_HISTORY)
1257                 return;
1258         d->currentcommit = d->commit + i;
1259
1260         // this state's number gets played around with later
1261         inactiveentitystate = defaultstate;
1262
1263         d->currentcommit->numentities = 0;
1264         d->currentcommit->framenum = ++d->latestframenumber;
1265         MSG_WriteByte(msg, svc_entities);
1266         MSG_WriteLong(msg, d->referenceframenum);
1267         MSG_WriteLong(msg, d->currentcommit->framenum);
1268         if (developer_networkentities.integer >= 1)
1269         {
1270                 Con_Printf("send svc_entities num:%i ref:%i (database: ref:%i commits:", d->currentcommit->framenum, d->referenceframenum, d->referenceframenum);
1271                 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1272                         if (d->commit[i].numentities)
1273                                 Con_Printf(" %i", d->commit[i].framenum);
1274                 Con_Print(")\n");
1275         }
1276         if (d->currententitynumber >= sv.max_edicts)
1277                 startnumber = 1;
1278         else
1279                 startnumber = bound(1, d->currententitynumber, sv.max_edicts - 1);
1280         MSG_WriteShort(msg, startnumber);
1281         // reset currententitynumber so if the loop does not break it we will
1282         // start at beginning next frame (if it does break, it will set it)
1283         d->currententitynumber = 1;
1284         for (i = 0, n = startnumber;n < sv.max_edicts;n++)
1285         {
1286                 // find the old state to delta from
1287                 e = EntityFrame4_GetReferenceEntity(d, n);
1288                 // prepare the buffer
1289                 SZ_Clear(&buf);
1290                 // entity exists, build an update (if empty there is no change)
1291                 // find the state in the list
1292                 for (;i < numstates && states[i].number < n;i++);
1293                 // make the message
1294                 s = states + i;
1295                 if (s->number == n)
1296                 {
1297                         // build the update
1298                         EntityState_WriteUpdate(s, &buf, e);
1299                 }
1300                 else
1301                 {
1302                         inactiveentitystate.number = n;
1303                         s = &inactiveentitystate;
1304                         if (e->active)
1305                         {
1306                                 // entity used to exist but doesn't anymore, send remove
1307                                 MSG_WriteShort(&buf, n | 0x8000);
1308                         }
1309                 }
1310                 // if the commit is full, we're done this frame
1311                 if (msg->cursize + buf.cursize > msg->maxsize - 4)
1312                 {
1313                         // next frame we will continue where we left off
1314                         break;
1315                 }
1316                 // add the entity to the commit
1317                 EntityFrame4_AddCommitEntity(d, s);
1318                 // if the message is empty, skip out now
1319                 if (buf.cursize)
1320                 {
1321                         // write the message to the packet
1322                         SZ_Write(msg, buf.data, buf.cursize);
1323                 }
1324         }
1325         d->currententitynumber = n;
1326
1327         // remove world message (invalid, and thus a good terminator)
1328         MSG_WriteShort(msg, 0x8000);
1329         // write the number of the end entity
1330         MSG_WriteShort(msg, d->currententitynumber);
1331         // just to be sure
1332         d->currentcommit = NULL;
1333 }
1334
1335
1336
1337
1338 #define E5_PROTOCOL_PRIORITYLEVELS 32
1339
1340 entityframe5_database_t *EntityFrame5_AllocDatabase(mempool_t *pool)
1341 {
1342         entityframe5_database_t *d;
1343         d = Mem_Alloc(pool, sizeof(*d));
1344         EntityFrame5_ResetDatabase(d);
1345         return d;
1346 }
1347
1348 void EntityFrame5_FreeDatabase(entityframe5_database_t *d)
1349 {
1350         Mem_Free(d);
1351 }
1352
1353 void EntityFrame5_ResetDatabase(entityframe5_database_t *d)
1354 {
1355         int i;
1356         memset(d, 0, sizeof(*d));
1357         d->latestframenum = 0;
1358         for (i = 0;i < MAX_EDICTS;i++)
1359                 d->states[i] = defaultstate;
1360 }
1361
1362
1363 int EntityState5_Priority(entityframe5_database_t *d, entity_state_t *view, entity_state_t *s, int changedbits, int age)
1364 {
1365         int lowprecision, limit, priority;
1366         double distance;
1367         if (!changedbits)
1368                 return 0;
1369         if (!s->active/* && changedbits & E5_FULLUPDATE*/)
1370                 return E5_PROTOCOL_PRIORITYLEVELS - 1;
1371         // check whole attachment chain to judge relevance to player
1372         lowprecision = false;
1373         for (limit = 0;limit < 256;limit++)
1374         {
1375                 if (s == view)
1376                         return E5_PROTOCOL_PRIORITYLEVELS - 1;
1377                 if (s->flags & RENDER_VIEWMODEL)
1378                         return E5_PROTOCOL_PRIORITYLEVELS - 1;
1379                 if (s->flags & RENDER_LOWPRECISION)
1380                         lowprecision = true;
1381                 if (!s->tagentity)
1382                 {
1383                         if (VectorCompare(s->origin, view->origin))
1384                                 return E5_PROTOCOL_PRIORITYLEVELS - 1;
1385                         break;
1386                 }
1387                 s = d->states + s->tagentity;
1388         }
1389         if (limit >= 256)
1390                 Con_Printf("Protocol: Runaway loop recursing tagentity links on entity %i\n", s->number);
1391         // it's not a viewmodel for this client
1392         distance = VectorDistance(view->origin, s->origin);
1393         priority = (E5_PROTOCOL_PRIORITYLEVELS / 2) + age - (int)(distance * (E5_PROTOCOL_PRIORITYLEVELS / 16384.0f));
1394         if (lowprecision)
1395                 priority -= (E5_PROTOCOL_PRIORITYLEVELS / 4);
1396         //if (changedbits & E5_FULLUPDATE)
1397         //      priority += 4;
1398         //if (changedbits & (E5_ATTACHMENT | E5_MODEL | E5_FLAGS | E5_COLORMAP))
1399         //      priority += 4;
1400         return (int) bound(1, priority, E5_PROTOCOL_PRIORITYLEVELS - 1);
1401 }
1402
1403 void EntityState5_WriteUpdate(int number, const entity_state_t *s, int changedbits, sizebuf_t *msg)
1404 {
1405         unsigned int bits = 0;
1406         if (!s->active)
1407                 MSG_WriteShort(msg, number | 0x8000);
1408         else
1409         {
1410                 bits = changedbits;
1411                 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))
1412                         bits |= E5_ORIGIN32;
1413                 if ((bits & E5_ANGLES) && !(s->flags & RENDER_LOWPRECISION))
1414                         bits |= E5_ANGLES16;
1415                 if ((bits & E5_MODEL) && s->modelindex >= 256)
1416                         bits |= E5_MODEL16;
1417                 if ((bits & E5_FRAME) && s->frame >= 256)
1418                         bits |= E5_FRAME16;
1419                 if (bits & E5_EFFECTS)
1420                 {
1421                         if (s->effects >= 65536)
1422                                 bits |= E5_EFFECTS32;
1423                         else if (s->effects >= 256)
1424                                 bits |= E5_EFFECTS16;
1425                 }
1426                 if (bits >= 256)
1427                         bits |= E5_EXTEND1;
1428                 if (bits >= 65536)
1429                         bits |= E5_EXTEND2;
1430                 if (bits >= 16777216)
1431                         bits |= E5_EXTEND3;
1432                 MSG_WriteShort(msg, number);
1433                 MSG_WriteByte(msg, bits & 0xFF);
1434                 if (bits & E5_EXTEND1)
1435                         MSG_WriteByte(msg, (bits >> 8) & 0xFF);
1436                 if (bits & E5_EXTEND2)
1437                         MSG_WriteByte(msg, (bits >> 16) & 0xFF);
1438                 if (bits & E5_EXTEND3)
1439                         MSG_WriteByte(msg, (bits >> 24) & 0xFF);
1440                 if (bits & E5_FLAGS)
1441                         MSG_WriteByte(msg, s->flags);
1442                 if (bits & E5_ORIGIN)
1443                 {
1444                         if (bits & E5_ORIGIN32)
1445                         {
1446                                 MSG_WriteCoord32f(msg, s->origin[0]);
1447                                 MSG_WriteCoord32f(msg, s->origin[1]);
1448                                 MSG_WriteCoord32f(msg, s->origin[2]);
1449                         }
1450                         else
1451                         {
1452                                 MSG_WriteCoord13i(msg, s->origin[0]);
1453                                 MSG_WriteCoord13i(msg, s->origin[1]);
1454                                 MSG_WriteCoord13i(msg, s->origin[2]);
1455                         }
1456                 }
1457                 if (bits & E5_ANGLES)
1458                 {
1459                         if (bits & E5_ANGLES16)
1460                         {
1461                                 MSG_WriteAngle16i(msg, s->angles[0]);
1462                                 MSG_WriteAngle16i(msg, s->angles[1]);
1463                                 MSG_WriteAngle16i(msg, s->angles[2]);
1464                         }
1465                         else
1466                         {
1467                                 MSG_WriteAngle8i(msg, s->angles[0]);
1468                                 MSG_WriteAngle8i(msg, s->angles[1]);
1469                                 MSG_WriteAngle8i(msg, s->angles[2]);
1470                         }
1471                 }
1472                 if (bits & E5_MODEL)
1473                 {
1474                         if (bits & E5_MODEL16)
1475                                 MSG_WriteShort(msg, s->modelindex);
1476                         else
1477                                 MSG_WriteByte(msg, s->modelindex);
1478                 }
1479                 if (bits & E5_FRAME)
1480                 {
1481                         if (bits & E5_FRAME16)
1482                                 MSG_WriteShort(msg, s->frame);
1483                         else
1484                                 MSG_WriteByte(msg, s->frame);
1485                 }
1486                 if (bits & E5_SKIN)
1487                         MSG_WriteByte(msg, s->skin);
1488                 if (bits & E5_EFFECTS)
1489                 {
1490                         if (bits & E5_EFFECTS32)
1491                                 MSG_WriteLong(msg, s->effects);
1492                         else if (bits & E5_EFFECTS16)
1493                                 MSG_WriteShort(msg, s->effects);
1494                         else
1495                                 MSG_WriteByte(msg, s->effects);
1496                 }
1497                 if (bits & E5_ALPHA)
1498                         MSG_WriteByte(msg, s->alpha);
1499                 if (bits & E5_SCALE)
1500                         MSG_WriteByte(msg, s->scale);
1501                 if (bits & E5_COLORMAP)
1502                         MSG_WriteByte(msg, s->colormap);
1503                 if (bits & E5_ATTACHMENT)
1504                 {
1505                         MSG_WriteShort(msg, s->tagentity);
1506                         MSG_WriteByte(msg, s->tagindex);
1507                 }
1508                 if (bits & E5_LIGHT)
1509                 {
1510                         MSG_WriteShort(msg, s->light[0]);
1511                         MSG_WriteShort(msg, s->light[1]);
1512                         MSG_WriteShort(msg, s->light[2]);
1513                         MSG_WriteShort(msg, s->light[3]);
1514                         MSG_WriteByte(msg, s->lightstyle);
1515                         MSG_WriteByte(msg, s->lightpflags);
1516                 }
1517                 if (bits & E5_GLOW)
1518                 {
1519                         MSG_WriteByte(msg, s->glowsize);
1520                         MSG_WriteByte(msg, s->glowcolor);
1521                 }
1522         }
1523 }
1524
1525 void EntityState5_ReadUpdate(entity_state_t *s)
1526 {
1527         int bits;
1528         bits = MSG_ReadByte();
1529         if (bits & E5_EXTEND1)
1530         {
1531                 bits |= MSG_ReadByte() << 8;
1532                 if (bits & E5_EXTEND2)
1533                 {
1534                         bits |= MSG_ReadByte() << 16;
1535                         if (bits & E5_EXTEND3)
1536                                 bits |= MSG_ReadByte() << 24;
1537                 }
1538         }
1539         if (bits & E5_FULLUPDATE)
1540         {
1541                 *s = defaultstate;
1542                 s->active = true;
1543         }
1544         if (bits & E5_FLAGS)
1545                 s->flags = MSG_ReadByte();
1546         if (bits & E5_ORIGIN)
1547         {
1548                 if (bits & E5_ORIGIN32)
1549                 {
1550                         s->origin[0] = MSG_ReadCoord32f();
1551                         s->origin[1] = MSG_ReadCoord32f();
1552                         s->origin[2] = MSG_ReadCoord32f();
1553                 }
1554                 else
1555                 {
1556                         s->origin[0] = MSG_ReadCoord13i();
1557                         s->origin[1] = MSG_ReadCoord13i();
1558                         s->origin[2] = MSG_ReadCoord13i();
1559                 }
1560         }
1561         if (bits & E5_ANGLES)
1562         {
1563                 if (bits & E5_ANGLES16)
1564                 {
1565                         s->angles[0] = MSG_ReadAngle16i(); 
1566                         s->angles[1] = MSG_ReadAngle16i(); 
1567                         s->angles[2] = MSG_ReadAngle16i(); 
1568                 }
1569                 else
1570                 {
1571                         s->angles[0] = MSG_ReadAngle8i(); 
1572                         s->angles[1] = MSG_ReadAngle8i(); 
1573                         s->angles[2] = MSG_ReadAngle8i(); 
1574                 }
1575         }
1576         if (bits & E5_MODEL)
1577         {
1578                 if (bits & E5_MODEL16)
1579                         s->modelindex = (unsigned short) MSG_ReadShort();
1580                 else
1581                         s->modelindex = MSG_ReadByte();
1582         }
1583         if (bits & E5_FRAME)
1584         {
1585                 if (bits & E5_FRAME16)
1586                         s->frame = (unsigned short) MSG_ReadShort();
1587                 else
1588                         s->frame = MSG_ReadByte();
1589         }
1590         if (bits & E5_SKIN)
1591                 s->skin = MSG_ReadByte();
1592         if (bits & E5_EFFECTS)
1593         {
1594                 if (bits & E5_EFFECTS32)
1595                         s->effects = (unsigned int) MSG_ReadLong();
1596                 else if (bits & E5_EFFECTS16)
1597                         s->effects = (unsigned short) MSG_ReadShort();
1598                 else
1599                         s->effects = MSG_ReadByte();
1600         }
1601         if (bits & E5_ALPHA)
1602                 s->alpha = MSG_ReadByte();
1603         if (bits & E5_SCALE)
1604                 s->scale = MSG_ReadByte();
1605         if (bits & E5_COLORMAP)
1606                 s->colormap = MSG_ReadByte();
1607         if (bits & E5_ATTACHMENT)
1608         {
1609                 s->tagentity = (unsigned short) MSG_ReadShort();
1610                 s->tagindex = MSG_ReadByte();
1611         }
1612         if (bits & E5_LIGHT)
1613         {
1614                 s->light[0] = (unsigned short) MSG_ReadShort();
1615                 s->light[1] = (unsigned short) MSG_ReadShort();
1616                 s->light[2] = (unsigned short) MSG_ReadShort();
1617                 s->light[3] = (unsigned short) MSG_ReadShort();
1618                 s->lightstyle = MSG_ReadByte();
1619                 s->lightpflags = MSG_ReadByte();
1620         }
1621         if (bits & E5_GLOW)
1622         {
1623                 s->glowsize = MSG_ReadByte();
1624                 s->glowcolor = MSG_ReadByte();
1625         }
1626
1627
1628         if (developer_networkentities.integer >= 2)
1629         {
1630                 Con_Printf("ReadFields e%i", s->number);
1631
1632                 if (bits & E5_ORIGIN)
1633                         Con_Printf(" E5_ORIGIN %f %f %f", s->origin[0], s->origin[1], s->origin[2]);
1634                 if (bits & E5_ANGLES)
1635                         Con_Printf(" E5_ANGLES %f %f %f", s->angles[0], s->angles[1], s->angles[2]);
1636                 if (bits & E5_MODEL)
1637                         Con_Printf(" E5_MODEL %i", s->modelindex);
1638                 if (bits & E5_FRAME)
1639                         Con_Printf(" E5_FRAME %i", s->frame);
1640                 if (bits & E5_SKIN)
1641                         Con_Printf(" E5_SKIN %i", s->skin);
1642                 if (bits & E5_EFFECTS)
1643                         Con_Printf(" E5_EFFECTS %i", s->effects);
1644                 if (bits & E5_FLAGS)
1645                 {
1646                         Con_Printf(" E5_FLAGS %i (", s->flags);
1647                         if (s->flags & RENDER_STEP)
1648                                 Con_Print(" STEP");
1649                         if (s->flags & RENDER_GLOWTRAIL)
1650                                 Con_Print(" GLOWTRAIL");
1651                         if (s->flags & RENDER_VIEWMODEL)
1652                                 Con_Print(" VIEWMODEL");
1653                         if (s->flags & RENDER_EXTERIORMODEL)
1654                                 Con_Print(" EXTERIORMODEL");
1655                         if (s->flags & RENDER_LOWPRECISION)
1656                                 Con_Print(" LOWPRECISION");
1657                         if (s->flags & RENDER_COLORMAPPED)
1658                                 Con_Print(" COLORMAPPED");
1659                         if (s->flags & RENDER_SHADOW)
1660                                 Con_Print(" SHADOW");
1661                         if (s->flags & RENDER_LIGHT)
1662                                 Con_Print(" LIGHT");
1663                         Con_Print(")");
1664                 }
1665                 if (bits & E5_ALPHA)
1666                         Con_Printf(" E5_ALPHA %f", s->alpha / 255.0f);
1667                 if (bits & E5_SCALE)
1668                         Con_Printf(" E5_SCALE %f", s->scale / 16.0f);
1669                 if (bits & E5_COLORMAP)
1670                         Con_Printf(" E5_COLORMAP %i", s->colormap);
1671                 if (bits & E5_ATTACHMENT)
1672                         Con_Printf(" E5_ATTACHMENT e%i:%i", s->tagentity, s->tagindex);
1673                 if (bits & E5_LIGHT)
1674                         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);
1675                 if (bits & E5_GLOW)
1676                         Con_Printf(" E5_GLOW %i:%i", s->glowsize * 4, s->glowcolor);
1677                 Con_Print("\n");
1678         }
1679 }
1680
1681 int EntityState5_DeltaBits(const entity_state_t *o, const entity_state_t *n)
1682 {
1683         unsigned int bits = 0;
1684         if (n->active)
1685         {
1686                 if (!o->active)
1687                         bits |= E5_FULLUPDATE;
1688                 if (!VectorCompare(o->origin, n->origin))
1689                         bits |= E5_ORIGIN;
1690                 if (!VectorCompare(o->angles, n->angles))
1691                         bits |= E5_ANGLES;
1692                 if (o->modelindex != n->modelindex)
1693                         bits |= E5_MODEL;
1694                 if (o->frame != n->frame)
1695                         bits |= E5_FRAME;
1696                 if (o->skin != n->skin)
1697                         bits |= E5_SKIN;
1698                 if (o->effects != n->effects)
1699                         bits |= E5_EFFECTS;
1700                 if (o->flags != n->flags)
1701                         bits |= E5_FLAGS;
1702                 if (o->alpha != n->alpha)
1703                         bits |= E5_ALPHA;
1704                 if (o->scale != n->scale)
1705                         bits |= E5_SCALE;
1706                 if (o->colormap != n->colormap)
1707                         bits |= E5_COLORMAP;
1708                 if (o->tagentity != n->tagentity || o->tagindex != n->tagindex)
1709                         bits |= E5_ATTACHMENT;
1710                 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)
1711                         bits |= E5_LIGHT;
1712                 if (o->glowsize != n->glowsize || o->glowcolor != n->glowcolor)
1713                         bits |= E5_GLOW;
1714         }
1715         else
1716                 if (o->active)
1717                         bits |= E5_FULLUPDATE;
1718         return bits;
1719 }
1720
1721 void EntityFrame5_CL_ReadFrame(void)
1722 {
1723         int n, enumber;
1724         entity_t *ent;
1725         entity_state_t *s;
1726         // read the number of this frame to echo back in next input packet
1727         cl.latestframenum = MSG_ReadLong();
1728         // read entity numbers until we find a 0x8000
1729         // (which would be remove world entity, but is actually a terminator)
1730         while ((n = (unsigned short)MSG_ReadShort()) != 0x8000 && !msg_badread)
1731         {
1732                 // get the entity number and look it up
1733                 enumber = n & 0x7FFF;
1734                 ent = cl_entities + enumber;
1735                 // slide the current into the previous slot
1736                 ent->state_previous = ent->state_current;
1737                 // read the update
1738                 s = &ent->state_current;
1739                 if (n & 0x8000)
1740                 {
1741                         // remove entity
1742                         *s = defaultstate;
1743                 }
1744                 else
1745                 {
1746                         // update entity
1747                         EntityState5_ReadUpdate(s);
1748                 }
1749                 // set the cl_entities_active flag
1750                 cl_entities_active[enumber] = s->active;
1751                 // set the update time
1752                 s->time = cl.mtime[0];
1753                 // fix the number (it gets wiped occasionally by copying from defaultstate)
1754                 s->number = enumber;
1755                 // check if we need to update the lerp stuff
1756                 if (s->active)
1757                         CL_MoveLerpEntityStates(&cl_entities[enumber]);
1758                 // print extra messages if desired
1759                 if (developer_networkentities.integer >= 2 && cl_entities[enumber].state_current.active != cl_entities[enumber].state_previous.active)
1760                 {
1761                         if (cl_entities[enumber].state_current.active)
1762                                 Con_Printf("entity #%i has become active\n", enumber);
1763                         else if (cl_entities[enumber].state_previous.active)
1764                                 Con_Printf("entity #%i has become inactive\n", enumber);
1765                 }
1766         }
1767 }
1768
1769 void EntityFrame5_AckFrame(entityframe5_database_t *d, int framenum, int viewentnum)
1770 {
1771         int i, j, k, l, bits;
1772         entityframe5_changestate_t *s, *s2;
1773         entityframe5_packetlog_t *p, *p2;
1774         // scan for packets made obsolete by this ack
1775         for (i = 0, p = d->packetlog;i < ENTITYFRAME5_MAXPACKETLOGS;i++, p++)
1776         {
1777                 // skip packets that are empty or in the future
1778                 if (p->packetnumber == 0 || p->packetnumber > framenum)
1779                         continue;
1780                 // if the packetnumber matches it is deleted without any processing 
1781                 // (since it was received).
1782                 // if the packet number is less than this ack it was lost and its
1783                 // important information will be repeated in this update if it is not
1784                 // already obsolete due to a later update.
1785                 if (p->packetnumber < framenum)
1786                 {
1787                         // packet was lost - merge deltabits into the main array so they
1788                         // will be re-sent, but only if there is no newer update of that
1789                         // bit in the logs (as those will arrive before this update)
1790                         for (j = 0, s = p->states;j < p->numstates;j++, s++)
1791                         {
1792                                 // check for any newer updates to this entity and mask off any
1793                                 // overlapping bits (we don't need to send something again if
1794                                 // it has already been sent more recently)
1795                                 bits = s->bits & ~d->deltabits[s->number];
1796                                 for (k = 0, p2 = d->packetlog;k < ENTITYFRAME5_MAXPACKETLOGS && bits;k++, p2++)
1797                                 {
1798                                         if (p2->packetnumber > framenum)
1799                                         {
1800                                                 for (l = 0, s2 = p2->states;l < p2->numstates;l++, p2++)
1801                                                 {
1802                                                         if (s2->number == s->number)
1803                                                         {
1804                                                                 bits &= ~s2->bits;
1805                                                                 break;
1806                                                         }
1807                                                 }
1808                                         }
1809                                 }
1810                                 // if the bits haven't all been cleared, there were some bits
1811                                 // lost with this packet, so set them again now
1812                                 if (bits)
1813                                 {
1814                                         d->deltabits[s->number] |= bits;
1815                                         d->priorities[s->number] = EntityState5_Priority(d, d->states + viewentnum, d->states + s->number, d->deltabits[s->number], d->latestframenum - d->updateframenum[s->number]);
1816                                 }
1817                         }
1818                 }
1819                 // delete this packet log as it is now obsolete
1820                 p->packetnumber = 0;
1821         }
1822 }
1823
1824 int entityframe5_prioritychaincounts[E5_PROTOCOL_PRIORITYLEVELS];
1825 unsigned short entityframe5_prioritychains[E5_PROTOCOL_PRIORITYLEVELS][ENTITYFRAME5_MAXSTATES];
1826
1827 void EntityFrame5_WriteFrame(sizebuf_t *msg, entityframe5_database_t *d, int numstates, const entity_state_t *states, int viewentnum)
1828 {
1829         const entity_state_t *n;
1830         int i, num, l, framenum, packetlognumber, priority;
1831         sizebuf_t buf;
1832         qbyte data[128];
1833         entityframe5_packetlog_t *packetlog;
1834
1835         framenum = d->latestframenum + 1;
1836
1837         // prepare the buffer
1838         memset(&buf, 0, sizeof(buf));
1839         buf.data = data;
1840         buf.maxsize = sizeof(data);
1841
1842         // detect changes in states
1843         num = 0;
1844         for (i = 0, n = states;i < numstates;i++, n++)
1845         {
1846                 // mark gaps in entity numbering as removed entities
1847                 for (;num < n->number;num++)
1848                 {
1849                         // if the entity used to exist, clear it
1850                         if (CHECKPVSBIT(d->visiblebits, num))
1851                         {
1852                                 CLEARPVSBIT(d->visiblebits, num);
1853                                 d->deltabits[num] = E5_FULLUPDATE;
1854                                 d->priorities[num] = EntityState5_Priority(d, d->states + viewentnum, d->states + num, d->deltabits[num], framenum - d->updateframenum[num]);
1855                                 d->states[num] = defaultstate;
1856                                 d->states[num].number = num;
1857                         }
1858                 }
1859                 // update the entity state data
1860                 if (!CHECKPVSBIT(d->visiblebits, num))
1861                 {
1862                         // entity just spawned in, don't let it completely hog priority
1863                         // because of being ancient on the first frame
1864                         d->updateframenum[num] = framenum;
1865                 }
1866                 SETPVSBIT(d->visiblebits, num);
1867                 d->deltabits[num] |= EntityState5_DeltaBits(d->states + num, n);
1868                 d->priorities[num] = EntityState5_Priority(d, d->states + viewentnum, d->states + num, d->deltabits[num], framenum - d->updateframenum[num]);
1869                 d->states[num] = *n;
1870                 d->states[num].number = num;
1871                 // advance to next entity so the next iteration doesn't immediately remove it
1872                 num++;
1873         }
1874         // all remaining entities are dead
1875         for (;num < MAX_EDICTS;num++)
1876         {
1877                 if (CHECKPVSBIT(d->visiblebits, num))
1878                 {
1879                         CLEARPVSBIT(d->visiblebits, num);
1880                         d->deltabits[num] = E5_FULLUPDATE;
1881                         d->priorities[num] = EntityState5_Priority(d, d->states + viewentnum, d->states + num, d->deltabits[num], framenum - d->updateframenum[num]);
1882                         d->states[num] = defaultstate;
1883                         d->states[num].number = num;
1884                 }
1885         }
1886
1887         // build lists of entities by priority level
1888         memset(entityframe5_prioritychaincounts, 0, sizeof(entityframe5_prioritychaincounts));
1889         l = 0;
1890         for (num = 0;num < MAX_EDICTS;num++)
1891         {
1892                 if (d->priorities[num])
1893                 {
1894                         l = num;
1895                         priority = d->priorities[num];
1896                         if (entityframe5_prioritychaincounts[priority] < ENTITYFRAME5_MAXSTATES)
1897                                 entityframe5_prioritychains[priority][entityframe5_prioritychaincounts[priority]++] = num;
1898                 }
1899         }
1900
1901         // return early if there are no entities to send this time
1902         if (l == 0)
1903                 return;
1904
1905         d->latestframenum = framenum;
1906         MSG_WriteByte(msg, svc_entities);
1907         MSG_WriteLong(msg, framenum);
1908
1909         // if packet log is full, an empty update is still written
1910         // (otherwise the client might have nothing to ack to remove packetlogs)
1911         for (packetlognumber = 0, packetlog = d->packetlog;packetlognumber < ENTITYFRAME5_MAXPACKETLOGS;packetlognumber++, packetlog++)
1912                 if (packetlog->packetnumber == 0)
1913                         break;
1914         if (packetlognumber < ENTITYFRAME5_MAXPACKETLOGS)
1915         {
1916                 // write to packet and log
1917                 packetlog->packetnumber = framenum;
1918                 packetlog->numstates = 0;
1919                 for (priority = E5_PROTOCOL_PRIORITYLEVELS - 1;priority >= 0 && packetlog->numstates < ENTITYFRAME5_MAXSTATES;priority--)
1920                 {
1921                         for (i = 0;i < entityframe5_prioritychaincounts[priority] && packetlog->numstates < ENTITYFRAME5_MAXSTATES;i++)
1922                         {
1923                                 num = entityframe5_prioritychains[priority][i];
1924                                 n = d->states + num;
1925                                 if (d->deltabits[num] & E5_FULLUPDATE)
1926                                         d->deltabits[num] = E5_FULLUPDATE | EntityState5_DeltaBits(&defaultstate, n);
1927                                 buf.cursize = 0;
1928                                 EntityState5_WriteUpdate(num, n, d->deltabits[num], &buf);
1929                                 // if the entity won't fit, try the next one
1930                                 if (msg->cursize + buf.cursize + 2 > msg->maxsize)
1931                                         continue;
1932                                 // write entity to the packet
1933                                 SZ_Write(msg, buf.data, buf.cursize);
1934                                 // mark age on entity for prioritization
1935                                 d->updateframenum[num] = framenum;
1936                                 // log entity so deltabits can be restored later if lost
1937                                 packetlog->states[packetlog->numstates].number = num;
1938                                 packetlog->states[packetlog->numstates].bits = d->deltabits[num];
1939                                 packetlog->numstates++;
1940                                 // clear deltabits and priority so it won't be sent again
1941                                 d->deltabits[num] = 0;
1942                                 d->priorities[num] = 0;
1943                         }
1944                 }
1945         }
1946
1947         MSG_WriteShort(msg, 0x8000);
1948 }
1949