Example #1
0
 public static Vector3 GetWorldSurfacePostion(Vector3d geoPosition, CelestialBody body)
 {
     if (!body)
     {
         return(Vector3.zero);
     }
     return(body.GetWorldSurfacePosition(geoPosition.x, geoPosition.y, geoPosition.z));
 }
Example #2
0
        public static double CalcElevationFrom(double lat1, double lon1, double altMSL1, double lat2, double lon2, double altMSL2, string bodyName)
        {
            CelestialBody cBody = FlightGlobals.Bodies.Find(body => body.name == bodyName);

            Vector3d x = cBody.GetWorldSurfacePosition(lat1, lon1, altMSL1);
            Vector3d y = cBody.GetWorldSurfacePosition(lat2, lon2, altMSL2);

            Vector3d targetDir = y - x;

            Vector3d up = (y - cBody.position).normalized;

            double angle = Vector3d.Angle(targetDir, up);

            //("Elevation angle = " + (angle - 90).ToString("F1") + "°");

            return(angle);
        }
Example #3
0
 public static Vector3 GetWorldSurfacePostion(Vector3d geoPosition, CelestialBody body)
 {
     if(!body)
     {
         return Vector3.zero;
     }
     return body.GetWorldSurfacePosition(geoPosition.x, geoPosition.y, geoPosition.z);
 }
Example #4
0
        public static Vector3d planetaryPosition(Vector3 v, CelestialBody planet)
        {
            double lng = planet.GetLongitude(v);
            double lat = planet.GetLatitude(v);
            double alt = planet.GetAltitude(v);

            return(planet.GetWorldSurfacePosition(lat, lng, alt));
        }
        public float length()
        {
            float totalLength = 0;

            for (int i = 0; i < waypoints.Count - 1; ++i)
            {
                //find out how much relPos is covered by this segment
                Vector3 start = referenceBody.GetWorldSurfacePosition(waypoints[i].latitude, waypoints[i].longitude, waypoints[i].altitude);
                Vector3 end   = referenceBody.GetWorldSurfacePosition(waypoints[i + 1].latitude, waypoints[i + 1].longitude, waypoints[i + 1].altitude);
                totalLength += (end - start).magnitude;
            }

            return(totalLength);
        }
        private bool IsInSafetyBubble(double lat, double lon, double alt, CelestialBody body)
        {
            if (body == null)
            {
                return(false);
            }

            return(IsInSafetyBubble(body.GetWorldSurfacePosition(lat, lon, alt), body));
        }
Example #7
0
        /// <summary>
        /// ReplaceMent for finding vessels
        /// </summary>
        /// <param name="flightState"></param>
        /// <param name="landedAt"></param>
        /// <param name="count"></param>
        /// <param name="name"></param>
        /// <param name="idx"></param>
        /// <param name="vType"></param>
        public static void FindVesselsLandedAtKK(FlightState flightState, string landedAt, out int count, out string name, out int idx, out VesselType vType)
        {
            // Log.Normal("Called");
            float maxDistance = 100f;

            int          vesselIndex = 0;
            KKLaunchSite launchSite  = LaunchSiteManager.GetLaunchSiteByName(landedAt);

            count = 0;
            name  = string.Empty;
            idx   = 0;
            vType = VesselType.Debris;

            if (flightState != null)
            {
                foreach (ProtoVessel vessel in flightState.protoVessels)
                {
                    if (vessel == null)
                    {
                        continue;
                    }

                    if (launchSite == null || launchSite.isSquad)
                    {
                        if (vessel.landedAt.Contains(landedAt))
                        {
                            count++;
                            name  = vessel.vesselName;
                            idx   = vesselIndex;
                            vType = vessel.vesselType;
                            break;
                        }
                    }
                    else
                    {
                        //if (vessel.situation == Vessel.Situations.SPLASHED || vessel.situation == Vessel.Situations.LANDED || vessel.situation == Vessel.Situations.PRELAUNCH )
                        //                        {
                        ////                            Log.Normal("Body: "+ FlightGlobals.Bodies[vessel.orbitSnapShot.ReferenceBodyIndex].name);
                        CelestialBody body     = FlightGlobals.Bodies[vessel.orbitSnapShot.ReferenceBodyIndex];
                        Vector3       position = body.GetWorldSurfacePosition(vessel.latitude, vessel.longitude, vessel.altitude);
                        float         distance = Vector3.Distance(position, launchSite.staticInstance.gameObject.transform.position);
                        //Log.Normal("Vessel with distance: " + distance);
                        if (distance < maxDistance)
                        {
                            Log.Normal("Found Vessel at Launchsite with distance: " + distance);
                            count++;
                            name  = vessel.vesselName;
                            idx   = vesselIndex;
                            vType = vessel.vesselType;
                            break;
                        }
                        //}
                    }
                    vesselIndex++;
                }
            }
        }
        private Vector3 selectEvePoint()
        {
            CelestialBody eve = FlightGlobals.Bodies.Where(b => b.name == "Eve").First();

            if (eveLatitude == 0.0)
            {
                CelestialBody sun = FlightGlobals.Bodies.Where(b => b.name == "Sun").First();

                // Three hand-picked spots
                double[][] points = new double[][] {
                    new double[] { 7.39669784381863, 3.1827231256902 },
                    new double[] { 5.90113274698536, -92.0459544666453 },
                    new double[] { 1.200368332465, 221.8829976215 }
                };

                float minDistance = float.MaxValue;
                foreach (double[] point in points)
                {
                    double latitude  = point[0];
                    double longitude = point[1];

                    // Get the actual position
                    Vector3 pos      = eve.GetWorldSurfacePosition(latitude, longitude, 0.0);
                    float   distance = Vector3.Distance(pos, sun.transform.position);
                    if (distance < minDistance)
                    {
                        eveLatitude  = point[0];
                        eveLongitude = point[1];
                        minDistance  = distance;
                    }
                }
            }

            // Figure out the terrain height
            double   latRads      = Math.PI / 180.0 * eveLatitude;
            double   lonRads      = Math.PI / 180.0 * eveLongitude;
            Vector3d radialVector = new Vector3d(Math.Cos(latRads) * Math.Cos(lonRads), Math.Sin(latRads), Math.Cos(latRads) * Math.Sin(lonRads));
            double   height       = Math.Max(eve.pqsController.GetSurfaceHeight(radialVector) - eve.pqsController.radius, 0.0);

            return(eve.GetWorldSurfacePosition(eveLatitude, eveLongitude, height + 10.0f));
        }
