public WaypointData(WaypointData orig, Contract contract)
            {
                type = orig.type;
                waypoint.altitude = orig.waypoint.altitude;
                waypoint.celestialName = orig.waypoint.celestialName;
                waypoint.height = orig.waypoint.height;
                waypoint.id = orig.waypoint.id;
                waypoint.index = orig.waypoint.index;
                waypoint.isClustered = orig.waypoint.isClustered;
                waypoint.isExplored = orig.waypoint.isExplored;
                waypoint.isOnSurface = orig.waypoint.isOnSurface;
                waypoint.landLocked = orig.waypoint.landLocked;
                waypoint.latitude = orig.waypoint.latitude;
                waypoint.longitude = orig.waypoint.longitude;
                waypoint.name = orig.waypoint.name;
                waypoint.visible = orig.waypoint.visible;

                randomAltitude = orig.randomAltitude;
                waterAllowed = orig.waterAllowed;
                forceEquatorial = orig.forceEquatorial;
                nearIndex = orig.nearIndex;
                count = orig.count;
                minDistance = orig.minDistance;
                maxDistance = orig.maxDistance;
                pqsCity = orig.pqsCity;
                pqsOffset = orig.pqsOffset;
                parameter = orig.parameter.ToList();
                randomName = orig.randomName;
                underwater = orig.underwater;

                SetContract(contract);
            }
        /// <summary>
        /// Copy constructor.
        /// </summary>
        public WaypointGenerator(WaypointGenerator orig, ConfiguredContract contract)
            : base()
        {
            foreach (WaypointData old in orig.waypoints)
            {
                // Copy waypoint data
                for (int i = 0; i < old.count; i++)
                {
                    WaypointData wpData = new WaypointData(old, contract);
                    waypoints.Add(wpData);

                    // Set the name
                    if (old.names.Any())
                    {
                        wpData.waypoint.name = (old.names.Count() == 1 ? old.names.First() : old.names.ElementAtOrDefault(i));
                    }
                    if (string.IsNullOrEmpty(wpData.waypoint.name) || wpData.waypoint.name.ToLower() == "site")
                    {
                        wpData.waypoint.name = StringUtilities.GenerateSiteName(random.Next(), wpData.waypoint.celestialBody, !wpData.waterAllowed);
                    }
                }
            }
            initialized = orig.initialized;
            orig.initialized = false;
            this.contract = contract;

            Initialize();
        }
Exemple #3
0
	private static WaypointData[] AddWaypointLayer(JSONObject wplJSON)
	{
		WaypointData[] wps = new WaypointData[wplJSON.list.Count];

		for (int i = 0; i < wps.Length; i++)
		{
			wps[i] = AddWaypoint(wplJSON[i]);
		}

		return wps;
	}
    public WaypointData CreateWaypointData(string name)
    {
        List<Transform> wps = GetWaypoints(name);
        if(wps != null) {
            WaypointData newWaypoint = new WaypointData();
            newWaypoint.curInd = 0;
            newWaypoint.waypoints = wps;
            return newWaypoint;
        }

        return null;
    }
Exemple #5
0
    public override void OnInspectorGUI()
    {
        NPC npc = Selection.activeGameObject.GetComponent<NPC>();
        npc.Start(); // we load npcData

        if (m_editMode)
        {
            GUILayout.Label("To add a Waypoint: right-click in the desired position.\n To change the order, edit Waypoint's name.\n");
            if (GUILayout.Button("Stop Editing"))
            {
                WaypointData wp;
                m_editMode = false;

                // destroy old waypoints
                foreach (WaypointData waypoint in Service.db.Select<WaypointData>("FROM " + WaypointData.TABLE_NAME+" WHERE npc==?", npc.Id)) {
                    waypoint.delete();
                }

                // save new waypoints
                foreach (Transform child in m_container.transform)
                {
                    wp = new WaypointData();
                    wp.npc = npc.Id;
                    wp.position = child.transform.position;
                    wp.create();
                }
                DestroyImmediate(m_container);
                m_count = 0;
            }
        }
        else
        {
            if (GUILayout.Button("Start Editing"))
            {
                m_editMode = true;
                checkContainer();

                // show existing waypoints
                foreach (WaypointData waypoint in npc.waypoints) {
                    createWaypoint(waypoint.position);
                }
            }
        }

        if (GUILayout.Button("Reset"))
        {
            m_count = 0;
            DestroyImmediate(m_container);
        }
    }
Exemple #6
0
    //Loads waypoint data
    public static WaypointData LoadWaypoints(string worldName)
    {
        string path = Application.persistentDataPath + "/Saves/" + worldName + "/Waypoints.SGSAVE";

        if (File.Exists(path))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            FileStream      stream    = new FileStream(path, FileMode.Open);

            WaypointData data = formatter.Deserialize(stream) as WaypointData;
            stream.Close();
            return(data);
        }
        else
        {
            Debug.LogWarning("Path does not exist: " + path);
            return(null);
        }
    }
Exemple #7
0
        void InitGlobalWaypoint(WaypointData data)
        {
            foreach (BasePlayer _player in BasePlayer.activePlayerList)
            {
                DrawWaypoint(_player, new Vector3(data.x, data.y, data.z), globalRefreshTime, true, data.name);
            }

            Timer repeat = timer.Repeat(globalRefreshTime, 0, () =>
            {
                foreach (BasePlayer _player in BasePlayer.activePlayerList)
                {
                    DrawWaypoint(_player, new Vector3(data.x, data.y, data.z), globalRefreshTime, true, data.name);
                }
            });

            timers.Add(new TimerData()
            {
                timer = repeat, name = data.name, data = data
            });
        }
Exemple #8
0
        public static void Load()
        {
            try
            {
                XmlDocument settingsDoc = new XmlDocument();
                settingsDoc.Load(Path.Combine(inputDirectory, "settings.xml"));
                Settings = settingsDoc.SelectNodes("randomizer/setting").Cast <XmlNode>().Select(x => x.InnerText).ToArray();

                XmlDocument waypointDoc = new XmlDocument();
                waypointDoc.Load(Path.Combine(inputDirectory, "waypoints.xml"));
                waypoints = new WaypointData(waypointDoc.SelectNodes("randomizer/item").Cast <XmlNode>()
                                             .ToDictionary(x => x.Attributes["name"].Value, x => new Waypoint
                {
                    logic = x.ChildNodes.Cast <XmlNode>().First(c => c.LocalName.Contains("ogic")).InnerText
                }));

                XmlDocument locationDoc = new XmlDocument();
                locationDoc.Load(Path.Combine(inputDirectory, "locations.xml"));
                locations = new LocationData(locationDoc.SelectNodes("randomizer/item").Cast <XmlNode>()
                                             .ToDictionary(x => x.Attributes["name"].Value, x => new LocationDef
                {
                    logic = x.ChildNodes.Cast <XmlNode>().First(c => c.LocalName.Contains("ogic")).InnerText,
                    pool  = x.ChildNodes.Cast <XmlNode>().First(c => c.LocalName == "pool").InnerText,
                }));

                XmlDocument macroDoc = new XmlDocument();
                macroDoc.Load(Path.Combine(inputDirectory, "macros.xml"));
                macros = macroDoc.SelectNodes("randomizer/macro").Cast <XmlNode>()
                         .ToDictionary(x => x.Attributes["name"].Value, x => x.InnerText);
            }
            catch (FileNotFoundException e)
            {
                LogicSimplifierApp.SendError("Input files expected at " + inputDirectory + " were not found.\n" + e);
                throw e;
            }
            catch (Exception e)
            {
                LogicSimplifierApp.SendError("Malformatted or unusable input files!\n" + e);
                throw e;
            }
        }
        public void WaypointPathfinding()
        {
            var waypointData = new WaypointData();
            var waypoint     = new Waypoint[32];

            for (int i = 0; i < waypoint.Length; ++i)
            {
                waypoint[i] = new Waypoint()
                {
                    link     = new List <int>(4),
                    position = new Vector2(0, i),
                };
            }
            waypoint[0].link.Add(1);
            waypoint[0].link.Add(2);
            waypoint[1].link.Add(6);
            waypoint[2].link.Add(6);
            waypoint[2].link.Add(3);
            waypoint[3].link.Add(4);
            waypoint[4].link.Add(5);
            waypoint[6].link.Add(7);
            waypoint[7].link.Add(8);
            waypoint[7].link.Add(9);
            waypointData.waypoint = waypoint;
            waypointData.MakeBidirectional();
            var graph = new WaypointGraph(waypointData);
            var astar = new AStarPathfinding();

            astar.FindPath(graph, 0, 9);
            CheckPath(astar.FormattedPath(), "path:9-7-6-2-0");
            astar.FindPath(graph, 5, 8);
            CheckPath(astar.FormattedPath(), "path:8-7-6-2-3-4-5");
            astar.FindPath(graph, 5, 31);
            CheckPath(astar.FormattedPath(), "path:31-x-9-7-6-2-3-4-5");

            astar.FindPath(graph, 0, -1);
            CheckPath(astar.FormattedPath(9), "path:9-7-6-2-0");
            CheckPath(astar.FormattedPath(6), "path:6-2-0");
            CheckPath(astar.FormattedPath(4), "path:4-3-2-0");
            CheckPath(astar.FormattedPath(11), "path:11-x-9-7-6-2-0");
        }
Exemple #10
0
    public void Purge()
    {
        if (waypoints.Count <= 0)
        {
            return;
        }

        WaypointData[] waypointsToDestroy = new WaypointData[waypoints.Count];
        WaypointData   waypointToDestroy;

        for (int i = 0; i < waypoints.Count; i++)
        {
            waypointsToDestroy[i] = waypoints[i];
        }

        for (int i = 0; i < waypointsToDestroy.Length; i++)
        {
            waypointToDestroy = waypointsToDestroy[i];
            WaypointData.Destroy(waypointToDestroy.cellData, this);
        }
    }
Exemple #11
0
    public void newPlace(string position, WaypointData.TypeOfPlace type, string name, string direction, string uri, string email, string telephone)
    {
        WaypointData waypoint = new WaypointData(position, type, name, direction, uri, email, telephone);

        _waypointList.Add(waypoint);
        _locations.Add(Conversions.StringToLatLon(position));
        GameObject instance = null;

        switch (type)
        {
        case WaypointData.TypeOfPlace.alojamiento:
            instance = Instantiate(alojamientoPrefab);
            break;

        case WaypointData.TypeOfPlace.barCopas:
            instance = Instantiate(barCopasPrefab);
            break;

        case WaypointData.TypeOfPlace.cafebar:
            instance = Instantiate(cafebarPrefab);
            break;

        case WaypointData.TypeOfPlace.centroTuristico:
            instance = Instantiate(centroTuristicoPrefab);
            break;

        case WaypointData.TypeOfPlace.monumento:
            instance = Instantiate(monumentoPrefab);
            break;

        case WaypointData.TypeOfPlace.restaurante:
            instance = Instantiate(restaurantePrefab);
            break;
        }
        instance.transform.GetChild(1).GetComponent <WayPointColliderHandler>().waypointData = waypoint;
        instance.transform.GetChild(0).GetComponent <TextMesh>().text = name;
        instance.transform.localPosition = _map.GeoToWorldPosition(_locations[_locations.Count - 1], true);
        instance.transform.localScale    = new Vector3(_spawnScale, _spawnScale, _spawnScale);
        _spawnedObjects.Add(instance);
    }
Exemple #12
0
        void setwpCMD(BasePlayer player, string command, string[] args)
        {
            if (!permission.UserHasPermission(player.UserIDString, permissionName))
            {
                player.ChatMessage(msg("No Permission", player.UserIDString));
                return;
            }
            if (args.Length != 1)
            {
                player.ChatMessage(msg("/setwp Invalid Syntax", player.UserIDString));
                return;
            }
            if (!playerWaypointsCache.ContainsKey(player.UserIDString))
            {
                playerWaypointsCache.Add(player.UserIDString, new List <WaypointData>());
            }
            if (playerWaypointsCache[player.UserIDString].Count == maxWaypoints)
            {
                player.ChatMessage(msg("Max Waypoints Allowed", player.UserIDString));
                return;
            }
            foreach (var entry in playerWaypointsCache[player.UserIDString])
            {
                if (args[0] == entry.name)
                {
                    player.ChatMessage(msg("Waypoint Already Exists", player.UserIDString));
                    return;
                }
            }
            WaypointData data = new WaypointData()
            {
                name = args[0], x = player.transform.position.x, y = player.transform.position.y, z = player.transform.position.z
            };

            playerWaypointsCache[player.UserIDString].Add(data);
            DrawWaypoint(player, new Vector3(data.x, data.y, data.z), playerWaypointDisplaytime, false, data.name);
        }
