Example #1
0
        internal void ResendBulletPacket(int netHandle, int netHandleTarget, bool shooting, Client exception)
        {
            var full = PacketOptimization.WriteBulletSync(netHandle, shooting, netHandleTarget);

            var msg = Server.CreateMessage();

            msg.Write((byte)PacketType.BulletPlayerSync);
            msg.Write(full.Length);
            msg.Write(full);

            List <NetConnection> connections = new List <NetConnection>();

            foreach (var client in exception.Streamer.GetNearClients())
            {
                if (client.NetConnection.Status == NetConnectionStatus.Disconnected)
                {
                    continue;
                }
                if (client.NetConnection.RemoteUniqueIdentifier == exception.NetConnection.RemoteUniqueIdentifier)
                {
                    continue;
                }
                //if (range && client.Position.DistanceToSquared(exception.Position) > 80000) continue;

                connections.Add(client.NetConnection);
            }

            Server.SendMessage(msg, connections, NetDeliveryMethod.ReliableSequenced, (int)ConnectionChannel.BulletSync);
        }
Example #2
0
        //Ped Packet
        internal void ResendPacket(PedData fullPacket, Client exception, bool pure)
        {
            byte[] full;
            var    basic = new byte[0];

            if (pure)
            {
                full = PacketOptimization.WritePureSync(fullPacket);
                if (fullPacket.NetHandle != null)
                {
                    basic = PacketOptimization.WriteBasicSync(fullPacket.NetHandle.Value, fullPacket.Position);
                }
            }
            else
            {
                full = PacketOptimization.WriteLightSync(fullPacket);
            }

            var msg = Server.CreateMessage();

            if (pure)
            {
                //if (client.Position.DistanceToSquared(fullPacket.Position) > 10000) // 1km
                //{
                //    var lastUpdateReceived = client.LastPacketReceived.Get(exception.handle.Value);

                //    if (lastUpdateReceived != 0 && Program.GetTicks() - lastUpdateReceived <= 1000) continue;
                //    msg.Write((byte)PacketType.BasicSync);
                //    msg.Write(basic.Length);
                //    msg.Write(basic);
                //    Server.SendMessage(msg, client.NetConnection, NetDeliveryMethod.UnreliableSequenced, (int)ConnectionChannel.BasicSync);

                //    client.LastPacketReceived.Set(exception.handle.Value, Program.GetTicks());
                //}
                //else
                //{
                msg.Write((byte)PacketType.PedPureSync);
                msg.Write(full.Length);
                msg.Write(full);
                //}
            }
            else
            {
                msg.Write((byte)PacketType.PedLightSync);
                msg.Write(full.Length);
                msg.Write(full);
            }

            List <NetConnection> connectionsNear = new List <NetConnection>();

            foreach (var client in exception.Streamer.GetNearClients())
            {
                if (client.Fake)
                {
                    continue;
                }
                if (client.NetConnection.Status == NetConnectionStatus.Disconnected)
                {
                    continue;
                }
                if (!client.ConnectionConfirmed)
                {
                    continue;
                }
                if (client == exception)
                {
                    continue;
                }

                if (pure)
                {
                    if (client.Position == null)
                    {
                        continue;
                    }

                    connectionsNear.Add(client.NetConnection);
                }
                else
                {
                    connectionsNear.Add(client.NetConnection);
                }
            }

            if (pure)
            {
                Server.SendMessage(msg, connectionsNear, NetDeliveryMethod.UnreliableSequenced, (int)ConnectionChannel.PureSync);
            }
            else
            {
                Server.SendMessage(msg, connectionsNear, NetDeliveryMethod.ReliableSequenced, (int)ConnectionChannel.LightSync);
            }


            if (pure)
            {
                var msgBasic = Server.CreateMessage();

                msgBasic.Write((byte)PacketType.BasicSync);
                msgBasic.Write(basic.Length);
                msgBasic.Write(basic);

                long ticks = Program.GetTicks();

                List <NetConnection> connectionsFar = new List <NetConnection>();

                foreach (var client in exception.Streamer.GetFarClients())
                {
                    if (client.Fake)
                    {
                        continue;
                    }
                    if (client.NetConnection.Status == NetConnectionStatus.Disconnected)
                    {
                        continue;
                    }
                    if (!client.ConnectionConfirmed)
                    {
                        continue;
                    }
                    if (client == exception)
                    {
                        continue;
                    }

                    var lastUpdateReceived = client.LastPacketReceived.Get(exception.handle.Value);

                    if (lastUpdateReceived != 0 && ticks - lastUpdateReceived <= 1000)
                    {
                        continue;
                    }

                    connectionsFar.Add(client.NetConnection);
                    client.LastPacketReceived.Set(exception.handle.Value, ticks);
                }

                Server.SendMessage(msgBasic, connectionsFar, NetDeliveryMethod.UnreliableSequenced, (int)ConnectionChannel.BasicSync);
            }
        }
Example #3
0
        public static void InvokeEvents(object sender, EventArgs e)
        {
            var player = Game.Player.Character;

            #region invokeonLocalPlayerShoot
            if (player != null && player.IsShooting)
            {
                JavascriptHook.InvokeCustomEvent(api => api?.invokeonLocalPlayerShoot((int)(player.Weapons.Current?.Hash ?? 0), Main.RaycastEverything(new Vector2(0, 0)).ToLVector()));
            }
            #endregion

            //#region invokeonPlayerRespawn
            var hasRespawned = (Function.Call <int>(Hash.GET_TIME_SINCE_LAST_DEATH) < 8000 &&
                                Function.Call <int>(Hash.GET_TIME_SINCE_LAST_DEATH) != -1 &&
                                Game.Player.CanControlCharacter);

            if (hasRespawned && !_lastDead)
            {
                _lastDead = true;
                var msg = Main.Client.CreateMessage();
                msg.Write((byte)PacketType.PlayerRespawned);
                Main.Client.SendMessage(msg, NetDeliveryMethod.ReliableOrdered, (int)ConnectionChannel.SyncEvent);

                JavascriptHook.InvokeCustomEvent(api => api?.invokeonPlayerRespawn());

                if (Main.Weather != null)
                {
                    Function.Call(Hash.SET_WEATHER_TYPE_NOW_PERSIST, Main.Weather);
                }
                if (Main.Time.HasValue)
                {
                    World.CurrentDayTime = new TimeSpan(Main.Time.Value.Hours, Main.Time.Value.Minutes, 00);
                }

                Function.Call(Hash.PAUSE_CLOCK, true);

                var us = Main.NetEntityHandler.EntityToStreamedItem(Game.Player.Character.Handle);

                Main.NetEntityHandler.ReattachAllEntities(us, true);
                foreach (
                    var source in
                    Main.NetEntityHandler.ClientMap.Values.Where(
                        item => item is RemoteParticle && ((RemoteParticle)item).EntityAttached == us.RemoteHandle)
                    .Cast <RemoteParticle>())
                {
                    Main.NetEntityHandler.StreamOut(source);
                    Main.NetEntityHandler.StreamIn(source);
                }
            }

            var pHealth = player.Health;
            var pArmor  = player.Armor;
            var pGun    = player.Weapons.Current?.Hash ?? WeaponHash.Unarmed;
            var pModel  = player.Model.Hash;

            if (pHealth != _lastPlayerHealth)
            {
                int test = _lastPlayerHealth;
                JavascriptHook.InvokeCustomEvent(api => api?.invokeonPlayerHealthChange(test));
            }

            if (pArmor != _lastPlayerArmor)
            {
                int test = _lastPlayerArmor;
                JavascriptHook.InvokeCustomEvent(api => api?.invokeonPlayerArmorChange(test));
            }

            if (pGun != _lastPlayerWeapon)
            {
                WeaponHash test = _lastPlayerWeapon;
                JavascriptHook.InvokeCustomEvent(api => api?.invokeonPlayerWeaponSwitch((int)test));
            }

            if (pModel != (int)_lastPlayerModel)
            {
                PedHash test = _lastPlayerModel;
                JavascriptHook.InvokeCustomEvent(api => api?.invokeonPlayerModelChange((int)test));
            }

            _lastPlayerHealth = pHealth;
            _lastPlayerArmor  = pArmor;
            _lastPlayerWeapon = pGun;
            _lastPlayerModel  = (PedHash)pModel;

            _lastDead = hasRespawned;

            var killed = Game.Player.Character.IsDead;
            if (killed && !_lastKilled)
            {
                var msg = Main.Client.CreateMessage();
                msg.Write((byte)PacketType.PlayerKilled);
                var killer = Function.Call <int>(Hash.GET_PED_SOURCE_OF_DEATH, Game.Player.Character);
                var weapon = Function.Call <int>(Hash.GET_PED_CAUSE_OF_DEATH, Game.Player.Character);

                var killerEnt = Main.NetEntityHandler.EntityToNet(killer);
                msg.Write(killerEnt);
                msg.Write(weapon);

                Main.Client.SendMessage(msg, NetDeliveryMethod.ReliableOrdered, (int)ConnectionChannel.SyncEvent);

                JavascriptHook.InvokeCustomEvent(api => api?.invokeonPlayerDeath(new LocalHandle(killer), weapon));

                //TODO: ADD OPTION TO ENABLE IT
                NativeUI.BigMessageThread.MessageInstance.ShowColoredShard("WASTED", "", HudColor.HUD_COLOUR_BLACK, HudColor.HUD_COLOUR_RED, 7000);
                Function.Call(Hash.REQUEST_SCRIPT_AUDIO_BANK, "HUD_MINI_GAME_SOUNDSET", true);
                Function.Call(Hash.PLAY_SOUND_FRONTEND, -1, "CHECKPOINT_NORMAL", "HUD_MINI_GAME_SOUNDSET");
            }

            _lastKilled = killed;

            if (player.CurrentVehicle != null)
            {
                var playerCar    = player.CurrentVehicle;
                var netPlayerCar = 0;


                RemoteVehicle cc = null;

                //invokeonVehicleHealthChange
                //invokeonVehicleWindowSmash
                #region invokeonVehicleDoorBreak
                if ((netPlayerCar = Main.NetEntityHandler.EntityToNet(playerCar.Handle)) != 0)
                {
                    var item = Main.NetEntityHandler.NetToStreamedItem(netPlayerCar) as RemoteVehicle;

                    if (item != null)
                    {
                        var lastHealth      = item.Health;
                        var lastDamageModel = item.DamageModel;

                        item.Position    = playerCar.Position.ToLVector();
                        item.Rotation    = playerCar.Rotation.ToLVector();
                        item.Health      = playerCar.EngineHealth;
                        item.IsDead      = playerCar.IsDead;
                        item.DamageModel = playerCar.GetVehicleDamageModel();

                        if (lastHealth != playerCar.EngineHealth)
                        {
                            JavascriptHook.InvokeCustomEvent(api => api?.invokeonVehicleHealthChange((int)lastHealth));
                        }

                        if (playerCar.IsEngineRunning ^ !PacketOptimization.CheckBit(item.Flag, EntityFlag.EngineOff))
                        {
                            playerCar.IsEngineRunning = !PacketOptimization.CheckBit(item.Flag, EntityFlag.EngineOff);
                        }

                        if (lastDamageModel != null)
                        {
                            if (lastDamageModel.BrokenWindows != item.DamageModel.BrokenWindows)
                            {
                                for (var i = 0; i < 8; i++)
                                {
                                    if (((lastDamageModel.BrokenWindows ^ item.DamageModel.BrokenWindows) & 1 << i) == 0)
                                    {
                                        continue;
                                    }
                                    var i1 = i;
                                    JavascriptHook.InvokeCustomEvent(api => api?.invokeonVehicleWindowSmash(i1));
                                }
                            }

                            if (lastDamageModel.BrokenDoors != item.DamageModel.BrokenDoors)
                            {
                                for (var i = 0; i < 8; i++)
                                {
                                    if (((lastDamageModel.BrokenDoors ^ item.DamageModel.BrokenDoors) & 1 << i) == 0)
                                    {
                                        continue;
                                    }
                                    var i1 = i;
                                    JavascriptHook.InvokeCustomEvent(api => api?.invokeonVehicleDoorBreak(i1));
                                }
                            }
                        }
                    }

                    cc = item;
                }
                #endregion

                #region invokeonPlayerExitVehicle
                if (playerCar != _lastPlayerCar)
                {
                    if (_lastPlayerCar != null)
                    {
                        var c = Main.NetEntityHandler.EntityToStreamedItem(_lastPlayerCar.Handle) as RemoteVehicle;

                        if (Main.VehicleSyncManager.IsSyncing(c))
                        {
                            _lastPlayerCar.IsInvincible = c?.IsInvincible ?? false;
                        }
                        else
                        {
                            _lastPlayerCar.IsInvincible = true;
                        }

                        if (c != null)
                        {
                            Function.Call(Hash.SET_VEHICLE_ENGINE_ON, _lastPlayerCar, !PacketOptimization.CheckBit(c.Flag, EntityFlag.EngineOff), true, true);
                        }

                        var h  = _lastPlayerCar.Handle;
                        var lh = new LocalHandle(h);
                        JavascriptHook.InvokeCustomEvent(api => api?.invokeonPlayerExitVehicle(lh));
                        _lastVehicleSiren = false;
                        _lastPlayerCar    = null;
                    }

                    //invokeonPlayerEnterVehicle
                    if (!Main.NetEntityHandler.ContainsLocalHandle(playerCar.Handle))
                    {
                        playerCar.Delete();
                        playerCar = null;
                    }
                    else
                    {
                        playerCar.IsInvincible = cc?.IsInvincible ?? false;

                        var handle = new LocalHandle(playerCar.Handle);
                        JavascriptHook.InvokeCustomEvent(api => api?.invokeonPlayerEnterVehicle(handle));
                        LastCarEnter   = DateTime.Now;
                        _lastPlayerCar = playerCar;
                    }
                }
                #endregion

                #region invokeonVehicleSirenToggle
                if (Util.Util.GetResponsiblePed(playerCar, player).Handle != 0)
                {
                    playerCar.IsInvincible = cc?.IsInvincible ?? false;
                }
                else
                {
                    playerCar.IsInvincible = true;
                }

                var siren = playerCar.IsSirenActive;

                if (siren != _lastVehicleSiren)
                {
                    JavascriptHook.InvokeCustomEvent(api => api?.invokeonVehicleSirenToggle());
                }

                _lastVehicleSiren = siren;
                #endregion
            }
            else
            {
                if (_lastPlayerCar != null)
                {
                    var c = Main.NetEntityHandler.EntityToStreamedItem(_lastPlayerCar.Handle) as RemoteVehicle;

                    if (Main.VehicleSyncManager.IsSyncing(c))
                    {
                        _lastPlayerCar.IsInvincible = c?.IsInvincible ?? false;
                    }
                    else
                    {
                        _lastPlayerCar.IsInvincible = true;
                    }

                    if (c != null)
                    {
                        Function.Call(Hash.SET_VEHICLE_ENGINE_ON, _lastPlayerCar, !PacketOptimization.CheckBit(c.Flag, EntityFlag.EngineOff), true, true);
                    }

                    var h  = _lastPlayerCar.Handle;
                    var lh = new LocalHandle(h);
                    JavascriptHook.InvokeCustomEvent(api => api?.invokeonPlayerExitVehicle(lh));
                    _lastVehicleSiren = false;
                    _lastPlayerCar    = null;
                }
            }
        }
