fixed the huge networking problems regarding invalid reference frames
[divverent/darkplaces.git] / protocol.c
1
2 #include "quakedef.h"
3
4 entity_state_t defaultstate =
5 {
6         0,//double time; // time this state was built
7         {0,0,0},//vec3_t origin;
8         {0,0,0},//vec3_t angles;
9         0,//int number; // entity number this state is for
10         0,//unsigned short active; // true if a valid state
11         0,//unsigned short modelindex;
12         0,//unsigned short frame;
13         0,//unsigned short effects;
14         0,//unsigned short tagentity;
15         0,//unsigned short specialvisibilityradius;
16         0,//unsigned short viewmodelforclient;
17         0,//unsigned short exteriormodelforclient;
18         0,//unsigned short nodrawtoclient;
19         0,//unsigned short drawonlytoclient;
20         {0,0,0,0},//short light[4];
21         0,//qbyte lightstyle;
22         0,//qbyte lightpflags;
23         0,//qbyte colormap;
24         0,//qbyte skin;
25         255,//qbyte alpha;
26         16,//qbyte scale;
27         0,//qbyte glowsize;
28         254,//qbyte glowcolor;
29         0,//qbyte flags;
30         0,//qbyte tagindex;
31         {0,0,0,0,0,0}//qbyte unused[6];
32 };
33
34 void ClearStateToDefault(entity_state_t *s)
35 {
36         *s = defaultstate;
37         /*
38         memset(s, 0, sizeof(*s));
39         s->alpha = 255;
40         s->scale = 16;
41         s->glowcolor = 254;
42         */
43 }
44
45 void EntityState_Write(entity_state_t *ent, sizebuf_t *msg, entity_state_t *delta)
46 {
47         int bits;
48         vec3_t org, deltaorg;
49         if (ent->active)
50         {
51                 // if not active last frame, delta from defaults
52                 if (!delta->active)
53                         delta = &defaultstate;
54                 bits = 0;
55                 VectorCopy(ent->origin, org);
56                 VectorCopy(delta->origin, deltaorg);
57                 if (ent->flags & RENDER_LOWPRECISION)
58                 {
59                         if (org[0] > 0)
60                                 org[0] = (int) (org[0] + 0.5f);
61                         else
62                                 org[0] = (int) (org[0] - 0.5f);
63                         if (org[1] > 0)
64                                 org[1] = (int) (org[1] + 0.5f);
65                         else
66                                 org[1] = (int) (org[1] - 0.5f);
67                         if (org[2] > 0)
68                                 org[2] = (int) (org[2] + 0.5f);
69                         else
70                                 org[2] = (int) (org[2] - 0.5f);
71                 }
72                 if (delta->flags & RENDER_LOWPRECISION)
73                 {
74                         if (deltaorg[0] > 0)
75                                 deltaorg[0] = (int) (deltaorg[0] + 0.5f);
76                         else
77                                 deltaorg[0] = (int) (deltaorg[0] - 0.5f);
78                         if (deltaorg[1] > 0)
79                                 deltaorg[1] = (int) (deltaorg[1] + 0.5f);
80                         else
81                                 deltaorg[1] = (int) (deltaorg[1] - 0.5f);
82                         if (deltaorg[2] > 0)
83                                 deltaorg[2] = (int) (deltaorg[2] + 0.5f);
84                         else
85                                 deltaorg[2] = (int) (deltaorg[2] - 0.5f);
86                 }
87                 if (fabs(org[0] - deltaorg[0]) > 0.01f)
88                         bits |= E_ORIGIN1;
89                 if (fabs(org[1] - deltaorg[1]) > 0.01f)
90                         bits |= E_ORIGIN2;
91                 if (fabs(org[2] - deltaorg[2]) > 0.01f)
92                         bits |= E_ORIGIN3;
93                 if ((qbyte) (ent->angles[0] * (256.0f / 360.0f)) != (qbyte) (delta->angles[0] * (256.0f / 360.0f)))
94                         bits |= E_ANGLE1;
95                 if ((qbyte) (ent->angles[1] * (256.0f / 360.0f)) != (qbyte) (delta->angles[1] * (256.0f / 360.0f)))
96                         bits |= E_ANGLE2;
97                 if ((qbyte) (ent->angles[2] * (256.0f / 360.0f)) != (qbyte) (delta->angles[2] * (256.0f / 360.0f)))
98                         bits |= E_ANGLE3;
99                 if ((ent->modelindex ^ delta->modelindex) & 0x00FF)
100                         bits |= E_MODEL1;
101                 if ((ent->modelindex ^ delta->modelindex) & 0xFF00)
102                         bits |= E_MODEL2;
103                 if ((ent->frame ^ delta->frame) & 0x00FF)
104                         bits |= E_FRAME1;
105                 if ((ent->frame ^ delta->frame) & 0xFF00)
106                         bits |= E_FRAME2;
107                 if ((ent->effects ^ delta->effects) & 0x00FF)
108                         bits |= E_EFFECTS1;
109                 if ((ent->effects ^ delta->effects) & 0xFF00)
110                         bits |= E_EFFECTS2;
111                 if (ent->colormap != delta->colormap)
112                         bits |= E_COLORMAP;
113                 if (ent->skin != delta->skin)
114                         bits |= E_SKIN;
115                 if (ent->alpha != delta->alpha)
116                         bits |= E_ALPHA;
117                 if (ent->scale != delta->scale)
118                         bits |= E_SCALE;
119                 if (ent->glowsize != delta->glowsize)
120                         bits |= E_GLOWSIZE;
121                 if (ent->glowcolor != delta->glowcolor)
122                         bits |= E_GLOWCOLOR;
123                 if (ent->flags != delta->flags)
124                         bits |= E_FLAGS;
125                 if (ent->tagindex != delta->tagindex || ent->tagentity != delta->tagentity)
126                         bits |= E_TAGATTACHMENT;
127                 if (ent->light[0] != delta->light[0] || ent->light[1] != delta->light[1] || ent->light[2] != delta->light[2] || ent->light[3] != delta->light[3])
128                         bits |= E_LIGHT;
129                 if (ent->lightstyle != delta->lightstyle)
130                         bits |= E_LIGHTSTYLE;
131                 if (ent->lightpflags != delta->lightpflags)
132                         bits |= E_LIGHTPFLAGS;
133
134                 if (bits) // don't send anything if it hasn't changed
135                 {
136                         if (bits & 0xFF000000)
137                                 bits |= E_EXTEND3;
138                         if (bits & 0x00FF0000)
139                                 bits |= E_EXTEND2;
140                         if (bits & 0x0000FF00)
141                                 bits |= E_EXTEND1;
142
143                         MSG_WriteShort(msg, ent->number);
144                         MSG_WriteByte(msg, bits & 0xFF);
145                         if (bits & E_EXTEND1)
146                         {
147                                 MSG_WriteByte(msg, (bits >> 8) & 0xFF);
148                                 if (bits & E_EXTEND2)
149                                 {
150                                         MSG_WriteByte(msg, (bits >> 16) & 0xFF);
151                                         if (bits & E_EXTEND3)
152                                                 MSG_WriteByte(msg, (bits >> 24) & 0xFF);
153                                 }
154                         }
155                         // LordHavoc: have to write flags first, as they can modify protocol
156                         if (bits & E_FLAGS)
157                                 MSG_WriteByte(msg, ent->flags);
158                         if (ent->flags & RENDER_LOWPRECISION)
159                         {
160                                 if (bits & E_ORIGIN1)
161                                         MSG_WriteShort(msg, org[0]);
162                                 if (bits & E_ORIGIN2)
163                                         MSG_WriteShort(msg, org[1]);
164                                 if (bits & E_ORIGIN3)
165                                         MSG_WriteShort(msg, org[2]);
166                                 if (bits & E_ANGLE1)
167                                         MSG_WriteAngle(msg, ent->angles[0]);
168                                 if (bits & E_ANGLE2)
169                                         MSG_WriteAngle(msg, ent->angles[1]);
170                                 if (bits & E_ANGLE3)
171                                         MSG_WriteAngle(msg, ent->angles[2]);
172                         }
173                         else
174                         {
175                                 if (bits & E_ORIGIN1)
176                                         MSG_WriteFloat(msg, org[0]);
177                                 if (bits & E_ORIGIN2)
178                                         MSG_WriteFloat(msg, org[1]);
179                                 if (bits & E_ORIGIN3)
180                                         MSG_WriteFloat(msg, org[2]);
181                                 if (bits & E_ANGLE1)
182                                         MSG_WritePreciseAngle(msg, ent->angles[0]);
183                                 if (bits & E_ANGLE2)
184                                         MSG_WritePreciseAngle(msg, ent->angles[1]);
185                                 if (bits & E_ANGLE3)
186                                         MSG_WritePreciseAngle(msg, ent->angles[2]);
187                         }
188                         if (bits & E_MODEL1)
189                                 MSG_WriteByte(msg, ent->modelindex & 0xFF);
190                         if (bits & E_MODEL2)
191                                 MSG_WriteByte(msg, (ent->modelindex >> 8) & 0xFF);
192                         if (bits & E_FRAME1)
193                                 MSG_WriteByte(msg, ent->frame & 0xFF);
194                         if (bits & E_FRAME2)
195                                 MSG_WriteByte(msg, (ent->frame >> 8) & 0xFF);
196                         if (bits & E_EFFECTS1)
197                                 MSG_WriteByte(msg, ent->effects & 0xFF);
198                         if (bits & E_EFFECTS2)
199                                 MSG_WriteByte(msg, (ent->effects >> 8) & 0xFF);
200                         if (bits & E_COLORMAP)
201                                 MSG_WriteByte(msg, ent->colormap);
202                         if (bits & E_SKIN)
203                                 MSG_WriteByte(msg, ent->skin);
204                         if (bits & E_ALPHA)
205                                 MSG_WriteByte(msg, ent->alpha);
206                         if (bits & E_SCALE)
207                                 MSG_WriteByte(msg, ent->scale);
208                         if (bits & E_GLOWSIZE)
209                                 MSG_WriteByte(msg, ent->glowsize);
210                         if (bits & E_GLOWCOLOR)
211                                 MSG_WriteByte(msg, ent->glowcolor);
212                         if (bits & E_TAGATTACHMENT)
213                         {
214                                 MSG_WriteShort(msg, ent->tagentity);
215                                 MSG_WriteByte(msg, ent->tagindex);
216                         }
217                         if (bits & E_LIGHT)
218                         {
219                                 MSG_WriteShort(msg, ent->light[0]);
220                                 MSG_WriteShort(msg, ent->light[1]);
221                                 MSG_WriteShort(msg, ent->light[2]);
222                                 MSG_WriteShort(msg, ent->light[3]);
223                         }
224                         if (bits & E_LIGHTSTYLE)
225                                 MSG_WriteByte(msg, ent->lightstyle);
226                         if (bits & E_LIGHTPFLAGS)
227                                 MSG_WriteByte(msg, ent->lightpflags);
228                 }
229         }
230         else if (delta->active)
231                 MSG_WriteShort(msg, ent->number | 0x8000);
232 }
233
234 void EntityState_ReadUpdate(entity_state_t *e, int number)
235 {
236         int bits;
237         cl_entities_active[number] = true;
238         e->active = true;
239         e->time = cl.mtime[0];
240         e->number = number;
241
242         bits = MSG_ReadByte();
243         if (bits & E_EXTEND1)
244         {
245                 bits |= MSG_ReadByte() << 8;
246                 if (bits & E_EXTEND2)
247                 {
248                         bits |= MSG_ReadByte() << 16;
249                         if (bits & E_EXTEND3)
250                                 bits |= MSG_ReadByte() << 24;
251                 }
252         }
253
254         if (cl.protocol == PROTOCOL_DARKPLACES2)
255         {
256                 if (bits & E_ORIGIN1)
257                         e->origin[0] = (signed short) MSG_ReadShort();
258                 if (bits & E_ORIGIN2)
259                         e->origin[1] = (signed short) MSG_ReadShort();
260                 if (bits & E_ORIGIN3)
261                         e->origin[2] = (signed short) MSG_ReadShort();
262         }
263         else
264         {
265                 if (bits & E_FLAGS)
266                         e->flags = MSG_ReadByte();
267                 if (e->flags & RENDER_LOWPRECISION || cl.protocol == PROTOCOL_DARKPLACES2)
268                 {
269                         if (bits & E_ORIGIN1)
270                                 e->origin[0] = (signed short) MSG_ReadShort();
271                         if (bits & E_ORIGIN2)
272                                 e->origin[1] = (signed short) MSG_ReadShort();
273                         if (bits & E_ORIGIN3)
274                                 e->origin[2] = (signed short) MSG_ReadShort();
275                 }
276                 else
277                 {
278                         if (bits & E_ORIGIN1)
279                                 e->origin[0] = MSG_ReadFloat();
280                         if (bits & E_ORIGIN2)
281                                 e->origin[1] = MSG_ReadFloat();
282                         if (bits & E_ORIGIN3)
283                                 e->origin[2] = MSG_ReadFloat();
284                 }
285         }
286         if (cl.protocol == PROTOCOL_DARKPLACES5 && !(e->flags & RENDER_LOWPRECISION))
287         {
288                 if (bits & E_ANGLE1)
289                         e->angles[0] = MSG_ReadPreciseAngle();
290                 if (bits & E_ANGLE2)
291                         e->angles[1] = MSG_ReadPreciseAngle();
292                 if (bits & E_ANGLE3)
293                         e->angles[2] = MSG_ReadPreciseAngle();
294         }
295         else
296         {
297                 if (bits & E_ANGLE1)
298                         e->angles[0] = MSG_ReadAngle();
299                 if (bits & E_ANGLE2)
300                         e->angles[1] = MSG_ReadAngle();
301                 if (bits & E_ANGLE3)
302                         e->angles[2] = MSG_ReadAngle();
303         }
304         if (bits & E_MODEL1)
305                 e->modelindex = (e->modelindex & 0xFF00) | (unsigned int) MSG_ReadByte();
306         if (bits & E_MODEL2)
307                 e->modelindex = (e->modelindex & 0x00FF) | ((unsigned int) MSG_ReadByte() << 8);
308         if (bits & E_FRAME1)
309                 e->frame = (e->frame & 0xFF00) | (unsigned int) MSG_ReadByte();
310         if (bits & E_FRAME2)
311                 e->frame = (e->frame & 0x00FF) | ((unsigned int) MSG_ReadByte() << 8);
312         if (bits & E_EFFECTS1)
313                 e->effects = (e->effects & 0xFF00) | (unsigned int) MSG_ReadByte();
314         if (bits & E_EFFECTS2)
315                 e->effects = (e->effects & 0x00FF) | ((unsigned int) MSG_ReadByte() << 8);
316         if (bits & E_COLORMAP)
317                 e->colormap = MSG_ReadByte();
318         if (bits & E_SKIN)
319                 e->skin = MSG_ReadByte();
320         if (bits & E_ALPHA)
321                 e->alpha = MSG_ReadByte();
322         if (bits & E_SCALE)
323                 e->scale = MSG_ReadByte();
324         if (bits & E_GLOWSIZE)
325                 e->glowsize = MSG_ReadByte();
326         if (bits & E_GLOWCOLOR)
327                 e->glowcolor = MSG_ReadByte();
328         if (cl.protocol == PROTOCOL_DARKPLACES2)
329                 if (bits & E_FLAGS)
330                         e->flags = MSG_ReadByte();
331         if (bits & E_TAGATTACHMENT)
332         {
333                 e->tagentity = MSG_ReadShort();
334                 e->tagindex = MSG_ReadByte();
335         }
336         if (bits & E_LIGHT)
337         {
338                 e->light[0] = MSG_ReadShort();
339                 e->light[1] = MSG_ReadShort();
340                 e->light[2] = MSG_ReadShort();
341                 e->light[3] = MSG_ReadShort();
342         }
343         if (bits & E_LIGHTSTYLE)
344                 e->lightstyle = MSG_ReadByte();
345         if (bits & E_LIGHTPFLAGS)
346                 e->lightpflags = MSG_ReadByte();
347
348         if (developer_networkentities.integer >= 2)
349         {
350                 Con_Printf("ReadUpdate e%i", number);
351
352                 if (bits & E_ORIGIN1)
353                         Con_Printf(" E_ORIGIN1 %f", e->origin[0]);
354                 if (bits & E_ORIGIN2)
355                         Con_Printf(" E_ORIGIN2 %f", e->origin[1]);
356                 if (bits & E_ORIGIN3)
357                         Con_Printf(" E_ORIGIN3 %f", e->origin[2]);
358                 if (bits & E_ANGLE1)
359                         Con_Printf(" E_ANGLE1 %f", e->angles[0]);
360                 if (bits & E_ANGLE2)
361                         Con_Printf(" E_ANGLE2 %f", e->angles[1]);
362                 if (bits & E_ANGLE3)
363                         Con_Printf(" E_ANGLE3 %f", e->angles[2]);
364                 if (bits & (E_MODEL1 | E_MODEL2))
365                         Con_Printf(" E_MODEL %i", e->modelindex);
366
367                 if (bits & (E_FRAME1 | E_FRAME2))
368                         Con_Printf(" E_FRAME %i", e->frame);
369                 if (bits & (E_EFFECTS1 | E_EFFECTS2))
370                         Con_Printf(" E_EFFECTS %i", e->effects);
371                 if (bits & E_ALPHA)
372                         Con_Printf(" E_ALPHA %f", e->alpha / 255.0f);
373                 if (bits & E_SCALE)
374                         Con_Printf(" E_SCALE %f", e->scale / 16.0f);
375                 if (bits & E_COLORMAP)
376                         Con_Printf(" E_COLORMAP %i", e->colormap);
377                 if (bits & E_SKIN)
378                         Con_Printf(" E_SKIN %i", e->skin);
379
380                 if (bits & E_GLOWSIZE)
381                         Con_Printf(" E_GLOWSIZE %i", e->glowsize * 4);
382                 if (bits & E_GLOWCOLOR)
383                         Con_Printf(" E_GLOWCOLOR %i", e->glowcolor);
384                 
385                 if (bits & E_LIGHT)
386                         Con_Printf(" E_LIGHT %i:%i:%i:%i", e->light[0], e->light[1], e->light[2], e->light[3]);
387                 if (bits & E_LIGHTPFLAGS)                       
388                         Con_Printf(" E_LIGHTPFLAGS %i", e->lightpflags);
389
390                 if (bits & E_TAGATTACHMENT)
391                         Con_Printf(" E_TAGATTACHMENT e%i:%i", e->tagentity, e->tagindex);
392                 if (bits & E_LIGHTSTYLE)
393                         Con_Printf(" E_LIGHTSTYLE %i", e->lightstyle);
394                 Con_Print("\n");
395         }
396 }
397
398 // (server) clears the database to contain no frames (thus delta compression compresses against nothing)
399 void EntityFrame_ClearDatabase(entity_database_t *d)
400 {
401         memset(d, 0, sizeof(*d));
402 }
403
404 // (server and client) removes frames older than 'frame' from database
405 void EntityFrame_AckFrame(entity_database_t *d, int frame)
406 {
407         int i;
408         if (d->ackframe < frame)
409                 d->ackframe = frame;
410         for (i = 0;i < d->numframes && d->frames[i].framenum < frame;i++);
411         // ignore outdated frame acks (out of order packets)
412         if (i == 0)
413                 return;
414         d->numframes -= i;
415         // if some queue is left, slide it down to beginning of array
416         if (d->numframes)
417                 memmove(&d->frames[0], &d->frames[i], sizeof(d->frames[0]) * d->numframes);
418 }
419
420 // (server) clears frame, to prepare for adding entities
421 void EntityFrame_Clear(entity_frame_t *f, vec3_t eye, int framenum)
422 {
423         f->time = 0;
424         f->framenum = framenum;
425         f->numentities = 0;
426         if (eye == NULL)
427         {
428                 VectorClear(f->eye);
429         }
430         else
431         {
432                 VectorCopy(eye, f->eye);
433         }
434 }
435
436 // (server) adds an entity to frame
437 void EntityFrame_AddEntity(entity_frame_t *f, entity_state_t *s)
438 {
439         if (f->numentities < MAX_ENTITY_DATABASE)
440         {
441                 f->entitydata[f->numentities] = *s;
442                 f->entitydata[f->numentities++].active = true;
443         }
444 }
445
446 // (server and client) reads a frame from the database
447 void EntityFrame_FetchFrame(entity_database_t *d, int framenum, entity_frame_t *f)
448 {
449         int i, n;
450         EntityFrame_Clear(f, NULL, -1);
451         for (i = 0;i < d->numframes && d->frames[i].framenum < framenum;i++);
452         if (i < d->numframes && framenum == d->frames[i].framenum)
453         {
454                 f->framenum = framenum;
455                 f->numentities = d->frames[i].endentity - d->frames[i].firstentity;
456                 n = MAX_ENTITY_DATABASE - (d->frames[i].firstentity % MAX_ENTITY_DATABASE);
457                 if (n > f->numentities)
458                         n = f->numentities;
459                 memcpy(f->entitydata, d->entitydata + d->frames[i].firstentity % MAX_ENTITY_DATABASE, sizeof(*f->entitydata) * n);
460                 if (f->numentities > n)
461                         memcpy(f->entitydata + n, d->entitydata, sizeof(*f->entitydata) * (f->numentities - n));
462                 VectorCopy(d->eye, f->eye);
463         }
464 }
465
466 // (server and client) adds a entity_frame to the database, for future reference
467 void EntityFrame_AddFrame(entity_database_t *d, entity_frame_t *f)
468 {
469         int n, e;
470         entity_frameinfo_t *info;
471
472         VectorCopy(f->eye, d->eye);
473
474         // figure out how many entity slots are used already
475         if (d->numframes)
476         {
477                 n = d->frames[d->numframes - 1].endentity - d->frames[0].firstentity;
478                 if (n + f->numentities > MAX_ENTITY_DATABASE || d->numframes >= MAX_ENTITY_HISTORY)
479                 {
480                         // ran out of room, dump database
481                         EntityFrame_ClearDatabase(d);
482                 }
483         }
484
485         info = &d->frames[d->numframes];
486         info->framenum = f->framenum;
487         e = -1000;
488         // make sure we check the newly added frame as well, but we haven't incremented numframes yet
489         for (n = 0;n <= d->numframes;n++)
490         {
491                 if (e >= d->frames[n].framenum)
492                 {
493                         if (e == f->framenum)
494                                 Con_Print("EntityFrame_AddFrame: tried to add out of sequence frame to database\n");
495                         else
496                                 Con_Print("EntityFrame_AddFrame: out of sequence frames in database\n");
497                         return;
498                 }
499                 e = d->frames[n].framenum;
500         }
501         // if database still has frames after that...
502         if (d->numframes)
503                 info->firstentity = d->frames[d->numframes - 1].endentity;
504         else
505                 info->firstentity = 0;
506         info->endentity = info->firstentity + f->numentities;
507         d->numframes++;
508
509         n = info->firstentity % MAX_ENTITY_DATABASE;
510         e = MAX_ENTITY_DATABASE - n;
511         if (e > f->numentities)
512                 e = f->numentities;
513         memcpy(d->entitydata + n, f->entitydata, sizeof(entity_state_t) * e);
514         if (f->numentities > e)
515                 memcpy(d->entitydata, f->entitydata + e, sizeof(entity_state_t) * (f->numentities - e));
516 }
517
518 // (server) writes a frame to network stream
519 static entity_frame_t deltaframe; // FIXME?
520 void EntityFrame_Write(entity_database_t *d, entity_frame_t *f, sizebuf_t *msg)
521 {
522         int i, onum, number;
523         entity_frame_t *o = &deltaframe;
524         entity_state_t *ent, *delta;
525
526         EntityFrame_AddFrame(d, f);
527
528         EntityFrame_FetchFrame(d, d->ackframe > 0 ? d->ackframe : -1, o);
529         MSG_WriteByte (msg, svc_entities);
530         MSG_WriteLong (msg, o->framenum);
531         MSG_WriteLong (msg, f->framenum);
532         MSG_WriteFloat (msg, f->eye[0]);
533         MSG_WriteFloat (msg, f->eye[1]);
534         MSG_WriteFloat (msg, f->eye[2]);
535
536         onum = 0;
537         for (i = 0;i < f->numentities;i++)
538         {
539                 ent = f->entitydata + i;
540                 number = ent->number;
541                 for (;onum < o->numentities && o->entitydata[onum].number < number;onum++)
542                 {
543                         // write remove message
544                         MSG_WriteShort(msg, o->entitydata[onum].number | 0x8000);
545                 }
546                 if (onum < o->numentities && (o->entitydata[onum].number == number))
547                 {
548                         // delta from previous frame
549                         delta = o->entitydata + onum;
550                         // advance to next entity in delta frame
551                         onum++;
552                 }
553                 else
554                 {
555                         // delta from defaults
556                         delta = &defaultstate;
557                 }
558                 EntityState_Write(ent, msg, delta);
559         }
560         for (;onum < o->numentities;onum++)
561         {
562                 // write remove message
563                 MSG_WriteShort(msg, o->entitydata[onum].number | 0x8000);
564         }
565         MSG_WriteShort(msg, 0xFFFF);
566 }
567
568 // (client) reads a frame from network stream
569 static entity_frame_t framedata; // FIXME?
570 void EntityFrame_Read(entity_database_t *d)
571 {
572         int number, removed;
573         entity_frame_t *f = &framedata, *delta = &deltaframe;
574         entity_state_t *e, *old, *oldend;
575
576         EntityFrame_Clear(f, NULL, -1);
577
578         // read the frame header info
579         f->time = cl.mtime[0];
580         number = MSG_ReadLong();
581         f->framenum = MSG_ReadLong();
582         f->eye[0] = MSG_ReadFloat();
583         f->eye[1] = MSG_ReadFloat();
584         f->eye[2] = MSG_ReadFloat();
585         EntityFrame_AckFrame(d, number);
586         EntityFrame_FetchFrame(d, number, delta);
587         old = delta->entitydata;
588         oldend = old + delta->numentities;
589         // read entities until we hit the magic 0xFFFF end tag
590         while ((number = (unsigned short) MSG_ReadShort()) != 0xFFFF)
591         {
592                 if (msg_badread)
593                         Host_Error("EntityFrame_Read: read error\n");
594                 removed = number & 0x8000;
595                 number &= 0x7FFF;
596                 if (number >= MAX_EDICTS)
597                         Host_Error("EntityFrame_Read: number (%i) >= MAX_EDICTS (%i)\n", number, MAX_EDICTS);
598
599                 // seek to entity, while copying any skipped entities (assume unchanged)
600                 while (old < oldend && old->number < number)
601                 {
602                         if (f->numentities >= MAX_ENTITY_DATABASE)
603                                 Host_Error("EntityFrame_Read: entity list too big\n");
604                         f->entitydata[f->numentities] = *old++;
605                         f->entitydata[f->numentities++].time = cl.mtime[0];
606                 }
607                 if (removed)
608                 {
609                         if (old < oldend && old->number == number)
610                                 old++;
611                         else
612                                 Con_Printf("EntityFrame_Read: REMOVE on unused entity %i\n", number);
613                 }
614                 else
615                 {
616                         if (f->numentities >= MAX_ENTITY_DATABASE)
617                                 Host_Error("EntityFrame_Read: entity list too big\n");
618
619                         // reserve this slot
620                         e = f->entitydata + f->numentities++;
621
622                         if (old < oldend && old->number == number)
623                         {
624                                 // delta from old entity
625                                 *e = *old++;
626                         }
627                         else
628                         {
629                                 // delta from defaults
630                                 *e = defaultstate;
631                         }
632
633                         EntityState_ReadUpdate(e, number);
634                 }
635         }
636         while (old < oldend)
637         {
638                 if (f->numentities >= MAX_ENTITY_DATABASE)
639                         Host_Error("EntityFrame_Read: entity list too big\n");
640                 f->entitydata[f->numentities] = *old++;
641                 f->entitydata[f->numentities++].time = cl.mtime[0];
642         }
643         EntityFrame_AddFrame(d, f);
644 }
645
646
647 // (client) returns the frame number of the most recent frame recieved
648 int EntityFrame_MostRecentlyRecievedFrameNum(entity_database_t *d)
649 {
650         if (d->numframes)
651                 return d->frames[d->numframes - 1].framenum;
652         else
653                 return -1;
654 }
655
656
657
658
659
660
661 entity_state_t *EntityFrame4_GetReferenceEntity(entity_database4_t *d, int number)
662 {
663         if (d->maxreferenceentities <= number)
664         {
665                 int oldmax = d->maxreferenceentities;
666                 entity_state_t *oldentity = d->referenceentity;
667                 d->maxreferenceentities = (number + 15) & ~7;
668                 d->referenceentity = Mem_Alloc(d->mempool, d->maxreferenceentities * sizeof(*d->referenceentity));
669                 if (oldentity)
670                 {
671                         memcpy(d->referenceentity, oldentity, oldmax * sizeof(*d->referenceentity));
672                         Mem_Free(oldentity);
673                 }
674                 // clear the newly created entities
675                 for (;oldmax < d->maxreferenceentities;oldmax++)
676                 {
677                         d->referenceentity[oldmax] = defaultstate;
678                         d->referenceentity[oldmax].number = oldmax;
679                 }
680         }
681         return d->referenceentity + number;
682 }
683
684 void EntityFrame4_AddCommitEntity(entity_database4_t *d, entity_state_t *s)
685 {
686         // resize commit's entity list if full
687         if (d->currentcommit->maxentities <= d->currentcommit->numentities)
688         {
689                 entity_state_t *oldentity = d->currentcommit->entity;
690                 d->currentcommit->maxentities += 8;
691                 d->currentcommit->entity = Mem_Alloc(d->mempool, d->currentcommit->maxentities * sizeof(*d->currentcommit->entity));
692                 if (oldentity)
693                 {
694                         memcpy(d->currentcommit->entity, oldentity, d->currentcommit->numentities * sizeof(*d->currentcommit->entity));
695                         Mem_Free(oldentity);
696                 }
697         }
698         d->currentcommit->entity[d->currentcommit->numentities++] = *s;
699 }
700
701 entity_database4_t *EntityFrame4_AllocDatabase(mempool_t *pool)
702 {
703         entity_database4_t *d;
704         d = Mem_Alloc(pool, sizeof(*d));
705         d->mempool = pool;
706         EntityFrame4_ResetDatabase(d);
707         d->ackframenum = -1;
708         return d;
709 }
710
711 void EntityFrame4_FreeDatabase(entity_database4_t *d)
712 {
713         int i;
714         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
715                 if (d->commit[i].entity)
716                         Mem_Free(d->commit[i].entity);
717         if (d->referenceentity)
718                 Mem_Free(d->referenceentity);
719         Mem_Free(d);
720 }
721
722 void EntityFrame4_ResetDatabase(entity_database4_t *d)
723 {
724         int i;
725         d->ackframenum = -1;
726         d->referenceframenum = -1;
727         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
728                 d->commit[i].numentities = 0;
729         for (i = 0;i < d->maxreferenceentities;i++)
730                 d->referenceentity[i] = defaultstate;
731 }
732
733 int EntityFrame4_AckFrame(entity_database4_t *d, int framenum)
734 {
735         int i, j, found;
736         entity_database4_commit_t *commit;
737         if (framenum == -1)
738         {
739                 // reset reference, but leave commits alone
740                 d->referenceframenum = -1;
741                 for (i = 0;i < d->maxreferenceentities;i++)
742                         d->referenceentity[i] = defaultstate;
743                 found = true;
744         }
745         else if (d->referenceframenum == framenum)
746                 found = true;
747         else
748         {
749                 found = false;
750                 for (i = 0, commit = d->commit;i < MAX_ENTITY_HISTORY;i++, commit++)
751                 {
752                         if (commit->numentities && commit->framenum <= framenum)
753                         {
754                                 if (commit->framenum == framenum)
755                                 {
756                                         found = true;
757                                         d->referenceframenum = framenum;
758                                         if (developer_networkentities.integer >= 3)
759                                         {
760                                                 for (j = 0;j < commit->numentities;j++)
761                                                 {
762                                                         entity_state_t *s = EntityFrame4_GetReferenceEntity(d, commit->entity[j].number);
763                                                         if (commit->entity[j].active != s->active)
764                                                         {
765                                                                 if (commit->entity[j].active)
766                                                                         Con_Printf("commit entity %i has become active (modelindex %i)\n", commit->entity[j].number, commit->entity[j].modelindex);
767                                                                 else
768                                                                         Con_Printf("commit entity %i has become inactive (modelindex %i)\n", commit->entity[j].number, commit->entity[j].modelindex);
769                                                         }
770                                                         *s = commit->entity[j];
771                                                 }
772                                         }
773                                         else
774                                                 for (j = 0;j < commit->numentities;j++)
775                                                         *EntityFrame4_GetReferenceEntity(d, commit->entity[j].number) = commit->entity[j];
776                                 }
777                                 commit->numentities = 0;
778                         }
779                 }
780         }
781         if (developer_networkentities.integer >= 1)
782         {
783                 Con_Printf("ack ref:%i database updated to: ref:%i commits:", framenum, d->referenceframenum);
784                 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
785                         if (d->commit[i].numentities)
786                                 Con_Printf(" %i", d->commit[i].framenum);
787                 Con_Print("\n");
788         }
789         return found;
790 }
791
792 int EntityFrame4_SV_WriteFrame_Entity(entity_database4_t *d, sizebuf_t *msg, int maxbytes, entity_state_t *s)
793 {
794         qbyte data[128];
795         sizebuf_t buf;
796         entity_state_t *e;
797         // prepare the buffer
798         memset(&buf, 0, sizeof(buf));
799         buf.data = data;
800         buf.maxsize = sizeof(data);
801         // make the message
802         e = EntityFrame4_GetReferenceEntity(d, s->number);
803         // send an update (may update or remove the entity)
804         EntityState_Write(s, &buf, e);
805         // if the message is empty, skip out now
806         if (!buf.cursize)
807                 return true;
808         // if the commit is full, we're done
809         if (msg->cursize + buf.cursize + 2 >= min(msg->maxsize, maxbytes))
810                 return false;
811         // add the entity to the commit
812         EntityFrame4_AddCommitEntity(d, s);
813         // write the message to the packet
814         SZ_Write(msg, buf.data, buf.cursize);
815         // carry on
816         return true;
817 }
818
819 extern void CL_MoveLerpEntityStates(entity_t *ent);
820 void EntityFrame4_CL_ReadFrame(entity_database4_t *d)
821 {
822         int i, n, cnumber, referenceframenum, framenum, enumber, done, stopnumber, skip = false;
823         // read the number of the frame this refers to
824         referenceframenum = MSG_ReadLong();
825         // read the number of this frame
826         framenum = MSG_ReadLong();
827         // read the start number
828         enumber = MSG_ReadShort();
829         if (developer_networkentities.integer >= 1)
830         {
831                 Con_Printf("recv svc_entities num:%i ref:%i database: ref:%i commits:", framenum, referenceframenum, d->referenceframenum);
832                 for (i = 0;i < MAX_ENTITY_HISTORY;i++)
833                         if (d->commit[i].numentities)
834                                 Con_Printf(" %i", d->commit[i].framenum);
835                 Con_Print("\n");
836         }
837         if (!EntityFrame4_AckFrame(d, referenceframenum))
838         {
839                 Con_Print("EntityFrame4_CL_ReadFrame: reference frame invalid (VERY BAD ERROR), this update will be skipped\n");
840                 skip = true;
841         }
842         d->currentcommit = NULL;
843         for (i = 0;i < MAX_ENTITY_HISTORY;i++)
844         {
845                 if (!d->commit[i].numentities)
846                 {
847                         d->currentcommit = d->commit + i;
848                         d->currentcommit->framenum = d->ackframenum = framenum;
849                         d->currentcommit->numentities = 0;
850                 }
851         }
852         if (d->currentcommit == NULL)
853         {
854                 Con_Printf("EntityFrame4_CL_ReadFrame: error while decoding frame %i: database full, reading but not storing this update\n", framenum);
855                 skip = true;
856         }
857         done = false;
858         while (!done && !msg_badread)
859         {
860                 // read the number of the modified entity
861                 // (gaps will be copied unmodified)
862                 n = (unsigned short)MSG_ReadShort();
863                 if (n == 0x8000)
864                 {
865                         // no more entities in this update, but we still need to copy the
866                         // rest of the reference entities (final gap)
867                         done = true;
868                         // read end of range number, then process normally
869                         n = (unsigned short)MSG_ReadShort();
870                 }
871                 // high bit means it's a remove message
872                 cnumber = n & 0x7FFF;
873                 // add one (the changed one) if not done
874                 stopnumber = cnumber + !done;
875                 // process entities in range from the last one to the changed one
876                 for (;enumber < stopnumber;enumber++)
877                 {
878                         if (skip)
879                         {
880                                 if (enumber == cnumber && (n & 0x8000) == 0)
881                                 {
882                                         entity_state_t tempstate;
883                                         EntityState_ReadUpdate(&tempstate, enumber);
884                                 }
885                                 continue;
886                         }
887                         // slide the current into the previous slot
888                         cl_entities[enumber].state_previous = cl_entities[enumber].state_current;
889                         // copy a new current from reference database
890                         cl_entities[enumber].state_current = *EntityFrame4_GetReferenceEntity(d, enumber);
891                         // if this is the one to modify, read more data...
892                         if (enumber == cnumber)
893                         {
894                                 if (n & 0x8000)
895                                 {
896                                         // simply removed
897                                         if (developer_networkentities.integer >= 2)
898                                                 Con_Printf("entity %i: remove\n", enumber);
899                                         cl_entities[enumber].state_current = defaultstate;
900                                 }
901                                 else
902                                 {
903                                         // read the changes
904                                         if (developer_networkentities.integer >= 2)
905                                                 Con_Printf("entity %i: update\n", enumber);
906                                         EntityState_ReadUpdate(&cl_entities[enumber].state_current, enumber);
907                                 }
908                         }
909                         else if (developer_networkentities.integer >= 4)
910                                 Con_Printf("entity %i: copy\n", enumber);
911                         // fix the number (it gets wiped occasionally by copying from defaultstate)
912                         cl_entities[enumber].state_current.number = enumber;
913                         // check if we need to update the lerp stuff
914                         if (cl_entities[enumber].state_current.active)
915                         {
916                                 CL_MoveLerpEntityStates(&cl_entities[enumber]);
917                                 cl_entities_active[enumber] = true;
918                         }
919                         // add this to the commit entry whether it is modified or not
920                         if (d->currentcommit)
921                                 EntityFrame4_AddCommitEntity(d, &cl_entities[enumber].state_current);
922                         // print extra messages if desired
923                         if (developer_networkentities.integer >= 2 && cl_entities[enumber].state_current.active != cl_entities[enumber].state_previous.active)
924                         {
925                                 if (cl_entities[enumber].state_current.active)
926                                         Con_Printf("entity #%i has become active\n", enumber);
927                                 else if (cl_entities[enumber].state_previous.active)
928                                         Con_Printf("entity #%i has become inactive\n", enumber);
929                         }
930                 }
931         }
932         d->currentcommit = NULL;
933         if (skip)
934                 EntityFrame4_ResetDatabase(d);
935 }
936
937