NetworkTranformChild.cs 18.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
using System;
using UnityEngine;

namespace UnityEngine.Networking
{
    /// <summary>
    /// A component to synchronize the position of child transforms of networked objects.
    /// <para>There must be a NetworkTransform on the root object of the hierarchy. There can be multiple NetworkTransformChild components on an object. This does not use physics for synchronization, it simply synchronizes the localPosition and localRotation of the child transform and lerps towards the recieved values.</para>
    /// </summary>
    [AddComponentMenu("Network/NetworkTransformChild")]
    [Obsolete("The high level API classes are deprecated and will be removed in the future.")]
    public class NetworkTransformChild : NetworkBehaviour
    {
        [SerializeField]
        Transform m_Target;

        [SerializeField]
        uint m_ChildIndex;

        NetworkTransform m_Root;

        [SerializeField] float                                  m_SendInterval = 0.1f;
        [SerializeField] NetworkTransform.AxisSyncMode          m_SyncRotationAxis = NetworkTransform.AxisSyncMode.AxisXYZ;
        [SerializeField] NetworkTransform.CompressionSyncMode   m_RotationSyncCompression = NetworkTransform.CompressionSyncMode.None;
        [SerializeField] float                                  m_MovementThreshold = 0.001f;

        [SerializeField] float                                  m_InterpolateRotation = 0.5f;
        [SerializeField] float                                  m_InterpolateMovement = 0.5f;
        [SerializeField] NetworkTransform.ClientMoveCallback3D  m_ClientMoveCallback3D;


        // movement smoothing
        Vector3         m_TargetSyncPosition;
        Quaternion      m_TargetSyncRotation3D;

        float           m_LastClientSyncTime; // last time client received a sync from server
        float           m_LastClientSendTime; // last time client send a sync to server

        Vector3         m_PrevPosition;
        Quaternion      m_PrevRotation;

        const float     k_LocalMovementThreshold = 0.00001f;
        const float     k_LocalRotationThreshold = 0.00001f;

        NetworkWriter   m_LocalTransformWriter;

        // settings
        /// <summary>
        /// The child transform to be synchronized.
        /// </summary>
        public Transform                            target { get {return m_Target; } set { m_Target = value; OnValidate(); } }
        /// <summary>
        /// A unique Identifier for this NetworkTransformChild component on this root object.
        /// </summary>
        public uint                                 childIndex { get { return m_ChildIndex; }}
        /// <summary>
        /// The sendInterval controls how often state updates are sent for this object.
        /// </summary>
        public float                                sendInterval { get { return m_SendInterval; } set { m_SendInterval = value; } }
        /// <summary>
        /// Which axis should rotation by synchronized for.
        /// </summary>
        public NetworkTransform.AxisSyncMode        syncRotationAxis { get { return m_SyncRotationAxis; } set { m_SyncRotationAxis = value; } }
        /// <summary>
        /// How much to compress rotation sync updates.
        /// </summary>
        public NetworkTransform.CompressionSyncMode rotationSyncCompression { get { return m_RotationSyncCompression; } set { m_RotationSyncCompression = value; } }
        /// <summary>
        /// The distance that an object can move without sending a movement synchronization update.
        /// <para>This applies to the child object's localPosition, not it's world position.</para>
        /// </summary>
        public float                                movementThreshold { get { return m_MovementThreshold; } set { m_MovementThreshold = value; } }
        /// <summary>
        /// The rate to interpolate to the target rotation.
        /// <para>A value of 1 will snap to the position, and lower positive values will interpolate more slowly.</para>
        /// </summary>
        public float                                interpolateRotation { get { return m_InterpolateRotation; } set { m_InterpolateRotation = value; } }
        /// <summary>
        /// The rate to interpolate towards the target position.
        /// <para>A value of 1 will snap to the position, and lower positive values will interpolate more slowly.</para>
        /// </summary>
        public float                                interpolateMovement { get { return m_InterpolateMovement; } set { m_InterpolateMovement = value; } }
        /// <summary>
        /// A callback function to allow server side validation of the movement of the child object.
        /// </summary>
        public NetworkTransform.ClientMoveCallback3D clientMoveCallback3D { get { return m_ClientMoveCallback3D; } set { m_ClientMoveCallback3D = value; } }