Exemple #13
0
    private static void ReadXmlWaypointDatas(XmlReader reader)
    {
        int                 x, z;
        int                 ownerUniqueID;
        Direction           orientation;
        WaypointManagerData manager = null;
        WaypointData        waypoint;

        if (reader.ReadToDescendant(PStrings.waypointData) == true)
        {
            do
            {
                x           = int.Parse(reader.GetAttribute(PStrings.xCoordinate));
                z           = int.Parse(reader.GetAttribute(PStrings.zCoordinate));
                orientation = (Direction)int.Parse(reader.GetAttribute(PStrings.orientation));

                ownerUniqueID = int.Parse(reader.GetAttribute(PStrings.uniqueID));

                if (obstacles.ContainsKey(ownerUniqueID) == true)
                {
                    manager = (WaypointManagerData)obstacles[ownerUniqueID].GetExtension(PStrings.waypointManager);
                }
                if (items.ContainsKey(ownerUniqueID) == true)
                {
                    manager = (WaypointManagerData)items[ownerUniqueID].GetExtension(PStrings.waypointManager);
                }
                if (entities.ContainsKey(ownerUniqueID) == true)
                {
                    manager = (WaypointManagerData)entities[ownerUniqueID].GetExtension(PStrings.waypointManager);
                }

                waypoint = WaypointData.Instantiate(Metrics.GetCell(new Coordinates(x, z)), manager);
                waypoint.SetOrientation(orientation);
            } while (reader.ReadToNextSibling(PStrings.waypointData));
        }
    }
    private void SaveWaypoints(List <Node> wps)
    {
        var scriptable = ScriptableObject.CreateInstance <WaypointsInfo>();

        scriptable.waypointsData = new List <WaypointData>();
        WaypointData wpData = default;

        for (int i = 0; i < wps.Count; i++)
        {
            wpData.id       = wps[i].Id;
            wpData.position = wps[i].transform.position;

            wpData.connectedNodesID = new List <int>();
            for (int j = 0; j < wps[i].Neighbours.Count; j++)
            {
                wpData.connectedNodesID.Add(wps[i].Neighbours[j].Id);
            }

            scriptable.waypointsData.Add(wpData);
        }

        scriptable.displayConnectionLines   = _setConnections;
        scriptable.radiusDistanceConnection = _radiusDistanceConnection;

        //Guardo el scriptable
        if (!AssetDatabase.IsValidFolder(_saveFolderPath))
        {
            var separatedPath = _saveFolderPath.Split('/');
            AssetDatabase.CreateFolder(separatedPath[0], separatedPath[1]);
        }

        var path = _saveFolderPath + '/' + _saveFilename;

        path = AssetDatabase.GenerateUniqueAssetPath(path);
        AssetDatabase.CreateAsset(scriptable, path);
    }
Exemple #15
0
            public WaypointData(WaypointData orig, Contract contract)
            {
                type = orig.type;
                waypoint.altitude      = orig.waypoint.altitude;
                waypoint.celestialName = orig.waypoint.celestialName;
                waypoint.height        = orig.waypoint.height;
                waypoint.id            = orig.waypoint.id;
                waypoint.index         = orig.waypoint.index;
                waypoint.isClustered   = orig.waypoint.isClustered;
                waypoint.isExplored    = orig.waypoint.isExplored;
                waypoint.isOnSurface   = orig.waypoint.isOnSurface;
                waypoint.landLocked    = orig.waypoint.landLocked;
                waypoint.latitude      = orig.waypoint.latitude;
                waypoint.longitude     = orig.waypoint.longitude;
                waypoint.name          = orig.waypoint.name;

                randomAltitude  = orig.randomAltitude;
                waterAllowed    = orig.waterAllowed;
                forceEquatorial = orig.forceEquatorial;
                nearIndex       = orig.nearIndex;
                nearDistance    = orig.nearDistance;

                SetContract(contract);
            }
Exemple #16
0
        void wpCMD(BasePlayer player, string command, string[] args)
        {
            if (!permission.UserHasPermission(player.UserIDString, permissionName))
            {
                if (!permission.UserHasPermission(player.UserIDString, permissionNameADMIN))
                {
                    player.ChatMessage(msg("No Permission", player.UserIDString));
                    return;
                }
            }
            if (args.Length != 1)
            {
                player.ChatMessage(msg("/wp Invalid Syntax", player.UserIDString));
                return;
            }
            if (!playerWaypointsCache.ContainsKey(player.UserIDString))
            {
                playerWaypointsCache.Add(player.UserIDString, new List <WaypointData>());
            }
            WaypointData data = null;

            foreach (var entry in playerWaypointsCache[player.UserIDString])
            {
                if (entry.name == args[0])
                {
                    data = entry;
                }
            }
            if (data == null)
            {
                player.ChatMessage(msg("Waypoint Not Found", player.UserIDString));
                return;
            }
            DrawWaypoint(player, new Vector3(data.x, data.y, data.z), playerWaypointDisplaytime, false, data.name);
            player.ChatMessage(msg("Waypoint Added", player.UserIDString));
        }
Exemple #17
0
    private void SelectAt(CellData cell)
    {
        if (selectionMode == SelectionMode.Null)
        {
            //////////////////////////////////////////////////////////////////////////////////////
            /// This should never happen but if it does nothing should be created or destroyed ///
            //////////////////////////////////////////////////////////////////////////////////////
        }
        else if (selectionMode == SelectionMode.Obstacle)
        {
            if (inputMode == InputMode.Null)
            {
                //////////////////////////////////////////////////////////////////////////////////////
                /// This should never happen but if it does nothing should be created or destroyed ///
                //////////////////////////////////////////////////////////////////////////////////////
            }
            else if (inputMode == InputMode.Constructive)
            {
                SetSelectedObstacle(cell.obstacle);
            }
            else if (inputMode == InputMode.Destructive)
            {
                SetSelectedObstacle(null);
            }
        }
        else if (selectionMode == SelectionMode.Item)
        {
            if (inputMode == InputMode.Null)
            {
                //////////////////////////////////////////////////////////////////////////////////////
                /// This should never happen but if it does nothing should be created or destroyed ///
                //////////////////////////////////////////////////////////////////////////////////////
            }
            else if (inputMode == InputMode.Constructive)
            {
                SetSelectedItem(cell.item);
            }
            else if (inputMode == InputMode.Destructive)
            {
                SetSelectedItem(null);
            }
        }
        else if (selectionMode == SelectionMode.Entity)
        {
            if (inputMode == InputMode.Null)
            {
                //////////////////////////////////////////////////////////////////////////////////////
                /// This should never happen but if it does nothing should be created or destroyed ///
                //////////////////////////////////////////////////////////////////////////////////////
            }
            else if (inputMode == InputMode.Constructive)
            {
                SetSelectedEntity(cell.entity);
            }
            else if (inputMode == InputMode.Destructive)
            {
                SetSelectedEntity(null);
            }
        }
        else if (selectionMode == SelectionMode.Effect)
        {
            if (inputMode == InputMode.Null)
            {
                //////////////////////////////////////////////////////////////////////////////////////
                /// This should never happen but if it does nothing should be created or destroyed ///
                //////////////////////////////////////////////////////////////////////////////////////
            }
            else if (inputMode == InputMode.Constructive)
            {
                if (effectMode == EffectMode.Null)
                {
                    /////////////////////////////////////////////////////////////////////////
                    /// This should never happen but if it does nothing should be changed ///
                    /////////////////////////////////////////////////////////////////////////
                }
                else if (effectMode == EffectMode.Grass && FoundationData.ValidateHasGrass(cell) == true)
                {
                    if (editColor == true)
                    {
                        cell.foundation.effectColorIndex = activeColor;
                    }
                }
                else if (effectMode == EffectMode.Fog && FoundationData.ValidateHasFog(cell) == true)
                {
                    if (editColor == true)
                    {
                        cell.foundation.effectColorIndex = activeColor;
                    }
                }
                else if (effectMode == EffectMode.Liquid && FoundationData.ValidateHasLiquid(cell) == true)
                {
                    if (editColor == true)
                    {
                        cell.foundation.effectColorIndex = activeColor;
                    }
                }
            }
            else if (inputMode == InputMode.Destructive)
            {
                if (effectMode == EffectMode.Null)
                {
                    /////////////////////////////////////////////////////////////////////////
                    /// This should never happen but if it does nothing should be changed ///
                    /////////////////////////////////////////////////////////////////////////
                }
                else if (effectMode == EffectMode.Grass && FoundationData.ValidateHasGrass(cell) == true)
                {
                    if (editColor == true)
                    {
                        cell.foundation.effectColorIndex = (int)ColI.Green;
                    }
                }
                else if (effectMode == EffectMode.Fog && FoundationData.ValidateHasFog(cell) == true)
                {
                    if (editColor == true)
                    {
                        cell.foundation.effectColorIndex = (int)ColI.Red;
                    }
                }
                else if (effectMode == EffectMode.Liquid && FoundationData.ValidateHasLiquid(cell) == true)
                {
                    if (editColor == true)
                    {
                        cell.foundation.effectColorIndex = (int)ColI.Blue;
                    }
                }
            }
        }
        else if (selectionMode == SelectionMode.Waypoint)
        {
            if (inputMode == InputMode.Null)
            {
                //////////////////////////////////////////////////////////////////////////////////////
                /// This should never happen but if it does nothing should be created or destroyed ///
                //////////////////////////////////////////////////////////////////////////////////////
            }
            else if (inputMode == InputMode.Constructive)
            {
                SetSelectedWaypoint(cell);
            }
            else if (inputMode == InputMode.Destructive)
            {
                SetSelectedWaypoint(cell);

                selectedWaypoint = null;
            }
        }
    }
Exemple #18
0
        public static WaypointGenerator Create(ConfigNode configNode, CelestialBody defaultBody, WaypointGeneratorFactory factory)
        {
            WaypointGenerator wpGenerator = new WaypointGenerator();

            bool valid = true;
            int  index = 0;

            foreach (ConfigNode child in configNode.GetNodes())
            {
                int count = child.HasValue("count") ? Convert.ToInt32(child.GetValue("count")) : 1;
                for (int i = 0; i < count; i++)
                {
                    double?      altitude = null;
                    WaypointData wpData   = new WaypointData(child.name);

                    valid &= ConfigNodeUtil.ParseValue <string>(child, "targetBody", ref wpData.waypoint.celestialName, factory, defaultBody != null ? defaultBody.name : null, Validation.NotNull);
                    valid &= ConfigNodeUtil.ParseValue <string>(child, "name", ref wpData.waypoint.name, factory, (string)null);
                    valid &= ConfigNodeUtil.ParseValue <string>(child, "icon", ref wpData.waypoint.id, factory);
                    valid &= ConfigNodeUtil.ParseValue <double?>(child, "altitude", ref altitude, factory, (double?)null, x => Validation.GE(x.Value, 0.0));

                    // Track the index
                    wpData.waypoint.index = index++;

                    // Get altitude
                    if (altitude == null)
                    {
                        wpData.waypoint.altitude = 0.0;
                        wpData.randomAltitude    = true;
                    }
                    else
                    {
                        wpData.waypoint.altitude = altitude.Value;
                    }

                    // Get settings that differ by type
                    if (child.name == "WAYPOINT")
                    {
                        valid &= ConfigNodeUtil.ParseValue <double>(child, "latitude", ref wpData.waypoint.latitude, factory);
                        valid &= ConfigNodeUtil.ParseValue <double>(child, "longitude", ref wpData.waypoint.longitude, factory);
                    }
                    else if (child.name == "RANDOM_WAYPOINT")
                    {
                        // Get settings for randomization
                        valid &= ConfigNodeUtil.ParseValue <bool>(child, "waterAllowed", ref wpData.waterAllowed, factory, true);
                        valid &= ConfigNodeUtil.ParseValue <bool>(child, "forceEquatorial", ref wpData.forceEquatorial, factory, false);
                    }
                    else if (child.name == "RANDOM_WAYPOINT_NEAR")
                    {
                        // Get settings for randomization
                        valid &= ConfigNodeUtil.ParseValue <bool>(child, "waterAllowed", ref wpData.waterAllowed, factory, true);

                        // Get near waypoint details
                        valid &= ConfigNodeUtil.ParseValue <int>(child, "nearIndex", ref wpData.nearIndex, factory, x => Validation.GE(x, 0));
                        valid &= ConfigNodeUtil.ParseValue <double>(child, "nearDistance", ref wpData.nearDistance, factory, x => Validation.GT(x, 0.0));
                    }
                    else
                    {
                        throw new ArgumentException("Unrecognized waypoint node: '" + child.name + "'");
                    }

                    // Add to the list
                    wpGenerator.waypoints.Add(wpData);
                }
            }

            return(valid ? wpGenerator : null);
        }
        protected override void OnLoad(ConfigNode configNode)
        {
            base.OnLoad(configNode);

            foreach (ConfigNode child in configNode.GetNodes("WAYPOINT"))
            {
                // Read all the waypoint data
                WaypointData wpData = new WaypointData();
                wpData.type = child.GetValue("type");
                wpData.parameter = ConfigNodeUtil.ParseValue<List<string>>(child, "parameter", new List<string>());
                wpData.waypoint.celestialName = child.GetValue("celestialName");
                wpData.waypoint.name = child.GetValue("name");
                wpData.waypoint.id = child.GetValue("icon");
                wpData.waypoint.latitude = Convert.ToDouble(child.GetValue("latitude"));
                wpData.waypoint.longitude = Convert.ToDouble(child.GetValue("longitude"));
                wpData.waypoint.altitude = Convert.ToDouble(child.GetValue("altitude"));
                wpData.waypoint.index = Convert.ToInt32(child.GetValue("index"));
                wpData.waypoint.visible = !(ConfigNodeUtil.ParseValue<bool?>(child, "hidden", (bool?)false).Value);
                wpData.waypoint.isClustered = ConfigNodeUtil.ParseValue<bool?>(child, "clustered", (bool?)false).Value;

                // Workaround for buggy stuff saved by older versions
                if (wpData.parameter.Any() && wpData.parameter.First().StartsWith("System.Collections.Generic.List"))
                {
                    wpData.parameter.Clear();
                }

                // Set contract data
                wpData.SetContract(contract);

                // Create additional waypoint details
                string paramID = wpData.parameter.FirstOrDefault();
                if (wpData.waypoint.visible && (!wpData.parameter.Any() || contract.AllParameters.
                    Where(p => p.ID == paramID && p.State == ParameterState.Complete).Any()))
                {
                    AddWayPoint(wpData.waypoint);
                }

                // Add to the global list
                waypoints.Add(wpData);
            }
        }
