public void TestSerializePositionInfo() { GameManager.Instance.CreateGame(new Player(), "test game"); BaseUnit unit = new BaseUnit(); unit.UnitClass = new UnitClass("Ship", GameConstants.UnitType.SurfaceShip); unit.UnitClass.TurnRangeDegrSec = 10; unit.UnitClass.MaxAccelerationKphSec = 10; unit.UnitClass.MaxSpeedKph = 40; unit.Position = new Position(60.0, 1.0, 0, 2); unit.Name = "USS Neverdock"; Position dest = new Position(61.0, 2.0); unit.MovementOrder.AddWaypoint(new Waypoint(dest)); CommsMarshaller marshaller = new CommsMarshaller(); PositionInfo pos = unit.GetPositionInfo(); byte[] bytes1 = marshaller.SerializeObjectForSending(pos); marshaller.AddToReceiveBufferEnd(bytes1, bytes1.Length); IMarshallable obj1 = marshaller.DeSerializeNextObjectInReceiveBuffer(); Assert.IsNotNull(obj1, "Should be 1 object in buffer."); PositionInfo posinfo = (PositionInfo)obj1; Assert.AreEqual(unit.Id, posinfo.UnitId, "Id should be the same"); GameManager.Instance.TerminateGame(); }
public void Send(IMarshallable obj) { if (obj != null) { _client.Send(obj); } }
private void HandleBaseUnitInfo(IMarshallable dataReceived) { BaseUnitInfo info = dataReceived as BaseUnitInfo; if (info != null) { if (_Units.Find(u => info.Id == u.Id) != null) { _Units.RemoveAll(u => u.Id == info.Id); } else { ShowInfo("Received BaseUnitInfo: " + info.ToString()); } if (info.IsMarkedForDeletion) { //ShowInfo(string.Format("Unit [{0}] {1} has been DESTROYED.", info.Id, info.UnitName)); } else { _Units.Add(info); } ShowGameInfo(); lstUnits.Items.Refresh(); } }
public void SendToClient(int tcpPlayerIndex, IMarshallable marshallable) { if (_Game != null) { _Game.SendToClient(tcpPlayerIndex, marshallable); } }
/// <summary> /// Suspends the listening for incoming PDU's. /// </summary> /// <param name="pdu">The <see cref="DIS.Dis1998.IMarshallable"/> PDU to be transmitted</param> /// <param name="group">The <see cref="DIS.Utilties.Networking.MulticastGroup"/> to send this PDU to.</param> public void sendPDU(IMarshallable pdu, MulticastGroup group) { DataOutputStream dos = new DataOutputStream(Endian.Big); pdu.MarshalAutoLengthSet(dos); byte[] data = dos.ConvertToBytes(); UdpClient.Send(data, data.Length, new IPEndPoint(group.Address, Port)); }
public void Send(int clientId, IMarshallable message) { TcpClient client = GetClientById(clientId); if (client != null) { Send(client, message); } }
private void HandleMessageInfo(IMarshallable dataReceived) { MessageInfo info = dataReceived as MessageInfo; if (info != null) { GameManager.Instance.MessageManager.AddMessage(info.ToString(), GameManager.MessageTypes.Game, null); } }
/// <summary> /// This method must be called repeatedly by the client code by a timer or otherwise. /// </summary> public void PollNetwork() { //_Logger.LogDebug("Gameclient attempting to poll network..."); if (ConnectionStatus != GameConstants.ConnectionStatusEnum.Connected || _TcpClient == null || !_TcpClient.Connected) { //try //{ // _Logger.LogWarning("Cannot poll network. Connection status: " + ConnectionStatus.ToString() // + " TcpClient: " + _TcpClient == null ? "null" : _TcpClient.ToString() // + " TcpClient connected?: " + _TcpClient == null ? "null" : _TcpClient.Connected.ToString()); //} //catch (Exception ex) //{ // _Logger.LogError("PollNetwork failed to log warning. " + ex.ToString()); //} return; } NetworkStream stream = _TcpClient.GetStream(); try { if (stream.DataAvailable) { do { int i = stream.Read(_ReadBuffer, 0, _ReadBuffer.Length); _CommsMarshaller.AddToReceiveBufferEnd(_ReadBuffer, i); while (_CommsMarshaller.IsObjectInReceiveBuffer()) { IMarshallable obj = _CommsMarshaller.DeSerializeNextObjectInReceiveBuffer(); DataReceived(obj); } } while (stream.DataAvailable); } } catch (ArgumentException ex) { _Logger.LogError("Error in GameClient.PollNetwork: " + ex.ToString()); } catch (Exception ex) { if (ex.InnerException == null) { _Logger.LogError("Error in GameClient.PollNetwork: " + ex.ToString()); } else { _Logger.LogError("Error in GameClient.PollNetwork: " + ex.ToString() + "\nInnerException: " + ex.InnerException.ToString()); } } }
public void TestSerializingDeserializing() { CommsMarshaller marshaller = new CommsMarshaller(); MessageString str = new MessageString(); str.Message = "Hello!"; byte[] bytes = marshaller.SerializeObjectForSending(str); marshaller.AddToReceiveBufferEnd(bytes, bytes.Length); IMarshallable obj = marshaller.DeSerializeNextObjectInReceiveBuffer(); Assert.IsNotNull(obj, "Object from send buffer should not be null."); }
private void HandleGameUIControlInfo(IMarshallable dataReceived) { Debug.Log("GameUIControl received"); GameUiControl guc = dataReceived as GameUiControl; Vector3 position = new Vector3((float)guc.PositionX, (float)guc.PositionY, (float)guc.PositionZ); Vector3 rotation = new Vector3((float)guc.RotationX, (float)guc.RotationY, (float)guc.RotationZ); PlayerUnit unit = GameManager.Instance.UnitManager.FindUnitById(guc.Id); GameManager.Instance.CameraManager.SetCameraFocus(position, rotation, unit != null ? unit : null); }
private void HandleUnitClass(IMarshallable dataReceived) { UnitClass unitClass = dataReceived as UnitClass; if (GameManager.Instance.AddUnitClass(unitClass)) { Debug.Log("UnitClass Added"); } else { Debug.Log("UnitClass not added. Already exists"); } }
private void HandleGroupInfo(IMarshallable dataReceived) { GroupInfo groupInfo = dataReceived as GroupInfo; if (groupInfo != null) { ShowInfo("***GroupInfo received.\n" + groupInfo.ToLongString()); if (_Groups.Find(u => groupInfo.Id == u.Id) != null) { _Detections.RemoveAll(u => u.Id == groupInfo.Id); } _Groups.Add(groupInfo); } }
private void HandleDetectedGroupInfo(IMarshallable dataReceived) { DetectedGroupInfo det = dataReceived as DetectedGroupInfo; if (det != null) { ShowInfo("### DetectedGroupInfo received: " + det.ToString()); if (_DetectedGroups.Contains(det)) { _DetectedGroups.Remove(det); } _DetectedGroups.Add(det); } }
private void HandleMessageInfo(IMarshallable dataReceived) { MessageInfo info = dataReceived as MessageInfo; if (info != null) { string temp = ""; if (!string.IsNullOrEmpty(info.FromPlayerId)) { temp = "From: " + info.FromPlayerId + "\n"; } temp += info.MessageBody; ShowInfo(temp); } }
public byte[] SerializeObjectForSending(IMarshallable obj) { int Token = (int)GetTypeTokenFromObject(obj); byte[] RawBytes = SerializeObjectToBytes(obj); int Length = RawBytes.Length; byte[] AllBytes = new byte[Length + TOKEN_BYTE_COUNT + LENGTH_BYTE_COUNT]; byte[] TokenBytes = BitConverter.GetBytes((UInt16)Token); byte[] LengthBytes = BitConverter.GetBytes((UInt32)Length); Array.Copy(TokenBytes, 0, AllBytes, 0, TOKEN_BYTE_COUNT); Array.Copy(LengthBytes, 0, AllBytes, TOKEN_BYTE_COUNT, LENGTH_BYTE_COUNT); Array.Copy(RawBytes, 0, AllBytes, TOKEN_BYTE_COUNT + LENGTH_BYTE_COUNT, RawBytes.Length); return(AllBytes); }
private void HandleDetectedUnitInfo(IMarshallable dataReceived) { string selectedId = string.Empty; DetectedUnitInfo det = dataReceived as DetectedUnitInfo; if (lstDetections.SelectedItem != null) { DetectedUnitInfo detUnit = lstDetections.SelectedItem as DetectedUnitInfo; if (detUnit != null) { selectedId = detUnit.Id; } } if (_Detections.Find(u => det.Id == u.Id) != null) { _Detections.RemoveAll(u => u.Id == det.Id); ShowInfo("DetectedUnitInfo received: Id=" + det.Id + " " + det.ToString()); } _Detections.Add(det); //if (det.PositionRegion != null) //{ // ShowInfo("### PositionRegion: " + det.PositionRegion.ToString()); //} ShowGameInfo(); UpdateUnitInfoWindow(); lstDetections.Items.Refresh(); if (!string.IsNullOrEmpty(selectedId)) { foreach (var it in lstDetections.Items) { DetectedUnitInfo detLst = it as DetectedUnitInfo; if (detLst != null) { if (detLst.Id == selectedId) { lstDetections.SelectedItem = it; } } } } }
private void HandlePositionInfo(IMarshallable dataReceived) { PositionInfo posInfo = dataReceived as PositionInfo; if (posInfo != null) { if (posInfo.IsDetection) { Enemy eUnit = GameManager.Instance.UnitManager.FindEnemyById(posInfo.UnitId); //~ Debug.Log("Is Detection"); if (eUnit != null) { eUnit.Position = posInfo; } else { Debug.Log("Enemy Unit does not exist. The Flying Dutchman???"); } } else { PlayerUnit pUnit = GameManager.Instance.UnitManager.FindUnitById(posInfo.UnitId); if (pUnit == null) //DO Something { //~ Debug.Log(string.Format("Unit is null {0}", posInfo.UnitId)); } else { pUnit.Position = posInfo; if (pUnit.Info.Tag == "main") { //Debug.Log(string.Format("Main unit PositionInfo.BearingDeg : {0} - for Unit: {1}", posInfo.BearingDeg, posInfo.UnitId)); } } } } }
private void HandleGameStateInfo(IMarshallable dataReceived) { GameStateInfo gameInfo = dataReceived as GameStateInfo; if (gameInfo != null) { if (gameInfo.InfoType == GameConstants.GameStateInfoType.UnitIsDestroyed) { if (_selectedUnitInfo != null && _selectedUnitInfo.Id == gameInfo.Id) { _selectedUnitInfo = null; } _Units.RemoveAll(u => u.Id == gameInfo.Id); lstUnits.Items.Refresh(); } else if (gameInfo.InfoType == GameConstants.GameStateInfoType.DetectedContactIsLost || gameInfo.InfoType == GameConstants.GameStateInfoType.DetectedContactIsDestroyed) { _Detections.RemoveAll(d => d.Id == gameInfo.Id); lstDetections.Items.Refresh(); } else if (gameInfo.InfoType == GameConstants.GameStateInfoType.DetectedContactGroupIsLost) { _DetectedGroups.RemoveAll(d => d.Id == gameInfo.Id); } else if (gameInfo.InfoType == GameConstants.GameStateInfoType.AircraftIsLanded) { _Units.RemoveAll(u => u.Id == gameInfo.Id); lstUnits.Items.Refresh(); ShowInfo("Aircraft has landed : " + gameInfo.Id); } else if (gameInfo.InfoType == GameConstants.GameStateInfoType.MissileLaunch) { } ShowInfo("***GameStateInfo: " + gameInfo.ToString()); } }
private void HandleDetectedUnitInfo(IMarshallable dataReceived) { //~ string selectedId = string.Empty; DetectedUnitInfo det = dataReceived as DetectedUnitInfo; GameManager.Instance.MessageManager.AddMessage(dataReceived.ToString(), GameManager.MessageTypes.Detection, det.Position); //Debug.Log(dataReceived.ToString()); if (det != null) { Enemy unit = null; GameObject go = null; try { unit = GameManager.Instance.UnitManager.FindEnemyById(det.Id); go = unit != null ? unit.gameObject : null; } catch (NullReferenceException ex) { Debug.Log(ex.Message); } if (go == null) { string UnitModelFileName = "unknownSurface"; switch (det.DetectionClassification) { case GameConstants.DetectionClassification.FixedWingAircraft: UnitModelFileName = "unknownFixedWing"; break; case GameConstants.DetectionClassification.Helicopter: UnitModelFileName = "unknownHeli"; break; case GameConstants.DetectionClassification.Mine: break; case GameConstants.DetectionClassification.Missile: break; case GameConstants.DetectionClassification.Submarine: UnitModelFileName = "unknownSubmarine"; break; case GameConstants.DetectionClassification.Surface: UnitModelFileName = "unknownSurface"; break; case GameConstants.DetectionClassification.Torpedo: break; case GameConstants.DetectionClassification.Unknown: break; default: break; } if (!string.IsNullOrEmpty(det.RefersToUnitClassId)) { UnitModelFileName = GameManager.Instance.GetUnitClass(det.RefersToUnitClassId).UnitModelFileName; } go = GetVesselByUnitClassId(UnitModelFileName, det.Position); go.name = det.RefersToUnitName; unit = go.AddComponent <Enemy>(); unit.Size = new Vector2(32, 32); Vector3 pos = new Vector3(); pos.x = ((float)det.Position.LongitudeOrthoProjected * GameManager.Instance.XMapModifier) + GameManager.Instance.XMapAddition; pos.z = ((float)det.Position.LatitudeOrthoProjected * GameManager.Instance.YMapModifier) + GameManager.Instance.YMapAddtion; pos.y = 30000; go.transform.parent = GameObject.Find("EnemyUnits").transform; if (det.DomainType != GameConstants.DomainType.Air) { go.transform.localScale = GameManager.Instance.GlobalScale; GameObject healthBar = Instantiate(HealthBar, Vector3.zero, Quaternion.identity) as GameObject; healthBar.transform.parent = go.transform; healthBar.transform.localPosition = Vector3.up * 10; } GameObject detGo = new GameObject("Detection"); DetectionMarker marker = detGo.AddComponent <DetectionMarker>(); marker.Position = pos; marker.MinSize = new Vector2(8, 8); marker.MaxSize = new Vector2(128, 128); marker.KillTime = 3; marker.FadeTime = 1.5f; marker.MessageToDisplay = new Message("Detection", GameManager.MessageTypes.Detection); } //~ MapEnemy mu = AddMapEnemy(unit, GameManager.Instance.GetTextureByUnitClassId("enemyDetection")); unit.Info = det; GameManager.Instance.UnitManager.AddEnemy(unit); } }
private void HandleGameStateInfo(IMarshallable dataReceived) { //GameManager.Instance.MessageManager.AddMessage(dataReceived.ToString(), GameManager.MessageTypes.Game, null); GameStateInfo gameInfo = dataReceived as GameStateInfo; if (gameInfo != null) { switch (gameInfo.InfoType) { case CommsMarshaller.GameStateInfoType.UnitIsDestroyed: PlayerUnit unit = GameManager.Instance.UnitManager.FindUnitById(gameInfo.Id); if (unit != null) { unit.Kill(true); } //~ ShowMessage("GameStateInfo object, UnitIsDestroyed"); break; case CommsMarshaller.GameStateInfoType.DetectedContactIsLost: //~ ShowMessage("GameStateInfo object, DetectedContactIsLost"); Debug.Log(string.Format("Lost detection Id: {0} - Time:{1}", gameInfo.Id, Time.time)); Enemy e = GameManager.Instance.UnitManager.FindEnemyById(gameInfo.Id); if (e != null) { e.Kill(); } else { Debug.Log("Lost contact with unit not in enemy list. Error?"); } break; case CommsMarshaller.GameStateInfoType.AircraftIsLanded: { PlayerUnit launchPlatform = GameManager.Instance.UnitManager.FindUnitById(gameInfo.SecondaryId); PlayerUnit aircraft = GameManager.Instance.UnitManager.FindUnitById(gameInfo.Id); Debug.Log(string.Format("Aircraft has landed: {0} on {1}", aircraft.Info.UnitName, launchPlatform.Info.UnitName)); if (aircraft != null) { Debug.Log(string.Format("Killing off unit: {0}. ", aircraft.Info.UnitName)); aircraft.Kill(false); Debug.Log(string.Format("{0} killed ", aircraft.Info.UnitName)); } else { Debug.Log("Aircraft is null"); break; } //gameInfo. if (launchPlatform != null) { AnimationLauncher al = launchPlatform.GetComponent <AnimationLauncher>(); Debug.Log(string.Format("Animation launcher is on: {0}", al.gameObject.name)); if (al != null) { UnitClass uc = GameManager.Instance.GetUnitClass(aircraft.Info.UnitClassId); Debug.Log(string.Format("Unitclass found: {0}. ", uc.UnitClassShortName)); al.TakeOffMode = uc.UnitType == GameConstants.UnitType.Helicopter ? AnimationLauncher.AnimMode.HelicopterLanding : AnimationLauncher.AnimMode.FixedWingLanding; Debug.Log(string.Format("Changed takeoffmode to: {0}. Attempting launch...", al.TakeOffMode.ToString())); al.LaunchAnimation(); Debug.Log(string.Format("Animation launched...")); } else { Debug.Log("AnimationLauncher is null"); } } else { Debug.Log("Launchplatform is null"); } //if (carrier != null) //{ // GameManager.Instance.UnitManager.SelectedUnit = carrier; //} //~ ShowMessage("GameStateInfo object, AircraftIsLanded"); break; } case CommsMarshaller.GameStateInfoType.AircraftTakeoff: { PlayerUnit launchPlatform = GameManager.Instance.UnitManager.FindUnitById(gameInfo.SecondaryId); //gameInfo. if (launchPlatform != null) { AnimationLauncher al = launchPlatform.GetComponent <AnimationLauncher>(); if (al != null) { UnitClass uc = GameManager.Instance.GetUnitClass(gameInfo.UnitClassId); al.TakeOffMode = uc.UnitType == GameConstants.UnitType.Helicopter ? AnimationLauncher.AnimMode.HelicopterTakeOff : AnimationLauncher.AnimMode.FixedWingTakeOff; al.LaunchAnimation(); } } break; } case CommsMarshaller.GameStateInfoType.MissileLaunch: PlayerUnit shooter = GameManager.Instance.UnitManager.FindUnitById(gameInfo.SecondaryId); if (shooter != null) { shooter.FireMissile(); } else { Debug.Log(gameInfo.SecondaryId + " is not a unit here"); } break; } } }
private void Send(TcpClient client, IMarshallable message) { byte[] msg = _commsMarshaller.SerializeObjectForSending(message); Send(client, msg); }
private void HandleGroupInfo(IMarshallable dataReceived) { GroupInfo gi = dataReceived as GroupInfo; GameManager.Instance.UnitManager.AddGroupInfo(gi); }
private void HandlePlayerInfo(IMarshallable dataReceived) { GameManager.Instance.PlayerInfo = dataReceived as PlayerInfo; }
private void HandleGameInfo(IMarshallable dataReceived) { Debug.Log(dataReceived.ToString()); GameManager.Instance.GameInfo = dataReceived as GameInfo; }
public void PollNetwork() { if (_listener == null) { return; } if (IsOpenForNewConnecions && _listener.Pending()) { TcpClient newClient = _listener.AcceptTcpClient(); var clientMar = new ClientMarshaller(_clientIndex, newClient, new CommsMarshaller()); _clients.Add(clientMar); ConnectionStatus = GameConstants.ConnectionStatusEnum.Connected; ClientAdded(_clientIndex); var msg = new MessageString { Message = "Server: You are client number " + _clientIndex }; Send(newClient, msg); _clientIndex++; _logger.LogDebug("PollNetwork: New client " + _clientIndex + " added."); } if (ConnectionStatus == GameConstants.ConnectionStatusEnum.Connected) { try { foreach (var clientMarshaller in _clients) { TcpClient client = clientMarshaller.Client; int clientId = clientMarshaller.ClientId; try { NetworkStream stream = client.GetStream(); if (stream.DataAvailable) { do { int i = stream.Read(_readBuffer, 0, _readBuffer.Length); clientMarshaller.Marshaller.AddToReceiveBufferEnd(_readBuffer, i); while (clientMarshaller.Marshaller.IsObjectInReceiveBuffer()) { IMarshallable obj = clientMarshaller.Marshaller.DeSerializeNextObjectInReceiveBuffer(); _logger.LogDebug("PollNetwork: Object read from receive buffer: " + obj.ObjectTypeToken); DataReceived(clientId, obj); } } while (stream.DataAvailable); } } catch (Exception ex) { if (ex.InnerException == null) { _logger.LogError("Error in GameServer.PollNetwork: " + ex.ToString() + " \nStackTrace: " + ex.StackTrace); } else { _logger.LogError("Error in GameServer.PollNetwork: " + ex.ToString() + "\nInnerException: " + ex.InnerException.ToString() + "\nStackTrace: " + ex.StackTrace); } } } } catch (Exception ex) { if (ex.InnerException == null) { _logger.LogError("Error in GameServer.PollNetwork: " + ex.ToString() + " \nStackTrace: " + ex.StackTrace); } else { _logger.LogError("Error in GameServer.PollNetwork: " + ex.ToString() + "\nInnerException: " + ex.InnerException.ToString() + "\nStackTrace: " + ex.StackTrace); } } } }
private void HandleBaseUnitInfo(IMarshallable dataReceived) { //~ GameManager.Instance.MessageManager.AddMessage(dataReceived.ToString()); BaseUnitInfo info = dataReceived as BaseUnitInfo; if (info != null) { PlayerUnit unit = GameManager.Instance.UnitManager.FindUnitById(info.Id); if (info.IsMarkedForDeletion) { //~ ShowMessage(string.Format("Unit [{0}] {1} has been DESTROYED.", info.Id, info.UnitName)); ////////////REMOVE OBJECT/////////////////////// Debug.Log(info + " is marked for deletion"); if (unit.Info.UnitType == GameConstants.UnitType.Missile) { //Instantiate explosives unit.MyMapUnit.Explode(); } Destroy(unit.gameObject); return; } //~ ShowMessage(info.UnitName + " " + info.IsMarkedForDeletion.ToString()); GameObject go = null; if (unit != null) { unit.Info = info; return; } if (go == null) //Make new one and add to _GameUnits list { //Debug.Log(info.UnitClassId); UnitClass vesselUnitClass = GameManager.Instance.GetUnitClass(info.UnitClassId); if (vesselUnitClass == null) { Debug.Log("Unitclass is NuLLL!!!!"); } go = GetVesselByUnitClassId(vesselUnitClass.UnitModelFileName, info.Position); unit = go.AddComponent <PlayerUnit>(); unit.Size = new Vector2(32, 32); //unit.OptionalAngleTest = optionalAngle; unit.PrefabMapUnit = MapUnit; go.transform.parent = GameObject.Find("SurfaceUnits").transform; if (info.DomainType != GameConstants.DomainType.Land && info.DomainType != GameConstants.DomainType.Air) { go.transform.localScale = GameManager.Instance.GlobalScale; } go.name = info.UnitName; if (info.DomainType != GameConstants.DomainType.Air) { GameObject healthBar = Instantiate(HealthBar, Vector3.zero, Quaternion.identity) as GameObject; healthBar.transform.parent = go.transform; healthBar.transform.localPosition = Vector3.up * 10; } //~ if(map != null) //~ { //~ map.UnitInfo = unit; //~ } //~ GameObject clone = Instantiate(ABurke, GameManager.Instance.GetVectorByLatLng((float)info.Position.Latitude, (float)info.Position.Longitude), Quaternion.identity) as GameObject; //~ Debug.Log(string.Format("Adding unit {0} to list", unit.Info.Id)); } //Debug.Log(info.Id + " created"); unit.Info = info; //~ MapUnit mu = AddMapUnit(unit, GameManager.Instance.GetTextureByUnitClassId(unit.Info.UnitClassId)); //~ unit.MapUnit = mu; GameManager.Instance.UnitManager.AddUnit(unit); if (go.audio != null) { GameManager.Instance.AudioManager.AddSound(go.audio); } if (GameManager.Instance.UnitManager.SelectedUnit == null) { GameManager.Instance.UnitManager.SelectedUnit = unit; } } }
public ObjectTokens GetTypeTokenFromObject(IMarshallable obj) { return(obj.ObjectTypeToken); }
public byte[] SerializeObjectToBytes(IMarshallable obj) { ObjectTokens Token = GetTypeTokenFromObject(obj); switch (Token) { case ObjectTokens.NoObject: throw new InvalidOperationException("SerializeObject called with NoObject."); case ObjectTokens.Enq: return(new CommsSerializationHelper <EnqObject>().SerializeToBytes((EnqObject)obj)); case ObjectTokens.Ack: return(new CommsSerializationHelper <AckObject>().SerializeToBytes((AckObject)obj)); case ObjectTokens.MessageString: return(new CommsSerializationHelper <MessageString>().SerializeToBytes((MessageString)obj)); case ObjectTokens.PositionInfo: return(new CommsSerializationHelper <PositionInfo>().SerializeToBytes((PositionInfo)obj)); case ObjectTokens.BaseUnitInfo: return(new CommsSerializationHelper <BaseUnitInfo>().SerializeToBytes((BaseUnitInfo)obj)); case ObjectTokens.GroupInfo: return(new CommsSerializationHelper <GroupInfo>().SerializeToBytes((GroupInfo)obj)); case ObjectTokens.DetectedGroupInfo: return(new CommsSerializationHelper <DetectedGroupInfo>().SerializeToBytes((DetectedGroupInfo)obj)); case ObjectTokens.DetectedUnitInfo: return(new CommsSerializationHelper <DetectedUnitInfo>().SerializeToBytes((DetectedUnitInfo)obj)); case ObjectTokens.DetecedUnitSensorInfo: return(new CommsSerializationHelper <DetecedUnitSensorInfo>().SerializeToBytes((DetecedUnitSensorInfo)obj)); case ObjectTokens.GameInfo: return(new CommsSerializationHelper <GameInfo>().SerializeToBytes((GameInfo)obj)); case ObjectTokens.GameStateInfo: return(new CommsSerializationHelper <GameStateInfo>().SerializeToBytes((GameStateInfo)obj)); case ObjectTokens.BattleDamageReport: return(new CommsSerializationHelper <BattleDamageReport>().SerializeToBytes((BattleDamageReport)obj)); case ObjectTokens.Formation: return(new CommsSerializationHelper <Formation>().SerializeToBytes((Formation)obj)); case ObjectTokens.FormationPosition: return(new CommsSerializationHelper <FormationPosition>().SerializeToBytes((FormationPosition)obj)); case ObjectTokens.MessageInfo: return(new CommsSerializationHelper <MessageInfo>().SerializeToBytes((MessageInfo)obj)); //case ObjectTokens.OrderInfo: // break; case ObjectTokens.UnitOrder: return(new CommsSerializationHelper <UnitOrder>().SerializeToBytes((UnitOrder)obj)); case ObjectTokens.UnitEngagementOrder: return(new CommsSerializationHelper <UnitEngagementOrder>().SerializeToBytes((UnitEngagementOrder)obj)); case ObjectTokens.UnitMovementOrder: return(new CommsSerializationHelper <UnitMovementOrder>().SerializeToBytes((UnitMovementOrder)obj)); case ObjectTokens.PlayerInfo: return(new CommsSerializationHelper <PlayerInfo>().SerializeToBytes((PlayerInfo)obj)); case ObjectTokens.SensorClass: return(new CommsSerializationHelper <SensorClass>().SerializeToBytes((SensorClass)obj)); case ObjectTokens.UnitClass: return(new CommsSerializationHelper <UnitClass>().SerializeToBytes((UnitClass)obj)); case ObjectTokens.WeaponClass: return(new CommsSerializationHelper <WeaponClass>().SerializeToBytes((WeaponClass)obj)); case ObjectTokens.ClientInfoRequest: return(new CommsSerializationHelper <ClientInfoRequest>().SerializeToBytes((ClientInfoRequest)obj)); case ObjectTokens.GameControlRequest: return(new CommsSerializationHelper <GameControlRequest>().SerializeToBytes((GameControlRequest)obj)); case ObjectTokens.GameScenario: return(new CommsSerializationHelper <GameScenario>().SerializeToBytes((GameScenario)obj)); case ObjectTokens.GameScenarioCarriedUnit: return(new CommsSerializationHelper <GameScenarioCarriedUnit>().SerializeToBytes((GameScenarioCarriedUnit)obj)); case ObjectTokens.WeatherSystemInfo: return(new CommsSerializationHelper <WeatherSystemInfo>().SerializeToBytes((WeatherSystemInfo)obj)); case ObjectTokens.NWDateTime: return(new CommsSerializationHelper <NWDateTime>().SerializeToBytes((NWDateTime)obj)); case ObjectTokens.WaypointInfo: return(new CommsSerializationHelper <WaypointInfo>().SerializeToBytes((WaypointInfo)obj)); case ObjectTokens.HighLevelOrder: return(new CommsSerializationHelper <HighLevelOrder>().SerializeToBytes((HighLevelOrder)obj)); case ObjectTokens.GameUiControl: return(new CommsSerializationHelper <GameUiControl>().SerializeToBytes((GameUiControl)obj)); case ObjectTokens.EventTrigger: return(new CommsSerializationHelper <EventTrigger>().SerializeToBytes((EventTrigger)obj)); case ObjectTokens.RegionInfo: return(new CommsSerializationHelper <RegionInfo>().SerializeToBytes((RegionInfo)obj)); case ObjectTokens.Campaign: return(new CommsSerializationHelper <Campaign>().SerializeToBytes((Campaign)obj)); case ObjectTokens.User: return(new CommsSerializationHelper <User>().SerializeToBytes((User)obj)); case ObjectTokens.AiHintInfo: return(new CommsSerializationHelper <AIHintInfo>().SerializeToBytes((AIHintInfo)obj)); case ObjectTokens.PlayerObjective: return(new CommsSerializationHelper <PlayerObjective>().SerializeToBytes((PlayerObjective)obj)); case ObjectTokens.SteamClientInitiateConnection: return(new CommsSerializationHelper <SteamClientInitiateConnection>().SerializeToBytes(( SteamClientInitiateConnection )obj)); case ObjectTokens.SteamGameServerInfo: return(new CommsSerializationHelper <SteamGameServerInfo>().SerializeToBytes(( SteamGameServerInfo )obj)); case ObjectTokens.SteamClientBeginAuthentication: return(new CommsSerializationHelper <SteamClientBeginAuthentication>().SerializeToBytes(( SteamClientBeginAuthentication )obj)); case ObjectTokens.SteamServerPassAuthentication: return(new CommsSerializationHelper <SteamServerPassAuthentication>().SerializeToBytes(( SteamServerPassAuthentication )obj)); case ObjectTokens.ClientLeavingServer: return(new CommsSerializationHelper <ClientLeavingServer>().SerializeToBytes(( ClientLeavingServer )obj)); case ObjectTokens.ServerExiting: return(new CommsSerializationHelper <ServerExiting>().SerializeToBytes(( ServerExiting )obj)); default: throw new InvalidOperationException("SerializeObject called with unknown object. " + obj.ObjectTypeToken); } }
public void HandleReceivedData(IMarshallable dataReceived) { //Debug.Log(dataReceived); switch (dataReceived.ObjectTypeToken) { case CommsMarshaller.ObjectTokens.NoObject: break; case CommsMarshaller.ObjectTokens.Enq: break; case CommsMarshaller.ObjectTokens.Ack: break; case CommsMarshaller.ObjectTokens.ClientInfoRequest: break; case CommsMarshaller.ObjectTokens.GameControlRequest: break; case CommsMarshaller.ObjectTokens.GameStateInfo: HandleGameStateInfo(dataReceived); break; case CommsMarshaller.ObjectTokens.GameUiControl: HandleGameUIControlInfo(dataReceived); break; case CommsMarshaller.ObjectTokens.MessageInfo: HandleMessageInfo(dataReceived); break; case CommsMarshaller.ObjectTokens.DefeatConditionSetInfo: break; case CommsMarshaller.ObjectTokens.DefeatConditionInfo: break; case CommsMarshaller.ObjectTokens.MessageString: MessageString str = dataReceived as MessageString; if (str != null) { //~ ShowMessage("MessageString: " + str.Message); } GameManager.Instance.MessageManager.AddMessage(str.Message, GameManager.MessageTypes.Game, null); break; case CommsMarshaller.ObjectTokens.BattleDamageReport: BattleDamageReport report = dataReceived as BattleDamageReport; PlayerInfo playerInfo = GameManager.Instance.PlayerInfo; if (report != null) { if (playerInfo != null) { //GameManager.Instance.MessageManager.AddMessage(string.Format("MessageToAttacker: {0} - MessageToAttackee: {1}", // string.IsNullOrEmpty(report.MessageToAttacker) ? report.ToString() : report.MessageToAttacker, // string.IsNullOrEmpty(report.MessageToAttackee) ? report.ToString() : report.MessageToAttackee), // GameManager.MessageTypes.Battle, report.Position); GameManager.Instance.MessageManager.AddMessage(report.PlayerInflictingDamageId == playerInfo.Id ? report.MessageToAttacker : report.MessageToAttackee, GameManager.MessageTypes.Battle, report.Position); if (report.DamagePercent > 0) { ////Check if it is we who have been hit if (report.PlayerSustainingDamageId == playerInfo.Id) { //Find unit which has been hit PlayerUnit unit = GameManager.Instance.UnitManager.FindUnitById(report.TargetPlatformId); if (unit != null) { //Spawn explosion unit.SpawnExplosion(); } } else { //TODO:Jan du må huske TargetPlatformId Enemy enemyUnit = GameManager.Instance.UnitManager.FindEnemyById(report.TargetPlatformId); if (enemyUnit != null) { enemyUnit.SpawnExplosion(); } else { Debug.Log("enemy is null"); } } } float distanceLat = Mathf.Abs((float)report.Position.Latitude - GameManager.Instance.Origin.Latitude); //float distanceLng = Mathf.Abs((float)report.Position.Longitude - GameManager.Instance.Origin.Longitude); //if (distanceLat < 1 && distanceLng < 1) //{ // //calculate distance and bearing // //Coordinate origin = new Coordinate((float)this.Info.Position.Latitude, (float)this.Info.Position.Longitude); // Coordinate position = new Coordinate((float)report.Position.Latitude, (float)report.Position.Longitude); // Coordinate coord = CoordinateHelper.CalculateCoordinateFromBearingAndDistance(GameManager.Instance.Origin, position); // Vector3 worldPos = new Vector3(coord.Longitude, (float)report.Position.HeightOverSeaLevelM, coord.Latitude); // //Debug.Log(worldPos); // worldPos.y = transform.position.y; // //transform.position = Vector3.Lerp(transform.position, worldPos, Time.deltaTime); //} } } break; case CommsMarshaller.ObjectTokens.GameInfo: HandleGameInfo(dataReceived); break; case CommsMarshaller.ObjectTokens.PlayerInfo: HandlePlayerInfo(dataReceived); break; case CommsMarshaller.ObjectTokens.PositionInfo: HandlePositionInfo(dataReceived); break; case CommsMarshaller.ObjectTokens.BaseUnitInfo: HandleBaseUnitInfo(dataReceived); break; case CommsMarshaller.ObjectTokens.GroupInfo: HandleGroupInfo(dataReceived); break; case CommsMarshaller.ObjectTokens.DetectedUnitInfo: HandleDetectedUnitInfo(dataReceived); break; case CommsMarshaller.ObjectTokens.OrderInfo: break; case CommsMarshaller.ObjectTokens.UnitMovementOrder: break; case CommsMarshaller.ObjectTokens.UnitEngagementOrder: break; case CommsMarshaller.ObjectTokens.UnitClass: Debug.Log("Received new unitclass"); HandleUnitClass(dataReceived); break; case CommsMarshaller.ObjectTokens.WeaponClass: break; case CommsMarshaller.ObjectTokens.SensorClass: break; case CommsMarshaller.ObjectTokens.GameScenario: break; case CommsMarshaller.ObjectTokens.GameScenarioAlliance: break; case CommsMarshaller.ObjectTokens.GameScenarioPlayer: break; case CommsMarshaller.ObjectTokens.GameScenarioGroup: break; case CommsMarshaller.ObjectTokens.GameScenarioUnit: break; default: //~ ShowMessage("WTF?"); break; } }
public void Send(IMarshallable obj) { byte[] bytes = _CommsMarshaller.SerializeObjectForSending(obj); //_CommsMarshaller.AddToBufferEnd(bytes, bytes.Length); Send(bytes); }