1

I am attempting to implement an example of client side prediction and server reconciliation, if there is a better approach please let me know! I am trying to hide the latency on a networked game. Currently I am using lidgren and XNA for the client and just a console application for the server. I have the lidgren on the server side set to simulate 1.5 sec of latency. So when I run this code it works for the most part but it seems that the client is buffering up moves and then eventual moves the character around on the screen but according the the demo I referenced below I dont see the buffering type of behavior I am just stumped on what it could be? Thanks in advance for any help you guys can provide, if you need to see more of the code just let me know I didnt want to flood the post with too much.

In the SendMovement method I am taking the users input and serializing a command to send to the server, it will go ahead and move the player and store the move command in a queue.

    private Queue<MovementCommand> _previousMovements = new Queue<MovementCommand>(5000);

    public void SendMovement(float elapsed, byte direction)
    {
        MovementCommand movement = new MovementCommand(_id, _sequenceNumber++, elapsed, direction);

        OutputCommand<MovementCommand> moveCommand = new OutputCommand<MovementCommand>(GamePacketTypes.Movement, movement);

        byte[] msgData = moveCommand.Serialize();

        Send(msgData);

        Console.WriteLine(string.Format("Elapsed Time = {0}, Sequence # = {1}", elapsed, _sequenceNumber));

        if (_clientSidePrediction == true)
        {
            _player.Move(movement);

            _previousMovements.Enqueue(movement);

        }
    }

When I receive a message back from the server I update the player position and then check to see what was the last input sequence from the server compared to the local sequence number.

    public void HandleMessages()
    {
        while (true)
        {
            if (mIncomingMessages.Count > 0)
            {
                for (int i = 0; i < mIncomingMessages.Count; i++)
                {
                    byte command = mIncomingMessages[i].ReadByte();


                    switch ((GamePacketTypes)command)
                    {
                        case GamePacketTypes.UpdateEntity:


                            EntityStateType stateObj = EntityStateType.Deserialize(mIncomingMessages[i].ReadBytes(mIncomingMessages[i].LengthBytes - 1));

                            _player.Position(stateObj);


                            if (_serverReconciliation == true)
                            {
                                if (stateObj.ID == _id)
                                {
                                    int j = 0;

                                    while (j < _previousMovements.Count)
                                    {
                                        MovementCommand move = _previousMovements.Peek();

                                        if (move.InputSequence <= stateObj.LastProcessedInput)
                                        {
                                            _previousMovements.Dequeue();
                                        }
                                        else
                                        {
                                            _player.Move(_previousMovements.Dequeue());
                                            j++;
                                        }

                                    }
                                }
                            }

                            break;

                    }

                }

                mIncomingMessages.Clear();
            }

            Thread.Sleep(25);
        }
    }

On the server side I just take the command from the client apply it to their character and set the last processed sequence for the client when the next state update goes out.

    private async Task<bool> HandleMovement(MovementCommand move)
    {
        switch((DirectionHeading)move.Direction)
        {
            case DirectionHeading.North:
                _player.Y -= (move.PressedTime * _player.Velocity);
                break;
            case DirectionHeading.East:
                _player.X += (move.PressedTime * _player.Velocity);
                break;
            case DirectionHeading.South:
                _player.Y += (move.PressedTime * _player.Velocity);
                break;
            case DirectionHeading.West:
                _player.X -= (move.PressedTime * _player.Velocity);

                break;

        }
        _player.Direction = move.Direction;
        LastProcessedInput = move.InputSequence;
        Console.WriteLine("Last Processed Input = {0}", LastProcessedInput);
        return true;
    }

Example code from Gabriel Gamebetta (hopefully he doesnt mind...)

// Get inputs and send them to the server.
// If enabled, do client-side prediction.
Client.prototype.processInputs = function() {
// Compute delta time since last update.
var now_ts = +new Date();
var last_ts = this.last_ts || now_ts;
var dt_sec = (now_ts - last_ts) / 1000.0;
this.last_ts = now_ts;

// Package player's input.
var input;
if (this.key_right) {
  input = { press_time: dt_sec };
} else if (this.key_left) {
  input = { press_time: -dt_sec };
} else {
  // Nothing interesting happened.
  return;
}

// Send the input to the server.
input.input_sequence_number = this.input_sequence_number++;
input.entity_id = this.entity_id;
this.server.network.send(client_server_lag, input);

// Do client-side prediction.
if (client_side_prediction) {
  this.entity.applyInput(input);
}

// Save this input for later reconciliation.
this.pending_inputs.push(input);
}


Server.prototype.processInputs = function() {
// Process all pending messages from clients.
while (true) {
var message = this.network.receive();
if (!message) {
  break;
}

// Update the state of the entity, based on its input.
// We just ignore inputs that don't look valid; this is what prevents
// clients from cheating.
if (this.validateInput(message)) {
  var id = message.entity_id;
  this.entities[id].applyInput(message);
  this.last_processed_input[id] = message.input_sequence_number;
 }
}

}

Client.prototype.processServerMessages = function() {
while (true) {
var message = this.network.receive();
if (!message) {
  break;
}

// World state is a list of entity states.
for (var i = 0; i < message.length; i++) {
  var state = message[i];

  if (state.entity_id == this.entity_id) {
    // Got the position of this client's entity.

    if (!this.entity) {
      // If this is the first server update, create a local entity.
      this.entity = new Entity();
    }

    // Set the position sent by the server.
    this.entity.x = state.position;

    if (server_reconciliation) {
      // Server Reconciliation. Re-apply all the inputs not yet processed by
      // the server.
      var j = 0;
      while (j < this.pending_inputs.length) {
        var input = this.pending_inputs[j];
        if (input.input_sequence_number <= state.last_processed_input) {
          // Already processed. Its effect is already taken into account
          // into the world update we just got, so we can drop it.
          this.pending_inputs.splice(j, 1);
        } else {
          // Not processed by the server yet. Re-apply it.
          this.entity.applyInput(input);
          j++;
        }
      }
    } else {
      // Reconciliation is disabled, so drop all the saved inputs.
      this.pending_inputs = [];
    }
  } else {
    // TO DO: add support for rendering other entities.
  }
}
}

1 Answer 1

1

No, I don't mind :) But maybe add a link to the articles to give other readers more context.

I don't know much C#, but in the innermost loop of HandleMessages() you're using Dequeue() in both branches, and you're incrementing j in one of these - I have a feeling this isn't correct. You may want to re-apply an input several times after a server update.

1
  • I tried to add a link to your page and it wouldnt allow me too :( I wish I could.
    – lakedoo
    Aug 27, 2014 at 13:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.