Exemplo n.º 1
0
        public void Add(UpdateDataStruct data)
        {
            this.bytes.Add((byte)Types.UpdateDataStruct);
            this.bytes.AddRange(BitConverter.GetBytes(System.Diagnostics.Stopwatch.GetTimestamp()));
            this.bytes.AddRange(BitConverter.GetBytes(data.pos_x));
            this.bytes.AddRange(BitConverter.GetBytes(data.pos_y));
            this.bytes.AddRange(BitConverter.GetBytes(data.pos_z));

            this.bytes.AddRange(BitConverter.GetBytes(data.rot_x));
            this.bytes.AddRange(BitConverter.GetBytes(data.rot_y));
            this.bytes.AddRange(BitConverter.GetBytes(data.rot_z));
            this.bytes.AddRange(BitConverter.GetBytes(data.rot_a));

            this.bytes.AddRange(BitConverter.GetBytes(data.vel_x));
            this.bytes.AddRange(BitConverter.GetBytes(data.vel_y));
            this.bytes.AddRange(BitConverter.GetBytes(data.vel_z));
            this.bytes.AddRange(BitConverter.GetBytes(data.camdir_x));
            this.bytes.AddRange(BitConverter.GetBytes(data.camdir_y));
            this.bytes.AddRange(BitConverter.GetBytes(data.camdir_z));

            this.bytes.AddRange(BitConverter.GetBytes(data.heading));

            this.bytes.AddRange(BitConverter.GetBytes(data.vehicle_model));
            this.bytes.AddRange(BitConverter.GetBytes(data.ped_health));
            this.bytes.AddRange(BitConverter.GetBytes(data.vehicle_health));
            this.bytes.AddRange(BitConverter.GetBytes(data.weapon));
            this.bytes.AddRange(BitConverter.GetBytes(data.vehicle_id));
            this.bytes.Add((byte)data.state);
            this.bytes.Add((byte)data.vstate);
        }
 public void broadcastData(UpdateDataStruct data)
 {
     if (Client.instance.BroadcastingPaused) return;
     try
     {
         var bpf = new BinaryPacketFormatter();
         bpf.Add(data);
         var bytes = bpf.getBytes();
         udp.Send(bytes, bytes.Length);
     }
     catch (Exception e) { Game.Log(e.Message); }
 }
 public ServerPlayer(uint id, string nick, ClientConnection connection)
 {
     this.id = id;
     this.nick = nick;
     virtualWorld = 0;
     model = "F_Y_NURSE";
     this.connection = connection;
     requester = new ServerRequester(this);
     data = UpdateDataStruct.Zero;
     isDead = true;
     Camera = new PlayerCamera(this);
     udpTunnel = new ServerUDPTunnel(this);
 }
Exemplo n.º 4
0
        public UpdateDataStruct readUpdateStruct()
        {
            if (readNextType() != BinaryPacketFormatter.Types.UpdateDataStruct)
            {
                throw new Exception("Desynchronization UpdateDataStruct");
            }
            UpdateDataStruct output = new UpdateDataStruct();

            output.timestamp = readInt64(true);
            output.pos_x     = readSingle(true);
            output.pos_y     = readSingle(true);
            output.pos_z     = readSingle(true);

            output.rot_x = readSingle(true);
            output.rot_y = readSingle(true);
            output.rot_z = readSingle(true);
            output.rot_a = readSingle(true);

            output.vel_x    = readSingle(true);
            output.vel_y    = readSingle(true);
            output.vel_z    = readSingle(true);
            output.camdir_x = readSingle(true);
            output.camdir_y = readSingle(true);
            output.camdir_z = readSingle(true);

            output.heading = readSingle(true);

            output.vehicle_model  = readInt32(true);
            output.ped_health     = readInt32(true);
            output.vehicle_health = readInt32(true);
            output.weapon         = readInt32(true);
            output.vehicle_id     = readUInt32(true);

            output.state  = (PlayerState)readByte(true);
            output.vstate = (VehicleState)readByte(true);

            return(output);
        }
