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