Exemple #20
0
    //loads game data
    public void LoadGame()
    {
        //Map Data
        MapData mapData = SaveSystem.LoadMap(WorldData.currentlyLoadedName);

        for (int i = 0; i < mapData.amplitude.Length; i++)
        {
            mg.terrainOctaves[i].amplitude = mapData.amplitude[i];
            mg.terrainOctaves[i].frequency = mapData.frequency[i];
        }
        mg.GenerateMap(mapData.seed);

        //Player Data
        PlayerData playerData = SaveSystem.LoadPlayer(WorldData.currentlyLoadedName);

        pc.speed              = playerData.speed;
        pc.swimmingSpeed      = playerData.swimSpeed;
        pc.sprintSpeed        = playerData.sprintSpeed;
        pc.jumpForce          = playerData.jumpForce;
        pc.transform.position = new Vector3(playerData.position[0], playerData.position[1], playerData.position[2]);
        pc.transform.rotation = Quaternion.Euler(new Vector3(0, playerData.playerRot, 0));

        //Inventory
        InventoryData inventoryData = SaveSystem.LoadInventory(WorldData.currentlyLoadedName);

        for (int i = 0; i < inventoryData.itemName.Length; i++)
        {
            string path = "ItemIcons/" + inventoryData.spriteName[i];
            Sprite icon = (Sprite)Resources.Load(path, typeof(Sprite));

            if (icon == null)
            {
                Debug.LogError("File not found: " + path);
            }
            pi.LoadInventory(inventoryData.itemName[i], icon, inventoryData.weight[i], inventoryData.value[i]);
        }

        //Player attribute data
        AttributeData attributeData = SaveSystem.LoadAttributes(WorldData.currentlyLoadedName);

        pa.bCanRegenHealth  = attributeData.canRegen[0];
        pa.bCanRegenStamina = attributeData.canRegen[1];
        pa.bCanRegenThirst  = attributeData.canRegen[2];
        pa.bCanRegenHunger  = attributeData.canRegen[3];

        pa.healthMeterDrainSpeed  = attributeData.drainSpeeds[0];
        pa.staminaMeterDrainSpeed = attributeData.drainSpeeds[1];
        pa.thirstMeterDrainSpeed  = attributeData.drainSpeeds[2];
        pa.hungerMeterDrainSpeed  = attributeData.drainSpeeds[3];

        pa.healthMeterRegenSpeed  = attributeData.regenSpeeds[0];
        pa.staminaMeterRegenSpeed = attributeData.regenSpeeds[1];
        pa.thirstMeterRegenSpeed  = attributeData.regenSpeeds[2];
        pa.hungerMeterRegenSpeed  = attributeData.regenSpeeds[3];

        pa.maxHealthMeter  = attributeData.maxValues[0];
        pa.maxStaminaMeter = attributeData.maxValues[1];
        pa.maxThirstMeter  = attributeData.maxValues[2];
        pa.maxHungerMeter  = attributeData.maxValues[3];

        pa.ChangeHealthLevel(attributeData.currentValues[0], false);
        pa.ChangeStaminaLevel(attributeData.currentValues[1], false);
        pa.ChangeThirstLevel(attributeData.currentValues[2], false);
        pa.ChangeHungerLevel(attributeData.currentValues[3], false);

        //Currently loaded chunks
        ChunkData chunkData = SaveSystem.LoadLoadedChunks(WorldData.currentlyLoadedName);

        pcl.chunknames = chunkData.loadedChunks;
        pcl.LoadMap();

        //Waypoint data
        WaypointData waypointData = SaveSystem.LoadWaypoints(WorldData.currentlyLoadedName);

        wm.waypoints = new Waypoint[waypointData.waypointIDs.Length];
        for (int i = 0; i < wm.waypoints.Length; i++)
        {
            if (waypointData.waypointInUse[i] == true) // if waypoint is in use
            {
                string name    = waypointData.waypointNames[i];
                bool   enabled = waypointData.waypointEnabled[i];

                float r = waypointData.waypointColors[i, 0];
                float g = waypointData.waypointColors[i, 1];
                float b = waypointData.waypointColors[i, 2];

                float x = waypointData.waypointLocations[i, 0];
                float y = waypointData.waypointLocations[i, 1];
                float z = waypointData.waypointLocations[i, 2];

                wm.AddWaypoint(name, new Vector3(x, y, z), new Color(r, g, b), enabled);
            }
        }

        //Load environment data
        EnvironmentData envData = SaveSystem.LoadEnvironment(WorldData.currentlyLoadedName);

        env.timeMultiplier = envData.timeMultiplier;
        env.daysInMonth    = envData.daysInMonth;
        env.monthsInYear   = envData.MonthsInYear;
        env.Clockwork      = envData.clockWork;

        env.tempMultiplier    = envData.tempMultiplier;
        env.bIsTempFahrenheit = envData.tempFahrenheit;
        env.temperature       = envData.temperature;
        env.tempPrecision     = envData.tempPrecision;

        env.windStrengthMultiplier = envData.windStrengthMultiplier;
        env.windStrength           = envData.windStrength;
        env.windStrengthPrecision  = envData.windStrengthPrecision;

        env.windAnglePrecision = envData.windAnglePrecision;
        env.windAngle          = envData.windAngle;

        env.seasonEnum  = (EnvironmentController.ESeasonEnum)System.Enum.Parse(typeof(EnvironmentController.ESeasonEnum), envData.season);
        env.weatherEnum = (EnvironmentController.EWeatherEnum)System.Enum.Parse(typeof(EnvironmentController.EWeatherEnum), envData.weather);
    }
        private void AddWayPoint(WaypointData wpData)
        {
            if (wpData.isAdded)
            {
                return;
            }

            Waypoint waypoint = wpData.waypoint;

            // No contract, no waypoint
            if (waypoint.contractReference == null)
            {
                return;
            }

            // Always surface and navigatable
            waypoint.isOnSurface = true;
            waypoint.isNavigatable = true;

            // Show only active waypoints in flight, but show offered as well in the tracking station
            if (HighLogic.LoadedScene == GameScenes.TRACKSTATION || HighLogic.LoadedScene == GameScenes.FLIGHT)
            {
                ContractConfiguratorParameters parms = HighLogic.CurrentGame.Parameters.CustomParams<ContractConfiguratorParameters>();

                if (contract.ContractState == Contract.State.Active && (parms.DisplayActiveWaypoints || HighLogic.LoadedScene != GameScenes.TRACKSTATION) ||
                    contract.ContractState == Contract.State.Offered && parms.DisplayOfferedWaypoints && HighLogic.LoadedScene == GameScenes.TRACKSTATION)
                {
                    WaypointManager.AddWaypoint(waypoint);
                    wpData.isAdded = true;
                }
            }
        }
        protected override void OnLoad(ConfigNode configNode)
        {
            base.OnLoad(configNode);

            foreach (ConfigNode child in configNode.GetNodes("WAYPOINT"))
            {
                // Read all the waypoint data
                WaypointData wpData = new WaypointData();
                wpData.type = child.GetValue("type");
                wpData.parameter = ConfigNodeUtil.ParseValue<List<string>>(child, "parameter", new List<string>());
                wpData.names = ConfigNodeUtil.ParseValue<List<string>>(child, "names", new List<string>());
                wpData.waypoint.celestialName = child.GetValue("celestialName");
                wpData.waypoint.name = child.GetValue("name");
                wpData.waypoint.id = child.GetValue("icon");
                wpData.waypoint.latitude = Convert.ToDouble(child.GetValue("latitude"));
                wpData.waypoint.longitude = Convert.ToDouble(child.GetValue("longitude"));
                wpData.waypoint.altitude = Convert.ToDouble(child.GetValue("altitude"));
                wpData.waypoint.index = Convert.ToInt32(child.GetValue("index"));
                wpData.waypoint.visible = !(ConfigNodeUtil.ParseValue<bool?>(child, "hidden", (bool?)false).Value);
                wpData.waypoint.isClustered = ConfigNodeUtil.ParseValue<bool?>(child, "clustered", (bool?)false).Value;

                string pqsCityName = ConfigNodeUtil.ParseValue<string>(child, "pqsCity", null);
                if (pqsCityName != null)
                {
                    CelestialBody body = FlightGlobals.Bodies.Where(b => b.name == wpData.waypoint.celestialName).First();
                    wpData.pqsCity = body.GetComponentsInChildren<PQSCity>(true).Where(pqs => pqs.name == pqsCityName).First();
                    wpData.pqsOffset = ConfigNodeUtil.ParseValue<Vector3d>(child, "pqsOffset");
                }

                wpData.randomAltitude = ConfigNodeUtil.ParseValue<bool?>(child, "randomAltitude", (bool?)false).Value;
                wpData.underwater = ConfigNodeUtil.ParseValue<bool?>(child, "underwater", (bool?)false).Value;

                // Set contract data
                wpData.SetContract(contract);

                // Create additional waypoint details
                string paramID = wpData.parameter.FirstOrDefault();
                if (wpData.waypoint.visible && (!wpData.parameter.Any() || contract.AllParameters.
                    Where(p => p.ID == paramID && p.State == ParameterState.Complete).Any()))
                {
                    AddWayPoint(wpData);
                }

                // Add to the global list
                waypoints.Add(wpData);
            }
        }
        public static WaypointGenerator Create(ConfigNode configNode, WaypointGeneratorFactory factory)
        {
            WaypointGenerator wpGenerator = new WaypointGenerator();

            bool valid = true;
            int  index = 0;

            foreach (ConfigNode child in ConfigNodeUtil.GetChildNodes(configNode))
            {
                DataNode dataNode = new DataNode("WAYPOINT_" + index, factory.dataNode, factory);
                try
                {
                    ConfigNodeUtil.SetCurrentDataNode(dataNode);
                    dataNode["type"] = child.name;

                    double?      altitude = null;
                    WaypointData wpData   = new WaypointData(child.name);

                    // Use an expression to default - then it'll work for dynamic contracts
                    if (!child.HasValue("targetBody"))
                    {
                        child.AddValue("targetBody", "@/targetBody");
                    }
                    valid &= ConfigNodeUtil.ParseValue <CelestialBody>(child, "targetBody", x => wpData.waypoint.celestialName = x != null ? x.name : "", factory);

                    valid &= ConfigNodeUtil.ParseValue <List <string> >(child, "name", x => wpData.names = x, factory, new List <string>());
                    valid &= ConfigNodeUtil.ParseValue <double?>(child, "altitude", x => altitude = x, factory, (double?)null);
                    valid &= ConfigNodeUtil.ParseValue <List <string> >(child, "parameter", x => wpData.parameter = x, factory, new List <string>());
                    valid &= ConfigNodeUtil.ParseValue <bool>(child, "hidden", x => wpData.waypoint.visible = !x, factory, false);
                    if (!wpData.waypoint.visible)
                    {
                        valid &= ConfigNodeUtil.ParseValue <string>(child, "icon", x => wpData.waypoint.id = x, factory, "");
                    }
                    else
                    {
                        valid &= ConfigNodeUtil.ParseValue <string>(child, "icon", x => wpData.waypoint.id = x, factory);
                    }

                    // The FinePrint logic is such that it will only look in Squad/Contracts/Icons for icons.
                    // Cheat this by hacking the path in the game database.
                    if (wpData.waypoint.id.Contains("/"))
                    {
                        GameDatabase.TextureInfo texInfo = GameDatabase.Instance.databaseTexture.Where(t => t.name == wpData.waypoint.id).FirstOrDefault();
                        if (texInfo != null)
                        {
                            texInfo.name = "Squad/Contracts/Icons/" + wpData.waypoint.id;
                        }
                    }

                    valid &= ConfigNodeUtil.ParseValue <bool>(child, "underwater", x => wpData.underwater = x, factory, false);
                    valid &= ConfigNodeUtil.ParseValue <bool>(child, "clustered", x => wpData.waypoint.isClustered = x, factory, false);

                    // Track the index
                    wpData.waypoint.index = index++;

                    // Get altitude
                    if (altitude == null)
                    {
                        wpData.waypoint.altitude = 0.0;
                        wpData.randomAltitude    = true;
                    }
                    else
                    {
                        wpData.waypoint.altitude = altitude.Value;
                    }

                    // Get settings that differ by type
                    if (child.name == "WAYPOINT")
                    {
                        valid &= ConfigNodeUtil.ParseValue <double>(child, "latitude", x => wpData.waypoint.latitude = x, factory);
                        valid &= ConfigNodeUtil.ParseValue <double>(child, "longitude", x => wpData.waypoint.longitude = x, factory);
                    }
                    else if (child.name == "RANDOM_WAYPOINT")
                    {
                        // Get settings for randomization
                        valid &= ConfigNodeUtil.ParseValue <bool>(child, "waterAllowed", x => wpData.waterAllowed = x, factory, true);
                        valid &= ConfigNodeUtil.ParseValue <bool>(child, "forceEquatorial", x => wpData.forceEquatorial = x, factory, false);
                        valid &= ConfigNodeUtil.ParseValue <int>(child, "count", x => wpData.count = x, factory, 1, x => Validation.GE(x, 1));
                    }
                    else if (child.name == "RANDOM_WAYPOINT_NEAR")
                    {
                        // Get settings for randomization
                        valid &= ConfigNodeUtil.ParseValue <bool>(child, "waterAllowed", x => wpData.waterAllowed = x, factory, true);

                        // Get near waypoint details
                        valid &= ConfigNodeUtil.ParseValue <int>(child, "nearIndex", x => wpData.nearIndex = x, factory,
                                                                 x => Validation.GE(x, 0) && Validation.LT(x, wpGenerator.waypoints.Count));
                        valid &= ConfigNodeUtil.ParseValue <bool>(child, "chained", x => wpData.chained = x, factory, false);
                        valid &= ConfigNodeUtil.ParseValue <int>(child, "count", x => wpData.count = x, factory, 1, x => Validation.GE(x, 1));

                        // Get distances
                        valid &= ConfigNodeUtil.ParseValue <double>(child, "minDistance", x => wpData.minDistance = x, factory, 0.0, x => Validation.GE(x, 0.0));
                        valid &= ConfigNodeUtil.ParseValue <double>(child, "maxDistance", x => wpData.maxDistance = x, factory, x => Validation.GT(x, 0.0));
                    }
                    else if (child.name == "PQS_CITY")
                    {
                        wpData.randomAltitude = false;
                        string dummy = null;
                        valid &= ConfigNodeUtil.ParseValue <string>(child, "pqsCity", x => dummy = x, factory, x =>
                        {
                            bool v = true;
                            if (!string.IsNullOrEmpty(wpData.waypoint.celestialName))
                            {
                                try
                                {
                                    CelestialBody body = FlightGlobals.Bodies.Where(b => b.name == wpData.waypoint.celestialName).First();
                                    wpData.pqsCity     = body.GetComponentsInChildren <PQSCity>(true).Where(pqs => pqs.name == x).First();
                                }
                                catch (Exception e)
                                {
                                    LoggingUtil.LogError(typeof(WaypointGenerator), "Couldn't load PQSCity with name '" + x + "'");
                                    LoggingUtil.LogException(e);
                                    v = false;
                                }
                            }
                            else
                            {
                                // Force this to get re-run when the targetBody is loaded
                                throw new DataNode.ValueNotInitialized("/targetBody");
                            }
                            return(v);
                        });
                        valid &= ConfigNodeUtil.ParseValue <Vector3d>(child, "pqsOffset", x => wpData.pqsOffset = x, factory, new Vector3d());
                    }
                    else
                    {
                        LoggingUtil.LogError(factory, "Unrecognized waypoint node: '" + child.name + "'");
                        valid = false;
                    }

                    // Check for unexpected values
                    valid &= ConfigNodeUtil.ValidateUnexpectedValues(child, factory);

                    // Copy waypoint data
                    WaypointData old = wpData;
                    for (int i = 0; i < old.count; i++)
                    {
                        wpData = new WaypointData(old, null);
                        wpGenerator.waypoints.Add(wpData);

                        if (old.parameter.Any())
                        {
                            wpData.parameter = new List <string>();
                            wpData.parameter.Add(old.parameter.Count() == 1 ? old.parameter.First() : old.parameter.ElementAtOrDefault(i));
                        }

                        // Set the name
                        if (old.names.Any())
                        {
                            wpData.waypoint.name = (old.names.Count() == 1 ? old.names.First() : old.names.ElementAtOrDefault(i));
                        }
                        if (string.IsNullOrEmpty(wpData.waypoint.name) || wpData.waypoint.name.ToLower() == "site")
                        {
                            wpData.waypoint.name = StringUtilities.GenerateSiteName(random.Next(), wpData.waypoint.celestialBody, !wpData.waterAllowed);
                        }

                        // Handle waypoint chaining
                        if (wpData.chained && i != 0)
                        {
                            wpData.nearIndex = wpGenerator.waypoints.Count - 2;
                        }
                    }
                }
                finally
                {
                    ConfigNodeUtil.SetCurrentDataNode(factory.dataNode);
                }
            }

            return(valid ? wpGenerator : null);
        }
