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