Example #4
0
        internal void ResendUnoccupiedPacket(VehicleData fullPacket, Client exception)
        {
            if (fullPacket.NetHandle == null)
            {
                return;
            }

            var vehicleEntity = new NetHandle(fullPacket.NetHandle.Value);
            var full          = PacketOptimization.WriteUnOccupiedVehicleSync(fullPacket);
            var basic         = PacketOptimization.WriteBasicUnOccupiedVehicleSync(fullPacket);

            var msgNear = Server.CreateMessage();

            msgNear.Write((byte)PacketType.UnoccupiedVehSync);
            msgNear.Write(full.Length);
            msgNear.Write(full);

            var msgFar = Server.CreateMessage();

            msgFar.Write((byte)PacketType.BasicUnoccupiedVehSync);
            msgFar.Write(basic.Length);
            msgFar.Write(basic);

            List <NetConnection> connectionsNear = new List <NetConnection>();
            List <NetConnection> connectionsFar  = new List <NetConnection>();

            foreach (var client in exception.Streamer.GetNearClients())
            {
                // skip sending a sync packet for a trailer to it's owner.
                if (CheckUnoccupiedTrailerDriver(client, vehicleEntity))
                {
                    continue;
                }
                if (client.NetConnection.Status == NetConnectionStatus.Disconnected)
                {
                    continue;
                }
                if (client.NetConnection.RemoteUniqueIdentifier == exception.NetConnection.RemoteUniqueIdentifier)
                {
                    continue;
                }

                if (client.Position == null)
                {
                    continue;
                }
                if (client.Position.DistanceToSquared(fullPacket.Position) < 20000)
                {
                    connectionsNear.Add(client.NetConnection);
                }
                else
                {
                    connectionsFar.Add(client.NetConnection);
                }
            }

            Server.SendMessage(msgNear, connectionsNear,
                               NetDeliveryMethod.UnreliableSequenced,
                               (int)ConnectionChannel.UnoccupiedVeh);

            foreach (var client in exception.Streamer.GetFarClients())
            {
                connectionsFar.Add(client.NetConnection);
            }

            Server.SendMessage(msgFar, connectionsFar,
                               NetDeliveryMethod.UnreliableSequenced,
                               (int)ConnectionChannel.UnoccupiedVeh);
        }
Example #5
0
        private bool CreateCharacter()
        {
            if (Character == null || !Character.Exists() || Character.Model.Hash != ModelHash)
            {
                if (Character != null && Character.Exists())
                {
                    Character?.Delete();
                }

                var gPos      = Position;
                var charModel = new Model(ModelHash);
                Util.Util.LoadModel(charModel);
                //Character = new Ped(Function.Call<int>(Hash.CREATE_PED, 26, charModel.Hash, gPos.X, gPos.Y, gPos.Z, _rotation.Z, false, false));
                Character = World.CreatePed(charModel, gPos, _rotation.Z);
                charModel.MarkAsNoLongerNeeded();

                if (Character == null)
                {
                    return(true);
                }

                lock (Main.NetEntityHandler.ClientMap) Main.NetEntityHandler.HandleMap.Set(RemoteHandle, Character.Handle);

                Character.CanBeTargetted       = true;
                Character.BlockPermanentEvents = true;
                //Function.Call(Hash.TASK_SET_BLOCKING_OF_NON_TEMPORARY_EVENTS, Character, true);
                //Character.IsInvincible = true;
                Character.CanRagdoll            = false;
                Character.CanSufferCriticalHits = false;

                if (Team == -1 || Team != Main.LocalTeam)
                {
                    Character.RelationshipGroup = Main.RelGroup;
                    //Function.Call(Hash.SET_PED_RELATIONSHIP_GROUP_DEFAULT_HASH, Character, Main.RelGroup);
                }
                else
                {
                    Character.RelationshipGroup = Main.FriendRelGroup;
                    //Function.Call(Hash.SET_PED_RELATIONSHIP_GROUP_DEFAULT_HASH, Character, Main.FriendRelGroup);
                }

                Character.FiringPattern = FiringPattern.FullAuto;
                Function.Call(Hash.SET_PED_DEFAULT_COMPONENT_VARIATION, Character); //BUG: <- Maybe causes crash?
                Function.Call(Hash.SET_PED_CAN_EVASIVE_DIVE, Character, false);
                Function.Call(Hash.SET_PED_DROPS_WEAPONS_WHEN_DEAD, Character, false);
                Function.Call(Hash.SET_PED_CAN_BE_TARGETTED, Character, true);
                Function.Call(Hash.SET_PED_CAN_BE_TARGETTED_BY_PLAYER, Character, Game.Player, true);
                Function.Call(Hash.SET_PED_GET_OUT_UPSIDE_DOWN_VEHICLE, Character, false);
                Function.Call(Hash.SET_PED_AS_ENEMY, Character, false);
                Function.Call(Hash.SET_CAN_ATTACK_FRIENDLY, Character, true, true);

                if (Alpha < 255)
                {
                    Character.Opacity = Alpha;
                }

                if (Props != null)
                {
                    foreach (var pair in Props)
                    {
                        Function.Call(Hash.SET_PED_COMPONENT_VARIATION, Character, pair.Key, pair.Value, Textures[pair.Key], 2);
                    }
                }

                if (Accessories != null)
                {
                    foreach (var pair in Accessories)
                    {
                        Function.Call(Hash.SET_PED_COMPONENT_VARIATION, Character, pair.Key, pair.Value.Item1, pair.Value.Item2, 2);
                    }
                }

                Main.NetEntityHandler.ReattachAllEntities(this, false);

                foreach (var source in Main.NetEntityHandler.ClientMap.Values
                         .Where(item => item is RemoteParticle && ((RemoteParticle)item).EntityAttached == RemoteHandle)
                         .Cast <RemoteParticle>())
                {
                    Main.NetEntityHandler.StreamOut(source);
                    Main.NetEntityHandler.StreamIn(source);
                }

                if (PacketOptimization.CheckBit(Flag, EntityFlag.Collisionless))
                {
                    Character.IsCollisionEnabled = false;
                }

                JavascriptHook.InvokeStreamInEvent(new LocalHandle(Character.Handle), (int)GTANetworkShared.EntityType.Player);
                return(true);
            }

            return(false);
        }
        internal void Pulse()
        {
            if (Util.Util.TickCount - _lastUpdate > UNOCCUPIED_VEH_RATE)
            {
                _lastUpdate = Util.Util.TickCount;

                if (SyncedVehicles.Count > 0)
                {
                    var vehicleCount = 0;
                    var buffer       = new List <byte>();

                    lock (SyncedVehicles)
                    {
                        foreach (var vehicle in SyncedVehicles)
                        {
                            var ent = Main.NetEntityHandler.NetToEntity(vehicle);

                            if (ent == null || !vehicle.StreamedIn)
                            {
                                continue;
                            }

                            var dist = ent.Model.IsBoat ? ent.Position.DistanceToSquared2D(vehicle.Position.ToVector()) : ent.Position.DistanceToSquared(vehicle.Position.ToVector());

                            var veh = new Vehicle(ent.Handle);

                            byte BrokenDoors   = 0;
                            byte BrokenWindows = 0;

                            for (var i = 0; i < 8; i++)
                            {
                                if (veh.Doors[(VehicleDoorIndex)i].IsBroken)
                                {
                                    BrokenDoors |= (byte)(1 << i);
                                }
                                if (!veh.Windows[(VehicleWindowIndex)i].IsIntact)
                                {
                                    BrokenWindows |= (byte)(1 << i);
                                }
                            }

                            var syncUnocVeh = dist > 2f || ent.Rotation.DistanceToSquared(vehicle.Rotation.ToVector()) > 2f ||
                                              Math.Abs(new Vehicle(ent.Handle).EngineHealth - vehicle.Health) > 1f ||
                                              Util.Util.BuildTyreFlag(new Vehicle(ent.Handle)) != vehicle.Tires ||
                                              vehicle.DamageModel == null ||
                                              vehicle.DamageModel.BrokenWindows != BrokenWindows ||
                                              vehicle.DamageModel.BrokenDoors != BrokenDoors;

                            if (!syncUnocVeh)
                            {
                                continue;
                            }
                            {
                                vehicle.Position = ent.Position.ToLVector();
                                vehicle.Rotation = ent.Rotation.ToLVector();
                                vehicle.Health   = veh.EngineHealth;
                                vehicle.Tires    = (byte)Util.Util.BuildTyreFlag(veh);

                                if (vehicle.DamageModel == null)
                                {
                                    vehicle.DamageModel = new VehicleDamageModel();
                                }

                                vehicle.DamageModel.BrokenWindows = BrokenWindows;
                                vehicle.DamageModel.BrokenDoors   = BrokenDoors;

                                var data = new VehicleData
                                {
                                    VehicleHandle = vehicle.RemoteHandle,
                                    Position      = vehicle.Position,
                                    Quaternion    = vehicle.Rotation,
                                    Velocity      = ent.Velocity.ToLVector(),
                                    VehicleHealth = vehicle.Health,
                                    DamageModel   = new VehicleDamageModel()
                                    {
                                        BrokenWindows = BrokenWindows,
                                        BrokenDoors   = BrokenDoors,
                                    }
                                };

                                if (ent.IsDead)
                                {
                                    data.Flag = (short)VehicleDataFlags.VehicleDead;
                                }
                                else
                                {
                                    data.Flag = 0;
                                }

                                byte tyreFlag = 0;

                                for (int i = 0; i < 8; i++)
                                {
                                    if (veh.IsTireBurst(i))
                                    {
                                        tyreFlag |= (byte)(1 << i);
                                    }
                                }

                                data.PlayerHealth = tyreFlag;

                                var bin = PacketOptimization.WriteUnOccupiedVehicleSync(data);

                                buffer.AddRange(bin);
                                vehicleCount++;
                            }
                        }
                    }

                    if (vehicleCount > 0)
                    {
                        buffer.Insert(0, (byte)vehicleCount);

                        var msg = Main.Client.CreateMessage();
                        msg.Write((byte)PacketType.UnoccupiedVehSync);
                        msg.Write(buffer.Count);
                        msg.Write(buffer.ToArray());

                        Main.Client.SendMessage(msg, NetDeliveryMethod.Unreliable, (int)ConnectionChannel.UnoccupiedVeh);

                        Main._bytesSent += buffer.Count;
                        Main._messagesSent++;
                    }
                }
            }

            for (int i = 0; i < Interpolations.Count; i++)
            {
                var pair = Interpolations.ElementAt(i);

                pair.Value.Pulse();

                if (pair.Value.HasFinished)
                {
                    Interpolations.Remove(pair.Key);
                }
            }
        }
