Esempio n. 1
0
        /// <summary>
        /// Determine if an element lies
        /// within the volume of the Space
        /// </summary>
        public bool IsInSpace(Element element)
        {
            DB.FamilyInstance familyInstance = element.InternalElement as DB.FamilyInstance;
            if (familyInstance != null)
            {
                if (familyInstance.HasSpatialElementCalculationPoint)
                {
                    DB.XYZ insertionPoint = familyInstance.GetSpatialElementCalculationPoint();

                    if (InternalSpace.IsPointInSpace(insertionPoint))
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
            }

            DB.LocationPoint insertionLocationPoint = element.InternalElement.Location as DB.LocationPoint;
            if (insertionLocationPoint != null)
            {
                DB.XYZ insertionPoint = insertionLocationPoint.Point;

                if (InternalSpace.IsPointInSpace(insertionPoint))
                {
                    return(true);
                }
            }

            return(false);
        }
Esempio n. 2
0
        private void UpdateFlightScene(
            EVREye eye,
            SteamVR_Utils.RigidTransform hmdTransform,
            SteamVR_Utils.RigidTransform hmdEyeTransform)
        {
            // in flight, don't allow movement of the origin point
            CurrentPosition = InitialPosition;
            CurrentRotation = InitialRotation;

            // get position of your eyeball
            Vector3 positionToHmd = hmdTransform.pos;
            Vector3 positionToEye = hmdTransform.pos + hmdTransform.rot * hmdEyeTransform.pos;

            // translate device space to Unity space, with world scaling
            Vector3    updatedPosition = DevicePoseToWorld(positionToEye);
            Quaternion updatedRotation = DevicePoseToWorld(hmdTransform.rot);

            // in flight, update the internal and flight cameras
            InternalCamera.Instance.transform.position = updatedPosition;
            InternalCamera.Instance.transform.rotation = updatedRotation;

            FlightCamera.fetch.transform.position = InternalSpace.InternalToWorld(InternalCamera.Instance.transform.position);
            FlightCamera.fetch.transform.rotation = InternalSpace.InternalToWorld(InternalCamera.Instance.transform.rotation);

            // store the eyeball position
            HmdEyePosition[(int)eye] = updatedPosition;
            HmdEyeRotation[(int)eye] = updatedRotation;
        }
Esempio n. 3
0
        private void GetPosition()
        {
            float moveForward = Input.GetKey(Settings.ForwardKey) ? Settings.ForwardSpeed * Time.deltaTime : 0;

            moveForward -= Input.GetKey(Settings.BackwardKey) ? Settings.ForwardSpeed * Time.deltaTime : 0;
            float moveRight = Input.GetKey(Settings.RightKey) ? Settings.HorizontalSpeed * Time.deltaTime : 0;

            moveRight -= Input.GetKey(Settings.LeftKey) ? Settings.HorizontalSpeed * Time.deltaTime : 0;
            float moveUp = Input.GetKey(Settings.UpKey) ? Settings.VerticalSpeed * Time.deltaTime : 0;

            moveUp -= Input.GetKey(Settings.DownKey) ? Settings.VerticalSpeed * Time.deltaTime : 0;
            Vector3 movement = new Vector3(moveRight, moveUp, moveForward);
            //ScreenMessages.PostScreenMessage("Forward: " + moveForward + ", Right: " + moveRight + ", Up: " + moveUp);


            // Make the movement relative to the camera rotation.
            Vector3 newPos = /*previousPos*/ KerbalCollider.transform.localPosition + (InternalCamera.Instance.transform.localRotation * movement);

            //cameraCollider.transform.localPosition = newPos;

            KerbalCollider.rigidbody.velocity = new Vector3(0, 0, 0);
            KerbalCollider.rigidbody.MovePosition(newPos);

            //InternalCamera.Instance.transform.localPosition = newPos;
            FlightCamera.fetch.transform.position = InternalSpace.InternalToWorld(InternalCamera.Instance.transform.position);
            //previousPos = newPos;
        }
Esempio n. 4
0
        private void PartCollidersToInternal()
        {
            var partBoxColliders = GetComponentsInChildren <BoxCollider>();

            foreach (var c in partBoxColliders)
            {
                if (c.isTrigger || c.tag != "Untagged")
                {
                    continue;
                }

                var go = Instantiate(c.gameObject);
                go.transform.parent   = c.gameObject.transform.parent;
                go.layer              = (int)Layers.InternalSpace;
                go.transform.position = InternalSpace.WorldToInternal(c.transform.position);
                go.transform.rotation = InternalSpace.WorldToInternal(c.transform.rotation);
                PartInternalColliderObjects.Add(go);
            }

            /*
             * Structure:
             * Part
             *  model
             *      BoxCOL x 12
             *          BoxCollider
             */

            /*public void OnDestroy()
             * {
             *  /*Debug.Log("#Destroying");
             *  foreach (Hatch h in Hatches)
             *      h.Destroy();
             *  Hatches.Clear();* /
             * }*/
        }
Esempio n. 5
0
        public void OnPreCull()
        {
            //If the IVA and Main camera transforms are not null (should't be) position and rotate the IVACamera correctly.
            if (JSIAdvTransparentPods.Instance.IVAcameraTransform != null && JSIAdvTransparentPods.Instance.MaincameraTransform != null && InternalSpace.Instance != null)
            {
                JSIAdvTransparentPods.Instance.IVAcameraTransform.position = InternalSpace.WorldToInternal(JSIAdvTransparentPods.Instance.MaincameraTransform.position);
                JSIAdvTransparentPods.Instance.IVAcameraTransform.rotation = InternalSpace.WorldToInternal(JSIAdvTransparentPods.Instance.MaincameraTransform.rotation);
                JSIAdvTransparentPods.Instance.IVAcamera.fieldOfView       = JSIAdvTransparentPods.Instance.Maincamera.fieldOfView;
            }

            for (int i = 0; i < JSIAdvTransparentPods.PartstoFilterfromIVADict.Count; i++)
            {
                try
                {
                    JSIAdvTransparentPods.PartstoFilterfromIVADict[i].internalModel.SetVisible(false);
                }
                catch (Exception ex)
                {
                    //if (precullMsgCount < 10)
                    //{
                    //    JSIAdvPodsUtil.Log_Debug("Unable to Precull internalModel for part {0}", JSIAdvTransparentPods.Instance.PartstoFilterfromIVADict[i].craftID);
                    //    JSIAdvPodsUtil.Log_Debug("Err : {0}", ex.Message);
                    //    precullMsgCount++;
                    //}
                }
            }
        }
Esempio n. 6
0
        public void GetOrientation()
        {
            float yaw   = 0;
            float pitch = 0;
            float roll  = 0;

            if (!cameraPositionLocked)
            {
#if true
                float mouseX = Input.GetAxis("Mouse X");
                yaw = mouseX * Settings.YawSpeed;
                float mouseY = Input.GetAxis("Mouse Y");
                pitch = -mouseY * Settings.PitchSpeed;
#else
                yaw = 0;
                if (Input.GetKey(KeyCode.L))
                {
                    yaw = Settings.YawSpeed * Time.deltaTime * 10;
                }
                else if (Input.GetKey(KeyCode.J))
                {
                    yaw = -Settings.YawSpeed * Time.deltaTime * 10;
                }
                pitch = 0;
                if (Input.GetKey(KeyCode.I))
                {
                    pitch = Settings.PitchSpeed * Time.deltaTime * 10;
                }
                else if (Input.GetKey(KeyCode.K))
                {
                    pitch = -Settings.PitchSpeed * Time.deltaTime * 10;
                }
                roll = 0;
#endif
            }
            if (Input.GetKey(Settings.RollCCWKey))
            {
                roll = Settings.RollSpeed * Time.deltaTime;
            }
            else if (Input.GetKey(Settings.RollCWKey))
            {
                roll = -Settings.RollSpeed * Time.deltaTime;
            }

            Quaternion rotYaw          = Quaternion.AngleAxis(yaw, previousRotation * Vector3.up);
            Quaternion rotPitch        = Quaternion.AngleAxis(pitch, previousRotation * Vector3.right);// *Quaternion.Euler(0, 90, 0);
            Quaternion rotRoll         = Quaternion.AngleAxis(roll, previousRotation * Vector3.forward);
            Transform  cameraTransform = InternalCamera.Instance.transform;
            cameraTransform.rotation = rotRoll * rotPitch * rotYaw * previousRotation;
            previousRotation         = cameraTransform.rotation;
            FlightCamera.fetch.transform.rotation = InternalSpace.InternalToWorld(cameraTransform.rotation);
        }
    void Update()
    {
        if (parentTransform == null)
        {
            return;
        }
        Vector3    pos = parentTransform.position;
        Quaternion rot = parentTransform.rotation;

        var xform = internalModel.transform;

        xform.position = InternalSpace.WorldToInternal(pos);
        xform.rotation = InternalSpace.WorldToInternal(rot) * Quaternion.Euler(90, 180, 0);
    }
Esempio n. 8
0
        /*/ FPS-style movement relative to a downward force.
         * // This works fine, but downwards is always relative to the IVA itself.
         * // Uses smooth mouselook from here: http://forum.unity3d.com/threads/a-free-simple-smooth-mouselook.73117/
         * private void IvaRelativeOrientation()
         * {
         *  // Allow the script to clamp based on a desired target value.
         *  var targetOrientation = Quaternion.Euler(targetDirection);
         *
         *  if (!cameraPositionLocked)
         *  {
         *      // Get raw mouse input for a cleaner reading on more sensitive mice.
         *      Vector2 mouseDelta = new Vector2(-Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
         *
         *      // Scale input against the sensitivity setting and multiply that against the smoothing value.
         *      mouseDelta = Vector2.Scale(mouseDelta, new Vector2(sensitivity.x * smoothing.x, sensitivity.y * smoothing.y));
         *
         *      // Interpolate mouse movement over time to apply smoothing delta.
         *      _smoothMouse.x = Mathf.Lerp(_smoothMouse.x, mouseDelta.x, 1f / smoothing.x);
         *      _smoothMouse.y = Mathf.Lerp(_smoothMouse.y, mouseDelta.y, 1f / smoothing.y);
         *
         *      // Find the absolute mouse movement value from point zero.
         *      _mouseAbsolute += _smoothMouse;
         *  }
         *
         *  // Clamp and apply the local x value first, so as not to be affected by world transforms.
         *  if (clampInDegrees.x < 360)
         *      _mouseAbsolute.x = Mathf.Clamp(_mouseAbsolute.x, -clampInDegrees.x * 0.5f, clampInDegrees.x * 0.5f);
         *
         *  Quaternion xRotation = Quaternion.AngleAxis(-_mouseAbsolute.y, targetOrientation * Vector3.right);
         *  InternalCamera.Instance.transform.rotation = xRotation;
         *
         *  // Then clamp and apply the global y value.
         *  if (clampInDegrees.y < 360)
         *      _mouseAbsolute.y = Mathf.Clamp(_mouseAbsolute.y, -clampInDegrees.y * 0.5f, clampInDegrees.y * 0.5f);
         *
         *  InternalCamera.Instance.transform.rotation *= targetOrientation;
         *
         *  Quaternion yRotation = Quaternion.AngleAxis(_mouseAbsolute.x, InternalCamera.Instance.transform.InverseTransformDirection(Vector3.forward));
         *  InternalCamera.Instance.transform.rotation *= yRotation;
         *
         *  FlightCamera.fetch.transform.rotation = InternalSpace.InternalToWorld(InternalCamera.Instance.transform.rotation);
         * }*/

        private void RelativeOrientation()
        {
            // Allow the script to clamp based on a desired target value.
            //var targetOrientation = Quaternion.Euler(targetDirection);

            if (!cameraPositionLocked)
            {
                // Get raw mouse input for a cleaner reading on more sensitive mice.
                Vector2 mouseDelta = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));

                // Scale input against the sensitivity setting and multiply that against the smoothing value.
                mouseDelta = Vector2.Scale(mouseDelta, new Vector2(sensitivity.x * smoothing.x, sensitivity.y * smoothing.y));

                // Interpolate mouse movement over time to apply smoothing delta.
                _smoothMouse.x = Mathf.Lerp(_smoothMouse.x, mouseDelta.x, 1f / smoothing.x);
                _smoothMouse.y = Mathf.Lerp(_smoothMouse.y, mouseDelta.y, 1f / smoothing.y);

                // Find the absolute mouse movement value from point zero.
                _mouseAbsolute += _smoothMouse;
            }
            Vector3 totalForce        = KerbalRigidbody.velocity; /*new Vector3(0f, 0f, -9.81f);*/ //GetFlightForces();
            var     targetOrientation = Quaternion.Euler(totalForce);

            // Clamp and apply the local x value first, so as not to be affected by world transforms.
            if (clampInDegrees.x < 360)
            {
                _mouseAbsolute.x = Mathf.Clamp(_mouseAbsolute.x, -clampInDegrees.x * 0.5f, clampInDegrees.x * 0.5f);
            }

            // Then clamp and apply the global y value.
            if (clampInDegrees.y < 360)
            {
                _mouseAbsolute.y = Mathf.Clamp(_mouseAbsolute.y, -clampInDegrees.y * 0.5f, clampInDegrees.y * 0.5f);
            }

            //InternalCamera.Instance.transform.rotation *= targetOrientation;

            InternalCamera.Instance.transform.localRotation = InternalSpace.WorldToInternal(Quaternion.AngleAxis(-_mouseAbsolute.y, targetOrientation * Vector3.up /*right*/) * targetOrientation); // Pitch
            Quaternion yaw = Quaternion.AngleAxis(-_mouseAbsolute.x, /*-gForce);*/ InternalCamera.Instance.transform.InverseTransformDirection(totalForce));                                        //Vector3.up));

            InternalCamera.Instance.transform.localRotation *= yaw;

            Quaternion roll = Quaternion.Euler(0, 0, 90);

            InternalCamera.Instance.transform.localRotation *= roll;

            FlightCamera.fetch.transform.rotation = InternalSpace.InternalToWorld(InternalCamera.Instance.transform.rotation);
        }
