renamed varray_ arrays to rsurface_array_, and they are no longer used outside the...
[divverent/darkplaces.git] / protocol.c
1
2 #include "quakedef.h"
3
4 #define E5_PROTOCOL_PRIORITYLEVELS 32
5
6 // this is 88 bytes (must match entity_state_t in protocol.h)
7 entity_state_t defaultstate =
8 {
9         // ! means this is not sent to client
10         0,//double time; // ! time this state was built (used on client for interpolation)
11         {0,0,0},//float origin[3];
12         {0,0,0},//float angles[3];
13         0,//int number; // entity number this state is for
14         0,//int effects;
15         0,//unsigned int customizeentityforclient; // !
16         0,//unsigned short modelindex;
17         0,//unsigned short frame;
18         0,//unsigned short tagentity;
19         0,//unsigned short specialvisibilityradius; // ! larger if it has effects/light
20         0,//unsigned short viewmodelforclient; // !
21         0,//unsigned short exteriormodelforclient; // ! not shown if first person viewing from this entity, shown in all other cases
22         0,//unsigned short nodrawtoclient; // !
23         0,//unsigned short drawonlytoclient; // !
24         {0,0,0,0},//unsigned short light[4]; // color*256 (0.00 to 255.996), and radius*1
25         0,//unsigned char active; // true if a valid state
26         0,//unsigned char lightstyle;
27         0,//unsigned char lightpflags;
28         0,//unsigned char colormap;
29         0,//unsigned char skin; // also chooses cubemap for rtlights if lightpflags & LIGHTPFLAGS_FULLDYNAMIC
30         255,//unsigned char alpha;
31         16,//unsigned char scale;
32         0,//unsigned char glowsize;
33         254,//unsigned char glowcolor;
34         0,//unsigned char flags;
35         0,//unsigned char tagindex;
36         {32, 32, 32},//unsigned char colormod[3];
37         // padding to a multiple of 8 bytes (to align the double time)
38         {0,0,0,0,0,0}//unsigned char unused[6]; // !
39 };
40
41 // LordHavoc: I own protocol ranges 96, 97, 3500-3599
42
43 struct protocolversioninfo_s
44 {
45         int number;
46         const char *name;
47 }
48 protocolversioninfo[] =
49 {
50         {0, "UNKNOWN"},
51         {3504, "DP7"},
52         {3503, "DP6"},
53         {3502, "DP5"},
54         {3501, "DP4"},
55         {3500, "DP3"},
56         {97, "DP2"},
57         {96, "DP1"},
58         {15, "QUAKEDP"},
59         {250, "NEHAHRAMOVIE"},
60         {15, "QUAKE"},
61         {28, "QUAKEWORLD"},
62         {0, NULL}
63 };
64
65 static mempool_t *sv2csqc = NULL;
66 int csqc_clent = 0;
67 sizebuf_t *sv2csqcbuf = NULL;
68 static unsigned char *sv2csqcents_version[MAX_SCOREBOARD];
69
70 static entity_frame_t deltaframe; // FIXME?
71 static entity_frame_t framedata; // FIXME?
72
73 int entityframe5_prioritychaincounts[E5_PROTOCOL_PRIORITYLEVELS];
74 unsigned short entityframe5_prioritychains[E5_PROTOCOL_PRIORITYLEVELS][ENTITYFRAME5_MAXSTATES];
75
76 protocolversion_t Protocol_EnumForName(const char *s)
77 {
78         int i;
79         for (i = 1;protocolversioninfo[i].name;i++)
80                 if (!strcasecmp(s, protocolversioninfo[i].name))
81                         return (protocolversion_t)i;
82         return PROTOCOL_UNKNOWN;
83 }
84
85 const char *Protocol_NameForEnum(protocolversion_t p)
86 {
87         return protocolversioninfo[p].name;
88 }
89
90 protocolversion_t Protocol_EnumForNumber(int n)
91 {
92         int i;
93         for (i = 1;protocolversioninfo[i].name;i++)
94                 if (protocolversioninfo[i].number == n)
95                         return (protocolversion_t)i;
96         return PROTOCOL_UNKNOWN;
97 }
98
99 int Protocol_NumberForEnum(protocolversion_t p)
100 {
101         return protocolversioninfo[p].number;
102 }
103
104 void Protocol_Names(char *buffer, size_t buffersize)
105 {
106         int i;
107         if (buffersize < 1)
108                 return;
109         buffer[0] = 0;
110         for (i = 1;protocolversioninfo[i].name;i++)
111         {
112                 if (i > 1)
113                         strlcat(buffer, " ", sizeof(buffer));
114                 strlcat(buffer, protocolversioninfo[i].name, sizeof(buffer));
115         }
116 }
117
118 void EntityFrameQuake_ReadEntity(int bits)
119 {
120         int num;
121         entity_t *ent;
122         entity_state_t s;
123
124         if (bits & U_MOREBITS)
125                 bits |= (MSG_ReadByte()<<8);
126         if ((bits & U_EXTEND1) && cls.protocol != PROTOCOL_NEHAHRAMOVIE)
127         {
128                 bits |= MSG_ReadByte() << 16;
129                 if (bits & U_EXTEND2)
130                         bits |= MSG_ReadByte() << 24;
131         }
132
133         if (bits & U_LONGENTITY)
134                 num = (unsigned short) MSG_ReadShort ();
135         else
136                 num = MSG_ReadByte ();
137
138         if (num >= MAX_EDICTS)
139                 Host_Error("EntityFrameQuake_ReadEntity: entity number (%i) >= MAX_EDICTS (%i)", num, MAX_EDICTS);
140         if (num < 1)
141                 Host_Error("EntityFrameQuake_ReadEntity: invalid entity number (%i)", num);
142
143         if (cl.num_entities <= num)
144         {
145                 cl.num_entities = num + 1;
146                 if (num >= cl.max_entities)
147                         CL_ExpandEntities(num);
148         }
149
150         ent = cl.entities + num;
151
152         // note: this inherits the 'active' state of the baseline chosen
153         // (state_baseline is always active, state_current may not be active if
154         // the entity was missing in the last frame)
155         if (bits & U_DELTA)
156                 s = ent->state_current;
157         else
158         {
159                 s = ent->state_baseline;
160                 s.active = true;
161         }
162
163         cl.isquakeentity[num] = true;
164         if (cl.lastquakeentity < num)
165                 cl.lastquakeentity = num;
166         s.number = num;
167         s.time = cl.mtime[0];
168         s.flags = 0;
169         if (bits & U_MODEL)             s.modelindex = (s.modelindex & 0xFF00) | MSG_ReadByte();
170         if (bits & U_FRAME)             s.frame = (s.frame & 0xFF00) | MSG_ReadByte();
171         if (bits & U_COLORMAP)  s.colormap = MSG_ReadByte();
172         if (bits & U_SKIN)              s.skin = MSG_ReadByte();
173         if (bits & U_EFFECTS)   s.effects = (s.effects & 0xFF00) | MSG_ReadByte();
174         if (bits & U_ORIGIN1)   s.origin[0] = MSG_ReadCoord(cls.protocol);
175         if (bits & U_ANGLE1)    s.angles[0] = MSG_ReadAngle(cls.protocol);
176         if (bits & U_ORIGIN2)   s.origin[1] = MSG_ReadCoord(cls.protocol);
177         if (bits & U_ANGLE2)    s.angles[1] = MSG_ReadAngle(cls.protocol);
178         if (bits & U_ORIGIN3)   s.origin[2] = MSG_ReadCoord(cls.protocol);
179         if (bits & U_ANGLE3)    s.angles[2] = MSG_ReadAngle(cls.protocol);
180         if (bits & U_STEP)              s.flags |= RENDER_STEP;
181         if (bits & U_ALPHA)             s.alpha = MSG_ReadByte();
182         if (bits & U_SCALE)             s.scale = MSG_ReadByte();
183         if (bits & U_EFFECTS2)  s.effects = (s.effects & 0x00FF) | (MSG_ReadByte() << 8);
184         if (bits & U_GLOWSIZE)  s.glowsize = MSG_ReadByte();
185         if (bits & U_GLOWCOLOR) s.glowcolor = MSG_ReadByte();
186         if (bits & U_COLORMOD)  {int c = MSG_ReadByte();s.colormod[0] = (unsigned char)(((c >> 5) & 7) * (32.0f / 7.0f));s.colormod[1] = (unsigned char)(((c >> 2) & 7) * (32.0f / 7.0f));s.colormod[2] = (unsigned char)((c & 3) * (32.0f / 3.0f));}
187         if (bits & U_GLOWTRAIL) s.flags |= RENDER_GLOWTRAIL;
188         if (bits & U_FRAME2)    s.frame = (s.frame & 0x00FF) | (MSG_ReadByte() << 8);
189         if (bits & U_MODEL2)    s.modelindex = (s.modelindex & 0x00FF) | (MSG_ReadByte() << 8);
190         if (bits & U_VIEWMODEL) s.flags |= RENDER_VIEWMODEL;
191         if (bits & U_EXTERIORMODEL)     s.flags |= RENDER_EXTERIORMODEL;
192
193         // LordHavoc: to allow playback of the Nehahra movie
194         if (cls.protocol == PROTOCOL_NEHAHRAMOVIE && (bits & U_EXTEND1))
195         {
196                 // LordHavoc: evil format
197                 int i = MSG_ReadFloat();
198                 int j = MSG_ReadFloat() * 255.0f;
199                 if (i == 2)
200                 {
201                         i = MSG_ReadFloat();
202                         if (i)
203                                 s.effects |= EF_FULLBRIGHT;
204                 }
205                 if (j < 0)
206                         s.alpha = 0;
207                 else if (j == 0 || j >= 255)
208                         s.alpha = 255;
209                 else
210                         s.alpha = j;
211         }
212
213         ent->state_previous = ent->state_current;
214         ent->state_current = s;
215         if (ent->state_current.active)
216         {
217                 CL_MoveLerpEntityStates(ent);
218                 cl.entities_active[ent->state_current.number] = true;
219         }
220
221         if (msg_badread)
222                 Host_Error("EntityFrameQuake_ReadEntity: read error");
223 }
224
225 void EntityFrameQuake_ISeeDeadEntities(void)
226 {
227         int num, lastentity;
228         if (cl.lastquakeentity == 0)
229                 return;
230         lastentity = cl.lastquakeentity;
231         cl.lastquakeentity = 0;
232         for (num = 0;num <= lastentity;num++)
233         {
234                 if (cl.isquakeentity[num])
235                 {
236                         if (cl.entities_active[num] && cl.entities[num].state_current.time == cl.mtime[0])
237                         {
238                                 cl.isquakeentity[num] = true;
239                                 cl.lastquakeentity = num;
240                         }
241                         else
242                         {
243                                 cl.isquakeentity[num] = false;
244                                 cl.entities_active[num] = false;
245                                 cl.entities[num].state_current = defaultstate;
246                                 cl.entities[num].state_current.number = num;
247                         }
248                 }
249         }
250 }
251
252 void EntityFrameCSQC_ClearVersions (void)
253 {
254         if(sv2csqc)
255         {
256                 Mem_FreePool(&sv2csqc);
257                 sv2csqc = NULL;
258         }
259         memset(sv2csqcents_version, 0, MAX_SCOREBOARD*sizeof(unsigned char *));
260 }
261
262 void EntityFrameCSQC_InitClientVersions (int client, qboolean clear)
263 {
264         if(!sv2csqc)
265                 sv2csqc = Mem_AllocPool("SV2CSQC", 0, NULL);
266         if(sv2csqcents_version[client])
267         {
268                 Mem_Free(sv2csqcents_version[client]);
269                 sv2csqcents_version[client] = NULL;
270         }
271         sv2csqcents_version[client] = Mem_Alloc(sv2csqc, MAX_EDICTS);
272         memset(sv2csqcents_version[client], 0, MAX_EDICTS);
273 }
274
275 //[515]: we use only one array per-client for SendEntity feature
276 void EntityFrameCSQC_WriteFrame (sizebuf_t *msg, int numstates, const entity_state_t *states)
277 {
278         sizebuf_t                               buf;
279         unsigned char                                   data[2048];
280         const entity_state_t    *s;
281         unsigned short                  i, t, t2, t0;
282         prvm_eval_t                             *val, *val2;
283         int                                             csqcents = 0;
284
285         if(!eval_SendEntity || !eval_Version)
286                 return;
287         --csqc_clent;
288         if(!sv2csqcents_version[csqc_clent])
289                 EntityFrameCSQC_InitClientVersions(csqc_clent, false);
290
291         for (csqcents = i = 0, s = states;i < numstates;i++, s++)
292         {
293                 //[515]: entities remove
294                 if(i+1 >= numstates)
295                         t2 = prog->num_edicts;
296                 else
297                         t2 = states[i+1].number;
298                 if(!i)
299                 {
300                         t0 = 1;
301                         t2 = s->number;
302                 }
303                 else
304                         t0 = s->number+1;
305                 for(t=t0; t<t2 ;t++)
306                         if(sv2csqcents_version[csqc_clent][t])
307                         {
308                                 if(!csqcents)
309                                 {
310                                         csqcents = 1;
311                                         memset(&buf, 0, sizeof(buf));
312                                         buf.data = data;
313                                         buf.maxsize = sizeof(data);
314                                         sv2csqcbuf = &buf;
315                                         SZ_Clear(&buf);
316                                         MSG_WriteByte(&buf, svc_csqcentities);
317                                 }
318                                 sv2csqcents_version[csqc_clent][t] = 0;
319                                 MSG_WriteShort(&buf, (unsigned short)t | 0x8000);
320                                 csqcents++;
321                         }
322                 //[515]: entities remove
323
324 //              if(!s->active)
325 //                      continue;
326                 val = PRVM_GETEDICTFIELDVALUE((&prog->edicts[s->number]), eval_SendEntity);
327                 if(val->function)
328                 {
329                         val2 = PRVM_GETEDICTFIELDVALUE((&prog->edicts[s->number]), eval_Version);
330                         if(sv2csqcents_version[csqc_clent][s->number] == (unsigned char)val2->_float)
331                                 continue;
332                         if(!csqcents)
333                         {
334                                 csqcents = 1;
335                                 memset(&buf, 0, sizeof(buf));
336                                 buf.data = data;
337                                 buf.maxsize = sizeof(data);
338                                 sv2csqcbuf = &buf;
339                                 SZ_Clear(&buf);
340                                 MSG_WriteByte(&buf, svc_csqcentities);
341                         }
342                         if((unsigned char)val2->_float == 0)
343                                 val2->_float = 1;
344                         MSG_WriteShort(&buf, s->number);
345                         ((int *)prog->globals.generic)[OFS_PARM0] = csqc_clent+1;
346                         prog->globals.server->self = s->number;
347                         PRVM_ExecuteProgram(val->function, "Null SendEntity\n");
348                         if(!prog->globals.generic[OFS_RETURN])
349                         {
350                                 buf.cursize -= 2;
351                                 if(sv2csqcents_version[csqc_clent][s->number])
352                                 {
353                                         sv2csqcents_version[csqc_clent][s->number] = 0;
354                                         MSG_WriteShort(&buf, (unsigned short)s->number | 0x8000);
355                                         csqcents++;
356                                 }
357                         }
358                         else
359                         {
360                                 sv2csqcents_version[csqc_clent][s->number] = (unsigned char)val2->_float;
361                                 csqcents++;
362                         }
363                         if (msg->cursize + buf.cursize > msg->maxsize)
364                                 break;
365                 }
366         }
367         if(csqcents)
368         {
369                 if(csqcents > 1)
370                 {
371                         MSG_WriteShort(&buf, 0);
372                         SZ_Write(msg, buf.data, buf.cursize);
373                 }
374                 sv2csqcbuf = NULL;
375         }
376 }
377
378 void EntityFrameQuake_WriteFrame(sizebuf_t *msg, int numstates, const entity_state_t *states)
379 {
380         const entity_state_t *s;
381         entity_state_t baseline;
382         int i, bits;
383         sizebuf_t buf;
384         unsigned char data[128];
385         prvm_eval_t *val;
386
387         // prepare the buffer
388         memset(&buf, 0, sizeof(buf));
389         buf.data = data;
390         buf.maxsize = sizeof(data);
391
392         for (i = 0, s = states;i < numstates;i++, s++)
393         {
394                 val = PRVM_GETEDICTFIELDVALUE((&prog->edicts[s->number]), eval_SendEntity);
395                 if(val && val->function)
396                         continue;
397
398                 // prepare the buffer
399                 SZ_Clear(&buf);
400
401 // send an update
402                 bits = 0;
403                 if (s->number >= 256)
404                         bits |= U_LONGENTITY;
405                 if (s->flags & RENDER_STEP)
406                         bits |= U_STEP;
407                 if (s->flags & RENDER_VIEWMODEL)
408                         bits |= U_VIEWMODEL;
409                 if (s->flags & RENDER_GLOWTRAIL)
410                         bits |= U_GLOWTRAIL;
411                 if (s->flags & RENDER_EXTERIORMODEL)
412                         bits |= U_EXTERIORMODEL;
413
414                 // LordHavoc: old stuff, but rewritten to have more exact tolerances
415                 baseline = prog->edicts[s->number].priv.server->baseline;
416                 if (baseline.origin[0] != s->origin[0])
417                         bits |= U_ORIGIN1;
418                 if (baseline.origin[1] != s->origin[1])
419                         bits |= U_ORIGIN2;
420                 if (baseline.origin[2] != s->origin[2])
421                         bits |= U_ORIGIN3;
422                 if (baseline.angles[0] != s->angles[0])
423                         bits |= U_ANGLE1;
424                 if (baseline.angles[1] != s->angles[1])
425                         bits |= U_ANGLE2;
426                 if (baseline.angles[2] != s->angles[2])
427                         bits |= U_ANGLE3;
428                 if (baseline.colormap != s->colormap)
429                         bits |= U_COLORMAP;
430                 if (baseline.skin != s->skin)
431                         bits |= U_SKIN;
432                 if (baseline.frame != s->frame)
433                 {
434                         bits |= U_FRAME;
435                         if (s->frame & 0xFF00)
436                                 bits |= U_FRAME2;
437                 }
438                 if (baseline.effects != s->effects)
439                 {
440                         bits |= U_EFFECTS;
441                         if (s->effects & 0xFF00)
442                                 bits |= U_EFFECTS2;
443                 }
444                 if (baseline.modelindex != s->modelindex)
445                 {
446                         bits |= U_MODEL;
447                         if (s->modelindex & 0xFF00)
448                                 bits |= U_MODEL2;
449                 }
450                 if (baseline.alpha != s->alpha)
451                         bits |= U_ALPHA;
452                 if (baseline.scale != s->scale)
453                         bits |= U_SCALE;
454                 if (baseline.glowsize != s->glowsize)
455                         bits |= U_GLOWSIZE;
456                 if (baseline.glowcolor != s->glowcolor)
457                         bits |= U_GLOWCOLOR;
458
459                 // if extensions are disabled, clear the relevant update flags
460                 if (sv.protocol == PROTOCOL_QUAKE || sv.protocol == PROTOCOL_NEHAHRAMOVIE)
461                         bits &= 0x7FFF;
462                 if (sv.protocol == PROTOCOL_NEHAHRAMOVIE)
463                         if (s->alpha != 255 || s->effects & EF_FULLBRIGHT)
464                                 bits |= U_EXTEND1;
465
466                 // write the message
467                 if (bits >= 16777216)
468                         bits |= U_EXTEND2;
469                 if (bits >= 65536)
470                         bits |= U_EXTEND1;
471                 if (bits >= 256)
472                         bits |= U_MOREBITS;
473                 bits |= U_SIGNAL;
474
475                 MSG_WriteByte (&buf, bits);
476                 if (bits & U_MOREBITS)          MSG_WriteByte(&buf, bits>>8);
477                 if (bits & U_EXTEND1)           MSG_WriteByte(&buf, bits>>16);
478                 if (bits & U_EXTEND2)           MSG_WriteByte(&buf, bits>>24);
479                 if (bits & U_LONGENTITY)        MSG_WriteShort(&buf, s->number);
480                 else                                            MSG_WriteByte(&buf, s->number);
481
482                 if (bits & U_MODEL)                     MSG_WriteByte(&buf, s->modelindex);
483                 if (bits & U_FRAME)                     MSG_WriteByte(&buf, s->frame);
484                 if (bits & U_COLORMAP)          MSG_WriteByte(&buf, s->colormap);
485                 if (bits & U_SKIN)                      MSG_WriteByte(&buf, s->skin);
486                 if (bits & U_EFFECTS)           MSG_WriteByte(&buf, s->effects);
487                 if (bits & U_ORIGIN1)           MSG_WriteCoord(&buf, s->origin[0], sv.protocol);
488                 if (bits & U_ANGLE1)            MSG_WriteAngle(&buf, s->angles[0], sv.protocol);
489                 if (bits & U_ORIGIN2)           MSG_WriteCoord(&buf, s->origin[1], sv.protocol);
490                 if (bits & U_ANGLE2)            MSG_WriteAngle(&buf, s->angles[1], sv.protocol);
491                 if (bits & U_ORIGIN3)           MSG_WriteCoord(&buf, s->origin[2], sv.protocol);
492                 if (bits & U_ANGLE3)            MSG_WriteAngle(&buf, s->angles[2], sv.protocol);
493                 if (bits & U_ALPHA)                     MSG_WriteByte(&buf, s->alpha);
494                 if (bits & U_SCALE)                     MSG_WriteByte(&buf, s->scale);
495                 if (bits & U_EFFECTS2)          MSG_WriteByte(&buf, s->effects >> 8);
496                 if (bits & U_GLOWSIZE)          MSG_WriteByte(&buf, s->glowsize);
497                 if (bits & U_GLOWCOLOR)         MSG_WriteByte(&buf, s->glowcolor);
498                 if (bits & U_COLORMOD)          {int c = ((int)bound(0, s->colormod[0] * (7.0f / 32.0f), 7) << 5) | ((int)bound(0, s->colormod[1] * (7.0f / 32.0f), 7) << 2) | ((int)bound(0, s->colormod[2] * (3.0f / 32.0f), 3) << 0);MSG_WriteByte(&buf, c);}
499                 if (bits & U_FRAME2)            MSG_WriteByte(&buf, s->frame >> 8);
500                 if (bits & U_MODEL2)            MSG_WriteByte(&buf, s->modelindex >> 8);
501
502                 // the nasty protocol
503                 if ((bits & U_EXTEND1) && sv.protocol == PROTOCOL_NEHAHRAMOVIE)
504                 {
505                         if (s->effects & EF_FULLBRIGHT)
506                         {
507                                 MSG_WriteFloat(&buf, 2); // QSG protocol version
508                                 MSG_WriteFloat(&buf, s->alpha <= 0 ? 0 : (s->alpha >= 255 ? 1 : s->alpha * (1.0f / 255.0f))); // alpha
509                                 MSG_WriteFloat(&buf, 1); // fullbright
510                         }
511                         else
512                         {
513                                 MSG_WriteFloat(&buf, 1); // QSG protocol version
514                                 MSG_WriteFloat(&buf, s->alpha <= 0 ? 0 : (s->alpha >= 255 ? 1 : s->alpha * (1.0f / 255.0f))); // alpha
515                         }
516                 }
517
518                 // if the commit is full, we're done this frame
519                 if (msg->cursize + buf.cursize > msg->maxsize)
520                 {
521                         // next frame we will continue where we left off
522                         break;
523                 }
524                 // write the message to the packet
525                 SZ_Write(msg, buf.data, buf.cursize);
526         }
527 }
528
529 int EntityState_DeltaBits(const entity_state_t *o, const entity_state_t *n)
530 {
531         unsigned int bits;
532         // if o is not active, delta from default
533         if (!o->active)
534                 o = &defaultstate;
535         bits = 0;
536         if (fabs(n->origin[0] - o->origin[0]) > (1.0f / 256.0f))
537                 bits |= E_ORIGIN1;
538         if (fabs(n->origin[1] - o->origin[1]) > (1.0f / 256.0f))
539                 bits |= E_ORIGIN2;
540         if (fabs(n->origin[2] - o->origin[2]) > (1.0f / 256.0f))
541                 bits |= E_ORIGIN3;
542         if ((unsigned char) (n->angles[0] * (256.0f / 360.0f)) != (unsigned char) (o->angles[0] * (256.0f / 360.0f)))
543                 bits |= E_ANGLE1;
544         if ((unsigned char) (n->angles[1] * (256.0f / 360.0f)) != (unsigned char) (o->angles[1] * (256.0f / 360.0f)))
545                 bits |= E_ANGLE2;
546         if ((unsigned char) (n->angles[2] * (256.0f / 360.0f)) != (unsigned char) (o->angles[2] * (256.0f / 360.0f)))
547                 bits |= E_ANGLE3;
548         if ((n->modelindex ^ o->modelindex) & 0x00FF)
549                 bits |= E_MODEL1;
550         if ((n->modelindex ^ o->modelindex) & 0xFF00)
551                 bits |= E_MODEL2;
552         if ((n->frame ^ o->frame) & 0x00FF)
553                 bits |= E_FRAME1;
554         if ((n->frame ^ o->frame) & 0xFF00)
555                 bits |= E_FRAME2;
556         if ((n->effects ^ o->effects) & 0x00FF)
557                 bits |= E_EFFECTS1;
558         if ((n->effects ^ o->effects) & 0xFF00)
559                 bits |= E_EFFECTS2;
560         if (n->colormap != o->colormap)
561                 bits |= E_COLORMAP;
562         if (n->skin != o->skin)
563                 bits |= E_SKIN;
564         if (n->alpha != o->alpha)
565                 bits |= E_ALPHA;
566         if (n->scale != o->scale)
567                 bits |= E_SCALE;
568         if (n->glowsize != o->glowsize)
569                 bits |= E_GLOWSIZE;
570         if (n->glowcolor != o->glowcolor)
571                 bits |= E_GLOWCOLOR;
572         if (n->flags != o->flags)
573                 bits |= E_FLAGS;
574         if (n->tagindex != o->tagindex || n->tagentity != o->tagentity)
575                 bits |= E_TAGATTACHMENT;
576         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])
577                 bits |= E_LIGHT;
578         if (n->lightstyle != o->lightstyle)
579                 bits |= E_LIGHTSTYLE;
580         if (n->lightpflags != o->lightpflags)
581                 bits |= E_LIGHTPFLAGS;
582
583         if (bits)
584         {
585                 if (bits &  0xFF000000)
586                         bits |= 0x00800000;
587                 if (bits &  0x00FF0000)
588                         bits |= 0x00008000;
589                 if (bits &  0x0000FF00)
590                         bits |= 0x00000080;
591         }
592         return bits;
593 }
594
595 void EntityState_WriteExtendBits(sizebuf_t *msg, unsigned int bits)
596 {
597         MSG_WriteByte(msg, bits & 0xFF);
598         if (bits & 0x00000080)
599         {
600                 MSG_WriteByte(msg, (bits >> 8) & 0xFF);
601                 if (bits & 0x00008000)
602                 {
603                         MSG_WriteByte(msg, (bits >> 16) & 0xFF);
604                         if (bits & 0x00800000)
605                                 MSG_WriteByte(msg, (bits >> 24) & 0xFF);
606                 }
607         }
608 }
609
610 void EntityState_WriteFields(const entity_state_t *ent, sizebuf_t *msg, unsigned int bits)
611 {
612         if (sv.protocol == PROTOCOL_DARKPLACES2)
613         {
614                 if (bits & E_ORIGIN1)
615                         MSG_WriteCoord16i(msg, ent->origin[0]);
616                 if (bits & E_ORIGIN2)
617                         MSG_WriteCoord16i(msg, ent->origin[1]);
618                 if (bits & E_ORIGIN3)
619                         MSG_WriteCoord16i(msg, ent->origin[2]);
620         }
621         else
622         {
623                 // LordHavoc: have to write flags first, as they can modify protocol
624                 if (bits & E_FLAGS)
625                         MSG_WriteByte(msg, ent->flags);
626                 if (ent->flags & RENDER_LOWPRECISION)
627                 {
628                         if (bits & E_ORIGIN1)
629                                 MSG_WriteCoord16i(msg, ent->origin[0]);
630                         if (bits & E_ORIGIN2)
631                                 MSG_WriteCoord16i(msg, ent->origin[1]);
632                         if (bits & E_ORIGIN3)
633                                 MSG_WriteCoord16i(msg, ent->origin[2]);
634                 }
635                 else
636                 {
637                         if (bits & E_ORIGIN1)
638                                 MSG_WriteCoord32f(msg, ent->origin[0]);
639                         if (bits & E_ORIGIN2)
640                                 MSG_WriteCoord32f(msg, ent->origin[1]);
641                         if (bits & E_ORIGIN3)
642                                 MSG_WriteCoord32f(msg, ent->origin[2]);
643                 }
644         }
645         if ((sv.protocol == PROTOCOL_DARKPLACES1 || sv.protocol == PROTOCOL_DARKPLACES2 || sv.protocol == PROTOCOL_DARKPLACES3 || sv.protocol == PROTOCOL_DARKPLACES4) && (ent->flags & RENDER_LOWPRECISION))
646         {
647                 if (bits & E_ANGLE1)
648                         MSG_WriteAngle8i(msg, ent->angles[0]);
649                 if (bits & E_ANGLE2)
650                         MSG_WriteAngle8i(msg, ent->angles[1]);
651                 if (bits & E_ANGLE3)
652                         MSG_WriteAngle8i(msg, ent->angles[2]);
653         }
654         else
655         {
656                 if (bits & E_ANGLE1)
657                         MSG_WriteAngle16i(msg, ent->angles[0]);
658                 if (bits & E_ANGLE2)
659                         MSG_WriteAngle16i(msg, ent->angles[1]);
660                 if (bits & E_ANGLE3)
661                         MSG_WriteAngle16i(msg, ent->angles[2]);
662         }
663         if (bits & E_MODEL1)
664                 MSG_WriteByte(msg, ent->modelindex & 0xFF);
665         if (bits & E_MODEL2)
666                 MSG_WriteByte(msg, (ent->modelindex >> 8) & 0xFF);
667         if (bits & E_FRAME1)
668                 MSG_WriteByte(msg, ent->frame & 0xFF);
669         if (bits & E_FRAME2)
670                 MSG_WriteByte(msg, (ent->frame >> 8) & 0xFF);
671         if (bits & E_EFFECTS1)
672                 MSG_WriteByte(msg, ent->effects & 0xFF);
673         if (bits & E_EFFECTS2)
674                 MSG_WriteByte(msg, (ent->effects >> 8) & 0xFF);
675         if (bits & E_COLORMAP)
676                 MSG_WriteByte(msg, ent->colormap);
677         if (bits & E_SKIN)
678                 MSG_WriteByte(msg, ent->skin);
679         if (bits & E_ALPHA)
680                 MSG_WriteByte(msg, ent->alpha);
681         if (bits & E_SCALE)
682                 MSG_WriteByte(msg, ent->scale);
683         if (bits & E_GLOWSIZE)
684                 MSG_WriteByte(msg, ent->glowsize);
685         if (bits & E_GLOWCOLOR)
686                 MSG_WriteByte(msg, ent->glowcolor);
687         if (sv.protocol == PROTOCOL_DARKPLACES2)
688                 if (bits & E_FLAGS)
689                         MSG_WriteByte(msg, ent->flags);
690         if (bits & E_TAGATTACHMENT)
691         {
692                 MSG_WriteShort(msg, ent->tagentity);
693                 MSG_WriteByte(msg, ent->tagindex);
694         }
695         if (bits & E_LIGHT)
696         {
697                 MSG_WriteShort(msg, ent->light[0]);
698                 MSG_WriteShort(msg, ent->light[1]);
699                 MSG_WriteShort(msg, ent->light[2]);
700                 MSG_WriteShort(msg, ent->light[3]);
701         }
702         if (bits & E_LIGHTSTYLE)
703                 MSG_WriteByte(msg, ent->lightstyle);
704         if (bits & E_LIGHTPFLAGS)
705                 MSG_WriteByte(msg, ent->lightpflags);
706 }
707
708 void EntityState_WriteUpdate(const entity_state_t *ent, sizebuf_t *msg, const entity_state_t *delta)
709 {
710         unsigned int bits;
711         if (ent->active)
712         {
713                 // entity is active, check for changes from the delta
714                 if ((bits = EntityState_DeltaBits(delta, ent)))
715                 {
716                         // write the update number, bits, and fields
717                         MSG_WriteShort(msg, ent->number);
718                         EntityState_WriteExtendBits(msg, bits);
719                         EntityState_WriteFields(ent, msg, bits);
720                 }
721         }
722         else
723         {
724                 // entity is inactive, check if the delta was active
725                 if (delta->active)
726                 {
727                         // write the remove number
728                         MSG_WriteShort(msg, ent->number | 0x8000);
729                 }
730         }
731 }
732
733 int EntityState_ReadExtendBits(void)
734 {
735         unsigned int bits;
736         bits = MSG_ReadByte();
737         if (bits & 0x00000080)
738         {
739                 bits |= MSG_ReadByte() << 8;
740                 if (bits & 0x00008000)
741                 {
742                         bits |= MSG_ReadByte() << 16;
743                         if (bits & 0x00800000)
744                                 bits |= MSG_ReadByte() << 24;
745                 }
746         }
747         return bits;
748 }
749
750 void EntityState_ReadFields(entity_state_t *e, unsigned int bits)
751 {
752         if (cls.protocol == PROTOCOL_DARKPLACES2)
753         {
754                 if (bits & E_ORIGIN1)
755                         e->origin[0] = MSG_ReadCoord16i();
756                 if (bits & E_ORIGIN2)
757                         e->origin[1] = MSG_ReadCoord16i();
758                 if (bits & E_ORIGIN3)
759                         e->origin[2] = MSG_ReadCoord16i();
760         }
761         else
762         {
763                 if (bits & E_FLAGS)
764                         e->flags = MSG_ReadByte();
765                 if (e->flags & RENDER_LOWPRECISION)
766                 {
767                         if (bits & E_ORIGIN1)
768                                 e->origin[0] = MSG_ReadCoord16i();
769                         if (bits & E_ORIGIN2)
770                                 e->origin[1] = MSG_ReadCoord16i();
771                         if (bits & E_ORIGIN3)
772                                 e->origin[2] = MSG_ReadCoord16i();
773                 }
774                 else
775                 {
776                         if (bits & E_ORIGIN1)
777                                 e->origin[0] = MSG_ReadCoord32f();
778                         if (bits & E_ORIGIN2)
779                                 e->origin[1] = MSG_ReadCoord32f();
780                         if (bits & E_ORIGIN3)
781                                 e->origin[2] = MSG_ReadCoord32f();
782                 }
783         }
784         if ((cls.protocol == PROTOCOL_DARKPLACES5 || cls.protocol == PROTOCOL_DARKPLACES6) && !(e->flags & RENDER_LOWPRECISION))
785         {
786                 if (bits & E_ANGLE1)
787                         e->angles[0] = MSG_ReadAngle16i();
788                 if (bits & E_ANGLE2)
789                         e->angles[1] = MSG_ReadAngle16i();
790                 if (bits & E_ANGLE3)
791                         e->angles[2] = MSG_ReadAngle16i();
792         }
793         else
794         {
795                 if (bits & E_ANGLE1)
796                         e->angles[0] = MSG_ReadAngle8i();
797                 if (bits & E_ANGLE2)
798                         e->angles[1] = MSG_ReadAngle8i();
799                 if (bits & E_ANGLE3)
800                         e->angles[2] = MSG_ReadAngle8i();
801         }
802         if (bits & E_MODEL1)
803                 e->modelindex = (e->modelindex & 0xFF00) | (unsigned int) MSG_ReadByte();
804         if (bits & E_MODEL2)
805                 e->modelindex = (e->modelindex & 0x00FF) | ((unsigned int) MSG_ReadByte() << 8);
806         if (bits & E_FRAME1)
807                 e->frame = (e->frame & 0xFF00) | (unsigned int) MSG_ReadByte();
808         if (bits & E_FRAME2)
809                 e->frame = (e->frame & 0x00FF) | ((unsigned int) MSG_ReadByte() << 8);
810         if (bits & E_EFFECTS1)
811                 e->effects = (e->effects & 0xFF00) | (unsigned int) MSG_ReadByte();
812         if (bits & E_EFFECTS2)
813                 e->effects = (e->effects & 0x00FF) | ((unsigned int) MSG_ReadByte() << 8);
814         if (bits & E_COLORMAP)
815                 e->colormap = MSG_ReadByte();
816         if (bits & E_SKIN)
817                 e->skin = MSG_ReadByte();
818         if (bits & E_ALPHA)
819                 e->alpha = MSG_ReadByte();
820         if (bits & E_SCALE)
821                 e->scale = MSG_ReadByte();
822         if (bits & E_GLOWSIZE)
823                 e->glowsize = MSG_ReadByte();
824         if (bits & E_GLOWCOLOR)
825                 e->glowcolor = MSG_ReadByte();
826         if (cls.protocol == PROTOCOL_DARKPLACES2)
827                 if (bits & E_FLAGS)
828                         e->flags = MSG_ReadByte();
829         if (bits & E_TAGATTACHMENT)
830         {
831                 e->tagentity = (unsigned short) MSG_ReadShort();
832                 e->tagindex = MSG_ReadByte();
833         }
834         if (bits & E_LIGHT)
835         {
836                 e->light[0] = (unsigned short) MSG_ReadShort();
837                 e->light[1] = (unsigned short) MSG_ReadShort();
838                 e->light[2] = (unsigned short) MSG_ReadShort();
839                 e->light[3] = (unsigned short) MSG_ReadShort();
840         }
841         if (bits & E_LIGHTSTYLE)
842                 e->lightstyle = MSG_ReadByte();
843         if (bits & E_LIGHTPFLAGS)
844                 e->lightpflags = MSG_ReadByte();
845
846         if (developer_networkentities.integer >= 2)
847         {
848                 Con_Printf("ReadFields e%i", e->number);
849
850                 if (bits & E_ORIGIN1)
851                         Con_Printf(" E_ORIGIN1 %f", e->origin[0]);
852                 if (bits & E_ORIGIN2)
853                         Con_Printf(" E_ORIGIN2 %f", e->origin[1]);
854                 if (bits & E_ORIGIN3)
855                         Con_Printf(" E_ORIGIN3 %f", e->origin[2]);
856                 if (bits & E_ANGLE1)
857                         Con_Printf(" E_ANGLE1 %f", e->angles[0]);
858                 if (bits & E_ANGLE2)
859                         Con_Printf(" E_ANGLE2 %f", e->angles[1]);
860                 if (bits & E_ANGLE3)
861                         Con_Printf(" E_ANGLE3 %f", e->angles[2]);
862                 if (bits & (E_MODEL1 | E_MODEL2))
863                         Con_Printf(" E_MODEL %i", e->modelindex);
864
865                 if (bits & (E_FRAME1 | E_FRAME2))
866                         Con_Printf(" E_FRAME %i", e->frame);
867                 if (bits & (E_EFFECTS1 | E_EFFECTS2))
868                         Con_Printf(" E_EFFECTS %i", e->effects);
869                 if (bits & E_ALPHA)
870                         Con_Printf(" E_ALPHA %f", e->alpha / 255.0f);
871                 if (bits & E_SCALE)
872                         Con_Printf(" E_SCALE %f", e->scale / 16.0f);
873                 if (bits & E_COLORMAP)
874                         Con_Printf(" E_COLORMAP %i", e->colormap);
875                 if (bits & E_SKIN)
876                         Con_Printf(" E_SKIN %i", e->skin);
877
878                 if (bits & E_GLOWSIZE)
879                         Con_Printf(" E_GLOWSIZE %i", e->glowsize * 4);
880                 if (bits & E_GLOWCOLOR)
881                         Con_Printf(" E_GLOWCOLOR %i", e->glowcolor);
882
883                 if (bits & E_LIGHT)
884                         Con_Printf(" E_LIGHT %i:%i:%i:%i", e->light[0], e->light[1], e->light[2], e->light[3]);
885                 if (bits & E_LIGHTPFLAGS)
886                         Con_Printf(" E_LIGHTPFLAGS %i", e->lightpflags);
887
888                 if (bits & E_TAGATTACHMENT)
889                         Con_Printf(" E_TAGATTACHMENT e%i:%i", e->tagentity, e->tagindex);
890                 if (bits & E_LIGHTSTYLE)
891                         Con_Printf(" E_LIGHTSTYLE %i", e->lightstyle);
892                 Con_Print("\n");
893         }
894 }
895
896 // (client and server) allocates a new empty database
897 entityframe_database_t *EntityFrame_AllocDatabase(mempool_t *mempool)
898 {
899         return (entityframe_database_t *)Mem_Alloc(mempool, sizeof(entityframe_database_t));
900 }
901
902 // (client and server) frees the database
903 void EntityFrame_FreeDatabase(entityframe_database_t *d)
904 {
905         Mem_Free(d);
906 }
907
908 // (server) clears the database to contain no frames (thus delta compression compresses against nothing)
909 void EntityFrame_ClearDatabase(entityframe_database_t *d)
910 {
911         memset(d, 0, sizeof(*d));
912 }
913
914 // (server and client) removes frames older than 'frame' from database
915 void EntityFrame_AckFrame(entityframe_database_t *d, int frame)
916 {
917         int i;
918         d->ackframenum = frame;
919         for (i = 0;i < d->numframes && d->frames[i].framenum < frame;i++);
920         // ignore outdated frame acks (out of order packets)
921         if (i == 0)
922                 return;
923         d->numframes -= i;
924         // if some queue is left, slide it down to beginning of array
925         if (d->numframes)
926                 memmove(&d->frames[0], &d->frames[i], sizeof(d->frames[0]) * d->numframes);
927 }
928
929 // (server) clears frame, to prepare for adding entities
930 void EntityFrame_Clear(entity_frame_t *f, vec3_t eye, int framenum)
931 {
932         f->time = 0;
933         f->framenum = framenum;
934         f->numentities = 0;
935         if (eye == NULL)
936                 VectorClear(f->eye);
937         else
938                 VectorCopy(eye, f->eye);
939 }
940
941 // (server and client) reads a frame from the database
942 void EntityFrame_FetchFrame(entityframe_database_t *d, int framenum, entity_frame_t *f)
943 {
944         int i, n;
945         EntityFrame_Clear(f, NULL, -1);
946         for (i = 0;i < d->numframes && d->frames[i].framenum < framenum;i++);
947         if (i < d->numframes && framenum == d->frames[i].framenum)
948         {
949                 f->framenum = framenum;
950                 f->numentities = d->frames[i].endentity - d->frames[i].firstentity;
951                 n = MAX_ENTITY_DATABASE - (d->frames[i].firstentity % MAX_ENTITY_DATABASE);
952                 if (n > f->numentities)
953                         n = f->numentities;
954                 memcpy(f->entitydata, d->entitydata + d->frames[i].firstentity % MAX_ENTITY_DATABASE, sizeof(*f->entitydata) * n);
955                 if (f->numentities > n)
956                         memcpy(f->entitydata + n, d->entitydata, sizeof(*f->entitydata) * (f->numentities - n));
957                 VectorCopy(d->eye, f->eye);
958         }
959 }
960
961 // (server and client) adds a entity_frame to the database, for future reference
962 void EntityFrame_AddFrame(entityframe_database_t *d, vec3_t eye, int framenum, int numentities, const entity_state_t *entitydata)
963 {
964         int n, e;
965         entity_frameinfo_t *info;
966
967         VectorCopy(eye, d->eye);
968
969         // figure out how many entity slots are used already
970         if (d->numframes)
971         {
972                 n = d->frames[d->numframes - 1].endentity - d->frames[0].firstentity;
973                 if (n + numentities > MAX_ENTITY_DATABASE || d->numframes >= MAX_ENTITY_HISTORY)
974                 {
975                         // ran out of room, dump database
976                         EntityFrame_ClearDatabase(d);
977                 }
978         }
979
980         info = &d->frames[d->numframes];
981         info->framenum = framenum;
982         e = -1000;
983         // make sure we check the newly added frame as well, but we haven't incremented numframes yet
984         for (n = 0;n <= d->numframes;n++)
985         {
986                 if (e >= d->frames[n].framenum)
987                 {
988                         if (e == framenum)
989                                 Con_Print("EntityFrame_AddFrame: tried to add out of sequence frame to database\n");
990                         else
991                                 Con_Print("EntityFrame_AddFrame: out of sequence frames in database\n");
992                         return;
993                 }
994                 e = d->frames[n].framenum;
995         }
996         // if database still has frames after that...
997         if (d->numframes)
998                 info->firstentity = d->frames[d->numframes - 1].endentity;
999         else
1000                 info->firstentity = 0;
1001         info->endentity = info->firstentity + numentities;
1002         d->numframes++;
1003
1004         n = info->firstentity % MAX_ENTITY_DATABASE;
1005         e = MAX_ENTITY_DATABASE - n;
1006         if (e > numentities)
1007                 e = numentities;
1008         memcpy(d->entitydata + n, entitydata, sizeof(entity_state_t) * e);
1009         if (numentities > e)
1010                 memcpy(d->entitydata, entitydata + e, sizeof(entity_state_t) * (numentities - e));
1011 }
1012
1013 // (server) writes a frame to network stream
1014 void EntityFrame_WriteFrame(sizebuf_t *msg, entityframe_database_t *d, int numstates, const entity_state_t *states, int viewentnum)
1015 {
1016         int i, onum, number;
1017         entity_frame_t *o = &deltaframe;
1018         const entity_state_t *ent, *delta;
1019         vec3_t eye;
1020         prvm_eval_t *val;
1021
1022         d->latestframenum++;
1023
1024         VectorClear(eye);
1025         for (i = 0;i < numstates;i++)
1026         {
1027                 if (states[i].number == viewentnum)
1028                 {
1029                         VectorSet(eye, states[i].origin[0], states[i].origin[1], states[i].origin[2] + 22);
1030                         break;
1031                 }
1032         }
1033
1034         EntityFrame_AddFrame(d, eye, d->latestframenum, numstates, states);
1035
1036         EntityFrame_FetchFrame(d, d->ackframenum, o);
1037
1038         MSG_WriteByte (msg, svc_entities);
1039         MSG_WriteLong (msg, o->framenum);
1040         MSG_WriteLong (msg, d->latestframenum);
1041         MSG_WriteFloat (msg, eye[0]);
1042         MSG_WriteFloat (msg, eye[1]);
1043         MSG_WriteFloat (msg, eye[2]);
1044
1045         onum = 0;
1046         for (i = 0;i < numstates;i++)
1047         {
1048                 ent = states + i;
1049                 number = ent->number;
1050
1051                 val = PRVM_GETEDICTFIELDVALUE((&prog->edicts[number]), eval_SendEntity);
1052                 if(val && val->function)
1053                                 continue;
1054                 for (;onum < o->numentities && o->entitydata[onum].number < number;onum++)
1055                 {
1056                         // write remove message
1057                         MSG_WriteShort(msg, o->entitydata[onum].number | 0x8000);
1058                 }
1059                 if (onum < o->numentities && (o->entitydata[onum].number == number))
1060                 {
1061                         // delta from previous frame
1062                         delta = o->entitydata + onum;
1063                         // advance to next entity in delta frame
1064                         onum++;
1065                 }
1066                 else
1067                 {
1068                         // delta from defaults
1069                         delta = &defaultstate;
1070                 }
1071                 EntityState_WriteUpdate(ent, msg, delta);
1072         }
1073         for (;onum < o->numentities;onum++)
1074         {
1075                 // write remove message
1076                 MSG_WriteShort(msg, o->entitydata[onum].number | 0x8000);
1077         }
1078         MSG_WriteShort(msg, 0xFFFF);
1079 }
1080
1081 // (client) reads a frame from network stream
1082 void EntityFrame_CL_ReadFrame(void)
1083 {
1084         int i, number, removed;
1085         entity_frame_t *f = &framedata, *delta = &deltaframe;
1086         entity_state_t *e, *old, *oldend;
1087         entity_t *ent;
1088         entityframe_database_t *d;
1089         if (!cl.entitydatabase)
1090                 cl.entitydatabase = EntityFrame_AllocDatabase(cls.levelmempool);
1091         d = cl.entitydatabase;
1092
1093         EntityFrame_Clear(f, NULL, -1);
1094
1095         // read the frame header info
1096         f->time = cl.mtime[0];
1097         number = MSG_ReadLong();
1098         for (i = 0;i < LATESTFRAMENUMS-1;i++)
1099                 cl.latestframenums[i] = cl.latestframenums[i+1];
1100         cl.latestframenums[LATESTFRAMENUMS-1] = f->framenum = MSG_ReadLong();
1101         f->eye[0] = MSG_ReadFloat();
1102         f->eye[1] = MSG_ReadFloat();
1103         f->eye[2] = MSG_ReadFloat();
1104         EntityFrame_AckFrame(d, number);
1105         EntityFrame_FetchFrame(d, number, delta);
1106         old = delta->entitydata;
1107         oldend = old + delta->numentities;
1108         // read entities until we hit the magic 0xFFFF end tag
1109         while ((number = (unsigned short) MSG_ReadShort()) != 0xFFFF && !msg_badread)
1110         {
1111                 if (msg_badread)
1112                         Host_Error("EntityFrame_Read: read error");
1113                 removed = number & 0x8000;
1114                 number &= 0x7FFF;
1115                 if (number >= MAX_EDICTS)
1116                         Host_Error("EntityFrame_Read: number (%i) >= MAX_EDICTS (%i)", number, MAX_EDICTS);
1117
1118                 // seek to entity, while copying any skipped entities (assume unchanged)
1119                 while (old < oldend && old->number < number)
1120                 {
1121                         if (f->numentities >= MAX_ENTITY_DATABASE)
1122                                 Host_Error("EntityFrame_Read: entity list too big");
1123                         f->entitydata[f->numentities] = *old++;
1124                         f->entitydata[f->numentities++].time = cl.mtime[0];
1125                 }
1126                 if (removed)
1127                 {
1128                         if (old < oldend && old->number == number)
1129                                 old++;
1130                         else
1131                                 Con_Printf("EntityFrame_Read: REMOVE on unused entity %i\n", number);
1132                 }
1133                 else
1134                 {
1135                         if (f->numentities >= MAX_ENTITY_DATABASE)
1136                                 Host_Error("EntityFrame_Read: entity list too big");
1137
1138                         // reserve this slot
1139                         e = f->entitydata + f->numentities++;
1140
1141                         if (old < oldend && old->number == number)
1142                         {
1143                                 // delta from old entity
1144                                 *e = *old++;
1145                         }
1146                         else
1147                         {
1148                                 // delta from defaults
1149                                 *e = defaultstate;
1150                         }
1151
1152                         if (cl.num_entities <= number)
1153                         {
1154                                 cl.num_entities = number + 1;
1155                                 if (number >= cl.max_entities)
1156                                         CL_ExpandEntities(number);
1157                         }
1158                         cl.entities_active[number] = true;
1159                         e->active = true;
1160                         e->time = cl.mtime[0];
1161                         e->number = number;
1162                         EntityState_ReadFields(e, EntityState_ReadExtendBits());
1163                 }
1164         }
1165         while (old < oldend)
1166         {
1167                 if (f->numentities >= MAX_ENTITY_DATABASE)
1168                         Host_Error("EntityFrame_Read: entity list too big");
1169                 f->entitydata[f->numentities] = *old++;
1170                 f->entitydata[f->numentities++].time = cl.mtime[0];
1171         }
1172         EntityFrame_AddFrame(d, f->eye, f->framenum, f->numentities, f->entitydata);
1173
1174         memset(cl.entities_active, 0, cl.num_entities * sizeof(unsigned char));
1175         number = 1;
1176         for (i = 0;i < f->numentities;i++)
1177         {
1178                 for (;number < f->entitydata[i].number && number < cl.num_entities;number++)
1179                 {
1180                         if (cl.entities_active[number])
1181                         {
1182                                 cl.entities_active[number] = false;
1183                                 cl.entities[number].state_current.active = false;
1184                         }
1185                 }
1186                 if (number >= cl.num_entities)
1187                         break;
1188                 // update the entity
1189                 ent = &cl.entities[number];
1190                 ent->state_previous = ent->state_current;
1191                 ent->state_current = f->entitydata[i];
1192                 CL_MoveLerpEntityStates(ent);
1193                 // the entity lives again...
1194                 cl.entities_active[number] = true;
1195                 number++;
1196         }
1197         for (;number < cl.num_entities;number++)
1198         {
1199                 if (cl.entities_active[number])
1200                 {
1201                         cl.entities_active[number] = false;
1202                         cl.entities[number].state_current.active = false;
1203                 }
1204         }
1205 }
1206
1207
1208 // (client) returns the frame number of the most recent frame recieved
1209 int EntityFrame_MostRecentlyRecievedFrameNum(entityframe_database_t *d)
1210 {
1211         if (d->numframes)
1212                 return d->frames[d->numframes - 1].framenum;
1213         else
1214                 return -1;
1215 }
1216
1217
1218
1219
1220
1221
1222 entity_state_t *EntityFrame4_GetReferenceEntity(entityframe4_database_t *d, int number)
1223 {
1224         if (d->maxreferenceentities <= number)
1225         {
1226                 int oldmax = d->maxreferenceentities;
1227                 entity_state_t *oldentity = d->referenceentity;
1228                 d->maxreferenceentities = (number + 15) & ~7;
1229                 d->referenceentity = (entity_state_t *)Mem_Alloc(d->mempool, d->maxreferenceentities * sizeof(*d->referenceentity));
1230                 if (oldentity)
1231                 {
1232                         memcpy(d->referenceentity, oldentity, oldmax * sizeof(*d->referenceentity));
1233                         Mem_Free(oldentity);
1234                 }
1235                 // clear the newly created entities
1236                 for (;oldmax < d->maxreferenceentities;oldmax++)
1237                 {
1238                         d->referenceentity[oldmax] = defaultstate;
1239                         d->referenceentity[oldmax].number = oldmax;
1240                 }
1241         }
1242         return d->referenceentity + number;
1243 }
1244
1245 void EntityFrame4_AddCommitEntity(entityframe4_database_t *d, const entity_state_t *s)
1246 {
1247         // resize commit's entity list if full
1248         if (d->currentcommit->maxentities <= d->currentcommit->numentities)
1249         {
1250                 entity_state_t *oldentity = d->currentcommit->entity;
1251                 d->currentcommit->maxentities += 8;
1252                 d->currentcommit->entity = (entity_state_t *)Mem_Alloc(d->mempool, d->currentcommit->maxentities * sizeof(*d->currentcommit->entity));
1253                 if (oldentity)
1254                 {
1255                         memcpy(d->currentcommit->entity, oldentity, d->currentcommit->numentities * sizeof(*d->currentcommit->entity));
1256                         Mem_Free(oldentity);
1257                 }
1258         }
1259         d->currentcommit->entity[d->currentcommit->numentities++] = *s;
1260 }
1261
1262 entityframe4_database_t *EntityFrame4_AllocDatabase(mempool_t *pool)
1263 {
1264         entityframe4_database_t *d;
1265         d = (entityframe4_database_t *)Mem_Alloc(pool, sizeof(*d));
1266         d->mempool = pool;
1267         EntityFrame4_ResetDatabase(d);
1268         return d;
1269 }
1270
1271 void EntityFrame4_FreeDatabase(entityframe4_database_t *d)
1272 {
1273         int i;
1274         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1275                 if (d->commit[i].entity)
1276                         Mem_Free(d->commit[i].entity);
1277         if (d->referenceentity)
1278                 Mem_Free(d->referenceentity);
1279         Mem_Free(d);
1280 }
1281
1282 void EntityFrame4_ResetDatabase(entityframe4_database_t *d)
1283 {
1284         int i;
1285         d->referenceframenum = -1;
1286         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1287                 d->commit[i].numentities = 0;
1288         for (i = 0;i < d->maxreferenceentities;i++)
1289                 d->referenceentity[i] = defaultstate;
1290 }
1291
1292 int EntityFrame4_AckFrame(entityframe4_database_t *d, int framenum, int servermode)
1293 {
1294         int i, j, found;
1295         entity_database4_commit_t *commit;
1296         if (framenum == -1)
1297         {
1298                 // reset reference, but leave commits alone
1299                 d->referenceframenum = -1;
1300                 for (i = 0;i < d->maxreferenceentities;i++)
1301                         d->referenceentity[i] = defaultstate;
1302                 // if this is the server, remove commits
1303                         for (i = 0, commit = d->commit;i < MAX_ENTITY_HISTORY;i++, commit++)
1304                                 commit->numentities = 0;
1305                 found = true;
1306         }
1307         else if (d->referenceframenum == framenum)
1308                 found = true;
1309         else
1310         {
1311                 found = false;
1312                 for (i = 0, commit = d->commit;i < MAX_ENTITY_HISTORY;i++, commit++)
1313                 {
1314                         if (commit->numentities && commit->framenum <= framenum)
1315                         {
1316                                 if (commit->framenum == framenum)
1317                                 {
1318                                         found = true;
1319                                         d->referenceframenum = framenum;
1320                                         if (developer_networkentities.integer >= 3)
1321                                         {
1322                                                 for (j = 0;j < commit->numentities;j++)
1323                                                 {
1324                                                         entity_state_t *s = EntityFrame4_GetReferenceEntity(d, commit->entity[j].number);
1325                                                         if (commit->entity[j].active != s->active)
1326                                                         {
1327                                                                 if (commit->entity[j].active)
1328                                                                         Con_Printf("commit entity %i has become active (modelindex %i)\n", commit->entity[j].number, commit->entity[j].modelindex);
1329                                                                 else
1330                                                                         Con_Printf("commit entity %i has become inactive (modelindex %i)\n", commit->entity[j].number, commit->entity[j].modelindex);
1331                                                         }
1332                                                         *s = commit->entity[j];
1333                                                 }
1334                                         }
1335                                         else
1336                                                 for (j = 0;j < commit->numentities;j++)
1337                                                         *EntityFrame4_GetReferenceEntity(d, commit->entity[j].number) = commit->entity[j];
1338                                 }
1339                                 commit->numentities = 0;
1340                         }
1341                 }
1342         }
1343         if (developer_networkentities.integer >= 1)
1344         {
1345                 Con_Printf("ack ref:%i database updated to: ref:%i commits:", framenum, d->referenceframenum);
1346                 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1347                         if (d->commit[i].numentities)
1348                                 Con_Printf(" %i", d->commit[i].framenum);
1349                 Con_Print("\n");
1350         }
1351         return found;
1352 }
1353
1354 void EntityFrame4_CL_ReadFrame(void)
1355 {
1356         int i, n, cnumber, referenceframenum, framenum, enumber, done, stopnumber, skip = false;
1357         entity_state_t *s;
1358         entityframe4_database_t *d;
1359         if (!cl.entitydatabase4)
1360                 cl.entitydatabase4 = EntityFrame4_AllocDatabase(cls.levelmempool);
1361         d = cl.entitydatabase4;
1362         // read the number of the frame this refers to
1363         referenceframenum = MSG_ReadLong();
1364         // read the number of this frame
1365         for (i = 0;i < LATESTFRAMENUMS-1;i++)
1366                 cl.latestframenums[i] = cl.latestframenums[i+1];
1367         cl.latestframenums[LATESTFRAMENUMS-1] = framenum = MSG_ReadLong();
1368         // read the start number
1369         enumber = (unsigned short) MSG_ReadShort();
1370         if (developer_networkentities.integer >= 1)
1371         {
1372                 Con_Printf("recv svc_entities num:%i ref:%i database: ref:%i commits:", framenum, referenceframenum, d->referenceframenum);
1373                 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1374                         if (d->commit[i].numentities)
1375                                 Con_Printf(" %i", d->commit[i].framenum);
1376                 Con_Print("\n");
1377         }
1378         if (!EntityFrame4_AckFrame(d, referenceframenum, false))
1379         {
1380                 Con_Print("EntityFrame4_CL_ReadFrame: reference frame invalid (VERY BAD ERROR), this update will be skipped\n");
1381                 skip = true;
1382         }
1383         d->currentcommit = NULL;
1384         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1385         {
1386                 if (!d->commit[i].numentities)
1387                 {
1388                         d->currentcommit = d->commit + i;
1389                         d->currentcommit->framenum = framenum;
1390                         d->currentcommit->numentities = 0;
1391                 }
1392         }
1393         if (d->currentcommit == NULL)
1394         {
1395                 Con_Printf("EntityFrame4_CL_ReadFrame: error while decoding frame %i: database full, reading but not storing this update\n", framenum);
1396                 skip = true;
1397         }
1398         done = false;
1399         while (!done && !msg_badread)
1400         {
1401                 // read the number of the modified entity
1402                 // (gaps will be copied unmodified)
1403                 n = (unsigned short)MSG_ReadShort();
1404                 if (n == 0x8000)
1405                 {
1406                         // no more entities in this update, but we still need to copy the
1407                         // rest of the reference entities (final gap)
1408                         done = true;
1409                         // read end of range number, then process normally
1410                         n = (unsigned short)MSG_ReadShort();
1411                 }
1412                 // high bit means it's a remove message
1413                 cnumber = n & 0x7FFF;
1414                 // if this is a live entity we may need to expand the array
1415                 if (cl.num_entities <= cnumber && !(n & 0x8000))
1416                 {
1417                         cl.num_entities = cnumber + 1;
1418                         if (cnumber >= cl.max_entities)
1419                                 CL_ExpandEntities(cnumber);
1420                 }
1421                 // add one (the changed one) if not done
1422                 stopnumber = cnumber + !done;
1423                 // process entities in range from the last one to the changed one
1424                 for (;enumber < stopnumber;enumber++)
1425                 {
1426                         if (skip || enumber >= cl.num_entities)
1427                         {
1428                                 if (enumber == cnumber && (n & 0x8000) == 0)
1429                                 {
1430                                         entity_state_t tempstate;
1431                                         EntityState_ReadFields(&tempstate, EntityState_ReadExtendBits());
1432                                 }
1433                                 continue;
1434                         }
1435                         // slide the current into the previous slot
1436                         cl.entities[enumber].state_previous = cl.entities[enumber].state_current;
1437                         // copy a new current from reference database
1438                         cl.entities[enumber].state_current = *EntityFrame4_GetReferenceEntity(d, enumber);
1439                         s = &cl.entities[enumber].state_current;
1440                         // if this is the one to modify, read more data...
1441                         if (enumber == cnumber)
1442                         {
1443                                 if (n & 0x8000)
1444                                 {
1445                                         // simply removed
1446                                         if (developer_networkentities.integer >= 2)
1447                                                 Con_Printf("entity %i: remove\n", enumber);
1448                                         *s = defaultstate;
1449                                 }
1450                                 else
1451                                 {
1452                                         // read the changes
1453                                         if (developer_networkentities.integer >= 2)
1454                                                 Con_Printf("entity %i: update\n", enumber);
1455                                         s->active = true;
1456                                         EntityState_ReadFields(s, EntityState_ReadExtendBits());
1457                                 }
1458                         }
1459                         else if (developer_networkentities.integer >= 4)
1460                                 Con_Printf("entity %i: copy\n", enumber);
1461                         // set the cl.entities_active flag
1462                         cl.entities_active[enumber] = s->active;
1463                         // set the update time
1464                         s->time = cl.mtime[0];
1465                         // fix the number (it gets wiped occasionally by copying from defaultstate)
1466                         s->number = enumber;
1467                         // check if we need to update the lerp stuff
1468                         if (s->active)
1469                                 CL_MoveLerpEntityStates(&cl.entities[enumber]);
1470                         // add this to the commit entry whether it is modified or not
1471                         if (d->currentcommit)
1472                                 EntityFrame4_AddCommitEntity(d, &cl.entities[enumber].state_current);
1473                         // print extra messages if desired
1474                         if (developer_networkentities.integer >= 2 && cl.entities[enumber].state_current.active != cl.entities[enumber].state_previous.active)
1475                         {
1476                                 if (cl.entities[enumber].state_current.active)
1477                                         Con_Printf("entity #%i has become active\n", enumber);
1478                                 else if (cl.entities[enumber].state_previous.active)
1479                                         Con_Printf("entity #%i has become inactive\n", enumber);
1480                         }
1481                 }
1482         }
1483         d->currentcommit = NULL;
1484         if (skip)
1485                 EntityFrame4_ResetDatabase(d);
1486 }
1487
1488 void EntityFrame4_WriteFrame(sizebuf_t *msg, entityframe4_database_t *d, int numstates, const entity_state_t *states)
1489 {
1490         const entity_state_t *e, *s;
1491         entity_state_t inactiveentitystate;
1492         int i, n, startnumber;
1493         sizebuf_t buf;
1494         unsigned char data[128];
1495         prvm_eval_t *val;
1496
1497         // if there isn't enough space to accomplish anything, skip it
1498         if (msg->cursize + 24 > msg->maxsize)
1499                 return;
1500
1501         // prepare the buffer
1502         memset(&buf, 0, sizeof(buf));
1503         buf.data = data;
1504         buf.maxsize = sizeof(data);
1505
1506         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1507                 if (!d->commit[i].numentities)
1508                         break;
1509         // if commit buffer full, just don't bother writing an update this frame
1510         if (i == MAX_ENTITY_HISTORY)
1511                 return;
1512         d->currentcommit = d->commit + i;
1513
1514         // this state's number gets played around with later
1515         inactiveentitystate = defaultstate;
1516
1517         d->currentcommit->numentities = 0;
1518         d->currentcommit->framenum = ++d->latestframenumber;
1519         MSG_WriteByte(msg, svc_entities);
1520         MSG_WriteLong(msg, d->referenceframenum);
1521         MSG_WriteLong(msg, d->currentcommit->framenum);
1522         if (developer_networkentities.integer >= 1)
1523         {
1524                 Con_Printf("send svc_entities num:%i ref:%i (database: ref:%i commits:", d->currentcommit->framenum, d->referenceframenum, d->referenceframenum);
1525                 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
1526                         if (d->commit[i].numentities)
1527                                 Con_Printf(" %i", d->commit[i].framenum);
1528                 Con_Print(")\n");
1529         }
1530         if (d->currententitynumber >= prog->max_edicts)
1531                 startnumber = 1;
1532         else
1533                 startnumber = bound(1, d->currententitynumber, prog->max_edicts - 1);
1534         MSG_WriteShort(msg, startnumber);
1535         // reset currententitynumber so if the loop does not break it we will
1536         // start at beginning next frame (if it does break, it will set it)
1537         d->currententitynumber = 1;
1538         for (i = 0, n = startnumber;n < prog->max_edicts;n++)
1539         {
1540                 val = PRVM_GETEDICTFIELDVALUE((&prog->edicts[n]), eval_SendEntity);
1541                 if(val && val->function)
1542                         continue;
1543                 // find the old state to delta from
1544                 e = EntityFrame4_GetReferenceEntity(d, n);
1545                 // prepare the buffer
1546                 SZ_Clear(&buf);
1547                 // entity exists, build an update (if empty there is no change)
1548                 // find the state in the list
1549                 for (;i < numstates && states[i].number < n;i++);
1550                 // make the message
1551                 s = states + i;
1552                 if (s->number == n)
1553                 {
1554                         // build the update
1555                         EntityState_WriteUpdate(s, &buf, e);
1556                 }
1557                 else
1558                 {
1559                         inactiveentitystate.number = n;
1560                         s = &inactiveentitystate;
1561                         if (e->active)
1562                         {
1563                                 // entity used to exist but doesn't anymore, send remove
1564                                 MSG_WriteShort(&buf, n | 0x8000);
1565                         }
1566                 }
1567                 // if the commit is full, we're done this frame
1568                 if (msg->cursize + buf.cursize > msg->maxsize - 4)
1569                 {
1570                         // next frame we will continue where we left off
1571                         break;
1572                 }
1573                 // add the entity to the commit
1574                 EntityFrame4_AddCommitEntity(d, s);
1575                 // if the message is empty, skip out now
1576                 if (buf.cursize)
1577                 {
1578                         // write the message to the packet
1579                         SZ_Write(msg, buf.data, buf.cursize);
1580                 }
1581         }
1582         d->currententitynumber = n;
1583
1584         // remove world message (invalid, and thus a good terminator)
1585         MSG_WriteShort(msg, 0x8000);
1586         // write the number of the end entity
1587         MSG_WriteShort(msg, d->currententitynumber);
1588         // just to be sure
1589         d->currentcommit = NULL;
1590 }
1591
1592
1593
1594
1595 entityframe5_database_t *EntityFrame5_AllocDatabase(mempool_t *pool)
1596 {
1597         int i;
1598         entityframe5_database_t *d;
1599         d = (entityframe5_database_t *)Mem_Alloc(pool, sizeof(*d));
1600         d->latestframenum = 0;
1601         for (i = 0;i < d->maxedicts;i++)
1602                 d->states[i] = defaultstate;
1603         return d;
1604 }
1605
1606 void EntityFrame5_FreeDatabase(entityframe5_database_t *d)
1607 {
1608         // all the [maxedicts] memory is allocated at once, so there's only one
1609         // thing to free
1610         if (d->maxedicts)
1611                 Mem_Free(d->deltabits);
1612         Mem_Free(d);
1613 }
1614
1615 void EntityFrame5_ExpandEdicts(entityframe5_database_t *d, int newmax)
1616 {
1617         if (d->maxedicts < newmax)
1618         {
1619                 unsigned char *data;
1620                 int oldmaxedicts = d->maxedicts;
1621                 int *olddeltabits = d->deltabits;
1622                 unsigned char *oldpriorities = d->priorities;
1623                 int *oldupdateframenum = d->updateframenum;
1624                 entity_state_t *oldstates = d->states;
1625                 unsigned char *oldvisiblebits = d->visiblebits;
1626                 d->maxedicts = newmax;
1627                 data = (unsigned char *)Mem_Alloc(sv_mempool, d->maxedicts * sizeof(int) + d->maxedicts * sizeof(unsigned char) + d->maxedicts * sizeof(int) + d->maxedicts * sizeof(entity_state_t) + (d->maxedicts+7)/8 * sizeof(unsigned char));
1628                 d->deltabits = (int *)data;data += d->maxedicts * sizeof(int);
1629                 d->priorities = (unsigned char *)data;data += d->maxedicts * sizeof(unsigned char);
1630                 d->updateframenum = (int *)data;data += d->maxedicts * sizeof(int);
1631                 d->states = (entity_state_t *)data;data += d->maxedicts * sizeof(entity_state_t);
1632                 d->visiblebits = (unsigned char *)data;data += (d->maxedicts+7)/8 * sizeof(unsigned char);
1633                 if (oldmaxedicts)
1634                 {
1635                         memcpy(d->deltabits, olddeltabits, oldmaxedicts * sizeof(int));
1636                         memcpy(d->priorities, oldpriorities, oldmaxedicts * sizeof(unsigned char));
1637                         memcpy(d->updateframenum, oldupdateframenum, oldmaxedicts * sizeof(int));
1638                         memcpy(d->states, oldstates, oldmaxedicts * sizeof(entity_state_t));
1639                         memcpy(d->visiblebits, oldvisiblebits, (oldmaxedicts+7)/8 * sizeof(unsigned char));
1640                         // the previous buffers were a single allocation, so just one free
1641                         Mem_Free(olddeltabits);
1642                 }
1643         }
1644 }
1645
1646 int EntityState5_Priority(entityframe5_database_t *d, int stateindex)
1647 {
1648         int lowprecision, limit, priority;
1649         double distance;
1650         int changedbits;
1651         int age;
1652         entity_state_t *view, *s;
1653         changedbits = d->deltabits[stateindex];
1654         if (!changedbits)
1655                 return 0;
1656         if (!d->states[stateindex].active/* && changedbits & E5_FULLUPDATE*/)
1657                 return E5_PROTOCOL_PRIORITYLEVELS - 1;
1658         // check whole attachment chain to judge relevance to player
1659         view = d->states + d->viewentnum;
1660         lowprecision = false;
1661         for (limit = 0;limit < 256;limit++)
1662         {
1663                 if (d->maxedicts < stateindex)
1664                         EntityFrame5_ExpandEdicts(d, (stateindex+256)&~255);
1665                 s = d->states + stateindex;
1666                 if (s == view)
1667                         return E5_PROTOCOL_PRIORITYLEVELS - 1;
1668                 if (s->flags & RENDER_VIEWMODEL)
1669                         return E5_PROTOCOL_PRIORITYLEVELS - 1;
1670                 if (s->flags & RENDER_LOWPRECISION)
1671                         lowprecision = true;
1672                 if (!s->tagentity)
1673                 {
1674                         if (VectorCompare(s->origin, view->origin))
1675                                 return E5_PROTOCOL_PRIORITYLEVELS - 1;
1676                         break;
1677                 }
1678                 stateindex = s->tagentity;
1679         }
1680         if (limit >= 256)
1681         {
1682                 Con_Printf("Protocol: Runaway loop recursing tagentity links on entity %i\n", stateindex);
1683                 return 0;
1684         }
1685         // it's not a viewmodel for this client
1686         distance = VectorDistance(view->origin, s->origin);
1687         age = d->latestframenum - d->updateframenum[stateindex];
1688         priority = (E5_PROTOCOL_PRIORITYLEVELS / 2) + age - (int)(distance * (E5_PROTOCOL_PRIORITYLEVELS / 16384.0f));
1689         if (lowprecision)
1690                 priority -= (E5_PROTOCOL_PRIORITYLEVELS / 4);
1691         //if (changedbits & E5_FULLUPDATE)
1692         //      priority += 4;
1693         //if (changedbits & (E5_ATTACHMENT | E5_MODEL | E5_FLAGS | E5_COLORMAP))
1694         //      priority += 4;
1695         return (int) bound(1, priority, E5_PROTOCOL_PRIORITYLEVELS - 1);
1696 }
1697
1698 void EntityState5_WriteUpdate(int number, const entity_state_t *s, int changedbits, sizebuf_t *msg)
1699 {
1700         unsigned int bits = 0;
1701
1702         prvm_eval_t *val;
1703         val = PRVM_GETEDICTFIELDVALUE((&prog->edicts[s->number]), eval_SendEntity);
1704         if(val && val->function)
1705                 return;
1706
1707         if (!s->active)
1708                 MSG_WriteShort(msg, number | 0x8000);
1709         else
1710         {
1711                 bits = changedbits;
1712                 if ((bits & E5_ORIGIN) && (!(s->flags & RENDER_LOWPRECISION) || s->origin[0] < -4096 || s->origin[0] >= 4096 || s->origin[1] < -4096 || s->origin[1] >= 4096 || s->origin[2] < -4096 || s->origin[2] >= 4096))
1713                         bits |= E5_ORIGIN32;
1714                 if ((bits & E5_ANGLES) && !(s->flags & RENDER_LOWPRECISION))
1715                         bits |= E5_ANGLES16;
1716                 if ((bits & E5_MODEL) && s->modelindex >= 256)
1717                         bits |= E5_MODEL16;
1718                 if ((bits & E5_FRAME) && s->frame >= 256)
1719                         bits |= E5_FRAME16;
1720                 if (bits & E5_EFFECTS)
1721                 {
1722                         if (s->effects >= 65536)
1723                                 bits |= E5_EFFECTS32;
1724                         else if (s->effects >= 256)
1725                                 bits |= E5_EFFECTS16;
1726                 }
1727                 if (bits >= 256)
1728                         bits |= E5_EXTEND1;
1729                 if (bits >= 65536)
1730                         bits |= E5_EXTEND2;
1731                 if (bits >= 16777216)
1732                         bits |= E5_EXTEND3;
1733                 MSG_WriteShort(msg, number);
1734                 MSG_WriteByte(msg, bits & 0xFF);
1735                 if (bits & E5_EXTEND1)
1736                         MSG_WriteByte(msg, (bits >> 8) & 0xFF);
1737                 if (bits & E5_EXTEND2)
1738                         MSG_WriteByte(msg, (bits >> 16) & 0xFF);
1739                 if (bits & E5_EXTEND3)
1740                         MSG_WriteByte(msg, (bits >> 24) & 0xFF);
1741                 if (bits & E5_FLAGS)
1742                         MSG_WriteByte(msg, s->flags);
1743                 if (bits & E5_ORIGIN)
1744                 {
1745                         if (bits & E5_ORIGIN32)
1746                         {
1747                                 MSG_WriteCoord32f(msg, s->origin[0]);
1748                                 MSG_WriteCoord32f(msg, s->origin[1]);
1749                                 MSG_WriteCoord32f(msg, s->origin[2]);
1750                         }
1751                         else
1752                         {
1753                                 MSG_WriteCoord13i(msg, s->origin[0]);
1754                                 MSG_WriteCoord13i(msg, s->origin[1]);
1755                                 MSG_WriteCoord13i(msg, s->origin[2]);
1756                         }
1757                 }
1758                 if (bits & E5_ANGLES)
1759                 {
1760                         if (bits & E5_ANGLES16)
1761                         {
1762                                 MSG_WriteAngle16i(msg, s->angles[0]);
1763                                 MSG_WriteAngle16i(msg, s->angles[1]);
1764                                 MSG_WriteAngle16i(msg, s->angles[2]);
1765                         }
1766                         else
1767                         {
1768                                 MSG_WriteAngle8i(msg, s->angles[0]);
1769                                 MSG_WriteAngle8i(msg, s->angles[1]);
1770                                 MSG_WriteAngle8i(msg, s->angles[2]);
1771                         }
1772                 }
1773                 if (bits & E5_MODEL)
1774                 {
1775                         if (bits & E5_MODEL16)
1776                                 MSG_WriteShort(msg, s->modelindex);
1777                         else
1778                                 MSG_WriteByte(msg, s->modelindex);
1779                 }
1780                 if (bits & E5_FRAME)
1781                 {
1782                         if (bits & E5_FRAME16)
1783                                 MSG_WriteShort(msg, s->frame);
1784                         else
1785                                 MSG_WriteByte(msg, s->frame);
1786                 }
1787                 if (bits & E5_SKIN)
1788                         MSG_WriteByte(msg, s->skin);
1789                 if (bits & E5_EFFECTS)
1790                 {
1791                         if (bits & E5_EFFECTS32)
1792                                 MSG_WriteLong(msg, s->effects);
1793                         else if (bits & E5_EFFECTS16)
1794                                 MSG_WriteShort(msg, s->effects);
1795                         else
1796                                 MSG_WriteByte(msg, s->effects);
1797                 }
1798                 if (bits & E5_ALPHA)
1799                         MSG_WriteByte(msg, s->alpha);
1800                 if (bits & E5_SCALE)
1801                         MSG_WriteByte(msg, s->scale);
1802                 if (bits & E5_COLORMAP)
1803                         MSG_WriteByte(msg, s->colormap);
1804                 if (bits & E5_ATTACHMENT)
1805                 {
1806                         MSG_WriteShort(msg, s->tagentity);
1807                         MSG_WriteByte(msg, s->tagindex);
1808                 }
1809                 if (bits & E5_LIGHT)
1810                 {
1811                         MSG_WriteShort(msg, s->light[0]);
1812                         MSG_WriteShort(msg, s->light[1]);
1813                         MSG_WriteShort(msg, s->light[2]);
1814                         MSG_WriteShort(msg, s->light[3]);
1815                         MSG_WriteByte(msg, s->lightstyle);
1816                         MSG_WriteByte(msg, s->lightpflags);
1817                 }
1818                 if (bits & E5_GLOW)
1819                 {
1820                         MSG_WriteByte(msg, s->glowsize);
1821                         MSG_WriteByte(msg, s->glowcolor);
1822                 }
1823                 if (bits & E5_COLORMOD)
1824                 {
1825                         MSG_WriteByte(msg, s->colormod[0]);
1826                         MSG_WriteByte(msg, s->colormod[1]);
1827                         MSG_WriteByte(msg, s->colormod[2]);
1828                 }
1829         }
1830 }
1831
1832 void EntityState5_ReadUpdate(entity_state_t *s)
1833 {
1834         int bits;
1835         bits = MSG_ReadByte();
1836         if (bits & E5_EXTEND1)
1837         {
1838                 bits |= MSG_ReadByte() << 8;
1839                 if (bits & E5_EXTEND2)
1840                 {
1841                         bits |= MSG_ReadByte() << 16;
1842                         if (bits & E5_EXTEND3)
1843                                 bits |= MSG_ReadByte() << 24;
1844                 }
1845         }
1846         if (bits & E5_FULLUPDATE)
1847         {
1848                 *s = defaultstate;
1849                 s->active = true;
1850         }
1851         if (bits & E5_FLAGS)
1852                 s->flags = MSG_ReadByte();
1853         if (bits & E5_ORIGIN)
1854         {
1855                 if (bits & E5_ORIGIN32)
1856                 {
1857                         s->origin[0] = MSG_ReadCoord32f();
1858                         s->origin[1] = MSG_ReadCoord32f();
1859                         s->origin[2] = MSG_ReadCoord32f();
1860                 }
1861                 else
1862                 {
1863                         s->origin[0] = MSG_ReadCoord13i();
1864                         s->origin[1] = MSG_ReadCoord13i();
1865                         s->origin[2] = MSG_ReadCoord13i();
1866                 }
1867         }
1868         if (bits & E5_ANGLES)
1869         {
1870                 if (bits & E5_ANGLES16)
1871                 {
1872                         s->angles[0] = MSG_ReadAngle16i();
1873                         s->angles[1] = MSG_ReadAngle16i();
1874                         s->angles[2] = MSG_ReadAngle16i();
1875                 }
1876                 else
1877                 {
1878                         s->angles[0] = MSG_ReadAngle8i();
1879                         s->angles[1] = MSG_ReadAngle8i();
1880                         s->angles[2] = MSG_ReadAngle8i();
1881                 }
1882         }
1883         if (bits & E5_MODEL)
1884         {
1885                 if (bits & E5_MODEL16)
1886                         s->modelindex = (unsigned short) MSG_ReadShort();
1887                 else
1888                         s->modelindex = MSG_ReadByte();
1889         }
1890         if (bits & E5_FRAME)
1891         {
1892                 if (bits & E5_FRAME16)
1893                         s->frame = (unsigned short) MSG_ReadShort();
1894                 else
1895                         s->frame = MSG_ReadByte();
1896         }
1897         if (bits & E5_SKIN)
1898                 s->skin = MSG_ReadByte();
1899         if (bits & E5_EFFECTS)
1900         {
1901                 if (bits & E5_EFFECTS32)
1902                         s->effects = (unsigned int) MSG_ReadLong();
1903                 else if (bits & E5_EFFECTS16)
1904                         s->effects = (unsigned short) MSG_ReadShort();
1905                 else
1906                         s->effects = MSG_ReadByte();
1907         }
1908         if (bits & E5_ALPHA)
1909                 s->alpha = MSG_ReadByte();
1910         if (bits & E5_SCALE)
1911                 s->scale = MSG_ReadByte();
1912         if (bits & E5_COLORMAP)
1913                 s->colormap = MSG_ReadByte();
1914         if (bits & E5_ATTACHMENT)
1915         {
1916                 s->tagentity = (unsigned short) MSG_ReadShort();
1917                 s->tagindex = MSG_ReadByte();
1918         }
1919         if (bits & E5_LIGHT)
1920         {
1921                 s->light[0] = (unsigned short) MSG_ReadShort();
1922                 s->light[1] = (unsigned short) MSG_ReadShort();
1923                 s->light[2] = (unsigned short) MSG_ReadShort();
1924                 s->light[3] = (unsigned short) MSG_ReadShort();
1925                 s->lightstyle = MSG_ReadByte();
1926                 s->lightpflags = MSG_ReadByte();
1927         }
1928         if (bits & E5_GLOW)
1929         {
1930                 s->glowsize = MSG_ReadByte();
1931                 s->glowcolor = MSG_ReadByte();
1932         }
1933         if (bits & E5_COLORMOD)
1934         {
1935                 s->colormod[0] = MSG_ReadByte();
1936                 s->colormod[1] = MSG_ReadByte();
1937                 s->colormod[2] = MSG_ReadByte();
1938         }
1939
1940
1941         if (developer_networkentities.integer >= 2)
1942         {
1943                 Con_Printf("ReadFields e%i", s->number);
1944
1945                 if (bits & E5_ORIGIN)
1946                         Con_Printf(" E5_ORIGIN %f %f %f", s->origin[0], s->origin[1], s->origin[2]);
1947                 if (bits & E5_ANGLES)
1948                         Con_Printf(" E5_ANGLES %f %f %f", s->angles[0], s->angles[1], s->angles[2]);
1949                 if (bits & E5_MODEL)
1950                         Con_Printf(" E5_MODEL %i", s->modelindex);
1951                 if (bits & E5_FRAME)
1952                         Con_Printf(" E5_FRAME %i", s->frame);
1953                 if (bits & E5_SKIN)
1954                         Con_Printf(" E5_SKIN %i", s->skin);
1955                 if (bits & E5_EFFECTS)
1956                         Con_Printf(" E5_EFFECTS %i", s->effects);
1957                 if (bits & E5_FLAGS)
1958                 {
1959                         Con_Printf(" E5_FLAGS %i (", s->flags);
1960                         if (s->flags & RENDER_STEP)
1961                                 Con_Print(" STEP");
1962                         if (s->flags & RENDER_GLOWTRAIL)
1963                                 Con_Print(" GLOWTRAIL");
1964                         if (s->flags & RENDER_VIEWMODEL)
1965                                 Con_Print(" VIEWMODEL");
1966                         if (s->flags & RENDER_EXTERIORMODEL)
1967                                 Con_Print(" EXTERIORMODEL");
1968                         if (s->flags & RENDER_LOWPRECISION)
1969                                 Con_Print(" LOWPRECISION");
1970                         if (s->flags & RENDER_COLORMAPPED)
1971                                 Con_Print(" COLORMAPPED");
1972                         if (s->flags & RENDER_SHADOW)
1973                                 Con_Print(" SHADOW");
1974                         if (s->flags & RENDER_LIGHT)
1975                                 Con_Print(" LIGHT");
1976                         Con_Print(")");
1977                 }
1978                 if (bits & E5_ALPHA)
1979                         Con_Printf(" E5_ALPHA %f", s->alpha / 255.0f);
1980                 if (bits & E5_SCALE)
1981                         Con_Printf(" E5_SCALE %f", s->scale / 16.0f);
1982                 if (bits & E5_COLORMAP)
1983                         Con_Printf(" E5_COLORMAP %i", s->colormap);
1984                 if (bits & E5_ATTACHMENT)
1985                         Con_Printf(" E5_ATTACHMENT e%i:%i", s->tagentity, s->tagindex);
1986                 if (bits & E5_LIGHT)
1987                         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);
1988                 if (bits & E5_GLOW)
1989                         Con_Printf(" E5_GLOW %i:%i", s->glowsize * 4, s->glowcolor);
1990                 if (bits & E5_COLORMOD)
1991                         Con_Printf(" E5_COLORMOD %f:%f:%f", s->colormod[0] / 32.0f, s->colormod[1] / 32.0f, s->colormod[2] / 32.0f);
1992                 Con_Print("\n");
1993         }
1994 }
1995
1996 int EntityState5_DeltaBits(const entity_state_t *o, const entity_state_t *n)
1997 {
1998         unsigned int bits = 0;
1999         if (n->active)
2000         {
2001                 if (!o->active)
2002                         bits |= E5_FULLUPDATE;
2003                 if (!VectorCompare(o->origin, n->origin))
2004                         bits |= E5_ORIGIN;
2005                 if (!VectorCompare(o->angles, n->angles))
2006                         bits |= E5_ANGLES;
2007                 if (o->modelindex != n->modelindex)
2008                         bits |= E5_MODEL;
2009                 if (o->frame != n->frame)
2010                         bits |= E5_FRAME;
2011                 if (o->skin != n->skin)
2012                         bits |= E5_SKIN;
2013                 if (o->effects != n->effects)
2014                         bits |= E5_EFFECTS;
2015                 if (o->flags != n->flags)
2016                         bits |= E5_FLAGS;
2017                 if (o->alpha != n->alpha)
2018                         bits |= E5_ALPHA;
2019                 if (o->scale != n->scale)
2020                         bits |= E5_SCALE;
2021                 if (o->colormap != n->colormap)
2022                         bits |= E5_COLORMAP;
2023                 if (o->tagentity != n->tagentity || o->tagindex != n->tagindex)
2024                         bits |= E5_ATTACHMENT;
2025                 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)
2026                         bits |= E5_LIGHT;
2027                 if (o->glowsize != n->glowsize || o->glowcolor != n->glowcolor)
2028                         bits |= E5_GLOW;
2029                 if (o->colormod[0] != n->colormod[0] || o->colormod[1] != n->colormod[1] || o->colormod[2] != n->colormod[2])
2030                         bits |= E5_COLORMOD;
2031         }
2032         else
2033                 if (o->active)
2034                         bits |= E5_FULLUPDATE;
2035         return bits;
2036 }
2037
2038 void EntityFrame5_CL_ReadFrame(void)
2039 {
2040         int i, n, enumber;
2041         entity_t *ent;
2042         entity_state_t *s;
2043         // read the number of this frame to echo back in next input packet
2044         for (i = 0;i < LATESTFRAMENUMS-1;i++)
2045                 cl.latestframenums[i] = cl.latestframenums[i+1];
2046         cl.latestframenums[LATESTFRAMENUMS-1] = MSG_ReadLong();
2047         if (developer_networkentities.integer)
2048                 Con_Printf("recv: svc_entities %i\n", cl.latestframenums[LATESTFRAMENUMS-1]);
2049         if (cls.protocol != PROTOCOL_QUAKE && cls.protocol != PROTOCOL_QUAKEDP && cls.protocol != PROTOCOL_NEHAHRAMOVIE && cls.protocol != PROTOCOL_DARKPLACES1 && cls.protocol != PROTOCOL_DARKPLACES2 && cls.protocol != PROTOCOL_DARKPLACES3 && cls.protocol != PROTOCOL_DARKPLACES4 && cls.protocol != PROTOCOL_DARKPLACES5 && cls.protocol != PROTOCOL_DARKPLACES6)
2050                 cl.servermovesequence = MSG_ReadLong();
2051         // read entity numbers until we find a 0x8000
2052         // (which would be remove world entity, but is actually a terminator)
2053         while ((n = (unsigned short)MSG_ReadShort()) != 0x8000 && !msg_badread)
2054         {
2055                 // get the entity number
2056                 enumber = n & 0x7FFF;
2057                 // we may need to expand the array
2058                 if (cl.num_entities <= enumber)
2059                 {
2060                         cl.num_entities = enumber + 1;
2061                         if (enumber >= cl.max_entities)
2062                                 CL_ExpandEntities(enumber);
2063                 }
2064                 // look up the entity
2065                 ent = cl.entities + enumber;
2066                 // slide the current into the previous slot
2067                 ent->state_previous = ent->state_current;
2068                 // read the update
2069                 s = &ent->state_current;
2070                 if (n & 0x8000)
2071                 {
2072                         // remove entity
2073                         *s = defaultstate;
2074                 }
2075                 else
2076                 {
2077                         // update entity
2078                         EntityState5_ReadUpdate(s);
2079                 }
2080                 // set the cl.entities_active flag
2081                 cl.entities_active[enumber] = s->active;
2082                 // set the update time
2083                 s->time = cl.mtime[0];
2084                 // fix the number (it gets wiped occasionally by copying from defaultstate)
2085                 s->number = enumber;
2086                 // check if we need to update the lerp stuff
2087                 if (s->active)
2088                         CL_MoveLerpEntityStates(&cl.entities[enumber]);
2089                 // print extra messages if desired
2090                 if (developer_networkentities.integer >= 2 && cl.entities[enumber].state_current.active != cl.entities[enumber].state_previous.active)
2091                 {
2092                         if (cl.entities[enumber].state_current.active)
2093                                 Con_Printf("entity #%i has become active\n", enumber);
2094                         else if (cl.entities[enumber].state_previous.active)
2095                                 Con_Printf("entity #%i has become inactive\n", enumber);
2096                 }
2097         }
2098 }
2099
2100 void EntityFrame5_LostFrame(entityframe5_database_t *d, int framenum)
2101 {
2102         int i, j, k, l, bits;
2103         entityframe5_changestate_t *s, *s2;
2104         entityframe5_packetlog_t *p, *p2;
2105         unsigned char statsdeltabits[(MAX_CL_STATS+7)/8];
2106         // scan for packets that were lost
2107         for (i = 0, p = d->packetlog;i < ENTITYFRAME5_MAXPACKETLOGS;i++, p++)
2108         {
2109                 if (p->packetnumber && p->packetnumber <= framenum)
2110                 {
2111                         // packet was lost - merge deltabits into the main array so they
2112                         // will be re-sent, but only if there is no newer update of that
2113                         // bit in the logs (as those will arrive before this update)
2114                         for (j = 0, s = p->states;j < p->numstates;j++, s++)
2115                         {
2116                                 // check for any newer updates to this entity and mask off any
2117                                 // overlapping bits (we don't need to send something again if
2118                                 // it has already been sent more recently)
2119                                 bits = s->bits & ~d->deltabits[s->number];
2120                                 for (k = 0, p2 = d->packetlog;k < ENTITYFRAME5_MAXPACKETLOGS && bits;k++, p2++)
2121                                 {
2122                                         if (p2->packetnumber > framenum)
2123                                         {
2124                                                 for (l = 0, s2 = p2->states;l < p2->numstates;l++, s2++)
2125                                                 {
2126                                                         if (s2->number == s->number)
2127                                                         {
2128                                                                 bits &= ~s2->bits;
2129                                                                 break;
2130                                                         }
2131                                                 }
2132                                         }
2133                                 }
2134                                 // if the bits haven't all been cleared, there were some bits
2135                                 // lost with this packet, so set them again now
2136                                 if (bits)
2137                                 {
2138                                         d->deltabits[s->number] |= bits;
2139                                         d->priorities[s->number] = EntityState5_Priority(d, s->number);
2140                                 }
2141                         }
2142                         // mark lost stats
2143                         for (j = 0;j < MAX_CL_STATS;j++)
2144                         {
2145                                 for (l = 0;l < (MAX_CL_STATS+7)/8;l++)
2146                                         statsdeltabits[l] = p->statsdeltabits[l] & ~d->statsdeltabits[l];
2147                                 for (k = 0, p2 = d->packetlog;k < ENTITYFRAME5_MAXPACKETLOGS;k++, p2++)
2148                                         if (p2->packetnumber > framenum)
2149                                                 for (l = 0;l < (MAX_CL_STATS+7)/8;l++)
2150                                                         statsdeltabits[l] = p->statsdeltabits[l] & ~p2->statsdeltabits[l];
2151                                 for (l = 0;l < (MAX_CL_STATS+7)/8;l++)
2152                                         d->statsdeltabits[l] |= statsdeltabits[l];
2153                         }
2154                         // delete this packet log as it is now obsolete
2155                         p->packetnumber = 0;
2156                 }
2157         }
2158 }
2159
2160 void EntityFrame5_AckFrame(entityframe5_database_t *d, int framenum)
2161 {
2162         int i;
2163         // scan for packets made obsolete by this ack and delete them
2164         for (i = 0;i < ENTITYFRAME5_MAXPACKETLOGS;i++)
2165                 if (d->packetlog[i].packetnumber <= framenum)
2166                         d->packetlog[i].packetnumber = 0;
2167 }
2168
2169 void EntityFrame5_WriteFrame(sizebuf_t *msg, entityframe5_database_t *d, int numstates, const entity_state_t *states, int viewentnum, int *stats, int movesequence)
2170 {
2171         const entity_state_t *n;
2172         int i, num, l, framenum, packetlognumber, priority;
2173         sizebuf_t buf;
2174         unsigned char data[128];
2175         entityframe5_packetlog_t *packetlog;
2176
2177         if (prog->max_edicts > d->maxedicts)
2178                 EntityFrame5_ExpandEdicts(d, prog->max_edicts);
2179
2180         framenum = d->latestframenum + 1;
2181         d->viewentnum = viewentnum;
2182
2183         // if packet log is full, mark all frames as lost, this will cause
2184         // it to send the lost data again
2185         for (packetlognumber = 0;packetlognumber < ENTITYFRAME5_MAXPACKETLOGS;packetlognumber++)
2186                 if (d->packetlog[packetlognumber].packetnumber == 0)
2187                         break;
2188         if (packetlognumber == ENTITYFRAME5_MAXPACKETLOGS)
2189         {
2190                 Con_DPrintf("EntityFrame5_WriteFrame: packetlog overflow for a client, resetting\n");
2191                 EntityFrame5_LostFrame(d, framenum);
2192                 packetlognumber = 0;
2193         }
2194
2195         // prepare the buffer
2196         memset(&buf, 0, sizeof(buf));
2197         buf.data = data;
2198         buf.maxsize = sizeof(data);
2199
2200         // detect changes in stats
2201         for (i = 0;i < MAX_CL_STATS;i++)
2202         {
2203                 if (d->stats[i] != stats[i])
2204                 {
2205                         d->statsdeltabits[i>>3] |= (1<<(i&7));
2206                         d->stats[i] = stats[i];
2207                 }
2208         }
2209
2210         // detect changes in states
2211         num = 0;
2212         for (i = 0, n = states;i < numstates;i++, n++)
2213         {
2214                 // mark gaps in entity numbering as removed entities
2215                 for (;num < n->number;num++)
2216                 {
2217                         // if the entity used to exist, clear it
2218                         if (CHECKPVSBIT(d->visiblebits, num))
2219                         {
2220                                 CLEARPVSBIT(d->visiblebits, num);
2221                                 d->deltabits[num] = E5_FULLUPDATE;
2222                                 d->priorities[num] = EntityState5_Priority(d, num);
2223                                 d->states[num] = defaultstate;
2224                                 d->states[num].number = num;
2225                         }
2226                 }
2227                 // update the entity state data
2228                 if (!CHECKPVSBIT(d->visiblebits, num))
2229                 {
2230                         // entity just spawned in, don't let it completely hog priority
2231                         // because of being ancient on the first frame
2232                         d->updateframenum[num] = framenum;
2233                 }
2234                 SETPVSBIT(d->visiblebits, num);
2235                 d->deltabits[num] |= EntityState5_DeltaBits(d->states + num, n);
2236                 d->priorities[num] = EntityState5_Priority(d, num);
2237                 d->states[num] = *n;
2238                 d->states[num].number = num;
2239                 // advance to next entity so the next iteration doesn't immediately remove it
2240                 num++;
2241         }
2242         // all remaining entities are dead
2243         for (;num < d->maxedicts;num++)
2244         {
2245                 if (CHECKPVSBIT(d->visiblebits, num))
2246                 {
2247                         CLEARPVSBIT(d->visiblebits, num);
2248                         d->deltabits[num] = E5_FULLUPDATE;
2249                         d->priorities[num] = EntityState5_Priority(d, num);
2250                         d->states[num] = defaultstate;
2251                         d->states[num].number = num;
2252                 }
2253         }
2254
2255         // if there isn't at least enough room for an empty svc_entities,
2256         // don't bother trying...
2257         if (buf.cursize + 11 > buf.maxsize)
2258                 return;
2259
2260         // build lists of entities by priority level
2261         memset(entityframe5_prioritychaincounts, 0, sizeof(entityframe5_prioritychaincounts));
2262         l = 0;
2263         for (num = 0;num < d->maxedicts;num++)
2264         {
2265                 if (d->priorities[num])
2266                 {
2267                         l = num;
2268                         priority = d->priorities[num];
2269                         if (entityframe5_prioritychaincounts[priority] < ENTITYFRAME5_MAXSTATES)
2270                                 entityframe5_prioritychains[priority][entityframe5_prioritychaincounts[priority]++] = num;
2271                 }
2272         }
2273
2274         // add packetlog entry
2275         packetlog = d->packetlog + packetlognumber;
2276         packetlog->packetnumber = framenum;
2277         packetlog->numstates = 0;
2278         // write stat updates
2279         if (sv.protocol != PROTOCOL_QUAKE && sv.protocol != PROTOCOL_QUAKEDP && sv.protocol != PROTOCOL_NEHAHRAMOVIE && sv.protocol != PROTOCOL_DARKPLACES1 && sv.protocol != PROTOCOL_DARKPLACES2 && sv.protocol != PROTOCOL_DARKPLACES3 && sv.protocol != PROTOCOL_DARKPLACES4 && sv.protocol != PROTOCOL_DARKPLACES5)
2280         {
2281                 for (i = 0;i < MAX_CL_STATS && msg->cursize + 6 + 11 <= msg->maxsize;i++)
2282                 {
2283                         if (d->statsdeltabits[i>>3] & (1<<(i&7)))
2284                         {
2285                                 d->statsdeltabits[i>>3] &= ~(1<<(i&7));
2286                                 packetlog->statsdeltabits[i>>3] |= (1<<(i&7));
2287                                 if (d->stats[i] >= 0 && d->stats[i] < 256)
2288                                 {
2289                                         MSG_WriteByte(msg, svc_updatestatubyte);
2290                                         MSG_WriteByte(msg, i);
2291                                         MSG_WriteByte(msg, d->stats[i]);
2292                                 }
2293                                 else
2294                                 {
2295                                         MSG_WriteByte(msg, svc_updatestat);
2296                                         MSG_WriteByte(msg, i);
2297                                         MSG_WriteLong(msg, d->stats[i]);
2298                                 }
2299                         }
2300                 }
2301         }
2302         // write state updates
2303         if (developer_networkentities.integer)
2304                 Con_Printf("send: svc_entities %i\n", framenum);
2305         d->latestframenum = framenum;
2306         MSG_WriteByte(msg, svc_entities);
2307         MSG_WriteLong(msg, framenum);
2308         if (sv.protocol != PROTOCOL_QUAKE && sv.protocol != PROTOCOL_QUAKEDP && sv.protocol != PROTOCOL_NEHAHRAMOVIE && sv.protocol != PROTOCOL_DARKPLACES1 && sv.protocol != PROTOCOL_DARKPLACES2 && sv.protocol != PROTOCOL_DARKPLACES3 && sv.protocol != PROTOCOL_DARKPLACES4 && sv.protocol != PROTOCOL_DARKPLACES5 && sv.protocol != PROTOCOL_DARKPLACES6)
2309                 MSG_WriteLong(msg, movesequence);
2310         for (priority = E5_PROTOCOL_PRIORITYLEVELS - 1;priority >= 0 && packetlog->numstates < ENTITYFRAME5_MAXSTATES;priority--)
2311         {
2312                 for (i = 0;i < entityframe5_prioritychaincounts[priority] && packetlog->numstates < ENTITYFRAME5_MAXSTATES;i++)
2313                 {
2314                         num = entityframe5_prioritychains[priority][i];
2315                         n = d->states + num;
2316                         if (d->deltabits[num] & E5_FULLUPDATE)
2317                                 d->deltabits[num] = E5_FULLUPDATE | EntityState5_DeltaBits(&defaultstate, n);
2318                         buf.cursize = 0;
2319                         EntityState5_WriteUpdate(num, n, d->deltabits[num], &buf);
2320                         // if the entity won't fit, try the next one
2321                         if (msg->cursize + buf.cursize + 2 > msg->maxsize)
2322                                 continue;
2323                         // write entity to the packet
2324                         SZ_Write(msg, buf.data, buf.cursize);
2325                         // mark age on entity for prioritization
2326                         d->updateframenum[num] = framenum;
2327                         // log entity so deltabits can be restored later if lost
2328                         packetlog->states[packetlog->numstates].number = num;
2329                         packetlog->states[packetlog->numstates].bits = d->deltabits[num];
2330                         packetlog->numstates++;
2331                         // clear deltabits and priority so it won't be sent again
2332                         d->deltabits[num] = 0;
2333                         d->priorities[num] = 0;
2334                 }
2335         }
2336         MSG_WriteShort(msg, 0x8000);
2337 }
2338
2339
2340 static int QW_TranslateEffects(int qweffects, int number)
2341 {
2342         int effects = 0;
2343         if (qweffects & QW_EF_BRIGHTFIELD)
2344                 effects |= EF_BRIGHTFIELD;
2345         if (qweffects & QW_EF_MUZZLEFLASH)
2346                 effects |= EF_MUZZLEFLASH;
2347         if (qweffects & QW_EF_FLAG1)
2348         {
2349                 // mimic FTEQW's interpretation of EF_FLAG1 as EF_NODRAW on non-player entities
2350                 if (number > cl.maxclients)
2351                         effects |= EF_NODRAW;
2352                 else
2353                         effects |= EF_FLAG1QW;
2354         }
2355         if (qweffects & QW_EF_FLAG2)
2356         {
2357                 // mimic FTEQW's interpretation of EF_FLAG2 as EF_ADDITIVE on non-player entities
2358                 if (number > cl.maxclients)
2359                         effects |= EF_ADDITIVE;
2360                 else
2361                         effects |= EF_FLAG2QW;
2362         }
2363         if (qweffects & QW_EF_RED)
2364         {
2365                 if (qweffects & QW_EF_BLUE)
2366                         effects |= EF_RED | EF_BLUE;
2367                 else
2368                         effects |= EF_RED;
2369         }
2370         else if (qweffects & QW_EF_BLUE)
2371                 effects |= EF_BLUE;
2372         else if (qweffects & QW_EF_BRIGHTLIGHT)
2373                 effects |= EF_BRIGHTLIGHT;
2374         else if (qweffects & QW_EF_DIMLIGHT)
2375                 effects |= EF_DIMLIGHT;
2376         return effects;
2377 }
2378
2379 void EntityStateQW_ReadPlayerUpdate(void)
2380 {
2381         int slot = MSG_ReadByte();
2382         int enumber = slot + 1;
2383         int weaponframe;
2384         int msec;
2385         int playerflags;
2386         int bits;
2387         entity_state_t *s;
2388         // look up the entity
2389         entity_t *ent = cl.entities + enumber;
2390         vec3_t viewangles;
2391         vec3_t velocity;
2392
2393         // slide the current state into the previous
2394         ent->state_previous = ent->state_current;
2395
2396         // read the update
2397         s = &ent->state_current;
2398         *s = defaultstate;
2399         s->active = true;
2400         s->colormap = enumber;
2401         playerflags = MSG_ReadShort();
2402         MSG_ReadVector(s->origin, cls.protocol);
2403         s->frame = MSG_ReadByte();
2404
2405         VectorClear(viewangles);
2406         VectorClear(velocity);
2407
2408         if (playerflags & QW_PF_MSEC)
2409         {
2410                 // time difference between last update this player sent to the server,
2411                 // and last input we sent to the server (this packet is in response to
2412                 // our input, so msec is how long ago the last update of this player
2413                 // entity occurred, compared to our input being received)
2414                 msec = MSG_ReadByte();
2415         }
2416         else
2417                 msec = 0;
2418         if (playerflags & QW_PF_COMMAND)
2419         {
2420                 bits = MSG_ReadByte();
2421                 if (bits & QW_CM_ANGLE1)
2422                         viewangles[0] = MSG_ReadAngle16i(); // cmd->angles[0]
2423                 if (bits & QW_CM_ANGLE2)
2424                         viewangles[1] = MSG_ReadAngle16i(); // cmd->angles[1]
2425                 if (bits & QW_CM_ANGLE3)
2426                         viewangles[2] = MSG_ReadAngle16i(); // cmd->angles[2]
2427                 if (bits & QW_CM_FORWARD)
2428                         MSG_ReadShort(); // cmd->forwardmove
2429                 if (bits & QW_CM_SIDE)
2430                         MSG_ReadShort(); // cmd->sidemove
2431                 if (bits & QW_CM_UP)
2432                         MSG_ReadShort(); // cmd->upmove
2433                 if (bits & QW_CM_BUTTONS)
2434                         MSG_ReadByte(); // cmd->buttons
2435                 if (bits & QW_CM_IMPULSE)
2436                         MSG_ReadByte(); // cmd->impulse
2437                 MSG_ReadByte(); // cmd->msec
2438         }
2439         if (playerflags & QW_PF_VELOCITY1)
2440                 velocity[0] = MSG_ReadShort();
2441         if (playerflags & QW_PF_VELOCITY2)
2442                 velocity[1] = MSG_ReadShort();
2443         if (playerflags & QW_PF_VELOCITY3)
2444                 velocity[2] = MSG_ReadShort();
2445         if (playerflags & QW_PF_MODEL)
2446                 s->modelindex = MSG_ReadByte();
2447         else
2448                 s->modelindex = cl.qw_modelindex_player;
2449         if (playerflags & QW_PF_SKINNUM)
2450                 s->skin = MSG_ReadByte();
2451         if (playerflags & QW_PF_EFFECTS)
2452                 s->effects = QW_TranslateEffects(MSG_ReadByte(), enumber);
2453         if (playerflags & QW_PF_WEAPONFRAME)
2454                 weaponframe = MSG_ReadByte();
2455         else
2456                 weaponframe = 0;
2457
2458         if (enumber == cl.playerentity)
2459         {
2460                 // if this is an update on our player, update the angles
2461                 VectorCopy(cl.viewangles, viewangles);
2462         }
2463
2464         // calculate the entity angles from the viewangles
2465         s->angles[0] = viewangles[0] * -0.0333;
2466         s->angles[1] = viewangles[1];
2467         s->angles[2] = 0;
2468         s->angles[2] = V_CalcRoll(s->angles, velocity)*4;
2469
2470         // if this is an update on our player, update interpolation state
2471         if (enumber == cl.playerentity)
2472         {
2473                 VectorCopy (cl.mpunchangle[0], cl.mpunchangle[1]);
2474                 VectorCopy (cl.mpunchvector[0], cl.mpunchvector[1]);
2475                 VectorCopy (cl.mvelocity[0], cl.mvelocity[1]);
2476                 cl.mviewzoom[1] = cl.mviewzoom[0];
2477
2478                 cl.idealpitch = 0;
2479                 cl.mpunchangle[0][0] = 0;
2480                 cl.mpunchangle[0][1] = 0;
2481                 cl.mpunchangle[0][2] = 0;
2482                 cl.mpunchvector[0][0] = 0;
2483                 cl.mpunchvector[0][1] = 0;
2484                 cl.mpunchvector[0][2] = 0;
2485                 cl.mvelocity[0][0] = 0;
2486                 cl.mvelocity[0][1] = 0;
2487                 cl.mvelocity[0][2] = 0;
2488                 cl.mviewzoom[0] = 1;
2489
2490                 VectorCopy(velocity, cl.mvelocity[0]);
2491                 cl.stats[STAT_WEAPONFRAME] = weaponframe;
2492                 if (playerflags & QW_PF_GIB)
2493                         cl.stats[STAT_VIEWHEIGHT] = 8;
2494                 else if (playerflags & QW_PF_DEAD)
2495                         cl.stats[STAT_VIEWHEIGHT] = -16;
2496                 else
2497                         cl.stats[STAT_VIEWHEIGHT] = 22;
2498         }
2499
2500         // set the cl.entities_active flag
2501         cl.entities_active[enumber] = s->active;
2502         // set the update time
2503         s->time = cl.mtime[0] - msec * 0.001; // qw has no clock
2504         // fix the number (it gets wiped occasionally by copying from defaultstate)
2505         s->number = enumber;
2506         // check if we need to update the lerp stuff
2507         if (s->active)
2508                 CL_MoveLerpEntityStates(&cl.entities[enumber]);
2509 }
2510
2511 static void EntityStateQW_ReadEntityUpdate(entity_state_t *s, int bits)
2512 {
2513         int qweffects = 0;
2514         s->active = true;
2515         s->number = bits & 511;
2516         bits &= ~511;
2517         if (bits & QW_U_MOREBITS)
2518                 bits |= MSG_ReadByte();
2519
2520         // store the QW_U_SOLID bit here?
2521
2522         if (bits & QW_U_MODEL)
2523                 s->modelindex = MSG_ReadByte();
2524         if (bits & QW_U_FRAME)
2525                 s->frame = MSG_ReadByte();
2526         if (bits & QW_U_COLORMAP)
2527                 s->colormap = MSG_ReadByte();
2528         if (bits & QW_U_SKIN)
2529                 s->skin = MSG_ReadByte();
2530         if (bits & QW_U_EFFECTS)
2531                 s->effects = QW_TranslateEffects(qweffects = MSG_ReadByte(), s->number);
2532         if (bits & QW_U_ORIGIN1)
2533                 s->origin[0] = MSG_ReadCoord13i();
2534         if (bits & QW_U_ANGLE1)
2535                 s->angles[0] = MSG_ReadAngle8i();
2536         if (bits & QW_U_ORIGIN2)
2537                 s->origin[1] = MSG_ReadCoord13i();
2538         if (bits & QW_U_ANGLE2)
2539                 s->angles[1] = MSG_ReadAngle8i();
2540         if (bits & QW_U_ORIGIN3)
2541                 s->origin[2] = MSG_ReadCoord13i();
2542         if (bits & QW_U_ANGLE3)
2543                 s->angles[2] = MSG_ReadAngle8i();
2544
2545         if (developer_networkentities.integer >= 2)
2546         {
2547                 Con_Printf("ReadFields e%i", s->number);
2548                 if (bits & QW_U_MODEL)
2549                         Con_Printf(" U_MODEL %i", s->modelindex);
2550                 if (bits & QW_U_FRAME)
2551                         Con_Printf(" U_FRAME %i", s->frame);
2552                 if (bits & QW_U_COLORMAP)
2553                         Con_Printf(" U_COLORMAP %i", s->colormap);
2554                 if (bits & QW_U_SKIN)
2555                         Con_Printf(" U_SKIN %i", s->skin);
2556                 if (bits & QW_U_EFFECTS)
2557                         Con_Printf(" U_EFFECTS %i", qweffects);
2558                 if (bits & QW_U_ORIGIN1)
2559                         Con_Printf(" U_ORIGIN1 %f", s->origin[0]);
2560                 if (bits & QW_U_ANGLE1)
2561                         Con_Printf(" U_ANGLE1 %f", s->angles[0]);
2562                 if (bits & QW_U_ORIGIN2)
2563                         Con_Printf(" U_ORIGIN2 %f", s->origin[1]);
2564                 if (bits & QW_U_ANGLE2)
2565                         Con_Printf(" U_ANGLE2 %f", s->angles[1]);
2566                 if (bits & QW_U_ORIGIN3)
2567                         Con_Printf(" U_ORIGIN3 %f", s->origin[2]);
2568                 if (bits & QW_U_ANGLE3)
2569                         Con_Printf(" U_ANGLE3 %f", s->angles[2]);
2570                 if (bits & QW_U_SOLID)
2571                         Con_Printf(" U_SOLID");
2572                 Con_Print("\n");
2573         }
2574 }
2575
2576 entityframeqw_database_t *EntityFrameQW_AllocDatabase(mempool_t *pool)
2577 {
2578         entityframeqw_database_t *d;
2579         d = (entityframeqw_database_t *)Mem_Alloc(pool, sizeof(*d));
2580         return d;
2581 }
2582
2583 void EntityFrameQW_FreeDatabase(entityframeqw_database_t *d)
2584 {
2585         Mem_Free(d);
2586 }
2587
2588 void EntityFrameQW_CL_ReadFrame(qboolean delta)
2589 {
2590         qboolean invalid = false;
2591         int number, oldsnapindex, newsnapindex, oldindex, newindex, oldnum, newnum;
2592         entity_t *ent;
2593         entityframeqw_database_t *d;
2594         entityframeqw_snapshot_t *oldsnap, *newsnap;
2595
2596         if (!cl.entitydatabaseqw)
2597                 cl.entitydatabaseqw = EntityFrameQW_AllocDatabase(cls.levelmempool);
2598         d = cl.entitydatabaseqw;
2599
2600         newsnapindex = cls.netcon->qw.incoming_sequence & QW_UPDATE_MASK;
2601         newsnap = d->snapshot + newsnapindex;
2602         memset(newsnap, 0, sizeof(*newsnap));
2603         oldsnapindex = -1;
2604         oldsnap = NULL;
2605         if (delta)
2606         {
2607                 number = MSG_ReadByte();
2608                 oldsnapindex = cl.qw_deltasequence[newsnapindex];
2609                 if ((number & QW_UPDATE_MASK) != (oldsnapindex & QW_UPDATE_MASK))
2610                         Con_DPrintf("WARNING: from mismatch\n");
2611                 if (oldsnapindex != -1)
2612                 {
2613                         if (cls.netcon->qw.outgoing_sequence - oldsnapindex >= QW_UPDATE_BACKUP-1)
2614                         {
2615                                 Con_DPrintf("delta update too old\n");
2616                                 newsnap->invalid = invalid = true; // too old
2617                                 delta = false;
2618                         }
2619                         oldsnap = d->snapshot + (oldsnapindex & QW_UPDATE_MASK);
2620                 }
2621                 else
2622                         delta = false;
2623         }
2624
2625         // read the number of this frame to echo back in next input packet
2626         cl.qw_validsequence = cls.netcon->qw.incoming_sequence;
2627         if (invalid)
2628                 cl.qw_validsequence = 0;
2629
2630         // read entity numbers until we find a 0x0000
2631         // (which would be an empty update on world entity, but is actually a terminator)
2632         newsnap->num_entities = 0;
2633         oldindex = 0;
2634         for (;;)
2635         {
2636                 int word = (unsigned short)MSG_ReadShort();
2637                 if (msg_badread)
2638                         return; // just return, the main parser will print an error
2639                 newnum = word == 0 ? 512 : (word & 511);
2640                 oldnum = delta ? (oldindex >= oldsnap->num_entities ? 9999 : oldsnap->entities[oldindex].number) : 9999;
2641
2642                 // copy unmodified oldsnap entities
2643                 while (newnum > oldnum) // delta only
2644                 {
2645                         if (developer_networkentities.integer >= 2)
2646                                 Con_Printf("copy %i\n", oldnum);
2647                         // copy one of the old entities
2648                         if (newsnap->num_entities >= QW_MAX_PACKET_ENTITIES)
2649                                 Host_Error("EntityFrameQW_CL_ReadFrame: newsnap->num_entities == MAX_PACKETENTITIES");
2650                         newsnap->entities[newsnap->num_entities] = oldsnap->entities[oldindex++];
2651                         newsnap->num_entities++;
2652                         oldnum = oldindex >= oldsnap->num_entities ? 9999 : oldsnap->entities[oldindex].number;
2653                 }
2654
2655                 if (word == 0)
2656                         break;
2657
2658                 if (developer_networkentities.integer >= 2)
2659                 {
2660                         if (word & QW_U_REMOVE)
2661                                 Con_Printf("remove %i\n", newnum);
2662                         else if (newnum == oldnum)
2663                                 Con_Printf("delta %i\n", newnum);
2664                         else
2665                                 Con_Printf("baseline %i\n", newnum);
2666                 }
2667
2668                 if (word & QW_U_REMOVE)
2669                 {
2670                         if (newnum != oldnum && !delta && !invalid)
2671                         {
2672                                 cl.qw_validsequence = 0;
2673                                 Con_Printf("WARNING: U_REMOVE %i on full update\n", newnum);
2674                         }
2675                 }
2676                 else
2677                 {
2678                         if (newsnap->num_entities >= QW_MAX_PACKET_ENTITIES)
2679                                 Host_Error("EntityFrameQW_CL_ReadFrame: newsnap->num_entities == MAX_PACKETENTITIES");
2680                         newsnap->entities[newsnap->num_entities] = (newnum == oldnum) ? oldsnap->entities[oldindex] : cl.entities[newnum].state_baseline;
2681                         EntityStateQW_ReadEntityUpdate(newsnap->entities + newsnap->num_entities, word);
2682                         newsnap->num_entities++;
2683                 }
2684
2685                 if (newnum == oldnum)
2686                         oldindex++;
2687         }
2688
2689         // expand cl.num_entities to include every entity we've seen this game
2690         newnum = newsnap->num_entities ? newsnap->entities[newsnap->num_entities - 1].number : 1;
2691         if (cl.num_entities <= newnum)
2692         {
2693                 cl.num_entities = newnum + 1;
2694                 if (cl.max_entities < newnum + 1)
2695                         CL_ExpandEntities(newnum);
2696         }
2697
2698         // now update the non-player entities from the snapshot states
2699         number = cl.maxclients + 1;
2700         for (newindex = 0;;newindex++)
2701         {
2702                 newnum = newindex >= newsnap->num_entities ? cl.num_entities : newsnap->entities[newindex].number;
2703                 // kill any missing entities
2704                 for (;number < newnum;number++)
2705                 {
2706                         if (cl.entities_active[number])
2707                         {
2708                                 cl.entities_active[number] = false;
2709                                 cl.entities[number].state_current.active = false;
2710                         }
2711                 }
2712                 if (number >= cl.num_entities)
2713                         break;
2714                 // update the entity
2715                 ent = &cl.entities[number];
2716                 ent->state_previous = ent->state_current;
2717                 ent->state_current = newsnap->entities[newindex];
2718                 ent->state_current.time = cl.mtime[0];
2719                 CL_MoveLerpEntityStates(ent);
2720                 // the entity lives again...
2721                 cl.entities_active[number] = true;
2722                 number++;
2723         }
2724 }