Example #7
0
        private void HandleVehiclePacket(VehicleData fullData, bool purePacket)
        {
            if (fullData.NetHandle == null)
            {
                return;
            }
            var syncPed = NetEntityHandler.GetPlayer(fullData.NetHandle.Value);

            syncPed.IsInVehicle = true;

            if (fullData.VehicleHandle != null)
            {
                LogManager.DebugLog("RECEIVED LIGHT VEHICLE PACKET " + fullData.VehicleHandle);
            }

            if (fullData.Position != null)
            {
                syncPed.Position = fullData.Position.ToVector();
            }

            if (fullData.VehicleHandle != null)
            {
                syncPed.VehicleNetHandle = fullData.VehicleHandle.Value;
            }
            if (fullData.Velocity != null)
            {
                syncPed.VehicleVelocity = fullData.Velocity.ToVector();
            }
            if (fullData.PedModelHash != null)
            {
                syncPed.ModelHash = fullData.PedModelHash.Value;
            }
            if (fullData.PedArmor != null)
            {
                syncPed.PedArmor = fullData.PedArmor.Value;
            }
            if (fullData.RPM != null)
            {
                syncPed.VehicleRPM = fullData.RPM.Value;
            }
            if (fullData.Quaternion != null)
            {
                syncPed.VehicleRotation = fullData.Quaternion.ToVector();
            }
            if (fullData.PlayerHealth != null)
            {
                syncPed.PedHealth = fullData.PlayerHealth.Value;
            }
            if (fullData.VehicleHealth != null)
            {
                syncPed.VehicleHealth = fullData.VehicleHealth.Value;
            }
            if (fullData.VehicleSeat != null)
            {
                syncPed.VehicleSeat = fullData.VehicleSeat.Value;
            }
            if (fullData.Latency != null)
            {
                syncPed.Latency = fullData.Latency.Value;
            }
            if (fullData.Steering != null)
            {
                syncPed.SteeringScale = fullData.Steering.Value;
            }
            if (fullData.Velocity != null)
            {
                syncPed.Speed = fullData.Velocity.ToVector().Length();
            }
            if (fullData.DamageModel != null && syncPed.MainVehicle != null)
            {
                syncPed.MainVehicle.SetVehicleDamageModel(fullData.DamageModel);
            }

            if (fullData.Flag != null)
            {
                syncPed.IsVehDead      = (fullData.Flag.Value & (short)VehicleDataFlags.VehicleDead) > 0;
                syncPed.IsHornPressed  = (fullData.Flag.Value & (short)VehicleDataFlags.PressingHorn) > 0;
                syncPed.Siren          = (fullData.Flag.Value & (short)VehicleDataFlags.SirenActive) > 0;
                syncPed.IsShooting     = (fullData.Flag.Value & (short)VehicleDataFlags.Shooting) > 0;
                syncPed.IsAiming       = (fullData.Flag.Value & (short)VehicleDataFlags.Aiming) > 0;
                syncPed.IsInBurnout    = (fullData.Flag.Value & (short)VehicleDataFlags.BurnOut) > 0;
                syncPed.ExitingVehicle = (fullData.Flag.Value & (short)VehicleDataFlags.ExitingVehicle) != 0;
                syncPed.IsPlayerDead   = (fullData.Flag.Value & (int)VehicleDataFlags.PlayerDead) != 0;
                syncPed.Braking        = (fullData.Flag.Value & (short)VehicleDataFlags.Braking) != 0;
            }

            if (fullData.WeaponHash != null)
            {
                syncPed.CurrentWeapon = fullData.WeaponHash.Value;
            }

            if (fullData.AimCoords != null)
            {
                syncPed.AimCoords = fullData.AimCoords.ToVector();
            }

            if (syncPed.VehicleNetHandle != 0 && fullData.Position != null)
            {
                var car = NetEntityHandler.NetToStreamedItem(syncPed.VehicleNetHandle) as RemoteVehicle;
                if (car != null)
                {
                    car.Position = fullData.Position;
                    car.Rotation = fullData.Quaternion;
                }
            }
            else if (syncPed.VehicleNetHandle != 00 && fullData.Position == null && fullData.Flag != null && !PacketOptimization.CheckBit(fullData.Flag.Value, VehicleDataFlags.Driver))
            {
                var car = NetEntityHandler.NetToStreamedItem(syncPed.VehicleNetHandle) as RemoteVehicle;
                if (car != null)
                {
                    syncPed.Position        = car.Position.ToVector();
                    syncPed.VehicleRotation = car.Rotation.ToVector();
                }
            }

            if (purePacket)
            {
                syncPed.LastUpdateReceived = Util.Util.TickCount;
                syncPed.StartInterpolation();
            }
        }
Example #8
0
        internal static void MainLoop()
        {
            bool lastPedData       = false;
            int  lastLightSyncSent = 0;

            while (true)
            {
                if (!Main.IsOnServer())
                {
                    Thread.Sleep(100);
                    continue;
                }

                object lastPacket;
                lock (SyncCollector.Lock)
                {
                    lastPacket = SyncCollector.LastSyncPacket;
                    SyncCollector.LastSyncPacket = null;
                }

                if (lastPacket == null)
                {
                    continue;
                }
                try
                {
                    if (lastPacket is PedData)
                    {
                        var bin = PacketOptimization.WritePureSync((PedData)lastPacket);

                        var msg = Main.Client.CreateMessage();
                        msg.Write((byte)PacketType.PedPureSync);
                        msg.Write(bin.Length);
                        msg.Write(bin);

                        try
                        {
                            Main.Client.SendMessage(msg, NetDeliveryMethod.UnreliableSequenced,
                                                    (int)ConnectionChannel.PureSync);
                        }
                        catch (Exception ex)
                        {
                            Util.Util.SafeNotify("FAILED TO SEND DATA: " + ex.Message);
                            LogManager.LogException(ex, "SENDPLAYERDATA");
                        }

                        if (!lastPedData || Environment.TickCount - lastLightSyncSent > LIGHT_SYNC_RATE)
                        {
                            lastLightSyncSent = Environment.TickCount;

                            LogManager.DebugLog("SENDING LIGHT VEHICLE SYNC");

                            var lightBin = PacketOptimization.WriteLightSync((PedData)lastPacket);

                            var lightMsg = Main.Client.CreateMessage();
                            lightMsg.Write((byte)PacketType.PedLightSync);
                            lightMsg.Write(lightBin.Length);
                            lightMsg.Write(lightBin);
                            try
                            {
                                Main.Client.SendMessage(lightMsg, NetDeliveryMethod.ReliableSequenced,
                                                        (int)ConnectionChannel.LightSync);
                            }
                            catch (Exception ex)
                            {
                                Util.Util.SafeNotify("FAILED TO SEND LIGHT DATA: " + ex.Message);
                                LogManager.LogException(ex, "SENDPLAYERDATA");
                            }

                            Main._bytesSent += lightBin.Length;
                            Main._messagesSent++;
                        }

                        lastPedData = true;

                        lock (Main._averagePacketSize)
                        {
                            Main._averagePacketSize.Add(bin.Length);
                            if (Main._averagePacketSize.Count > 10)
                            {
                                Main._averagePacketSize.RemoveAt(0);
                            }
                        }

                        Main._bytesSent += bin.Length;
                        Main._messagesSent++;
                    }
                    else
                    {
                        var bin = PacketOptimization.WritePureSync((VehicleData)lastPacket);

                        var msg = Main.Client.CreateMessage();
                        msg.Write((byte)PacketType.VehiclePureSync);
                        msg.Write(bin.Length);
                        msg.Write(bin);
                        try
                        {
                            Main.Client.SendMessage(msg, NetDeliveryMethod.UnreliableSequenced,
                                                    (int)ConnectionChannel.PureSync);
                        }
                        catch (Exception ex)
                        {
                            Util.Util.SafeNotify("FAILED TO SEND DATA: " + ex.Message);
                            LogManager.LogException(ex, "SENDPLAYERDATA");
                        }

                        if (lastPedData || Environment.TickCount - lastLightSyncSent > LIGHT_SYNC_RATE)
                        {
                            lastLightSyncSent = Environment.TickCount;

                            LogManager.DebugLog("SENDING LIGHT VEHICLE SYNC");

                            var lightBin = PacketOptimization.WriteLightSync((VehicleData)lastPacket);

                            var lightMsg = Main.Client.CreateMessage();
                            lightMsg.Write((byte)PacketType.VehicleLightSync);
                            lightMsg.Write(lightBin.Length);
                            lightMsg.Write(lightBin);
                            try
                            {
                                Main.Client.SendMessage(lightMsg, NetDeliveryMethod.ReliableSequenced,
                                                        (int)ConnectionChannel.LightSync);
                            }
                            catch (Exception ex)
                            {
                                Util.Util.SafeNotify("FAILED TO SEND LIGHT DATA: " + ex.Message);
                                LogManager.LogException(ex, "SENDPLAYERDATA");
                            }

                            Main._bytesSent += lightBin.Length;
                            Main._messagesSent++;
                        }

                        lastPedData = false;

                        lock (Main._averagePacketSize)
                        {
                            Main._averagePacketSize.Add(bin.Length);
                            if (Main._averagePacketSize.Count > 10)
                            {
                                Main._averagePacketSize.RemoveAt(0);
                            }
                        }

                        Main._bytesSent += bin.Length;
                        Main._messagesSent++;
                    }
                }
                catch (Exception ex)
                {
                    LogManager.LogException(ex, "SYNCSENDER");
                }

                LogManager.DebugLog("END SYNC SEND");

                Thread.Sleep(PURE_SYNC_RATE);
            }
        }