Exemple #24
0
    public WaypointData JsonToWaypoint(string t, TypeOfPlace a, bool todo)
    {
        string[] splitArray  = new string[10000];
        string[] splitArray2 = new string[10000];

        string coordenadas, url, telefono, nombre, email, direccion;

        TypeOfPlace tipo;

        //Coordenadas
        splitArray = t.Split(new string[] { "[" }, StringSplitOptions.None);
        if (!splitArray[0].Equals(t))
        {
            splitArray2 = splitArray[1].Split(new string[] { "]" }, StringSplitOptions.None);
            splitArray  = splitArray2[0].Split(new string[] { "," }, StringSplitOptions.None);
            coordenadas = splitArray[1] + ", " + splitArray[0];
        }
        else
        {
            coordenadas = "";
        }

        //URL del lugar
        splitArray = t.Split(new string[] { "\"schema_url\" : \"" }, StringSplitOptions.None);
        if (!splitArray[0].Equals(t))
        {
            splitArray2 = splitArray[1].Split(new string[] { "\"" }, StringSplitOptions.None);
            url         = splitArray2[0];
        }
        else
        {
            url = "";
        }

        //email del lugar
        splitArray = t.Split(new string[] { "\"schema_email\" : \"" }, StringSplitOptions.None);
        if (!splitArray[0].Equals(t))
        {
            splitArray2 = splitArray[1].Split(new string[] { "\"" }, StringSplitOptions.None);
            email       = splitArray2[0];
        }
        else
        {
            email = "";
        }

        //teléfono del lugar
        splitArray = t.Split(new string[] { "\"schema_telephone\" : \"" }, StringSplitOptions.None);
        if (!splitArray[0].Equals(t))
        {
            splitArray2 = splitArray[1].Split(new string[] { "\"" }, StringSplitOptions.None);
            telefono    = splitArray2[0];
        }
        else
        {
            telefono = "";
        }

        //email del lugar
        splitArray = t.Split(new string[] { "\"rdfs_label\" : \"" }, StringSplitOptions.None);
        if (!splitArray[0].Equals(t))
        {
            splitArray2 = splitArray[1].Split(new string[] { "\"" }, StringSplitOptions.None);
            nombre      = splitArray2[0];
        }
        else
        {
            nombre = "";
        }

        //email del lugar
        splitArray = t.Split(new string[] { "\"schema_address_streetAddress\" : \"" }, StringSplitOptions.None);
        if (!splitArray[0].Equals(t))
        {
            splitArray2 = splitArray[1].Split(new string[] { "\"" }, StringSplitOptions.None);
            direccion   = splitArray2[0];
        }
        else
        {
            direccion = "";
        }

        if (todo)
        {
            //tipo
            splitArray = t.Split(new string[] { "\"type\" : \"" }, StringSplitOptions.None);

            splitArray2 = splitArray[1].Split(new string[] { "\"" }, StringSplitOptions.None);
            switch (splitArray2[0])
            {
            case "0":
                tipo = TypeOfPlace.alojamiento;
                break;

            case "1":
                tipo = TypeOfPlace.barCopas;
                break;

            case "2":
                tipo = TypeOfPlace.cafebar;
                break;

            case "3":
                tipo = TypeOfPlace.centroTuristico;
                break;

            case "4":
                tipo = TypeOfPlace.monumento;
                break;

            case "5":
                tipo = TypeOfPlace.restaurante;
                break;

            default:
                tipo = TypeOfPlace.cafebar;
                //Debug.Log("FALLO: " + t);
                break;
            }
        }
        else
        {
            tipo = a;
        }
        WaypointData final = new WaypointData(coordenadas, tipo, nombre, direccion, url, email, telefono);

        return(final);
    }
Exemple #25
0
    public override void OnInspectorGUI()
    {
        NPC npc = Selection.activeGameObject.GetComponent<NPC>();
        npc.Start(); // we load npcData

        if (m_editMode)
        {
            GUILayout.Label("To add a Waypoint: wheel/middle click in the desired position.\n To change the order, edit Waypoint's name.\n");
            if (GUILayout.Button("Stop Editing"))
            {
                WaypointData wp;
                m_editMode = false;
                checkContainer();

                // destroy old waypoints
                foreach (WaypointData waypoint in Service.db.Select<WaypointData>("FROM " + WaypointData.TABLE_NAME+" WHERE npc==?", npc.Id)) {
                    waypoint.delete();
                }

                // save new waypoints
                foreach (Transform child in m_container.transform)
                {
                    wp = new WaypointData();
                    wp.npc = npc.Id;
                    wp.position = child.transform.position;
                    wp.create();
                }
                DestroyImmediate(m_container);
                m_count = 0;

                // copy waypoints to clipboard
                TextEditor te = new TextEditor();
                te.content = new GUIContent(coords);
                te.SelectAll();
                te.Copy();
            }
        }
        else
        {
            if (GUILayout.Button("Start Editing"))
            {
                m_editMode = true;
                checkContainer();
                resetList();

                // show existing waypoints
                foreach (WaypointData waypoint in npc.waypoints) {
                    createWaypoint(waypoint.position);
                }
            }
            if (coords.Length > 0) {
                GUILayout.Label("\nCurrent Waypoints:");
                nothing = GUILayout.TextArea(coords);
            }
        }

        if (GUILayout.Button("Reset"))
        {
            m_count = 0;
            nothing = "";
            coords = "";
            checkContainer();
            DestroyImmediate(m_container);
        }
    }
        /// <summary>
        /// Copy constructor.
        /// </summary>
        public WaypointGenerator(WaypointGenerator orig, ConfiguredContract contract)
            : base()
        {
            foreach (WaypointData old in orig.waypoints)
            {
                // Copy waypoint data
                for (int i = 0; i < old.count; i++)
                {
                    WaypointData wpData = new WaypointData(old, contract);
                    waypoints.Add(wpData);

                    if (old.parameter.Any())
                    {
                        wpData.parameter = new List<string>();
                        wpData.parameter.Add(old.parameter.Count() == 1 ? old.parameter.First() : old.parameter.ElementAtOrDefault(i));
                    }
                }
            }
            initialized = orig.initialized;
            orig.initialized = false;
            this.contract = contract;

            Initialize();
        }