Esempio n. 9
0
 private static Vector3 CT(Vector3 vector, bool asInternal = false)
 {
     if (1 == 1)
     {
         return(vector);
     }
     if (CameraManager.Instance.currentCameraMode == CameraManager.CameraMode.IVA || CameraManager.Instance.currentCameraMode == CameraManager.CameraMode.Internal)
     {
         if (asInternal)
         {
             return(vector);
         }
         return(InternalSpace.WorldToInternal(vector));
     }
     return(vector);
 }
Esempio n. 10
0
        private List <DB.BoundarySegment> GetBoundarySegment()
        {
            List <DB.BoundarySegment> output = new List <DB.BoundarySegment>();

            DB.SpatialElementBoundaryOptions opt = new DB.SpatialElementBoundaryOptions();

            foreach (List <DB.BoundarySegment> segments in InternalSpace.GetBoundarySegments(opt))
            {
                foreach (DB.BoundarySegment segment in segments)
                {
                    output.Add(segment);
                }
            }

            return(output.Distinct().ToList());
        }
Esempio n. 11
0
 private static Vector3 CT(Vector3 vector, bool asInternal = false)
 {
     if (1 == 1)
     {
         return(vector);
     }
     // TODO: Figure out why this code is unreachable
     if (CameraManager.Instance.currentCameraMode == CameraManager.CameraMode.IVA ||
         CameraManager.Instance.currentCameraMode == CameraManager.CameraMode.Internal)
     {
         if (asInternal)
         {
             return(vector);
         }
         return(InternalSpace.WorldToInternal(vector));
     }
     return(vector);
 }
Esempio n. 12
0
        private static void UpdateFlightScene(
            SteamVR_Utils.RigidTransform hmdTransform,
            SteamVR_Utils.RigidTransform hmdEyeTransform)
        {
            CurrentPosition = InitialPosition;
            CurrentRotation = InitialRotation;

            Vector3 positionToHmd = hmdTransform.pos * (1 / kerbalScale);
            Vector3 positionToEye = positionToHmd + hmdTransform.rot * (hmdEyeTransform.pos * (1 / kerbalScale));

            Vector3    updatedPosition = CurrentPosition + CurrentRotation * positionToEye;
            Quaternion updatedRotation = CurrentRotation * hmdTransform.rot;

            InternalCamera.Instance.transform.position = updatedPosition;
            InternalCamera.Instance.transform.rotation = updatedRotation;

            FlightCamera.fetch.transform.position = InternalSpace.InternalToWorld(InternalCamera.Instance.transform.position);
            FlightCamera.fetch.transform.rotation = InternalSpace.InternalToWorld(InternalCamera.Instance.transform.rotation);
        }
Esempio n. 13
0
        public void OnUpdate2()
        {
            // calculate scope repositioning. when your head moves down, the image moves down
            // x - right
            // y - forward
            // z - downwards

            /*Vector3 viewfinderDeltaPositionL = viewfinderTransform.InverseTransformPoint(
             *  Scene.Instance.HmdEyePosition[(int)EVREye.Eye_Left]);
             * Vector3 viewfinderDeltaPositionR = viewfinderTransform.InverseTransformPoint(
             *  Scene.Instance.HmdEyePosition[(int)EVREye.Eye_Right]);
             * Vector3 viewfinderDeltaPosition =
             *  (viewfinderDeltaPositionL.sqrMagnitude < viewfinderDeltaPositionR.sqrMagnitude) ?
             *  viewfinderDeltaPositionL : viewfinderDeltaPositionR;*/
            Vector3 viewfinderDeltaPosition = viewfinderTransform.InverseTransformPoint(
                Scene.Instance.HmdEyePosition[(int)EVREye.Eye_Right]);

            Vector3 scopeDeltaPosition = cameraRot * new Vector3(
                viewfinderDeltaPosition.x * parallaxFactor, viewfinderDeltaPosition.z * parallaxFactor, 0f);

            Vector3 newScopePosition = cameraPos + scopeDeltaPosition;

            scopeCameraGameObject.transform.position = InternalSpace.InternalToWorld(newScopePosition);
            scopeCameraGameObject.transform.rotation = InternalSpace.InternalToWorld(cameraRot);

            // crosshair positioning
            crosshair.transform.position = InternalSpace.InternalToWorld(newScopePosition + cameraRot *
                                                                         new Vector3(0f, 0f, crosshairOffset));
            crosshair.transform.rotation = InternalSpace.InternalToWorld(cameraRot * Quaternion.Euler(-90f, 0f, 0f));

            // DEBUG

            /*if (cameraGizmo == null) {
             *  cameraGizmo = Utils.CreateGizmo();
             *  cameraGizmo.transform.localScale = Vector3.one * 0.75f;
             *  DontDestroyOnLoad(cameraGizmo);
             * }
             * cameraGizmo.transform.position = cameraPos;
             * cameraGizmo.transform.rotation = cameraRot;*/
        }
Esempio n. 14
0
        public void LateUpdate()
        {
            if (Time.timeSinceLevelLoad < 2f || CameraManager.Instance == null)
            {
                return;
            }

            //If the Stock Overlay camera is not on or we are in flight cam mode.
            if (!StockOverlayCamIsOn && CameraManager.Instance.currentCameraMode == CameraManager.CameraMode.Flight)
            {
                //This is a bit of a performance hit, we are checking ALL loaded vessels to filter out NON JSIAdvTransparentPods.
                //PartstoFilterFromIVADict will contain all loaded vessels that are not JSIAdvTransparentPods, as well as any that are but are too far from the
                //camera or are set to auto or OFF.
                foreach (Vessel vsl in FlightGlobals.Vessels.Where(p => p.loaded))
                {
                    foreach (Part part in vsl.parts)
                    {
                        if (part.internalModel != null)
                        {
                            if (!part.Modules.Contains("JSIAdvTransparentPod"))
                            {
                                if (!PartstoFilterfromIVADict.Contains(part))
                                {
                                    PartstoFilterfromIVADict.Add(part);
                                }
                            }
                        }
                    }
                }

                //If the IVA and Main camera transforms are not null (should't be) position and rotate the IVACamera correctly.
                if (IVAcameraTransform != null && MaincameraTransform != null && InternalSpace.Instance != null)
                {
                    IVAcameraTransform.position = InternalSpace.WorldToInternal(MaincameraTransform.position);
                    IVAcameraTransform.rotation = InternalSpace.WorldToInternal(MaincameraTransform.rotation);
                    IVAcamera.fieldOfView       = Maincamera.fieldOfView;
                }
            }
        }