Example #9
0
 /// <summary>
 /// Set the trajectories target to a latitude, longitude and altitude at the HomeWorld.
 /// </summary>
 public static void SetTarget(double lat, double lon, double alt = 2.0)
 {
     if (FlightGlobals.ActiveVessel != null)
     {
         CelestialBody body = FlightGlobals.Bodies.SingleOrDefault(b => b.isHomeWorld);    // needs fixing, vessel is not allways at kerbin
         if (body != null)
         {
             Vector3d worldPos = body.GetWorldSurfacePosition(lat, lon, alt);
             Trajectory.Target.Set(body, worldPos - body.position);
         }
     }
 }
Example #10
0
        public static DMPRaycastPair RaycastGround(double latitude, double longitude, CelestialBody body)
        {
            //We can only find the ground on bodies that actually *have* ground and if we are in flight near the origin
            if (!HighLogic.LoadedSceneIsFlight || FlightGlobals.fetch.activeVessel == null || body.pqsController == null)
            {
                return(new DMPRaycastPair(-1f, Vector3.up));
            }
            //Math functions take radians.
            double latRadians  = latitude * Mathf.Deg2Rad;
            double longRadians = longitude * Mathf.Deg2Rad;
            //Radial vector
            Vector3d surfaceRadial = new Vector3d(Math.Cos(latRadians) * Math.Cos(longRadians), Math.Sin(latRadians), Math.Cos(latRadians) * Math.Sin(longRadians));
            double   surfaceHeight = body.pqsController.GetSurfaceHeight(surfaceRadial) - body.pqsController.radius;
            Vector3d origin        = body.GetWorldSurfacePosition(latitude, longitude, surfaceHeight + 500);
            //Only return the surface if it's really close.
            double  highestHit    = double.NegativeInfinity;
            Vector3 rotatedVector = Vector3.up;

            if (Vector3d.Distance(FlightGlobals.fetch.activeVessel.GetWorldPos3D(), origin) < 2500)
            {
                //Down vector
                Vector3d downVector = -body.GetSurfaceNVector(latitude, longitude);
                //Magic numbers, comes from Vessel.GetHeightFromTerrain
                LayerMask    groundMask  = 32768;
                RaycastHit[] raycastHits = Physics.RaycastAll(origin, downVector, 1000f, groundMask);
                foreach (RaycastHit raycastHit in raycastHits)
                {
                    if (raycastHit.collider == null)
                    {
                        //I don't think this is technically possible, but unity's weird enough that we should probably check this anyway.
                        continue;
                    }
                    if (raycastHit.collider.name == body.name)
                    {
                        continue;
                    }
                    double hitAltitude = body.GetAltitude(raycastHit.point);
                    if ((hitAltitude > highestHit) && (!body.ocean || hitAltitude > 0))
                    {
                        highestHit    = hitAltitude;
                        rotatedVector = Quaternion.Inverse(body.rotation) * raycastHit.normal;
                    }
                }
            }
            if (double.IsNegativeInfinity(highestHit))
            {
                return(new DMPRaycastPair(-1f, Vector3.up));
            }
            else
            {
                return(new DMPRaycastPair(highestHit, rotatedVector));
            }
        }
Example #11
0
 public static DMPRaycastPair RaycastGround(double latitude, double longitude, CelestialBody body)
 {
     //We can only find the ground on bodies that actually *have* ground and if we are in flight near the origin
     if (!HighLogic.LoadedSceneIsFlight || FlightGlobals.fetch.activeVessel == null || body.pqsController == null)
     {
         return new DMPRaycastPair(-1f, Vector3.up);
     }
     //Math functions take radians.
     double latRadians = latitude * Mathf.Deg2Rad;
     double longRadians = longitude * Mathf.Deg2Rad;
     //Radial vector
     Vector3d surfaceRadial = new Vector3d(Math.Cos(latRadians) * Math.Cos(longRadians), Math.Sin(latRadians), Math.Cos(latRadians) * Math.Sin(longRadians));
     double surfaceHeight = body.pqsController.GetSurfaceHeight(surfaceRadial) - body.pqsController.radius;
     Vector3d origin = body.GetWorldSurfacePosition(latitude, longitude, surfaceHeight + 500);
     //Only return the surface if it's really close.
     double highestHit = double.NegativeInfinity;
     Vector3 rotatedVector = Vector3.up;
     if (Vector3d.Distance(FlightGlobals.fetch.activeVessel.GetWorldPos3D(), origin) < 2500)
     {
         //Down vector
         Vector3d downVector = -body.GetSurfaceNVector(latitude, longitude);
         //Magic numbers!
         LayerMask groundMask = 33792;
         RaycastHit[] raycastHits = Physics.RaycastAll(origin, downVector, 1000f, groundMask);
         foreach (RaycastHit raycastHit in raycastHits)
         {
             if (raycastHit.collider == null)
             {
                 //I don't think this is technically possible, but unity's weird enough that we should probably check this anyway.
                 continue;
             }
             if (raycastHit.collider.name == body.name)
             {
                 continue;
             }
             double hitAltitude = body.GetAltitude(raycastHit.point);
             if ((hitAltitude > highestHit) && (!body.ocean || hitAltitude > 0))
             {
                 highestHit = hitAltitude;
                 rotatedVector = Quaternion.Inverse(body.rotation) * raycastHit.normal;
             }
         }
     }
     if (highestHit == double.NegativeInfinity)
     {
         return new DMPRaycastPair(-1f, Vector3.up);
     }
     else
     {
         return new DMPRaycastPair(highestHit, rotatedVector);
     }
 }