Exemple #27
0
    IEnumerator CreateWayPointDelayed(WaypointData wp, bool withName)
    {
        yield return(new WaitForSeconds(Random.Range(0, 0.5f)));

        newPlace(wp, withName);
    }
Exemple #28
0
        public static WaypointGenerator Create(ConfigNode configNode, CelestialBody defaultBody, WaypointGeneratorFactory factory)
        {
            WaypointGenerator wpGenerator = new WaypointGenerator();

            bool valid = true;
            int  index = 0;

            foreach (ConfigNode child in ConfigNodeUtil.GetChildNodes(configNode))
            {
                double?      altitude = null;
                WaypointData wpData   = new WaypointData(child.name);

                valid &= ConfigNodeUtil.ParseValue <string>(child, "targetBody", x => wpData.waypoint.celestialName = x, factory, defaultBody != null ? defaultBody.name : null, Validation.NotNull);
                valid &= ConfigNodeUtil.ParseValue <string>(child, "name", x => wpData.waypoint.name = x, factory, (string)null);
                valid &= ConfigNodeUtil.ParseValue <double?>(child, "altitude", x => altitude = x, factory, (double?)null);
                valid &= ConfigNodeUtil.ParseValue <string>(child, "parameter", x => wpData.parameter = x, factory, "");
                valid &= ConfigNodeUtil.ParseValue <bool>(child, "hidden", x => wpData.hidden = x, factory, false);
                if (wpData.hidden)
                {
                    valid &= ConfigNodeUtil.ParseValue <string>(child, "icon", x => wpData.waypoint.id = x, factory, "");
                }
                else
                {
                    valid &= ConfigNodeUtil.ParseValue <string>(child, "icon", x => wpData.waypoint.id = x, factory);
                }

                // The FinePrint logic is such that it will only look in Squad/Contracts/Icons for icons.
                // Cheat this by hacking the path in the game database.
                if (wpData.waypoint.id.Contains("/"))
                {
                    GameDatabase.TextureInfo texInfo = GameDatabase.Instance.databaseTexture.Where(t => t.name == wpData.waypoint.id).FirstOrDefault();
                    if (texInfo != null)
                    {
                        texInfo.name = "Squad/Contracts/Icons/" + wpData.waypoint.id;
                    }
                }

                // Track the index
                wpData.waypoint.index = index++;

                // Get altitude
                if (altitude == null)
                {
                    wpData.waypoint.altitude = 0.0;
                    wpData.randomAltitude    = true;
                }
                else
                {
                    wpData.waypoint.altitude = altitude.Value;
                }

                DataNode dataNode = new DataNode("WAYPOINT_" + (index - 1), factory.dataNode, factory);
                try
                {
                    ConfigNodeUtil.SetCurrentDataNode(dataNode);

                    // Get settings that differ by type
                    if (child.name == "WAYPOINT")
                    {
                        valid &= ConfigNodeUtil.ParseValue <double>(child, "latitude", x => wpData.waypoint.latitude = x, factory);
                        valid &= ConfigNodeUtil.ParseValue <double>(child, "longitude", x => wpData.waypoint.longitude = x, factory);
                    }
                    else if (child.name == "RANDOM_WAYPOINT")
                    {
                        // Get settings for randomization
                        valid &= ConfigNodeUtil.ParseValue <bool>(child, "waterAllowed", x => wpData.waterAllowed = x, factory, true);
                        valid &= ConfigNodeUtil.ParseValue <bool>(child, "forceEquatorial", x => wpData.forceEquatorial = x, factory, false);
                        valid &= ConfigNodeUtil.ParseValue <int>(child, "count", x => wpData.count = x, factory, 1, x => Validation.GE(x, 1));
                    }
                    else if (child.name == "RANDOM_WAYPOINT_NEAR")
                    {
                        // Get settings for randomization
                        valid &= ConfigNodeUtil.ParseValue <bool>(child, "waterAllowed", x => wpData.waterAllowed = x, factory, true);

                        // Get near waypoint details
                        valid &= ConfigNodeUtil.ParseValue <int>(child, "nearIndex", x => wpData.nearIndex = x, factory, x => Validation.GE(x, 0));
                        valid &= ConfigNodeUtil.ParseValue <int>(child, "count", x => wpData.count = x, factory, 1, x => Validation.GE(x, 1));

                        // Get distances
                        valid &= ConfigNodeUtil.ParseValue <double>(child, "minDistance", x => wpData.minDistance = x, factory, 0.0, x => Validation.GE(x, 0.0));

                        // To be deprecated
                        if (child.HasValue("nearDistance"))
                        {
                            valid &= ConfigNodeUtil.ParseValue <double>(child, "nearDistance", x => wpData.maxDistance = x, factory, x => Validation.GT(x, 0.0));
                            LoggingUtil.LogWarning(factory, "The 'nearDistance' attribute is obsolete as of Contract Configurator 0.7.4.  It will be removed in 1.0.0 in favour of minDistance/maxDistance.");
                        }
                        else
                        {
                            valid &= ConfigNodeUtil.ParseValue <double>(child, "maxDistance", x => wpData.maxDistance = x, factory, x => Validation.GT(x, wpData.minDistance));
                        }
                    }
                    else if (child.name == "PQS_CITY")
                    {
                        wpData.randomAltitude = false;
                        string pqsCity = null;
                        valid &= ConfigNodeUtil.ParseValue <string>(child, "pqsCity", x => pqsCity = x, factory);
                        if (pqsCity != null)
                        {
                            try
                            {
                                CelestialBody body = FlightGlobals.Bodies.Where(b => b.name == wpData.waypoint.celestialName).First();
                                wpData.pqsCity = body.GetComponentsInChildren <PQSCity>(true).Where(pqs => pqs.name == pqsCity).First();
                            }
                            catch (Exception e)
                            {
                                LoggingUtil.LogError(typeof(WaypointGenerator), "Couldn't load PQSCity with name '" + pqsCity + "'");
                                LoggingUtil.LogException(e);
                                valid = false;
                            }
                        }
                        valid &= ConfigNodeUtil.ParseValue <Vector3d>(child, "pqsOffset", x => wpData.pqsOffset = x, factory, new Vector3d());
                    }
                    else
                    {
                        LoggingUtil.LogError(factory, "Unrecognized waypoint node: '" + child.name + "'");
                        valid = false;
                    }
                }
                finally
                {
                    ConfigNodeUtil.SetCurrentDataNode(factory.dataNode);
                }

                // Add to the list
                wpGenerator.waypoints.Add(wpData);
            }

            return(valid ? wpGenerator : null);
        }
Exemple #29
0
    private void SetSelectedWaypoint(CellData cellData)
    {
        Metrics.WaypointVisuals(false);
        WaypointManagerData waypointManager = null;
        bool isValidPlacement = false;

        if (selectedObstacle != null)
        {
            waypointManager = (WaypointManagerData)selectedObstacle.GetExtension(PStrings.waypointManager);
        }
        else if (selectedItem != null)
        {
            waypointManager = (WaypointManagerData)selectedItem.GetExtension(PStrings.waypointManager);
        }
        else if (selectedEntity != null)
        {
            waypointManager = (WaypointManagerData)selectedEntity.GetExtension(PStrings.waypointManager);
        }

        if (waypointManager == null)
        {
            return;
        }

        if (inputMode == InputMode.Constructive)
        {
            selectedWaypoint = waypointManager.GetWaypointAt(cellData);

            if (selectedWaypoint == null)
            {
                if (selectedObstacle != null)
                {
                    isValidPlacement = selectedObstacle.Validation(cellData, activeDirection);
                }
                else if (selectedItem != null)
                {
                    isValidPlacement = selectedItem.Validation(cellData);
                }
                else if (selectedEntity != null)
                {
                    isValidPlacement = selectedEntity.Validation(cellData);
                }

                if (isValidPlacement == true)
                {
                    selectedWaypoint = WaypointData.Instantiate(cellData, waypointManager);
                }
            }
            else
            {
                editorUI.SetSelectWaypoint();
            }

            if (selectedWaypoint != null)
            {
                editorUI.waypointSelectionUI.SetUIBasedOn(waypointManager, selectedWaypoint);
            }
        }
        else if (inputMode == InputMode.Destructive)
        {
            WaypointData.Destroy(cellData, waypointManager);
        }
    }
        private void SetAltitude(WaypointData wpData, CelestialBody body)
        {
            if (wpData.randomAltitude)
            {
                if (wpData.underwater && body.ocean)
                {
                    Vector3d radialVector = QuaternionD.AngleAxis(wpData.waypoint.longitude, Vector3d.down) *
                      QuaternionD.AngleAxis(wpData.waypoint.latitude, Vector3d.forward) * Vector3d.right;
                    double oceanFloor = body.pqsController.GetSurfaceHeight(radialVector) - body.pqsController.radius;

                    wpData.waypoint.altitude = random.NextDouble() * (oceanFloor);
                }
                else if (body.atmosphere)
                {
                    wpData.waypoint.altitude = random.NextDouble() * (body.atmosphereDepth);
                }
                else
                {
                    wpData.waypoint.altitude = 0.0;
                }
            }
            // Clamp underwater waypoints to sea-floor
            else if (wpData.underwater)
            {
                Vector3d radialVector = QuaternionD.AngleAxis(wpData.waypoint.longitude, Vector3d.down) *
                  QuaternionD.AngleAxis(wpData.waypoint.latitude, Vector3d.forward) * Vector3d.right;
                double oceanFloor = body.pqsController.GetSurfaceHeight(radialVector) - body.pqsController.radius;

                wpData.waypoint.altitude = Math.Max(oceanFloor, wpData.waypoint.altitude);
            }
        }
Exemple #31
0
	public virtual void Generate() 
	{
		Data = ModelLevel.GetWaypointByIndex(Index);
	}
Exemple #32
0
    // This method could really be improved. Some of the last parts could be done in a separate thread. However, the lagging still remains.
    // Apparently this is a known issue, and the only thing I could think of that might help, was to read smaller parts of the camera per frame and then
    // merge them all together. Would need to see if it works.

    // Also, by using WaitForEndOfFrame, we now can't exit Game Mode. We could:
    // 1. Move the debug logic into Game Mode
    // 2. Make this a MonoBehaviour and use LateUpdate instead of a Coroutine for the method ProcessWaypoints
    private IEnumerator ProcessWaypoints()
    {
        while (waypointsProcessed < totalWaypoints)
        {
            if (waypointsToProcess.Count > 0)
            {
                Debug.Log(string.Format("Capturing image. {0}/{1}", waypointsProcessed + 1, totalWaypoints));
                WaypointData waypointData = waypointsToProcess.Dequeue();
                Waypoint     waypoint     = waypointData.waypoint;

                // Move the camera to the waypoint
                gameObject.transform.SetPositionAndRotation(waypoint.dronePosition, waypoint.droneRotation);

                // Wait until the frame ends
                yield return(new WaitForEndOfFrame());

                // Render the camera and store it in a texture
                Texture2D screenShot = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.RGB24, false);
                camera.Render();

                yield return(null);

                // Read the render texture into the Texture2D
                RenderTexture.active = renderTexture;
                screenShot.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
                RenderTexture.active = null; //Added to avoid errors

                yield return(null);

                // Check for visible GCPs from the curreny waypoint
                string imageName = GetImageName(waypointData.waypointNumber);
                gcpManager.CheckForVisibleGCPs(screenShot, camera, imageName);

                yield return(null);

                // Save the texture into disk and then delete it
                SaveImage(screenShot, imageName);
                Object.Destroy(screenShot);

                yield return(null);

                // Geotag the image properly
                geoTagger.TagImage(waypoint, Path.Combine(folderPath, imageName));

                // Update number or waypoints processed
                waypointsProcessed++;
            }
            else
            {
                // If there are no waypoint to process, wait for a second before checking again
                yield return(new WaitForSeconds(1));
            }
        }
        // Finished processing all the waypoints. Wait a few seconds for the possible tagging to end
        yield return(new WaitForSeconds(2));

        // Destroy the created GameObject and render texture
        Object.Destroy(gameObject);
        Object.Destroy(renderTexture);

        // Write GCP file to disk
        gcpManager.WriteToFile(georeferencing, folderPath);

        // Generate event for potential listeners
        OnProcessedAllWaypoints?.Invoke();
    }