        // runtime data
        /// <summary>
        /// The most recent time when a movement synchronization packet arrived for this object.
        /// </summary>
        public float                lastSyncTime { get { return m_LastClientSyncTime; } }
        /// <summary>
        /// The target position interpolating towards.
        /// </summary>
        public Vector3              targetSyncPosition { get { return m_TargetSyncPosition; } }
        /// <summary>
        /// The target rotation interpolating towards.
        /// </summary>
        public Quaternion           targetSyncRotation3D { get { return m_TargetSyncRotation3D; } }

        void OnValidate()
        {
            // root parent of target must have a NetworkTransform
            if (m_Target != null)
            {
                Transform parent = m_Target.parent;
                if (parent == null)
                {
                    if (LogFilter.logError) { Debug.LogError("NetworkTransformChild target cannot be the root transform."); }
                    m_Target = null;
                    return;
                }
                while (parent.parent != null)
                {
                    parent = parent.parent;
                }

                m_Root = parent.gameObject.GetComponent<NetworkTransform>();
                if (m_Root == null)
                {
                    if (LogFilter.logError) { Debug.LogError("NetworkTransformChild root must have NetworkTransform"); }
                    m_Target = null;
                    return;
                }
            }

            if (m_Root != null)
            {
                // childIndex is the index within all the NetworkChildTransforms on the root
                m_ChildIndex = UInt32.MaxValue;
                var childTransforms = m_Root.GetComponents<NetworkTransformChild>();
                for (uint i = 0; i < childTransforms.Length; i++)
                {
                    if (childTransforms[i] == this)
                    {
                        m_ChildIndex = i;
                        break;
                    }
                }
                if (m_ChildIndex == UInt32.MaxValue)
                {
                    if (LogFilter.logError) { Debug.LogError("NetworkTransformChild component must be a child in the same hierarchy"); }
                    m_Target = null;
                }
            }

            if (m_SendInterval < 0)
            {
                m_SendInterval = 0;
            }

            if (m_SyncRotationAxis < NetworkTransform.AxisSyncMode.None || m_SyncRotationAxis > NetworkTransform.AxisSyncMode.AxisXYZ)
            {
                m_SyncRotationAxis = NetworkTransform.AxisSyncMode.None;
            }

            if (movementThreshold < 0)
            {
                movementThreshold = 0.00f;
            }

            if (interpolateRotation < 0)
            {
                interpolateRotation = 0.01f;
            }
            if (interpolateRotation > 1.0f)
            {
                interpolateRotation = 1.0f;
            }

            if (interpolateMovement < 0)
            {
                interpolateMovement  = 0.01f;
            }
            if (interpolateMovement > 1.0f)
            {
                interpolateMovement = 1.0f;
            }
        }

        void Awake()
        {
            m_PrevPosition = m_Target.localPosition;
            m_PrevRotation = m_Target.localRotation;

            // cache these to avoid per-frame allocations.
            if (localPlayerAuthority)
            {
                m_LocalTransformWriter = new NetworkWriter();
            }
        }

        public override bool OnSerialize(NetworkWriter writer, bool initialState)
        {
            if (initialState)
            {
                // always write initial state, no dirty bits
            }
            else if (syncVarDirtyBits == 0)
            {
                writer.WritePackedUInt32(0);
                return false;
            }
            else
            {
                // dirty bits
                writer.WritePackedUInt32(1);
            }

            SerializeModeTransform(writer);
            return true;
        }

        void SerializeModeTransform(NetworkWriter writer)
        {
            // position
            writer.Write(m_Target.localPosition);

            // rotation
            if (m_SyncRotationAxis != NetworkTransform.AxisSyncMode.None)
            {
                NetworkTransform.SerializeRotation3D(writer, m_Target.localRotation, syncRotationAxis, rotationSyncCompression);
            }
            m_PrevPosition = m_Target.localPosition;
            m_PrevRotation = m_Target.localRotation;
        }