Exemplo n.º 5
0
        private void initAndConnect(string ip, short port, string nickname)
        {
            currentIP = ip;
            GTA.Native.Function.Call("DISABLE_PAUSE_MENU", 1);
            GTA.Native.Function.Call("SET_FILTER_MENU_ON", 1);
            BroadcastingPaused = true;
            playerNames = new Dictionary<uint, string>();
            playerModels = new Dictionary<uint, string>();
            isCurrentlyDead = false;
            actionQueue = new Queue<Action>();
            instance = this;

            jsEngine = new JavaScriptEngine();

            CurrentVirtualWorld = 0;

            cameraController = new CameraController(this);

            debugDraw = new ClientTextView(new System.Drawing.PointF(10, 400), "", new GTA.Font("Segoe UI", 24, FontScaling.Pixel), System.Drawing.Color.White);

            pedStreamer = new PedStreamer(this, 100.0f);
            vehicleStreamer = new VehicleStreamer(this, 100.0f);

            pedController = new PlayerPedController();
            npcPedController = new NPCPedController();
            vehicleController = new VehicleController();
            playerVehicleController = new PlayerVehicleController();
            chatController = new ChatController(this);
            keyboardHandler = new KeyboardHandler(this);
            currentState = ClientState.Initializing;
            Interval = 80;
            //cam = new Camera();
            //cam.Activate();
            currentState = ClientState.Disconnected;
            System.IO.File.WriteAllText("multiv-log.txt", "");
            perFrameRenderer = new PerFrameRenderer(this);

            Player.Character.CurrentRoom = Room.FromString("R_00000000_00000000");

            startTimersandBindEvents();
            try
            {
                if (client != null && client.Connected)
                {
                    client.Close();
                }
                client = new TcpClient();
                IPAddress address = IPAddress.Parse(ip);
                nick = nickname;

                client.Connect(address, port);

                Client.currentData = UpdateDataStruct.Zero;

                serverConnection = new ServerConnection(this);

                World.CurrentDayTime = new TimeSpan(12, 00, 00);
                World.PedDensity = 0;
                World.CarDensity = 0;
                // AlternateHook.call(AlternateHook.OtherCommands.TERMINATE_ALL_SCRIPTS_FOR_NETWORK_GAME);
                GTA.Native.Function.Call("CLEAR_AREA", 0.0f, 0.0f, 0.0f, 4000.0f, true);
                currentState = ClientState.Connecting;
            }
            catch
            {
                currentState = ClientState.Disconnected;
                if (client != null && client.Connected)
                {
                    client.Close();
                }
                throw;
            }
        }
