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