Example #12
0
        public void onDraw()
        {
            if (!isCompatible)
            {
                return;
            }
            if (siteLocations.Count < 1 || lsTexture == null || !showSites || !iconDisplayDistance())
            {
                return;
            }

            CelestialBody Kerbin       = getKSCBody();
            Vector3d      planet_pos   = ScaledSpace.LocalToScaledSpace(Kerbin.position);
            bool          isActiveSite = false;

            foreach (KeyValuePair <string, LaunchSite> kvp in siteLocations)
            {
                Camera   camera = MapView.MapCamera.camera;
                Vector3d point  = Kerbin.GetWorldSurfacePosition(kvp.Value.geographicLocation.x, kvp.Value.geographicLocation.y, 0);
                if (!IsOccluded(point, Kerbin))
                {
                    isActiveSite = kvp.Value.name.Equals(activeSite);
                    point        = ScaledSpace.LocalToScaledSpace(point);
                    point        = camera.WorldToScreenPoint(point);
                    Rect iconBound = new Rect((float)point.x, (float)(Screen.height - point.y), 28f, 28f);
                    if (isActiveSite)
                    {
                        Graphics.DrawTexture(iconBound, lsActiveTexture);
                    }
                    else
                    {
                        Graphics.DrawTexture(iconBound, lsTexture);
                    }

                    if (iconBound.Contains(Event.current.mousePosition))
                    {
                        GUI.Label(new Rect((float)(point.x) + 28f, (float)(Screen.height - point.y) + 5f, 50, 20), kvp.Value.displayName, siteText);
                        if (Event.current.type == EventType.mouseDown && Event.current.button == 0)
                        {
                            if (isActiveSite)
                            {
                                ScreenMessages.PostScreenMessage("Cannot set launch site to active site.", 2.5f, ScreenMessageStyle.LOWER_CENTER);
                            }
                            else
                            {
                                setSite(kvp.Value);
                            }
                        }
                    }
                }
            }
        }
Example #13
0
 public static void SetTarget(double lat, double lon, double alt = 2.0)
 {
     if (FlightGlobals.ActiveVessel != null)
     {
         //Hard coded to Kerbin currently, should be changed
         CelestialBody body = FlightGlobals.Bodies.SingleOrDefault(x => x.isHomeWorld);
         if (body != null)
         {
             Vector3d worldPos = body.GetWorldSurfacePosition(lat, lon, alt);
             Trajectory.Target.SetFromWorldPos(body, worldPos - body.position);
         }
     }
 }
Example #14
0
        static public Transform SetUpTransform(CelestialBody body, double latitude, double longitude, double alt)
        {
            // Set up transform so Y is up and (0,0,0) is target position
            Vector3d origin = body.GetWorldSurfacePosition(latitude, longitude, alt);
            Vector3d vEast  = body.GetWorldSurfacePosition(latitude, longitude - 0.1, alt) - origin;
            Vector3d vUp    = body.GetWorldSurfacePosition(latitude, longitude, alt + 1) - origin;

            // Convert to body co-ordinates
            origin = body.transform.InverseTransformPoint(origin);
            vEast  = body.transform.InverseTransformVector(vEast);
            vUp    = body.transform.InverseTransformVector(vUp);

            GameObject go = new GameObject();
            // Need to rotation that converts (0,1,0) to vUp in the body transform
            Quaternion quat = Quaternion.FromToRotation(new Vector3(0, 1, 0), vUp);

            Transform o_transform = go.transform;

            o_transform.SetPositionAndRotation(origin, quat);
            o_transform.SetParent(body.transform, false);
            return(o_transform);
        }
Example #15
0
        public Vector3d GetPointOnGlideslope(double glideslope, double distanceOnCenterline)
        {
            Vector3d runwayStart       = Start();
            Vector3d runwayEnd         = End();
            Vector3d runwayDir         = (runwayEnd - runwayStart).normalized;
            Vector3d pointOnGlideslope = runwayStart - (distanceOnCenterline * runwayDir);

            double altitude = start.altitude + Math.Tan(glideslope * Mathf.Deg2Rad) * distanceOnCenterline;

            body.GetLatLonAlt(pointOnGlideslope, out double latAtDistance, out double lonAtDistance, out double altAtDistance);

            return(body.GetWorldSurfacePosition(latAtDistance, lonAtDistance, altitude));
        }
            void FixedUpdate()
            {
                if (param != null && param.starJeb != null)
                {
                    if (param.velocity != null)
                    {
                        param.starJeb.SetPosition(param.starJeb.transform.position + (param.velocity.Value * Time.fixedDeltaTime));
                    }
                    else if (param.Destination != null)
                    {
                        Vector3 direction = (param.starJeb.transform.position - param.Destination.Value).normalized;

                        float t = Time.fixedTime - param.stepTime;
                        float x = t / 8.0f - 1.0f;
                        if (t + Time.fixedDeltaTime * 2.0f > 8.0f)
                        {
                            x = 0.0f;
                        }

                        if (param.starJeb.altitude < param.starJeb.terrainAltitude + 10.0f)
                        {
                            CelestialBody body = param.DestinationBody;
                            double        lat  = body.GetLatitude(param.starJeb.transform.position);
                            double        lon  = body.GetLongitude(param.starJeb.transform.position);
                            param.starJeb.SetPosition(body.GetWorldSurfacePosition(lat, lon, param.starJeb.terrainAltitude + 10.0f));
                        }
                        else
                        {
                            param.starJeb.SetPosition(param.Destination.Value + direction * param.startDistance * x * x);
                        }
                    }

                    if (param.Destination != null)
                    {
                        // Adjust the velocity, but only every frame - adjusting this too frequently
                        // seems to cause the velocity to resonate back and forth
                        if (Time.frameCount != lastAdjustment)
                        {
                            lastAdjustment = Time.frameCount;
                            param.starJeb.ChangeWorldVelocity(-param.starJeb.GetSrfVelocity());

                            // Keep us safe!
                            foreach (Part p in param.starJeb.parts)
                            {
                                p.crashTolerance = 10000000.0f;
                            }
                            CheatOptions.NoCrashDamage = true;
                        }
                    }
                }
            }
