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