Example #9
0
        internal void OnTick(object sender, EventArgs e)
        {
            if (!Main.IsOnServer())
            {
                return;
            }
            var player = Game.Player.Character;

            if (player.IsInVehicle())
            {
                var veh = player.CurrentVehicle;

                var horn    = Game.Player.IsPressingHorn;
                var siren   = veh.SirenActive;
                var vehdead = veh.IsDead;

                var obj = new VehicleData();
                obj.Position      = veh.Position.ToLVector();
                obj.VehicleHandle = Main.NetEntityHandler.EntityToNet(player.CurrentVehicle.Handle);
                obj.Quaternion    = veh.Rotation.ToLVector();
                obj.PedModelHash  = player.Model.Hash;
                obj.PlayerHealth  = (byte)Util.Util.Clamp(0, player.Health, 255);
                obj.VehicleHealth = veh.EngineHealth;
                obj.Velocity      = veh.Velocity.ToLVector();
                obj.PedArmor      = (byte)player.Armor;
                obj.RPM           = veh.CurrentRPM;
                obj.VehicleSeat   = (short)Util.Util.GetPedSeat(player);
                obj.Flag          = 0;
                obj.Steering      = veh.SteeringAngle;

                if (horn)
                {
                    obj.Flag |= (byte)VehicleDataFlags.PressingHorn;
                }
                if (siren)
                {
                    obj.Flag |= (byte)VehicleDataFlags.SirenActive;
                }
                if (vehdead)
                {
                    obj.Flag |= (byte)VehicleDataFlags.VehicleDead;
                }
                if (player.IsDead)
                {
                    obj.Flag |= (short)VehicleDataFlags.PlayerDead;
                }

                if (Util.Util.GetResponsiblePed(veh).Handle == player.Handle)
                {
                    obj.Flag |= (byte)VehicleDataFlags.Driver;
                }

                if (veh.IsInBurnout)
                {
                    obj.Flag |= (byte)VehicleDataFlags.BurnOut;
                }

                if (ForceAimData)
                {
                    obj.Flag |= (byte)VehicleDataFlags.HasAimData;
                }

                if (player.IsSubtaskActive(167) || player.IsSubtaskActive(168))
                {
                    obj.Flag |= (short)VehicleDataFlags.ExitingVehicle;
                }

                if (!WeaponDataProvider.DoesVehicleSeatHaveGunPosition((VehicleHash)veh.Model.Hash, Util.Util.GetPedSeat(Game.Player.Character)) &&
                    WeaponDataProvider.DoesVehicleSeatHaveMountedGuns((VehicleHash)veh.Model.Hash) &&
                    Util.Util.GetPedSeat(Game.Player.Character) == -1)
                {
                    obj.Flag      |= (byte)VehicleDataFlags.HasAimData;
                    obj.AimCoords  = new GTANetworkShared.Vector3(0, 0, 0);
                    obj.WeaponHash = Main.GetCurrentVehicleWeaponHash(Game.Player.Character);
                    if (Game.IsEnabledControlPressed(0, Control.VehicleFlyAttack))
                    {
                        obj.Flag |= (byte)VehicleDataFlags.Shooting;
                    }
                }
                else if (WeaponDataProvider.DoesVehicleSeatHaveGunPosition((VehicleHash)veh.Model.Hash, Util.Util.GetPedSeat(Game.Player.Character)))
                {
                    obj.Flag      |= (byte)VehicleDataFlags.HasAimData;
                    obj.WeaponHash = 0;
                    obj.AimCoords  = Main.RaycastEverything(new Vector2(0, 0)).ToLVector();
                    if (Game.IsEnabledControlPressed(0, Control.VehicleAttack))
                    {
                        obj.Flag |= (byte)VehicleDataFlags.Shooting;
                    }
                }
                else
                {
                    if ((player.IsSubtaskActive(200) || player.IsSubtaskActive(190)) &&
                        Game.IsEnabledControlPressed(0, Control.Attack) &&
                        Game.Player.Character.Weapons.Current?.AmmoInClip != 0)
                    {
                        obj.Flag |= (byte)VehicleDataFlags.Shooting;
                        obj.Flag |= (byte)VehicleDataFlags.HasAimData;
                    }

                    if (((player.IsSubtaskActive(200) || player.IsSubtaskActive(190)) &&
                         Game.Player.Character.Weapons.Current?.AmmoInClip != 0) ||
                        (Game.Player.Character.Weapons.Current?.Hash == WeaponHash.Unarmed &&
                         player.IsSubtaskActive(200)))
                    {
                        obj.Flag |= (byte)VehicleDataFlags.Aiming;
                        obj.Flag |= (byte)VehicleDataFlags.HasAimData;
                    }

                    var outputArg = new OutputArgument();
                    Function.Call(Hash.GET_CURRENT_PED_WEAPON, Game.Player.Character, outputArg, true);
                    obj.WeaponHash = outputArg.GetResult <int>();

                    lock (Lock)
                    {
                        if (LastSyncPacket != null && LastSyncPacket is VehicleData &&
                            WeaponDataProvider.NeedsFakeBullets(obj.WeaponHash.Value) &&
                            (((VehicleData)LastSyncPacket).Flag & (byte)VehicleDataFlags.Shooting) != 0)
                        {
                            obj.Flag |= (byte)VehicleDataFlags.Shooting;
                            obj.Flag |= (byte)VehicleDataFlags.HasAimData;
                        }
                    }

                    obj.AimCoords = Main.RaycastEverything(new Vector2(0, 0)).ToLVector();
                }

                Vehicle trailer;

                if ((VehicleHash)veh.Model.Hash == VehicleHash.TowTruck ||
                    (VehicleHash)veh.Model.Hash == VehicleHash.TowTruck2)
                {
                    trailer = veh.TowedVehicle;
                }
                else if ((VehicleHash)veh.Model.Hash == VehicleHash.Cargobob ||
                         (VehicleHash)veh.Model.Hash == VehicleHash.Cargobob2 ||
                         (VehicleHash)veh.Model.Hash == VehicleHash.Cargobob3 ||
                         (VehicleHash)veh.Model.Hash == VehicleHash.Cargobob4)
                {
                    trailer = SyncEventWatcher.GetVehicleCargobobVehicle(veh);
                }
                else
                {
                    trailer = SyncEventWatcher.GetVehicleTrailerVehicle(veh);
                }

                if (trailer != null && trailer.Exists())
                {
                    obj.Trailer = trailer.Position.ToLVector();
                }

                if (Util.Util.GetResponsiblePed(veh) == player)
                {
                    obj.DamageModel = veh.GetVehicleDamageModel();
                }

                lock (Lock)
                {
                    LastSyncPacket = obj;
                }
            }
            else
            {
                bool aiming   = player.IsSubtaskActive(ESubtask.AIMED_SHOOTING_ON_FOOT) || player.IsSubtaskActive(ESubtask.AIMING_THROWABLE); // Game.IsControlPressed(0, GTA.Control.Aim);
                bool shooting = Function.Call <bool>(Hash.IS_PED_SHOOTING, player.Handle);

                GTA.Math.Vector3 aimCoord = new Vector3();
                if (aiming || shooting)
                {
                    aimCoord = Main.RaycastEverything(new Vector2(0, 0));
                }

                var obj = new PedData();
                obj.AimCoords    = aimCoord.ToLVector();
                obj.Position     = player.Position.ToLVector();
                obj.Quaternion   = player.Rotation.ToLVector();
                obj.PedArmor     = (byte)player.Armor;
                obj.PedModelHash = player.Model.Hash;
                obj.WeaponHash   = (int)player.Weapons.Current.Hash;
                obj.WeaponAmmo   = player.Weapons.Current.Ammo;
                obj.PlayerHealth = (byte)Util.Util.Clamp(0, player.Health, 255);
                obj.Velocity     = player.Velocity.ToLVector();

                obj.Flag = 0;

                if (player.IsRagdoll)
                {
                    obj.Flag |= (int)PedDataFlags.Ragdoll;
                }
                if (Function.Call <int>(Hash.GET_PED_PARACHUTE_STATE, Game.Player.Character.Handle) == 0 &&
                    Game.Player.Character.IsInAir)
                {
                    obj.Flag |= (int)PedDataFlags.InFreefall;
                }
                if (player.IsInMeleeCombat)
                {
                    obj.Flag |= (int)PedDataFlags.InMeleeCombat;
                }
                if (aiming || shooting)
                {
                    obj.Flag |= (int)PedDataFlags.Aiming;
                }
                if ((player.IsInMeleeCombat && Game.IsControlJustPressed(0, Control.Attack)))
                {
                    obj.Flag |= (int)PedDataFlags.Shooting;
                }
                if (Function.Call <bool>(Hash.IS_PED_JUMPING, player.Handle))
                {
                    obj.Flag |= (int)PedDataFlags.Jumping;
                }
                if (Function.Call <int>(Hash.GET_PED_PARACHUTE_STATE, Game.Player.Character.Handle) == 2)
                {
                    obj.Flag |= (int)PedDataFlags.ParachuteOpen;
                }
                if (player.IsInCover())
                {
                    obj.Flag |= (int)PedDataFlags.IsInCover;
                }
                if (!Function.Call <bool>((Hash)0x6A03BF943D767C93, player))
                {
                    obj.Flag |= (int)PedDataFlags.IsInLowerCover;
                }
                if (player.IsInCoverFacingLeft)
                {
                    obj.Flag |= (int)PedDataFlags.IsInCoverFacingLeft;
                }
                if (player.IsReloading)
                {
                    obj.Flag |= (int)PedDataFlags.IsReloading;
                }
                if (ForceAimData)
                {
                    obj.Flag |= (int)PedDataFlags.HasAimData;
                }
                if (player.IsSubtaskActive(ESubtask.USING_LADDER))
                {
                    obj.Flag |= (int)PedDataFlags.IsOnLadder;
                }
                if (Function.Call <bool>(Hash.IS_PED_CLIMBING, player) && !player.IsSubtaskActive(ESubtask.USING_LADDER))
                {
                    obj.Flag |= (int)PedDataFlags.IsVaulting;
                }
                if (Function.Call <bool>(Hash.IS_ENTITY_ON_FIRE, player))
                {
                    obj.Flag |= (int)PedDataFlags.OnFire;
                }
                if (player.IsDead)
                {
                    obj.Flag |= (int)PedDataFlags.PlayerDead;
                }

                if (player.IsSubtaskActive(168))
                {
                    obj.Flag |= (int)PedDataFlags.ClosingVehicleDoor;
                }

                if (player.IsSubtaskActive(161) || player.IsSubtaskActive(162) || player.IsSubtaskActive(163) ||
                    player.IsSubtaskActive(164))
                {
                    obj.Flag |= (int)PedDataFlags.EnteringVehicle;

                    obj.VehicleTryingToEnter =
                        Main.NetEntityHandler.EntityToNet(Function.Call <int>(Hash.GET_VEHICLE_PED_IS_TRYING_TO_ENTER,
                                                                              Game.Player.Character));

                    obj.SeatTryingToEnter = (sbyte)
                                            Function.Call <int>(Hash.GET_SEAT_PED_IS_TRYING_TO_ENTER,
                                                                Game.Player.Character);
                }

                obj.Speed = Main.GetPedWalkingSpeed(player);

                lock (Lock)
                {
                    LastSyncPacket = obj;
                }

                bool sendShootingPacket;

                if (!WeaponDataProvider.IsWeaponAutomatic(unchecked ((GTANetworkShared.WeaponHash)obj.WeaponHash.Value)))
                {
                    sendShootingPacket = (shooting && !player.IsSubtaskActive(ESubtask.AIMING_PREVENTED_BY_OBSTACLE) &&
                                          !player.IsSubtaskActive(ESubtask.MELEE_COMBAT));
                }
                else
                {
                    if (!_lastShooting && !player.IsSubtaskActive(ESubtask.MELEE_COMBAT))
                    {
                        sendShootingPacket = (shooting && !player.IsSubtaskActive(ESubtask.AIMING_PREVENTED_BY_OBSTACLE) &&
                                              !player.IsSubtaskActive(ESubtask.MELEE_COMBAT)) ||
                                             ((player.IsInMeleeCombat || player.IsSubtaskActive(ESubtask.MELEE_COMBAT)) &&
                                              Game.IsEnabledControlPressed(0, Control.Attack));
                    }
                    else
                    {
                        sendShootingPacket = (!player.IsSubtaskActive(ESubtask.AIMING_PREVENTED_BY_OBSTACLE) &&
                                              !player.IsSubtaskActive(ESubtask.MELEE_COMBAT) &&
                                              !player.IsReloading &&
                                              player.Weapons.Current.AmmoInClip > 0 &&
                                              Game.IsEnabledControlPressed(0, Control.Attack)) ||
                                             ((player.IsInMeleeCombat || player.IsSubtaskActive(ESubtask.MELEE_COMBAT)) &&
                                              Game.IsEnabledControlPressed(0, Control.Attack));
                    }

                    if (!sendShootingPacket && _lastShooting && !_lastBullet)
                    {
                        _lastBullet = true;
                        return;
                    }
                }

                _lastBullet = false;

                if (Game.Player.Character.IsRagdoll)
                {
                    sendShootingPacket = false;
                }

                if (!player.IsSubtaskActive(ESubtask.MELEE_COMBAT) && player.Weapons.Current.Ammo == 0)
                {
                    sendShootingPacket = false;
                }


                if (sendShootingPacket && !_lastShooting)
                {
                    _lastShooting = true;

                    _lastShot = DateTime.Now;

                    var     msg        = Main.Client.CreateMessage();
                    byte[]  bin        = null;
                    SyncPed syncPlayer = null;

                    if (Main.OnShootingLagCompensation)
                    {
                        syncPlayer = Main.GetPedDamagedByPlayer();
                    }

                    if (syncPlayer != null)
                    {
                        bin = PacketOptimization.WriteBulletSync(0, true, syncPlayer.RemoteHandle);
                        msg.Write((byte)PacketType.BulletPlayerSync);
                    }
                    else
                    {
                        bin = PacketOptimization.WriteBulletSync(0, true, aimCoord.ToLVector());
                        msg.Write((byte)PacketType.BulletSync);
                    }

                    msg.Write(bin.Length);
                    msg.Write(bin);

                    Main.Client.SendMessage(msg, NetDeliveryMethod.ReliableOrdered, (int)ConnectionChannel.BulletSync);

                    Main._bytesSent += bin.Length;
                    Main._messagesSent++;
                }
                else if (!sendShootingPacket && _lastShooting && DateTime.Now.Subtract(_lastShot).TotalMilliseconds > 50)
                {
                    _lastShooting = false;

                    var     msg        = Main.Client.CreateMessage();
                    byte[]  bin        = null;
                    SyncPed syncPlayer = null;
                    if (Main.OnShootingLagCompensation)
                    {
                        syncPlayer = Main.GetPedDamagedByPlayer();
                    }
                    if (syncPlayer != null)
                    {
                        bin = PacketOptimization.WriteBulletSync(0, false, syncPlayer.RemoteHandle);
                        msg.Write((byte)PacketType.BulletPlayerSync);
                    }
                    else
                    {
                        bin = PacketOptimization.WriteBulletSync(0, false, aimCoord.ToLVector());
                        msg.Write((byte)PacketType.BulletSync);
                    }
                    msg.Write(bin.Length);
                    msg.Write(bin);

                    Main.Client.SendMessage(msg, NetDeliveryMethod.ReliableOrdered, (int)ConnectionChannel.BulletSync);

                    Main._bytesSent += bin.Length;
                    Main._messagesSent++;
                }
            }
        }