Example #17
0
        public static void DrawWaypoint(CelestialBody targetBody, double latitude, double longitude, double altitude, string id, int seed, float alpha = -1.0f)
        {
            Log.Info("DrawWaypoint, id: " + id);
            // Translate to scaled space
            Vector3d localSpacePoint  = targetBody.GetWorldSurfacePosition(latitude, longitude, altitude);
            Vector3d scaledSpacePoint = ScaledSpace.LocalToScaledSpace(localSpacePoint);

            // Don't draw if it's behind the camera
            if (Vector3d.Dot(PlanetariumCamera.Camera.transform.forward, scaledSpacePoint.normalized) < 0.0)
            {
                return;
            }

            // Translate to screen position
            Vector3 screenPos = PlanetariumCamera.Camera.WorldToScreenPoint(new Vector3((float)scaledSpacePoint.x, (float)scaledSpacePoint.y, (float)scaledSpacePoint.z));

            // Draw the marker at half-resolution (30 x 45) - that seems to match the one in the map view
            Rect markerRect = new Rect(screenPos.x - 15f, (float)Screen.height - screenPos.y - 45.0f, 30f, 45f);

            // Half-res for the icon too (16 x 16)
            Rect iconRect = new Rect(screenPos.x - 8f, (float)Screen.height - screenPos.y - 39.0f, 16f, 16f);

            if (alpha < 0.0f)
            {
                Vector3 cameraPos    = ScaledSpace.ScaledToLocalSpace(PlanetariumCamera.Camera.transform.position);
                bool    occluded     = WaypointData.IsOccluded(targetBody, cameraPos, localSpacePoint, altitude);
                float   desiredAlpha = occluded ? 0.3f : 1.0f * Config.opacity;
                if (lastAlpha < 0.0f)
                {
                    lastAlpha = desiredAlpha;
                }
                else if (lastAlpha < desiredAlpha)
                {
                    lastAlpha = Mathf.Clamp(lastAlpha + Time.deltaTime * 4f, lastAlpha, desiredAlpha);
                }
                else
                {
                    lastAlpha = Mathf.Clamp(lastAlpha - Time.deltaTime * 4f, desiredAlpha, lastAlpha);
                }
                alpha = lastAlpha;
            }

            // Draw the marker
            Graphics.DrawTexture(markerRect, GameDatabase.Instance.GetTexture("Squad/Contracts/Icons/marker", false), new Rect(0.0f, 0.0f, 1f, 1f), 0, 0, 0, 0, new Color(0.5f, 0.5f, 0.5f, 0.5f * (alpha - 0.3f) / 0.7f));

            // Draw the icon
            Graphics.DrawTexture(iconRect, /* ContractDefs.sprites[id].texture */
                                 GetContractIcon(id, seed), new Rect(0.0f, 0.0f, 1f, 1f), 0, 0, 0, 0, SystemUtilities.RandomColor(seed, alpha));
            Log.Info("id: " + id);
        }
Example #18
0
        public static void DrawWaypoint(CelestialBody targetBody, double latitude, double longitude, double altitude, string id, int seed, float alpha = -1.0f)
        {
            // Translate to scaled space
            Vector3d localSpacePoint = targetBody.GetWorldSurfacePosition(latitude, longitude, altitude);
            Vector3d scaledSpacePoint = ScaledSpace.LocalToScaledSpace(localSpacePoint);

            // Don't draw if it's behind the camera
            Camera camera = MapView.MapIsEnabled ? PlanetariumCamera.Camera : FlightCamera.fetch.mainCamera;
            Vector3 cameraPos = ScaledSpace.ScaledToLocalSpace(camera.transform.position);
            if (Vector3d.Dot(camera.transform.forward, scaledSpacePoint.normalized) < 0.0)
            {
                return;
            }

            // Translate to screen position
            Vector3 screenPos = camera.WorldToScreenPoint(new Vector3((float)scaledSpacePoint.x, (float)scaledSpacePoint.y, (float)scaledSpacePoint.z));

            // Draw the marker at half-resolution (30 x 45) - that seems to match the one in the map view
            Rect markerRect = new Rect(screenPos.x - 15f, (float)Screen.height - screenPos.y - 45.0f, 30f, 45f);

            // Half-res for the icon too (16 x 16)
            Rect iconRect = new Rect(screenPos.x - 8f, (float)Screen.height - screenPos.y - 39.0f, 16f, 16f);

            if (alpha < 0.0f)
            {
                bool occluded = WaypointData.IsOccluded(targetBody, cameraPos, localSpacePoint, altitude);
                float desiredAlpha = occluded ? 0.3f : 1.0f * Config.opacity;
                if (lastAlpha < 0.0f)
                {
                    lastAlpha = desiredAlpha;
                }
                else if (lastAlpha < desiredAlpha)
                {
                    lastAlpha = Mathf.Clamp(lastAlpha + Time.deltaTime * 4f, lastAlpha, desiredAlpha);
                }
                else
                {
                    lastAlpha = Mathf.Clamp(lastAlpha - Time.deltaTime * 4f, desiredAlpha, lastAlpha);
                }
                alpha = lastAlpha;
            }

            // Draw the marker
            Graphics.DrawTexture(markerRect, GameDatabase.Instance.GetTexture("Squad/Contracts/Icons/marker", false), new Rect(0.0f, 0.0f, 1f, 1f), 0, 0, 0, 0, new Color(0.5f, 0.5f, 0.5f, 0.5f * (alpha - 0.3f) / 0.7f));

            // Draw the icon
            Graphics.DrawTexture(iconRect, ContractDefs.sprites[id].texture, new Rect(0.0f, 0.0f, 1f, 1f), 0, 0, 0, 0, SystemUtilities.RandomColor(seed, alpha));
        }
        /// <summary>
        /// sets the latitude and lognitude from the deltas of north and east and creates a new reference vector
        /// </summary>
        /// <param name="north"></param>
        /// <param name="east"></param>
        internal void Setlatlng(double north, double east)
        {
            body = selectedDecal.CelestialBody;
            double latOffset = north / (body.Radius * KKMath.deg2rad);

            latitude += latOffset;
            double lonOffset = east / (body.Radius * KKMath.deg2rad);

            longitude += lonOffset * Math.Cos(Mathf.Deg2Rad * latitude);

            Vector3d newpos = body.GetWorldSurfacePosition(latitude, longitude, altitude);

            selectedDecal.mapDecal.transform.position = newpos;

            referenceVector = body.GetRelSurfaceNVector(latitude, longitude).normalized *body.Radius;
        }