Exemple #33
0
    public virtual void SetWaypoints(List <WaypointData> waypoints)
    {
        // invalid
        if (waypoints == null || waypoints.Count < 2)
        {
            View.SetActive(false);
            return;
        }

        View.SetActive(true);

        int numberOfQuads = waypoints.Count - 1;

        _mesh = new Mesh();

        float totalDistance   = GetPathDistance(waypoints);
        float currentDistance = 0f;

        var uvs       = new Vector2[numberOfQuads * 4];
        var vertices  = new Vector3[numberOfQuads * 4];
        var colors    = new Color[numberOfQuads * 4];
        var triangles = new int[numberOfQuads * 6];

        for (int i = 0; i < numberOfQuads; i++)
        {
            WaypointData startWaypoint = waypoints[i];
            WaypointData endWaypoint   = waypoints[i + 1];

            Vector3 currentForward = (endWaypoint.Vertex - startWaypoint.Vertex).normalized;
            Vector3 pastForward    = i > 0
                ? (waypoints[i].Vertex - waypoints[i - 1].Vertex).normalized
                : currentForward;
            Vector3 futureForward = i < numberOfQuads - 1
                ? (waypoints[i + 2].Vertex - waypoints[i + 1].Vertex).normalized
                : currentForward;

            bool justTurned  = Vector3.Dot(currentForward, pastForward) < Mathf.Epsilon;
            bool aboutToTurn = Vector3.Dot(currentForward, futureForward) < Mathf.Epsilon;

            float normalizedStart = currentDistance / totalDistance;

            currentDistance += Vector3.Distance(startWaypoint.Vertex, endWaypoint.Vertex);
            float normalizedEnd = currentDistance / totalDistance;

            AddQuad(
                i,
                normalizedStart,
                normalizedEnd,
                Width,
                justTurned,
                aboutToTurn || i == numberOfQuads - 1,
                startWaypoint,
                endWaypoint,
                ref uvs,
                ref vertices,
                ref colors,
                ref triangles);
        }

        _mesh.vertices  = vertices;
        _mesh.uv        = uvs;
        _mesh.triangles = triangles;
        _mesh.colors    = colors;
        _mesh.RecalculateNormals();
        ;

        View.GetComponent <MeshFilter>().mesh = _mesh;
    }
        public static WaypointGenerator Create(ConfigNode configNode, WaypointGeneratorFactory factory)
        {
            WaypointGenerator wpGenerator = new WaypointGenerator();

            bool valid = true;
            int index = 0;
            foreach (ConfigNode child in ConfigNodeUtil.GetChildNodes(configNode))
            {
                DataNode dataNode = new DataNode("WAYPOINT_" + index, factory.dataNode, factory);
                try
                {
                    ConfigNodeUtil.SetCurrentDataNode(dataNode);
                    dataNode["type"] = child.name;

                    double? altitude = null;
                    WaypointData wpData = new WaypointData(child.name);

                    // Use an expression to default - then it'll work for dynamic contracts
                    if (!child.HasValue("targetBody"))
                    {
                        child.AddValue("targetBody", "@/targetBody.Name()");
                    }
                    valid &= ConfigNodeUtil.ParseValue<string>(child, "targetBody", x => wpData.waypoint.celestialName = x, factory, Validation.CheckCelestialBody);

                    valid &= ConfigNodeUtil.ParseValue<string>(child, "name", x => wpData.waypoint.name = x, factory, (string)null);
                    valid &= ConfigNodeUtil.ParseValue<double?>(child, "altitude", x => altitude = x, factory, (double?)null);
                    valid &= ConfigNodeUtil.ParseValue<string>(child, "parameter", x => wpData.parameter = x, factory, "");
                    valid &= ConfigNodeUtil.ParseValue<bool>(child, "hidden", x => wpData.waypoint.visible = !x, factory, false);
                    if (!wpData.waypoint.visible)
                    {
                        valid &= ConfigNodeUtil.ParseValue<string>(child, "icon", x => wpData.waypoint.id = x, factory, "");
                    }
                    else
                    {
                        valid &= ConfigNodeUtil.ParseValue<string>(child, "icon", x => wpData.waypoint.id = x, factory);
                    }

                    // The FinePrint logic is such that it will only look in Squad/Contracts/Icons for icons.
                    // Cheat this by hacking the path in the game database.
                    if (wpData.waypoint.id.Contains("/"))
                    {
                        GameDatabase.TextureInfo texInfo = GameDatabase.Instance.databaseTexture.Where(t => t.name == wpData.waypoint.id).FirstOrDefault();
                        if (texInfo != null)
                        {
                            texInfo.name = "Squad/Contracts/Icons/" + wpData.waypoint.id;
                        }
                    }

                    // Track the index
                    wpData.waypoint.index = index++;

                    // Get altitude
                    if (altitude == null)
                    {
                        wpData.waypoint.altitude = 0.0;
                        wpData.randomAltitude = true;
                    }
                    else
                    {
                        wpData.waypoint.altitude = altitude.Value;
                    }

                    // Get settings that differ by type
                    if (child.name == "WAYPOINT")
                    {
                        valid &= ConfigNodeUtil.ParseValue<double>(child, "latitude", x => wpData.waypoint.latitude = x, factory);
                        valid &= ConfigNodeUtil.ParseValue<double>(child, "longitude", x => wpData.waypoint.longitude = x, factory);
                    }
                    else if (child.name == "RANDOM_WAYPOINT")
                    {
                        // Get settings for randomization
                        valid &= ConfigNodeUtil.ParseValue<bool>(child, "waterAllowed", x => wpData.waterAllowed = x, factory, true);
                        valid &= ConfigNodeUtil.ParseValue<bool>(child, "forceEquatorial", x => wpData.forceEquatorial = x, factory, false);
                        valid &= ConfigNodeUtil.ParseValue<int>(child, "count", x => wpData.count = x, factory, 1, x => Validation.GE(x, 1));
                    }
                    else if (child.name == "RANDOM_WAYPOINT_NEAR")
                    {
                        // Get settings for randomization
                        valid &= ConfigNodeUtil.ParseValue<bool>(child, "waterAllowed", x => wpData.waterAllowed = x, factory, true);

                        // Get near waypoint details
                        valid &= ConfigNodeUtil.ParseValue<int>(child, "nearIndex", x => wpData.nearIndex = x, factory,
                            x => Validation.GE(x, 0) && Validation.LT(x, wpGenerator.waypoints.Count));
                        valid &= ConfigNodeUtil.ParseValue<int>(child, "count", x => wpData.count = x, factory, 1, x => Validation.GE(x, 1));

                        // Get distances
                        valid &= ConfigNodeUtil.ParseValue<double>(child, "minDistance", x => wpData.minDistance = x, factory, 0.0, x => Validation.GE(x, 0.0));
                        valid &= ConfigNodeUtil.ParseValue<double>(child, "maxDistance", x => wpData.maxDistance = x, factory, x => Validation.GT(x, wpData.minDistance));
                    }
                    else if (child.name == "PQS_CITY")
                    {
                        wpData.randomAltitude = false;
                        string pqsCity = null;
                        valid &= ConfigNodeUtil.ParseValue<string>(child, "pqsCity", x => pqsCity = x, factory);
                        if (pqsCity != null && !string.IsNullOrEmpty(wpData.waypoint.celestialName))
                        {
                            try
                            {
                                CelestialBody body = FlightGlobals.Bodies.Where(b => b.name == wpData.waypoint.celestialName).First();
                                wpData.pqsCity = body.GetComponentsInChildren<PQSCity>(true).Where(pqs => pqs.name == pqsCity).First();
                            }
                            catch (Exception e)
                            {
                                LoggingUtil.LogError(typeof(WaypointGenerator), "Couldn't load PQSCity with name '" + pqsCity + "'");
                                LoggingUtil.LogException(e);
                                valid = false;
                            }
                        }
                        valid &= ConfigNodeUtil.ParseValue<Vector3d>(child, "pqsOffset", x => wpData.pqsOffset = x, factory, new Vector3d());
                    }
                    else
                    {
                        LoggingUtil.LogError(factory, "Unrecognized waypoint node: '" + child.name + "'");
                        valid = false;
                    }

                    // Check for unexpected values
                    valid &= ConfigNodeUtil.ValidateUnexpectedValues(child, factory);

                    // Generate a random name
                    if (!child.HasValue("name"))
                    {
                        wpData.randomName = true;
                    }

                    // Add to the list
                    wpGenerator.waypoints.Add(wpData);
                }
                finally
                {
                    ConfigNodeUtil.SetCurrentDataNode(factory.dataNode);
                }
            }

            return valid ? wpGenerator : null;
        }
        private void GeneratePQSCityCoordinates(WaypointData wpData, CelestialBody body)
        {
            LoggingUtil.LogVerbose(this, "   pqs city: " + wpData.pqsCity);
            LoggingUtil.LogVerbose(this, "   Generating a waypoint based on PQS city " + wpData.pqsCity.name + "...");

            Vector3d position = wpData.pqsCity.transform.position;
            LoggingUtil.LogVerbose(this, "    pqs city position = " + position);

            // Translate by the PQS offset (inverse transform of coordinate system)
            Vector3d v = wpData.pqsOffset;
            Vector3d i = wpData.pqsCity.transform.right;
            Vector3d j = wpData.pqsCity.transform.forward;
            Vector3d k = wpData.pqsCity.transform.up;
            LoggingUtil.LogVerbose(this, "    i, j, k = " + i + ", " + j + "," + k);
            LoggingUtil.LogVerbose(this, "    pqs transform = " + wpData.pqsCity.transform);
            LoggingUtil.LogVerbose(this, "    parent transform = " + wpData.pqsCity.transform.parent);
            Vector3d offsetPos = new Vector3d(
                (j.y * k.z - j.z * k.y) * v.x + (i.z * k.y - i.y * k.z) * v.y + (i.y * j.z - i.z * j.y) * v.z,
                (j.z * k.x - j.x * k.z) * v.x + (i.x * k.z - i.z * k.x) * v.y + (i.z * j.x - i.x * j.z) * v.z,
                (j.x * k.y - j.y * k.x) * v.x + (i.y * k.x - i.x * k.y) * v.y + (i.x * j.y - i.y * j.x) * v.z
            );
            offsetPos *= (i.x * j.y * k.z) + (i.y * j.z * k.x) + (i.z * j.x * k.y) - (i.z * j.y * k.x) - (i.y * j.x * k.z) - (i.x * j.z * k.y);
            wpData.waypoint.latitude = body.GetLatitude(position + offsetPos);
            wpData.waypoint.longitude = body.GetLongitude(position + offsetPos);
            LoggingUtil.LogVerbose(this, "    resulting lat, lon = (" + wpData.waypoint.latitude + ", " + wpData.waypoint.longitude + ")");
        }