        public override void OnDeserialize(NetworkReader reader, bool initialState)
        {
            if (isServer && NetworkServer.localClientActive)
                return;

            if (!initialState)
            {
                if (reader.ReadPackedUInt32() == 0)
                    return;
            }
            UnserializeModeTransform(reader, initialState);

            m_LastClientSyncTime = Time.time;
        }

        void UnserializeModeTransform(NetworkReader reader, bool initialState)
        {
            if (hasAuthority)
            {
                // this component must read the data that the server wrote, even if it ignores it.
                // otherwise the NetworkReader stream will still contain that data for the next component.

                // position
                reader.ReadVector3();

                if (syncRotationAxis != NetworkTransform.AxisSyncMode.None)
                {
                    NetworkTransform.UnserializeRotation3D(reader, syncRotationAxis, rotationSyncCompression);
                }
                return;
            }

            if (isServer && m_ClientMoveCallback3D != null)
            {
                var pos = reader.ReadVector3();
                var vel = Vector3.zero;
                var rot = Quaternion.identity;
                if (syncRotationAxis != NetworkTransform.AxisSyncMode.None)
                {
                    rot = NetworkTransform.UnserializeRotation3D(reader, syncRotationAxis, rotationSyncCompression);
                }

                if (m_ClientMoveCallback3D(ref pos, ref vel, ref rot))
                {
                    m_TargetSyncPosition = pos;
                    if (syncRotationAxis != NetworkTransform.AxisSyncMode.None)
                    {
                        m_TargetSyncRotation3D = rot;
                    }
                }
                else
                {
                    // rejected by callback
                    return;
                }
            }
            else
            {
                // position
                m_TargetSyncPosition = reader.ReadVector3();

                // rotation
                if (syncRotationAxis != NetworkTransform.AxisSyncMode.None)
                {
                    m_TargetSyncRotation3D = NetworkTransform.UnserializeRotation3D(reader, syncRotationAxis, rotationSyncCompression);
                }
            }
        }

        void FixedUpdate()
        {
            if (isServer)
            {
                FixedUpdateServer();
            }
            if (isClient)
            {
                FixedUpdateClient();
            }
        }

        void FixedUpdateServer()
        {
            if (syncVarDirtyBits != 0)
                return;

            // dont run if network isn't active
            if (!NetworkServer.active)
                return;

            // dont run if we haven't been spawned yet
            if (!isServer)
                return;

            // dont' auto-dirty if no send interval
            if (GetNetworkSendInterval() == 0)
                return;

            float distance = (m_Target.localPosition - m_PrevPosition).sqrMagnitude;
            if (distance < movementThreshold)
            {
                distance = Quaternion.Angle(m_PrevRotation, m_Target.localRotation);
                if (distance < movementThreshold)
                {
                    return;
                }
            }

            // This will cause transform to be sent
            SetDirtyBit(1);
        }

        void FixedUpdateClient()
        {
            // dont run if we haven't received any sync data
            if (m_LastClientSyncTime == 0)
                return;

            // dont run if network isn't active
            if (!NetworkServer.active && !NetworkClient.active)
                return;

            // dont run if we haven't been spawned yet
            if (!isServer && !isClient)
                return;

            // dont run if not expecting continuous updates
            if (GetNetworkSendInterval() == 0)
                return;

            // dont run this if this client has authority over this player object
            if (hasAuthority)
                return;

            // interpolate on client
            if (m_LastClientSyncTime != 0)
            {
                if (m_InterpolateMovement > 0)
                {
                    m_Target.localPosition = Vector3.Lerp(m_Target.localPosition, m_TargetSyncPosition, m_InterpolateMovement);
                }
                else
                {
                    m_Target.localPosition = m_TargetSyncPosition;
                }

                if (m_InterpolateRotation > 0)
                {
                    m_Target.localRotation = Quaternion.Slerp(m_Target.localRotation, m_TargetSyncRotation3D, m_InterpolateRotation);
                }
                else
                {
                    m_Target.localRotation = m_TargetSyncRotation3D;
                }
            }
        }

