public void broadcastData(ServerPlayer player) { if (player.data.client_has_been_set) { return; } else { player.data.client_has_been_set = true; } try { if (player.data != null) { InvokeParallelForEachPlayer((single) => { if (single.id != player.id) { var bpf = new BinaryPacketFormatter(Commands.UpdateData); bpf.Add(player.id); bpf.Add(player.data); single.connection.write(bpf.getBytes()); //Console.WriteLine("Streaming to Player " + single.Value.nick); } }); } } catch (Exception e) { Console.WriteLine(e); } }
public void EnterVehicle(ServerVehicle vehicle) { currentVehicleId = vehicle.id; var bpf = new BinaryPacketFormatter(Commands.NPC_walkTo); bpf.Add(id); bpf.Add(vehicle.id); broadcastEvent(bpf); }
public void WalkTo(Vector3 position) { this.position = position; var bpf = new BinaryPacketFormatter(Commands.NPC_walkTo); bpf.Add(id); bpf.Add(position); broadcastEvent(bpf); }
public void show(ServerPlayer player) { var bpf = new BinaryPacketFormatter(Commands.NPCDialog_show); bpf.Add(id); bpf.Add(caption); bpf.Add(text); bpf.Add(String.Join("\x01", responses.ToArray())); player.connection.write(bpf.getBytes()); }
public void update() { var bpf = new BinaryPacketFormatter(Commands.TextView_update); bpf.Add(id); bpf.Add(size); bpf.Add(position.X); bpf.Add(position.Y); bpf.Add(text); player.connection.write(bpf.getBytes()); }
public void broadcastVehiclesToPlayer(ServerPlayer player) { foreach (var pair in vehicleController.vehicles) { var bpf = new BinaryPacketFormatter(Commands.Vehicle_create); bpf.Add(pair.Value.id); bpf.Add(pair.Value.position); bpf.Add(pair.Value.orientation); bpf.Add(ModelDictionary.getVehicleByName(pair.Value.model)); player.connection.write(bpf.getBytes()); } }
public void broadcastNPCsToPlayer(ServerPlayer player) { foreach (var pair in ServerNPC.NPCPool) { var bpf = new BinaryPacketFormatter(Commands.NPC_create); bpf.Add(pair.Value.id); bpf.Add(pair.Value.Position); bpf.Add(pair.Value.Heading); bpf.Add(pair.Value.Model); bpf.Add(pair.Value.Name); player.connection.write(bpf.getBytes()); } }
public void broadcastPlayerName(ServerPlayer player) { InvokeParallelForEachPlayer((single) => { if (single != player) { var bpf = new BinaryPacketFormatter(Commands.Global_setPlayerName); bpf.Add(player.id); bpf.Add(player.Nick); single.connection.write(bpf.getBytes()); } }); }
private void updatePing() { var bpf = new BinaryPacketFormatter(Commands.Client_ping); bpf.Add(DateTime.Now.Ticks); connection.write(bpf.getBytes()); }
public void writeChat(ServerPlayer player, string text) { var bpf = new BinaryPacketFormatter(Commands.Chat_writeLine); bpf.Add(text); player.connection.write(bpf.getBytes()); }
public void LookAt(Vector3 position) { var bpf = new BinaryPacketFormatter(Commands.Camera_lookAt); bpf.Add(position); player.connection.write(bpf.getBytes()); }
public void destroy() { textviewspool.Remove(id); var bpf = new BinaryPacketFormatter(Commands.TextView_destroy); bpf.Add(id); player.connection.write(bpf.getBytes()); }
public void LeaveVehicle() { currentVehicleId = 0; var bpf = new BinaryPacketFormatter(Commands.NPC_leaveVehicle); bpf.Add(id); broadcastEvent(bpf); }
public ServerVehicle create(string model, Vector3 position, Quaternion orientation) { uint vid = findLowestFreeId(); ServerVehicle veh = new ServerVehicle(vid); veh.position = position; veh.orientation = orientation; veh.model = model; vehicles.Add(vid, veh); Server.instance.InvokeParallelForEachPlayer((player) => { var bpf = new BinaryPacketFormatter(Commands.Vehicle_create); bpf.Add(veh.id); bpf.Add(veh.position); bpf.Add(veh.orientation); bpf.Add(ModelDictionary.getVehicleByName(veh.model)); player.connection.write(bpf.getBytes()); }); return(veh); }
public void broadcastPlayers() { try { if (player.data != null && endpoint != null) { Server.instance.InvokeParallelForEachPlayer((single) => { if (single.id != player.id) { var bpf = new BinaryPacketFormatter(); bpf.Add(single.id); bpf.Add(single.data); var bytes = bpf.getBytes(); udp.Send(bytes, bytes.Length, endpoint); } }); } } catch (Exception e) { Console.WriteLine(e); } }
public TextView(ServerPlayer player, string text, float fontsize, Point position) { if (textviewspool == null) { textviewspool = new Dictionary <uint, TextView>(); } this.text = text; this.size = fontsize; this.position = position; this.player = player; id = findLowestFreeId(); textviewspool.Add(id, this); var bpf = new BinaryPacketFormatter(Commands.TextView_create); bpf.Add(id); bpf.Add(size); bpf.Add(position.X); bpf.Add(position.Y); bpf.Add(text); player.connection.write(bpf.getBytes()); }
private void InitInstance(ClientConnection connection, Commands action, Action <object[]> onComplete) { if (requestPool == null) { requestPool = new Dictionary <uint, Request>(); } this.action = action; this.connection = connection; this.onComplete = onComplete; uint id = findLowestFreeId(); requestPool.Add(id, this); bpf = new BinaryPacketFormatter(action); bpf.Add(id); }
public void broadcastData(UpdateDataStruct data) { if (Client.instance.BroadcastingPaused) { return; } try { var bpf = new BinaryPacketFormatter(); bpf.Add(data); var bytes = bpf.getBytes(); udp.Send(bytes, bytes.Length); } catch (Exception e) { Game.Log(e.Message); } }
private void eventOnKeyUp(object sender, GTA.KeyEventArgs e) { if (lastKeyUp != null && lastKeyUp == (int)e.Key) { return; } if (client.currentState == ClientState.Connected) { var bpf = new BinaryPacketFormatter(Commands.Keys_up); bpf.Add((int)e.Key); client.serverConnection.write(bpf.getBytes()); } lastKeyUp = (int)e.Key; lastKeyDown = 0; }
private void onBroadcastTimer(object sender, ElapsedEventArgs e) { string currentMessage; while ((currentMessage = chat.dequeue()) != null) { string message = currentMessage; InvokeParallelForEachPlayer((player) => { var bpf = new BinaryPacketFormatter(Commands.Chat_writeLine); bpf.Add(message); player.connection.write(bpf.getBytes()); }); } InvokeParallelForEachPlayer((player) => { player.connection.flush(); player.udpTunnel.broadcastPlayers(); }); }
public void updatePed(uint id, UpdateDataStruct data, StreamedPed ped) { var posnew = new Vector3(data.pos_x, data.pos_y, data.pos_z - 1.0f); ped.position = posnew; ped.heading = data.heading; ped.direction = new Vector3(data.rot_x, data.rot_y, data.rot_z); ped.cameraDirection = new Vector3(data.camdir_x, data.camdir_y, data.camdir_z); if (ped.IsStreamedIn() && data.vehicle_id == 0) { if (ped.gameReference.isInVehicle()) { ped.gameReference.CurrentVehicle.PassengersLeaveVehicle(true); //ped.gameReference.CurrentVehicle.Delete(); } float delta = posnew.DistanceTo(ped.gameReference.Position); Vector3 vdelta = posnew - ped.gameReference.Position; //ped.gameReference.Weapons.MP5.Ammo = 999; int healthDelta = data.ped_health - ped.gameReference.Health; ped.gameReference.Health = data.ped_health; ped.last_game_health = data.ped_health; if (data.weapon > 0) { if (ped.gameReference.Weapons.Current != (Weapon)data.weapon) { ped.gameReference.Weapons.FromType((Weapon)data.weapon).Ammo = 999; ped.gameReference.Weapons.FromType((Weapon)data.weapon).AmmoInClip = 999; ped.gameReference.Weapons.Select((Weapon)data.weapon); } } else { ped.gameReference.Weapons.RemoveAll(); } if (healthDelta > 20 && healthDelta < 100) { var bpf = new BinaryPacketFormatter(Commands.Player_damage); bpf.Add(id); //Client.instance.chatController.writeChat("damaged " + healthDelta) ; Client.instance.serverConnection.write(bpf.getBytes()); } bool cancelPositionUpdate = false; if ((data.state & PlayerState.IsShooting) != 0) { ped.animator.playAnimation(PedAnimations.Shoot); cancelPositionUpdate = true; } else if ((data.state & PlayerState.IsAiming) != 0) { ped.animator.playAnimation(PedAnimations.Aim); cancelPositionUpdate = true; } else if ((data.state & PlayerState.IsRagdoll) != 0 || data.ped_health <= 0) { ped.animator.playAnimation(PedAnimations.Ragdoll); ped.gameReference.Velocity = new Vector3(data.vel_x, data.vel_y, data.vel_z); cancelPositionUpdate = true; } else if ((data.vstate & VehicleState.IsEnteringVehicle) != 0) { ped.animator.playAnimation(PedAnimations.EnterClosestVehicle); cancelPositionUpdate = true; } else if ((data.state & PlayerState.IsCrouching) != 0) { ped.animator.playAnimation(PedAnimations.Couch); } else { if ((data.vstate & VehicleState.IsAccelerating) != 0) { if ((data.vstate & VehicleState.IsSprinting) != 0) { ped.animator.playAnimation(PedAnimations.Run); } else { ped.animator.playAnimation(PedAnimations.Walk); } } else { ped.animator.playAnimation(PedAnimations.StandStill); } } if (!cancelPositionUpdate) { ped.gameReference.Position = posnew; } ped.gameReference.Heading = data.heading; //ped.gameReference.Velocity = new Vector3(elemValue.vel_x, elemValue.vel_y, elemValue.vel_z); //ped.gameReference.Task.ClearAllImmediately(); } }
public void updateVehicle(uint id, UpdateDataStruct data, StreamedPed ped) { if (data.vehicle_id > 0) { var posnew = new Vector3(data.pos_x, data.pos_y, data.pos_z); StreamedVehicle veh = vehicleController.GetInstance(data.vehicle_id); if (veh != null) { if (veh.IsStreamedIn()) { if (ped != null && ped.IsStreamedIn() && !ped.gameReference.isInVehicle()) { if ((data.state & PlayerState.IsPassenger1) != 0) { ped.gameReference.WarpIntoVehicle(veh.gameReference, VehicleSeat.RightFront); } else if ((data.state & PlayerState.IsPassenger2) != 0) { ped.gameReference.WarpIntoVehicle(veh.gameReference, VehicleSeat.LeftRear); } else if ((data.state & PlayerState.IsPassenger3) != 0) { ped.gameReference.WarpIntoVehicle(veh.gameReference, VehicleSeat.RightFront); } else { ped.gameReference.WarpIntoVehicle(veh.gameReference, VehicleSeat.Driver); } } int healthDelta = data.ped_health - ped.gameReference.Health; ped.gameReference.Health = data.ped_health; ped.last_game_health = data.ped_health; if (healthDelta > 20 && healthDelta < 100) { var bpf = new BinaryPacketFormatter(Commands.Player_damage); bpf.Add(id); //Client.instance.chatController.writeChat("damaged " + healthDelta) ; Client.instance.serverConnection.write(bpf.getBytes()); } int vehicleHealthDelta = data.vehicle_health - veh.gameReference.Health; veh.gameReference.Health = data.vehicle_health; veh.last_game_health = data.vehicle_health; if (vehicleHealthDelta > 20 && vehicleHealthDelta < 2000 && data.vehicle_id > 0) { var bpf = new BinaryPacketFormatter(Commands.Vehicle_damage, id, data.vehicle_id, vehicleHealthDelta); Client.instance.serverConnection.write(bpf.getBytes()); } if ((data.vstate & VehicleState.IsAsPassenger) != 0) { return; } veh.position = posnew; if (veh.gameReference.Position.DistanceTo(posnew) > 1.0f) { veh.gameReference.Position = posnew; } //veh.gameReference.Position = posnew; veh.orientation = new Quaternion(data.rot_x, data.rot_y, data.rot_z, data.rot_a); //veh.gameReference.ApplyForce(, Vector3.Zero); veh.gameReference.RotationQuaternion = veh.orientation; var vel = new Vector3(data.vel_x, data.vel_y, data.vel_z); if (System.Math.Abs(veh.gameReference.Velocity.Length() - vel.Length()) > 6.0f) { veh.gameReference.ApplyForce(vel); } if ((data.vstate & VehicleState.IsBraking) == 0) { ped.gameReference.Task.DrivePointRoute(veh.gameReference, 999.0f, posnew - veh.gameReference.Velocity); } else { ped.gameReference.Task.DrivePointRoute(veh.gameReference, 999.0f, posnew + veh.gameReference.Velocity); } if ((data.state & PlayerState.IsShooting) != 0) { Vector3 pos = veh.gameReference.Position + veh.gameReference.Direction; GTA.Native.Function.Call("FIRE_PED_WEAPON", ped.gameReference, pos.X, pos.Y, pos.Z); GTA.Native.Function.Call("TASK_SHOOT_AT_COORD", ped.gameReference, pos.X, pos.Y, pos.Z, (Int32)4, 999992); } } } } }
private void eventOnKeyDown(object sender, GTA.KeyEventArgs e) { if (lastKeyDown != null && lastKeyDown == (int)e.Key) { return; } if (!inKeyboardTypingMode && e.Key == System.Windows.Forms.Keys.T) { inKeyboardTypingMode = true; cursorpos = 0; historyIndex = 0; client.getPlayer().CanControlCharacter = false; } else if (inKeyboardTypingMode) { if (e.Key == System.Windows.Forms.Keys.Enter) { if (client.chatController.currentTypedText.Length > 0) { commandHistory.Add(client.chatController.currentTypedText); if (commandHistory.Count > 100) { commandHistory = commandHistory.Skip(commandHistory.Count - 100).ToList(); } var bpf = new BinaryPacketFormatter(Commands.Chat_sendMessage); bpf.Add(client.chatController.currentTypedText); client.serverConnection.write(bpf.getBytes()); } client.chatController.currentTypedText = ""; cursorpos = 0; inKeyboardTypingMode = false; client.getPlayer().CanControlCharacter = true; } else if (e.Key == System.Windows.Forms.Keys.Escape) { client.chatController.currentTypedText = ""; cursorpos = 0; inKeyboardTypingMode = false; } else if (e.Key == System.Windows.Forms.Keys.Left) { cursorpos = cursorpos > 0 ? cursorpos - 1 : cursorpos; } else if (e.Key == System.Windows.Forms.Keys.Down) { if (commandHistory.Count > 0) { if (historyIndex <= 1) { client.chatController.currentTypedText = commandHistory[commandHistory.Count - 1]; cursorpos = 0; } else { historyIndex--; if (historyIndex < 0) { historyIndex = 0; } client.chatController.currentTypedText = commandHistory[commandHistory.Count - historyIndex]; cursorpos = client.chatController.currentTypedText.Length; } } } else if (e.Key == System.Windows.Forms.Keys.Up) { if (commandHistory.Count > 0) { historyIndex++; if (historyIndex > commandHistory.Count) { historyIndex = commandHistory.Count; } client.chatController.currentTypedText = commandHistory[commandHistory.Count - historyIndex]; cursorpos = client.chatController.currentTypedText.Length; } } else if (e.Key == System.Windows.Forms.Keys.Right) { cursorpos = cursorpos >= client.chatController.currentTypedText.Length ? client.chatController.currentTypedText.Length : cursorpos + 1; } else if (e.Key == System.Windows.Forms.Keys.Back) { if (cursorpos > 0) { string leftcut = cursorpos > 0 ? client.chatController.currentTypedText.Substring(0, cursorpos - 1) : client.chatController.currentTypedText; string rightcut = client.chatController.currentTypedText.Substring(cursorpos, client.chatController.currentTypedText.Length - cursorpos); client.chatController.currentTypedText = leftcut + rightcut; cursorpos = cursorpos > 0 ? cursorpos - 1 : cursorpos; } } else { string leftcut = client.chatController.currentTypedText.Substring(0, cursorpos); string rightcut = cursorpos >= client.chatController.currentTypedText.Length ? "" : client.chatController.currentTypedText.Substring(cursorpos, client.chatController.currentTypedText.Length - cursorpos); string newstr = keyboardUS.ParseKey((int)e.Key, e.Shift, e.Control, e.Alt); client.chatController.currentTypedText = leftcut + newstr + rightcut; cursorpos += newstr.Length; } return; } if (e.Key == System.Windows.Forms.Keys.G) { Vehicle veh = World.GetClosestVehicle(client.getPlayerPed().Position, 20.0f); if (veh != null && veh.Exists()) { VehicleSeat seat = veh.GetFreePassengerSeat(); client.getPlayerPed().Task.EnterVehicle(veh, seat); } } if (client.currentState == ClientState.Connected) { var bpf = new BinaryPacketFormatter(Commands.Keys_down); bpf.Add((int)e.Key); client.serverConnection.write(bpf.getBytes()); } lastKeyDown = (int)e.Key; lastKeyUp = 0; }
private void onReceive(IAsyncResult iar) { lock (client) { try { client.client.Client.EndReceive(iar); var bpr = new BinaryPacketReader(buffer); while (bpr.canRead()) { Commands command = bpr.readCommand(); if (command == Commands.Invalid) { break; } try { switch (command) { case Commands.Client_enableUDPTunnel: { int port = bpr.readInt32(); client.udpTunnel = new ClientUDPTunnel(port); } break; case Commands.Client_ping: { Int64 timestamp = bpr.readInt64(); write(new BinaryPacketFormatter(Commands.Client_ping, timestamp).getBytes()); } break; case Commands.Player_setModel: { string model = MIVSDK.ModelDictionary.getPedModelById(bpr.readUInt32()); client.enqueueAction(new Action(delegate { client.getPlayer().Model = new Model(model); })); } break; case Commands.Player_setHeading: { var g = bpr.readSingle(); client.enqueueAction(new Action(delegate { client.getPlayerPed().Heading = g; })); } break; case Commands.Player_setVirtualWorld: { uint id = bpr.readUInt32(); uint vworld = bpr.readUInt32(); if (client.pedController.Exists(id)) { var instance = client.pedController.GetInstance(id); instance.VirtualWorld = vworld; } } break; case Commands.Game_setGameTime: { var g = bpr.readInt64(); client.enqueueAction(new Action(delegate { World.CurrentDayTime = new TimeSpan(g); })); } break; case Commands.Game_setWeather: { var g = bpr.readByte(); client.enqueueAction(new Action(delegate { World.Weather = (Weather)(int)g; GTA.Native.Function.Call("FORCE_WEATHER_NOW", (int)g); })); } break; case Commands.Game_fadeScreenIn: { var data = bpr.readInt32(); client.enqueueAction(new Action(delegate { Game.FadeScreenIn(data); })); } break; case Commands.Game_fadeScreenOut: { var data = bpr.readInt32(); client.enqueueAction(new Action(delegate { Game.FadeScreenOut(data); })); } break; case Commands.Game_showLoadingScreen: { var data = bpr.readInt32(); client.enqueueAction(new Action(delegate { GTA.Native.Function.Call("FORCE_LOADING_SCREEN"); })); } break; case Commands.Game_hideLoadingScreen: { var data = bpr.readInt32(); client.enqueueAction(new Action(delegate { GTA.Native.Function.Call("DONT_DISPLAY_LOADING_ON_FADE_THIS_FRAME"); Game.FadeScreenIn(1); })); } break; case Commands.Game_setGravity: { var data = bpr.readSingle(); client.enqueueAction(new Action(delegate { client.getPlayerPed().GravityMultiplier = data; })); } break; case Commands.Client_setVirtualWorld: { client.CurrentVirtualWorld = bpr.readUInt32(); } break; case Commands.Client_pauseBroadcast: { client.BroadcastingPaused = true; } break; case Commands.Client_resumeBroadcast: { client.BroadcastingPaused = false; } break; case Commands.Client_JSEval: { string script = bpr.readString(); client.enqueueAction(new Action(delegate { client.jsEngine.Execute(script); })); } break; case Commands.Vehicle_removePeds: { uint id = bpr.readUInt32(); uint vworld = bpr.readUInt32(); if (client.vehicleController.Exists(id)) { var instance = client.vehicleController.GetInstance(id); if (instance.StreamedIn) { instance.gameReference.EveryoneLeaveVehicle(); } } } break; case Commands.Vehicle_repaint: { uint id = bpr.readUInt32(); ushort color = bpr.readUInt16(); if (client.vehicleController.Exists(id)) { var instance = client.vehicleController.GetInstance(id); if (instance.StreamedIn) { instance.gameReference.Color = (ColorIndex)color; } } } break; case Commands.Vehicle_repair: { uint id = bpr.readUInt32(); if (client.vehicleController.Exists(id)) { var instance = client.vehicleController.GetInstance(id); //instance.health = 100; if (instance.StreamedIn) { instance.gameReference.Repair(); } } } break; case Commands.Vehicle_setModel: { uint id = bpr.readUInt32(); string model = MIVSDK.ModelDictionary.getVehicleById(bpr.readUInt32()); if (client.vehicleController.Exists(id)) { var instance = client.vehicleController.GetInstance(id); instance.model = model; if (instance.StreamedIn) { instance.gameReference.Delete(); } } } break; case Commands.Vehicle_setOrientation: { uint id = bpr.readUInt32(); Quaternion quat = fromSharpDX(bpr.readQuaternion()); if (client.vehicleController.Exists(id)) { var instance = client.vehicleController.GetInstance(id); instance.orientation = quat; if (instance.StreamedIn) { instance.gameReference.RotationQuaternion = quat; } } } break; case Commands.Vehicle_setPosition: { uint id = bpr.readUInt32(); Vector3 position = fromSharpDX(bpr.readVector3()); if (client.vehicleController.Exists(id)) { var instance = client.vehicleController.GetInstance(id); instance.position = position; if (instance.StreamedIn) { instance.gameReference.Position = position; } } } break; case Commands.Vehicle_setVelocity: { uint id = bpr.readUInt32(); Vector3 velocity = fromSharpDX(bpr.readVector3()); if (client.vehicleController.Exists(id)) { var instance = client.vehicleController.GetInstance(id); if (instance.StreamedIn) { instance.gameReference.Velocity = velocity; } } } break; case Commands.Vehicle_setVirtualWorld: { uint id = bpr.readUInt32(); uint vworld = bpr.readUInt32(); if (client.vehicleController.Exists(id)) { var instance = client.vehicleController.GetInstance(id); instance.VirtualWorld = vworld; } } break; case Commands.NPC_setVirtualWorld: { uint id = bpr.readUInt32(); uint vworld = bpr.readUInt32(); if (client.npcPedController.Exists(id)) { var instance = client.npcPedController.GetInstance(id); instance.VirtualWorld = vworld; } } break; case Commands.Player_setHealth: { int h = bpr.readInt32(); //client.chatController.writeChat("setting healtcz " + h.ToString()); client.enqueueAction(new Action(delegate { client.getPlayerPed().Health = h; })); } break; case Commands.Player_setVehicleHealth: { int h = bpr.readInt32(); //client.chatController.writeChat("setting healtcz " + h.ToString()); client.enqueueAction(new Action(delegate { if (client.getPlayerPed().isInVehicle()) { if (h <= 0) { client.getPlayerPed().CurrentVehicle.Explode(); } else { client.getPlayerPed().CurrentVehicle.Health = h; } } })); } break; case Commands.Chat_writeLine: { client.chatController.writeChat(bpr.readString()); } break; case Commands.Player_setPosition: { Vector3 vec = fromSharpDX(bpr.readVector3()); //client.chatController.writeChat("OasK"); client.enqueueAction(new Action(delegate { client.getPlayer().TeleportTo(vec); })); } break; case Commands.Player_setVelocity: { Vector3 vec = fromSharpDX(bpr.readVector3()); client.enqueueAction(new Action(delegate { client.getPlayerPed().Velocity = vec; })); } break; case Commands.InternalClient_finishSpawn: { client.enqueueAction(new Action(delegate { client.finishSpawn(); })); } break; case Commands.Camera_setPosition: { var data = fromSharpDX(bpr.readVector3()); client.enqueueAction(new Action(delegate { client.cameraController.Position = data; })); } break; case Commands.Camera_setDirection: { var data = fromSharpDX(bpr.readVector3()); client.enqueueAction(new Action(delegate { client.cameraController.Direction = data; })); } break; case Commands.Camera_setOrientation: { var data = fromSharpDX(bpr.readVector3()); client.enqueueAction(new Action(delegate { client.cameraController.Rotation = data; })); } break; case Commands.Camera_setFOV: { var data = bpr.readSingle(); client.enqueueAction(new Action(delegate { client.cameraController.FOV = data; })); } break; case Commands.Camera_lookAt: { var data = fromSharpDX(bpr.readVector3()); client.enqueueAction(new Action(delegate { client.cameraController.LookAt(data); })); } break; case Commands.Camera_reset: { client.enqueueAction(new Action(delegate { client.cameraController.Reset(); })); } break; case Commands.Player_freeze: { client.enqueueAction(new Action(delegate { client.getPlayer().CanControlCharacter = false; })); } break; case Commands.Player_unfreeze: { client.enqueueAction(new Action(delegate { client.getPlayer().CanControlCharacter = true; })); } break; case Commands.Player_giveWeapon: { Weapon weapon = (Weapon)bpr.readInt32(); int ammo = bpr.readInt32(); client.enqueueAction(new Action(delegate { client.getPlayerPed().Weapons.FromType(weapon).Ammo = ammo; })); } break; case Commands.Global_setPlayerPedText: { uint playerid = bpr.readUInt32(); string text = bpr.readString(); if (client.pedController.Exists(playerid)) { StreamedPed ped = client.pedController.GetInstance(playerid); ped.CurrentChatMessage = text; } } break; case Commands.Global_setPlayerModel: { uint playerid = bpr.readUInt32(); string model = MIVSDK.ModelDictionary.getPedModelById(bpr.readUInt32()); if (client.playerModels.ContainsKey(playerid)) { client.playerModels[playerid] = model; } else { client.playerModels.Add(playerid, model); } if (client.pedController.Exists(playerid)) { var player = client.pedController.GetInstance(playerid); if (player.IsStreamedIn()) { player.gameReference.Delete(); } } } break; case Commands.Global_setPlayerName: { uint playerid = bpr.readUInt32(); string name = bpr.readString(); if (client.playerNames.ContainsKey(playerid)) { client.playerNames[playerid] = name; } else { client.playerNames.Add(playerid, name); } if (client.pedController.Exists(playerid)) { var player = client.pedController.GetInstance(playerid); if (player.IsStreamedIn()) { player.gameReference.Delete(); } } } break; case Commands.Global_createPlayer: { uint playerid = bpr.readUInt32(); string model = MIVSDK.ModelDictionary.getPedModelById(bpr.readUInt32()); string name = bpr.readString(); if (client.playerNames.ContainsKey(playerid)) { client.playerNames[playerid] = name; } else { client.playerNames.Add(playerid, name); } if (client.playerModels.ContainsKey(playerid)) { client.playerModels[playerid] = model; } else { client.playerModels.Add(playerid, model); } client.pedController.Add(playerid, new StreamedPed(client.pedStreamer, model, name, Vector3.Zero, 0, (BlipColor)(playerid % 13))); } break; case Commands.Request_getSelectedPlayer: { uint requestid = bpr.readUInt32(); client.enqueueAction(new Action(delegate { var peds = World.GetPeds(client.getPlayerPed().Position, 80.0f); Ped selectedPed = null; foreach (var ped in peds) { var projected = (Vector2)World.WorldToScreenProject(ped.Position); if (Math.Abs((projected - new Vector2(Game.Resolution.Width / 2, Game.Resolution.Height / 2)).Length()) < 30.0) { selectedPed = ped; break; } } var bpf = new BinaryPacketFormatter(Commands.Request_getSelectedPlayer); bpf.Add(requestid); if (selectedPed != null) { bpf.Add(client.pedController.dict.Count(a => a.Value.IsStreamedIn() && a.Value.gameReference == selectedPed) > 0 ? client.pedController.dict.First(a => a.Value.IsStreamedIn() && a.Value.gameReference == selectedPed).Key : 0); } else { bpf.Add(0); } client.serverConnection.write(bpf.getBytes()); })); } break; case Commands.Request_getCameraPosition: { uint requestid = bpr.readUInt32(); client.enqueueAction(new Action(delegate { var bpf = new BinaryPacketFormatter(Commands.Request_getCameraPosition); bpf.Add(requestid); bpf.Add(new SharpDX.Vector3(Game.CurrentCamera.Position.X, Game.CurrentCamera.Position.Y, Game.CurrentCamera.Position.Z)); client.serverConnection.write(bpf.getBytes()); })); } break; case Commands.Request_worldToScreen: { uint requestid = bpr.readUInt32(); var world = bpr.readVector3(); client.enqueueAction(new Action(delegate { var bpf = new BinaryPacketFormatter(Commands.Request_worldToScreen); bpf.Add(requestid); var screen = (Vector2)World.WorldToScreenProject(new Vector3(world.X, world.Y, world.Z)); bpf.Add(screen.X); bpf.Add(screen.Y); client.serverConnection.write(bpf.getBytes()); })); } break; case Commands.Request_isObjectVisible: { uint requestid = bpr.readUInt32(); var position = bpr.readVector3(); client.enqueueAction(new Action(delegate { var bpf = new BinaryPacketFormatter(Commands.Request_isObjectVisible); bpf.Add(requestid); bpf.Add(new byte[1] { (byte)(Game.CurrentCamera.isSphereVisible(new Vector3(position.X, position.Y, position.Z), 1.0f) ? 1 : 0) }); client.serverConnection.write(bpf.getBytes()); })); } break; case Commands.Vehicle_create: { uint id = bpr.readUInt32(); Vector3 pos = fromSharpDX(bpr.readVector3()); Quaternion rot = fromSharpDX(bpr.readQuaternion()); string model = MIVSDK.ModelDictionary.getVehicleById(bpr.readUInt32()); client.enqueueAction(new Action(delegate { client.vehicleController.Add(id, new StreamedVehicle(client.vehicleStreamer, model, pos, rot)); })); } break; case Commands.NPC_create: { //int count = bpr.readInt32(); uint id = bpr.readUInt32(); Vector3 pos = fromSharpDX(bpr.readVector3()); float heading = bpr.readSingle(); string model = MIVSDK.ModelDictionary.getPedModelById(bpr.readUInt32()); string str = bpr.readString(); client.enqueueAction(new Action(delegate { client.npcPedController.Add(id, new StreamedPed(client.pedStreamer, model, str, pos, heading, BlipColor.Grey)); })); } break; case Commands.NPC_update: { //int count = bpr.readInt32(); uint id = bpr.readUInt32(); Vector3 pos = fromSharpDX(bpr.readVector3()); float heading = bpr.readSingle(); string model = MIVSDK.ModelDictionary.getPedModelById(bpr.readUInt32()); string str = bpr.readString(); client.enqueueAction(new Action(delegate { var ped = client.npcPedController.GetInstance(id); ped.position = pos; ped.heading = heading; ped.model = model; ped.networkname = str; })); } break; case Commands.NPC_setPosition: { uint id = bpr.readUInt32(); Vector3 pos = fromSharpDX(bpr.readVector3()); client.enqueueAction(new Action(delegate { var ped = client.npcPedController.GetInstance(id); ped.position = pos; if (ped.IsStreamedIn()) { ped.gameReference.Position = pos; } })); } break; case Commands.NPC_setHeading: { uint id = bpr.readUInt32(); float heading = bpr.readSingle(); client.enqueueAction(new Action(delegate { var ped = client.npcPedController.GetInstance(id); ped.heading = heading; if (ped.IsStreamedIn()) { ped.gameReference.Heading = heading; } })); } break; case Commands.NPC_runTo: { uint id = bpr.readUInt32(); Vector3 pos = fromSharpDX(bpr.readVector3()); client.enqueueAction(new Action(delegate { var ped = client.npcPedController.GetInstance(id); ped.position = pos; if (ped.IsStreamedIn()) { ped.animator.refreshAnimationForce(); ped.animator.playAnimation(PedAnimations.RunTo, pos); } })); } break; case Commands.NPC_walkTo: { uint id = bpr.readUInt32(); Vector3 pos = fromSharpDX(bpr.readVector3()); client.enqueueAction(new Action(delegate { var ped = client.npcPedController.GetInstance(id); ped.position = pos; if (ped.IsStreamedIn()) { ped.animator.refreshAnimationForce(); ped.animator.playAnimation(PedAnimations.WalkTo, pos); } })); } break; case Commands.NPC_enterVehicle: { uint id = bpr.readUInt32(); uint vid = bpr.readUInt32(); client.enqueueAction(new Action(delegate { var ped = client.npcPedController.GetInstance(id); ped.vehicle_id = vid; var veh = client.vehicleController.GetInstance(vid); if (ped.IsStreamedIn() && veh.IsStreamedIn()) { ped.gameReference.WarpIntoVehicle(veh.gameReference, VehicleSeat.Driver); } })); } break; case Commands.NPC_driveTo: { uint id = bpr.readUInt32(); Vector3 pos = fromSharpDX(bpr.readVector3()); client.enqueueAction(new Action(delegate { var ped = client.npcPedController.GetInstance(id); if (ped.vehicle_id > 0) { var veh = client.vehicleController.GetInstance(ped.vehicle_id); if (ped.IsStreamedIn() && veh.IsStreamedIn()) { ped.gameReference.Task.DriveTo(veh.gameReference, pos, 999.0f, false, true); } } })); } break; case Commands.NPC_leaveVehicle: { uint id = bpr.readUInt32(); client.enqueueAction(new Action(delegate { var ped = client.npcPedController.GetInstance(id); ped.vehicle_id = 0; if (ped.IsStreamedIn()) { ped.gameReference.LeaveVehicle(); } })); } break; case Commands.NPC_setModel: { uint id = bpr.readUInt32(); string model = MIVSDK.ModelDictionary.getPedModelById(bpr.readUInt32()); client.enqueueAction(new Action(delegate { var ped = client.npcPedController.GetInstance(id); ped.model = model; if (ped.IsStreamedIn()) { ped.gameReference.Delete(); } })); } break; case Commands.NPC_setImmortal: { uint id = bpr.readUInt32(); byte option = bpr.readByte(); client.enqueueAction(new Action(delegate { var ped = client.npcPedController.GetInstance(id); ped.immortal = option == 1; if (ped.IsStreamedIn()) { ped.gameReference.Invincible = option == 1; } })); } break; case Commands.NPCDialog_show: { uint id = bpr.readUInt32(); string captiontext = bpr.readString(); string texttext = bpr.readString(); string str = bpr.readString(); string[] split = str.Split('\x01'); client.enqueueAction(new Action(delegate { GTA.Forms.Form form = new GTA.Forms.Form(); GTA.Forms.Label caption = new GTA.Forms.Label(); caption.Location = new System.Drawing.Point(10, 10); caption.Text = captiontext; GTA.Forms.Label text = new GTA.Forms.Label(); text.Location = new System.Drawing.Point(10, 40); text.Text = texttext; form.Controls.Add(caption); form.Controls.Add(text); for (int i = 0; i < split.Length; i++) { GTA.Forms.Button button = new GTA.Forms.Button(); button.Location = new System.Drawing.Point(10, 40 + i * 20); button.Text = split[i]; button.MouseDown += (s, o) => { var bpf = new BinaryPacketFormatter(Commands.NPCDialog_sendResponse); bpf.Add(id); bpf.Add(new byte[1] { (byte)(i - 2) }); write(bpf.getBytes()); form.Close(); }; form.Controls.Add(button); } form.Show(); })); } break; } } catch (Exception e) { Client.log("Failed dispatching command " + command.ToString() + " with " + e.Message + " " + e.StackTrace); client.chatController.writeChat("Failed dispatching command " + command.ToString() + " with " + e.Message + " " + e.StackTrace); client.chatController.writeChat("Disconnected abnormally from server"); client.currentState = ClientState.Disconnected; } } client.client.Client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, onReceive, null); //} } catch (Exception e) { Client.log("Failed receive with message " + e.Message + " " + e.StackTrace); client.chatController.writeChat("Failed receive with message " + e.Message + " " + e.StackTrace); client.chatController.writeChat("Disconnected abnormally from server"); client.currentState = ClientState.Disconnected; //throw e; } } }
private void onReceive(IAsyncResult iar) { lock (Connection) { try { int count = Connection.Client.EndReceive(iar); } catch { Console.WriteLine("Client disconnected"); return; } var bpr = new BinaryPacketReader(Buffer); while (bpr.canRead()) { Commands command = bpr.readCommand(); if (command == Commands.Invalid) { break; } switch (command) { case Commands.Disconnect: { if (Player != null) { Server.instance.api.invokeOnPlayerDisconnect(Player); } } break; case Commands.Connect: { string nick = bpr.readString(); if (OnConnect != null) { OnConnect.Invoke(nick); } } break; case Commands.InternalClient_requestSpawn: { if (Player != null) { Server.instance.api.invokeOnPlayerDie(Player); Server.instance.api.invokeOnPlayerSpawn(Player); var bpf = new BinaryPacketFormatter(Commands.InternalClient_finishSpawn); Player.connection.write(bpf.getBytes()); } } break; case Commands.Client_ping: { Int64 timestamp = bpr.readInt64(); Int64 current = DateTime.Now.Ticks; Player.Ping = (int)((current - timestamp) / 10000); } break; case Commands.Request_getSelectedPlayer: { if (Player != null) { uint requestid = bpr.readUInt32(); uint playerid = bpr.readUInt32(); Request.dispatch(requestid, playerid); } } break; case Commands.Request_getCameraPosition: { if (Player != null) { uint requestid = bpr.readUInt32(); var vect = bpr.readVector3(); Request.dispatch(requestid, vect); } } break; case Commands.Request_isObjectVisible: { if (Player != null) { uint requestid = bpr.readUInt32(); var vect = bpr.readByte() == 1; Request.dispatch(requestid, vect); } } break; case Commands.Request_worldToScreen: { if (Player != null) { uint requestid = bpr.readUInt32(); var x = bpr.readSingle(); var y = bpr.readSingle(); Request.dispatch(requestid, new SharpDX.Vector2(x, y)); } } break; case Commands.Chat_sendMessage: { string text = bpr.readString(); if (text.StartsWith("/")) { List <string> split = text.Split(' ').ToList(); Server.instance.api.invokeOnPlayerSendCommand(Player, split.First().Substring(1), split.Skip(1).ToArray()); } else { Server.instance.api.invokeOnPlayerSendText(Player, text); } } break; case Commands.Player_damage: { if (Player != null) { uint playerid = bpr.readUInt32(); var bpf = new BinaryPacketFormatter(Commands.Player_setHealth); int newvalue = Server.instance.getPlayerById(playerid).data.ped_health - 10; bpf.Add(newvalue); var damaged_player = Server.instance.getPlayerById(playerid); damaged_player.connection.write(bpf.getBytes()); if (newvalue <= 0 && !Player.isDead) { Player.isDead = true; Server.instance.api.invokeOnPlayerDie(damaged_player, Player, (Enums.Weapon)Player.data.weapon); } } } break; case Commands.Vehicle_damage: { if (Player != null) { uint playerid = bpr.readUInt32(); uint vehicleid = bpr.readUInt32(); int delta = bpr.readInt32(); var bpf = new BinaryPacketFormatter(Commands.Player_setVehicleHealth); int newvalue = Server.instance.vehicleController.getById(vehicleid).health - delta; bpf.Add(newvalue); Server.instance.getPlayerById(playerid).connection.write(bpf.getBytes()); } } break; case Commands.Keys_down: { if (Player != null) { int key = bpr.readInt32(); Server.instance.api.invokeOnPlayerKeyDown(Player, (System.Windows.Forms.Keys)key); } } break; case Commands.Keys_up: { if (Player != null) { int key = bpr.readInt32(); Server.instance.api.invokeOnPlayerKeyUp(Player, (System.Windows.Forms.Keys)key); } } break; case Commands.NPCDialog_sendResponse: { if (Player != null) { uint key = bpr.readUInt32(); byte answer = Buffer[6]; ServerNPCDialog.invokeResponse(Player, key, answer); } } break; case Commands.UpdateData: { if (Player != null) { MIVSDK.UpdateDataStruct data = bpr.readUpdateStruct(); if (Player.data.ped_health > data.ped_health) { Server.instance.api.invokeOnPlayerTakeDamage(Player, Player.data.ped_health, data.ped_health, Player.data.ped_health - data.ped_health); } Player.updateData(data); } } break; } } Connection.Client.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, onReceive, null); } }
private void eventOnTick(object sender, EventArgs e) { try { while (actionQueue.Count > 0) { actionQueue.Dequeue().Invoke(); } } catch (Exception ex) { log("Failed executing action queue with message " + ex.Message); } if (currentState == ClientState.Connected) { if (currentData == null) { currentData = UpdateDataStruct.Zero; } if (!BroadcastingPaused && Player.Character.Exists()) { try { UpdateDataStruct data = new UpdateDataStruct(); if (Player.Character.isInVehicle() && Player.Character.CurrentVehicle.GetPedOnSeat(VehicleSeat.Driver) == Player.Character) { if (vehicleController.dict.Count(a => a.Value.IsStreamedIn() && a.Value.gameReference == Player.Character.CurrentVehicle) > 0) { try { Vector3 pos = Player.Character.CurrentVehicle.Position; data.pos_x = pos.X; data.pos_y = pos.Y; data.pos_z = pos.Z; Vector3 currentSpeed = Player.Character.CurrentVehicle.Velocity; float speed = Player.Character.CurrentVehicle.Speed; if (currentData.pos_x != 0) { float deltax = (pos.X - currentData.pos_x); float deltay = (pos.Y - currentData.pos_y); float deltaz = (pos.Z - currentData.pos_z); data.vel_x = (deltax < 0 ? currentSpeed.X * -1 : currentSpeed.X); data.vel_y = (deltay < 0 ? currentSpeed.Y * -1 : currentSpeed.Y); data.vel_z = (deltaz < 0 ? currentSpeed.Z * -1 : currentSpeed.Z); } else { data.vel_x = currentSpeed.X; data.vel_y = currentSpeed.Y; data.vel_z = currentSpeed.Z; } Quaternion quat = Player.Character.CurrentVehicle.RotationQuaternion; data.rot_x = quat.X; data.rot_y = quat.Y; data.rot_z = quat.Z; data.rot_a = quat.W; data.vehicle_model = Player.Character.CurrentVehicle.Model.Hash; data.vehicle_health = Player.Character.CurrentVehicle.Health; var cveh = vehicleController.dict.First(a => a.Value.IsStreamedIn() && a.Value.gameReference == Player.Character.CurrentVehicle); data.vehicle_id = cveh.Key; data.ped_health = Player.Character.Health; data.heading = Player.Character.CurrentVehicle.Heading; cveh.Value.position = pos; cveh.Value.orientation = quat; } catch (Exception eq) { Game.Log("Failed pedInvehicle position measure processing: " + eq.Message); } } data.state = 0; } else { try { Vector3 pos = Player.Character.Position; data.pos_x = pos.X; data.pos_y = pos.Y; data.pos_z = pos.Z; Vector3 vel = Player.Character.Velocity; data.vel_x = vel.X; data.vel_y = vel.Y; data.vel_z = vel.Z; data.rot_x = Player.Character.Direction.X; data.rot_y = Player.Character.Direction.Y; data.rot_z = Player.Character.Direction.Z; data.rot_a = 0; data.vehicle_model = 0; data.vehicle_health = 0; // for passengers:)client.pedController.dict.First(a => a.Value.IsStreamedIn() && a.Value.gameReference == selectedPed) data.vehicle_id = Player.Character.isInVehicle() ? vehicleController.dict.First(a => a.Value.IsStreamedIn() && a.Value.gameReference == Player.Character.CurrentVehicle).Key : 0; data.ped_health = Player.Character.Health; data.heading = Player.Character.Heading; data.weapon = (int)Player.Character.Weapons.CurrentType; data.state = 0; data.state |= Player.Character.isShooting ? PlayerState.IsShooting : 0; data.state |= Game.isGameKeyPressed(GameKey.Aim) ? PlayerState.IsAiming : 0; data.state |= Game.isGameKeyPressed(GameKey.Crouch) ? PlayerState.IsCrouching : 0; data.state |= Game.isGameKeyPressed(GameKey.Jump) ? PlayerState.IsJumping : 0; data.state |= Game.isGameKeyPressed(GameKey.Attack) ? PlayerState.IsShooting : 0; data.state |= Player.Character.isInVehicle() && Player.Character.CurrentVehicle.GetPedOnSeat(VehicleSeat.RightFront) == Player.Character ? PlayerState.IsPassenger1 : 0; data.state |= Player.Character.isInVehicle() && Player.Character.CurrentVehicle.GetPedOnSeat(VehicleSeat.LeftRear) == Player.Character ? PlayerState.IsPassenger2 : 0; data.state |= Player.Character.isInVehicle() && Player.Character.CurrentVehicle.GetPedOnSeat(VehicleSeat.RightRear) == Player.Character ? PlayerState.IsPassenger3 : 0; } catch (Exception eq) { Game.Log("Failed ped position measure processing: " + eq.Message); } } data.vstate = 0; data.vstate |= Game.isGameKeyPressed(GameKey.MoveForward) ? VehicleState.IsAccelerating : 0; data.vstate |= Game.isGameKeyPressed(GameKey.MoveBackward) ? VehicleState.IsBraking : 0; data.vstate |= Game.isGameKeyPressed(GameKey.MoveLeft) ? VehicleState.IsSterringLeft : 0; data.vstate |= Game.isGameKeyPressed(GameKey.MoveRight) ? VehicleState.IsSterringRight : 0; data.vstate |= Game.isGameKeyPressed(GameKey.Sprint) ? VehicleState.IsSprinting : 0; data.vstate |= Player.Character.isGettingIntoAVehicle ? VehicleState.IsEnteringVehicle : 0; data.vstate |= (data.state & PlayerState.IsPassenger1) != 0 || (data.state & PlayerState.IsPassenger2) != 0 || (data.state & PlayerState.IsPassenger3) != 0 ? VehicleState.IsAsPassenger : 0; data.camdir_x = Game.CurrentCamera.Direction.X; data.camdir_y = Game.CurrentCamera.Direction.Y; data.camdir_z = Game.CurrentCamera.Direction.Z; /* * var bpf = new BinaryPacketFormatter(Commands.UpdateData); * bpf.Add(data); * serverConnection.write(bpf.getBytes());*/ if (udpTunnel != null) { udpTunnel.broadcastData(data); } try { if (!isCurrentlyDead && (Player.Character.Health == 0 || Player.Character.isDead || !Player.Character.isAlive)) { //Game.FadeScreenOut(4000); //Player.Character.Die(); //AlternateHook.call(AlternateHookRequest.OtherCommands.FAKE_DEATHARREST); //AlternateHook.call(AlternateHookRequest.OtherCommands.CREATE_PLAYER, 0.0f, 0.0f, 0.0f, null); isCurrentlyDead = true; } if (isCurrentlyDead && !Player.Character.isDead && Player.Character.isAlive && Player.Character.Health > 0) { Game.FadeScreenIn(2000); isCurrentlyDead = false; var bpf2 = new BinaryPacketFormatter(Commands.InternalClient_requestSpawn); serverConnection.write(bpf2.getBytes()); } } catch (Exception eq) { Game.Log("Failed death processing: " + eq.Message); } currentData = data; } catch (Exception ex) { Game.Log("Failed sending new Player data with message " + ex.Message); } } try { serverConnection.flush(); } catch (Exception ex) { Game.Log("Failed sending packets " + ex.Message); } try { updateAllPlayers(); pedStreamer.Update(); vehicleStreamer.Update(); pedStreamer.UpdateNormalTick(); vehicleStreamer.UpdateNormalTick(); } catch (Exception ex) { log("Failed updating streamers and players with message " + ex.Message); } } if (currentState == ClientState.Connecting) { currentState = ClientState.Connected; darkscreen.destroy(); Game.FadeScreenIn(3000); GTA.Native.Function.Call("DO_SCREEN_FADE_IN_UNHACKED", 2000); GTA.Native.Function.Call("FORCE_LOADING_SCREEN", false); var bpf = new BinaryPacketFormatter(Commands.Connect); bpf.Add(nick); serverConnection.write(bpf.getBytes()); Player.Model = new Model("F_Y_HOOKER_01"); Player.NeverGetsTired = true; //ClientTextureDraw draw = new ClientTextureDraw(new System.Drawing.RectangleF(20, 20, 400, 400), @"C:\Users\Aerofly\Desktop\4duzy.png"); //chatController.writeChat("Connected"); } }