Beispiel #1
0
        public void Serialize(Stream stream, IUnique source, AlertLog log = null)
        {
            log?.RaiseAlert("BEG", "Beginning serialisation...");
            _Format  = new Dictionary <string, TypeFieldsFormat>();
            _Aliases = new Dictionary <Type, string>();
            _Uniques = new UniquesCollection();
            _Writer  = new StreamWriter(stream);

            // Write base item:
            _Writer.WriteLine(SerializeItem(source));

            // Write uniques:
            int i = 0;

            while (i < _Uniques.Count)
            {
                log?.RaiseAlert("PROG", "Writing...", (double)i / (double)_Uniques.Count, AlertLevel.Information);
                IUnique unique = _Uniques[i];
                _Writer.WriteLine(SerializeItem(unique));
                i++;
            }

            //_Writer.WriteLine();
            //_Writer.WriteLine(FORMAT);

            //_Writer.Write(GenerateFormatDescription());

            _Writer.Flush();

            log?.RaiseAlert("BEG", "Serialisation complete.");
        }
Beispiel #2
0
    // Alert player while no planes are active
    IEnumerator FindARPlanesAlert()
    {
        // Remove enemy if things become disoriented
        if (enemySpawnObject != null)
        {
            Destroy(enemySpawnObject);
        }

        string alertMessage = "";

        if (arPlanesTracking.Count > 0)
        {
            alertMessage = "";
            AlertLog.write(alertMessage);
            yield return(new WaitForSeconds(0));

            StartCoroutine(SpawnEnemiesAR());
        }
        else
        {
            alertMessage = "LOOK AROUND SLOWLY FOR TANK PORTALS";
            AlertLog.write(alertMessage);
            yield return(new WaitForSeconds(0.5f));

            alertMessage = "";
            AlertLog.write(alertMessage);
            yield return(new WaitForSeconds(0.5f));

            StartCoroutine(FindARPlanesAlert());
        }
    }
Beispiel #3
0
        public static void Save(AlertLog alertlog)
        {
            var db = new GPSTrackerEntities1();

            db.AlertLogs.AddObject(alertlog);
            db.SaveChanges();
        }
Beispiel #4
0
        /// <summary>
        /// Read map geometry data, automatically retrieving the
        /// </summary>
        /// <param name="address">The address to search for</param>
        /// <param name="range">The distance around the specified location to download</param>
        /// <param name="layerNames"></param>
        /// <returns></returns>
        public GeometryLayerTable ReadMap(string address, double range = 0.005, IList <string> layerNames = null,
                                          AlertLog log = null)
        {
            /*Vector ll = LatitudeAndLongitudeFromAddress(address);
             * if (!ll.IsValid()) return null;*/
            var latLong = LatitudeAndLongitudeFromAddress(address);

            return(ReadMap(latLong, range, layerNames, log));
        }
Beispiel #5
0
        /// <summary>
        /// Get the longitude and latitude for an address string
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        public AnglePair LatitudeAndLongitudeFromAddress(string address, AlertLog log = null)
        {
            // Nominatim requires a contact email address
            string queryString = NominatimAPI + "q=" + address + "&format=xml&[email protected]";

            var      web     = new WebClient();
            string   xml     = web.DownloadString(queryString);
            XElement xmlTree = XElement.Parse(xml);
            var      place   = xmlTree.Element("place");
            string   lat     = place.Attribute("lat").Value;
            string   lon     = place.Attribute("lon").Value;

            double latitude;

            double.TryParse(lat, NumberStyles.Any, CultureInfo.InvariantCulture, out latitude);

            double longitude;

            double.TryParse(lon, NumberStyles.Any, CultureInfo.InvariantCulture, out longitude);

            return(AnglePair.FromDegrees(latitude, longitude));


            /*var geocoder = new ForwardGeocoder();
             * var task = geocoder.Geocode(new ForwardGeocodeRequest
             * {
             *  queryString = address,
             *  BreakdownAddressElements = true,
             *  ShowExtraTags = true,
             *  ShowAlternativeNames = true,
             * });
             *
             * if (task.Result.Length > 0)
             * {
             *  var response = task.Result[0];
             *  return AnglePair.FromDegrees(response.Latitude, response.Longitude);
             * }
             * else
             *  throw new Exception("Address '" + address + "' could not be found.");
             */

            /*var gls = new GoogleLocationService();
             * try
             * {
             *  var mapPt = gls.GetLatLongFromAddress(address);
             *  if (mapPt == null) return Vector.Unset;
             *  return new Vector(mapPt.Longitude, mapPt.Latitude);
             * }
             * catch
             * {
             *  return Vector.Unset;
             * }*/
        }
