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