Exemplo n.º 6
0
        private void eventOnTick(object sender, EventArgs e)
        {
            try
            {
                while (actionQueue.Count > 0)
                {
                    actionQueue.Dequeue().Invoke();
                }
            }
            catch (Exception ex)
            {
                log("Failed executing action queue with message " + ex.Message);
            }
            if (currentState == ClientState.Connected)
            {
                if (currentData == null) currentData = UpdateDataStruct.Zero;
                if (!BroadcastingPaused && Player.Character.Exists())
                {
                    try
                    {
                        UpdateDataStruct data = new UpdateDataStruct();
                        if (Player.Character.isInVehicle() && Player.Character.CurrentVehicle.GetPedOnSeat(VehicleSeat.Driver) == Player.Character)
                        {
                            if (vehicleController.dict.Count(a => a.Value.IsStreamedIn() && a.Value.gameReference == Player.Character.CurrentVehicle) > 0)
                            {
                                try
                                {
                                    Vector3 pos = Player.Character.CurrentVehicle.Position;
                                    data.pos_x = pos.X;
                                    data.pos_y = pos.Y;
                                    data.pos_z = pos.Z;

                                    Vector3 currentSpeed = Player.Character.CurrentVehicle.Velocity;
                                    float speed = Player.Character.CurrentVehicle.Speed;
                                    if (currentData.pos_x != 0)
                                    {
                                        float deltax = (pos.X - currentData.pos_x);
                                        float deltay = (pos.Y - currentData.pos_y);
                                        float deltaz = (pos.Z - currentData.pos_z);
                                        data.vel_x = (deltax < 0 ? currentSpeed.X * -1 : currentSpeed.X);
                                        data.vel_y = (deltay < 0 ? currentSpeed.Y * -1 : currentSpeed.Y);
                                        data.vel_z = (deltaz < 0 ? currentSpeed.Z * -1 : currentSpeed.Z);
                                    }
                                    else
                                    {
                                        data.vel_x = currentSpeed.X;
                                        data.vel_y = currentSpeed.Y;
                                        data.vel_z = currentSpeed.Z;
                                    }

                                    Quaternion quat = Player.Character.CurrentVehicle.RotationQuaternion;
                                    data.rot_x = quat.X;
                                    data.rot_y = quat.Y;
                                    data.rot_z = quat.Z;
                                    data.rot_a = quat.W;

                                    data.vehicle_model = Player.Character.CurrentVehicle.Model.Hash;
                                    data.vehicle_health = Player.Character.CurrentVehicle.Health;
                                    var cveh = vehicleController.dict.First(a => a.Value.IsStreamedIn() && a.Value.gameReference == Player.Character.CurrentVehicle);

                                    data.vehicle_id = cveh.Key;
                                    data.ped_health = Player.Character.Health;
                                    data.heading = Player.Character.CurrentVehicle.Heading;

                                    cveh.Value.position = pos;
                                    cveh.Value.orientation = quat;
                                }
                                catch (Exception eq)
                                {
                                    Game.Log("Failed pedInvehicle position measure processing: " + eq.Message);
                                }
                            }
                            data.state = 0;
                        }
                        else
                        {

                            try
                            {
                                Vector3 pos = Player.Character.Position;
                                data.pos_x = pos.X;
                                data.pos_y = pos.Y;
                                data.pos_z = pos.Z;

                                Vector3 vel = Player.Character.Velocity;
                                data.vel_x = vel.X;
                                data.vel_y = vel.Y;
                                data.vel_z = vel.Z;

                                data.rot_x = Player.Character.Direction.X;
                                data.rot_y = Player.Character.Direction.Y;
                                data.rot_z = Player.Character.Direction.Z;
                                data.rot_a = 0;

                                data.vehicle_model = 0;
                                data.vehicle_health = 0;
                                // for passengers:)client.pedController.dict.First(a => a.Value.IsStreamedIn() && a.Value.gameReference == selectedPed)
                                data.vehicle_id = Player.Character.isInVehicle() ? vehicleController.dict.First(a => a.Value.IsStreamedIn() && a.Value.gameReference == Player.Character.CurrentVehicle).Key : 0;
                                data.ped_health = Player.Character.Health;
                                data.heading = Player.Character.Heading;
                                data.weapon = (int)Player.Character.Weapons.CurrentType;
                                data.state = 0;
                                data.state |= Player.Character.isShooting ? PlayerState.IsShooting : 0;
                                data.state |= Game.isGameKeyPressed(GameKey.Aim) ? PlayerState.IsAiming : 0;
                                data.state |= Game.isGameKeyPressed(GameKey.Crouch) ? PlayerState.IsCrouching : 0;
                                data.state |= Game.isGameKeyPressed(GameKey.Jump) ? PlayerState.IsJumping : 0;
                                data.state |= Game.isGameKeyPressed(GameKey.Attack) ? PlayerState.IsShooting : 0;

                                data.state |= Player.Character.isInVehicle() && Player.Character.CurrentVehicle.GetPedOnSeat(VehicleSeat.RightFront) == Player.Character ? PlayerState.IsPassenger1 : 0;
                                data.state |= Player.Character.isInVehicle() && Player.Character.CurrentVehicle.GetPedOnSeat(VehicleSeat.LeftRear) == Player.Character ? PlayerState.IsPassenger2 : 0;
                                data.state |= Player.Character.isInVehicle() && Player.Character.CurrentVehicle.GetPedOnSeat(VehicleSeat.RightRear) == Player.Character ? PlayerState.IsPassenger3 : 0;
                            }
                            catch (Exception eq)
                            {
                                Game.Log("Failed ped position measure processing: " + eq.Message);
                            }
                        }
                        data.vstate = 0;
                        data.vstate |= Game.isGameKeyPressed(GameKey.MoveForward) ? VehicleState.IsAccelerating : 0;
                        data.vstate |= Game.isGameKeyPressed(GameKey.MoveBackward) ? VehicleState.IsBraking : 0;
                        data.vstate |= Game.isGameKeyPressed(GameKey.MoveLeft) ? VehicleState.IsSterringLeft : 0;
                        data.vstate |= Game.isGameKeyPressed(GameKey.MoveRight) ? VehicleState.IsSterringRight : 0;
                        data.vstate |= Game.isGameKeyPressed(GameKey.Sprint) ? VehicleState.IsSprinting : 0;
                        data.vstate |= Player.Character.isGettingIntoAVehicle ? VehicleState.IsEnteringVehicle : 0;
                        data.vstate |= (data.state & PlayerState.IsPassenger1) != 0 || (data.state & PlayerState.IsPassenger2) != 0 || (data.state & PlayerState.IsPassenger3) != 0
                            ? VehicleState.IsAsPassenger : 0;

                        data.camdir_x = Game.CurrentCamera.Direction.X;
                        data.camdir_y = Game.CurrentCamera.Direction.Y;
                        data.camdir_z = Game.CurrentCamera.Direction.Z;
                        /*
                        var bpf = new BinaryPacketFormatter(Commands.UpdateData);
                        bpf.Add(data);
                        serverConnection.write(bpf.getBytes());*/
                        if (udpTunnel != null)
                        {
                            udpTunnel.broadcastData(data);
                        }

                        try
                        {
                            if (!isCurrentlyDead && (Player.Character.Health == 0 || Player.Character.isDead || !Player.Character.isAlive))
                            {
                                //Game.FadeScreenOut(4000);
                                //Player.Character.Die();
                                //AlternateHook.call(AlternateHookRequest.OtherCommands.FAKE_DEATHARREST);
                                //AlternateHook.call(AlternateHookRequest.OtherCommands.CREATE_PLAYER, 0.0f, 0.0f, 0.0f, null);
                                isCurrentlyDead = true;
                            }

                            if (isCurrentlyDead && !Player.Character.isDead && Player.Character.isAlive && Player.Character.Health > 0)
                            {
                                Game.FadeScreenIn(2000);
                                isCurrentlyDead = false;

                                var bpf2 = new BinaryPacketFormatter(Commands.InternalClient_requestSpawn);
                                serverConnection.write(bpf2.getBytes());

                            }
                        }
                        catch (Exception eq)
                        {
                            Game.Log("Failed death processing: " + eq.Message);
                        }

                        currentData = data;
                    }
                    catch (Exception ex)
                    {
                        Game.Log("Failed sending new Player data with message " + ex.Message);
                    }
                }
                try
                {
                    serverConnection.flush();
                }
                catch (Exception ex)
                {
                    Game.Log("Failed sending packets " + ex.Message);
                }
                try
                {
                    updateAllPlayers();
                    pedStreamer.Update();
                    vehicleStreamer.Update();
                    pedStreamer.UpdateNormalTick();
                    vehicleStreamer.UpdateNormalTick();
                }
                catch (Exception ex)
                {
                    log("Failed updating streamers and players with message " + ex.Message);
                }
            }

            if (currentState == ClientState.Connecting)
            {
                currentState = ClientState.Connected;

                darkscreen.destroy();
                Game.FadeScreenIn(3000);
                GTA.Native.Function.Call("DO_SCREEN_FADE_IN_UNHACKED", 2000);
                GTA.Native.Function.Call("FORCE_LOADING_SCREEN", false);

                var bpf = new BinaryPacketFormatter(Commands.Connect);
                bpf.Add(nick);
                serverConnection.write(bpf.getBytes());

                Player.Model = new Model("F_Y_HOOKER_01");
                Player.NeverGetsTired = true;

                //ClientTextureDraw draw = new ClientTextureDraw(new System.Drawing.RectangleF(20, 20, 400, 400), @"C:\Users\Aerofly\Desktop\4duzy.png");

                //chatController.writeChat("Connected");
            }
        }
        public void updateData(UpdateDataStruct data)
        {
            this.data = data;
            if (isDead && data.ped_health > 0)
            {
                isDead = false;
                Server.instance.api.invokeOnPlayerSpawn(this);
            }
            if (!isDead && data.ped_health <= 0)
            {
                isDead = true;
                Server.instance.api.invokeOnPlayerDie(this);
            }

            if (data.vehicle_id > 0)
            {
                Server.instance.vehicleController.vehicles[data.vehicle_id].position = data.getPositionVector();
                Server.instance.vehicleController.vehicles[data.vehicle_id].orientation = data.getOrientationQuaternion();
                Server.instance.vehicleController.vehicles[data.vehicle_id].velocity = data.getVelocityVector();
                Server.instance.vehicleController.vehicles[data.vehicle_id].health = data.vehicle_health;
            }
            Server.instance.api.invokeOnPlayerUpdate(this);
            //Server.instance.broadcastData(this);
            //Console.WriteLine("Updated Player " + nick);
        }
        public void Add(UpdateDataStruct data)
        {
            this.bytes.Add((byte)Types.UpdateDataStruct);
            this.bytes.AddRange(BitConverter.GetBytes(System.Diagnostics.Stopwatch.GetTimestamp()));
            this.bytes.AddRange(BitConverter.GetBytes(data.pos_x));
            this.bytes.AddRange(BitConverter.GetBytes(data.pos_y));
            this.bytes.AddRange(BitConverter.GetBytes(data.pos_z));

            this.bytes.AddRange(BitConverter.GetBytes(data.rot_x));
            this.bytes.AddRange(BitConverter.GetBytes(data.rot_y));
            this.bytes.AddRange(BitConverter.GetBytes(data.rot_z));
            this.bytes.AddRange(BitConverter.GetBytes(data.rot_a));

            this.bytes.AddRange(BitConverter.GetBytes(data.vel_x));
            this.bytes.AddRange(BitConverter.GetBytes(data.vel_y));
            this.bytes.AddRange(BitConverter.GetBytes(data.vel_z));
            this.bytes.AddRange(BitConverter.GetBytes(data.camdir_x));
            this.bytes.AddRange(BitConverter.GetBytes(data.camdir_y));
            this.bytes.AddRange(BitConverter.GetBytes(data.camdir_z));

            this.bytes.AddRange(BitConverter.GetBytes(data.heading));

            this.bytes.AddRange(BitConverter.GetBytes(data.vehicle_model));
            this.bytes.AddRange(BitConverter.GetBytes(data.ped_health));
            this.bytes.AddRange(BitConverter.GetBytes(data.vehicle_health));
            this.bytes.AddRange(BitConverter.GetBytes(data.weapon));
            this.bytes.AddRange(BitConverter.GetBytes(data.vehicle_id));
            this.bytes.Add((byte)data.state);
            this.bytes.Add((byte)data.vstate);
        }
        public void updatePed(uint id, UpdateDataStruct data, StreamedPed ped)
        {
            var posnew = new Vector3(data.pos_x, data.pos_y, data.pos_z - 1.0f);
            ped.position = posnew;
            ped.heading = data.heading;
            ped.direction = new Vector3(data.rot_x, data.rot_y, data.rot_z);
            ped.cameraDirection = new Vector3(data.camdir_x, data.camdir_y, data.camdir_z);
            if (ped.IsStreamedIn() && data.vehicle_id == 0)
            {
                if (ped.gameReference.isInVehicle())
                {
                    ped.gameReference.CurrentVehicle.PassengersLeaveVehicle(true);
                    //ped.gameReference.CurrentVehicle.Delete();
                }

                float delta = posnew.DistanceTo(ped.gameReference.Position);
                Vector3 vdelta = posnew - ped.gameReference.Position;
                //ped.gameReference.Weapons.MP5.Ammo = 999;

                int healthDelta = data.ped_health - ped.gameReference.Health;
                ped.gameReference.Health = data.ped_health;
                ped.last_game_health = data.ped_health;

                if (data.weapon > 0)
                {
                    if (ped.gameReference.Weapons.Current != (Weapon)data.weapon)
                    {
                        ped.gameReference.Weapons.FromType((Weapon)data.weapon).Ammo = 999;
                        ped.gameReference.Weapons.FromType((Weapon)data.weapon).AmmoInClip = 999;
                        ped.gameReference.Weapons.Select((Weapon)data.weapon);
                    }
                }
                else
                {
                    ped.gameReference.Weapons.RemoveAll();
                }

                if (healthDelta > 20 && healthDelta < 100)
                {
                    var bpf = new BinaryPacketFormatter(Commands.Player_damage);
                    bpf.Add(id);
                    //Client.instance.chatController.writeChat("damaged " + healthDelta) ;
                    Client.instance.serverConnection.write(bpf.getBytes());
                }

                bool cancelPositionUpdate = false;

                if ((data.state & PlayerState.IsShooting) != 0)
                {
                    ped.animator.playAnimation(PedAnimations.Shoot);
                    cancelPositionUpdate = true;
                }
                else
                    if ((data.state & PlayerState.IsAiming) != 0)
                    {
                        ped.animator.playAnimation(PedAnimations.Aim);
                        cancelPositionUpdate = true;
                    }
                    else
                        if ((data.state & PlayerState.IsRagdoll) != 0 || data.ped_health <= 0)
                        {
                            ped.animator.playAnimation(PedAnimations.Ragdoll);
                            ped.gameReference.Velocity = new Vector3(data.vel_x, data.vel_y, data.vel_z);
                            cancelPositionUpdate = true;
                        }
                        else
                            if ((data.vstate & VehicleState.IsEnteringVehicle) != 0)
                            {
                                ped.animator.playAnimation(PedAnimations.EnterClosestVehicle);
                                cancelPositionUpdate = true;
                            }
                            else
                                if ((data.state & PlayerState.IsCrouching) != 0)
                                {
                                    ped.animator.playAnimation(PedAnimations.Couch);
                                }
                                else
                                {
                                    if ((data.vstate & VehicleState.IsAccelerating) != 0)
                                    {
                                        if ((data.vstate & VehicleState.IsSprinting) != 0)
                                        {
                                            ped.animator.playAnimation(PedAnimations.Run);
                                        }
                                        else
                                        {
                                            ped.animator.playAnimation(PedAnimations.Walk);
                                        }
                                    }
                                    else
                                    {
                                        ped.animator.playAnimation(PedAnimations.StandStill);
                                    }
                                }

                if (!cancelPositionUpdate)
                {
                    ped.gameReference.Position = posnew;
                }
                ped.gameReference.Heading = data.heading;

                //ped.gameReference.Velocity = new Vector3(elemValue.vel_x, elemValue.vel_y, elemValue.vel_z);
                //ped.gameReference.Task.ClearAllImmediately();
            }
        }