        // --------------------- local transform sync  ------------------------

        void Update()
        {
            if (!hasAuthority)
                return;

            if (!localPlayerAuthority)
                return;

            if (NetworkServer.active)
                return;

            if (Time.time - m_LastClientSendTime > GetNetworkSendInterval())
            {
                SendTransform();
                m_LastClientSendTime = Time.time;
            }
        }

        bool HasMoved()
        {
            float diff = 0;

            // check if position has changed
            diff = (m_Target.localPosition - m_PrevPosition).sqrMagnitude;
            if (diff > k_LocalMovementThreshold)
            {
                return true;
            }

            // check if rotation has changed
            diff = Quaternion.Angle(m_Target.localRotation, m_PrevRotation);
            if (diff > k_LocalRotationThreshold)
            {
                return true;
            }

            // check if velocty has changed

            return false;
        }

        [Client]
        void SendTransform()
        {
            if (!HasMoved() || ClientScene.readyConnection == null)
            {
                return;
            }

            m_LocalTransformWriter.StartMessage(MsgType.LocalChildTransform);
            m_LocalTransformWriter.Write(netId);
            m_LocalTransformWriter.WritePackedUInt32(m_ChildIndex);
            SerializeModeTransform(m_LocalTransformWriter);

            m_PrevPosition = m_Target.localPosition;
            m_PrevRotation = m_Target.localRotation;


            m_LocalTransformWriter.FinishMessage();

#if UNITY_EDITOR
            Profiler.IncrementStatOutgoing(MsgType.LocalChildTransform, "16:LocalChildTransform");
#endif
            ClientScene.readyConnection.SendWriter(m_LocalTransformWriter, GetNetworkChannel());
        }

        static internal void HandleChildTransform(NetworkMessage netMsg)
        {
            NetworkInstanceId netId = netMsg.reader.ReadNetworkId();
            uint childIndex = netMsg.reader.ReadPackedUInt32();

#if UNITY_EDITOR
            Profiler.IncrementStatIncoming(MsgType.LocalChildTransform, "16:LocalChildTransform");
#endif

            GameObject foundObj = NetworkServer.FindLocalObject(netId);
            if (foundObj == null)
            {
                if (LogFilter.logError) { Debug.LogError("Received NetworkTransformChild data for GameObject that doesn't exist"); }
                return;
            }
            var children = foundObj.GetComponents<NetworkTransformChild>();
            if (children == null || children.Length == 0)
            {
                if (LogFilter.logError) { Debug.LogError("HandleChildTransform no children"); }
                return;
            }
            if (childIndex >= children.Length)
            {
                if (LogFilter.logError) { Debug.LogError("HandleChildTransform childIndex invalid"); }
                return;
            }

            NetworkTransformChild foundSync = children[childIndex];
            if (foundSync == null)
            {
                if (LogFilter.logError) { Debug.LogError("HandleChildTransform null target"); }
                return;
            }
            if (!foundSync.localPlayerAuthority)
            {
                if (LogFilter.logError) { Debug.LogError("HandleChildTransform no localPlayerAuthority"); }
                return;
            }

            if (!netMsg.conn.clientOwnedObjects.Contains(netId))
            {
                if (LogFilter.logWarn) { Debug.LogWarning("NetworkTransformChild netId:" + netId + " is not for a valid player"); }
                return;
            }

            foundSync.UnserializeModeTransform(netMsg.reader, false);
            foundSync.m_LastClientSyncTime = Time.time;

            if (!foundSync.isClient)
            {
                // dedicated server wont interpolate, so snap.
                foundSync.m_Target.localPosition = foundSync.m_TargetSyncPosition;
                foundSync.m_Target.localRotation = foundSync.m_TargetSyncRotation3D;
            }
        }

        public override int GetNetworkChannel()
        {
            return Channels.DefaultUnreliable;
        }

        public override float GetNetworkSendInterval()
        {
            return m_SendInterval;
        }
    }
}