public void ReceiveServerMessage(ServerStateMessage stateMessage)
 {
     if (stateMessage.tick > m_latestStateMessage.tick)
     {
         m_latestStateMessage = stateMessage;
     }
 }
 private void SetRigidbodyStates(ServerStateMessage stateMessage)
 {
     // Override the client rigidbodies with the server rigidbody parameters
     for (int i = 0; i < stateMessage.rigidbody_states.Length; i++)
     {
         RigidbodyState serverRigidbodyState = stateMessage.rigidbody_states[i];
         Transform      clientRigidbody      = m_syncObjects[i];
         clientRigidbody.position = serverRigidbodyState.position;
         clientRigidbody.rotation = serverRigidbodyState.rotation;
     }
 }
    public void ReceiveServerMessage(ServerStateMessage stateMessage)
    {
        if (stateMessage.tick > m_latestStateMessage.tick)
        {
            m_latestStateMessage = stateMessage;

            // Whenever we get a server message, interpolate the client to this position
            // Thus, viewing client see's the paddle in the past
            SetRigidbodyStates(stateMessage);
        }
    }
 private void SetRigidbodyStates(ServerStateMessage stateMessage)
 {
     // Override the client rigidbodies with the server rigidbody parameters
     for (int i = 0; i < stateMessage.rigidbody_states.Length; i++)
     {
         RigidbodyState serverRigidbodyState = stateMessage.rigidbody_states[i];
         Rigidbody      clientRigidbody      = m_syncedRigidbodies[i];
         clientRigidbody.position        = serverRigidbodyState.position;
         clientRigidbody.rotation        = serverRigidbodyState.rotation;
         clientRigidbody.velocity        = serverRigidbodyState.velocity;
         clientRigidbody.angularVelocity = serverRigidbodyState.angular_velocity;
     }
 }
    private void DispatchOutgoingMessages(float dt)
    {
        m_snapshotTimeAccum += dt;
        if (m_snapshotTimeAccum > m_timeBetweenSnapshots)
        {
            m_snapshotTimeAccum -= dt;

            // Send messages after fake latency time is reached
            while (m_messagesToSend.Count > 0 && m_messagesToSend.Peek().sendTime <= Time.time)
            {
                ServerStateMessage message = m_messagesToSend.Dequeue().message;

                if (NewServerMessage != null)
                {
                    NewServerMessage(message);
                }
            }
        }
    }
    private bool DoesAnyObjectNeedCorrection(ServerStateMessage serverStateMessage)
    {
        /// Return true if any rigidbody is deviating from a server rigidbody position
        uint bufferIndex = serverStateMessage.tick % BUFFER_SIZE;

        for (int i = 0; i < serverStateMessage.rigidbody_states.Length; i++)
        {
            RigidbodyState      serverState = serverStateMessage.rigidbody_states[i];
            RigidbodyStateNoVel clientState = m_stateBuffer[bufferIndex].rigidbody_states[i];

            Vector3 position_error = serverState.position - clientState.position;
            float   rotation_error = 1.0f - Quaternion.Dot(serverState.rotation, clientState.rotation);

            if (position_error.sqrMagnitude > PositionErrorThreshold * PositionErrorThreshold ||
                rotation_error > RotationErrorThreshold * RotationErrorThreshold)
            {
                return(true);
            }
        }
        return(false);
    }