Exemplo n.º 10
0
        public void updateVehicle(uint id, UpdateDataStruct data, StreamedPed ped)
        {
            if (data.vehicle_id > 0)
            {
                var posnew = new Vector3(data.pos_x, data.pos_y, data.pos_z);
                StreamedVehicle veh = vehicleController.GetInstance(data.vehicle_id);
                if (veh != null)
                {
                    if (veh.IsStreamedIn())
                    {
                        if (ped != null && ped.IsStreamedIn() && !ped.gameReference.isInVehicle())
                        {
                            if ((data.state & PlayerState.IsPassenger1) != 0)
                            {
                                ped.gameReference.WarpIntoVehicle(veh.gameReference, VehicleSeat.RightFront);
                            }
                            else if ((data.state & PlayerState.IsPassenger2) != 0)
                            {
                                ped.gameReference.WarpIntoVehicle(veh.gameReference, VehicleSeat.LeftRear);
                            }
                            else if ((data.state & PlayerState.IsPassenger3) != 0)
                            {
                                ped.gameReference.WarpIntoVehicle(veh.gameReference, VehicleSeat.RightFront);
                            }
                            else
                            {
                                ped.gameReference.WarpIntoVehicle(veh.gameReference, VehicleSeat.Driver);
                            }
                        }

                        int healthDelta = data.ped_health - ped.gameReference.Health;
                        ped.gameReference.Health = data.ped_health;
                        ped.last_game_health = data.ped_health;

                        if (healthDelta > 20 && healthDelta < 100)
                        {
                            var bpf = new BinaryPacketFormatter(Commands.Player_damage);
                            bpf.Add(id);
                            //Client.instance.chatController.writeChat("damaged " + healthDelta) ;
                            Client.instance.serverConnection.write(bpf.getBytes());
                        }

                        int vehicleHealthDelta = data.vehicle_health - veh.gameReference.Health;
                        veh.gameReference.Health = data.vehicle_health;
                        veh.last_game_health = data.vehicle_health;

                        if (vehicleHealthDelta > 20 && vehicleHealthDelta < 2000 && data.vehicle_id > 0)
                        {
                            var bpf = new BinaryPacketFormatter(Commands.Vehicle_damage, id, data.vehicle_id, vehicleHealthDelta);
                            Client.instance.serverConnection.write(bpf.getBytes());
                        }

                        if ((data.vstate & VehicleState.IsAsPassenger) != 0) return;
                        veh.position = posnew;
                        if (veh.gameReference.Position.DistanceTo(posnew) > 1.0f)
                        {
                            veh.gameReference.Position = posnew;
                        }
                        //veh.gameReference.Position = posnew;
                        veh.orientation = new Quaternion(data.rot_x, data.rot_y, data.rot_z, data.rot_a);
                        //veh.gameReference.ApplyForce(, Vector3.Zero);
                        veh.gameReference.RotationQuaternion = veh.orientation;
                        var vel = new Vector3(data.vel_x, data.vel_y, data.vel_z);
                        if (System.Math.Abs(veh.gameReference.Velocity.Length() - vel.Length()) > 6.0f)
                        {
                            veh.gameReference.ApplyForce(vel);
                        }
                        if ((data.vstate & VehicleState.IsBraking) == 0)
                        {
                            ped.gameReference.Task.DrivePointRoute(veh.gameReference, 999.0f, posnew - veh.gameReference.Velocity);
                        }
                        else
                        {
                            ped.gameReference.Task.DrivePointRoute(veh.gameReference, 999.0f, posnew + veh.gameReference.Velocity);
                        }
                        if ((data.state & PlayerState.IsShooting) != 0)
                        {
                            Vector3 pos = veh.gameReference.Position + veh.gameReference.Direction;
                            GTA.Native.Function.Call("FIRE_PED_WEAPON", ped.gameReference, pos.X, pos.Y, pos.Z);
                            GTA.Native.Function.Call("TASK_SHOOT_AT_COORD", ped.gameReference, pos.X, pos.Y, pos.Z, (Int32)4, 999992);
                        }
                    }
                }
            }
        }
        public UpdateDataStruct readUpdateStruct()
        {
            if (readNextType() != BinaryPacketFormatter.Types.UpdateDataStruct) throw new Exception("Desynchronization UpdateDataStruct");
            UpdateDataStruct output = new UpdateDataStruct();
            output.timestamp = readInt64(true);
            output.pos_x = readSingle(true);
            output.pos_y = readSingle(true);
            output.pos_z = readSingle(true);

            output.rot_x = readSingle(true);
            output.rot_y = readSingle(true);
            output.rot_z = readSingle(true);
            output.rot_a = readSingle(true);

            output.vel_x = readSingle(true);
            output.vel_y = readSingle(true);
            output.vel_z = readSingle(true);
            output.camdir_x = readSingle(true);
            output.camdir_y = readSingle(true);
            output.camdir_z = readSingle(true);

            output.heading = readSingle(true);

            output.vehicle_model = readInt32(true);
            output.ped_health = readInt32(true);
            output.vehicle_health = readInt32(true);
            output.weapon = readInt32(true);
            output.vehicle_id = readUInt32(true);

            output.state = (PlayerState)readByte(true);
            output.vstate = (VehicleState)readByte(true);

            return output;
        }
        private void onReceive(IAsyncResult iar)
        {
            lock (Connection)
            {
                try
                {
                    int count = Connection.Client.EndReceive(iar);
                }
                catch
                {
                    Console.WriteLine("Client disconnected");
                    return;
                }

                var bpr = new BinaryPacketReader(Buffer);
                while (bpr.canRead())
                {
                    Commands command = bpr.readCommand();
                    if (command == Commands.Invalid)
                    {
                        break;
                    }
                    switch (command)
                    {
                    case Commands.Disconnect:
                    {
                        if (Player != null)
                        {
                            Server.instance.api.invokeOnPlayerDisconnect(Player);
                        }
                    }
                    break;

                    case Commands.Connect:
                    {
                        string nick = bpr.readString();
                        if (OnConnect != null)
                        {
                            OnConnect.Invoke(nick);
                        }
                    }
                    break;

                    case Commands.InternalClient_requestSpawn:
                    {
                        if (Player != null)
                        {
                            Server.instance.api.invokeOnPlayerDie(Player);
                            Server.instance.api.invokeOnPlayerSpawn(Player);
                            var bpf = new BinaryPacketFormatter(Commands.InternalClient_finishSpawn);
                            Player.connection.write(bpf.getBytes());
                        }
                    }
                    break;

                    case Commands.Client_ping:
                    {
                        Int64 timestamp = bpr.readInt64();
                        Int64 current   = DateTime.Now.Ticks;
                        Player.Ping = (int)((current - timestamp) / 10000);
                    }
                    break;

                    case Commands.Request_getSelectedPlayer:
                    {
                        if (Player != null)
                        {
                            uint requestid = bpr.readUInt32();
                            uint playerid  = bpr.readUInt32();
                            Request.dispatch(requestid, playerid);
                        }
                    }
                    break;

                    case Commands.Request_getCameraPosition:
                    {
                        if (Player != null)
                        {
                            uint requestid = bpr.readUInt32();
                            var  vect      = bpr.readVector3();
                            Request.dispatch(requestid, vect);
                        }
                    }
                    break;

                    case Commands.Request_isObjectVisible:
                    {
                        if (Player != null)
                        {
                            uint requestid = bpr.readUInt32();
                            var  vect      = bpr.readByte() == 1;
                            Request.dispatch(requestid, vect);
                        }
                    }
                    break;

                    case Commands.Request_worldToScreen:
                    {
                        if (Player != null)
                        {
                            uint requestid = bpr.readUInt32();
                            var  x         = bpr.readSingle();
                            var  y         = bpr.readSingle();
                            Request.dispatch(requestid, new SharpDX.Vector2(x, y));
                        }
                    }
                    break;

                    case Commands.Chat_sendMessage:
                    {
                        string text = bpr.readString();
                        if (text.StartsWith("/"))
                        {
                            List <string> split = text.Split(' ').ToList();
                            Server.instance.api.invokeOnPlayerSendCommand(Player, split.First().Substring(1), split.Skip(1).ToArray());
                        }
                        else
                        {
                            Server.instance.api.invokeOnPlayerSendText(Player, text);
                        }
                    }
                    break;

                    case Commands.Player_damage:
                    {
                        if (Player != null)
                        {
                            uint playerid = bpr.readUInt32();
                            var  bpf      = new BinaryPacketFormatter(Commands.Player_setHealth);
                            int  newvalue = Server.instance.getPlayerById(playerid).data.ped_health - 10;
                            bpf.Add(newvalue);
                            var damaged_player = Server.instance.getPlayerById(playerid);
                            damaged_player.connection.write(bpf.getBytes());
                            if (newvalue <= 0 && !Player.isDead)
                            {
                                Player.isDead = true;
                                Server.instance.api.invokeOnPlayerDie(damaged_player, Player, (Enums.Weapon)Player.data.weapon);
                            }
                        }
                    }
                    break;

                    case Commands.Vehicle_damage:
                    {
                        if (Player != null)
                        {
                            uint playerid  = bpr.readUInt32();
                            uint vehicleid = bpr.readUInt32();
                            int  delta     = bpr.readInt32();
                            var  bpf       = new BinaryPacketFormatter(Commands.Player_setVehicleHealth);
                            int  newvalue  = Server.instance.vehicleController.getById(vehicleid).health - delta;
                            bpf.Add(newvalue);
                            Server.instance.getPlayerById(playerid).connection.write(bpf.getBytes());
                        }
                    }
                    break;

                    case Commands.Keys_down:
                    {
                        if (Player != null)
                        {
                            int key = bpr.readInt32();
                            Server.instance.api.invokeOnPlayerKeyDown(Player, (System.Windows.Forms.Keys)key);
                        }
                    }
                    break;

                    case Commands.Keys_up:
                    {
                        if (Player != null)
                        {
                            int key = bpr.readInt32();
                            Server.instance.api.invokeOnPlayerKeyUp(Player, (System.Windows.Forms.Keys)key);
                        }
                    }
                    break;

                    case Commands.NPCDialog_sendResponse:
                    {
                        if (Player != null)
                        {
                            uint key    = bpr.readUInt32();
                            byte answer = Buffer[6];
                            ServerNPCDialog.invokeResponse(Player, key, answer);
                        }
                    }
                    break;

                    case Commands.UpdateData:
                    {
                        if (Player != null)
                        {
                            MIVSDK.UpdateDataStruct data = bpr.readUpdateStruct();
                            if (Player.data.ped_health > data.ped_health)
                            {
                                Server.instance.api.invokeOnPlayerTakeDamage(Player, Player.data.ped_health, data.ped_health, Player.data.ped_health - data.ped_health);
                            }
                            Player.updateData(data);
                        }
                    }
                    break;
                    }
                }

                Connection.Client.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, onReceive, null);
            }
        }