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