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