RpcTarget WriteSync(NetStream syncStream) { syncStream.WriteVector3(transform.position); syncStream.WriteFloat(transform.rotation.eulerAngles.y); syncStream.WriteVector2(new Vector2(velocity.x, velocity.z)); return RpcTarget.NonControllers; }
void Instantiate(NetStream stream) { if (stream.ReadBool()) Die(); if (!gameObject.activeSelf) gameObject.SetActive(true); float posX = stream.ReadFloat(); float posZ = stream.ReadFloat(); transform.position = new Vector3(posX, 0, posZ); }
RpcTarget WriteSync(NetStream syncStream) { Vector3 velocity = transform.position - lastPos; syncStream.WriteVector3(transform.position); syncStream.WriteQuaternion(transform.rotation); syncStream.WriteVector2(new Vector2(velocity.x, velocity.z)); lastPos = transform.position; return RpcTarget.Server; }
internal void TriggerReadInstantiateData(NetStream stream) { if (OnReadInstantiateData != null) { OnReadInstantiateData(stream); } stream.Release(); }
internal void TriggerReadSync(NetStream stream) { if (OnReadSync != null) { OnReadSync(stream); } stream.Release(); }
public ulong Add(NetStream streamValue) { NetStream stream = streamValue.Copy(); ulong key = RandomUlong(); ulongKeys.Add(key); stringKeys.Add(EmptyString); streams.Add(stream); return key; }
internal static bool TryWriteParam(NetStream stream, object param) { try { WriteParam(stream, param); return(true); } catch { return(false); } }
void Instantiate(NetStream stream) { PlayerName = stream.ReadString(); Hp = stream.ReadInt(); Vector3 pos = stream.ReadVector3(); inventory.SetAllFromStream(stream); // Prevemt jumpiness during handoff by ignoring position data if similar enough: if (transform.position != Vector3.zero && Vector3.Distance(transform.position, pos) < 5) return; transform.position = pos; }
public static object ItemDeserializer(NetStream stream) { uint dbId = stream.ReadUInt(); int quantity = stream.ReadInt(); IInvItem item; if (!Inventory.TryCloneFromDb(dbId, quantity, stream, out item)) { Debug.LogError("Failed to deserialize IInvItem. Item with given ID not found in database: " + dbId); } return item; }
public bool TryGetCreatorData(out NetStream creatorData) { if (!HasCreatorData()) { creatorData = null; return(false); } creatorData = TriggerGetCreatorData(); return(true); }
private void InitializeStream() { sendStream = NetStream.Create(); AdvanceLocalSequence(); var header = WriteHeader(); reliableWindow.Add(header.ObjSequence, sendStream); sendWindow.Add(header.ObjSequence); sendWindowTime.Add(header.SendTime); }
internal void ForceAck() { if (sendStream != null) { return; } sendStream = NetStream.Create(); WriteHeader(); FlushStream(); }
void ReadSync(NetStream syncStream) { Vector3 position = syncStream.ReadVector3(); Quaternion rotation = syncStream.ReadQuaternion(); Vector2 velocity = syncStream.ReadVector2(); lastPos = position; lastRot = rotation; lastVel = velocity; transform.position = position; transform.rotation = rotation; }
public bool TryGet(ulong ulongKey, out NetStream stream) { int index; if (!TryGetIndex(ulongKey, out index)) { stream = null; return false; } var foundStream = streams[index].Copy(); foundStream.Position = 0; stream = foundStream; return true; }
private void ProcessReceived(IPEndPoint endpoint, int bytesReceived, NetStream readStream) { if (EndpointConnected(endpoint)) { endpointToConnection[endpoint].ReceiveStream(readStream); } else { ProcessUnconnected(endpoint, bytesReceived, readStream); } }
internal bool ClientApproval(IPEndPoint endpoint, NetStream data) { if (OnClientApproval == null) { return(true); } else { return(OnClientApproval(endpoint, data)); } }
/// <summary> Attempts to connect to a server located at the supplied endpoint. </summary> public void Connect(IPEndPoint endpoint) { if (EndpointConnected(endpoint) || connectingEndpoints.Contains(endpoint)) { return; } NetStream approvalData = NetStream.Create(); approvalData.WriteByte((byte)ByteCmd.Connect); Events.WriteApproval(endpoint, approvalData); Connect(endpoint, approvalData); }
internal bool FlushStream() { if (sendStream == null) { return(false); } Connection.Socket.SendStream(Connection, sendStream); LastReliableSent = NetTime.Milliseconds(); Connection.LastSendTime = LastReliableSent; sendStream = null; return(true); }
/// <summary> Attempts to connect to a peer located at the supplied endpoint. </summary> public void ConnectToPeer(IPEndPoint endpoint) { if (EndpointConnected(endpoint) || ConnectingTo(endpoint)) { return; } NetStream approvalData = NetStream.Create(); approvalData.WriteByte((byte)ByteCmd.ConnectToPeer); Events.WritePeerApproval(endpoint, approvalData); Connect(endpoint, approvalData); }
private void ReceivePeerConnectionRequest(IPEndPoint endpoint, NetStream readStream) { if (!AcceptConnections || Connections.Count >= MaxConnections || !Events.PeerApproval(endpoint, readStream)) { NetLog.Info("Refused peer connection: " + endpoint); TrySend(new[] { (byte)ByteCmd.RefuseConnection }, 1, endpoint); } else { CreateConnection(endpoint, false, true); } }
internal static void WriteNetMessage(NetStream stream, NetMessage message) { stream.WriteUShort(message.MessageId, 11); stream.WriteBool(message.ViewId != 0); if (message.ViewId != 0) { stream.WriteUInt(message.ViewId, 20); } foreach (object param in message.Parameters) { WriteParam(stream, param); } }
/// <summary> Fires sync event to trigger sync messsage creation. </summary> internal void TriggerSyncEvent() { if (!syncEnabled || OnWriteSync == null) { return; } if (syncStream == null) { syncStream = NetStream.New(); } syncStream.Reset(); SendSync(OnWriteSync(syncStream)); }
void ReadSync(NetStream syncStream) { Vector3 position = new Vector3(syncStream.ReadFloat(), transform.position.y, syncStream.ReadFloat()); Vector2 velocity = syncStream.ReadVector2(); lastPos = position; lastVel = new Vector3(velocity.x, 0, velocity.y); if (Time.time - lastTime > 1.2) { if (Vector3.Distance(transform.position, lastPos) > 2f) { transform.position = lastPos; } } lastTime = Time.time; positionDiff = transform.position - position; }
/// <summary> Removes acked messages from the send window, releases the stream, updates connection ping, and /// increments the Delivered stat. </summary> private void MessageDelivered(int index, NetHeader header) { Delivered++; NetStream strm = reliableWindow[sendWindow[index]]; if (header.AckTime > 0) { Connection.UpdatePing(NetTime.Milliseconds(), sendWindowTime[index], header.AckTime); } reliableWindow.Remove(sendWindow[index]); sendWindow.RemoveAt(index); sendWindowTime.RemoveAt(index); strm.Release(); }
internal static NetMessage ReadNetMessage(NetStream stream) { List <Type> paramTypes; ushort messageId = stream.ReadUShort(11); uint viewId = 0; if (stream.ReadBool()) { viewId = stream.ReadUInt(20); } if (messageId == (int)Cmd.RequestResponse) { return(CreateResponseMessage(stream, messageId, viewId)); } if (messageId > 1800) { if (!stream.Socket.Command.Exists(messageId)) { NetLog.Error("Cannot deserialize message, Command ID not found: " + messageId); return(null); } paramTypes = stream.Socket.Command.ParamTypes(messageId); } else { if (!stream.Socket.Rpc.Exists(messageId)) { NetLog.Error("Cannot deserialize message, RPC ID not found: " + messageId); return(null); } paramTypes = stream.Socket.Rpc.ParamTypes(messageId); } NetMessage netMessage = NetMessage.Create(messageId, viewId, paramTypes.Count, false); if (stream.Socket.Rpc.TakesRequests(messageId)) { return(CreateRequestMessage(stream, netMessage, paramTypes)); } for (int i = 0; i < paramTypes.Count; i++) { netMessage.Parameters[i] = ReadParam(stream, paramTypes[i]); } return(netMessage); }
/// <summary> Updates receive time and forwards stream to proper channel for deserialization. </summary> internal void ReceiveStream(NetStream stream) { stream.Connection = this; LastReceiveTime = NetTime.Milliseconds(); bool reliable = stream.ReadBool(); if (!reliable) { Unreliable.DeserializeStream(stream); } else { Reliable.RouteIncomingStream(stream); } }
internal NetStream ReadNetStream() { NetStream newStream = New(); newStream.Size = ReadUShort(14); int count = newStream.Size >> 3; int bits = newStream.Size % 8; ReadByteArray(newStream.ByteBuffer, count); if (bits != 0) { newStream.ByteBuffer[count] = ReadByte(bits); } return(newStream); }
/// <summary> Removes a datagram from the buffer and retries delivery. </summary> private void RetryOutOfOrder(int index) { NetStream strm = recvBuffer[index]; int dist = recvBufferSeqDist[index]; recvBuffer.RemoveAt(index); recvBufferSeqDist.RemoveAt(index); if (dist == 63) { RouteIncomingStream(strm); } else if (dist == 1) { DeliverStream(strm); } }
RpcTarget WriteSync(NetStream syncStream) { // If we don't want to sync for this frame, return RpcTarget.None // If lastPos == Vector3.zero, position change has already been synced. if (lastPos == Vector3.zero) return RpcTarget.None; syncStream.WriteVector3(lastPos); syncStream.WriteFloat(lastRot.eulerAngles.y); syncStream.WriteVector2(lastVel); lastPos = Vector3.zero; // We return the RpcTarget for who we want to send the sync info to. Since we receive // the position, rotation, and velocity from the PlayerOwner, we want to send to everyone // BUT the PlayerOwner, so we choose to return RpcTarget.NonControllers. return RpcTarget.NonControllers; }
void ReadSync(NetStream syncStream) { Vector3 position = syncStream.ReadVector3(); float yRot = syncStream.ReadFloat(); Vector2 velocity = syncStream.ReadVector2(); lastTime = 0f; lastPos = position; lastRot = Quaternion.Euler(0, yRot, 0); lastVel = new Vector3(velocity.x, 0, velocity.y); if (teleport) { if (Vector3.Distance(transform.position, lastPos) > 2f) { transform.position = lastPos; transform.rotation = lastRot; } teleport = false; } positionDiff = transform.position - position; }
public bool TryAdd(string stringKey, NetStream streamValue, out ulong key) { NetStream stream = streamValue.Copy(); if (string.IsNullOrEmpty(stringKey)) { Debug.LogError("TryAdd failed! String key is null or empty."); key = ulong.MinValue; return false; } if (stringKeys.Contains(stringKey)) { Debug.LogError("TryAdd failed! Database already contains provided string key: " + stringKey); key = ulong.MinValue; return false; } key = RandomUlong(); ulongKeys.Add(key); stringKeys.Add(stringKey); streams.Add(stream); return true; }
private void ProcessUnconnected(IPEndPoint endpoint, int bytesReceived, NetStream readStream) { if (connectingEndpoints.Contains(endpoint)) { ReceiveConnectionResponse(endpoint, bytesReceived, readStream); } else if (bytesReceived > 0) { byte cmd = readStream.ReadByte(); if (cmd == (byte)ByteCmd.Connect) { ReceiveConnectionRequest(endPoint, readStream); } else if (cmd == (byte)ByteCmd.ConnectToPeer) { ReceivePeerConnectionRequest(endPoint, readStream); } } }
private static NetMessage CreateResponseMessage(NetStream stream, ushort messageId, uint viewId) { ushort requestId = stream.ReadUShort(); if (!stream.Socket.Request.Exists(viewId, requestId)) { return(null); } bool isSuccessful = stream.ReadBool(); object result = null; if (isSuccessful) { Type resultType = stream.Socket.Request.Type(viewId, requestId); result = ReadParam(stream, resultType); } object[] requestParams = { requestId, isSuccessful, result }; return(NetMessage.Create(messageId, viewId, requestParams, true)); }
/// <summary> Receives data until CanReceive is no longer true (receive buffer empty). </summary> private void ReceiveAll() { if (socket == null) { return; } while (CanReceive()) { var readStream = NetStream.Create(); readStream.Socket = this; int received = 0; if (!TryReceive(readStream.Data, readStream.Data.Length, ref received, ref endPoint)) { return; } readStream.Length = received << 3; ProcessReceived(endPoint, received, readStream); } }
/// <summary> Deserializes incoming reliable stream into NetMessages, forwards them to the NetSocket, releases the stream, /// increments the remote sequence, and retries the out-of-order buffer when needed. </summary> private void DeliverStream(NetStream strm) { // Deserialize stream into individual messages and pass them to the socket: while (NetSerializer.CanReadMessage(strm)) { var message = NetSerializer.ReadNetMessage(strm); if (message == null) { NetLog.Error("Failed to parse reliable message from: " + Connection.Endpoint + " Pos: " + strm.Pos + " Size: " + strm.Size); break; } Connection.Socket.ReceiveMessage(message, Connection); } // Return stream to pool and update receive buffer distances: strm.Release(); LastAcceptedRemoteSequence++; if (recvBuffer.Count > 0) { DecrementReceiveBuffer(); } }
internal void CopyTo(NetStream stream) { if (Position == 0) { if (WriteLength) { stream.WriteUShort((ushort)Position, 14); } return; } int count = Position >> 3; int bits = Position % 8; if (WriteLength) { stream.WriteUShort((ushort)Position, 14); } stream.WriteByteArray(ByteBuffer, count); if (bits != 0) { stream.WriteByte(ByteBuffer[count], bits); } }
private static NetMessage CreateRequestMessage(NetStream stream, NetMessage netMessage, List <Type> paramTypes) { int requestIndex = -1; for (int i = 0; i < paramTypes.Count; i++) { if (paramTypes[i].IsGenericType && paramTypes[i].GetGenericTypeDefinition() == typeof(NetRequest <>)) { requestIndex = i; netMessage.Parameters[i] = null; continue; } netMessage.Parameters[i] = ReadParam(stream, paramTypes[i]); } if (!stream.CanRead(16)) { return(netMessage); } ushort requestId = stream.ReadUShort(); if (requestIndex != -1) { netMessage.Parameters[requestIndex] = Activator.CreateInstance(paramTypes[requestIndex], netMessage.ViewId, requestId, stream.Connection); } else { object[] newParams = new object[paramTypes.Count + 1]; netMessage.Parameters.CopyTo(newParams, 0); newParams[newParams.Length - 1] = requestId; netMessage.Parameters = newParams; } return(netMessage); }
private void ReceiveConnectionResponse(IPEndPoint endpoint, int bytesReceived, NetStream readStream) { bool isPeer = RemoveFromConnecting(endpoint, true); if (bytesReceived == 1 && readStream.Data[0] == (byte)ByteCmd.RefuseConnection) { NetLog.Info("Connection refused by: " + endpoint); return; } var connection = CreateConnection(endpoint, true, isPeer); if (bytesReceived > 1) { connection.ReceiveStream(readStream); } }
public static void ItemSerializer(NetStream stream, object instance) { IInvItem item = (IInvItem) instance; stream.WriteUInt(item.DbId); stream.WriteInt(item.Quantity); item.WriteAdditional(stream); }
public IInvItem Clone(int withQuantity, NetStream stream) { return new MeleeWeapon(DbId, Name, QuantityMax, withQuantity, Damage, Cooldown, stream.ReadBool()); }
/// <summary> Updates receive time and forwards stream to proper channel for deserialization. </summary> internal void ReceiveStream(NetStream stream) { stream.Connection = this; LastReceiveTime = NetTime.Milliseconds(); bool reliable = stream.ReadBool(); if (!reliable) Unreliable.DeserializeStream(stream); else Reliable.RouteIncomingStream(stream); }
internal void SendStream(NetConnection connection, NetStream stream) { SendStream(connection.Endpoint, stream); }
internal void SendStream(IPEndPoint endpoint, NetStream stream) { TrySend(stream.Data, stream.Pos + 7 >> 3, endpoint); }
public bool TryUpdate(ulong ulongKey, NetStream stream) { int index; if (stream == null || !TryGetIndex(ulongKey, out index)) return false; NetStream oldStream = streams[index]; streams[index] = stream.Copy(); if (stream != oldStream) oldStream.Release(); return true; }
public NetView CreateView(NetConnection controller, int group, string prefabBase, NetStream instantiateData) { var view = CreateView(controller, Socket.Self, NewViewId(), group, prefabBase, NetView.Relation.Creator); view.TriggerReadInstantiateData(instantiateData); if (OnNetViewCreated != null) { OnNetViewCreated(view); } return(view); }
private void AddRequest(NetStream stream, NetRequest<ulong> request, NetConnection connection) { if (!connection.IsPeer && !connection.IsServer) return; request.Result = Add(stream); }
void Instantiate(NetStream stream) { transform.position = stream.ReadVector3(); }
public NetView CreateView(NetConnection controller, int group, string prefabBase, NetStream instantiateData) { var view = CreateView(controller, Socket.Self, NewViewId(), group, prefabBase, NetView.Relation.Creator); view.TriggerReadInstantiateData(instantiateData); if (OnNetViewCreated != null) OnNetViewCreated(view); return view; }
private void WriteInstantiateData(NetStream stream) { stream.WriteBool(set); if (!set) return; stream.WriteVector3(transform.position); ExampleItems.ItemSerializer(stream, item); }
public NetView CreateView(int group, string prefabBase, NetStream instantiateData) { NetView view = CreateView(null, group, prefabBase, instantiateData); return(view); }
private bool PeerApproval(IPEndPoint endPoint, NetStream data) { if (endPoint.Port > ServerPortRoot + 512 || endPoint.Port < ServerPortRoot) return false; string address = endPoint.Address.ToString(); return (address == ServerAddress || PeerAddresses.Contains(address)); }
internal void CopyTo(NetStream stream) { if (Position == 0) { if (WriteLength) stream.WriteUShort((ushort)Position, 14); return; } int count = Position >> 3; int bits = Position % 8; if (WriteLength) stream.WriteUShort((ushort)Position, 14); stream.WriteByteArray(ByteBuffer, count); if (bits != 0) stream.WriteByte(ByteBuffer[count], bits); }
void Instantiate(NetStream stream) { catAnimator.Dead = stream.ReadBool(); PlayerName = stream.ReadString(); transform.position = stream.ReadVector3(); inventory.SetAllFromStream(stream); }
internal void Send(int id, NetConnection connection, NetStream stream) { NetMessage message = NetMessage.Create((ushort) id, 0, 1, true); message.Parameters[0] = stream; connection.Send(message); }
private void ReadSync(NetStream stream) { transform.position = stream.ReadVector3(); }
private void WriteProxyData(NetStream stream) { stream.WriteBool(Dead); stream.WriteFloat(transform.position.x); stream.WriteFloat(transform.position.z); }
private void TryAddRequest(string stringKey, NetStream stream, NetRequest<ulong> request, NetConnection connection) { if (!connection.IsPeer && !connection.IsServer) return; ulong result; if (TryAdd(stringKey, stream, out result)) request.Result = result; }
private void ReadInstantiateData(NetStream stream) { transform.position = stream.ReadVector3(); }
public void WriteAdditional(NetStream stream) { stream.WriteBool(Equipped); }
public IInvItem Clone(int withQuantity, NetStream stream) { return new Armor(DbId, Name, QuantityMax, withQuantity, Protection, MountPoint, stream.ReadBool()); }