Example #20
0
            public static double GetDistanceToSun(Vessel vessel)
            {
                if (vessel == null)
                {
                    return(0.0);
                }
                CelestialBody sun = GetSun();

                if (sun == null)
                {
                    return(0.0);
                }
                Vector3d posVessel = vessel.GetWorldPos3D();
                Vector3d posSun    = sun.GetWorldSurfacePosition(0.0, 0.0, 0.0);

                return(Vector3d.Distance(posVessel, posSun));
            }
Example #21
0
        private void focusOnSite(Vector2d loc)
        {
            Debug.Log("Focusing on site");
            PlanetariumCamera camera = PlanetariumCamera.fetch;
            CelestialBody     Kerbin = getKSCBody();
            Vector3d          point  = ScaledSpace.LocalToScaledSpace(Kerbin.GetWorldSurfacePosition(loc.x, loc.y, 0));
            Vector3           vec    = ScaledSpace.LocalToScaledSpace(Kerbin.transform.localPosition);

            point = (point - vec).normalized * Kerbin.Radius;
            camera.SetCamCoordsFromPosition(new Vector3((float)point.x, (float)point.y, (float)point.z));

            // this works for RSS, may have to change for other sizes.
            // float distance = camera.startDistance * 3.5f;
            float distance = (float)(Kerbin.Radius * 0.00035);

            camera.SetDistance(distance);
        }
Example #22
0
        /// <summary>
        /// Decodes the path.
        /// </summary>
        /// <returns>The path.</returns>
        /// <param name="pathEncoded">Path encoded.</param>
        /// <param name="body">Body.</param>
        internal static List <Vector3d> DecodePath(string pathEncoded, CelestialBody body)
        {
            List <Vector3d> result = new List <Vector3d> ();

            if (pathEncoded == null || pathEncoded.Length == 0)
            {
                return(result);
            }

            // Path is compressed, decompress
            // For compatibility purposes only
            if (!pathEncoded.Contains(";"))
            {
                //pathEncoded = LZString.decompressFromBase64(pathEncoded);

                // Change LZString implementation of base64 to native functions
                // Replace # with forward slash (two forward slashes seems to be interpreted as a start of the comment when read from a save file)
                string temp         = pathEncoded;
                var    encodedBytes = System.Convert.FromBase64String(temp.Replace('#', '/'));
                temp = System.Text.Encoding.UTF8.GetString(encodedBytes);
                if (temp.Contains(":")) // backward compatibility for path encoded with LZString
                {
                    pathEncoded = temp;
                }
                else
                {
                    pathEncoded = LZString.decompressFromBase64(pathEncoded);
                }
            }

            char[]   separators = new char[] { ';' };
            string[] wps        = pathEncoded.Split(separators, StringSplitOptions.RemoveEmptyEntries);

            foreach (var wp in wps)
            {
                string[] latlon          = wp.Split(':');
                double   latitude        = double.Parse(latlon [0]);
                double   longitude       = double.Parse(latlon [1]);
                double   altitude        = GeoUtils.TerrainHeightAt(latitude, longitude, body);
                Vector3d localSpacePoint = body.GetWorldSurfacePosition(latitude, longitude, altitude);
                result.Add(localSpacePoint);
            }

            return(result);
        }
        private static void ApplyInterpolationsToLoadedVessel(Vessel vessel, VesselPositionUpdate update, VesselPositionUpdate target, CelestialBody lerpedBody, float percentage)
        {
            //Do not call vessel.orbitDriver.updateFromParameters()!!
            //It will set the vessel at the CURRENT position and ignore that the orbit is from the PAST!

            var currentSurfaceRelRotation = Quaternion.Slerp(update.SurfaceRelRotation, target.SurfaceRelRotation, percentage);

            //If you don't set srfRelRotation and vessel is packed it won't change it's rotation
            vessel.srfRelRotation = currentSurfaceRelRotation;
            vessel.SetRotation((Quaternion)lerpedBody.rotation * currentSurfaceRelRotation, true);

            vessel.Landed   = percentage < 0.5 ? update.Landed : target.Landed;
            vessel.Splashed = percentage < 0.5 ? update.Splashed : target.Splashed;

            vessel.latitude  = LunaMath.Lerp(update.LatLonAlt[0], target.LatLonAlt[0], percentage);
            vessel.longitude = LunaMath.Lerp(update.LatLonAlt[1], target.LatLonAlt[1], percentage);
            vessel.altitude  = LunaMath.Lerp(update.LatLonAlt[2], target.LatLonAlt[2], percentage);

            //var startLatLonAltPos = update.Body.GetWorldSurfacePosition(update.LatLonAlt[0], update.LatLonAlt[1], update.LatLonAlt[2]);
            //var targetLatLonAltPos = target.Body.GetWorldSurfacePosition(target.LatLonAlt[0], target.LatLonAlt[1], target.LatLonAlt[2]);

            //var startOrbitPos = startOrbit.getPositionAtUT(startOrbit.epoch);
            //var endOrbitPos = endOrbit.getPositionAtUT(endOrbit.epoch);

            vessel.SetPosition(vessel.orbit.getPositionAtUT(Planetarium.GetUniversalTime()));
            if (vessel.situation <= Vessel.Situations.PRELAUNCH)
            {
                vessel.SetPosition(lerpedBody.GetWorldSurfacePosition(vessel.latitude, vessel.longitude, vessel.altitude));
            }

            //Always run this at the end!!
            //Otherwise during docking, the orbital speeds are not displayed correctly and you won't be able to dock
            if (!vessel.packed)
            {
                var velBeforeCorrection = vessel.rootPart.rb.velocity;
                vessel.rootPart.ResumeVelocity();
                if (velBeforeCorrection != vessel.rootPart.rb.velocity)
                {
                    foreach (var part in vessel.Parts)
                    {
                        part.ResumeVelocity();
                    }
                }
            }
        }