Exemple #36
0
 public static void Setup(WaypointData wData, Dictionary <string, string> macros)
 {
     BaseLogicCalculator.wData  = wData;
     BaseLogicCalculator.macros = macros;
 }
        public static WaypointGenerator Create(ConfigNode configNode, WaypointGeneratorFactory factory)
        {
            WaypointGenerator wpGenerator = new WaypointGenerator();

            bool valid = true;
            int index = 0;
            foreach (ConfigNode child in ConfigNodeUtil.GetChildNodes(configNode))
            {
                DataNode dataNode = new DataNode("WAYPOINT_" + index, factory.dataNode, factory);
                try
                {
                    ConfigNodeUtil.SetCurrentDataNode(dataNode);
                    dataNode["type"] = child.name;

                    double? altitude = null;
                    WaypointData wpData = new WaypointData(child.name);

                    // Use an expression to default - then it'll work for dynamic contracts
                    if (!child.HasValue("targetBody"))
                    {
                        child.AddValue("targetBody", "@/targetBody");
                    }
                    valid &= ConfigNodeUtil.ParseValue<CelestialBody>(child, "targetBody", x => wpData.waypoint.celestialName = x != null ? x.name : "", factory);

                    valid &= ConfigNodeUtil.ParseValue<List<string>>(child, "name", x => wpData.names = x, factory, new List<string>());
                    valid &= ConfigNodeUtil.ParseValue<double?>(child, "altitude", x => altitude = x, factory, (double?)null);
                    valid &= ConfigNodeUtil.ParseValue<List<string>>(child, "parameter", x => wpData.parameter = x, factory, new List<string>());
                    valid &= ConfigNodeUtil.ParseValue<bool>(child, "hidden", x => wpData.waypoint.visible = !x, factory, false);
                    if (!wpData.waypoint.visible)
                    {
                        valid &= ConfigNodeUtil.ParseValue<string>(child, "icon", x => wpData.waypoint.id = x, factory, "");
                    }
                    else
                    {
                        valid &= ConfigNodeUtil.ParseValue<string>(child, "icon", x => wpData.waypoint.id = x, factory);
                    }

                    valid &= ConfigNodeUtil.ParseValue<bool>(child, "underwater", x => wpData.underwater = x, factory, false);
                    valid &= ConfigNodeUtil.ParseValue<bool>(child, "clustered", x => wpData.waypoint.isClustered = x, factory, false);

                    // Track the index
                    wpData.waypoint.index = index++;

                    // Get altitude
                    if (altitude == null)
                    {
                        wpData.waypoint.altitude = 0.0;
                        wpData.randomAltitude = true;
                    }
                    else
                    {
                        wpData.waypoint.altitude = altitude.Value;
                    }

                    // Get settings that differ by type
                    if (child.name == "WAYPOINT")
                    {
                        valid &= ConfigNodeUtil.ParseValue<double>(child, "latitude", x => wpData.waypoint.latitude = x, factory);
                        valid &= ConfigNodeUtil.ParseValue<double>(child, "longitude", x => wpData.waypoint.longitude = x, factory);
                    }
                    else if (child.name == "RANDOM_WAYPOINT")
                    {
                        // Get settings for randomization
                        valid &= ConfigNodeUtil.ParseValue<bool>(child, "waterAllowed", x => wpData.waterAllowed = x, factory, true);
                        valid &= ConfigNodeUtil.ParseValue<bool>(child, "forceEquatorial", x => wpData.forceEquatorial = x, factory, false);
                        valid &= ConfigNodeUtil.ParseValue<int>(child, "count", x => wpData.count = x, factory, 1, x => Validation.GE(x, 1));
                    }
                    else if (child.name == "RANDOM_WAYPOINT_NEAR")
                    {
                        // Get settings for randomization
                        valid &= ConfigNodeUtil.ParseValue<bool>(child, "waterAllowed", x => wpData.waterAllowed = x, factory, true);

                        // Get near waypoint details
                        valid &= ConfigNodeUtil.ParseValue<int>(child, "nearIndex", x => wpData.nearIndex = x, factory,
                            x => Validation.GE(x, 0) && Validation.LT(x, wpGenerator.waypoints.Count));
                        valid &= ConfigNodeUtil.ParseValue<bool>(child, "chained", x => wpData.chained = x, factory, false);
                        valid &= ConfigNodeUtil.ParseValue<int>(child, "count", x => wpData.count = x, factory, 1, x => Validation.GE(x, 1));

                        // Get distances
                        valid &= ConfigNodeUtil.ParseValue<double>(child, "minDistance", x => wpData.minDistance = x, factory, 0.0, x => Validation.GE(x, 0.0));
                        valid &= ConfigNodeUtil.ParseValue<double>(child, "maxDistance", x => wpData.maxDistance = x, factory, x => Validation.GT(x, 0.0));
                    }
                    else if (child.name == "PQS_CITY")
                    {
                        wpData.randomAltitude = false;
                        string dummy = null;
                        valid &= ConfigNodeUtil.ParseValue<string>(child, "pqsCity", x => dummy = x, factory, x =>
                        {
                            bool v = true;
                            if (!string.IsNullOrEmpty(wpData.waypoint.celestialName))
                            {
                                try
                                {
                                    CelestialBody body = FlightGlobals.Bodies.Where(b => b.name == wpData.waypoint.celestialName).First();
                                    wpData.pqsCity = body.GetComponentsInChildren<PQSCity>(true).Where(pqs => pqs.name == x).First();
                                }
                                catch (Exception e)
                                {
                                    LoggingUtil.LogError(typeof(WaypointGenerator), "Couldn't load PQSCity with name '" + x + "'");
                                    LoggingUtil.LogException(e);
                                    v = false;
                                }
                            }
                            else
                            {
                                // Force this to get re-run when the targetBody is loaded
                                throw new DataNode.ValueNotInitialized("/targetBody");
                            }
                            return v;
                        });
                        valid &= ConfigNodeUtil.ParseValue<Vector3d>(child, "pqsOffset", x => wpData.pqsOffset = x, factory, new Vector3d());
                    }
                    else
                    {
                        LoggingUtil.LogError(factory, "Unrecognized waypoint node: '" + child.name + "'");
                        valid = false;
                    }

                    // Check for unexpected values
                    valid &= ConfigNodeUtil.ValidateUnexpectedValues(child, factory);

                    // Copy waypoint data
                    WaypointData old = wpData;
                    for (int i = 0; i < old.count; i++)
                    {
                        wpData = new WaypointData(old, null);
                        wpGenerator.waypoints.Add(wpData);

                        if (old.parameter.Any())
                        {
                            wpData.parameter = new List<string>();
                            wpData.parameter.Add(old.parameter.Count() == 1 ? old.parameter.First() : old.parameter.ElementAtOrDefault(i));
                        }

                        // Set the name
                        if (old.names.Any())
                        {
                            wpData.waypoint.name = (old.names.Count() == 1 ? old.names.First() : old.names.ElementAtOrDefault(i));
                        }
                        if (string.IsNullOrEmpty(wpData.waypoint.name) || wpData.waypoint.name.ToLower() == "site")
                        {
                            wpData.waypoint.name = StringUtilities.GenerateSiteName(random.Next(), wpData.waypoint.celestialBody, !wpData.waterAllowed);
                        }

                        // Handle waypoint chaining
                        if (wpData.chained && i != 0)
                        {
                            wpData.nearIndex = wpGenerator.waypoints.Count - 2;
                        }
                    }
                }
                finally
                {
                    ConfigNodeUtil.SetCurrentDataNode(factory.dataNode);
                }
            }

            return valid ? wpGenerator : null;
        }
Exemple #38
0
 public void AddWaypoint(WaypointData waypoint)
 {
     waypoints.Add(waypoint);
     RebuildPath();
 }
        protected override void OnLoad(ConfigNode configNode)
        {
            base.OnLoad(configNode);

            foreach (ConfigNode child in configNode.GetNodes("WAYPOINT"))
            {
                // Read all the waypoint data
                WaypointData wpData = new WaypointData();
                wpData.type = child.GetValue("type");
                wpData.parameter = ConfigNodeUtil.ParseValue<string>(child, "parameter", "");
                wpData.waypoint.celestialName = child.GetValue("celestialName");
                wpData.waypoint.name = child.GetValue("name");
                wpData.waypoint.id = child.GetValue("icon");
                wpData.waypoint.latitude = Convert.ToDouble(child.GetValue("latitude"));
                wpData.waypoint.longitude = Convert.ToDouble(child.GetValue("longitude"));
                wpData.waypoint.altitude = Convert.ToDouble(child.GetValue("altitude"));
                wpData.waypoint.index = Convert.ToInt32(child.GetValue("index"));
                wpData.waypoint.visible = !(ConfigNodeUtil.ParseValue<bool?>(child, "hidden", (bool?)false).Value);

                // Set contract data
                wpData.SetContract(contract);

                // Create additional waypoint details
                if (wpData.waypoint.visible && (string.IsNullOrEmpty(wpData.parameter) || contract.AllParameters.
                    Where(p => p.ID == wpData.parameter && p.State == ParameterState.Complete).Any()))
                {
                    AddWayPoint(wpData.waypoint);
                }

                // Add to the global list
                waypoints.Add(wpData);
            }
        }
        bool StartMove(Creature creature)
        {
            if (path == null || path.Empty())
            {
                return(false);
            }

            if (Stopped())
            {
                return(true);
            }

            bool transportPath = creature.GetTransport() != null;

            if (isArrivalDone)
            {
                if ((currentNode == path.Count - 1) && !repeating) // If that's our last waypoint
                {
                    WaypointData waypoint = path.LookupByIndex((int)currentNode);

                    float x = waypoint.x;
                    float y = waypoint.y;
                    float z = waypoint.z;
                    float o = creature.GetOrientation();

                    if (!transportPath)
                    {
                        creature.SetHomePosition(x, y, z, o);
                    }
                    else
                    {
                        Transport trans = creature.GetTransport();
                        if (trans)
                        {
                            o -= trans.GetOrientation();
                            creature.SetTransportHomePosition(x, y, z, o);
                            trans.CalculatePassengerPosition(ref x, ref y, ref z, ref o);
                            creature.SetHomePosition(x, y, z, o);
                        }
                        else
                        {
                            transportPath = false;
                        }
                        // else if (vehicle) - this should never happen, vehicle offsets are const
                    }

                    creature.GetMotionMaster().Initialize();
                    return(false);
                }

                currentNode = (uint)((currentNode + 1) % path.Count);
            }

            var node = path.LookupByIndex((int)currentNode);

            isArrivalDone = false;

            creature.AddUnitState(UnitState.RoamingMove);

            Position       formationDest = new Position(node.x, node.y, node.z, (node.orientation != 0 && node.delay != 0) ? node.orientation : 0.0f);
            MoveSplineInit init          = new MoveSplineInit(creature);

            //! If creature is on transport, we assume waypoints set in DB are already transport offsets
            if (transportPath)
            {
                init.DisableTransportPathTransformations();
                ITransport trans = creature.GetDirectTransport();
                if (trans != null)
                {
                    float orientation = formationDest.GetOrientation();
                    trans.CalculatePassengerPosition(ref formationDest.posX, ref formationDest.posY, ref formationDest.posZ, ref orientation);
                    formationDest.SetOrientation(orientation);
                }
            }

            //! Do not use formationDest here, MoveTo requires transport offsets due to DisableTransportPathTransformations() call
            //! but formationDest contains global coordinates
            init.MoveTo(node.x, node.y, node.z);

            //! Accepts angles such as 0.00001 and -0.00001, 0 must be ignored, default value in waypoint table
            if (node.orientation != 0 && node.delay != 0)
            {
                init.SetFacing(node.orientation);
            }

            switch (node.moveType)
            {
            case WaypointMoveType.Land:
                init.SetAnimation(AnimType.ToGround);
                break;

            case WaypointMoveType.Takeoff:
                init.SetAnimation(AnimType.ToFly);
                break;

            case WaypointMoveType.Run:
                init.SetWalk(false);
                break;

            case WaypointMoveType.Walk:
                init.SetWalk(true);
                break;
            }

            init.Launch();

            //Call for creature group update
            if (creature.GetFormation() != null && creature.GetFormation().GetLeader() == creature)
            {
                creature.GetFormation().LeaderMoveTo(formationDest, node.id, (uint)node.moveType, (node.orientation != 0 && node.delay != 0) ? true : false);
            }

            return(true);
        }
Exemple #41
0
    public List <WaypointData> GetNear(bool[] types, string position)
    {
        BsonDocument t = new BsonDocument();

        string[] coordenadas = new string[2];
        coordenadas = position.Split(new string[] { "," }, StringSplitOptions.None);
        t           = BsonDocument.Parse("{  geometry:   { $near:  {    $geometry: { type: \"Point\",  coordinates:[" + coordenadas[1] + ", " + coordenadas[0] + "] } }}   }");
        List <WaypointData> lista   = new List <WaypointData>();
        var          collection     = database.GetCollection <BsonDocument>("Todo");
        var          secondDocument = collection.Find(t).ToList();
        WaypointData aux            = null;
        int          contador       = 0;//Contador para devolver max 5 resultados

        foreach (var document in secondDocument.AsEnumerable())
        {
            if (contador < 5)
            {
                aux = JsonToWaypoint(document.ToString(), TypeOfPlace.restaurante, true);
                switch (aux.Type)
                {
                case TypeOfPlace.alojamiento:
                    if (types[0])
                    {
                        lista.Add(aux);
                        contador = contador + 1;
                    }
                    break;

                case TypeOfPlace.barCopas:
                    if (types[1])
                    {
                        lista.Add(aux);
                        contador = contador + 1;
                    }
                    break;

                case TypeOfPlace.cafebar:
                    if (types[2])
                    {
                        lista.Add(aux);
                        contador = contador + 1;
                    }
                    break;

                case TypeOfPlace.centroTuristico:
                    if (types[3])
                    {
                        lista.Add(aux);
                        contador = contador + 1;
                    }
                    break;

                case TypeOfPlace.monumento:
                    if (types[4])
                    {
                        lista.Add(aux);
                        contador = contador + 1;
                    }
                    break;

                case TypeOfPlace.restaurante:
                    if (types[5])
                    {
                        lista.Add(aux);
                        contador = contador + 1;
                    }
                    break;

                default:

                    break;
                }
            }
            else
            {
                return(lista);
            }
        }
        return(lista);
    }
