private NetworkEntity ReadEntity(ISerializationContext context, IValueReader reader) { var entity = new NetworkEntity (reader.ReadString (), EntityType.Client); entity.NetworkID = reader.ReadUInt16 (); UInt16 fieldCount = reader.ReadUInt16 (); for (int f = 0; f < fieldCount; f++) { string name = reader.ReadString (); ushort typeID = reader.ReadUInt16 (); Type type; context.TypeMap.TryGetType (typeID, out type); object value; if (type == typeof (Vector2)) value = reader.Read (context, Vector2Serializer.Instance); else if (type == typeof (Vector3)) value = reader.Read (context, Vector3Serializer.Instance); else value = reader.Read (context, type); entity.Fields.Add (name, new PropertyGroup (value, type)); } return entity; }
public static void CopyFrom(this NetworkEntity self, NetworkEntity networkEntity) { var deepCopy = networkEntity.DeepCopy (); foreach (var kvp in deepCopy.Fields) self.Fields[kvp.Key] = kvp.Value; }
private void SyncEntity(NetworkEntity entity) { var localEntity = entityMap [entity.NetworkID]; foreach (var kvp in entity.Fields) localEntity.Fields[kvp.Key] = kvp.Value; }
public void Register(NetworkEntity networkEntity) { if (networkEntity.EntityType != EntityType.Client) throw new ArgumentException ("You can only register client entities."); entities.Add (networkEntity); entityMap.Add (networkEntity.NetworkID, networkEntity); }
public void RegisterEntity(NetworkEntity entity) { lock (entityLock) { entity.NetworkID = ++lastEntityID; entities.Add (entity.NetworkID, entity); } }
public override NetworkEntity Lerp(NetworkEntity source, NetworkEntity one, NetworkEntity two, float lerp) { return new CPlayer { Name = Name, Position = Vector2.Lerp (((CPlayer)one).Position, ((CPlayer)two).Position, lerp) }; }
public NetworkEntity GetMerged(NetworkEntity source, DateTime time) { uint networkID = source.NetworkID; // Extrapolation is disabled so just use the latest version if (Newer == null || Older == null) return source; double renderTime = (time - Older.Taken).TotalSeconds; double timeRange = (Newer.Taken - Older.Taken).TotalSeconds; NetworkEntity one = Older.GetEntity (networkID).Entity; NetworkEntity two = Newer.GetEntity (networkID).Entity; // If the last snapshot doesn't have the character return the most recent one if (one == null) return source; return LerpEntity (source, one, two, (float)(renderTime / timeRange)); }
private void CreateEntity(NetworkEntity entity) { if (!entityTypeInformation.ContainsKey (entity.EntityName)) throw new Exception ("Entity has not been registered with the network system"); EntityInformation info = entityTypeInformation[entity.EntityName]; var newEntity = (NetworkEntity)info.Create (); newEntity.NetworkID = entity.NetworkID; lock (entityLock) entities.Add (newEntity.NetworkID, newEntity); SyncEntity (entity); OnEntityCreated (newEntity); }
public abstract void SyncStart(NetworkEntity networkEntity);
protected virtual void OnEntityCreated(NetworkEntity entity) { }
private bool FindLobbyById(string lobbyId, out Lobby lobby) => NetworkEntity.FindEntityById(_lobbies, lobbyId, out lobby);
public void TakeItem(NetworkEntity item) { Debug.Log(string.Format("Player {0} take item {1}", this.Entity.EntityId, item.EntityId)); m_myController.TakeItem(item); }
public static NetworkWaitingGuiFactory With(NetworkEntity networkEntity) { return new NetworkWaitingGuiFactory() { networkEntity = (NetworkEntityWaiting) networkEntity }; }
/// <summary> /// Used to process an incoming stream. /// </summary> /// <param name="rawData"></param> /// <param name="rawDataOffset"></param> /// <param name="fixedLength"></param> /// <param name="packetOwner"></param> public void ProcessPacket(byte[] rawData, uint rawDataOffset, uint fixedLength, NetworkEntity packetOwner) { Message incomingMessage = null; incomingMessage = this.priorityMessagesPool.BorrowMessage; ((BufferedMessage)incomingMessage).Load(rawData, rawDataOffset, fixedLength); ((BufferedMessage)incomingMessage).SetOwnerMessageNetworkEntity(packetOwner); if (!this.localCommandsQueue.EnqueueCommandMessage(ref incomingMessage)) { this.priorityMessagesPool.Recycle(incomingMessage); } }
void Start() { networkEntity = GetComponent <NetworkEntity>(); currentPlayerTargeter = currentPlayer.GetComponent <Targeter> (); }
public void Deserialize(DeserializeEvent e) { NetworkEntity = e.Reader.ReadSerializable <NetworkEntity>(); HasAuthority = e.Reader.ReadBoolean(); }
public NetworkModel(NetworkEntity entity) { NetworkId = entity.NETWORKID; NetworkName = entity.NETWORK_NAME; }
private void Awake() { entity = GetComponent <NetworkEntity>(); entity.OnRegisterCallback += Init; }
/// <summary> /// Test the given NetworkEntity and applies the filter on it. /// </summary> /// <param name="entityToBeTested">Reference to a NetworkEntity to be tested.</param> /// <returns>True if the NetworkEntity maches, false otherwise.</returns> public abstract bool Match(FilterMode filteringMode, ref NetworkEntity entityToBeTested);
public NetworkEntityPacket(NetworkEntity networkEntity) { this.networkEntity = networkEntity; }
public bool FindPlayerById(string id, out PlayerData player) => NetworkEntity.FindEntityById(Players, id, out player);
private bool FindCardById(IEnumerable <CommonCard> cardsStack, string cardId, out CommonCard foundCard) => NetworkEntity.FindEntityById(cardsStack, cardId, out foundCard);
/// <summary> /// Handles the main behaviour of the server side client. /// </summary> protected void HandleConnectionProcess() { Message tempMessage = null; NetworkEntity myNetworkEntityReference = this; bool thisThreadAlive = true; if (!this.ableToRun) { KSPMGlobals.Globals.Log.WriteTo(Error.ErrorType.ServerClientUnableToRun.ToString()); return; } KSPMGlobals.Globals.Log.WriteTo(string.Format("[{0}]Going alive {1}", this.id, this.ownerNetworkCollection.socketReference.RemoteEndPoint.ToString())); while (thisThreadAlive) { switch (this.currentStatus) { ///This is the starting status of each ServerSideClient. case ClientStatus.Handshaking: Message.HandshakeAccetpMessage(myNetworkEntityReference, out tempMessage); PacketHandler.EncodeRawPacket(ref tempMessage.bodyMessage); KSPMGlobals.Globals.KSPMServer.priorityOutgoingMessagesQueue.EnqueueCommandMessage(ref tempMessage); this.currentStatus = ClientStatus.Awaiting; //Awaiting for the Authentication message coming from the remote client. break; case ClientStatus.Awaiting: break; case ClientStatus.Authenticated: this.currentStatus = ClientStatus.UDPSettingUp; Message.UDPSettingUpMessage(myNetworkEntityReference, out tempMessage); PacketHandler.EncodeRawPacket(ref tempMessage.bodyMessage); KSPMGlobals.Globals.KSPMServer.priorityOutgoingMessagesQueue.EnqueueCommandMessage(ref tempMessage); KSPMGlobals.Globals.Log.WriteTo(string.Format("[{0}]{1} Pairing code", this.Id, System.Convert.ToString(this.pairingCode, 2))); this.usingUdpConnection = true; this.ReceiveUDPDatagram(); break; case ClientStatus.Connected: KSPMGlobals.Globals.KSPMServer.chatManager.RegisterUser(this, Chat.Managers.ChatManager.UserRegisteringMode.Public); KSPMGlobals.Globals.Log.WriteTo(string.Format("[{0}]{1} has connected", this.Id, this.gameUser.Username)); Message.SettingUpChatSystem(this, KSPMGlobals.Globals.KSPMServer.chatManager.AvailableGroupList, out tempMessage); PacketHandler.EncodeRawPacket(ref tempMessage.bodyMessage); KSPMGlobals.Globals.KSPMServer.priorityOutgoingMessagesQueue.EnqueueCommandMessage(ref tempMessage); KSPMGlobals.Globals.Log.WriteTo(string.Format("[{0}] Setting up KSPM Chat system.", this.Id)); this.connected = true; this.currentStatus = ClientStatus.Awaiting; thisThreadAlive = false; break; } if (!this.connected && this.timer.ElapsedMilliseconds > ServerSettings.ConnectionProcessTimeOut && !this.markedToDie) { this.markedToDie = true; KSPMGlobals.Globals.Log.WriteTo(string.Format("[{0}] Connection process has taken too long: {1}.", this.id, this.timer.ElapsedMilliseconds)); KSPMGlobals.Globals.KSPMServer.DisconnectClient(this); thisThreadAlive = false; } Thread.Sleep(3); } }
public bool FindUserById(string userId, out UserData user) => NetworkEntity.FindEntityById(ConnectedUsers, userId, out user);
public void RegisterEntity(NetworkEntity entity) { }
protected abstract TCommand CreateTransferCommandForEntity(Entity entity, NetworkEntity networkEntity, TSelector selectorComponent);
public bool QueueEntityMessage(ulong sendTo, string msgCode, NetworkEntity entity, params object[] args) { return(QueueEntityMessage(sendTo, GetMessageCode(msgCode), entity, args)); }
/// <summary> /// Method which removes a client, and is used to set the callback inside the networkentity. /// </summary> /// <param name="caller"></param> /// <param name="arg"></param> protected void RejectMessageToClient(NetworkEntity caller, object arg) { this.clientsHandler.RemoveClient(caller); }
public NetworkEntity AddOrSetComponent(Entity entity, GameObject optionalGameObject, NetworkEntity data = default(NetworkEntity)) { data = AddOrSetComponent(entity, data); var wrapper = optionalGameObject.GetComponent <NetworkEntityWrapper>() ?? optionalGameObject.AddComponent <NetworkEntityWrapper>(); wrapper.Value = data; return(data); }
public void AddEntity(NetworkEntity entity) { SyncEntities.Added.Add(entity); }
public virtual void OnEntityCreated(NetworkEntity entity) { }
private void OnEnable() { m_networkEntity = target as NetworkEntity; }
protected abstract TCommand CreateTransferCommandForEntity(Entity entity, ref NetworkEntity networkEntity, ref TSelector selectorComponent, ref TSelector2 selectorComponent2);
public abstract void SyncUpdate(NetworkEntity networkEntity);
public override void OnEntityCreated(NetworkEntity entity) { game.OnPlayerCreated ((CPlayer)entity); }
protected virtual void OnEntityDestroyed(NetworkEntity entity) { }
private NetworkEntity LerpEntity(NetworkEntity source, NetworkEntity one, NetworkEntity two, float lerp) { return source.Lerp(source, one, two, lerp); }
public void Update(bool onlyDrawGUI) { if (onlyDrawGUI && character != null) { CharGUI.Render(_node, _win, character as CharacterEntity, _charView); return; } if (!_connected.IsCompleted) { _node.Tick().Wait(); return; } else if (!_connected.Result) { _node.Tick().Wait(); return; } if (!joined) { var session = _node.AllGhosts().SingleOrDefault(x => x is SessionEntity); if (session != null) { ((SessionEntity)session).Join("Name" + (new System.Random()).Next().ToString()); joined = true; } } if (_win != null) { _win.DispatchEvents(); _win.Clear(Color.Blue); } var deltaTime = GetDeltaTime(); foreach (var ghost in _node.AllGhosts()) { if (ghost is ICharacterLikeMovement charLikeMovement) { if (charLikeMovement.PhysicsBody == null) { var pos = ((IPositionedEntity)ghost).Position; lock (_physicsWorld) { var body = _physicsWorld.CreateDynamicBody(new Vector2(pos.X, pos.Y), 1, _physicsWorld.CreateCircleWorldSpace(new Vector2(pos.X, pos.Y), 1f, 1)); body.UserData = ghost.Id; charLikeMovement.PhysicsBody = body; } } else { var pos = ((IPositionedEntity)ghost).Position; var _debugPhysicsShape = new RectShapeHandle(); var aabb = charLikeMovement.PhysicsBody.AABB; HierarchyTransform v = new HierarchyTransform(Vec2.New(aabb.Center.x, aabb.Center.y), 0, null); _debugPhysicsShape.FillColor = Color.Transparent; _debugPhysicsShape.OutlineColor = Color.Red; _debugPhysicsShape.OutlineThickness = 1; _debugPhysicsShape.Size = new SFML.System.Vector2f(aabb.Extent.x * 2, aabb.Extent.y * 2); v.DrawShapeAt(_debugPhysicsShape, Vec2.New(0.5f, 0.5f)); } if (ghost.HasAuthority) { character = ghost; if (_win != null ? _win.HasFocus() : true) { charLikeMovement.UpdateControls(); } charLikeMovement.UpdateMovement(); _charView.Center = new Vector2f(charLikeMovement.SmoothPosition.X, charLikeMovement.SmoothPosition.Y); if (_win != null) { _charView.Size = new Vector2f(256, -256 * ((float)_win.Size.Y / (float)_win.Size.X)); _win.SetView(_charView); } } else { charLikeMovement.InterpolationUpdate(deltaTime); } } } DrawSite(SimpleServer._debugCreator._rootInstance); foreach (var ghost in _node.AllGhosts()) { if (ghost is IRenderable rnd) { rnd.Render(_win); } } CharGUI.Render(_node, _win, character as CharacterEntity, _charView); var tick = _node.Tick(); lock (_physicsWorld) { _physicsWorld.DeltaTime = EnvironmentAPI.Time.DeltaTime; _physicsWorld.Update(); } lock (_physicsWorld) { foreach (var body in _physicsWorld.Bodies) { var aabb = body.AABB; var _shape = new RectShapeHandle(); HierarchyTransform v = new HierarchyTransform(Vec2.New(aabb.Center.x, aabb.Center.y), body.Angle / Mathf.PI * 180, null); _shape.FillColor = Color.Transparent; _shape.OutlineColor = Color.Red; _shape.OutlineThickness = 1; _shape.Size = new SFML.System.Vector2f(aabb.Extent.x * 2, aabb.Extent.y * 2); foreach (var shape in body.shapes) { if (shape is VoltPolygon vp) { HierarchyTransform vpt = new HierarchyTransform(Vec2.New(vp.bodySpaceAABB.Center.x, vp.bodySpaceAABB.Center.y), 0, v); _shape.FillColor = Color.Transparent; _shape.OutlineColor = Color.Yellow; _shape.OutlineThickness = 1; _shape.Size = new SFML.System.Vector2f(vp.bodySpaceAABB.Extent.x * 2, vp.bodySpaceAABB.Extent.y * 2); vpt.DrawShapeAt(_shape, Vec2.New(0.5f, 0.5f)); } } } } if (_win != null) { _win.Display(); } tick.Wait(); }
public static void Unregister(NetworkEntity netEnt) { entities.Remove(netEnt.networkable.ID); }
void Start() { _CharacterAnim = GetComponent <Animator>(); _CharacterRigidbody = GetComponent <Rigidbody>(); _netWorkEntity = GetComponent <NetworkEntity>(); }
protected override ServerPlayerBuilderPacket CreateTransferCommandForEntity(Entity entity, NetworkEntity networkEntity, ref ServerPlayer serverPlayer, ref Player player) { return(new ServerPlayerBuilderPacket { networkConnectionId = serverPlayer.networkConnectionId, networkEntityId = networkEntity.networkEntityId, playerId = player.playerId }); }
public NetworkWrapper(NetworkEntity entity) { Guid = entity.Guid; GameObjects = entity.GetComponents(typeof(NetworkedComponent)); }
private void initNetwork() { NetworkView networkView = GetComponent<NetworkView>(); network = NetworkEntityFactory.With(networkView).Get(NetworkRole); network.Start(); }
public void RegisterEntity(NetworkEntity entity) { entity.Id = _entities.Count; _entities.Add(entity); }
public void AddNetworkEntity(NetworkEntity networkEntity) { lock (networkEntityLock) networkEntities.Add(networkEntity); }
private void WriteEntity(NetworkEntity entity, ISerializationContext context, IValueWriter writer) { writer.WriteString (entity.EntityName); writer.WriteUInt16 ((UInt16)entity.NetworkID); writer.WriteUInt16 ((UInt16)entity.Fields.Count); foreach (var kvp in entity.Fields) { object fieldValue = kvp.Value.Value; writer.WriteString (kvp.Key); // Write the field type ushort typeID; context.TypeMap.GetTypeId (fieldValue.GetType (), out typeID); writer.WriteUInt16 (typeID); if (fieldValue is Vector2) writer.Write (context, (Vector2)fieldValue, Vector2Serializer.Instance); else if (fieldValue is Vector3) writer.Write (context, (Vector3)fieldValue, Vector3Serializer.Instance); else writer.Write (context, fieldValue, kvp.Value.Type); } }
void Start() { _networkEntity = GetComponent <NetworkEntity>(); _myPlayerTargeter = myPlayer.GetComponent <Targeter>(); }