Esempio n. 15
0
        public override void OnUpdate()
        {
            // camera position/rotation in internal space
            // Vector3 internalCameraPos = Scene.Instance.HmdEyePosition[(int)EVREye.Eye_Right] + Scene.Instance.HmdEyeRotation[(int)EVREye.Eye_Right] * new Vector3(0f, 0f, 0.3f);
            Vector3 internalCameraPos = Scene.Instance.HmdEyePosition[(int)EVREye.Eye_Right];

            Quaternion internalCameraRot = Quaternion.LookRotation(viewfinderTransform.position -
                                                                   internalCameraPos, new Vector3(0f, 0f, -1f));

            // offset to the view position on the craft
            Vector3 offsetCameraPos = new Vector3(0f, 2f, 0f);

            internalCameraPos += offsetCameraPos;

            Vector3    worldCameraPos = InternalSpace.InternalToWorld(internalCameraPos);
            Quaternion worldCameraRot = InternalSpace.InternalToWorld(internalCameraRot);

            scopeCameraGameObject.transform.position = worldCameraPos;
            scopeCameraGameObject.transform.rotation = worldCameraRot;

            // crosshair positioning
            Vector3    crosshairRelPosition = new Vector3(0f, 0f, crosshairOffset);
            Vector3    crosshairPosition    = internalCameraPos + internalCameraRot * crosshairRelPosition;
            Quaternion crosshairRotation    = internalCameraRot * Quaternion.Euler(-90f, 0f, 0f);

            crosshair.transform.position = InternalSpace.InternalToWorld(crosshairPosition);
            crosshair.transform.rotation = InternalSpace.InternalToWorld(crosshairRotation);
            // crosshair.transform.position = InternalSpace.InternalToWorld(new Vector3(0f, 24f, 0f));
            // crosshair.transform.rotation = InternalSpace.InternalToWorld(Quaternion.Euler(180f, 0f, 0f));

            /*if (cameraGizmo == null) {
             *  cameraGizmo = Utils.CreateGizmo();
             *  cameraGizmo.transform.localScale = Vector3.one * 0.75f;
             *  DontDestroyOnLoad(cameraGizmo);
             * }
             * cameraGizmo.transform.position = internalCameraPos;
             * cameraGizmo.transform.rotation = internalCameraRot;*/
        }