Beispiel #6
0
        private async Task SendAlertEmail(Guid jGuid, int alertConfigId, string serviceErrorList, ExtendSettings extendSettings)
        {
            using var client = new HttpClient();
            try
            {
                var emailConfig = await new EmailConfigImpl(ConnectionString).ListByAlertConfigId(alertConfigId);
                foreach (var item in emailConfig.Where(x => x.IsEnable))
                {
                    var emailSetting = new MailRequest()
                    {
                        SenderName = item.SenderName,
                        ToMail     = item.ToMail,
                        CCMail     = item.CCMail,
                        Subject    = item.Subject,
                        Message    = item.Message.Replace("{check_id}", jGuid.ToString())
                                     .Replace("{service_list}", serviceErrorList),
                        IsResend   = item.IsResend,
                        ServiceID  = item.ServiceId,
                        smsEMailID = item.SmsEmailId,
                        langID     = item.LangId,
                        DataSign   = item.DataSign
                    };

                    using var stringContent = new StringContent(JsonConvert.SerializeObject(emailSetting), System.Text.Encoding.UTF8, "application/json");
                    //var response = await client.PostAsync(new Uri(ExtendSettings.SendMailUrl), stringContent);
                    var response = await client.PostAsync(new Uri(extendSettings.SendMailUrl), stringContent);

                    var responseMessage = await response.Content.ReadAsStringAsync();

                    var alertLog = new AlertLog()
                    {
                        AlertType       = "EMAIL",
                        AlertUrl        = extendSettings.SendMailUrl,
                        RequestMessage  = JsonConvert.SerializeObject(emailSetting),
                        ResponseMessage = responseMessage
                    };
                    await new AlertLogImpl(ConnectionString).Add(alertLog);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Beispiel #7
0
        /// <summary>
        /// Parse a line of text as a data format
        /// </summary>
        /// <param name="line"></param>
        /// <returns></returns>
        public TypeFieldsFormat ReadFormat(string line, AlertLog log = null)
        {
            TypeFieldsFormat result;
            int    i        = FORMAT.Length;
            string alias    = line.NextChunk(ref i, KEY_SEPARATOR);
            string typeName = line.NextChunk(ref i, OPEN_DATABLOCK);
            Type   type     = GetType(typeName);
            var    fields   = new List <FieldInfo>();

            if (type != null)
            {
                while (i < line.Length)
                {
                    string fieldName = line.NextChunk(ref i, SEPARATOR, CLOSE_DATABLOCK);
                    if (!string.IsNullOrEmpty(fieldName))
                    {
                        FieldInfo field = type.GetBaseField(fieldName);
                        //TODO: check for mapped fields if null
                        if (field == null)
                        {
                            log?.RaiseAlert("FNF " + fieldName + " on " + typeName, "Field '" + fieldName + "' cannot be found on type '" + type.Name + "'.", AlertLevel.Warning);
                        }
                        fields.Add(field);
                    }
                }

                result = new TypeFieldsFormat(alias, type, fields);
                if (_Format != null)
                {
                    _Format.Add(alias, result);
                }
                if (_Aliases != null)
                {
                    _Aliases.Add(type, alias);
                }
                return(result);
            }
            else
            {
                return(null);
            }
        }
Beispiel #8
0
        /// <summary>
        /// Read map geometry data, automatically retrieving map data from the OpenStreetMap servers
        /// </summary>
        /// <param name="latitude">The latitude, in degrees</param>
        /// <param name="longitude">The longitude, in degrees</param>
        /// <param name="range">The range around the specified latitude and longitude to be collected, in degrees</param>
        /// <param name="layerNames"></param>
        /// <returns></returns>
        public GeometryLayerTable ReadMap(double latitude, double longitude, double range = 0.005, IList <string> layerNames = null,
                                          AlertLog log = null)
        {
            //FilePath osmFile = FilePath.Temp + "TempMap.osm";
            //DownloadMap(latitude, longitude, osmFile, range);
            //return ReadMap(osmFile, latitude, longitude);
            var data = DownloadMapData(longitude - range, latitude - range, longitude + range, latitude + range);

            try
            {
                using (var stream = new MemoryStream(data))
                {
                    return(ReadMap(stream, AnglePair.FromDegrees(latitude, longitude), layerNames));
                }
            }
            catch (Exception ex)
            {
                log?.RaiseAlert("Error reading map " + ex.Message, AlertLevel.Information);
                return(null);
            }
        }
        private void WriteModel(RobotController robot, AlertLog log)
        {
            log?.RaiseAlert("Writing Salamander model to Robot...");
            RobotIDMappingTable idMap = new RobotIDMappingTable();
            bool result = robot.WriteModelToRobot(FilePath, Document.Model, ref idMap, null, log);

            if (result)
            {
                robot.Close();
                log?.RaiseAlert("Robot file written successfully.");
            }
            else
            {
                log?.RaiseAlert("Writing Robot file failed!", Nucleus.Alerts.AlertLevel.Error);
            }
            robot.Release(result);
            idMap.LinkToFile(FilePath);
            Document.IDMappings[FilePath] = idMap;
            idMap.SaveAsCSV(FilePath.AddNameSuffix("_Mapping", ".csv"));
            Result = result;
        }
Beispiel #10
0
        private async Task SendAlertSms(int alertConfigId, ExtendSettings extendSettings)
        {
            using var client = new HttpClient();
            try
            {
                var smsConfig = await new SmsConfigImpl(ConnectionString).ListByAlertConfigId(alertConfigId);
                foreach (var item in smsConfig.Where(x => x.IsEnable))
                {
                    var smsSetting = new SmsRequest()
                    {
                        AccountName = item.AccountName,
                        Mobile      = item.Mobile,
                        Message     = item.Message,
                        IsResend    = item.IsResend,
                        ServiceID   = item.ServiceId,
                        smsEMailID  = item.SmsEmailId,
                        langID      = item.LangId,
                        DataSign    = item.DataSign
                    };

                    using var stringContent = new StringContent(JsonConvert.SerializeObject(smsSetting), System.Text.Encoding.UTF8, "application/json");
                    var response = await client.PostAsync(new Uri(extendSettings.SendSmsUrl), stringContent);

                    var responseMessage = await response.Content.ReadAsStringAsync();

                    var alertLog = new AlertLog()
                    {
                        AlertType       = "SMS",
                        AlertUrl        = extendSettings.SendSmsUrl,
                        RequestMessage  = JsonConvert.SerializeObject(smsSetting),
                        ResponseMessage = responseMessage
                    };
                    await new AlertLogImpl(ConnectionString).Add(alertLog);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Beispiel #11
0
        public async Task <int> Add(AlertLog alertLog)
        {
            try
            {
                var spName = "dbo.usp_AlertLog_Add";

                var parameterValues = new object[4]
                {
                    alertLog.AlertType,
                    alertLog.AlertUrl,
                    alertLog.RequestMessage,
                    alertLog.ResponseMessage
                };

                var thisTask = Task.Run(() => SqlHelper.ExecuteNonQueryAsync(_connString, spName, parameterValues));
                var result   = await thisTask;
                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #12
0
        public void SendAlertAndSaveInAlertLogTbl(int fenceId, long messageAlertId, int alertId, string action)
        {
            var alertUsers = UserFenceMapManager.GetByFenceId(fenceId);

            foreach (var user in alertUsers)
            {
                var userDetail = Aspnet_UserManager.GetByUserName(user.UserName);
                var emailId    = userDetail.EmailId;
                SendMail(emailId, alertName, message);

                //now inserting value in alertlog table
                var alertLog = new AlertLog
                {
                    MessageAlertId = messageAlertId,
                    UserId         = userDetail.UserId,
                    AlertId        = alertId,
                    FenceId        = fenceId,
                    Action         = action,
                    Success        = true
                };
                AlertLogManager.Save(alertLog);
            }
        }
Beispiel #13
0
        /// <summary>
        /// Run an analysis on the specified model
        /// </summary>
        /// <param name="model"></param>
        /// <param name="alertLog"></param>
        /// <returns></returns>
        public ModelResults AnalyseModel(Model.Model model, AnalysisCaseCollection cases, AlertLog alertLog = null)
        {
            alertLog?.RaiseAlert("BLD", "Building analysis model...");

            var results = new ModelResults();

            // Create model:
            var feModel = new BFE.Model();

            // Create nodes:
            var nodesMap = new Dictionary <Guid, BFE.Node>();

            foreach (var node in model.Nodes)
            {
                var bfeNode = ToBFE.Convert(node);
                feModel.Nodes.Add(bfeNode);
                nodesMap.Add(node.GUID, bfeNode);
            }

            // Create materials:

            /*var materialsMap = new Dictionary<Guid, BFE.Materials.BaseMaterial>();
             * foreach (var material in model.Materials)
             * {
             *  var bfeMat = ToBFE.Convert(material);
             *  materialsMap.Add(material.GUID, bfeMat);
             * }*/

            // Create sections:

            /*foreach (var family in model.Families)
             * {
             *  if (family is SectionFamily)
             *  {
             *      SectionFamily section = (SectionFamily)family;
             *      //TODO?
             *  }
             * }*/

            // Create elements:
            var elementMap = new Dictionary <Guid, BFE.FrameElement2Node>();

            foreach (var element in model.Elements)
            {
                if (element is LinearElement)
                {
                    var linEl = (LinearElement)element;
                    if (linEl.StartNode != null && linEl.EndNode != null && linEl.Family != null)
                    {
                        var el = new BFE.FrameElement2Node(
                            nodesMap[linEl.StartNode.GUID], nodesMap[linEl.EndNode.GUID]);
                        //TODO: Releases
                        //TODO: Orientation
                        //TODO: Offsets
                        if (linEl.Family.Profile?.Perimeter != null)
                        {
                            var profile = ToBFE.Convert(linEl.Family.Profile.Perimeter);
                            el.Geometry = profile;
                            el.UseOverridedProperties = false;
                            //TODO: Hollow sections
                        }
                        el.E = linEl.Family.GetPrimaryMaterial()?.GetE(Geometry.Direction.X) ?? 210e9;
                        feModel.Elements.Add(el);
                        elementMap.Add(element.GUID, el);
                    }
                    else
                    {
                        alertLog.RaiseAlert("INCOMPLETE DATA", linEl, "Incomplete data.  Will be excluded from analysis.");
                    }
                }
            }

            //Loading time!
            // TODO: Limit to specific load cases?
            foreach (var load in model.Loads)
            {
                if (load is LinearElementLoad)
                {
                    var lEL = (LinearElementLoad)load;
                    if (lEL.IsMoment)
                    {
                        alertLog.RaiseAlert("MOMENTS UNSUPPORTED", load, "Moment line loads are not supported.", AlertLevel.Error);
                    }
                    else
                    {
                        // TODO: Set load case
                        var bLoad = new BFE.UniformLoad1D(lEL.Value, ToBFE.Convert(lEL.Direction), ToBFE.Convert(lEL.Axes));

                        // TODO: Generalise
                        var elements = lEL.AppliedTo.Items;
                        foreach (var el in elements)
                        {
                            elementMap[el.GUID].Loads.Add(bLoad);
                        }
                    }
                }
                else if (load is NodeLoad)
                {
                    var nL = (NodeLoad)load;
                }
                else
                {
                    alertLog.RaiseAlert("LOAD TYPE UNSUPPORTED", load, "Load type is not supported.", AlertLevel.Error);
                }
            }

            alertLog?.RaiseAlert("BLD", "Analysis model built.");

            alertLog.RaiseAlert("SLV", "Solving...");

            feModel.Solve();

            alertLog.RaiseAlert("SLV", "Solved.");

            foreach (var kvp in nodesMap)
            {
                var disp = kvp.Value.GetNodalDisplacement();
                var nR   = new NodeResults();
                var cNR  = new CaseNodeResults();

                //nR.Add(cNR);
            }

            /*foreach (var element in model.Elements)
             * {
             *  bNS = nodesMap[element]
             * }*/
            return(results);
        }
Beispiel #14
0
    // Update is called once per frame
    void Update()
    {
        // Check if there is a plane above the enemy
        Vector3 enemySkyPosition = new Vector3(transform.position.x, transform.position.y + 100.0f, transform.position.z);

        RaycastHit[] allSkyHits                 = Physics.RaycastAll(enemySkyPosition, Vector3.down);
        Vector3      highestARPlanePos          = new Vector3(transform.position.x, -999.9f, transform.position.z);
        Vector3      highestARPlaneCenter       = new Vector3(transform.position.x, -999.9f, transform.position.z);
        Vector3      highestARPlaneCenterGround = new Vector3(transform.position.x, transform.position.y, transform.position.z);

        foreach (var hit in allSkyHits)
        {
            print(hit.collider.name);
            if (hit.collider.name.Length > 7 && hit.collider.name.Substring(0, 7) == "ARPlane" && highestARPlanePos.y < hit.point.y)
            {
                highestARPlanePos    = new Vector3(hit.point.x, hit.point.y, hit.point.z);
                highestARPlaneCenter = new Vector3(
                    hit.collider.transform.position.x,
                    hit.collider.transform.position.y,
                    hit.collider.transform.position.z
                    );
                highestARPlaneCenterGround = new Vector3(highestARPlaneCenter.x, transform.position.y, highestARPlaneCenter.z);
            }
        }

        // There is a plane above the enemy
        if (allSkyHits.Count() > 0 && transform.position.y < highestARPlanePos.y)
        {
            if ((highestARPlanePos.y - transform.position.y) > .3 || facingClimbHeight == true)
            {
                float angle = 1;
                if (Vector3.Angle(transform.forward, highestARPlaneCenterGround - transform.position) > angle &&
                    facingClimbCenter == false)
                {
                    Quaternion groundRotation = Quaternion.LookRotation(highestARPlaneCenterGround - transform.position);
                    transform.rotation = Quaternion.RotateTowards(transform.rotation, groundRotation, turnSpeed * 1.2f * Time.deltaTime);
                }
                else
                {
                    // Save original rotation
                    if (facingClimbCenter == false)
                    {
                        originalRotation  = transform.rotation;
                        facingClimbCenter = true;
                    }

                    if (Vector3.Angle(transform.forward, highestARPlaneCenter - transform.position) > angle &&
                        facingClimbHeight == false)
                    {
                        Vector3    climbTo       = new Vector3(highestARPlaneCenter.x, highestARPlaneCenter.y + 0.05f, highestARPlaneCenter.z);
                        Quaternion climbRotation = Quaternion.LookRotation(climbTo - transform.position);
                        transform.rotation = Quaternion.RotateTowards(transform.rotation, climbRotation, turnSpeed * 1.2f * Time.deltaTime);
                    }
                    // Looking up to plane, start climbing
                    else
                    {
                        facingClimbHeight   = true;
                        transform.position += transform.forward * moveSpeed * 1.2f * Time.deltaTime;
                    }
                }
            }
            else
            {
                transform.position = new Vector3(highestARPlanePos.x, highestARPlanePos.y + 0.05f, highestARPlanePos.z);
            }
        }
        // Climbed above plane or was already above
        // Check to make sure enemy is flat again
        else
        {
            // Level enemy if not leveled from climbing
            float angle = 0.1f;
            if (facingClimbHeight == true && transform.rotation != originalRotation)
            {
                transform.rotation = Quaternion.RotateTowards(transform.rotation, originalRotation, turnSpeed * 1.2f * Time.deltaTime);
            }
            else
            {
                facingClimbHeight = false;
                facingClimbCenter = false;

                target = GameObject.FindWithTag("MainCamera");
                targetVectorARGround = new Vector3(target.transform.position.x, transform.position.y, target.transform.position.z);

                // This makes the enemy tank "look" at the player in regard to the x, z axis
                float turnAngle = 15;
                float stopAngle = 1;
                if (Vector3.Angle(transform.forward, targetVectorARGround - transform.position) > turnAngle)
                {
                    turning = true;
                }

                if (Vector3.Angle(transform.forward, targetVectorARGround - transform.position) < stopAngle)
                {
                    turning = false;
                }

                // Either turn towards player or move towards player
                if (turning == true)
                {
                    Quaternion targetRotation = Quaternion.LookRotation(targetVectorARGround - transform.position);
                    transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, turnSpeed * Time.deltaTime);
                }
                else if (Vector3.Distance(targetVectorARGround, transform.position) > 0.5f && (Physics.Raycast(transform.position, Vector3.down, 0.1f)))
                {
                    transform.position += transform.forward * moveSpeed * Time.deltaTime;
                }
            }
        }

        string enemyAlert = "";

        // Determine where the target is in reference to the player
        Vector3 enemyPos       = Quaternion.Inverse(target.transform.rotation) * (transform.position - target.transform.position);
        bool    easilyViewable = false;

        Vector3 screenPoint = camera.WorldToViewportPoint(transform.position);

        if (screenPoint.z > 0 && screenPoint.x > 0.1 && screenPoint.x < 0.9 && screenPoint.y > 0.1 && screenPoint.y < 0.9)
        {
            easilyViewable = true;
        }
        else
        {
            easilyViewable = false;
        }

        if (Vector3.Distance(targetVectorARGround, transform.position) < 2f)
        {
            enemyAlert += "ENEMY IN RANGE";
        }

        print(enemyPos.ToString());

        if (!easilyViewable)
        {
            if (enemyPos.z < 0)
            {
                enemyAlert += "\n\nENEMY TO REAR";
            }
            else if (enemyPos.x > 0.5f)
            {
                enemyAlert += "\n\nENEMY TO RIGHT";
            }
            else if (enemyPos.x < -0.5f)
            {
                enemyAlert += "\n\nENEMY TO LEFT";
            }
            else if (enemyPos.y < 0)
            {
                enemyAlert += "\n\nENEMY BELOW";
            }
        }

        AlertLog.write(enemyAlert);
    }
 /// <summary>
 /// Initialises a new RobotConversionContext instance using the specified mapping table and options
 /// </summary>
 /// <param name="idMap"></param>
 /// <param name="options"></param>
 public RobotConversionContext(RobotIDMappingTable idMap, RobotConversionOptions options, AlertLog log) 
     : this(idMap)
 {
     Options = options;
     Log = log;
 }
Beispiel #16
0
        public AlertsLogDialog(AlertLog log)
        {
            InitializeComponent();

            this.DataContext = log;
        }
Beispiel #17
0
        protected void PopulateFields(ref object target, TypeFieldsFormat format, ref int i, string line, AlertLog log)
        {
            string chunk;
            int    j          = 0;
            IList  items      = null; //Items for array reinstantiation
            object currentKey = null; //Current key object for Dictionaries

            while (i < line.Length)   // && j < format.Fields.Count())
            {
                char c;
                chunk = line.NextChunk(out c, ref i, SEPARATOR, OPEN_DATABLOCK, CLOSE_DATABLOCK, KEY_SEPARATOR);
                if (c == SEPARATOR || c == CLOSE_DATABLOCK)
                {
                    // Chunk is simple value
                    if (!string.IsNullOrEmpty(chunk))
                    {
                        if (j < format.Fields.Count())
                        {
                            FieldInfo fI    = format.Fields[j];
                            object    value = String2Object(chunk, fI.FieldType);
                            fI.SetValue(target, value);
                        }
                        else if (target is IDictionary && currentKey != null) //Dictionary value
                        {
                            //Add to dictionary
                            IDictionary dic       = (IDictionary)target;
                            Type[]      arguments = dic.GetType().GetGenericArguments();
                            if (arguments.Length > 1)
                            {
                                object value = String2Object(chunk, arguments[1]);
                                //TODO: What if value is complex object?
                                dic[currentKey] = value;
                            }
                            currentKey = null;
                        }
                        else if (format.Type.IsList())
                        {
                            Type type = format.Type.GetElementType();
                            if (format.Type.ContainsGenericParameters)
                            {
                                type = format.Type.GenericTypeArguments[0];
                            }
                            object value = String2Object(chunk, type);
                            if (format.Type.IsArray)
                            {
                                if (items == null)
                                {
                                    Type listType = typeof(List <>).MakeGenericType(type);
                                    items = Activator.CreateInstance(listType) as IList;
                                    //TODO!!! Create list of required type!
                                }
                                items.Add(value);
                            }
                            else
                            {
                                IList list = (IList)target;
                                list.Add(value);
                            }
                            //TODO
                        }
                    }
                    j++;

                    if (c == CLOSE_DATABLOCK)
                    {
                        // The current object definition is finished - can step out

                        if (items != null)
                        {
                            Type  type        = format.Type.GetElementType();
                            Array targetArray = Array.CreateInstance(type, items.Count);
                            for (int k = 0; k < items.Count; k++)
                            {
                                targetArray.SetValue(items[k], k);
                            }
                            target = targetArray;
                        }

                        return;
                    }
                }
                else if (c == OPEN_DATABLOCK)
                {
                    // Chunk is the type alias of an embedded object
                    if (_Format.ContainsKey(chunk))
                    {
                        TypeFieldsFormat subFormat = _Format[chunk];
                        object           value     = null;
                        if (!subFormat.Type.IsArray)
                        {
                            value = subFormat.Type.Instantiate();
                        }
                        else
                        {
                            value = Activator.CreateInstance(subFormat.Type, new object[] { 0 });
                        }
                        PopulateFields(ref value, subFormat, ref i, line, log);
                        if (j < format.Fields.Count)
                        {
                            // Is sub-object belonging to a field
                            FieldInfo fI = format.Fields[j];
                            fI.SetValue(target, value);
                        }
                        else if (target is Array)
                        {
                            if (items == null)
                            {
                                items = new List <object>();
                                //TODO: Create list of specified type
                            }
                            items.Add(value);
                        }
                        else if (target is IDictionary && currentKey != null) //Dictionary value
                        {
                            IDictionary dic = (IDictionary)target;
                            dic[currentKey] = value;
                            currentKey      = null;
                        }
                        else if (target is IDictionary && line[i] == KEY_SEPARATOR) //Dictionary key
                        {
                            currentKey = value;
                            i++; //Skip the key separator character
                        }
                        else if (target is IList)
                        {
                            // Is an entry in the target collection
                            IList list = (IList)target;
                            list.Add(value);
                        }
                        //j++;
                        //i++; //Skip the next separator?
                    }
                    else
                    {
                        log?.RaiseAlert("FNF" + chunk, "Formatting data for type alias '" + chunk + "' not found.", AlertLevel.Warning);
                    }
                }
                else if (c == KEY_SEPARATOR && target is IDictionary)
                {
                    // Is a key for a dictionary:
                    Type[] genTypes = target.GetType().GetGenericArguments();
                    currentKey = String2Object(chunk, genTypes[0]);
                }
                else
                {
                    // Line is not closed correctly - must be a multiline string
                    // TODO
                }
            }
        }
Beispiel #18
0
        /// <summary>
        /// Download a map for the given coordinate range and save it at the specified location
        /// </summary>
        /// <param name="left">The lower-bound longitude</param>
        /// <param name="bottom">The lower-bound latitude</param>
        /// <param name="right">The upper-bound longitude</param>
        /// <param name="top">The upper-bound latitude</param>
        /// <param name="saveTo">The filepath to save the map file to</param>
        public bool DownloadMap(double left, double bottom, double right, double top, FilePath saveTo, AlertLog log = null)
        {
            //Compile the OpenStreetMap API URL:
            string osmAPIGet = BuildGetURL(left, bottom, right, top);

            using (var client = new WebClient())
            {
                try
                {
                    client.DownloadFile(osmAPIGet, saveTo);
                }
                catch (Exception ex)
                {
                    log?.RaiseAlert("Error downloading map " + ex.Message, AlertLevel.Warning);
                    return(false);
                }
            }
            return(true);
        }
Beispiel #19
0
        public IUnique Deserialize(Stream stream, AlertLog log = null)
        {
            IUnique result = null;

            _Format  = new Dictionary <string, TypeFieldsFormat>();
            _Aliases = new Dictionary <Type, string>();
            _Uniques = new UniquesCollection();
            _Reader  = new StreamReader(stream);

            // First, read through once to end:
            log?.RaiseAlert("FORM", "Reading format data...");

            string line;
            int    lineCount = 0;

            while ((line = _Reader.ReadLine()) != null)
            {
                lineCount++;
                if (line.StartsWith(FORMAT))
                {
                    ReadFormat(line, log);
                }
                else if (line.StartsWith(DATA))
                {
                    // Initial pass: Create object
                    int    i         = DATA.Length;
                    string guid      = line.NextChunk(ref i, KEY_SEPARATOR);
                    string typeAlias = line.NextChunk(ref i, OPEN_DATABLOCK);
                    if (_Format.ContainsKey(typeAlias))
                    {
                        TypeFieldsFormat format = _Format[typeAlias];

                        IUnique unique = format.Type.Instantiate() as IUnique;//FormatterServices.GetUninitializedObject(format.Type) as IUnique;
                        if (unique is IUniqueWithModifiableGUID)
                        {
                            var uniqueMG = (IUniqueWithModifiableGUID)unique;
                            uniqueMG.SetGUID(new Guid(guid));
                        }
                        else
                        {
                            FieldInfo fI = format.Type.GetBaseField("_GUID"); // Will not work if backing field is named differently!
                            fI.SetValue(unique, new Guid(guid));
                        }
                        _Uniques.Add(unique);
                        if (result == null)
                        {
                            result = unique;                 // Set primary output object
                        }
                    }
                    else
                    {
                        log?.RaiseAlert("FNF" + typeAlias, "Formatting data for type alias '" + typeAlias + "' not found.", AlertLevel.Warning);
                    }
                }
            }

            log?.RaiseAlert("FORM", "Format data read.");

            // Next: Second pass - populate fields with data

            // Rewind:
            stream.Seek(0, SeekOrigin.Begin);
            _Reader = new StreamReader(stream);
            int lineNum = 0;

            while ((line = _Reader.ReadLine()) != null)
            {
                log?.RaiseAlert("DAT", "Reading data...", (double)lineNum / (double)lineCount);
                if (line.StartsWith(DATA))
                {
                    // Initial pass: Create object
                    int    i         = DATA.Length;
                    string guid      = line.NextChunk(ref i, KEY_SEPARATOR);
                    string typeAlias = line.NextChunk(ref i, OPEN_DATABLOCK);
                    if (_Format.ContainsKey(typeAlias))
                    {
                        TypeFieldsFormat format = _Format[typeAlias];
                        object           unique = _Uniques[new Guid(guid)];
                        PopulateFields(ref unique, format, ref i, line, log);
                    }
                }
                lineNum++;
            }

            log?.RaiseAlert("DAT", "Reading data complete.", 1.0);

            log?.RaiseAlert("FIN", "Finalising...");

            // Finally: Call OnDeserialized function on each object
            foreach (var unique in _Uniques)
            {
                MethodInfo mInfo = unique.GetType().GetOnDeserializedMethod();
                if (mInfo != null)
                {
                    mInfo.Invoke(unique, new object[] { new StreamingContext() });
                }
                // TODO: Pass in populated streamingcontext arguments?
            }

            log?.RaiseAlert("FIN", "Finalised");

            return(result);
        }
Beispiel #20
0
        /// <summary>
        /// Download map data for a specified bounding box as a byte array
        /// </summary>
        /// <param name="left"></param>
        /// <param name="bottom"></param>
        /// <param name="right"></param>
        /// <param name="top"></param>
        /// <returns></returns>
        public byte[] DownloadMapData(double left, double bottom, double right, double top, AlertLog log = null)
        {
            string osmAPIGet = BuildGetURL(left, bottom, right, top);

            using (var client = new WebClient())
            {
                try
                {
                    return(client.DownloadData(osmAPIGet));
                }
                catch (Exception ex)
                {
                    log?.RaiseAlert("Error downloading map data " + ex.Message, AlertLevel.Warning);
                    return(new byte[] { });
                }
            }
        }
Beispiel #21
0
 /// <summary>
 /// Read map geometry data, automatically retrieving map data from the OpenStreetMap servers
 /// </summary>
 /// <param name="latLong">The latitude and longitude of the map origin</param>
 /// <param name="range">The range around the specified latitude and longitude to be collected, in degrees</param>
 /// <param name="layerNames"></param>
 /// <returns></returns>
 public GeometryLayerTable ReadMap(AnglePair latLong, double range = 0.005, IList <string> layerNames = null,
                                   AlertLog log = null)
 {
     return(ReadMap(latLong.Elevation.Degrees, latLong.Azimuth.Degrees, range, layerNames, log));
 }
Beispiel #22
0
    // Spawn tanks onto planes during the scene
    IEnumerator SpawnEnemiesAR()
    {
        // If there are reliable AR planes
        if (arPlanesTracking.Count > 0)
        {
            // If there is no current enemy spawn
            if (enemySpawnObject == null)
            {
                // Clear alert box
                string alertMessage = "";
                AlertLog.write(alertMessage);

                // Buffer next spawn
                yield return(new WaitForSeconds(3));

                // Determine current enemy tier
                int currentScore = PlayerPrefs.GetInt("PlayerScore");
                while (enemyTier < spawnScores.Count() - 1 && currentScore >= spawnScores[enemyTier + 1])
                {
                    enemyTier++;
                }

                // Random seed
                System.Random randomSeed = new System.Random();

                // Get random enemy from available tiers
                int randomEnemyIndex = randomSeed.Next(0, enemyTier + 1);

                // Get spawn position
                // If AR plane spawn
                if ((randomEnemyIndex == 0 || randomEnemyIndex == 2) && spawnOnARPlanes)
                {
                    // If we lost our plane, start looking again
                    if (!(arPlanesTracking.Count > 0))
                    {
                        yield return(new WaitForSeconds(0.25f));

                        StartCoroutine(FindARPlanesAlert());
                    }

                    // Get a random AR plane
                    int     randomPlaneIndex = randomSeed.Next(0, arPlanesTracking.Count);
                    ARPlane arPlane          = arPlanesTracking[randomPlaneIndex];

                    // Random x, z offset from center of AR plane
                    // May sometimes not be above actual plane
                    Vector3 min         = arPlane.GetComponent <MeshFilter>().mesh.bounds.min;
                    Vector3 max         = arPlane.GetComponent <MeshFilter>().mesh.bounds.max;
                    double  randXDouble = (randomSeed.NextDouble() * ((double)max.x - (double)min.x)) + (double)min.x;
                    float   randX       = (float)randXDouble;
                    double  randZDouble = (randomSeed.NextDouble() * ((double)max.z - (double)min.z)) + (double)min.z;
                    float   randZ       = (float)randZDouble;

                    // Store random AR spawn location
                    spawnARPosition = new Vector3(arPlane.center.x + randX, arPlane.center.y + 0.05f, arPlane.center.z + randZ);

                    // If the random point was not within the bounds, just place in center of the plane
                    if (!Physics.Raycast(spawnARPosition, Vector3.down, 0.1f))
                    {
                        spawnARPosition = new Vector3(arPlane.center.x, arPlane.center.y + 0.05f, arPlane.center.z);
                    }

                    // If below a different plane, lift tank up to highest plane
                    Vector3      spawnSkyPosition  = new Vector3(spawnARPosition.x, spawnARPosition.y + 100.0f, spawnARPosition.z);
                    RaycastHit[] allSkyHits        = Physics.RaycastAll(spawnSkyPosition, Vector3.down);
                    Vector3      highestARPlanePos = new Vector3(spawnARPosition.x, -999.9f, spawnARPosition.z);

                    // Find highest plane
                    foreach (var hit in allSkyHits)
                    {
                        if (hit.collider.name.Substring(0, 7) == "ARPlane" && highestARPlanePos.y < hit.point.y)
                        {
                            highestARPlanePos = new Vector3(transform.position.x, hit.point.y, transform.position.z);
                        }
                    }

                    // Place a bit above highest plane if one is found
                    if (spawnARPosition.y < highestARPlanePos.y)
                    {
                        spawnARPosition.y = highestARPlanePos.y + 0.05f;
                    }

                    // Store player location information in reference to AR plane
                    target             = GameObject.FindWithTag("MainCamera");
                    targetVectorGround = new Vector3(target.transform.position.x, spawnARPosition.y, target.transform.position.z);

                    // Store spawn position
                    spawnPosition = spawnARPosition;
                } // If non-AR plane spawn
                else if (randomEnemyIndex == 1 || !spawnOnARPlanes)
                {
                    // Get a random spawn location from given positions
                    int       randomSpawnIndex = randomSeed.Next(0, enemySpawnPoints.Count());
                    Transform enemySpawnPoint  = enemySpawnPoints[randomSpawnIndex];
                    spawnPosition = new Vector3(enemySpawnPoint.position.x, enemySpawnPoint.position.y, enemySpawnPoint.position.z);
                }

                // Place enemy at spawn point
                enemySpawnObject = Instantiate(enemyPrefabs[randomEnemyIndex], spawnPosition, Quaternion.identity);

                // If AR spawn, rotate to face player
                if (randomEnemyIndex == 0)
                {
                    // Spawn with random direction
                    enemySpawnObject.transform.rotation = Quaternion.Euler(0, randomSeed.Next(0, 360), 0);
                }
                else if (randomEnemyIndex == 1)
                {
                    // Let the missile go for 8 seconds
                    int missileTimer = 8;
                    while (enemySpawnObject != null && missileTimer > 0)
                    {
                        yield return(new WaitForSeconds(1f));

                        missileTimer--;
                    }

                    // If the missile was not destoryed after given time,
                    // destory the missile
                    if (enemySpawnObject != null)
                    {
                        Destroy(enemySpawnObject);
                    }
                }
                else if (randomEnemyIndex == 2)
                {
                    // Spawn facing player
                    enemySpawnObject.transform.LookAt(targetVectorGround);
                }
            }

            // Wait some time then start again
            if (arPlanesTracking.Count > 0)
            {
                yield return(new WaitForSeconds(0.5f));

                StartCoroutine(SpawnEnemiesAR());
            }
            else
            {
                yield return(new WaitForSeconds(0));

                StartCoroutine(FindARPlanesAlert());
            }
        } // If there are no reliable AR planes
        else
        {
            yield return(new WaitForSeconds(0));

            StartCoroutine(FindARPlanesAlert());
        }
    }
Beispiel #23
0
    void FixedUpdate()
    {
        if (Vector3.Distance(transform.position, target.transform.position) < 1.8f)
        {
            randomTurns  = false;
            directTarget = true;
        }

        if (Vector3.Distance(transform.position, target.transform.position) < 0.2f)
        {
            directTarget = false;
            stopRotation = true;
        }

        if (!stopRotation)
        {
            if (directTarget)
            {
                transform.LookAt(target.transform);
            }

            if (randomTurns)
            {
                if (Vector3.Distance(transform.position, target.transform.position) > 7f)
                {
                    transform.LookAt(target.transform);
                }
                else if (Time.time > nextTurnTime)
                {
                    // Get next turn time
                    System.Random randomSeed = new System.Random();
                    double        timeRange  = (double)turnIntervalMax - (double)(turnIntervalMin);
                    double        sampleTime = randomSeed.NextDouble();
                    double        scaledTime = (sampleTime * timeRange) + (turnIntervalMin);
                    float         randomTime = (float)scaledTime;
                    nextTurnTime = Time.time + randomTime;

                    // Turn random direction
                    double turnRange  = (double)turnRangeMax - (double)(turnRangeMin);
                    double sampleTurn = randomSeed.NextDouble();
                    double scaledTurn = (sampleTurn * turnRange) + (turnRangeMin);
                    float  turnDegree = (float)scaledTurn;
                    transform.LookAt(target.transform);
                    transform.Rotate(0.0f, turnDegree, 0.0f);
                }
            }
        }

        transform.position += transform.forward * moveSpeed * Time.deltaTime;

        string enemyAlert = "";

        // Determine where the target is in reference to the player
        Vector3 enemyPos       = Quaternion.Inverse(target.transform.rotation) * (transform.position - target.transform.position);
        bool    easilyViewable = false;

        Vector3 screenPoint = camera.WorldToViewportPoint(transform.position);

        if (screenPoint.z > 0 && screenPoint.x > 0.1 && screenPoint.x < 0.9 && screenPoint.y > 0.1 && screenPoint.y < 0.9)
        {
            easilyViewable = true;
        }
        else
        {
            easilyViewable = false;
        }

        if (Vector3.Distance(target.transform.position, transform.position) < 3f)
        {
            enemyAlert += "ENEMY IN RANGE";
        }

        if (!easilyViewable)
        {
            if (enemyPos.z < 0)
            {
                enemyAlert += "\n\nENEMY TO REAR";
            }
            else if (enemyPos.x > 0.5f)
            {
                enemyAlert += "\n\nENEMY TO RIGHT";
            }
            else if (enemyPos.x < -0.5f)
            {
                enemyAlert += "\n\nENEMY TO LEFT";
            }
            else if (enemyPos.y < 0)
            {
                enemyAlert += "\n\nENEMY BELOW";
            }
        }

        AlertLog.write(enemyAlert);
    }