Example #24
0
            public void update()
            {
                // only update once per cycle
                if (Planetarium.GetUniversalTime() != timestamp)
                {
                    Vector3?impactPos = API.GetTrueImpactPosition();

                    if (impactPos.HasValue)
                    {
                        lastImpactRadialVector = trueImpactRadialVector;
                        trueImpactRadialVector = impactPos.Value;
                        timeTillImpact         = API.GetTimeTillImpact().Value;

                        isValid = (lastImpactRadialVector - trueImpactRadialVector).magnitude < 100;

                        trueTargetRadialVector = mainBody.GetWorldSurfacePosition(target.targetLatitude, target.targetLongitude, targetAlt) - mainBody.position;
                        //float angle = (float)(timeTillImpact * mainBody.angularVelocity.magnitude / Math.PI * 180.0);
                        //trueTargetRadialVector = Quaternion.AngleAxis(angle, mainBody.angularVelocity.normalized) * trueTargetRadialVector;
                        trueTargetRadialVector = Quaternion.AngleAxis(-360f * (float)mainBody.rotPeriodRecip * Mathf.Lerp(0f, (float)timeTillImpact, (float)(vesselState.altitudeASL / mainBody.atmosphereDepth)), mainBody.RotationAxis) * trueTargetRadialVector;
                        orbitNormal            = target.orbit.SwappedOrbitNormal();

                        orbitClosestToImpact = Vector3.ProjectOnPlane(trueImpactRadialVector, orbitNormal);
                        orbitClosestToTarget = Vector3.ProjectOnPlane(trueTargetRadialVector, orbitNormal);
                        Vector3 targetForward = -Vector3.Cross(orbitClosestToTarget.normalized, orbitNormal);

                        differenceTarget = orbitClosestToTarget - trueImpactRadialVector;

                        //How far ahead the target is compared to impact, in degrees
                        targetAheadAngle = Vector3.SignedAngle(orbitClosestToTarget, trueImpactRadialVector, orbitNormal);

                        distanceTarget = trueTargetRadialVector - vesselState.orbitalPosition;
                        distanceImpact = trueImpactRadialVector - vesselState.orbitalPosition;
                        //calculate sideway derivation at target location, which means we have to rescale if current impact is earlier or later
                        normalDifference   = Vector3d.Dot(trueTargetRadialVector - trueImpactRadialVector, orbitNormal);
                        backwardDifference = -Vector3d.Dot(differenceTarget, targetForward); /* = overshoot >0, too short <0 */
                        forwardDistance    = Vector3d.Dot(distanceTarget, targetForward);
                    }
                    else
                    {
                        isValid = false;
                    }
                    timestamp = Planetarium.GetUniversalTime();
                }
            }
Example #25
0
        public static void updateCoordinates(CelestialBody b)
        {
            if (anomalies.Contains(b.name))
            {
                for (int i = 0; i < anomalies[b.name].AnomalyCount; i++)
                {
                    DMAnomalyObject anom = anomalies[b.name].getAnomaly(i);

                    if (anom == null)
                    {
                        continue;
                    }

                    anom.WorldLocation = b.GetWorldSurfacePosition(anom.Lat, anom.Lon, anom.Alt);
                    anom.Lat           = b.GetLatitude(anom.WorldLocation);
                    anom.Lon           = b.GetLongitude(anom.WorldLocation);
                }
            }
        }
Example #26
0
        public static List <ProtoVessel> FindVesselsLandedAt2(FlightState flightState, string landedAt)
        {
            float maxDistance       = 100f;
            List <ProtoVessel> list = new List <ProtoVessel>();

            if (flightState != null)
            {
                KKLaunchSite launchSite = LaunchSiteManager.GetLaunchSiteByName(landedAt);

                foreach (ProtoVessel vessel in flightState.protoVessels)
                {
                    if (vessel == null)
                    {
                        continue;
                    }

                    if (launchSite == null || launchSite.isSquad)
                    {
                        if (vessel.landedAt.Contains(landedAt))
                        {
                            list.Add(vessel);
                        }
                    }
                    else
                    {
                        //if (vessel.situation == Vessel.Situations.SPLASHED || vessel.situation == Vessel.Situations.LANDED || vessel.situation == Vessel.Situations.PRELAUNCH)
                        //{
                        CelestialBody body     = FlightGlobals.Bodies[vessel.orbitSnapShot.ReferenceBodyIndex];
                        Vector3       position = body.GetWorldSurfacePosition(vessel.latitude, vessel.longitude, vessel.altitude);
                        float         distance = Vector3.Distance(position, launchSite.staticInstance.transform.position);

                        if (distance < maxDistance)
                        {
                            Log.Normal("Found Vessel at Launchsite with distance: " + distance);
                            list.Add(vessel);
                        }
                        //}
                    }
                }
            }
            return(list);
        }
Example #27
0
 //Adapted from KMP. Called from PlayerStatusWorker.
 public static bool isInSafetyBubble(Vector3d worldPos, CelestialBody body, double safetyBubbleDistance)
 {
     if (body == null)
     {
         return(false);
     }
     foreach (SafetyBubblePosition position in positions)
     {
         if (body.name == position.celestialBody)
         {
             Vector3d testPos  = body.GetWorldSurfacePosition(position.latitude, position.longitude, position.altitude);
             double   distance = Vector3d.Distance(worldPos, testPos);
             if (distance < safetyBubbleDistance)
             {
                 return(true);
             }
         }
     }
     return(false);
 }