Esempio n. 16
0
        // Old IVA cam updater. It takes exclusive control of the camera and doesn't reset on vehicle change.
        // It also needs to update rotation on EVERY Update() call or Squad will overwrite it before render.
        // Inspiration from: https://github.com/pizzaoverhead/KerbTrack/blob/master/KerbTrack/KerbTrack.cs#L402-459
        private void OldUpdateIVACamera(float camPitch, float camYaw, float camZoom, float camSensitivity)
        {
            float fovMaxIVA   = 90f;
            float fovMinIVA   = 10f;
            float pitchMaxIVA = 60f;
            float pitchMinIVA = -30f;
            float maxRot      = 60f;
            float IVAscale    = 10.0f;

            float pitchChange = Mathf.Clamp(camPitch * IVAscale * Time.deltaTime * 30f, pitchMinIVA, pitchMaxIVA);
            float yawChange   = Mathf.Clamp(camYaw * IVAscale * Time.deltaTime * 30f, -maxRot, maxRot);

            InternalCamera cam = InternalCamera.Instance;

            cam.transform.localRotation          *= Quaternion.Euler(-pitchChange, yawChange, 0);
            FlightCamera.fetch.transform.rotation = InternalSpace.InternalToWorld(cam.transform.rotation);
            Debug.Log("Cam rotation: " + cam.transform.localRotation.ToString());

            if (camZoom != 0)
            {
                // InternalCamera.Instance.SetFOV(Utility.Clamp(InternalCamera.Instance.camera.fieldOfView + camZoom * IVAscale, fovMinIVA, fovMaxIVA));
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Return a grid of points in the space
        /// </summary>
        /// <param name="step">Lenght between two points</param>
        public List <Point> Grid(double step)
        {
            step = UnitConverter.DynamoToHostFactor(DB.UnitType.UT_Length) * step;
            List <Point> grid = new List <Point>();

            DB.BoundingBoxXYZ bb = InternalElement.get_BoundingBox(null);

            for (double x = bb.Min.X; x < bb.Max.X;)
            {
                for (double y = bb.Min.Y; y < bb.Max.Y;)
                {
                    DB.XYZ point = new DB.XYZ(x, y, bb.Min.Z);
                    if (InternalSpace.IsPointInSpace(point))
                    {
                        grid.Add(GeometryPrimitiveConverter.ToPoint(InternalTransform.OfPoint(point)));
                    }
                    y = y + step;
                }

                x = x + step;
            }

            return(grid);
        }
Esempio n. 18
0
        private void UpdatePosition()
        {
            float moveForward = Input.GetKey(Settings.ForwardKey) ? Settings.ForwardSpeed * Time.deltaTime : 0;

            moveForward -= Input.GetKey(Settings.BackwardKey) ? Settings.ForwardSpeed * Time.deltaTime : 0;
            float moveRight = Input.GetKey(Settings.RightKey) ? Settings.HorizontalSpeed * Time.deltaTime : 0;

            moveRight -= Input.GetKey(Settings.LeftKey) ? Settings.HorizontalSpeed * Time.deltaTime : 0;
            float moveUp = Input.GetKey(Settings.UpKey) ? Settings.VerticalSpeed * Time.deltaTime : 0;

            moveUp -= Input.GetKey(Settings.DownKey) ? Settings.VerticalSpeed * Time.deltaTime : 0;
            Vector3 movement = new Vector3(moveRight, moveUp, moveForward);

            // Make the movement relative to the camera rotation.
            Vector3 newPos = KerbalIva.transform.localPosition + (InternalCamera.Instance.transform.localRotation * movement);

            //KerbalCollider.rigidbody.velocity = new Vector3(0, 0, 0);
            KerbalIva.GetComponentCached <Rigidbody>(ref KerbalRigidbody);
            KerbalRigidbody.MovePosition(newPos);

            // Jump. TODO: Detect when not in contact with the ground to prevent jetpacking (Physics.CapsuleCast).
            if (Input.GetKey(Settings.JumpKey))
            {
                // Jump in the opposite direction to gravity.
                KerbalRigidbody.AddForce(-InternalSpace.WorldToInternal(GetFlightForcesWorldSpace()) * Settings.JumpForce * Time.deltaTime);
            }

            FlightCamera.fetch.transform.position = InternalSpace.InternalToWorld(InternalCamera.Instance.transform.position);

#if Experimental
            // Move the world space collider.
            KerbalWorldSpaceCollider.GetComponentCached <Rigidbody>(ref KerbalWorldSpaceRigidbody);
            //KerbalWorldSpaceRigidbody.MovePosition(KerbalCollider.transform.localPosition);
            KerbalWorldSpaceRigidbody.MovePosition(InternalSpace.InternalToWorld(KerbalCollider.transform.localPosition));
#endif
        }
Esempio n. 19
0
        private static bool GameObjectBoundsCamera(GameObject go)
        {
            // The transform containing the mesh can be buried several levels deep.
            int childCount = go.transform.childCount;

            for (int i = 0; i < childCount; i++)
            {
                Transform child = go.transform.GetChild(i);
                if (child.name != "main camera pivot" && child.GetComponent <Part>() == null)
                {
                    GameObject   goc   = child.gameObject;
                    MeshFilter[] meshc = goc.GetComponents <MeshFilter>();
                    for (int m = 0; m < meshc.Length; m++)
                    {
                        Bounds meshBounds = meshc[m].mesh.bounds;
                        if (meshBounds != null)
                        {
                            Vector3 camPos = InternalSpace.InternalToWorld(InternalCamera.Instance.transform.position);
                            // Bounds are relative to the transform position, not the world.
                            camPos -= goc.transform.position;

                            if (meshBounds.Contains(camPos))
                            {
                                return(true);
                            }
                        }
                    }
                    bool foundGrandChild = GameObjectBoundsCamera(goc);
                    if (foundGrandChild)
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
Esempio n. 20
0
        private void ApplyGravity()
        {
            KerbalIva.GetComponentCached(ref KerbalRigidbody);
            if (Gravity)
            {
                Vector3 gForce           = FlightGlobals.getGeeForceAtPosition(KerbalIva.transform.position);
                Vector3 centrifugalForce = FlightGlobals.getCentrifugalAcc(KerbalIva.transform.position, FreeIva.CurrentPart.orbit.referenceBody);
                Vector3 coriolisForce    = FlightGlobals.getCoriolisAcc(FreeIva.CurrentPart.vessel.rb_velocity + Krakensbane.GetFrameVelocityV3f(), FreeIva.CurrentPart.orbit.referenceBody);

                gForce           = InternalSpace.WorldToInternal(gForce);
                centrifugalForce = InternalSpace.WorldToInternal(centrifugalForce);
                coriolisForce    = InternalSpace.WorldToInternal(coriolisForce);
                flightForces     = gForce + centrifugalForce + coriolisForce;

                KerbalRigidbody.AddForce(gForce, ForceMode.Acceleration);
                KerbalRigidbody.AddForce(centrifugalForce, ForceMode.Acceleration);
                KerbalRigidbody.AddForce(coriolisForce, ForceMode.Acceleration);
                KerbalRigidbody.AddForce(Krakensbane.GetLastCorrection(), ForceMode.VelocityChange);

                if (FreeIva.SelectedObject != null)
                {
                    Rigidbody rbso = FreeIva.SelectedObject.GetComponent <Rigidbody>();
                    if (rbso == null)
                    {
                        rbso = FreeIva.SelectedObject.AddComponent <Rigidbody>();
                    }
                    rbso.AddForce(gForce, ForceMode.Acceleration);
                    rbso.AddForce(centrifugalForce, ForceMode.Acceleration);
                    rbso.AddForce(coriolisForce, ForceMode.Acceleration);
                }
            }
            else
            {
                KerbalRigidbody.velocity = Vector3.zero;
            }
        }
        public void cameraRotationCallback(byte ID, object Data)
        {
            //Debug.Log("Camera Rotation Callback");
            newCameraRotation = KerbalSimpitUtils.ByteArrayToStructure <CameraRotationalStruct>((byte[])Data);
            // Bit fields:
            // pitch = 1
            // roll = 2
            // yaw = 4
            switch (cameraManager.currentCameraMode)
            {
            case CameraManager.CameraMode.Flight:
                FlightCamera flightCamera = FlightCamera.fetch;
                if ((newCameraRotation.mask & (byte)1) > 0)
                {
                    myCameraRotation.pitch = newCameraRotation.pitch;
                    // Debug.Log("Rotation Message Seen");
                    float newPitch = flightCamera.camPitch + (myCameraRotation.pitch * flightCameraPitchMultiplier);
                    if (newPitch > flightCamera.maxPitch)
                    {
                        flightCamera.camPitch = flightCamera.maxPitch;
                    }
                    else if (newPitch < flightCamera.minPitch)
                    {
                        flightCamera.camPitch = flightCamera.minPitch;
                    }
                    else
                    {
                        flightCamera.camPitch = newPitch;
                    }
                }
                if ((newCameraRotation.mask & (byte)2) > 0)
                {
                    myCameraRotation.roll = newCameraRotation.roll;
                }
                if ((newCameraRotation.mask & (byte)4) > 0)
                {
                    myCameraRotation.yaw = newCameraRotation.yaw;
                    // Debug.Log("Yaw Message Seen");
                    float newHdg = flightCamera.camHdg + (myCameraRotation.yaw * flightCameraYawMultiplier);
                    flightCamera.camHdg = newHdg;
                }
                if ((newCameraRotation.mask & (byte)8) > 0)
                {
                    myCameraRotation.zoom = newCameraRotation.zoom;
                    float newZoom = flightCamera.Distance + (myCameraRotation.zoom * flightCameraZoomMultiplier);
                    if (newZoom > flightCamera.maxDistance)
                    {
                        newZoom = flightCamera.maxDistance;
                    }
                    else if (newZoom < flightCamera.minDistance)
                    {
                        newZoom = flightCamera.minDistance;
                    }
                    flightCamera.SetDistance(newZoom);
                }
                break;

            case CameraManager.CameraMode.IVA:
            case CameraManager.CameraMode.Internal:
                Kerbal ivaKerbal = cameraManager.IVACameraActiveKerbal;

                if (ivaKerbal == null)
                {
                    Debug.Log("Kerbal is null");
                }

                InternalCamera ivaCamera = InternalCamera.Instance;
                ivaCamera.mouseLocked = false;

                if (ivaCamera == null)
                {
                    Debug.Log("IVA Camera is null");
                }
                else
                {
                    float newPitch = (float)ivaPitchField.GetValue(ivaCamera);
                    float newYaw   = (float)ivaYawField.GetValue(ivaCamera);

                    if ((newCameraRotation.mask & (byte)1) > 0)
                    {
                        myCameraRotation.pitch = newCameraRotation.pitch;
                        //Debug.Log("IVA Rotation Message Seen");
                        newPitch += (myCameraRotation.pitch * ivaCameraMultiplier);

                        if (newPitch > ivaCamera.maxPitch)
                        {
                            newPitch = ivaCamera.maxPitch;
                        }
                        else if (newPitch < ivaCamera.minPitch)
                        {
                            newPitch = ivaCamera.minPitch;
                        }
                    }
                    if ((newCameraRotation.mask & (byte)2) > 0)
                    {
                        myCameraRotation.roll = newCameraRotation.roll;
                    }
                    if ((newCameraRotation.mask & (byte)4) > 0)
                    {
                        myCameraRotation.yaw = newCameraRotation.yaw;
                        //Debug.Log("IVA Yaw Message Seen");
                        newYaw += (myCameraRotation.yaw * ivaCameraMultiplier);
                        if (newYaw > 120f)
                        {
                            newYaw = 120f;
                        }
                        else if (newYaw < -120f)
                        {
                            newYaw = -120f;
                        }
                    }
                    //Debug.Log("Before set angle");
                    if (this.ivaCamFieldsLoaded)
                    {
                        ivaPitchField.SetValue(ivaCamera, newPitch);
                        ivaYawField.SetValue(ivaCamera, newYaw);
                        // Debug.Log("Camera vector: " + ivaCamera.transform.localEulerAngles.ToString());
                        FlightCamera.fetch.transform.rotation = InternalSpace.InternalToWorld(InternalCamera.Instance.transform.rotation);
                    }
                }
                break;

            default:
                Debug.Log("Kerbal Simpit does not support this camera mode: " + cameraManager.currentCameraMode.ToString());
                break;
            }
        }
        public void Update()
        {
            if (Time.timeSinceLevelLoad < 1f)
            {
                return;
            }

            // In the editor, none of this logic should matter, even though the IVA probably exists already.
            if (HighLogic.LoadedSceneIsEditor && !disableLoadingInEditor)
            {
                if (transparentPodSetting == "ON" || (transparentPodSetting == "AUTO" && mouseOver))
                {
                    // Make the internal model visible...
                    if (part.internalModel != null)
                    {
                        part.internalModel.SetVisible(true);
                    }
                    // And for a good measure we make sure the shader change has been applied.
                    SetShaders(true);
                    // Now we attach the restored IVA directly into the pod at zero local coordinates and rotate it,
                    // so that it shows up on the main outer view camera in the correct location.
                    VoodooRotate();
                    setVisible = true;
                    //if (JSIZfighterStock != null)
                    //    JSIZfighterStock.Update(stockOverlayTransform);
                    //if (JSIZfightertransparent != null)
                    //    JSIZfightertransparent.Update(transparentPodTransform);
                }

                // If we are in editor mode we need to turn off the internal if the internal is in OFF or AUTO mode and not moused over.
                //Otherwise we make it visible.
                if (transparentPodSetting == "OFF" || (transparentPodSetting == "AUTO" && !mouseOver))
                {
                    // Make the internal model Invisible...
                    if (part.internalModel != null)
                    {
                        part.internalModel.SetVisible(false);
                    }
                    SetShaders(false);
                    setVisible = false;
                }

                JSIAdvPodsUtil.Log_Debug("Part {0} : Layer {1}", part.name, part.gameObject.layer);

                //Turn the DepthMasks off in the Editor or we get Z-Fighting.
                SetDepthMask();
            }
            if (HighLogic.LoadedSceneIsFlight)
            {
                //Now FlightScene Processing

                //IVA OBstruction process of the transparentPodSetting field
                //If previously IVA was obstructed and now it is not reset the transparentPodSetting back to it's previous value.
                if (previsIVAobstructed && !isIVAobstructed)
                {
                    transparentPodSetting                    = prevtransparentPodSetting;
                    displaytransparentPodSetting             = prevdisplaytransparentPodSetting;
                    Events["eventToggleTransparency"].active = true;
                }
                previsIVAobstructed = isIVAobstructed;
                //isIVAobstructed = false;

                // If the root part changed, or the IVA is mysteriously missing, we reset it and take note of where it ended up.
                if (vessel.rootPart != knownRootPart || lastActiveVessel != FlightGlobals.ActiveVessel || part.internalModel == null)
                {
                    ResetIVA();
                }

                // So we do have an internal model, right?
                if (part.internalModel != null)
                {
                    // If transparentPodSetting = OFF or AUTO and not the focused active part we treat the part like a non-transparent part.
                    // and we turn off the shaders (if set) and the internal to the filter list and exit OnUpdate.
                    if (transparentPodSetting == "OFF" || (transparentPodSetting == "AUTO" && !mouseOver) && !isIVAobstructed)
                    {
                        SetShaders(false);
                        if (!JSIAdvTransparentPods.PartstoFilterfromIVADict.Contains(part))
                        {
                            JSIAdvTransparentPods.PartstoFilterfromIVADict.Add(part);
                        }
                        setVisible = false;
                        return;
                    }

                    //If we are in flight and the user has the Stock Overlay on and this part is not part of the active vessel we turn off the internal.
                    // also if the user has set the LoadedInactive to False - we don't show TransparentPods that aren't on the active vessel.
                    // We turn it off rather than registering it for the PreCull list because if Stock Overlay is on the JSI camera is not active.
                    if (!vessel.isActiveVessel &&
                        (JSIAdvPodsUtil.StockOverlayCamIsOn || !LoadGlobals.Instance.LoadedInactive))
                    {
                        part.internalModel.SetVisible(false);
                        setVisible = false;
                        SetShaders(false);
                        JSIAdvPodsUtil.Log_Debug(
                            "Internal turned off as vessel is Not Active Vessel and stock overlay is on or LoadedInactive is False: ({0}) {1}",
                            part.craftID, vessel.vesselName);
                        return;
                    }

                    if (!vessel.isActiveVessel)
                    {
                        //For some reason (probably performance) Squad do not actively update the position and rotation of InternalModels that are not part of the active vessel.
                        //Calculate the Vessel position and rotation and then apply that to the InternalModel position and rotation with the MagicalVoodooRotation.
                        Vector3 VesselPosition = part.vessel.transform.position +
                                                 part.vessel.transform.rotation * part.orgPos;
                        part.internalModel.transform.position = InternalSpace.WorldToInternal(VesselPosition);
                        Quaternion VesselRotation = part.vessel.transform.rotation * part.orgRot;
                        part.internalModel.transform.rotation = InternalSpace.WorldToInternal(VesselRotation) *
                                                                MagicalVoodooRotation;

                        // If the current part is not part of the active vessel, we calculate the distance from the part to the flight camera.
                        // If this distance is > distanceToCameraThreshold metres we turn off transparency for the part.
                        // Uses Maths calcs intead of built in Unity functions as this is up to 5 times faster.
                        Vector3   heading;
                        Transform thisPart     = part.transform;
                        Transform flightCamera = FlightCamera.fetch.transform;
                        heading.x = thisPart.position.x - flightCamera.position.x;
                        heading.y = thisPart.position.y - flightCamera.position.y;
                        heading.z = thisPart.position.z - flightCamera.position.z;
                        var distanceSquared = heading.x * heading.x + heading.y * heading.y + heading.z * heading.z;
                        distanceToCamera = Mathf.Sqrt(distanceSquared);

                        if (distanceToCamera > distanceToCameraThreshold)
                        {
                            SetShaders(false);
                            //part.internalModel.SetVisible(false);
                            if (!JSIAdvTransparentPods.PartstoFilterfromIVADict.Contains(part))
                            {
                                JSIAdvTransparentPods.PartstoFilterfromIVADict.Add(part);
                            }
                            setVisible = false;
                            return;
                        }
                    }

                    //If inactive vessel IVAs are turned on via the settings then we:
                    //Check for obstructions between this IVA and the Camera that may be on lower layers and turn off the IVA if there is one.
                    //Not a perfect solution..... and bad performance-wise.
                    if (LoadGlobals.Instance.LoadedInactive)
                    {
                        if (JSIAdvTransparentPods.Instance != null &&
                            CameraManager.Instance.currentCameraMode == CameraManager.CameraMode.Flight)
                        {
                            if (JSIAdvTransparentPods.Instance.MaincameraTransform != null)
                            {
                                isIVAobstructed = IsIVAObstructed(part.transform, JSIAdvTransparentPods.Instance.MaincameraTransform);
                                if (isIVAobstructed)
                                {
                                    if (!JSIAdvTransparentPods.PartstoFilterfromIVADict.Contains(part))
                                    {
                                        JSIAdvTransparentPods.PartstoFilterfromIVADict.Add(part);
                                    }
                                    SetShaders(false);
                                    setVisible = false;
                                    //Set the prevtransparentPodSetting to the current transparentPodSetting and then set transparenPodSetting to "OFF"
                                    if (!previsIVAobstructed)
                                    {
                                        Events["eventToggleTransparency"].active = false;
                                        prevtransparentPodSetting        = transparentPodSetting;
                                        prevdisplaytransparentPodSetting = displaytransparentPodSetting;
                                        transparentPodSetting            = "Obstructed";
                                        displaytransparentPodSetting     = transparentPodSetting;
                                    }
                                    return;
                                }
                            }
                        }
                    }

                    // Make the internal model visible...
                    // And for a good measure we make sure the shader change has been applied.
                    SetShaders(true);
                    if (JSIAdvTransparentPods.PartstoFilterfromIVADict.Contains(part))
                    {
                        JSIAdvTransparentPods.PartstoFilterfromIVADict.Remove(part);
                    }
                    setVisible = true;
                    part.internalModel.SetVisible(true);
                }
                else
                {
                    JSIAdvPodsUtil.Log("Where is my Internal model for : {0}", part.craftID);
                }
            }
        }
Esempio n. 23
0
            void OnPreRender()
            {
                if (!gotPoses && HmdOn)
                {
                    Part hoveredPart = Mouse.HoveredPart;
                    if (hoveredPart != null)
                    {
                        hoveredPart.HighlightActive = false;
                    }

                    lock (KerbalVRPlugin.hmdRightEyeRenderTexture) lock (KerbalVRPlugin.hmdLeftEyeRenderTexture)
                        {
                            //check if active kerbal changed
                            if (CameraManager.Instance.currentCameraMode.Equals(CameraManager.CameraMode.IVA) && CameraManager.Instance.IVACameraActiveKerbalIndex != lastKerbalID)
                            {
                                //reenable last kerbal
                                activeKerbal.SetVisibleInPortrait(true);
                                activeKerbal.gameObject.active = true;

                                activeKerbal = CameraManager.Instance.IVACameraActiveKerbal;
                                lastKerbalID = CameraManager.Instance.IVACameraActiveKerbalIndex;

                                //deactivate curent kerbal
                                activeKerbal.SetVisibleInPortrait(false);
                                activeKerbal.gameObject.active = false;
                            }

                            gotPoses = true;

                            EVRCompositorError vrCompositorError = EVRCompositorError.None;

                            //get poses from VR api
                            vrSystem.GetDeviceToAbsoluteTrackingPose(ETrackingUniverseOrigin.TrackingUniverseSeated, predict, vrDevicePoses);
                            HmdMatrix34_t vrLeftEyeTransform  = vrSystem.GetEyeToHeadTransform(EVREye.Eye_Left);
                            HmdMatrix34_t vrRightEyeTransform = vrSystem.GetEyeToHeadTransform(EVREye.Eye_Right);
                            vrCompositorError      = vrCompositor.WaitGetPoses(vrRenderPoses, vrGamePoses);
                            RenderSlave.leftReady  = false;
                            RenderSlave.rightReady = false;
                            if (vrCompositorError != EVRCompositorError.None)
                            {
                                KerbalVRPlugin.warn("WaitGetPoses failed: " + vrCompositorError.ToString());
                            }

                            // convert SteamVR poses to Unity coordinates
                            hmdTransform         = new Utils.RigidTransform(vrDevicePoses[OpenVR.k_unTrackedDeviceIndex_Hmd].mDeviceToAbsoluteTracking);
                            hmdLeftEyeTransform  = new Utils.RigidTransform(vrLeftEyeTransform);
                            hmdRightEyeTransform = new Utils.RigidTransform(vrRightEyeTransform);
                            ctrlPoseLeft         = new Utils.RigidTransform(vrDevicePoses[ctrlIndexLeft].mDeviceToAbsoluteTracking);
                            ctrlPoseRight        = new Utils.RigidTransform(vrDevicePoses[ctrlIndexRight].mDeviceToAbsoluteTracking);


                            //calculate corect position acording to vessel orientation
                            hmdTransform.rot = (O_Interior.transform.rotation) * hmdTransform.rot;
                            hmdTransform.pos = (O_Interior.transform.rotation) * hmdTransform.pos + O_Interior.transform.position;

                            //shema:
                            //rotate Camera acording to Hmd rotation
                            //reset local position
                            //set new local position acording to eye position
                            //add position of hmd

                            //internal camera has no special transformations
                            camLeft_Interior.transform.localRotation = hmdTransform.rot;
                            camLeft_Interior.transform.localPosition = new Vector3(0f, 0f, 0f);
                            camLeft_Interior.transform.Translate(hmdLeftEyeTransform.pos);
                            camLeft_Interior.transform.localPosition += hmdTransform.pos;

                            camRight_Interior.transform.localRotation = hmdTransform.rot;
                            camRight_Interior.transform.localPosition = new Vector3(0f, 0f, 0f);
                            camRight_Interior.transform.Translate(hmdRightEyeTransform.pos);
                            camRight_Interior.transform.localPosition += hmdTransform.pos;

                            //rotations and positions for all following cameras are converted from internal to wolrd space:
                            camLeft_Near.transform.localRotation = InternalSpace.InternalToWorld(hmdTransform.rot);
                            camLeft_Near.transform.localPosition = new Vector3(0f, 0f, 0f);
                            camLeft_Near.transform.Translate(hmdLeftEyeTransform.pos);
                            camLeft_Near.transform.localPosition += InternalSpace.InternalToWorld(hmdTransform.pos);

                            camRight_Near.transform.localRotation = InternalSpace.InternalToWorld(hmdTransform.rot);
                            camRight_Near.transform.localPosition = new Vector3(0f, 0f, 0f);
                            camRight_Near.transform.Translate(hmdRightEyeTransform.pos);
                            camRight_Near.transform.localPosition += InternalSpace.InternalToWorld(hmdTransform.pos);

                            camLeft_Far.transform.localRotation = InternalSpace.InternalToWorld(hmdTransform.rot);
                            camLeft_Far.transform.localPosition = new Vector3(0f, 0f, 0f);
                            camLeft_Far.transform.Translate(hmdLeftEyeTransform.pos);
                            camLeft_Far.transform.localPosition += InternalSpace.InternalToWorld(hmdTransform.pos);

                            camRight_Far.transform.localRotation = InternalSpace.InternalToWorld(hmdTransform.rot);
                            camRight_Far.transform.localPosition = new Vector3(0f, 0f, 0f);
                            camRight_Far.transform.Translate(hmdRightEyeTransform.pos);
                            camRight_Far.transform.localPosition += InternalSpace.InternalToWorld(hmdTransform.pos);

                            //the sky and star Cameras are in ScaledSpace so the vectors have to be scaled down
                            leftSky.transform.localRotation = InternalSpace.InternalToWorld(hmdTransform.rot);
                            leftSky.transform.localPosition = new Vector3(0f, 0f, 0f);
                            leftSky.transform.Translate(hmdLeftEyeTransform.pos * ScaledSpace.InverseScaleFactor);
                            leftSky.transform.localPosition += (hmdTransform.pos * ScaledSpace.InverseScaleFactor);

                            rightSky.transform.localRotation = InternalSpace.InternalToWorld(hmdTransform.rot);
                            rightSky.transform.localPosition = new Vector3(0f, 0f, 0f);
                            rightSky.transform.Translate(hmdRightEyeTransform.pos * ScaledSpace.InverseScaleFactor);
                            rightSky.transform.localPosition += (hmdTransform.pos * ScaledSpace.InverseScaleFactor);

                            leftStars.transform.localRotation = InternalSpace.InternalToWorld(hmdTransform.rot);
                            leftStars.transform.localPosition = new Vector3(0f, 0f, 0f);
                            leftStars.transform.Translate(hmdLeftEyeTransform.pos * ScaledSpace.InverseScaleFactor);
                            leftStars.transform.localPosition += InternalSpace.InternalToWorld(hmdTransform.pos * ScaledSpace.InverseScaleFactor);

                            rightStars.transform.localRotation = InternalSpace.InternalToWorld(hmdTransform.rot);
                            rightStars.transform.localPosition = new Vector3(0f, 0f, 0f);
                            rightStars.transform.Translate(hmdRightEyeTransform.pos * ScaledSpace.InverseScaleFactor);
                            rightStars.transform.localPosition += InternalSpace.InternalToWorld(hmdTransform.pos * ScaledSpace.InverseScaleFactor);
                        }
                }
            }
Esempio n. 24
0
        private void UpdateFlightIvaScene(
            EVREye eye,
            SteamVR_Utils.RigidTransform hmdTransform,
            SteamVR_Utils.RigidTransform hmdEyeTransform)
        {
            // in flight, don't allow movement of the origin point
            CurrentPosition = InitialPosition;
            CurrentRotation = InitialRotation;

            // get position of your eyeball
            Vector3 positionToHmd = hmdTransform.pos;
            Vector3 positionToEye = hmdTransform.pos + hmdTransform.rot * hmdEyeTransform.pos;

            // translate device space to Unity space, with world scaling
            Vector3    updatedPosition = DevicePoseToWorld(positionToEye);
            Quaternion updatedRotation = DevicePoseToWorld(hmdTransform.rot);

            var worldPos = InternalSpace.InternalToWorld(updatedPosition);
            var worldRot = InternalSpace.InternalToWorld(updatedRotation);

            // in flight, update the internal and flight cameras
            var ic = InternalCamera.Instance;

            if (ic != null)
            {
                ic.transform.position = updatedPosition;
                ic.transform.rotation = updatedRotation;
            }

            var fc = FlightCamera.fetch;

            if (fc != null)
            {
                fc.transform.position = worldPos;
                fc.transform.rotation = worldRot;
            }


            var fx = FXCamera.Instance;

            if (fx != null)
            {
                fx.transform.position = worldPos;
                fx.transform.rotation = worldRot;
            }

            var gc = GalaxyCameraControl.Instance;

            if (gc != null)
            {
                gc.transform.rotation = worldRot;
            }

            var sc = ScaledCamera.Instance;

            if (sc != null)
            {
                sc.transform.rotation = worldRot;
            }

            if (galaxyCam == null)
            {
                galaxyCam = GameObject.Find("GalaxyCamera");
            }
            if (galaxyCam != null)
            {
                galaxyCam.transform.rotation = worldRot;
            }

            // store the eyeball position
            HmdEyePosition[(int)eye] = updatedPosition;
            HmdEyeRotation[(int)eye] = updatedRotation;
        }
        public void LateUpdate()
        {
            if (Time.timeSinceLevelLoad < 2f)
            {
                return;
            }

            //Reset the mouseOver flag.
            mouseOver = false;

            //In editor Logic
            if (HighLogic.LoadedSceneIsEditor)
            {
                // If we are in editor mode we need to turn off the internal if the internal is in OFF or AUTO mode and not moused over.
                //Otherwise we make it visible.
                if (transparentPodSetting == "OFF" || (transparentPodSetting == "AUTO" && !mouseOver))
                {
                    SetShaders(false);
                    if (part.internalModel != null)
                    {
                        part.internalModel.SetVisible(false);
                    }
                    setVisible = false;
                }
                else
                {
                    SetShaders(true);
                    if (part.internalModel != null)
                    {
                        part.internalModel.SetVisible(true);
                    }
                    setVisible = true;
                }
                //For some reason we need to keep turning off the Renderers with the DepthMask Shader.. Because setting the
                //activated.
                if (part.internalModel != null)
                {
                    foreach (Renderer renderer in part.internalModel.GetComponentsInChildren <Renderer>(true))
                    {
                        if (renderer.material.shader == DepthMaskShader)
                        {
                            renderer.enabled          = false;
                            renderer.gameObject.layer = 29;
                        }
                    }
                }
            }

            //In flight logic.
            //If we are in flight and the user has the Stock Overlay on and this part is not part of the active vessel we turn off the internal.
            // also if the user has set the LoadedInactive to true - we don't show TransparentPods that aren't on the active vessel.
            // We turn it off rather than registering it for the PreCull list because if Stock Overlay is on the JSI camera is not active.
            if (HighLogic.LoadedSceneIsFlight && CameraManager.Instance != null && InternalSpace.Instance != null)
            {
                if (!vessel.isActiveVessel && (JSIAdvTransparentPods.Instance.StockOverlayCamIsOn || LoadGlobals.settings.LoadedInactive))
                {
                    if (part.internalModel != null)
                    {
                        part.internalModel.SetVisible(false);
                    }
                    setVisible = false;
                    SetShaders(false);
                    CheckStowaways();
                    JSIAdvTPodsUtil.Log_Debug("Internal turned off as stockoverlay is on and part is not in active vessel : ({0}) {1}", part.craftID, vessel.vesselName);
                    return;
                }
                //Finally we check for Stowaways on the PortraitCams
                CheckStowaways();

                //For some reason (probably performance) Squad do not actively update the position and rotation of InternalModels that are not part of the active vessel.
                if (!vessel.isActiveVessel)
                {
                    //Calculate the Vessel position and rotation and then apply that to the InternalModel position and rotation with the MagicalVoodooRotation.
                    Vector3 VesselPosition = part.vessel.transform.position + part.vessel.transform.rotation * part.orgPos;
                    if (part.internalModel != null)
                    {
                        part.internalModel.transform.position = InternalSpace.WorldToInternal(VesselPosition);
                        Quaternion VesselRotation = part.vessel.transform.rotation * part.orgRot;
                        part.internalModel.transform.rotation = InternalSpace.WorldToInternal(VesselRotation) * MagicalVoodooRotation;
                    }
                }
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Overrides the Update method, called every frame.
        /// </summary>
        void LateUpdate()
        {
            try
            {
                // do nothing unless we are in IVA
                hmdIsAllowed = (CameraManager.Instance.currentCameraMode == CameraManager.CameraMode.IVA);

                // start HMD using the Y key
                if (Input.GetKeyDown(KeyCode.Y) && hmdIsAllowed)
                {
                    if (!hmdIsInitialized)
                    {
                        log("Initializing HMD...");
                        try
                        {
                            bool retVal = InitHMD();
                            if (retVal)
                            {
                                log("HMD initialized.");
                            }
                        }
                        catch (Exception e)
                        {
                            err(e.Message);
                        }
                    }
                    else
                    {
                        ResetInitialHmdPosition();
                    }
                }

                // perform regular updates if HMD is initialized
                if (hmdIsAllowed && hmdIsInitialized)
                {
                    EVRCompositorError vrCompositorError = EVRCompositorError.None;

                    // get latest HMD pose
                    //--------------------------------------------------------------
                    vrSystem.GetDeviceToAbsoluteTrackingPose(ETrackingUniverseOrigin.TrackingUniverseSeated, 0.0f, vrDevicePoses);
                    HmdMatrix34_t vrLeftEyeTransform  = vrSystem.GetEyeToHeadTransform(EVREye.Eye_Left);
                    HmdMatrix34_t vrRightEyeTransform = vrSystem.GetEyeToHeadTransform(EVREye.Eye_Right);
                    vrCompositorError = vrCompositor.WaitGetPoses(vrRenderPoses, vrGamePoses);

                    if (vrCompositorError != EVRCompositorError.None)
                    {
                        warn("WaitGetPoses failed: " + (int)vrCompositorError);
                        return;
                    }

                    // convert SteamVR poses to Unity coordinates
                    var hmdTransform         = new SteamVR_Utils.RigidTransform(vrDevicePoses[OpenVR.k_unTrackedDeviceIndex_Hmd].mDeviceToAbsoluteTracking);
                    var hmdLeftEyeTransform  = new SteamVR_Utils.RigidTransform(vrLeftEyeTransform);
                    var hmdRightEyeTransform = new SteamVR_Utils.RigidTransform(vrRightEyeTransform);
                    var ctrlPoseLeft         = new SteamVR_Utils.RigidTransform(vrDevicePoses[ctrlIndexLeft].mDeviceToAbsoluteTracking);
                    var ctrlPoseRight        = new SteamVR_Utils.RigidTransform(vrDevicePoses[ctrlIndexRight].mDeviceToAbsoluteTracking);



                    // Render the LEFT eye
                    //--------------------------------------------------------------
                    // rotate camera according to the HMD orientation
                    InternalCamera.Instance.transform.localRotation = hmdTransform.rot;

                    // translate the camera to match the position of the left eye, from origin
                    InternalCamera.Instance.transform.localPosition = new Vector3(0f, 0f, 0f);
                    InternalCamera.Instance.transform.Translate(hmdLeftEyeTransform.pos);

                    // translate the camera to match the position of the HMD
                    InternalCamera.Instance.transform.localPosition += hmdTransform.pos;

                    // move the FlightCamera to match the position of the InternalCamera (so the outside world moves accordingly)
                    FlightCamera.fetch.transform.position = InternalSpace.InternalToWorld(InternalCamera.Instance.transform.position);
                    FlightCamera.fetch.transform.rotation = InternalSpace.InternalToWorld(InternalCamera.Instance.transform.rotation);

                    // render the set of cameras
                    foreach (CameraProperties camStruct in camerasToRender)
                    {
                        // set projection matrix
                        camStruct.camera.projectionMatrix = camStruct.hmdLeftProjMatrix;

                        // set texture to render to
                        camStruct.camera.targetTexture = hmdLeftEyeRenderTexture;

                        // render camera
                        camStruct.camera.Render();
                    }


                    // Render the RIGHT eye (see previous comments)
                    //--------------------------------------------------------------
                    InternalCamera.Instance.transform.localRotation = hmdTransform.rot;
                    InternalCamera.Instance.transform.localPosition = new Vector3(0f, 0f, 0f);
                    InternalCamera.Instance.transform.Translate(hmdRightEyeTransform.pos);
                    InternalCamera.Instance.transform.localPosition += hmdTransform.pos;
                    FlightCamera.fetch.transform.position            = InternalSpace.InternalToWorld(InternalCamera.Instance.transform.position);
                    FlightCamera.fetch.transform.rotation            = InternalSpace.InternalToWorld(InternalCamera.Instance.transform.rotation);

                    foreach (CameraProperties camStruct in camerasToRender)
                    {
                        camStruct.camera.projectionMatrix = camStruct.hmdRightProjMatrix;
                        camStruct.camera.targetTexture    = hmdRightEyeRenderTexture;
                        camStruct.camera.Render();
                    }

                    try
                    {
                        // Set camera position to an HMD-centered position (for regular screen rendering)
                        //--------------------------------------------------------------
                        if (renderToScreen)
                        {
                            foreach (CameraProperties camStruct in camerasToRender)
                            {
                                camStruct.camera.targetTexture    = null;
                                camStruct.camera.projectionMatrix = camStruct.originalProjMatrix;
                            }
                            InternalCamera.Instance.transform.localRotation = hmdTransform.rot;
                            InternalCamera.Instance.transform.localPosition = hmdTransform.pos;
                            FlightCamera.fetch.transform.position           = InternalSpace.InternalToWorld(InternalCamera.Instance.transform.position);
                            FlightCamera.fetch.transform.rotation           = InternalSpace.InternalToWorld(InternalCamera.Instance.transform.rotation);
                        }


                        // Submit frames to HMD
                        //--------------------------------------------------------------
                        vrCompositorError = vrCompositor.Submit(EVREye.Eye_Left, ref hmdLeftEyeTexture, ref hmdTextureBounds, EVRSubmitFlags.Submit_Default);
                        if (vrCompositorError != EVRCompositorError.None)
                        {
                            warn("Submit (Eye_Left) failed: " + (int)vrCompositorError);
                        }

                        vrCompositorError = vrCompositor.Submit(EVREye.Eye_Right, ref hmdRightEyeTexture, ref hmdTextureBounds, EVRSubmitFlags.Submit_Default);
                        if (vrCompositorError != EVRCompositorError.None)
                        {
                            warn("Submit (Eye_Right) failed: " + (int)vrCompositorError);
                        }

                        vrCompositor.PostPresentHandoff();

                        //  GL.Flush();
                    } catch (Exception e)
                    {
                        err("Exception! " + e.ToString());
                    }

                    // disable highlighting of parts due to mouse
                    // TODO: there needs to be a better way to do this. this affects the Part permanently
                    Part hoveredPart = Mouse.HoveredPart;
                    if (hoveredPart != null)
                    {
                        hoveredPart.HighlightActive  = false;
                        hoveredPart.highlightColor.a = 0f;// = new Color(0f, 0f, 0f, 0f);
                        //Debug.Log("[KerbalVR] hovered part: " + hoveredPart.name);
                    }


                    // DEBUG
                    if (Input.GetKeyDown(KeyCode.O))
                    {
                        log("POSITION hmdTransform : " + hmdTransform.pos.x + ", " + hmdTransform.pos.y + ", " + hmdTransform.pos.z);
                        log("POSITION hmdLTransform : " + hmdLeftEyeTransform.pos.x + ", " + hmdLeftEyeTransform.pos.y + ", " + hmdLeftEyeTransform.pos.z);
                        log("POSITION hmdRTransform : " + hmdRightEyeTransform.pos.x + ", " + hmdRightEyeTransform.pos.y + ", " + hmdRightEyeTransform.pos.z);
                        log("POSITION ctrlPoseRight : " + ctrlPoseRight.pos.x + ", " + ctrlPoseRight.pos.y + ", " + ctrlPoseRight.pos.z);

                        log("POSITION InternalCamera.Instance.transform.abs : " + InternalCamera.Instance.transform.position.x + ", " + InternalCamera.Instance.transform.position.y + ", " + InternalCamera.Instance.transform.position.z);
                        log("POSITION InternalCamera.Instance.transform.rel : " + InternalCamera.Instance.transform.localPosition.x + ", " + InternalCamera.Instance.transform.localPosition.y + ", " + InternalCamera.Instance.transform.localPosition.z);

                        foreach (Camera c in Camera.allCameras)
                        {
                            log("Camera: " + c.name + ", cullingMask = " + c.cullingMask);
                        }
                    }
                }

                // if we are exiting VR, restore the cameras
                if (!hmdIsAllowed && hmdIsAllowed_prev)
                {
                    foreach (CameraProperties camStruct in camerasToRender)
                    {
                        camStruct.camera.projectionMatrix = camStruct.originalProjMatrix;
                        camStruct.camera.targetTexture    = null;
                    }
                }

                hmdIsAllowed_prev = hmdIsAllowed;
            }
            catch (Exception e)
            {
                err(e.ToString());
            }
        }
        public override void OnUpdate()
        {
            if (Time.timeSinceLevelLoad < 2f)
            {
                return;
            }

            // In the editor, none of this logic should matter, even though the IVA probably exists already.
            if (HighLogic.LoadedSceneIsEditor)
            {
                // Make the internal model visible...
                part.internalModel.SetVisible(true);
                // And for a good measure we make sure the shader change has been applied.
                SetShaders(true);
                // Now we attach the restored IVA directly into the pod at zero local coordinates and rotate it,
                // so that it shows up on the main outer view camera in the correct location.
                VoodooRotate();
                setVisible = true;
                return;
            }

            //Now FlightScene Processing

            // If the root part changed, or the IVA is mysteriously missing, we reset it and take note of where it ended up.
            if (vessel.rootPart != knownRootPart || lastActiveVessel != FlightGlobals.ActiveVessel || part.internalModel == null)
            {
                ResetIVA();
            }

            // If transparentPodSetting = OFF or AUTO and not the focused active part we treat the part like a non-transparent part.
            // and we turn off the shaders (if set) and the internal to the filter list and exit OnUpdate.
            if (transparentPodSetting == "OFF" || (transparentPodSetting == "AUTO" && !mouseOver))
            {
                SetShaders(false);
                //part.internalModel.SetVisible(false);
                if (!JSIAdvTransparentPods.Instance.PartstoFilterfromIVADict.Contains(part))
                {
                    JSIAdvTransparentPods.Instance.PartstoFilterfromIVADict.Add(part);
                }
                setVisible = false;
                return;
            }

            //If we are in IVA mode or If the camera is not in flight mode or PArt is not part of ActiveVessel and user has set LoadedInactive to true we go no further.
            if (JSIAdvTPodsUtil.IsInIVA() || CameraManager.Instance.currentCameraMode != CameraManager.CameraMode.Flight ||
                (vessel.id != FlightGlobals.ActiveVessel.id && LoadGlobals.settings.LoadedInactive))
            {
                return;
            }

            // So we do have an internal model, right?
            if (part.internalModel != null)
            {
                // If the current part is not part of the active vessel, we calculate the distance from the part to the flight camera.
                // If this distance is > distanceToCameraThreshold metres we turn off transparency for the part.
                // Uses Maths calcs intead of built in Unity functions as this is up to 5 times faster.
                if (!vessel.isActiveVessel && LoadGlobals.settings.LoadedInactive && CameraManager.Instance.currentCameraMode == CameraManager.CameraMode.Flight)
                {
                    Vector3   heading;
                    Transform thisPart     = part.transform;
                    Transform flightCamera = FlightCamera.fetch.transform;
                    heading.x = thisPart.position.x - flightCamera.position.x;
                    heading.y = thisPart.position.y - flightCamera.position.y;
                    heading.z = thisPart.position.z - flightCamera.position.z;
                    var distanceSquared = heading.x * heading.x + heading.y * heading.y + heading.z * heading.z;
                    distanceToCamera = Mathf.Sqrt(distanceSquared);

                    if (distanceToCamera > distanceToCameraThreshold)
                    {
                        SetShaders(false);
                        //part.internalModel.SetVisible(false);
                        if (!JSIAdvTransparentPods.Instance.PartstoFilterfromIVADict.Contains(part))
                        {
                            JSIAdvTransparentPods.Instance.PartstoFilterfromIVADict.Add(part);
                        }
                        setVisible = false;
                        return;
                    }
                }

                //If not the active vessel IVAs are turned on via the settings then we:
                //Check for obstructions between this IVA and the Camera that may be on lower layers and turn off the IVA if there is one.
                //Not a perfect solution..... and bad performance-wise.
                if (LoadGlobals.settings.LoadedInactive)
                {
                    if (JSIAdvTransparentPods.Instance != null && setVisible)
                    {
                        if (JSIAdvTransparentPods.Instance.IVAcameraTransform != null)
                        {
                            Transform IVAtoWorld = new GameObject().transform;
                            IVAtoWorld.position =
                                InternalSpace.InternalToWorld(part.internalModel.transform.position);
                            IVAtoWorld.rotation = InternalSpace.InternalToWorld(part.internalModel.transform.rotation);
                            Transform IVACameratoWorld = new GameObject().transform;
                            IVACameratoWorld.position =
                                InternalSpace.InternalToWorld(JSIAdvTransparentPods.Instance.IVAcameraTransform.position);
                            IVAtoWorld.rotation = InternalSpace.InternalToWorld(JSIAdvTransparentPods.Instance.IVAcameraTransform.rotation);
                            if (JSIAdvTPodsUtil.IsIVAObstructed(IVAtoWorld, IVACameratoWorld))
                            {
                                if (!JSIAdvTransparentPods.Instance.PartstoFilterfromIVADict.Contains(part))
                                {
                                    JSIAdvTransparentPods.Instance.PartstoFilterfromIVADict.Add(part);
                                }
                            }
                            IVAtoWorld.gameObject.DestroyGameObject();
                            IVACameratoWorld.gameObject.DestroyGameObject();
                        }
                    }
                }

                // Make the internal model visible...
                // And for a good measure we make sure the shader change has been applied.
                SetShaders(true);
                if (JSIAdvTransparentPods.Instance.PartstoFilterfromIVADict.Contains(part))
                {
                    JSIAdvTransparentPods.Instance.PartstoFilterfromIVADict.Remove(part);
                }
                setVisible = true;
                part.internalModel.SetVisible(true);
            }
            else
            {
                JSIAdvTPodsUtil.Log("Where is my Internal model for : {0}", part.craftID);
            }
        }
Esempio n. 28
0
        public void UpdateCurrentPart()
        {
            if (_previousCameraPosition == InternalCamera.Instance.transform.position)
            {
                return;
            }
            //Debug.Log("###########################");
            _previousCameraPosition = InternalCamera.Instance.transform.position;
            Vector3 camPos   = InternalSpace.InternalToWorld(InternalCamera.Instance.transform.position);
            Part    lastPart = CurrentPart;

            // Part colliders are larger than the parts themselves and overlap.
            // Find which of the containing parts we're nearest to.
            List <Part> possibleParts = new List <Part>();

            if (CurrentPart.collider.bounds.Contains(camPos))
            {
                //Debug.Log("# Adding previous currentpart.");
                possibleParts.Add(CurrentPart);
            }
            // Check all attached parts.
            if (CurrentPart.parent != null && CurrentPart.parent.collider.bounds.Contains(camPos))
            {
                //Debug.Log("# Adding parent " + CurrentPart.parent);
                possibleParts.Add(CurrentPart.parent);
            }
            foreach (Part c in CurrentPart.children)
            {
                if (c.collider.bounds.Contains(camPos))
                {
                    //Debug.Log("# Adding child " + c);
                    possibleParts.Add(c);
                }
            }
            if (possibleParts.Count == 0)
            {
                //Debug.Log("# Zero connected parts found, checking everything.");
                foreach (Part p in FlightGlobals.ActiveVessel.parts)
                {
                    if (p.collider.bounds.Contains(InternalSpace.InternalToWorld(InternalCamera.Instance.transform.position)))
                    {
                        //Debug.Log("# Adding vessel part " + p);
                        possibleParts.Add(p);
                    }
                }
            }

            if (possibleParts.Count == 0)
            {
                //Debug.Log("# No potential parts found");
                return;
            }

            if (possibleParts.Count == 1)
            {
                //Debug.Log("# Only one part found: " + possibleParts[0]);
                CurrentPart = possibleParts[0];
                if (CurrentPart != lastPart)
                {
                    OnIvaPartChanged.Fire(CurrentPart);
                }

                /*else
                 *  Debug.Log("# Same part as before: " + CurrentPart + " at " + CurrentPart.transform.position);*/
                return;
            }

            float minDistance = float.MaxValue;
            Part  closestPart = null;

            //Debug.Log("# Checking " + possibleParts.Count + " possibilities.");
            foreach (Part pp in possibleParts)
            {
                // Raycast from the camera to the centre of the collider.
                // TODO: Figure out how to deal with multi-collider parts.
                Vector3    c         = pp.collider.bounds.center;
                Vector3    direction = c - camPos;
                Ray        ray       = new Ray(camPos, direction);
                RaycastHit hitInfo;
                if (!pp.collider.Raycast(ray, out hitInfo, direction.magnitude))
                {
                    //Debug.Log("# Raycast missed part from inside: " + pp);
                    // Ray didn't hit the collider => we are inside the collider.
                    float dist = Vector3.Distance(pp.collider.bounds.center, camPos);
                    if (dist < minDistance)
                    {
                        closestPart = pp;
                        minDistance = dist;
                    }

                    /*else
                     *  Debug.Log("# Part was further away: " + minDistance + " vs part's " + dist);*/
                }

                /*else
                 *  Debug.Log("# Raycast hit part from outside: " + pp);*/
            }
            if (closestPart != null)
            {
                //Debug.Log("# New closest part found: " + closestPart);
                CurrentPart = closestPart;
                if (CurrentPart != lastPart)
                {
                    OnIvaPartChanged.Fire(CurrentPart);
                }

                /*else
                 *  Debug.Log("# Same part as before: " + CurrentPart + " at " + CurrentPart.transform.position);*/
            }

            /*else
             *  Debug.Log("# No closest part found.");*/
            // Keep the last part we were inside as the current part: We could be transitioning between hatches.
            // TODO: Idendify/store when we are outside all parts (EVA from IVA?).
        }
Esempio n. 29
0
        void Update()
        {
            if (Input.GetKeyDown(toggleEnabledKey))
            {
                trackerEnabled = !trackerEnabled;
            }
            if (Input.GetKeyDown(resetOrientationKey))
            {
                tracker.ResetOrientation();
            }

            if (!trackerEnabled)
            {
                return;
            }

            if (tracker != null)
            {
                Vector3 rot = new Vector3(0, 0, 0);
                Vector3 pos = new Vector3(0, 0, 0);
                try
                {
                    tracker.GetData(ref rot, ref pos);
                }
                catch (Exception e)
                {
                    Debug.Log("[KerbTrack] " + GetTrackerName((Enums.Trackers)activeTracker) + " error: " + e.Message + "\n" + e.StackTrace);
                    trackerEnabled = false;
                    return;
                }
                float pitch = (float)rot.x;
                float yaw   = (float)rot.y;
                float roll  = (float)rot.z;
                float x     = pos.x;
                float y     = pos.y;
                float z     = pos.z;

                switch (CameraManager.Instance.currentCameraMode)
                {
                case CameraManager.CameraMode.External:
                {
                    break;
                }

                case CameraManager.CameraMode.Flight:
                {
                    if (!externalTrackingEnabled)
                    {
                        return;
                    }

                    if (activeTracker == (int)Enums.Trackers.Joystick)
                    {
                        Vector2 joyCamPos = new Vector3(0, 0);
                        ((JoystickTracker)tracker).GetFlightCamData(ref joyCamPos);
                        bool relative = true;
                        if (relative)
                        {
                            FlightCamera.fetch.camPitch += -joyCamPos.x * pitchScaleFlight * Time.deltaTime;
                            FlightCamera.fetch.camHdg   += -joyCamPos.y * yawScaleFlight * Time.deltaTime;
                        }
                        else
                        {
                            FlightCamera.fetch.camPitch = -joyCamPos.x * pitchScaleFlight;
                            FlightCamera.fetch.camHdg   = -joyCamPos.y * yawScaleFlight;
                        }
                    }
                    else
                    {
                        bool freeLook = true;
                        if (freeLook)
                        {
                            // If tracker supports quaternions, use them directly.
                            var qtracker = tracker as IQuatTracker;
                            if (qtracker != null)
                            {
                                //var joystickRotation = FlightCamera.fetch.transform.localRotation;
                                var quat = FlightCamera.fetch.transform.localRotation;
                                qtracker.GetQuatData(ref quat);
                                Quaternion deltaRot;
                                if (lastRotation != Quaternion.identity)
                                {
                                    deltaRot = Quaternion.Inverse(lastRotation) * quat;
                                }
                                else
                                {
                                    deltaRot = quat;
                                }
                                lastRotation = quat;

                                FlightCamera.fetch.transform.localRotation = FlightCamera.fetch.transform.localRotation * deltaRot;
                            }
                            else
                            {
                                pv = pitch * pitchScaleIVA + pitchOffsetIVA;
                                yv = yaw * yawScaleIVA + yawOffsetIVA;
                                rv = roll * rollScaleIVA + rollOffsetIVA;
                                xp = x * xScale + xOffset;
                                yp = y * yScale + yOffset;
                                zp = z * -zScale + zOffset;
                                FlightCamera.fetch.transform.localEulerAngles = new Vector3(pv, yv, rv);
                            }
                            //FlightCamera.fetch.transform.localPosition = new Vector3(xp, yp, zp);
                            // Without setting the flight camera transform, the pod rotates about without changing the background.
                            //FlightCamera.fetch.transform.rotation = InternalSpace.InternalToWorld(InternalCamera.Instance.transform.rotation);
                            //FlightCamera.fetch.transform.position = InternalSpace.InternalToWorld(InternalCamera.Instance.transform.position);
                            break;
                        }
                        else
                        {
                            // Orbit around the vessel in the same way as the stock camera.
                            FlightCamera.fetch.camPitch = -pitch * pitchScaleFlight;
                            FlightCamera.fetch.camHdg   = -yaw * yawScaleFlight;
                        }
                    }
                    pv = pitch * pitchScaleFlight;
                    yv = yaw * yawScaleFlight;
                    break;
                }

                case CameraManager.CameraMode.Internal: // Window zoom cameras
                case CameraManager.CameraMode.IVA:      // Main IVA cameras
                {
                    pv = pitch * pitchScaleIVA + pitchOffsetIVA;
                    yv = yaw * yawScaleIVA + yawOffsetIVA;
                    rv = roll * rollScaleIVA + rollOffsetIVA;
                    xp = x * xScale + xOffset;
                    yp = y * yScale + yOffset;
                    zp = z * -zScale + zOffset;
                    // If tracker supports quaternions, use them directly.
                    var qtracker = tracker as IQuatTracker;
                    if (qtracker != null)
                    {
                        var quat = InternalCamera.Instance.transform.localRotation;
                        qtracker.GetQuatData(ref quat);
                        InternalCamera.Instance.transform.localRotation = quat;
                    }
                    else
                    {
                        InternalCamera.Instance.transform.localEulerAngles = new Vector3(
                            -Mathf.Clamp(pv, pitchMinIVA, pitchMaxIVA),
                            -Mathf.Clamp(yv, yawMinIVA, yawMaxIVA),
                            Mathf.Clamp(rv, rollMinIVA, rollMaxIVA));
                    }
                    InternalCamera.Instance.transform.localPosition = new Vector3(
                        Mathf.Clamp(xp, xMinIVA, xMaxIVA),
                        Mathf.Clamp(yp, yMinIVA, yMaxIVA),
                        Mathf.Clamp(zp, zMinIVA, zMaxIVA));
                    // Without setting the flight camera transform, the pod rotates about without changing the background.
                    FlightCamera.fetch.transform.rotation = InternalSpace.InternalToWorld(InternalCamera.Instance.transform.rotation);
                    FlightCamera.fetch.transform.position = InternalSpace.InternalToWorld(InternalCamera.Instance.transform.position);
                    break;
                }

                case CameraManager.CameraMode.Map:
                {
                    if (!mapTrackingEnabled)
                    {
                        return;
                    }
                    PlanetariumCamera.fetch.camPitch = -pitch * pitchScaleMap;
                    PlanetariumCamera.fetch.camHdg   = -yaw * yawScaleMap;
                    pv = pitch * pitchScaleMap;
                    yv = yaw * yawScaleMap;
                    break;
                }
                }
            }
        }
Esempio n. 30
0
        // Free movement with no "down".
        private void FreeOrientation()
        {
            float yaw   = 0;
            float pitch = 0;
            float roll  = 0;

            if (!cameraPositionLocked)
            {
                if (MouseLook)
                {
                    float mouseX = Input.GetAxis("Mouse X");
                    yaw = mouseX * Settings.YawSpeed;
                    float mouseY = Input.GetAxis("Mouse Y");
                    pitch = -mouseY * Settings.PitchSpeed;
                }
                else
                {
                    yaw = 0;
                    if (Input.GetKey(KeyCode.L))
                    {
                        yaw = Settings.YawSpeed * Time.deltaTime * 10;
                    }
                    else if (Input.GetKey(KeyCode.J))
                    {
                        yaw = -Settings.YawSpeed * Time.deltaTime * 10;
                    }
                    pitch = 0;
                    if (Input.GetKey(KeyCode.I))
                    {
                        pitch = Settings.PitchSpeed * Time.deltaTime * 10;
                    }
                    else if (Input.GetKey(KeyCode.K))
                    {
                        pitch = -Settings.PitchSpeed * Time.deltaTime * 10;
                    }
                    roll = 0;
                }
            }
            if (Input.GetKey(Settings.RollCCWKey))
            {
                roll = Settings.RollSpeed * Time.deltaTime;
            }
            else if (Input.GetKey(Settings.RollCWKey))
            {
                roll = -Settings.RollSpeed * Time.deltaTime;
            }

            Quaternion rotYaw   = Quaternion.AngleAxis(yaw, previousRotation * Vector3.up);
            Quaternion rotPitch = Quaternion.AngleAxis(pitch, previousRotation * Vector3.right);// *Quaternion.Euler(0, 90, 0);


            Transform cameraTransform = InternalCamera.Instance.transform;


            /*Vector3 gForce = FlightGlobals.getGeeForceAtPosition(FlightCamera.fetch.transform.position);
             * Vector3 gDirection = gForce.normalized;
             * Vector3 gDirectionInternal = InternalSpace.WorldToInternal(-gDirection).normalized;*/

            //Utils.line.SetPosition(0, InternalCamera.Instance.transform.localPosition);
            //Utils.line.SetPosition(1, InternalCamera.Instance.transform.localPosition - Quaternion.AngleAxis(90, Vector3.up) * gDirectionInternal);

            /*float angle = Vector3.Angle(Vector3.Project(gDirectionInternal, cameraTransform.forward).normalized, cameraTransform.up);
             * Quaternion rotRoll = Quaternion.AngleAxis(angle, previousRotation * Vector3.forward);*/
            //Quaternion.LookRotation



            Quaternion rotRoll = Quaternion.AngleAxis(roll, previousRotation * Vector3.forward);

            /* new *
             * if (Gravity)
             * {
             *  gForce = FlightGlobals.getGeeForceAtPosition(KerbalCollider.transform.position);
             *  gForce = InternalSpace.WorldToInternal(gForce);
             *  Quaternion rotation = Quaternion.LookRotation(-gForce, Vector3.forward);
             *  Quaternion current = cameraTransform.rotation;
             *  rotRoll = Quaternion.Slerp(current, rotation, Time.deltaTime);
             * }*/


            cameraTransform.rotation = rotRoll * rotPitch * rotYaw * previousRotation;
            previousRotation         = cameraTransform.rotation;
            FlightCamera.fetch.transform.rotation = InternalSpace.InternalToWorld(cameraTransform.rotation);
        }