Ejemplo n.º 7
0
    void handleServerResponse(string response)
    {
        string[] singleJSONStrings = response.Split(new char[] { '\n' }, System.StringSplitOptions.RemoveEmptyEntries);

        for (int i = 0; i < singleJSONStrings.Length; i++)
        {
            if (System.Text.RegularExpressions.Regex.IsMatch(singleJSONStrings[i], "\"type\"\\s*:\\s*\"end\""))
            {
                b.AppendLine("Server terminated connection");
                chatClient.Close();
                chatClient = null;
                continue;
            }

            if (System.Text.RegularExpressions.Regex.IsMatch(singleJSONStrings[i], "\"type\"\\s*:\\s*\"welcome\""))
            {
                b.AppendLine("Received welcome from server!\nFollowing coordinates have been assigned to you:");
                WelcomeMessage message = UnityEngine.JsonUtility.FromJson <WelcomeMessage>(singleJSONStrings[i]);
                b.AppendLine(message.position);
                this.teleportAvatar(message.position);
                continue;
            }

            if (System.Text.RegularExpressions.Regex.IsMatch(singleJSONStrings[i], "\"type\"\\s*:\\s*\"newcomer\""))
            {
                b.Append("New player connected! Name: ");
                ServerNewcomerMessage message = UnityEngine.JsonUtility.FromJson <ServerNewcomerMessage>(singleJSONStrings[i]);
                b.Append(message.name);
                b.Append(" Position: ");
                b.Append(message.position);
                b.Append("\n");

                try {
                    string[] coords = message.position.Split(',');
                    float    x      = float.Parse(coords[0], System.Globalization.CultureInfo.InvariantCulture);
                    float    y      = float.Parse(coords[1], System.Globalization.CultureInfo.InvariantCulture);
                    float    z      = float.Parse(coords[2], System.Globalization.CultureInfo.InvariantCulture);
                    otherPlayerList.Add(new OtherPlayer(message.name, x, y, z, otherPlayerPrefab));
                } catch (System.Exception e) {
                    b.AppendLine(e.ToString());
                }
                continue;
            }

            if (System.Text.RegularExpressions.Regex.IsMatch(singleJSONStrings[i], "\"type\"\\s*:\\s*\"disconnect\""))
            {
                ServerDisconnectMessage message = UnityEngine.JsonUtility.FromJson <ServerDisconnectMessage>(singleJSONStrings[i]);
                b.Append("Player ");
                b.Append(message.name);
                b.Append(" disconnected!\n");
                OtherPlayer disconnected = otherPlayerList.Find(x => x.getName().Equals(message.name));
                otherPlayerList.Remove(disconnected);
                disconnected.destroy();
                continue;
            }

            if (System.Text.RegularExpressions.Regex.IsMatch(singleJSONStrings[i], "\"type\"\\s*:\\s*\"blockAction\""))
            {
                try {
                    BlockActionMessage message = UnityEngine.JsonUtility.FromJson <BlockActionMessage>(singleJSONStrings[i]);

                    string[] positionRaw = message.position.Split(',');
                    float    x           = float.Parse(positionRaw[0], System.Globalization.CultureInfo.InvariantCulture);
                    float    y           = float.Parse(positionRaw[1], System.Globalization.CultureInfo.InvariantCulture);
                    float    z           = float.Parse(positionRaw[2], System.Globalization.CultureInfo.InvariantCulture);
                    Vector3  position    = new Vector3(x, y, z);

                    GameObject result = this.blockPlacementInstance.blockPlacementList.Find(block => block.transform.position == position);

                    if (result == null)
                    {
                        int        blockID  = int.Parse(message.blockID);
                        GameObject newBlock = GameObject.Instantiate(this.blockPlacementInstance.blockSelectionList[blockID], position, Quaternion.identity);
                        this.blockPlacementInstance.blockPlacementList.Add(newBlock);
                    }
                    else
                    {
                        this.blockPlacementInstance.blockPlacementList.Remove(result);
                        GameObject.Destroy(result);
                    }
                } catch (System.Exception e) {
                    b.AppendLine(e.ToString());
                }
                continue;
            }

            if (System.Text.RegularExpressions.Regex.IsMatch(singleJSONStrings[i], "\"type\"\\s*:\\s*\"positionUpdate\""))
            {
                try {
                    PositionUpdateMessage message = UnityEngine.JsonUtility.FromJson <PositionUpdateMessage>(singleJSONStrings[i]);

                    string[] positionRaw = message.position.Split(',');
                    float    x           = float.Parse(positionRaw[0], System.Globalization.CultureInfo.InvariantCulture);
                    float    y           = float.Parse(positionRaw[1], System.Globalization.CultureInfo.InvariantCulture);
                    float    z           = float.Parse(positionRaw[2], System.Globalization.CultureInfo.InvariantCulture);
                    Vector3  position    = new Vector3(x, y, z);

                    OtherPlayer moved = otherPlayerList.Find(player => player.getName().Equals(message.name));
                    moved.move(position);
                } catch (System.Exception e) {
                }
            }

            if (System.Text.RegularExpressions.Regex.IsMatch(singleJSONStrings[i], "\"type\"\\s*:\\s*\"chat\""))
            {
                ServerMessage message = UnityEngine.JsonUtility.FromJson <ServerMessage>(singleJSONStrings[i]);
                b.Append(message.sender);
                b.Append(message.world ? " (world): " : " (you): ");
                b.Append(message.content);
                b.Append('\n');
                continue;
            }

            if (System.Text.RegularExpressions.Regex.IsMatch(singleJSONStrings[i], "\"type\"\\s*:\\s*\"ping\""))
            {
                int latency = System.Environment.TickCount - this.pingTimer;
                b.Append("Ping: ");
                b.Append(latency);
                b.Append(" ms\n");
            }

            if (System.Text.RegularExpressions.Regex.IsMatch(singleJSONStrings[i], "\"type\"\\s*:\\s*\"state\""))
            {
                foreach (OtherPlayer player in otherPlayerList)
                {
                    player.destroy();
                }
                otherPlayerList.Clear();


                ServerStateMessage message         = UnityEngine.JsonUtility.FromJson <ServerStateMessage>(singleJSONStrings[i]);
                string             parsedPositions = message.positions;
                parsedPositions = parsedPositions.Replace("{", "");
                parsedPositions = parsedPositions.Replace("}", "");
                parsedPositions = parsedPositions.Replace("\\", "");
                parsedPositions = parsedPositions.Replace("\"", "");
                parsedPositions = parsedPositions.Replace(":", ",");

                string[] positionData = parsedPositions.Split(new char[] { ',' });

                b.AppendLine("Generating list of players and their global positions:");
                for (int j = 0; j < positionData.Length; j += 4)
                {
                    b.AppendLine("Name: " + positionData[j] + ", X:" + positionData[j + 1] + ", Y:" + positionData[j + 2] + ", Z:" + positionData[j + 3]);
                    if (positionData[j].Equals(ownName))
                    {
                        continue;
                    }
                    float x = float.Parse(positionData[j + 1], System.Globalization.CultureInfo.InvariantCulture);
                    float y = float.Parse(positionData[j + 2], System.Globalization.CultureInfo.InvariantCulture);
                    float z = float.Parse(positionData[j + 3], System.Globalization.CultureInfo.InvariantCulture);
                    otherPlayerList.Add(new OtherPlayer(positionData[j], x, y, z, otherPlayerPrefab));
                }

                continue;
            }
        }



        if (!this.chatText.text.Equals(b.ToString()))
        {
            this.chatText.text     = b.ToString();
            this.TimeLeftUntilFade = fadeOutTime;
        }
    }