Example #28
0
        IEnumerator LifeRoutine()
        {
            geoPos = VectorUtils.WorldPositionToGeoCoords(transform.position, body);

            pe.EmitParticle();

            float startTime = Time.time;

            while (Time.time - startTime < pe.maxEnergy)
            {
                transform.position = body.GetWorldSurfacePosition(geoPos.x, geoPos.y, geoPos.z);
                velocity          += FlightGlobals.getGeeForceAtPosition(transform.position) * Time.fixedDeltaTime;
                Vector3 dragForce = (0.008f) * drag * 0.5f * velocity.sqrMagnitude * (float)FlightGlobals.getAtmDensity(FlightGlobals.getStaticPressure(transform.position), FlightGlobals.getExternalTemperature(), body) * velocity.normalized;
                velocity           -= (dragForce) * Time.fixedDeltaTime;
                transform.position += velocity * Time.fixedDeltaTime;
                geoPos              = VectorUtils.WorldPositionToGeoCoords(transform.position, body);
                yield return(new WaitForFixedUpdate());
            }

            gameObject.SetActive(false);
        }
Example #29
0
        private static void ApplyInterpolationsToVessel(Vessel vessel, VesselPositionUpdate update, VesselPositionUpdate target, CelestialBody lerpedBody, float percentage)
        {
            var currentSurfaceRelRotation = Quaternion.Slerp(update.SurfaceRelRotation, target.SurfaceRelRotation, percentage);

            //If you don't set srfRelRotation and vessel is packed it won't change it's rotation
            vessel.srfRelRotation = currentSurfaceRelRotation;

            vessel.Landed   = percentage < 0.5 ? update.Landed : target.Landed;
            vessel.Splashed = percentage < 0.5 ? update.Splashed : target.Splashed;

            vessel.latitude  = LunaMath.Lerp(update.LatLonAlt[0], target.LatLonAlt[0], percentage);
            vessel.longitude = LunaMath.Lerp(update.LatLonAlt[1], target.LatLonAlt[1], percentage);
            vessel.altitude  = LunaMath.Lerp(update.LatLonAlt[2], target.LatLonAlt[2], percentage);

            var rotation = (Quaternion)lerpedBody.rotation * currentSurfaceRelRotation;
            var position = vessel.situation <= Vessel.Situations.SUB_ORBITAL ?
                           lerpedBody.GetWorldSurfacePosition(vessel.latitude, vessel.longitude, vessel.altitude) :
                           vessel.orbit.getPositionAtUT(TimeSyncSystem.UniversalTime);

            SetVesselPositionAndRotation(vessel, position, rotation);
        }
Example #30
0
        public static void DrawGroundMarker(CelestialBody body, double latitude, double longitude, double alt, Color c, bool map, double rotation = 0, double radius = 0)
        {
            Vector3d up     = body.GetSurfaceNVector(latitude, longitude);
            Vector3d center = body.GetWorldSurfacePosition(latitude, longitude, alt + 0.5f);
            Vector3d north  = Vector3d.Exclude(up, body.transform.up).normalized;

            if (!map)
            {
                Vector3 centerPoint = FlightCamera.fetch.mainCamera.WorldToViewportPoint(center);
                if ((centerPoint.z < 0) || (centerPoint.x < -1) || (centerPoint.x > 1) || (centerPoint.y < -1) || (centerPoint.y > 1))
                {
                    return;
                }
            }

            GLTriangle(center, center + radius * (QuaternionD.AngleAxis(rotation - 10, up) * north),
                       center + radius * (QuaternionD.AngleAxis(rotation + 10, up) * north), c, map);
            GLTriangle(center, center + radius * (QuaternionD.AngleAxis(rotation + 110, up) * north),
                       center + radius * (QuaternionD.AngleAxis(rotation + 130, up) * north), c, map);
            GLTriangle(center, center + radius * (QuaternionD.AngleAxis(rotation - 110, up) * north),
                       center + radius * (QuaternionD.AngleAxis(rotation - 130, up) * north), c, map);
        }
Example #31
0
    public void LateUpdate()
    {
        if (HighLogic.LoadedSceneIsFlight)
        {
            if (FlightGlobals.fetch != null)
            {
                Vector3 worldPosition = new Vector3();
                Vector3 vesselPos;

                Vector3d surfacePos = targetBody.GetWorldSurfacePosition(latitude, longitude, height + altitude);
                worldPosition = new Vector3((float)surfacePos.x, (float)surfacePos.y, (float)surfacePos.z);

                //indicator position
                vesselPos = FlightGlobals.fetch.activeVessel.GetWorldPos3D();

                Vector3 directionToWaypoint = (worldPosition - vesselPos).normalized;
                Vector3 rotatedDirection    = navBallBehaviour.attitudeGymbal * directionToWaypoint;
                indicator.transform.localPosition = rotatedDirection * navBallBehaviour.progradeVector.localPosition.magnitude;

                indicator.transform.rotation = Quaternion.Euler(90f, 180f, 180f);

                //indicator visibility (invisible if on back half sphere)
                if (waypointOn && FlightGlobals.ActiveVessel.mainBody == targetBody)
                {
                    indicator.SetActive(indicator.transform.localPosition.z > 0.0d);
                }
                else
                {
                    indicator.SetActive(false);
                }

                return;
            }
        }

        indicator.SetActive(false);
        return;
    }
        static bool DrawGroundMarker(CelestialBody body, Coordinates pos, Color c, float r = IconSize, Texture2D texture = null)
        {
            Vector3d center;
            Camera   camera;

            if (MapView.MapIsEnabled)
            {
                //TODO: cache local center coordinates of the marker
                camera = PlanetariumCamera.Camera;
                center = body.position + (body.TerrainAltitude(pos.Lat, pos.Lon) + body.Radius) * body.GetSurfaceNVector(pos.Lat, pos.Lon);
            }
            else
            {
                camera = FlightCamera.fetch.mainCamera;
                center = body.GetWorldSurfacePosition(pos.Lat, pos.Lon, body.TerrainAltitude(pos.Lat, pos.Lon) + GLB.WaypointHeight);
                if (camera.transform.InverseTransformPoint(center).z <= 0)
                {
                    return(false);
                }
            }
            return(!IsOccluded(center, body) &&
                   DrawMarker(camera.WorldToScreenPoint(MapView.MapIsEnabled ? ScaledSpace.LocalToScaledSpace(center) : center), c, r, texture));
        }
 public static double DragLength(this CelestialBody body, double altitudeASL, double dragCoeff, double mass)
 {
     return(body.DragLength(body.GetWorldSurfacePosition(0, 0, altitudeASL), dragCoeff, mass));
 }
