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