Example #10
0
        private static void PedData(Ped player)
        {
            bool aiming   = player.IsSubtaskActive(ESubtask.AIMED_SHOOTING_ON_FOOT) || player.IsSubtaskActive(ESubtask.AIMING_THROWABLE); // Game.IsControlPressed(GTA.Control.Aim);
            bool shooting = Function.Call <bool>(Hash.IS_PED_SHOOTING, player.Handle);

            GTA.Math.Vector3 aimCoord = new Vector3();
            if (aiming || shooting)
            {
                aimCoord = Main.RaycastEverything(new Vector2(0, 0));
            }

            Weapon currentWeapon = player.Weapons.Current;

            var obj = new PedData
            {
                AimCoords    = aimCoord.ToLVector(),
                Position     = player.Position.ToLVector(),
                Quaternion   = player.Rotation.ToLVector(),
                PedArmor     = (byte)player.Armor,
                PedModelHash = player.Model.Hash,
                WeaponHash   = (int)currentWeapon.Hash,
                WeaponAmmo   = currentWeapon.Ammo,
                PlayerHealth = (byte)Util.Util.Clamp(0, player.Health, 255),
                Velocity     = player.Velocity.ToLVector(),
                Flag         = 0
            };


            if (player.IsRagdoll)
            {
                obj.Flag |= (int)PedDataFlags.Ragdoll;
            }
            if (Function.Call <int>(Hash.GET_PED_PARACHUTE_STATE, player.Handle) == 0 &&
                player.IsInAir)
            {
                obj.Flag |= (int)PedDataFlags.InFreefall;
            }
            if (player.IsInMeleeCombat)
            {
                obj.Flag |= (int)PedDataFlags.InMeleeCombat;
            }
            if (aiming || shooting)
            {
                obj.Flag |= (int)PedDataFlags.Aiming;
            }
            if ((player.IsInMeleeCombat && Game.IsControlJustPressed(Control.Attack)))
            {
                obj.Flag |= (int)PedDataFlags.Shooting;
            }
            if (Function.Call <bool>(Hash.IS_PED_JUMPING, player.Handle))
            {
                obj.Flag |= (int)PedDataFlags.Jumping;
            }
            if (Function.Call <int>(Hash.GET_PED_PARACHUTE_STATE, player.Handle) == 2)
            {
                obj.Flag |= (int)PedDataFlags.ParachuteOpen;
            }
            if (player.IsInCover())
            {
                obj.Flag |= (int)PedDataFlags.IsInCover;
            }
            if (!Function.Call <bool>((Hash)0x6A03BF943D767C93, player))
            {
                obj.Flag |= (int)PedDataFlags.IsInLowerCover;
            }
            if (player.IsInCoverFacingLeft)
            {
                obj.Flag |= (int)PedDataFlags.IsInCoverFacingLeft;
            }
            if (player.IsReloading)
            {
                obj.Flag |= (int)PedDataFlags.IsReloading;
            }
            if (ForceAimData)
            {
                obj.Flag |= (int)PedDataFlags.HasAimData;
            }
            if (player.IsSubtaskActive(ESubtask.USING_LADDER))
            {
                obj.Flag |= (int)PedDataFlags.IsOnLadder;
            }
            if (Function.Call <bool>(Hash.IS_PED_CLIMBING, player) && !player.IsSubtaskActive(ESubtask.USING_LADDER))
            {
                obj.Flag |= (int)PedDataFlags.IsVaulting;
            }
            if (Function.Call <bool>(Hash.IS_ENTITY_ON_FIRE, player))
            {
                obj.Flag |= (int)PedDataFlags.OnFire;
            }
            if (player.IsDead)
            {
                obj.Flag |= (int)PedDataFlags.PlayerDead;
            }

            if (player.IsSubtaskActive(168))
            {
                obj.Flag |= (int)PedDataFlags.ClosingVehicleDoor;
            }

            if (player.IsSubtaskActive(161) || player.IsSubtaskActive(162) || player.IsSubtaskActive(163) ||
                player.IsSubtaskActive(164))
            {
                obj.Flag |= (int)PedDataFlags.EnteringVehicle;

                obj.VehicleTryingToEnter =
                    Main.NetEntityHandler.EntityToNet(Function.Call <int>(Hash.GET_VEHICLE_PED_IS_TRYING_TO_ENTER,
                                                                          player));

                obj.SeatTryingToEnter = (sbyte)
                                        Function.Call <int>(Hash.GET_SEAT_PED_IS_TRYING_TO_ENTER,
                                                            player);
            }

            obj.Speed = Main.GetPedWalkingSpeed(player);

            lock (Lock)
            {
                LastSyncPacket = obj;
            }

            bool sendShootingPacket;

            if (obj.WeaponHash != null && !WeaponDataProvider.IsWeaponAutomatic(unchecked ((GTANetworkShared.WeaponHash)obj.WeaponHash.Value)))
            {
                sendShootingPacket = (shooting && !player.IsSubtaskActive(ESubtask.AIMING_PREVENTED_BY_OBSTACLE) && !player.IsSubtaskActive(ESubtask.MELEE_COMBAT));
            }
            else
            {
                if (!_lastShooting && !player.IsSubtaskActive(ESubtask.MELEE_COMBAT))
                {
                    sendShootingPacket = (shooting && !player.IsSubtaskActive(ESubtask.AIMING_PREVENTED_BY_OBSTACLE) &&
                                          !player.IsSubtaskActive(ESubtask.MELEE_COMBAT)) ||
                                         ((player.IsInMeleeCombat || player.IsSubtaskActive(ESubtask.MELEE_COMBAT)) &&
                                          Game.IsEnabledControlPressed(Control.Attack));
                }
                else
                {
                    sendShootingPacket = (!player.IsSubtaskActive(ESubtask.AIMING_PREVENTED_BY_OBSTACLE) &&
                                          !player.IsSubtaskActive(ESubtask.MELEE_COMBAT) &&
                                          !player.IsReloading &&
                                          player.Weapons.Current.AmmoInClip > 0 &&
                                          Game.IsEnabledControlPressed(Control.Attack)) ||
                                         ((player.IsInMeleeCombat || player.IsSubtaskActive(ESubtask.MELEE_COMBAT)) &&
                                          Game.IsEnabledControlPressed(Control.Attack));
                }

                if (!sendShootingPacket && _lastShooting && !_lastBullet)
                {
                    _lastBullet   = true;
                    _lastShooting = false;
                    return;
                }
            }

            _lastBullet = false;

            if (player.IsRagdoll)
            {
                sendShootingPacket = false;
            }

            if (!player.IsSubtaskActive(ESubtask.MELEE_COMBAT) && player.Weapons.Current.Ammo == 0)
            {
                sendShootingPacket = false;
            }

            if (sendShootingPacket && !_lastShooting && DateTime.Now.Subtract(_lastShot).TotalMilliseconds > 50)
            {
                //Util.Util.SafeNotify("Sending BPacket " + DateTime.Now.Millisecond);
                _sent         = false;
                _lastShooting = true;
                _lastShot     = DateTime.Now;

                var    msg = Main.Client.CreateMessage();
                byte[] bin;

                var syncPlayer = Main.GetPedWeHaveDamaged();

                if (syncPlayer != null)
                {
                    bin = PacketOptimization.WriteBulletSync(0, true, syncPlayer.RemoteHandle);
                    msg.Write((byte)PacketType.BulletPlayerSync);
                }
                else
                {
                    bin = PacketOptimization.WriteBulletSync(0, true, aimCoord.ToLVector());
                    msg.Write((byte)PacketType.BulletSync);
                }

                msg.Write(bin.Length);
                msg.Write(bin);
                Main.Client.SendMessage(msg, NetDeliveryMethod.ReliableOrdered, (int)ConnectionChannel.BulletSync);
                Main.BytesSent += bin.Length;
                Main.MessagesSent++;
            }
            else if (!sendShootingPacket && !_sent && DateTime.Now.Subtract(_lastShot).TotalMilliseconds > 50)
            {
                //Util.Util.SafeNotify("Sending NPacket " + DateTime.Now.Millisecond);
                _sent         = true;
                _lastShooting = false;
                _lastShot     = DateTime.Now;

                var msg = Main.Client.CreateMessage();

                byte[] bin = PacketOptimization.WriteBulletSync(0, false, aimCoord.ToLVector());
                msg.Write((byte)PacketType.BulletSync);

                msg.Write(bin.Length);
                msg.Write(bin);
                Main.Client.SendMessage(msg, NetDeliveryMethod.ReliableOrdered, (int)ConnectionChannel.BulletSync);
                Main.BytesSent += bin.Length;
                Main.MessagesSent++;
            }
        }