Exemple #42
0
    public static void insertWaypointsTo(int id, List<Vector3> waypoints)
    {
        WaypointData wp;

        foreach (Vector3 waypoint in waypoints) {
            wp = new WaypointData();
            wp.npc = id;
            wp.position = waypoint;
            wp.create();
        }
    }
Exemple #43
0
    override public void OnInspectorGUI()
    {
        // Do not enable the editor ingame
        if (Application.isPlaying)
        {
            return;
        }

        NPC npc = Selection.activeGameObject.GetComponent <NPC>();

        npc.Start();         // we load npcData
        npcPos = npc.transform.position;

        if (m_editMode)
        {
            GUILayout.Label("To add a Waypoint: wheel/middle click in the desired position.\n To change the order, edit Waypoint's name.\n");
            if (GUILayout.Button("Stop Editing"))
            {
                WaypointData wp;
                m_editMode = false;
                checkContainer();

                // destroy old waypoints
                foreach (WaypointData waypoint in Service.db.Select <WaypointData>("FROM " + WaypointData.TABLE_NAME + " WHERE npc==?", npc.Id))
                {
                    waypoint.delete();
                }

                // save new waypoints
                foreach (Transform child in m_container.transform)
                {
                    wp          = new WaypointData();
                    wp.npc      = npc.Id;
                    wp.position = npcPos - child.transform.position;                     // save the relative pos
                    wp.create();
                }
                DestroyImmediate(m_container);
                m_count = 0;


                // copy waypoints to clipboard
                TextEditor te = new TextEditor();
                te.text = coords;
                te.SelectAll();
                te.Copy();
            }
        }
        else
        {
            if (GUILayout.Button("Start Editing"))
            {
                m_editMode = true;
                checkContainer();
                resetList();

                // show existing waypoints
                foreach (WaypointData waypoint in npc.waypoints)
                {
                    createWaypoint(npcPos + waypoint.position);
                }
            }
            if (coords.Length > 0)
            {
                GUILayout.Label("\nCurrent Waypoints:");
                nothing = GUILayout.TextArea(coords);
            }
        }

        if (GUILayout.Button("Reset"))
        {
            m_count = 0;
            nothing = "";
            coords  = "";
            checkContainer();
            DestroyImmediate(m_container);
        }
    }
Exemple #44
0
 public void RemoveWaypoint(WaypointData waypoint)
 {
     waypoints.Remove(waypoint);
     RebuildPath();
 }
Exemple #45
0
        public static WaypointGenerator Create(ConfigNode configNode, WaypointGeneratorFactory factory)
        {
            WaypointGenerator wpGenerator = new WaypointGenerator();

            // Waypoint Manager integration
            EventData <string> onWaypointIconAdded = GameEvents.FindEvent <EventData <string> >("OnWaypointIconAdded");

            bool valid = true;
            int  index = 0;

            foreach (ConfigNode child in ConfigNodeUtil.GetChildNodes(configNode))
            {
                DataNode dataNode = new DataNode("WAYPOINT_" + index, factory.dataNode, factory);
                try
                {
                    ConfigNodeUtil.SetCurrentDataNode(dataNode);
                    dataNode["type"] = child.name;

                    double?      altitude = null;
                    WaypointData wpData   = new WaypointData(child.name);

                    // Use an expression to default - then it'll work for dynamic contracts
                    if (!child.HasValue("targetBody"))
                    {
                        child.AddValue("targetBody", "@/targetBody");
                    }
                    valid &= ConfigNodeUtil.ParseValue <CelestialBody>(child, "targetBody", x => wpData.waypoint.celestialName = x != null ? x.name : "", factory);

                    valid &= ConfigNodeUtil.ParseValue <List <string> >(child, "name", x => wpData.names = x, factory, new List <string>());
                    valid &= ConfigNodeUtil.ParseValue <double?>(child, "altitude", x => altitude = x, factory, (double?)null);
                    valid &= ConfigNodeUtil.ParseValue <List <string> >(child, "parameter", x => wpData.parameter = x, factory, new List <string>());
                    valid &= ConfigNodeUtil.ParseValue <bool>(child, "hidden", x => wpData.waypoint.visible = !x, factory, false);

                    Action <string> assignWaypoint = (x) =>
                    {
                        wpData.waypoint.id = x;
                        if (onWaypointIconAdded != null)
                        {
                            onWaypointIconAdded.Fire(x);
                        }
                    };
                    if (!wpData.waypoint.visible)
                    {
                        valid &= ConfigNodeUtil.ParseValue <string>(child, "icon", assignWaypoint, factory, "");
                    }
                    else
                    {
                        valid &= ConfigNodeUtil.ParseValue <string>(child, "icon", assignWaypoint, factory);
                    }

                    valid &= ConfigNodeUtil.ParseValue <bool>(child, "underwater", x => wpData.underwater = x, factory, false);
                    valid &= ConfigNodeUtil.ParseValue <bool>(child, "clustered", x => wpData.waypoint.isClustered = x, factory, false);

                    // Track the index
                    wpData.waypoint.index = index++;

                    // Get altitude
                    if (altitude == null)
                    {
                        wpData.waypoint.altitude = 0.0;
                        wpData.randomAltitude    = true;
                    }
                    else
                    {
                        wpData.waypoint.altitude = altitude.Value;
                    }

                    // Get settings that differ by type
                    if (child.name == "WAYPOINT")
                    {
                        valid &= ConfigNodeUtil.ParseValue <double>(child, "latitude", x => wpData.waypoint.latitude = x, factory);
                        valid &= ConfigNodeUtil.ParseValue <double>(child, "longitude", x => wpData.waypoint.longitude = x, factory);
                    }
                    else if (child.name == "RANDOM_WAYPOINT")
                    {
                        // Get settings for randomization
                        valid &= ConfigNodeUtil.ParseValue <bool>(child, "waterAllowed", x => wpData.waterAllowed = x, factory, true);
                        valid &= ConfigNodeUtil.ParseValue <bool>(child, "forceEquatorial", x => wpData.forceEquatorial = x, factory, false);
                        valid &= ConfigNodeUtil.ParseValue <int>(child, "count", x => wpData.count = x, factory, 1, x => Validation.GE(x, 1));
                    }
                    else if (child.name == "RANDOM_WAYPOINT_NEAR")
                    {
                        // Get settings for randomization
                        valid &= ConfigNodeUtil.ParseValue <bool>(child, "waterAllowed", x => wpData.waterAllowed = x, factory, true);

                        // Get near waypoint details
                        valid &= ConfigNodeUtil.ParseValue <int>(child, "nearIndex", x => wpData.nearIndex = x, factory,
                                                                 x => Validation.GE(x, 0) && Validation.LT(x, wpGenerator.waypoints.Count));
                        valid &= ConfigNodeUtil.ParseValue <bool>(child, "chained", x => wpData.chained = x, factory, false);
                        valid &= ConfigNodeUtil.ParseValue <int>(child, "count", x => wpData.count = x, factory, 1, x => Validation.GE(x, 1));

                        // Get distances
                        valid &= ConfigNodeUtil.ParseValue <double>(child, "minDistance", x => wpData.minDistance = x, factory, 0.0, x => Validation.GE(x, 0.0));
                        valid &= ConfigNodeUtil.ParseValue <double>(child, "maxDistance", x => wpData.maxDistance = x, factory, x => Validation.GT(x, 0.0));
                    }
                    else if (child.name == "PQS_CITY")
                    {
                        wpData.randomAltitude = false;
                        string dummy = null;
                        valid &= ConfigNodeUtil.ParseValue <string>(child, "pqsCity", x => dummy = x, factory, x =>
                        {
                            bool v = true;
                            if (!string.IsNullOrEmpty(wpData.waypoint.celestialName))
                            {
                                try
                                {
                                    CelestialBody body = FlightGlobals.Bodies.Where(b => b.name == wpData.waypoint.celestialName).First();
                                    wpData.pqsCity     = body.GetComponentsInChildren <PQSCity>(true).Where(pqs => pqs.name == x).First();
                                }
                                catch (Exception e)
                                {
                                    LoggingUtil.LogError(typeof(WaypointGenerator), "Couldn't load PQSCity with name '{0}'", x);
                                    LoggingUtil.LogException(e);
                                    v = false;
                                }
                            }
                            else
                            {
                                // Force this to get re-run when the targetBody is loaded
                                throw new DataNode.ValueNotInitialized("/targetBody");
                            }
                            return(v);
                        });
                        valid &= ConfigNodeUtil.ParseValue <Vector3d>(child, "pqsOffset", x => wpData.pqsOffset = x, factory, new Vector3d());
                    }
                    else if (child.name == "LAUNCH_SITE")
                    {
                        wpData.randomAltitude = false;
                        string dummy = null;
                        valid &= ConfigNodeUtil.ParseValue <string>(child, "launchSite", x => dummy = x, factory, x =>
                        {
                            bool v = true;
                            if (!string.IsNullOrEmpty(wpData.waypoint.celestialName))
                            {
                                try
                                {
                                    wpData.launchSite = ConfigNodeUtil.ParseLaunchSiteValue(x);
                                }
                                catch (Exception e)
                                {
                                    LoggingUtil.LogError(typeof(WaypointGenerator), "Couldn't load Launch Site with name '{0}'", x);
                                    LoggingUtil.LogException(e);
                                    v = false;
                                }
                            }
                            else
                            {
                                // Force this to get re-run when the targetBody is loaded
                                throw new DataNode.ValueNotInitialized("/targetBody");
                            }
                            return(v);
                        });
                        valid &= ConfigNodeUtil.ParseValue <Vector3d>(child, "pqsOffset", x => wpData.pqsOffset = x, factory, new Vector3d());
                    }
                    else
                    {
                        LoggingUtil.LogError(factory, "Unrecognized waypoint node: '{0}'", child.name);
                        valid = false;
                    }

                    // Check for unexpected values
                    valid &= ConfigNodeUtil.ValidateUnexpectedValues(child, factory);

                    // Copy waypoint data
                    WaypointData old = wpData;
                    wpData = new WaypointData(old, null);
                    wpGenerator.waypoints.Add(wpData);
                }
                finally
                {
                    ConfigNodeUtil.SetCurrentDataNode(factory.dataNode);
                }
            }

            return(valid ? wpGenerator : null);
        }
Exemple #46
0
	private static WaypointData AddWaypoint(JSONObject waypointJSON)
	{
		WaypointData waypoint = new WaypointData();
		waypoint.Type = waypointJSON["type"].str.ToLower();
		waypoint.Index = int.Parse(waypointJSON["name"].str);
		waypoint.duration = float.Parse(waypointJSON["properties"]["time"].str);

		if (waypointJSON["properties"]["waypoint"])
			waypoint.linkWaypointIndex = int.Parse(waypointJSON["properties"]["waypoint"].str);

		Vector4 values;

		switch (waypoint.Type)
		{
			case "line":
			case "line-fixed":
				values = new Vector4(waypointJSON["x"].f, waypointJSON["y"].f, waypointJSON["polyline"][1]["x"].f, waypointJSON["polyline"][1]["y"].f);
				
				values.x = values.x - Constants.SCREEN_WIDTH_BY_PIXEL / 2;
				values.y = Constants.SCREEN_HEIGHT_BY_PIXEL - values.y - Constants.SCREEN_HEIGHT_BY_PIXEL / 2;
				values.z = values.x + values.z ;
				values.w = values.y - values.w;
				
				values *= Constants.FACTOR_PIXEL_TO_METER;
				
				waypoint.position = new Vector2(values.x, values.y);
				waypoint.target = new Vector2(values.z, values.w);
				break;

			case "circle":
				values = new Vector4(waypointJSON["x"].f, waypointJSON["y"].f, waypointJSON["width"].f, waypointJSON["height"].f);
				
				values.x = values.x - Constants.SCREEN_WIDTH_BY_PIXEL / 2;
				values.y = Constants.SCREEN_HEIGHT_BY_PIXEL - values.y - Constants.SCREEN_HEIGHT_BY_PIXEL / 2;
				
				values.x += values.z / 2;
				values.y += - values.w / 2;
				
				values *= Constants.FACTOR_PIXEL_TO_METER;
				
				waypoint.position = new Vector2(values.x, values.y);
				waypoint.target = new Vector2(values.z, values.w);
				break;
		}

		return waypoint;
	}