Example #34
0
 //Adapted from KMP. Called from PlayerStatusWorker.
 public bool isInSafetyBubble(Vector3d worlPos, CelestialBody body)
 {
     //If not at Kerbin or past ceiling we're definitely clear
     if (body.name != "Kerbin")
     {
         return false;
     }
     Vector3d landingPadPosition = body.GetWorldSurfacePosition(-0.0971978130377757, 285.44237039111, 60);
     Vector3d runwayPosition = body.GetWorldSurfacePosition(-0.0486001121594686, 285.275552559723, 60);
     double landingPadDistance = Vector3d.Distance(worlPos, landingPadPosition);
     double runwayDistance = Vector3d.Distance(worlPos, runwayPosition);
     return runwayDistance < SAFETY_BUBBLE_DISTANCE || landingPadDistance < SAFETY_BUBBLE_DISTANCE;
 }
 public void Update(CelestialBody body, double latitude, double longitude, double altitude)
 {
     Update(body.GetWorldSurfacePosition(latitude, longitude, altitude));
 }
 static bool DrawGroundMarker(CelestialBody body, Coordinates pos, Color c, float r = IconSize, Texture2D texture = null)
 {
     Vector3d center;
     Camera camera;
     if(MapView.MapIsEnabled)
     {
         //TODO: cache local center coordinates of the marker
         camera = PlanetariumCamera.Camera;
         center = body.position + (body.TerrainAltitude(pos.Lat, pos.Lon)+body.Radius) * body.GetSurfaceNVector(pos.Lat, pos.Lon);
     }
     else
     {
         camera = FlightCamera.fetch.mainCamera;
         center = body.GetWorldSurfacePosition(pos.Lat, pos.Lon, body.TerrainAltitude(pos.Lat, pos.Lon)+GLB.WaypointHeight);
         if(camera.transform.InverseTransformPoint(center).z <= 0) return false;
     }
     return !IsOccluded(center, body) &&
         DrawMarker(camera.WorldToScreenPoint(MapView.MapIsEnabled ? ScaledSpace.LocalToScaledSpace(center) : center), c, r, texture);
 }
Example #37
0
        private bool isInSafetyBubble(Vector3d pos, CelestialBody body, double altitude)
        {
            //Assume Kerbin if body isn't supplied for some reason
            if (body == null) body = FlightGlobals.Bodies.Find(b => b.name == "Kerbin");

            //If KSC out of range, syncing, not at Kerbin, or past ceiling we're definitely clear
            if (syncing || body.name != "Kerbin" || altitude > SAFETY_BUBBLE_CEILING)
                return false;

            //Cylindrical safety bubble -- project vessel position to a plane positioned at KSC with normal pointed away from surface
            Vector3d kscNormal = body.GetSurfaceNVector(-0.102668048654,-74.5753856554);
            Vector3d kscPosition = body.GetWorldSurfacePosition(-0.102668048654,-74.5753856554,60);
            double projectionDistance = Vector3d.Dot(kscNormal, (pos - kscPosition)) * -1;
            Vector3d projectedPos = pos + (Vector3d.Normalize(kscNormal)*projectionDistance);

            return Vector3d.Distance(kscPosition, projectedPos) < safetyBubbleRadius;
        }
Example #38
0
 public float Distance(double latitude1, double longitude1, double altitude1, double latitude2, double longitude2, double altitude2, CelestialBody body)
 {
     // I did use great circle distance, but now I'm actually thinking a straight line might be best.
     Vector3d position1 = body.GetWorldSurfacePosition(latitude1, longitude1, altitude1);
     Vector3d position2 = body.GetWorldSurfacePosition(latitude2, longitude2, altitude2);
     return (float)Vector3d.Distance(position1, position2);
 }
Example #39
0
        private bool isInSafetyBubble(Vector3d pos, CelestialBody body, double altitude)
        {
            //Assume Kerbin if body isn't supplied for some reason
            if (body == null)
                body = FlightGlobals.Bodies.Find(b => b.name == "Kerbin");

            //If not at Kerbin or past ceiling we're definitely clear
            if (body.name != "Kerbin" || altitude > SAFETY_BUBBLE_CEILING)
                return false;

            //Cylindrical safety bubble -- project vessel position to a plane positioned at KSC with normal pointed away from surface
            Vector3d kscNormal = body.GetSurfaceNVector(-0.102668048654, -74.5753856554);
            Vector3d kscPosition = body.GetWorldSurfacePosition(-0.102668048654, -74.5753856554, 60);
            Vector3d landingPadPosition = body.GetWorldSurfacePosition(-0.0971978130377757, 285.44237039111, 60);
            Vector3d runwayPosition = body.GetWorldSurfacePosition(-0.0486001121594686, 285.275552559723, 60);
            double projectionDistance = Vector3d.Dot(kscNormal, (pos - kscPosition)) * -1;
            double landingPadDistance = Vector3d.Distance(pos, landingPadPosition);
            double runwayDistance = Vector3d.Distance(pos, runwayPosition);
            Vector3d projectedPos = pos + (Vector3d.Normalize(kscNormal) * projectionDistance);
            return Vector3d.Distance(kscPosition, projectedPos) < safetyBubbleRadius || runwayDistance < MIN_SAFETY_BUBBLE_DISTANCE || landingPadDistance < MIN_SAFETY_BUBBLE_DISTANCE;
        }