Example #11
0
        public void OnTick(object sender, EventArgs e)
        {
            Main.TickCount++;
            try
            {
                Ped player = Game.Player.Character;
                var res    = UIMenu.GetScreenResolutionMantainRatio();

                if (Environment.TickCount - _lastCheck > 1000)
                {
                    _bytesSentPerSecond     = _bytesSent - _lastBytesSent;
                    _bytesReceivedPerSecond = _bytesReceived - _lastBytesReceived;

                    _lastBytesReceived = _bytesReceived;
                    _lastBytesSent     = _bytesSent;


                    _lastCheck = Environment.TickCount;
                }

                if (!string.IsNullOrWhiteSpace(_threadsafeSubtitle))
                {
                    GTA.UI.Screen.ShowSubtitle(_threadsafeSubtitle, 500);
                }

                DEBUG_STEP = 1;

                if (!_hasInitialized)
                {
                    RebuildServerBrowser();
#if INTEGRITYCHECK
                    if (!VerifyGameIntegrity())
                    {
                        _mainWarning          = new Warning("alert", "Could not verify game integrity.\nPlease restart your game, or update Grand Theft Auto V.");
                        _mainWarning.OnAccept = () =>
                        {
                            if (Client != null && IsOnServer())
                            {
                                Client.Disconnect("Quit");
                            }
                            CEFManager.Dispose();
                            CEFManager.DisposeCef();
                            Script.Wait(500);
                            //Environment.Exit(0);
                            Process.GetProcessesByName("GTA5")[0].Kill();
                            Process.GetCurrentProcess().Kill();
                        };
                    }
#endif
                    _hasInitialized = true;
                }
                DEBUG_STEP = 2;

                if (!_hasPlayerSpawned && player != null && player.Handle != 0 && !Game.IsLoading)
                {
                    GTA.UI.Screen.FadeOut(1);
                    ResetPlayer();
                    MainMenu.RefreshIndex();
                    _hasPlayerSpawned     = true;
                    MainMenu.Visible      = true;
                    World.RenderingCamera = MainMenuCamera;

                    var address = Util.Util.FindPattern("\x32\xc0\xf3\x0f\x11\x09", "xxxxxx"); // Weapon/radio slowdown

                    DEBUG_STEP = 3;

                    if (address != IntPtr.Zero)
                    {
                        Util.Util.WriteMemory(address, 0x90, 6);
                    }

                    address = Util.Util.FindPattern("\x48\x85\xC0\x0F\x84\x00\x00\x00\x00\x8B\x48\x50", "xxxxx????xxx");
                    // unlock objects; credit goes to the GTA-MP team

                    DEBUG_STEP = 4;

                    if (address != IntPtr.Zero)
                    {
                        Util.Util.WriteMemory(address, 0x90, 24);
                    }

                    //TerminateGameScripts();

                    GTA.UI.Screen.FadeIn(1000);
                }

                DEBUG_STEP = 5;

                Game.DisableControlThisFrame(0, Control.EnterCheatCode);
                Game.DisableControlThisFrame(0, Control.FrontendPause);
                Game.DisableControlThisFrame(0, Control.FrontendPauseAlternate);
                Game.DisableControlThisFrame(0, Control.FrontendSocialClub);
                Game.DisableControlThisFrame(0, Control.FrontendSocialClubSecondary);

                if (!player.IsJumping)
                {
                    //Game.DisableControlThisFrame(0, Control.MeleeAttack1);
                    Game.DisableControlThisFrame(0, Control.MeleeAttackLight);
                }

                Function.Call(Hash.HIDE_HELP_TEXT_THIS_FRAME);

                if (Game.Player.Character.IsRagdoll)
                {
                    Game.DisableControlThisFrame(0, Control.Attack);
                    Game.DisableControlThisFrame(0, Control.Attack2);
                }

                if (_mainWarning != null)
                {
                    _mainWarning.Draw();
                    return;
                }

                if ((Game.IsControlJustPressed(0, Control.FrontendPauseAlternate) || Game.IsControlJustPressed(0, Control.FrontendPause)) &&
                    !MainMenu.Visible && !_wasTyping)
                {
                    MainMenu.Visible = true;

                    if (!IsOnServer())
                    {
                        if (MainMenu.Visible)
                        {
                            World.RenderingCamera = MainMenuCamera;
                        }
                        else
                        {
                            World.RenderingCamera = null;
                        }
                    }
                    else if (MainMenu.Visible)
                    {
                        RebuildPlayersList();
                    }

                    MainMenu.RefreshIndex();
                }
                else
                {
                    if (!BlockControls)
                    {
                        MainMenu.ProcessControls();
                    }
                    MainMenu.Update();
                    MainMenu.CanLeave = IsOnServer();
                    if (MainMenu.Visible && !MainMenu.TemporarilyHidden && !_mainMapItem.Focused && _hasScAvatar && File.Exists(GTANInstallDir + "\\images\\scavatar.png"))
                    {
                        var safe = new Point(300, 180);
                        Util.Util.DxDrawTexture(0, GTANInstallDir + "images\\scavatar.png", res.Width - safe.X - 64, safe.Y - 80, 64, 64, 0, 255, 255, 255, 255, false);
                    }

                    if (!IsOnServer())
                    {
                        Game.EnableControlThisFrame(0, Control.FrontendPause);
                    }
                }
                DEBUG_STEP = 6;

                if (_isGoingToCar && Game.IsControlJustPressed(0, Control.PhoneCancel))
                {
                    Game.Player.Character.Task.ClearAll();
                    _isGoingToCar = false;
                }

                if (Client == null || Client.ConnectionStatus == NetConnectionStatus.Disconnected || Client.ConnectionStatus == NetConnectionStatus.None)
                {
                    return;
                }
                // BELOW ONLY ON SERVER

                _versionLabel.Position      = new Point((int)(res.Width / 2), 0);
                _versionLabel.TextAlignment = UIResText.Alignment.Centered;
                _versionLabel.Draw();

                DEBUG_STEP = 7;

                if (_wasTyping)
                {
                    Game.DisableControlThisFrame(0, Control.FrontendPauseAlternate);
                }

                var playerCar = Game.Player.Character.CurrentVehicle;

                DEBUG_STEP = 8;

                Watcher.Tick();

                DEBUG_STEP = 9;

                _playerGodMode = Game.Player.IsInvincible;

                //invokeonLocalPlayerShoot
                if (player != null && player.IsShooting)
                {
                    JavascriptHook.InvokeCustomEvent(
                        api =>
                        api?.invokeonLocalPlayerShoot((int)(player.Weapons.Current?.Hash ?? 0),
                                                      RaycastEverything(new Vector2(0, 0)).ToLVector()));
                }


                DEBUG_STEP = 10;

                int           netPlayerCar = 0;
                RemoteVehicle cc           = null;
                if (playerCar != null && (netPlayerCar = NetEntityHandler.EntityToNet(playerCar.Handle)) != 0)
                {
                    var item = NetEntityHandler.NetToStreamedItem(netPlayerCar) as RemoteVehicle;

                    if (item != null)
                    {
                        var lastHealth      = item.Health;
                        var lastDamageModel = item.DamageModel;

                        item.Position    = playerCar.Position.ToLVector();
                        item.Rotation    = playerCar.Rotation.ToLVector();
                        item.Health      = playerCar.EngineHealth;
                        item.IsDead      = playerCar.IsDead;
                        item.DamageModel = playerCar.GetVehicleDamageModel();

                        if (lastHealth != playerCar.EngineHealth)
                        {
                            JavascriptHook.InvokeCustomEvent(api => api?.invokeonVehicleHealthChange((int)lastHealth));
                        }

                        if (playerCar.IsEngineRunning ^ !PacketOptimization.CheckBit(item.Flag, EntityFlag.EngineOff))
                        {
                            playerCar.IsEngineRunning = !PacketOptimization.CheckBit(item.Flag, EntityFlag.EngineOff);
                        }

                        if (lastDamageModel != null)
                        {
                            if (lastDamageModel.BrokenWindows != item.DamageModel.BrokenWindows)
                            {
                                for (int i = 0; i < 8; i++)
                                {
                                    if (((lastDamageModel.BrokenWindows ^ item.DamageModel.BrokenWindows) & 1 << i) != 0)
                                    {
                                        var i1 = i;
                                        JavascriptHook.InvokeCustomEvent(api => api?.invokeonVehicleWindowSmash(i1));
                                    }
                                }
                            }

                            if (lastDamageModel.BrokenDoors != item.DamageModel.BrokenDoors)
                            {
                                for (int i = 0; i < 8; i++)
                                {
                                    if (((lastDamageModel.BrokenDoors ^ item.DamageModel.BrokenDoors) & 1 << i) != 0)
                                    {
                                        var i1 = i;
                                        JavascriptHook.InvokeCustomEvent(api => api?.invokeonVehicleDoorBreak(i1));
                                    }
                                }
                            }
                        }
                    }

                    cc = item;
                }

                DEBUG_STEP = 11;

                if (playerCar != _lastPlayerCar)
                {
                    if (_lastPlayerCar != null)
                    {
                        var c = NetEntityHandler.EntityToStreamedItem(_lastPlayerCar.Handle) as
                                RemoteVehicle;

                        if (VehicleSyncManager.IsSyncing(c))
                        {
                            _lastPlayerCar.IsInvincible = c?.IsInvincible ?? false;
                        }
                        else
                        {
                            _lastPlayerCar.IsInvincible = true;
                        }

                        if (c != null)
                        {
                            Function.Call(Hash.SET_VEHICLE_ENGINE_ON, _lastPlayerCar,
                                          !PacketOptimization.CheckBit(c.Flag, EntityFlag.EngineOff), true, true);
                        }

                        int h  = _lastPlayerCar.Handle;
                        var lh = new LocalHandle(h);
                        JavascriptHook.InvokeCustomEvent(api => api?.invokeonPlayerExitVehicle(lh));
                        _lastVehicleSiren = false;
                    }

                    if (playerCar != null)
                    {
                        if (!NetEntityHandler.ContainsLocalHandle(playerCar.Handle))
                        {
                            playerCar.Delete();
                            playerCar = null;
                        }
                        else
                        {
                            playerCar.IsInvincible = cc?.IsInvincible ?? false;

                            LocalHandle handle = new LocalHandle(playerCar.Handle);
                            JavascriptHook.InvokeCustomEvent(api => api?.invokeonPlayerEnterVehicle(handle));
                        }
                    }

                    LastCarEnter = DateTime.Now;
                }

                DEBUG_STEP = 12;

                if (playerCar != null)
                {
                    if (playerCar.GetResponsiblePed().Handle == player.Handle)
                    {
                        playerCar.IsInvincible = cc?.IsInvincible ?? false;
                    }
                    else
                    {
                        playerCar.IsInvincible = true;
                    }

                    var siren = playerCar.SirenActive;

                    if (siren != _lastVehicleSiren)
                    {
                        JavascriptHook.InvokeCustomEvent(api => api?.invokeonVehicleSirenToggle());
                    }

                    _lastVehicleSiren = siren;
                }

                Game.Player.Character.MaxHealth = 200;

                var playerObj = NetEntityHandler.EntityToStreamedItem(Game.Player.Character.Handle) as RemotePlayer;

                if (playerObj != null)
                {
                    Game.Player.IsInvincible = playerObj.IsInvincible;
                }

                if (!string.IsNullOrWhiteSpace(CustomAnimation))
                {
                    var sp = CustomAnimation.Split();

                    if (
                        !Function.Call <bool>(Hash.IS_ENTITY_PLAYING_ANIM, Game.Player.Character,
                                              sp[0], sp[1],
                                              3))
                    {
                        Game.Player.Character.Task.ClearSecondary();

                        Function.Call(Hash.TASK_PLAY_ANIM, Game.Player.Character,
                                      Util.Util.LoadDict(sp[0]), sp[1],
                                      8f, 10f, -1, AnimationFlag, -8f, 1, 1, 1);
                    }
                }

                DEBUG_STEP     = 13;
                _lastPlayerCar = playerCar;


                if (Game.IsControlJustPressed(0, Control.ThrowGrenade) && !Game.Player.Character.IsInVehicle() && IsOnServer() && !Chat.IsFocused)
                {
                    var vehs = World.GetAllVehicles().OrderBy(v => v.Position.DistanceToSquared(Game.Player.Character.Position)).Take(1).ToList();
                    if (vehs.Any() && Game.Player.Character.IsInRangeOfEx(vehs[0].Position, 6f))
                    {
                        var         relPos = vehs[0].GetOffsetFromWorldCoords(Game.Player.Character.Position);
                        VehicleSeat seat   = VehicleSeat.Any;

                        if (relPos.X < 0 && relPos.Y > 0)
                        {
                            seat = VehicleSeat.LeftRear;
                        }
                        else if (relPos.X >= 0 && relPos.Y > 0)
                        {
                            seat = VehicleSeat.RightFront;
                        }
                        else if (relPos.X < 0 && relPos.Y <= 0)
                        {
                            seat = VehicleSeat.LeftRear;
                        }
                        else if (relPos.X >= 0 && relPos.Y <= 0)
                        {
                            seat = VehicleSeat.RightRear;
                        }

                        if (vehs[0].PassengerCapacity == 1)
                        {
                            seat = VehicleSeat.Passenger;
                        }

                        if (vehs[0].PassengerCapacity > 3 && vehs[0].GetPedOnSeat(seat).Handle != 0)
                        {
                            if (seat == VehicleSeat.LeftRear)
                            {
                                for (int i = 3; i < vehs[0].PassengerCapacity; i += 2)
                                {
                                    if (vehs[0].GetPedOnSeat((VehicleSeat)i).Handle == 0)
                                    {
                                        seat = (VehicleSeat)i;
                                        break;
                                    }
                                }
                            }
                            else if (seat == VehicleSeat.RightRear)
                            {
                                for (int i = 4; i < vehs[0].PassengerCapacity; i += 2)
                                {
                                    if (vehs[0].GetPedOnSeat((VehicleSeat)i).Handle == 0)
                                    {
                                        seat = (VehicleSeat)i;
                                        break;
                                    }
                                }
                            }
                        }

                        if (WeaponDataProvider.DoesVehicleSeatHaveGunPosition((VehicleHash)vehs[0].Model.Hash, 0, true) && Game.Player.Character.IsIdle && !Game.Player.IsAiming)
                        {
                            Game.Player.Character.SetIntoVehicle(vehs[0], seat);
                        }
                        else
                        {
                            Game.Player.Character.Task.EnterVehicle(vehs[0], seat, -1, 2f);
                        }
                        _isGoingToCar = true;
                    }
                }

                DEBUG_STEP = 14;

                Game.DisableControlThisFrame(0, Control.SpecialAbility);
                Game.DisableControlThisFrame(0, Control.SpecialAbilityPC);
                Game.DisableControlThisFrame(0, Control.SpecialAbilitySecondary);
                Game.DisableControlThisFrame(0, Control.CharacterWheel);
                Game.DisableControlThisFrame(0, Control.Phone);
                Game.DisableControlThisFrame(0, Control.Duck);

                DEBUG_STEP = 15;

                VehicleSyncManager?.Pulse();

                DEBUG_STEP = 16;

                if (StringCache != null)
                {
                    StringCache?.Pulse();
                }

                DEBUG_STEP = 17;

                double aver = 0;
                lock (_averagePacketSize)
                    aver = _averagePacketSize.Count > 0 ? _averagePacketSize.Average() : 0;

                _statsItem.Text =
                    string.Format(
                        "~h~Bytes Sent~h~: {0}~n~~h~Bytes Received~h~: {1}~n~~h~Bytes Sent / Second~h~: {5}~n~~h~Bytes Received / Second~h~: {6}~n~~h~Average Packet Size~h~: {4}~n~~n~~h~Messages Sent~h~: {2}~n~~h~Messages Received~h~: {3}",
                        _bytesSent, _bytesReceived, _messagesSent, _messagesReceived,
                        aver, _bytesSentPerSecond,
                        _bytesReceivedPerSecond);



                DEBUG_STEP = 18;
                if (Game.IsControlPressed(0, Control.Aim) && !Game.Player.Character.IsInVehicle() && Game.Player.Character.Weapons.Current.Hash != WeaponHash.Unarmed)
                {
                    Game.DisableControlThisFrame(0, Control.Jump);
                }

                //CRASH WORKAROUND: DISABLE PARACHUTE RUINER2
                if (Game.Player.Character.IsInVehicle())
                {
                    if (Game.Player.Character.CurrentVehicle.IsInAir && Game.Player.Character.CurrentVehicle.Model.Hash == 941494461)
                    {
                        Game.DisableAllControlsThisFrame(0);
                    }
                }


                DEBUG_STEP = 19;
                Function.Call((Hash)0x5DB660B38DD98A31, Game.Player, 0f);
                DEBUG_STEP              = 20;
                Game.MaxWantedLevel     = 0;
                Game.Player.WantedLevel = 0;
                DEBUG_STEP              = 21;
                lock (_localMarkers)
                {
                    foreach (var marker in _localMarkers)
                    {
                        World.DrawMarker((MarkerType)marker.Value.MarkerType, marker.Value.Position.ToVector(),
                                         marker.Value.Direction.ToVector(), marker.Value.Rotation.ToVector(),
                                         marker.Value.Scale.ToVector(),
                                         Color.FromArgb(marker.Value.Alpha, marker.Value.Red, marker.Value.Green, marker.Value.Blue));
                    }
                }

                DEBUG_STEP = 22;
                var hasRespawned = (Function.Call <int>(Hash.GET_TIME_SINCE_LAST_DEATH) < 8000 &&
                                    Function.Call <int>(Hash.GET_TIME_SINCE_LAST_DEATH) != -1 &&
                                    Game.Player.CanControlCharacter);

                if (hasRespawned && !_lastDead)
                {
                    _lastDead = true;
                    var msg = Client.CreateMessage();
                    msg.Write((byte)PacketType.PlayerRespawned);
                    Client.SendMessage(msg, NetDeliveryMethod.ReliableOrdered, (int)ConnectionChannel.SyncEvent);

                    JavascriptHook.InvokeCustomEvent(api => api?.invokeonPlayerRespawn());

                    if (Weather != null)
                    {
                        Function.Call(Hash.SET_WEATHER_TYPE_NOW_PERSIST, Weather);
                    }
                    if (Time.HasValue)
                    {
                        World.CurrentDayTime = new TimeSpan(Time.Value.Hours, Time.Value.Minutes, 00);
                    }

                    Function.Call(Hash.PAUSE_CLOCK, true);

                    var us = NetEntityHandler.EntityToStreamedItem(Game.Player.Character.Handle);

                    NetEntityHandler.ReattachAllEntities(us, true);
                    foreach (
                        var source in
                        Main.NetEntityHandler.ClientMap.Values.Where(
                            item => item is RemoteParticle && ((RemoteParticle)item).EntityAttached == us.RemoteHandle)
                        .Cast <RemoteParticle>())
                    {
                        Main.NetEntityHandler.StreamOut(source);
                        Main.NetEntityHandler.StreamIn(source);
                    }
                }

                var pHealth = player.Health;
                var pArmor  = player.Armor;
                var pGun    = player.Weapons.Current?.Hash ?? WeaponHash.Unarmed;
                var pModel  = player.Model.Hash;

                if (pHealth != _lastPlayerHealth)
                {
                    int test = _lastPlayerHealth;
                    JavascriptHook.InvokeCustomEvent(api => api?.invokeonPlayerHealthChange(test));
                }

                if (pArmor != _lastPlayerArmor)
                {
                    int test = _lastPlayerArmor;
                    JavascriptHook.InvokeCustomEvent(api => api?.invokeonPlayerArmorChange(test));
                }

                if (pGun != _lastPlayerWeapon)
                {
                    WeaponHash test = _lastPlayerWeapon;
                    JavascriptHook.InvokeCustomEvent(api => api?.invokeonPlayerWeaponSwitch((int)test));
                }

                if (pModel != (int)_lastPlayerModel)
                {
                    PedHash test = _lastPlayerModel;
                    JavascriptHook.InvokeCustomEvent(api => api?.invokeonPlayerModelChange((int)test));
                }

                _lastPlayerHealth = pHealth;
                _lastPlayerArmor  = pArmor;
                _lastPlayerWeapon = pGun;
                _lastPlayerModel  = (PedHash)pModel;

                DEBUG_STEP = 23;
                _lastDead  = hasRespawned;
                DEBUG_STEP = 24;
                var killed = Game.Player.Character.IsDead;
                DEBUG_STEP = 25;
                if (killed && !_lastKilled)
                {
                    var msg = Client.CreateMessage();
                    msg.Write((byte)PacketType.PlayerKilled);
                    var killer = Function.Call <int>(Hash.GET_PED_SOURCE_OF_DEATH, Game.Player.Character);
                    var weapon = Function.Call <int>(Hash.GET_PED_CAUSE_OF_DEATH, Game.Player.Character);


                    var killerEnt = NetEntityHandler.EntityToNet(killer);
                    msg.Write(killerEnt);
                    msg.Write(weapon);

                    /*
                     * var playerMod = (PedHash)Game.Player.Character.Model.Hash;
                     * if (playerMod != PedHash.Michael && playerMod != PedHash.Franklin && playerMod != PedHash.Trevor)
                     * {
                     *  _lastModel = Game.Player.Character.Model.Hash;
                     *  var lastMod = new Model(PedHash.Michael);
                     *  lastMod.Request(10000);
                     *  Function.Call(Hash.SET_PLAYER_MODEL, Game.Player, lastMod);
                     *  Game.Player.Character.Kill();
                     * }
                     * else
                     * {
                     *  _lastModel = 0;
                     * }
                     */
                    Client.SendMessage(msg, NetDeliveryMethod.ReliableOrdered, (int)ConnectionChannel.SyncEvent);

                    JavascriptHook.InvokeCustomEvent(api => api?.invokeonPlayerDeath(new LocalHandle(killer), weapon));

                    NativeUI.BigMessageThread.MessageInstance.ShowColoredShard("WASTED", "", HudColor.HUD_COLOUR_BLACK, HudColor.HUD_COLOUR_RED, 7000);
                    Function.Call(Hash.REQUEST_SCRIPT_AUDIO_BANK, "HUD_MINI_GAME_SOUNDSET", true);
                    Function.Call(Hash.PLAY_SOUND_FRONTEND, -1, "CHECKPOINT_NORMAL", "HUD_MINI_GAME_SOUNDSET");
                }

                /*
                 * if (Function.Call<int>(Hash.GET_TIME_SINCE_LAST_DEATH) < 8000 &&
                 *  Function.Call<int>(Hash.GET_TIME_SINCE_LAST_DEATH) != -1)
                 * {
                 *  if (_lastModel != 0 && Game.Player.Character.Model.Hash != _lastModel)
                 *  {
                 *      var lastMod = new Model(_lastModel);
                 *      lastMod.Request(10000);
                 *      Function.Call(Hash.SET_PLAYER_MODEL, new InputArgument(Game.Player), lastMod.Hash);
                 *  }
                 * }
                 */


                DEBUG_STEP = 28;


                if (!IsSpectating && _lastSpectating)
                {
                    Game.Player.Character.Opacity          = 255;
                    Game.Player.Character.IsPositionFrozen = false;
                    Game.Player.IsInvincible = false;
                    Game.Player.Character.IsCollisionEnabled = true;
                    SpectatingEntity                       = 0;
                    CurrentSpectatingPlayer                = null;
                    _currentSpectatingPlayerIndex          = 100000;
                    Game.Player.Character.PositionNoOffset = _preSpectatorPos;
                }
                if (IsSpectating)
                {
                    if (SpectatingEntity != 0)
                    {
                        Game.Player.Character.Opacity          = 0;
                        Game.Player.Character.IsPositionFrozen = true;
                        Game.Player.IsInvincible = true;
                        Game.Player.Character.IsCollisionEnabled = false;

                        Control[] exceptions = new[]
                        {
                            Control.LookLeftRight,
                            Control.LookUpDown,
                            Control.LookLeft,
                            Control.LookRight,
                            Control.LookUp,
                            Control.LookDown,
                        };

                        Game.DisableAllControlsThisFrame(0);
                        foreach (var c in exceptions)
                        {
                            Game.EnableControlThisFrame(0, c);
                        }

                        var ent = NetEntityHandler.NetToEntity(SpectatingEntity);

                        if (ent != null)
                        {
                            if (Function.Call <bool>(Hash.IS_ENTITY_A_PED, ent) && new Ped(ent.Handle).IsInVehicle())
                            {
                                Game.Player.Character.PositionNoOffset = ent.Position + new GTA.Math.Vector3(0, 0, 1.3f);
                            }
                            else
                            {
                                Game.Player.Character.PositionNoOffset = ent.Position;
                            }
                        }
                    }
                    else if (SpectatingEntity == 0 && CurrentSpectatingPlayer == null &&
                             NetEntityHandler.ClientMap.Values.Count(op => op is SyncPed && !((SyncPed)op).IsSpectating &&
                                                                     (((SyncPed)op).Team == 0 || ((SyncPed)op).Team == Main.LocalTeam) &&
                                                                     (((SyncPed)op).Dimension == 0 || ((SyncPed)op).Dimension == Main.LocalDimension)) > 0)
                    {
                        CurrentSpectatingPlayer =
                            NetEntityHandler.ClientMap.Values.Where(
                                op =>
                                op is SyncPed && !((SyncPed)op).IsSpectating &&
                                (((SyncPed)op).Team == 0 || ((SyncPed)op).Team == Main.LocalTeam) &&
                                (((SyncPed)op).Dimension == 0 || ((SyncPed)op).Dimension == Main.LocalDimension))
                            .ElementAt(_currentSpectatingPlayerIndex %
                                       NetEntityHandler.ClientMap.Values.Count(
                                           op =>
                                           op is SyncPed && !((SyncPed)op).IsSpectating &&
                                           (((SyncPed)op).Team == 0 || ((SyncPed)op).Team == Main.LocalTeam) &&
                                           (((SyncPed)op).Dimension == 0 ||
                                            ((SyncPed)op).Dimension == Main.LocalDimension))) as SyncPed;
                    }
                    else if (SpectatingEntity == 0 && CurrentSpectatingPlayer != null)
                    {
                        Game.Player.Character.Opacity          = 0;
                        Game.Player.Character.IsPositionFrozen = true;
                        Game.Player.IsInvincible = true;
                        Game.Player.Character.IsCollisionEnabled = false;
                        Game.DisableAllControlsThisFrame(0);

                        if (CurrentSpectatingPlayer.Character == null)
                        {
                            Game.Player.Character.PositionNoOffset = CurrentSpectatingPlayer.Position;
                        }
                        else if (CurrentSpectatingPlayer.IsInVehicle)
                        {
                            Game.Player.Character.PositionNoOffset = CurrentSpectatingPlayer.Character.Position + new GTA.Math.Vector3(0, 0, 1.3f);
                        }
                        else
                        {
                            Game.Player.Character.PositionNoOffset = CurrentSpectatingPlayer.Character.Position;
                        }

                        if (Game.IsControlJustPressed(0, Control.PhoneLeft))
                        {
                            _currentSpectatingPlayerIndex--;
                            CurrentSpectatingPlayer = null;
                        }
                        else if (Game.IsControlJustPressed(0, Control.PhoneRight))
                        {
                            _currentSpectatingPlayerIndex++;
                            CurrentSpectatingPlayer = null;
                        }

                        if (CurrentSpectatingPlayer != null)
                        {
                            var center = new Point((int)(res.Width / 2), (int)(res.Height / 2));

                            new UIResText("Now spectating:~n~" + CurrentSpectatingPlayer.Name,
                                          new Point(center.X, (int)(res.Height - 200)), 0.4f, Color.White, GTA.UI.Font.ChaletLondon,
                                          UIResText.Alignment.Centered)
                            {
                                Outline = true,
                            }.Draw();

                            new Sprite("mparrow", "mp_arrowxlarge", new Point(center.X - 264, (int)(res.Height - 232)), new Size(64, 128), 180f, Color.White).Draw();
                            new Sprite("mparrow", "mp_arrowxlarge", new Point(center.X + 200, (int)(res.Height - 232)), new Size(64, 128)).Draw();
                        }
                    }
                }

                _lastSpectating = IsSpectating;

                _lastKilled = killed;

                var collection = new CallCollection();

                collection.Call(Hash.SET_RANDOM_TRAINS, 0);
                collection.Call(Hash.CAN_CREATE_RANDOM_COPS, false);
                DEBUG_STEP = 29;
                collection.Call(Hash.SET_VEHICLE_DENSITY_MULTIPLIER_THIS_FRAME, 0f);
                collection.Call(Hash.SET_VEHICLE_POPULATION_BUDGET, 0);
                collection.Call(Hash.SET_PED_POPULATION_BUDGET, 0);
                collection.Call(Hash.SUPPRESS_SHOCKING_EVENTS_NEXT_FRAME);
                collection.Call(Hash.SUPPRESS_AGITATION_EVENTS_NEXT_FRAME);
                collection.Call(Hash.SET_RANDOM_VEHICLE_DENSITY_MULTIPLIER_THIS_FRAME, 0f);
                collection.Call(Hash.SET_PARKED_VEHICLE_DENSITY_MULTIPLIER_THIS_FRAME, 0f);
                collection.Call(Hash.SET_NUMBER_OF_PARKED_VEHICLES, -1);
                collection.Call(Hash.SET_ALL_LOW_PRIORITY_VEHICLE_GENERATORS_ACTIVE, false);
                collection.Call(Hash.SET_FAR_DRAW_VEHICLES, false);
                collection.Call(Hash.DESTROY_MOBILE_PHONE);
                collection.Call((Hash)0x015C49A93E3E086E, true);
                collection.Call(Hash.SET_PED_DENSITY_MULTIPLIER_THIS_FRAME, 0f);
                collection.Call(Hash.SET_SCENARIO_PED_DENSITY_MULTIPLIER_THIS_FRAME, 0f, 0f);
                collection.Call(Hash.SET_CAN_ATTACK_FRIENDLY, Game.Player.Character, true, true);
                collection.Call(Hash.SET_PED_CAN_BE_TARGETTED, Game.Player.Character, true);
                collection.Call((Hash)0xF796359A959DF65D, false); // Display distant vehicles
                collection.Call(Hash.SET_AUTO_GIVE_PARACHUTE_WHEN_ENTER_PLANE, Game.Player, false);
                collection.Call((Hash)0xD2B315B6689D537D, Game.Player, false);
                collection.Call(Hash.DISPLAY_CASH, false);
                collection.Execute();
                DEBUG_STEP = 30;


                GameScript.Pulse();

                if ((Game.Player.Character.Position - _lastWaveReset).LengthSquared() > 10000f) // 100f * 100f
                {
                    Function.Call((Hash)0x5E5E99285AE812DB);
                    Function.Call((Hash)0xB96B00E976BE977F, 0f);

                    _lastWaveReset = Game.Player.Character.Position;
                }

                Function.Call((Hash)0x2F9A292AD0A3BD89);
                Function.Call((Hash)0x5F3B7749C112D552);

                if (Function.Call <bool>(Hash.IS_STUNT_JUMP_IN_PROGRESS))
                {
                    Function.Call(Hash.CANCEL_STUNT_JUMP);
                }

                DEBUG_STEP = 31;
                if (Function.Call <int>(Hash.GET_PED_PARACHUTE_STATE, Game.Player.Character) == 2)
                {
                    Game.DisableControlThisFrame(0, Control.Aim);
                    Game.DisableControlThisFrame(0, Control.Attack);
                }
                DEBUG_STEP = 32;


                if (RemoveGameEntities && Util.Util.TickCount - _lastEntityRemoval > 500) // Save ressource
                {
                    _lastEntityRemoval = Util.Util.TickCount;
                    foreach (var entity in World.GetAllPeds())
                    {
                        if (!NetEntityHandler.ContainsLocalHandle(entity.Handle) && entity != Game.Player.Character)
                        {
                            entity.Kill(); //"Some special peds like Epsilon guys or seashark minigame will refuse to despawn if you don't kill them first." - Guad
                            entity.Delete();
                        }
                    }

                    foreach (var entity in World.GetAllVehicles())
                    {
                        if (entity == null)
                        {
                            continue;
                        }
                        var veh = NetEntityHandler.NetToStreamedItem(entity.Handle, useGameHandle: true) as RemoteVehicle;
                        if (veh == null)
                        {
                            entity.Delete();
                            continue;
                        }
                        //TO CHECK
                        if (entity.IsVehicleEmpty() && !VehicleSyncManager.IsInterpolating(entity.Handle) && veh.TraileredBy == 0 && !VehicleSyncManager.IsSyncing(veh) && ((entity.Handle == Game.Player.LastVehicle?.Handle && DateTime.Now.Subtract(LastCarEnter).TotalMilliseconds > 3000) || entity.Handle != Game.Player.LastVehicle?.Handle))
                        {
                            if (entity.Position.DistanceToSquared(veh.Position.ToVector()) > 2f)
                            {
                                entity.PositionNoOffset = veh.Position.ToVector();
                                entity.Quaternion       = veh.Rotation.ToVector().ToQuaternion();
                            }
                        }

                        //veh.Position = entity.Position.ToLVector();
                        //veh.Rotation = entity.Rotation.ToLVector();
                    }
                }
                _whoseturnisitanyways = !_whoseturnisitanyways;

                DEBUG_STEP = 34;
                NetEntityHandler.UpdateAttachments();
                DEBUG_STEP = 35;
                NetEntityHandler.DrawMarkers();
                DEBUG_STEP = 36;
                NetEntityHandler.DrawLabels();
                DEBUG_STEP = 37;
                NetEntityHandler.UpdateMisc();
                DEBUG_STEP = 38;
                NetEntityHandler.UpdateInterpolations();
                DEBUG_STEP = 39;
                WeaponInventoryManager.Update();
                DEBUG_STEP = 40;

                /*string stats = string.Format("{0}Kb (D)/{1}Kb (U), {2}Msg (D)/{3}Msg (U)", _bytesReceived / 1000,
                 *  _bytesSent / 1000, _messagesReceived, _messagesSent);
                 */
                //GTA.UI.Screen.ShowSubtitle(stats);


                PedThread.OnTick("thisaintnullnigga", e);

                DebugInfo.Draw();

                //Thread calcucationThread = new Thread(Work);
                //calcucationThread.IsBackground = true;
                //calcucationThread.Start();

                lock (_threadJumping)
                {
                    if (_threadJumping.Any())
                    {
                        Action action = _threadJumping.Dequeue();
                        if (action != null)
                        {
                            action.Invoke();
                        }
                    }
                }
                DEBUG_STEP = 41;
            }
            catch (Exception ex) // Catch any other exception. (can prevent crash)
            {
                LogManager.LogException(ex, "MAIN OnTick: STEP : " + DEBUG_STEP);
            }
        }