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