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