Example #1
0
        public void Add()
        {
            
                                                 GroupLayer gl = AppState.ViewDef.FindOrCreateGroupLayer(@"Weather/Rain");
                                                 var w = new WebMercator();
                                                 //Buienradar
                                                 var wi = new ElementLayer() { ID = "Rain Radar" };
                                                 var i = new Image
                                                 {
                                                     Source = new BitmapImage(new Uri("http://www2.buienradar.nl/euradar/latlon_0.gif")),
                                                     IsHitTestVisible = false,
                                                     Stretch = Stretch.Fill
                                                 };
                                                 //<LatLonBox><north>59.9934</north><south>41.4389</south><east>20.4106</east><west>-14.9515</west></LatLonBox>
                                                 var mpa = new MapPoint(-14.9515, 41.4389);
                                                 var mpb = new MapPoint(20.4106, 59.9934);
                                                 mpa = w.FromGeographic(mpa) as MapPoint;
                                                 mpb = w.FromGeographic(mpb) as MapPoint;
                                                 var envelope = new Envelope(mpa, mpb);
                                                 ElementLayer.SetEnvelope(i, envelope);
                                                 wi.Children.Add(i);
                                                 wi.Initialize();
                                                 wi.Visible = true;
                                                 gl.ChildLayers.Add(wi);
            
            

        }
		// Create Polygon graphics on the map in the center and the center of four equal quadrants
		private void MyMapView_NavigationCompleted(object sender, EventArgs e)
		{
			MyMapView.NavigationCompleted -= MyMapView_NavigationCompleted;
			try
			{
				var height = MyMapView.Extent.Height / 4;
				var width = MyMapView.Extent.Width / 4;
				var length = width / 4;
				var center = MyMapView.Extent.GetCenter();
				var topLeft = new MapPoint(center.X - width, center.Y + height, MyMapView.SpatialReference);
				var topRight = new MapPoint(center.X + width, center.Y + height, MyMapView.SpatialReference);
				var bottomLeft = new MapPoint(center.X - width, center.Y - height, MyMapView.SpatialReference);
				var bottomRight = new MapPoint(center.X + width, center.Y - height, MyMapView.SpatialReference);

				var redSymbol = new SimpleFillSymbol() { Color = Colors.Red };
				var blueSymbol = new SimpleFillSymbol() { Color = Colors.Blue };

				_graphicsOverlay.Graphics.Add(new Graphic() { Geometry = CreatePolygonBox(center, length), Symbol = blueSymbol });
				_graphicsOverlay.Graphics.Add(new Graphic() { Geometry = CreatePolygonBox(topLeft, length), Symbol = redSymbol });
				_graphicsOverlay.Graphics.Add(new Graphic() { Geometry = CreatePolygonBox(topRight, length), Symbol = redSymbol });
				_graphicsOverlay.Graphics.Add(new Graphic() { Geometry = CreatePolygonBox(bottomLeft, length), Symbol = redSymbol });
				_graphicsOverlay.Graphics.Add(new Graphic() { Geometry = CreatePolygonBox(bottomRight, length), Symbol = redSymbol });
			}
			catch (Exception ex)
			{
				var _x = new MessageDialog("Error occurred : " + ex.Message, "Sample Error").ShowAsync();
			}
        }
        void ZoomToLevel(int level, MapPoint point)
        {
            bool zoomentry = false;
            double resolution;
            if (level == -1)
                resolution = map.Resolution;
            else
                resolution = (this.map.Layers["basemap"] as TiledLayer).TileInfo.Lods[level].Resolution;


            if (Math.Abs(map.Resolution - resolution) < 0.05)
            {
                this.map.PanTo(point);
                return;
            }
            zoomentry = false;
            this.map.ZoomToResolution(resolution);

            map.ExtentChanged += (s, a) =>
            {
                if (!zoomentry)
                    this.map.PanTo(point);

                zoomentry = true;

                //   SwitchLayerVisibility();
            };



        }
Example #4
0
        public static BoundingBox GetBoundingBoxMiles(MapPoint point, double halfSideInMiles)
        {
            // Bounding box surrounding the point at given coordinates,
            // assuming local approximation of Earth surface as a sphere
            // of radius given by WGS84
            var lat = Deg2rad(point.Latitude);
            var lon = Deg2rad(point.Longitude);
            var halfSide = 1609.344 * halfSideInMiles;

            // Radius of Earth at given latitude
            var radius = WGS84EarthRadius(lat);
            // Radius of the parallel at given latitude
            var pradius = radius * Math.Cos(lat);

            var latMin = lat - halfSide / radius;
            var latMax = lat + halfSide / radius;
            var lonMin = lon - halfSide / pradius;
            var lonMax = lon + halfSide / pradius;

            return new BoundingBox
            {
                MinPoint = new MapPoint { Latitude = Rad2deg(latMin), Longitude = Rad2deg(lonMin) },
                MaxPoint = new MapPoint { Latitude = Rad2deg(latMax), Longitude = Rad2deg(lonMax) }
            };
        }
		public async Task<RouteResult> GetRoute(string address, MapPoint from, CancellationToken cancellationToken)
		{
			var to = await Geocode(address, cancellationToken).ConfigureAwait(false);
			if (to == null)
				throw new ArgumentException("Address not found");
			return await GetRoute(from, to, cancellationToken);
		}
		private async Task QueryElevation(MapPoint location)
		{
			if (MySceneView.GetCurrentViewpoint(ViewpointType.BoundingGeometry) == null)
				return;

			if (!_isSceneReady)
				return;

			try
			{
				_isSceneReady = false;

				double elevation = await _fileElevationSource.GetElevationAsync(location);

				if (elevation.ToString() == "NaN")
				{
					mapTip.Visibility = System.Windows.Visibility.Hidden;
					return;
				}

				MapView.SetViewOverlayAnchor(mapTip, location);
				mapTip.Visibility = System.Windows.Visibility.Visible;
				txtElevation.Text = String.Format("Elevation: {0} meters", elevation.ToString());

			}
			catch (Exception ex)
			{
				MessageBox.Show("Error retrieving elevation values: " + ex.Message, "Sample Error");
			}
			finally
			{
				_isSceneReady = true;
			}
		}
Example #7
0
 /// <summary> Adds tree with default properties. </summary>
 public void AddTree(MapPoint point)
 {
     _tileModelEditor.AddTree(new Tree()
     {
         Point = point
     });
 }
        private async void Initialize()
        {
            // Create new Map with basemap
            Map myMap = new Map(Basemap.CreateTopographic());

            // Create a MapPoint the map should zoom to
            MapPoint mapPoint = new MapPoint(
                -13630484, 4545415, SpatialReferences.WebMercator);

            // Set the initial viewpoint for map
            myMap.InitialViewpoint = new Viewpoint(mapPoint, 90000);

            // Provide used Map to the MapView
            MyMapView.Map = myMap;

            // Create the uri for the feature service
            Uri featureServiceUri = new Uri(
                "https://sampleserver6.arcgisonline.com/arcgis/rest/services/SF311/FeatureServer/0");

            // Initialize feature table using a url to feature server url
            ServiceFeatureTable featureTable = new ServiceFeatureTable(featureServiceUri);

            // Initialize a new feature layer based on the feature table
            _featureLayer = new FeatureLayer(featureTable);

            //Add the feature layer to the map
            myMap.OperationalLayers.Add(_featureLayer);

            // TODO: https://github.com/Esri/arcgis-runtime-samples-xamarin/issues/96
            if (Device.OS == TargetPlatform.iOS || Device.OS == TargetPlatform.Other)
            {
                await _featureLayer.RetryLoadAsync();
            }
        }
        private async void Initialize()
        {
            // Create new Map with basemap
            Map myMap = new Map(Basemap.CreateTopographic());

            // Create a mappoint the map should zoom to
            MapPoint mapPoint = new MapPoint(-13630484, 4545415, SpatialReferences.WebMercator);

            // Set the initial viewpoint for map
            myMap.InitialViewpoint = new Viewpoint(mapPoint, 90000);

            // Provide used Map to the MapView
            _myMapView.Map = myMap;

            // Create the uri for the feature service
            Uri featureServiceUri = new Uri("http://sampleserver6.arcgisonline.com/arcgis/rest/services/SF311/FeatureServer/0");

            // Initialize feature table using a url to feature server url
            ServiceFeatureTable featureTable = new ServiceFeatureTable(featureServiceUri);

            // Initialize a new feature layer based on the feature table
            _featureLayer = new FeatureLayer(featureTable);

            //Add the feature layer to the map
            myMap.OperationalLayers.Add(_featureLayer);
        }
	public void EditorUpdateWall(HouseController house)
	{
		WallController wc = GetComponent<WallController>();

		MapPoint p;
		bool ne=false,nw=false,se=false,sw=false;

		p = new MapPoint(wc.Position.X, wc.Position.Y);
		if(house.GetCell(p)==null)
			ne=true;

		p = new MapPoint(wc.Position.X-1, wc.Position.Y);
		if(house.GetCell(p)==null)
			nw=true;

		p = new MapPoint(wc.Position.X, wc.Position.Y-1);
		if(house.GetCell(p)==null)
			se=true;

		p = new MapPoint(wc.Position.X-1, wc.Position.Y-1);
		if(house.GetCell(p)==null)
			sw=true;

		North = ne && nw;
		South = se && sw;
		East = ne && se;
		West = nw && sw;

	}
        // Creates a polyline with two paths in the shape of an 'X' centered at the given point
        private Polyline CreatePolylineX(MapPoint center, double length)
        {
            var halfLen = length / 2.0;

			LineSegment segment = new LineSegment(
				new MapPoint(center.X - halfLen, center.Y + halfLen, MyMapView.SpatialReference),
				new MapPoint(center.X + halfLen, center.Y - halfLen, MyMapView.SpatialReference));

			LineSegment segment2 = new LineSegment(
				new MapPoint(center.X + halfLen, center.Y + halfLen, MyMapView.SpatialReference),
				new MapPoint(center.X - halfLen, center.Y - halfLen, MyMapView.SpatialReference));

			var segmentCollection = new SegmentCollection(MyMapView.SpatialReference)
			{
				segment
			};

			var segmentCollection2 = new SegmentCollection(MyMapView.SpatialReference)
			{
				segment2
			};

			return new Polyline(new [] { segmentCollection, segmentCollection2},
				MyMapView.SpatialReference);
        }
        private void Modify(MapPoint center, bool upMode)
        {
            var sw = new Stopwatch();
            sw.Start();

            var mesh = gameObject.GetComponent<MeshFilter>().mesh;
            var vertices = mesh.vertices;

            var radius = 5;

            bool isModified = false;
            _meshIndex.Query(center, radius, vertices, (i, distance, _) =>
            {
                var vertex = vertices[i];
                float heightDiff = (distance - radius)/2;
                vertices[i] = new Vector3(
                    vertex.x,
                    vertex.y + (upMode ? -heightDiff : heightDiff),
                    vertex.z);
                isModified = true;
            });

            if (isModified)
            {
                mesh.vertices = vertices;
                mesh.RecalculateBounds();
                mesh.RecalculateNormals();

                DestroyImmediate(gameObject.GetComponent<MeshCollider>());
                gameObject.AddComponent<MeshCollider>();
            }

            sw.Stop();
            Debug.Log(String.Format("Processed in {0}ms (incl. collider). Status: {1} ", sw.ElapsedMilliseconds, isModified));
        }
Example #13
0
        public static Graphic NewDonut(double x, double y, double innerRadius, double outerRadius)
        {
            double[] px = new double[NUM];
            double[] py = new double[NUM];
            GeometryAlgorithms.CircleToPoints(x, y, outerRadius, NUM, px, py, AngleDirection.CounterClockwise);

            Esri.ArcGISRuntime.Geometry.PointCollection pc = new Esri.ArcGISRuntime.Geometry.PointCollection();
            for (int i = 0; i < NUM; i++)
            {
                MapPoint p = new MapPoint(px[i], py[i]);
                pc.Add(p);
            }
            pc.Add(pc[0]);

            PolygonBuilder polygon = new PolygonBuilder(pc);

            GeometryAlgorithms.CircleToPoints(x, y, innerRadius, NUM, px, py, AngleDirection.Clockwise);
            pc = new Esri.ArcGISRuntime.Geometry.PointCollection();
            for (int i = 0; i < NUM; i++)
            {
                MapPoint p = new MapPoint(px[i], py[i]);
                pc.Add(p);
            }
            pc.Add(pc[0]);
            polygon.AddPart(pc);

            Graphic g = new Graphic();
            g.Geometry = polygon.ToGeometry();
            return g;
        }
        private void Initialize()
        {
            // Create new Map with basemap
            Map myMap = new Map(Basemap.CreateTopographic());

            // Create and set initial map location
            MapPoint initialLocation = new MapPoint(
                -11000000, 5000000, SpatialReferences.WebMercator);
                myMap.InitialViewpoint = new Viewpoint(initialLocation, 100000000);

            // Create feature table using a url
            _featureTable = new ServiceFeatureTable(new Uri(_statesUrl));

            // Create feature layer using this feature table
            _featureLayer = new FeatureLayer(_featureTable);

            // Set the Opacity of the Feature Layer
            _featureLayer.Opacity = 0.6;

            // Create a new renderer for the States Feature Layer
            SimpleLineSymbol lineSymbol = new SimpleLineSymbol(
                SimpleLineSymbolStyle.Solid, Color.Black, 1); 
            SimpleFillSymbol fillSymbol = new SimpleFillSymbol(
                SimpleFillSymbolStyle.Solid, Color.Yellow, lineSymbol);

            // Set States feature layer renderer
            _featureLayer.Renderer = new SimpleRenderer(fillSymbol);

            // Add feature layer to the map
            myMap.OperationalLayers.Add(_featureLayer);

            // Assign the map to the MapView
            _myMapView.Map = myMap;
        }
        public static string GetMapPointAsDisplayString(MapPoint mp)
        {
            if (mp == null)
                return "NA";

            var result = string.Format("{0:0.0} {1:0.0}", mp.Y, mp.X);

            // .ToGeoCoordinate function calls will fail if there is no Spatial Reference
            if (mp.SpatialReference == null)
                return result;

            ToGeoCoordinateParameter tgparam = null;

            try
            {
                switch (VisibilityConfig.AddInConfig.DisplayCoordinateType)
                {
                    case CoordinateTypes.DD:
                        tgparam = new ToGeoCoordinateParameter(GeoCoordinateType.DD);
                        tgparam.NumDigits = 6;
                        result = mp.ToGeoCoordinateString(tgparam);
                        break;
                    case CoordinateTypes.DDM:
                        tgparam = new ToGeoCoordinateParameter(GeoCoordinateType.DDM);
                        tgparam.NumDigits = 4;
                        result = mp.ToGeoCoordinateString(tgparam);
                        break;
                    case CoordinateTypes.DMS:
                        tgparam = new ToGeoCoordinateParameter(GeoCoordinateType.DMS);
                        tgparam.NumDigits = 2;
                        result = mp.ToGeoCoordinateString(tgparam);
                        break;
                    case CoordinateTypes.GARS:
                        tgparam = new ToGeoCoordinateParameter(GeoCoordinateType.GARS);
                        result = mp.ToGeoCoordinateString(tgparam);
                        break;
                    case CoordinateTypes.MGRS:
                        tgparam = new ToGeoCoordinateParameter(GeoCoordinateType.MGRS);
                        result = mp.ToGeoCoordinateString(tgparam);
                        break;
                    case CoordinateTypes.USNG:
                        tgparam = new ToGeoCoordinateParameter(GeoCoordinateType.USNG);
                        tgparam.NumDigits = 5;
                        result = mp.ToGeoCoordinateString(tgparam);
                        break;
                    case CoordinateTypes.UTM:
                        tgparam = new ToGeoCoordinateParameter(GeoCoordinateType.UTM);
                        tgparam.GeoCoordMode = ToGeoCoordinateMode.UtmNorthSouth;
                        result = mp.ToGeoCoordinateString(tgparam);
                        break;
                    default:
                        break;
                }
            }
            catch(Exception ex)
            {
                // do nothing
            }
            return result;
        }
	void InstantiatePhantom(MapPoint p, bool isGreen)
	{
		Transform ph = Instantiate<Transform>(isGreen?Green:Red);
		ph.parent = transform;
		ph.localPosition = new Vector3(p.X+0.5f,p.Y+0.5f,0);
		phantoms.Add(p.toInt(),ph);
	}
        private static Camera Translate(this Camera camera, ISensor sensor, double moveFactor, double zoomFactor, double rotationFactor, double tiltFactor)
        {
            var x = sensor.Translation.X;
            var y = -sensor.Translation.Z;
            var move = sensor.Translation.Length;
            var zoom = sensor.Translation.Y;
            var rotation = -Math.Sign(sensor.Rotation.Y) * sensor.Rotation.Angle;
            var tilt = sensor.Rotation.X;

            //Rotate
            var rotation1 = rotation * rotationFactor;
            var rotation2 = rotation1 < 0 && camera.Heading < 0.1 ? 359.5 : rotation1;
            var camera1 = camera.Rotate(rotation2, 0);

            //Zoom
            var deltaAltitude = zoom * camera1.Location.Z * zoomFactor;
            var camera2 = camera1.Elevate(deltaAltitude);

            //Move
            var azimuth1 = Math.Atan(y / x) / Math.PI * 180;
            var azimuth2 = x > 0 ? 90 - azimuth1 : x < 0 ? 270 - azimuth1 : y >= 0 ? 0 : 180;
            var azimuth3 = (azimuth2 + camera2.Heading) % 360;
            var point1 = camera2.Location;
            var point2 = GeometryEngine.GeodesicMove(point1, point1.Z * move * moveFactor, LinearUnits.Meters, azimuth3);
            var point3 = new MapPoint(point2.X, point2.Y, point1.Z + deltaAltitude);
            var camera3 = camera2.SetLocation(point3);

            //Tilt
            var pitch1 = camera3.Pitch + tilt * tiltFactor;
            var pitch2 = pitch1 < 0 ? 0 : (pitch1 > 180 ? 180 : pitch1);
            var camera4 = camera3.SetPitch(pitch2);

            return camera4;
        }
        private void Initialize()
        {
            // Create new Map with basemap
            Map myMap = new Map(Basemap.CreateImagery());

            // Create initial map location and reuse the location for graphic
            MapPoint centralLocation = new MapPoint(-226773, 6550477, SpatialReferences.WebMercator);
            Viewpoint initialViewpoint = new Viewpoint(centralLocation, 7500);

            // Set initial viewpoint
            myMap.InitialViewpoint = initialViewpoint;

            // Provide used Map to the MapView
            _myMapView.Map = myMap;

            // Create overlay to where graphics are shown
            GraphicsOverlay overlay = new GraphicsOverlay();

            // Add created overlay to the MapView
            _myMapView.GraphicsOverlays.Add(overlay);

            // Create a simple marker symbol
            SimpleMarkerSymbol simpleSymbol = new SimpleMarkerSymbol()
            {
                Color = Color.Red,
                Size = 10,
                Style = SimpleMarkerSymbolStyle.Circle
            };

            // Add a new graphic with a central point that was created earlier
            Graphic graphicWithSymbol = new Graphic(centralLocation, simpleSymbol);
            overlay.Graphics.Add(graphicWithSymbol);
        }
		// Create polyline graphics on the map in the center and the center of four equal quadrants
		void MyMapView_SpatialReferenceChanged(object sender, EventArgs e)
		{
			MyMapView.SpatialReferenceChanged -= MyMapView_SpatialReferenceChanged;

			try
			{
				// Get current viewpoints extent from the MapView
				var currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
				var viewpointExtent = currentViewpoint.TargetGeometry.Extent;
				var height = viewpointExtent.Height / 4;
				var width = viewpointExtent.Width / 4;
				var length = width / 4;
				var center = viewpointExtent.GetCenter();
				var topLeft = new MapPoint(center.X - width, center.Y + height, MyMapView.SpatialReference);
				var topRight = new MapPoint(center.X + width, center.Y + height, MyMapView.SpatialReference);
				var bottomLeft = new MapPoint(center.X - width, center.Y - height, MyMapView.SpatialReference);
				var bottomRight = new MapPoint(center.X + width, center.Y - height, MyMapView.SpatialReference);

				var redSymbol = new SimpleLineSymbol() { Color = Colors.Red, Width = 4, Style = SimpleLineStyle.Solid };
				var blueSymbol = new SimpleLineSymbol() { Color = Colors.Blue, Width = 4, Style = SimpleLineStyle.Solid };

				_graphicsOverlay.Graphics.Add(new Graphic() { Geometry = CreatePolylineX(center, length), Symbol = blueSymbol });
				_graphicsOverlay.Graphics.Add(new Graphic() { Geometry = CreatePolylineX(topLeft, length), Symbol = redSymbol });
				_graphicsOverlay.Graphics.Add(new Graphic() { Geometry = CreatePolylineX(topRight, length), Symbol = redSymbol });
				_graphicsOverlay.Graphics.Add(new Graphic() { Geometry = CreatePolylineX(bottomLeft, length), Symbol = redSymbol });
				_graphicsOverlay.Graphics.Add(new Graphic() { Geometry = CreatePolylineX(bottomRight, length), Symbol = redSymbol });
			}
			catch (Exception ex)
			{
				var _x = new MessageDialog("Error occurred : " + ex.Message, "Sample Error").ShowAsync();
			}
		}
        private void WorldFileLoaded(object sender, DownloadStringCompletedEventArgs e)
        {
            //Checks to see if there was an error
            if (e.Error == null)
            {
                //grab the data from the world file
                string myData = e.Result;
                //split string into an array based on new line characters
                string[] lines = myData.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
                //convert the strings into doubles
                double[] coordValues = new double[6];
                for(int i = 0; i < 6; i++) {
                    coordValues[i] = Convert.ToDouble(lines[i]);
                }
                //calculate the pixel height and width in real world coordinates
                double pixelWidth = Math.Sqrt(Math.Pow(coordValues[0], 2) + Math.Pow(coordValues[1], 2));
                double pixelHeight = Math.Sqrt(Math.Pow(coordValues[2], 2) + Math.Pow(coordValues[3], 2));

                //Create a map point for the top left and bottom right
                MapPoint topLeft = new MapPoint(coordValues[4], coordValues[5]);
                MapPoint bottomRight = new MapPoint(coordValues[4] + (pixelWidth * imageWidth), coordValues[5] + (pixelHeight * imageHeight));
                //create an envelope for the elmently layer
                Envelope extent = new Envelope(topLeft.X, topLeft.Y, bottomRight.X, bottomRight.Y);
                ElementLayer.SetEnvelope(image, extent);
                //Zoom to the extent of the image
                MyMap.Extent = extent;
            }
        }
		protected override void OnPointSelected(MapPoint place)
		{
			AppCommon.Inst.CurrentReq = new Request { Src = place };
			AppCommon.Inst.NearestPointProvider.DirectionAdded -= OnPointDirectionsAdded;
			AppCommon.Inst.NearestPointProvider.PointsReset -= OnPointsReset;
			this.StartNextActivity<ReqDetailsActivity> ();
		}
        private async void Initialize()
        {
            // Create new Map with basemap
            Map myMap = new Map(Basemap.CreateTopographic());

            // Create and set initial map location
            MapPoint initialLocation = new MapPoint(
                -13630484, 4545415, SpatialReferences.WebMercator);
            myMap.InitialViewpoint = new Viewpoint(initialLocation, 500000);

            // Create uri to the used feature service
            var serviceUri = new Uri(
               "http://sampleserver6.arcgisonline.com/arcgis/rest/services/SF311/FeatureServer/0");

            // Create feature table for the incident feature service
            _incidentsFeatureTable = new ServiceFeatureTable(serviceUri);

            // Define the request mode
            _incidentsFeatureTable.FeatureRequestMode = FeatureRequestMode.ManualCache;

            // When feature table is loaded, populate data
            _incidentsFeatureTable.LoadStatusChanged += OnLoadedPopulateData;

            // Create FeatureLayer that uses the created table
            FeatureLayer incidentsFeatureLayer = new FeatureLayer(_incidentsFeatureTable);

            // Add created layer to the map
            myMap.OperationalLayers.Add(incidentsFeatureLayer);

            // Assign the map to the MapView
            _myMapView.Map = myMap;
        }
 public void MapPointConstructor_Test()
 {
     MapPoint target = new MapPoint();
     Assert.AreEqual(0, target.Lat);
     Assert.AreEqual(0, target.Lon);
     Assert.AreEqual(null, target.Name);
 }
		// Create four point graphics on the map in the center of four equal quadrants
		private void MyMapView_NavigationCompleted(object sender, EventArgs e)
		{
			MyMapView.NavigationCompleted -= MyMapView_NavigationCompleted;
			try
			{
				var height = MyMapView.Extent.Height / 4;
				var width = MyMapView.Extent.Width / 4;
				var center = MyMapView.Extent.GetCenter();

				var topLeft = new MapPoint(center.X - width, center.Y + height, MyMapView.SpatialReference);
				var topRight = new MapPoint(center.X + width, center.Y + height, MyMapView.SpatialReference);
				var bottomLeft = new MapPoint(center.X - width, center.Y - height, MyMapView.SpatialReference);
				var bottomRight = new MapPoint(center.X + width, center.Y - height, MyMapView.SpatialReference);

				var symbol = new SimpleMarkerSymbol() { Color = Colors.Red, Size = 15, Style = SimpleMarkerStyle.Diamond };

				_graphicsOverlay.Graphics.Add(new Graphic() { Geometry = topLeft, Symbol = symbol });
				_graphicsOverlay.Graphics.Add(new Graphic() { Geometry = topRight, Symbol = symbol });
				_graphicsOverlay.Graphics.Add(new Graphic() { Geometry = bottomLeft, Symbol = symbol });
				_graphicsOverlay.Graphics.Add(new Graphic() { Geometry = bottomRight, Symbol = symbol });

				_graphicsOverlay.Graphics.Add(new Graphic()
				{
					Geometry = new MapPoint(0, 0),
					Symbol = new SimpleMarkerSymbol() { Size = 15, Color = Colors.Blue }
				});
			}
			catch (Exception ex)
			{
				var _x = new MessageDialog("Error occurred : " + ex.Message, "Sample Error").ShowAsync();
			}
		}
        private void Modify(MapPoint center)
        {
            var sw = new Stopwatch();
            sw.Start();

            var mesh = gameObject.GetComponent<MeshFilter>().mesh;
            var vertices = mesh.vertices;
            var radius = 5;
            _meshIndex.Query(center, radius, vertices, (i, distance, direction) =>
            {
                var vertex = vertices[i];
                vertices[i] = new Vector3(
                    vertex.x + direction.x*(distance - radius)/2,
                    vertex.y,
                    vertex.z + direction.y*(distance - radius)/2);
            });

            mesh.vertices = vertices;
            mesh.RecalculateNormals();

            DestroyImmediate(gameObject.GetComponent<MeshCollider>());
            gameObject.AddComponent<MeshCollider>();

            sw.Stop();

            Debug.Log(String.Format("Processed in {0}ms (incl. collider)", sw.ElapsedMilliseconds));
        }
    public static void ProjectEnvelopeAsync(Envelope envelope, SpatialReference spatialReference, EventHandler<GeometryEventArgs> callback)
    {
      if (envelope.SpatialReference.WKID == spatialReference.WKID)
      {
        callback(null, new GeometryEventArgs() { Geometry = envelope });
        return;
      }

      if ((envelope.SpatialReference.WKID == WKIDs.WebMercator || envelope.SpatialReference.WKID == WKIDs.WebMercatorAuxiliarySphere) && spatialReference.WKID == WKIDs.Geographic)
      {
        MapPoint p1 = new MapPoint(Math.Max(envelope.XMin, -19977660), Math.Max(envelope.YMin, -43076226));
        MapPoint p2 = new MapPoint(Math.Min(envelope.XMax, 19998531), Math.Min(envelope.YMax, 33656597));
        Envelope output = new Envelope(ESRI.ArcGIS.Client.Bing.Transform.WebMercatorToGeographic(p1),
                                       ESRI.ArcGIS.Client.Bing.Transform.WebMercatorToGeographic(p2));
        output.SpatialReference = spatialReference;
        callback(null, new GeometryEventArgs() { Geometry = output });
        return;
      }
      
      if (envelope.SpatialReference.WKID == WKIDs.Geographic && (spatialReference.WKID == WKIDs.WebMercator || spatialReference.WKID == WKIDs.WebMercatorAuxiliarySphere))
      {
        MapPoint p1 = new MapPoint(envelope.XMin, envelope.YMin);
        MapPoint p2 = new MapPoint(envelope.XMax, envelope.YMax);
        Envelope output = new Envelope(ESRI.ArcGIS.Client.Bing.Transform.GeographicToWebMercator(p1),
                                       ESRI.ArcGIS.Client.Bing.Transform.GeographicToWebMercator(p2));
        output.SpatialReference = spatialReference;
        callback(null, new GeometryEventArgs() { Geometry = output });
        return;
      }

      ProjectAsync(envelope, spatialReference, callback);
    }
Example #27
0
        protected override Graphic OnCreateGraphic(GraphicCollection cluster, MapPoint point, int maxClusterCount)
        {
            if (cluster.Count == 1) return cluster[0];

            double sum = 0;

            foreach (var g in cluster) {
                if (!g.Attributes.ContainsKey("Poi")) continue;
                try {
                    var poi = g.Attributes["Poi"] as PoI;
                    if (poi == null) continue;
                    if (poi.Labels.ContainsKey(AggregateLabel))
                        sum += Convert.ToDouble(poi.Labels[AggregateLabel]);
                }
                catch { }
            }
            //double size = (sum + 450) / 30;
            var size = (Math.Log(sum * SymbolScale / 10) * 10 + 20);
            if (size < 12) size = 12;
            var graphic = new Graphic
            {
                Symbol = new ClusterSymbol { Size = size },
                Geometry = point
            };
            graphic.Attributes.Add("Count", sum);
            graphic.Attributes.Add("Size", size);
            graphic.Attributes.Add("Color", InterpolateColor(size - 12, 100));
            return graphic;
        }
        private void Initialize()
        {
            // Create new Map
            Map myMap = new Map();

            // Create the uri for the tiled layer
            Uri tiledLayerUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer");

            // Create a tiled layer using url
            ArcGISTiledLayer tiledLayer = new ArcGISTiledLayer(tiledLayerUri);
            tiledLayer.Name = "Tiled Layer";

            // Add the tiled layer to map
            myMap.OperationalLayers.Add(tiledLayer);

            // Create the uri for the ArcGISMapImage layer
            var imageLayerUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer");

            // Create ArcGISMapImage layer using a url
            ArcGISMapImageLayer imageLayer = new ArcGISMapImageLayer(imageLayerUri);
            imageLayer.Name = "Image Layer";

            // Set the visible scale range for the image layer
            imageLayer.MinScale = 40000000;
            imageLayer.MaxScale = 2000000;

            // Add the image layer to map
            myMap.OperationalLayers.Add(imageLayer);

            //Create Uri for feature layer
            var featureLayerUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Recreation/FeatureServer/0");

            //Create a feature layer using url
            FeatureLayer myFeatureLayer = new FeatureLayer(featureLayerUri);
            myFeatureLayer.Name = "Feature Layer";

            // Add the feature layer to map
            myMap.OperationalLayers.Add(myFeatureLayer);

            // Create a mappoint the map should zoom to
            MapPoint mapPoint = new MapPoint(-11000000, 4500000, SpatialReferences.WebMercator);

            // Set the initial viewpoint for map
            myMap.InitialViewpoint = new Viewpoint(mapPoint, 50000000);

            // Initialize the model list with unknown status for each layer
            foreach (Layer layer in myMap.OperationalLayers)
            {
                _layerStatusModels.Add(new LayerStatusModel(layer.Name, "Unknown"));
            }

            // Create the tableview source and pass the list of models to it
            _tableView.Source = new LayerViewStatusTableSource(_layerStatusModels);

            // Event for layer view state changed
            _myMapView.LayerViewStateChanged += OnLayerViewStateChanged;

            // Provide used Map to the MapView
            _myMapView.Map = myMap;
        }
        private void BroadcastCoordinateValues(MapPoint mapPoint)
        {
            var dict = new Dictionary<CoordinateType, string>();
            if (mapPoint == null)
                return;

            var dd = new CoordinateDD(mapPoint.Y, mapPoint.X);

            try
            {
                dict.Add(CoordinateType.DD, dd.ToString("", new CoordinateDDFormatter()));
            }
            catch { }
            try
            {
                dict.Add(CoordinateType.DDM, new CoordinateDDM(dd).ToString("", new CoordinateDDMFormatter()));
            }
            catch { }
            try
            {
                dict.Add(CoordinateType.DMS, new CoordinateDMS(dd).ToString("", new CoordinateDMSFormatter()));
            }
            catch { }

            Mediator.NotifyColleagues(CoordinateToolLibrary.Constants.BroadcastCoordinateValues, dict);

        }
Example #30
0
        static string _doubleFormat = "F6"; // XML precision

        #endregion Fields

        #region Methods

        public static bool WriteCEXML(ref ParcelData parcelData, string xmlFileName, ref Configuration configuration, ESRI.ArcGIS.Client.Geometry.SpatialReference spatialReference, ref PointDictionary pointDictionary, ref MapPoint projectedStartPoint, double scale, double rotation)
        {
            DocumentEntry documentType = parcelData.DocumentEntries.CurrentItem as DocumentEntry; ;

              XmlWriterSettings settings = new XmlWriterSettings();
              settings.Indent = true;
              settings.IndentChars = "  ";
              settings.NewLineChars = "\r\n";
              settings.NewLineHandling = NewLineHandling.Replace;

              XmlWriter writer = XmlWriter.Create(xmlFileName, settings);
              if (writer == null)
            return false;

              writer.WriteStartDocument();
              writer.WriteStartElement("geodata", "GeoSurveyPacketData", @"http://www.geodata.com.au/schemas/GeoSurvey/ESRI/1.0/");
              writer.WriteElementString("schemaVersion", "2.0");

              WriteUnits(ref writer, ref spatialReference, ref configuration);
              WriteJobParameters(ref writer, ref configuration);
              WritePlans(ref writer, ref parcelData, ref pointDictionary, ref projectedStartPoint, scale, rotation, ref configuration, ref documentType);
              WritePoints(ref writer);
              WriteControl(ref writer);

              writer.WriteEndElement();
              writer.WriteEndDocument();
              writer.Dispose();             // force write of item.

              return true;
        }
        private void Initialize()
        {
            // Create new Scene
            Scene myScene = new Scene
            {
                // Set Scene's base map property
                Basemap = Basemap.CreateImagery()
            };

            // Create a camera with coordinates showing layer data
            Camera camera = new Camera(53.04, -4.04, 1300, 0, 90.0, 0);

            // Assign the Scene to the SceneView
            MySceneView.Scene = myScene;

            // Create ElevationSource from elevation data Uri
            ArcGISTiledElevationSource elevationSource = new ArcGISTiledElevationSource(
                new Uri("https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer"));

            // Add elevationSource to BaseSurface's ElevationSources
            MySceneView.Scene.BaseSurface.ElevationSources.Add(elevationSource);

            // Set view point of scene view using camera
            MySceneView.SetViewpointCameraAsync(camera);

            // Create overlays with elevation modes
            _drapedBillboardedOverlay = new GraphicsOverlay();
            _drapedBillboardedOverlay.SceneProperties.SurfacePlacement = SurfacePlacement.DrapedBillboarded;
            MySceneView.GraphicsOverlays.Add(_drapedBillboardedOverlay);

            _drapedFlatOverlay = new GraphicsOverlay();
            _drapedFlatOverlay.SceneProperties.SurfacePlacement = SurfacePlacement.DrapedFlat;

            GraphicsOverlay relativeOverlay = new GraphicsOverlay();

            relativeOverlay.SceneProperties.SurfacePlacement = SurfacePlacement.Relative;
            MySceneView.GraphicsOverlays.Add(relativeOverlay);

            GraphicsOverlay absoluteOverlay = new GraphicsOverlay();

            absoluteOverlay.SceneProperties.SurfacePlacement = SurfacePlacement.Absolute;
            MySceneView.GraphicsOverlays.Add(absoluteOverlay);

            // Create point for graphic location
            MapPoint point = new MapPoint(-4.04, 53.06, 1000, camera.Location.SpatialReference);

            // Create a red triangle symbol
            SimpleMarkerSymbol triangleSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Triangle, Color.FromArgb(255, 255, 0, 0), 10);

            // Create a text symbol for each elevation mode
            TextSymbol drapedBillboardedText = new TextSymbol("DRAPED BILLBOARDED", Color.FromArgb(255, 255, 255, 255), 10,
                                                              HorizontalAlignment.Center,
                                                              VerticalAlignment.Middle);

            drapedBillboardedText.OffsetY += 20;

            TextSymbol drapedFlatText = new TextSymbol("DRAPED FLAT", Color.FromArgb(255, 255, 255, 255), 10,
                                                       HorizontalAlignment.Center,
                                                       VerticalAlignment.Middle);

            drapedFlatText.OffsetY += 20;

            TextSymbol relativeText = new TextSymbol("RELATIVE", Color.FromArgb(255, 255, 255, 255), 10,
                                                     HorizontalAlignment.Center,
                                                     VerticalAlignment.Middle);

            relativeText.OffsetY += 20;

            TextSymbol absoluteText = new TextSymbol("ABSOLUTE", Color.FromArgb(255, 255, 255, 255), 10,
                                                     HorizontalAlignment.Center,
                                                     VerticalAlignment.Middle);

            absoluteText.OffsetY += 20;

            // Add the point graphic and text graphic to the corresponding graphics overlay
            _drapedBillboardedOverlay.Graphics.Add(new Graphic(point, triangleSymbol));
            _drapedBillboardedOverlay.Graphics.Add(new Graphic(point, drapedBillboardedText));

            _drapedFlatOverlay.Graphics.Add(new Graphic(point, triangleSymbol));
            _drapedFlatOverlay.Graphics.Add(new Graphic(point, drapedFlatText));

            relativeOverlay.Graphics.Add(new Graphic(point, triangleSymbol));
            relativeOverlay.Graphics.Add(new Graphic(point, relativeText));

            absoluteOverlay.Graphics.Add(new Graphic(point, triangleSymbol));
            absoluteOverlay.Graphics.Add(new Graphic(point, absoluteText));
        }
        private async Task ProcessRouteRequest(MapPoint tappedPoint)
        {
            // Clear any existing overlays.
            _routeOverlay.Graphics.Clear();
            _myMapView.DismissCallout();

            // Return if there is no network available for routing.
            if (_networkDataset == null)
            {
                await ShowGeocodeResult(tappedPoint);

                return;
            }

            // Set the start point if it hasn't been set.
            if (_startPoint == null)
            {
                _startPoint = tappedPoint;

                await ShowGeocodeResult(tappedPoint);

                // Show the start point.
                _waypointOverlay.Graphics.Add(await GraphicForPoint(_startPoint));

                return;
            }

            if (_endPoint == null)
            {
                await ShowGeocodeResult(tappedPoint);

                // Show the end point.
                _endPoint = tappedPoint;
                _waypointOverlay.Graphics.Add(await GraphicForPoint(_endPoint));

                // Create the route task from the local network dataset.
                RouteTask routingTask = await RouteTask.CreateAsync(_networkDataset);

                // Configure route parameters for the route between the two tapped points.
                RouteParameters routingParameters = await routingTask.CreateDefaultParametersAsync();

                List <Stop> stops = new List <Stop> {
                    new Stop(_startPoint), new Stop(_endPoint)
                };
                routingParameters.SetStops(stops);

                // Get the first route result.
                RouteResult result = await routingTask.SolveRouteAsync(routingParameters);

                Route firstRoute = result.Routes.First();

                // Show the route on the map. Note that symbology for the graphics overlay is defined in Initialize().
                Polyline routeLine = firstRoute.RouteGeometry;
                _routeOverlay.Graphics.Add(new Graphic(routeLine));

                return;
            }

            // Reset graphics and route.
            _routeOverlay.Graphics.Clear();
            _waypointOverlay.Graphics.Clear();
            _startPoint = null;
            _endPoint   = null;
        }
        private void CalculateDriveTime(MapPoint mapPoint)
        {
            double dDriveTime = 0;

            if (Double.TryParse(tbDriveTimeValue.Text, out dDriveTime) == false)
            {
                return;
            }
            if (dDriveTime <= 0)
            {
                return;
            }

            // make sure the facilities graphic layer has the only one new graphic, based on the mapPoint click location
            Graphic clickGraphic = new Graphic();

            //clickGraphic.Symbol = LayoutRoot.Resources["DefaultMarkerSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol;
            clickGraphic.Geometry = mapPoint;
            int facilityNumber = 1;

            clickGraphic.Attributes.Add("FacilityNumber", facilityNumber);
            _facilitiesGraphicsLayer.Graphics.Clear();
            _facilitiesGraphicsLayer.Graphics.Add(clickGraphic);

            GenerateBarriers();

            try
            {
                RouteServiceAreaParameters routeParams = new RouteServiceAreaParameters()
                {
                    Facilities      = _facilitiesGraphicsLayer.Graphics,
                    DefaultBreaks   = tbDriveTimeValue.Text,
                    TravelDirection = EncodeFacilityTravelDirections(comboFacilityTravelDirection.SelectionBoxItem.ToString()),
                    //Barriers = _pointBarriers.Count > 0 ? _pointBarriers : null,
                    //PolylineBarriers = _polylineBarriers.Count > 0 ? _polylineBarriers : null,
                    //PolygonBarriers = _polygonBarriers.Count > 0 ? _polygonBarriers : null,

                    //ExcludeSourcesFromPolygons = null,
                    //MergeSimilarPolygonRanges = false,
                    //OutputLines = EncodeOutputLines("None"), //"esriNAOutputLineNone"
                    //OverlapLines = true,
                    //OverlapPolygons = true,
                    //SplitLineAtBreaks = false,
                    //SplitPolygonsAtBreaks = true,

                    OutputPolygons = EncodeOutputPolygons("Simplified"), //"esriNAOutputPolygonSimplified",

                    TrimOuterPolygon         = true,
                    TrimPolygonDistance      = 100.0,
                    TrimPolygonDistanceUnits = esriUnits.esriMeters,
                    ReturnFacilities         = false,
                    ReturnBarriers           = false,
                    ReturnPolylineBarriers   = false,
                    ReturnPolygonBarriers    = false,
                    OutSpatialReference      = Map.SpatialReference,

                    AccumulateAttributes = null,
                    //ImpedanceAttribute = "TravelTime"
                    //RestrictionAttributes = "Non-routeable segments,Avoid passenger ferries,TurnRestriction,OneWay".Split(','),
                    //RestrictUTurns = EncodeRestrictUTurns("Allow Backtrack"), //"esriNFSBAllowBacktrack"
                    OutputGeometryPrecision      = 100.0,
                    OutputGeometryPrecisionUnits = esriUnits.esriMeters
                };

                if (_routeTask.IsBusy)
                {
                    _routeTask.CancelAsync();
                }

                _routeTask.SolveServiceAreaAsync(routeParams);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + '\n' + ex.StackTrace);
            }
        }
Example #34
0
        public async Task <List <Graphic> > FindPlaces(MapPoint myLocation)
        {
            List <Graphic> placeGraphics = new List <Graphic>();

            #region Search for places
            //  From .NET Developers Guide: Search for places topic
            //        https://developers.arcgis.com/net/latest/wpf/guide/search-for-places-geocoding-.htm
            // Finding geocode output attributes: https://developers.arcgis.com/rest/geocode/api-reference/geocoding-service-output.htm
            // ** Go to https://developers.arcgis.com/rest/ and then search "Geocode service" ... it'll be about the 5th match!
            // If letting the user select result output attributes, see "Search for places" topic and search the page for "Get locator info"


            //var geocodeServiceUrl = @"https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer";
            //LocatorTask geocodeTask = await LocatorTask.CreateAsync(new Uri(geocodeServiceUrl));

            //// return if points of interest are not supported by this locator
            //if (!geocodeTask.LocatorInfo.SupportsPoi) { return null; }

            //// set geocode parameters to return a max of 10 candidates near the current location
            //// var mapCenter = MyMapView.GetCurrentViewpoint(ViewpointType.CenterAndScale).TargetGeometry as MapPoint;
            //var geocodeParams = new GeocodeParameters
            //{
            //    MaxResults = 10,
            //    PreferredSearchLocation = myLocation // mapCenter
            //};

            //// request address, name, and url as result attributes
            //geocodeParams.ResultAttributeNames.Add("Place_addr");
            //geocodeParams.ResultAttributeNames.Add("PlaceName");
            //geocodeParams.ResultAttributeNames.Add("URL");

            //// find candidates using a place category
            //var matches = await geocodeTask.GeocodeAsync(Item.PlaceType.ToLower(), geocodeParams);

            //if (matches.Count == 0) { return null; }

            // ** end: search for places
            #endregion
            //  Use code from .NET Developers Guide: Search for places topic
            //        https://developers.arcgis.com/net/latest/wpf/guide/search-for-places-geocoding-.htm
            //
            // To find geocode output attributes: https://developers.arcgis.com/rest/geocode/api-reference/geocoding-service-output.htm
            // ** Go to https://developers.arcgis.com/rest/ and then search "Geocode service" ... it'll be about the 5th match
            //
            // If letting the user select result output attributes, see "Search for places" topic and search the page for "Get locator info"


            #region Create graphics from results

            //foreach (var m in matches)
            //{
            //    // Get the match attribute values
            //    string name = m.Attributes["PlaceName"].ToString();
            //    string address = m.Attributes["Place_addr"].ToString();
            //    string url = m.Attributes["URL"].ToString();

            //    // Create a graphic to represent this place, add the attribute values
            //    Graphic poi = new Graphic(m.DisplayLocation);
            //    poi.Attributes.Add("Address", address);
            //    poi.Attributes.Add("Name", name);
            //    poi.Attributes.Add("URL", url);

            //    // Add the place graphic to the collection
            //    placeGraphics.Add(poi);
            //}

            // ** end: create graphics
            #endregion

            return(placeGraphics);
        }
Example #35
0
    /// <summary>
    /// 奏でる
    /// </summary>
    public override bool Melody(ManageDungeon dun, PlayerCharacter player)
    {
        BaseCharacter[] targets;

        player.AttackInfo.Initialize();

        //音を鳴らす
        player.AttackInfo.AddVoice(VoiceInformation.VoiceType.Sing);

        switch (MType)
        {
        //放電
        case MelodyType.Electric:

            //サウンドを鳴らす
            player.AttackInfo.AddSound(SoundInformation.SoundType.ElectricMelody);

            const int ElectricDamage = 20;
            int       damage         = ElectricDamage + Mathf.FloorToInt(player.BaseAttack);

            //エフェクト
            player.AttackInfo.AddEffect(EffectSpark.CreateObject(player));

            //メッセージ
            player.AttackInfo.AddMessage(
                string.Format(CommonConst.Message.MelodySing, DisplayNameInMessage));

            //部屋の中のキャラクターを取得
            targets = dun.GetRoomCharacters(player);

            //全員にダメージ
            foreach (BaseCharacter c in targets)
            {
                AttackState atState = c.AddDamage(damage);

                //ダメージエフェクト
                EffectDamage d = EffectDamage.CreateObject(c);
                d.SetText(damage.ToString(), AttackState.Hit);
                player.AttackInfo.AddEffect(d);

                //ヒットメッセージ
                player.AttackInfo.AddMessage(
                    c.GetMessageAttackHit(damage));

                //対象が死亡したら
                if (atState == AttackState.Death)
                {
                    player.AttackInfo.AddKillList(c);

                    player.AttackInfo.AddMessage(
                        c.GetMessageDeath(c.HaveExperience));

                    player.Death(c, player.AttackInfo);
                }
            }


            break;

        //狂乱
        case MelodyType.Confusion:

            //サウンドを鳴らす
            player.AttackInfo.AddSound(SoundInformation.SoundType.Smoke);

            //メッセージ
            player.AttackInfo.AddMessage(
                string.Format(CommonConst.Message.MelodySing, DisplayNameInMessage));

            //部屋の中のキャラクターを取得
            targets = dun.GetRoomCharacters(player);

            //全員を混乱
            foreach (BaseCharacter c in targets)
            {
                //対象に混乱を付与
                int result = c.AddStateAbnormal((int)StateAbnormal.Confusion);
                //対象が混乱になったらメッセージを表示
                if (result != 0)
                {
                    player.AttackInfo.AddEffect(EffectSmoke.CreateObject(c));

                    player.AttackInfo.AddMessage(
                        CommonFunction.GetAbnormalMessage(StateAbnormal.Confusion, c));
                }
            }
            break;

        //まどろみ
        case MelodyType.Sleep:

            //サウンドを鳴らす
            player.AttackInfo.AddSound(SoundInformation.SoundType.Smoke);

            //メッセージ
            player.AttackInfo.AddMessage(
                string.Format(CommonConst.Message.MelodySing, DisplayNameInMessage));

            //部屋の中のキャラクターを取得
            targets = dun.GetRoomCharacters(player);

            //全員を睡眠
            foreach (BaseCharacter c in targets)
            {
                //対象に睡眠を付与
                int result = c.AddStateAbnormal((int)StateAbnormal.Sleep);
                //対象が睡眠になったらメッセージを表示
                if (result != 0)
                {
                    player.AttackInfo.AddEffect(EffectSmoke.CreateObject(c));

                    player.AttackInfo.AddMessage(
                        CommonFunction.GetAbnormalMessage(StateAbnormal.Sleep, c));
                }
            }
            break;

        //無秩序
        case MelodyType.Anarchy:

            //サウンドを鳴らす
            player.AttackInfo.AddSound(SoundInformation.SoundType.Smoke);

            //メッセージ
            player.AttackInfo.AddMessage(string.Format(CommonConst.Message.MelodySing, DisplayNameInMessage));

            //部屋の中のキャラクターを取得
            targets = dun.GetRoomCharacters(player);

            //全員をデコイ
            foreach (BaseCharacter c in targets)
            {
                //対象にデコイを付与
                int result = c.AddStateAbnormal((int)StateAbnormal.Decoy);
                //対象がデコイになったらメッセージを表示
                if (result != 0)
                {
                    player.AttackInfo.AddEffect(EffectSmoke.CreateObject(c));

                    player.AttackInfo.AddMessage(
                        CommonFunction.GetAbnormalMessage(StateAbnormal.Decoy, c));
                }
            }
            break;

        //薄ら日
        case MelodyType.Light:

            //エフェクト
            player.AttackInfo.AddEffect(EffectFlash.CreateObject());

            //サウンドを鳴らす
            player.AttackInfo.AddSound(SoundInformation.SoundType.Smoke);

            //メッセージ
            player.AttackInfo.AddMessage(string.Format(CommonConst.Message.MelodySing, DisplayNameInMessage));

            dun.IsVisible      = true;
            dun.IsEnemyVisible = true;
            dun.IsItemVisible  = true;
            dun.IsTrapVisible  = true;
            break;

        //角笛
        case MelodyType.Horn:

            //サウンドを鳴らす
            player.AttackInfo.AddSound(SoundInformation.SoundType.Summon);

            //エフェクトの発動
            player.AttackInfo.AddEffect(EffectSummon.CreateObject(player));

            int cnt = CommonFunction.ConvergenceRandom(3, 0.9f, 1.2f, 10);

            for (int i = 0; i < cnt; i++)
            {
                dun.SetUpCharacterMap();
                //敵の出現地点を取得
                MapPoint mp = dun.GetCharacterEmptyTarget(player.CurrentPoint);
                if (CommonFunction.IsNull(mp) == true)
                {
                    break;
                }

                int  enemytype           = TableEnemyMap.GetValue(dun.DungeonObjNo, DisplayInformation.Info.Floor);
                uint rand                = CommonFunction.GetRandomUInt32();
                BaseEnemyCharacter enemy = TableEnemyIncidence.GetEnemy(enemytype, rand, DisplayInformation.Info.Floor);

                enemy.SetCharacterDisplayObject(mp.X, mp.Y);
                dun.AddNewCharacter(enemy);
            }
            DisplayInformation.Info.AddMessage(
                CommonConst.Message.TrapSummon);

            break;

        // 忘却
        case MelodyType.Forget:

            //メッセージ
            player.AttackInfo.AddMessage(
                string.Format(CommonConst.Message.MelodySing, DisplayNameInMessage));

            //効果音
            player.AttackInfo.AddSound(SoundInformation.SoundType.Summon);

            if (dun.IsVisible == false)
            {
                for (int j = 1; j < dun.X - 1; j++)
                {
                    for (int i = 1; i < dun.Y - 1; i++)
                    {
                        dun.Dungeon.DungeonMap.Get(i, j).IsClear = false;
                    }
                }

                player.AttackInfo.AddMessage(CommonConst.Message.ForgetMap);

                player.AttackInfo.AddEffect(EffectSmoke.CreateObject(player));
            }

            break;

        //捨て置き
        case MelodyType.ThrowAway:

            //メッセージ
            player.AttackInfo.AddMessage(
                string.Format(CommonConst.Message.MelodySing, DisplayNameInMessage));

            player.AttackInfo.AddMessage(
                string.Format(CommonConst.Message.ThrowAway, player.DisplayNameInMessage));

            GameStateInformation.Info.IsThrowAway = true;

            break;
        }
        return(true);
    }
Example #36
0
        /// <summary>
        /// Runs a search and populates the map with results based on the provided information
        /// </summary>
        /// <param name="enteredText">Results to search for</param>
        /// <param name="locationText">Location around which to find results</param>
        /// <param name="restrictToExtent">If true, limits results to only those that are within the current extent</param>
        private async Task UpdateSearch(string enteredText, string locationText, bool restrictToExtent = false)
        {
            // Clear any existing markers
            _myMapView.GraphicsOverlays.Clear();

            // Return gracefully if the textbox is empty or the geocoder isn't ready
            if (string.IsNullOrWhiteSpace(enteredText) || _geocoder == null)
            {
                return;
            }

            // Create the geocode parameters
            GeocodeParameters parameters = new GeocodeParameters();

            // Get the MapPoint for the current search location
            MapPoint searchLocation = await GetSearchMapPoint(locationText);

            // Update the geocode parameters if the map point is not null
            if (searchLocation != null)
            {
                parameters.PreferredSearchLocation = searchLocation;
            }

            // Update the search area if desired
            if (restrictToExtent)
            {
                // Get the current map extent
                Geometry extent = _myMapView.VisibleArea;

                // Update the search parameters
                parameters.SearchArea = extent;
            }

            // Show the progress bar
            _myProgressBar.Visibility = Android.Views.ViewStates.Visible;

            // Get the location information
            IReadOnlyList <GeocodeResult> locations = await _geocoder.GeocodeAsync(enteredText, parameters);

            // Stop gracefully and show a message if the geocoder does not return a result
            if (locations.Count < 1)
            {
                _myProgressBar.Visibility = Android.Views.ViewStates.Gone; // 1. Hide the progress bar
                ShowStatusMessage("No results found");                     // 2. Show a message
                return;                                                    // 3. Stop
            }

            // Create the GraphicsOverlay so that results can be drawn on the map
            GraphicsOverlay resultOverlay = new GraphicsOverlay();

            // Add each address to the map
            foreach (GeocodeResult location in locations)
            {
                // Get the Graphic to display
                Graphic point = await GraphicForPoint(location.DisplayLocation);

                // Add the specific result data to the point
                point.Attributes["Match_Title"] = location.Label;

                // Get the address for the point
                IReadOnlyList <GeocodeResult> addresses = await _geocoder.ReverseGeocodeAsync(location.DisplayLocation);

                // Add the first suitable address if possible
                if (addresses.Count() > 0)
                {
                    point.Attributes["Match_Address"] = addresses.First().Label;
                }

                // Add the Graphic to the GraphicsOverlay
                resultOverlay.Graphics.Add(point);
            }

            // Hide the progress bar
            _myProgressBar.Visibility = Android.Views.ViewStates.Gone;

            // Add the GraphicsOverlay to the MapView
            _myMapView.GraphicsOverlays.Add(resultOverlay);

            // Create a viewpoint for the extent containing all graphics
            Viewpoint viewExtent = new Viewpoint(resultOverlay.Extent);

            // Update the map viewpoint
            _myMapView.SetViewpoint(viewExtent);
        }
Example #37
0
        // Asynchronously adjust the given viewpoint, taking into consideration elevation and KML altitude mode.
        private async Task <Viewpoint> GetAltitudeAdjustedViewpointAsync(KmlNode node, Viewpoint baseViewpoint)
        {
            // Get the altitude mode; assume clamp-to-ground if not specified.
            KmlAltitudeMode altMode = KmlAltitudeMode.ClampToGround;

            if (node.Viewpoint != null)
            {
                altMode = node.Viewpoint.AltitudeMode;
            }

            // If the altitude mode is Absolute, the base viewpoint doesn't need adjustment.
            if (altMode == KmlAltitudeMode.Absolute)
            {
                return(baseViewpoint);
            }

            double   altitude;
            Envelope lookAtExtent = baseViewpoint.TargetGeometry as Envelope;
            MapPoint lookAtPoint  = baseViewpoint.TargetGeometry as MapPoint;

            if (lookAtExtent != null)
            {
                // Get the altitude for the extent.
                try
                {
                    altitude = await _mySceneView.Scene.BaseSurface.GetElevationAsync(lookAtExtent.GetCenter());
                }
                catch (Exception)
                {
                    altitude = 0;
                }

                // Apply elevation adjustment to the geometry.
                Envelope target;
                if (altMode == KmlAltitudeMode.ClampToGround)
                {
                    target = new Envelope(
                        lookAtExtent.XMin, lookAtExtent.YMin,
                        lookAtExtent.XMax, lookAtExtent.YMax,
                        altitude, lookAtExtent.Depth + altitude,
                        lookAtExtent.SpatialReference);
                }
                else
                {
                    target = new Envelope(
                        lookAtExtent.XMin, lookAtExtent.YMin,
                        lookAtExtent.XMax, lookAtExtent.YMax,
                        lookAtExtent.ZMin + altitude, lookAtExtent.ZMax + altitude,
                        lookAtExtent.SpatialReference);
                }

                if (node.Viewpoint != null)
                {
                    // Return adjusted geometry with adjusted camera if a viewpoint was specified on the node.
                    return(new Viewpoint(target, baseViewpoint.Camera.Elevate(altitude)));
                }
                else
                {
                    // Return adjusted geometry.
                    return(new Viewpoint(target));
                }
            }
            else if (lookAtPoint != null)
            {
                // Get the altitude adjustment.
                try
                {
                    altitude = await _mySceneView.Scene.BaseSurface.GetElevationAsync(lookAtPoint);
                }
                catch (Exception)
                {
                    altitude = 0;
                }

                // Apply elevation adjustment to the geometry.
                MapPoint target;
                if (altMode == KmlAltitudeMode.ClampToGround)
                {
                    target = new MapPoint(lookAtPoint.X, lookAtPoint.Y, altitude, lookAtPoint.SpatialReference);
                }
                else
                {
                    target = new MapPoint(
                        lookAtPoint.X, lookAtPoint.Y, lookAtPoint.Z + altitude,
                        lookAtPoint.SpatialReference);
                }

                if (node.Viewpoint != null)
                {
                    // Return adjusted geometry with adjusted camera if a viewpoint was specified on the node.
                    return(new Viewpoint(target, baseViewpoint.Camera.Elevate(altitude)));
                }
                else
                {
                    // Google Earth defaults: 1000m away and 45-degree tilt.
                    return(new Viewpoint(target, new Camera(target, 1000, 0, 45, 0)));
                }
            }
            else
            {
                throw new InvalidOperationException("KmlNode has unexpected Geometry for its Extent: " +
                                                    baseViewpoint.TargetGeometry);
            }
        }
        private void Initialize()
        {
            // Create new Scene.
            Scene myScene = new Scene
            {
                // Set the Scene's basemap property.
                Basemap = Basemap.CreateImagery()
            };

            // Create a camera with coordinates showing layer data.
            Camera camera = new Camera(48.389124348393182, -4.4595173327138591, 140, 322, 74, 0);

            // Assign the Scene to the SceneView.
            MySceneView.Scene = myScene;

            // Create ElevationSource from elevation data Uri.
            ArcGISTiledElevationSource elevationSource = new ArcGISTiledElevationSource(
                new Uri("https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer"));

            // Create scene layer from the Brest, France scene server.
            var sceneLayer = new ArcGISSceneLayer(new Uri("https://tiles.arcgis.com/tiles/P3ePLMYs2RVChkJx/arcgis/rest/services/Buildings_Brest/SceneServer"));

            MySceneView.Scene.OperationalLayers.Add(sceneLayer);

            // Add elevationSource to BaseSurface's ElevationSources.
            MySceneView.Scene.BaseSurface.ElevationSources.Add(elevationSource);

            // Set view point of scene view using camera.
            MySceneView.SetViewpointCameraAsync(camera);

            // Create overlays with elevation modes.
            _drapedBillboardedOverlay = new GraphicsOverlay();
            _drapedBillboardedOverlay.SceneProperties.SurfacePlacement = SurfacePlacement.DrapedBillboarded;
            MySceneView.GraphicsOverlays.Add(_drapedBillboardedOverlay);

            _drapedFlatOverlay = new GraphicsOverlay();
            _drapedFlatOverlay.SceneProperties.SurfacePlacement = SurfacePlacement.DrapedFlat;

            GraphicsOverlay relativeToSceneOverlay = new GraphicsOverlay();

            relativeToSceneOverlay.SceneProperties.SurfacePlacement = SurfacePlacement.RelativeToScene;
            MySceneView.GraphicsOverlays.Add(relativeToSceneOverlay);

            GraphicsOverlay relativeToSurfaceOverlay = new GraphicsOverlay();

            relativeToSurfaceOverlay.SceneProperties.SurfacePlacement = SurfacePlacement.Relative;
            MySceneView.GraphicsOverlays.Add(relativeToSurfaceOverlay);

            GraphicsOverlay absoluteOverlay = new GraphicsOverlay();

            absoluteOverlay.SceneProperties.SurfacePlacement = SurfacePlacement.Absolute;
            MySceneView.GraphicsOverlays.Add(absoluteOverlay);

            // Create point for graphic location.
            MapPoint sceneRelatedPoint   = new MapPoint(-4.4610562, 48.3902727, 70, camera.Location.SpatialReference);
            MapPoint surfaceRelatedPoint = new MapPoint(-4.4609257, 48.3903965, 70, camera.Location.SpatialReference);

            // Create a red triangle symbol.
            var triangleSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Triangle, Color.FromArgb(255, 255, 0, 0), 10);

            // Create a text symbol for each elevation mode.
            TextSymbol drapedBillboardedText = new TextSymbol("DRAPED BILLBOARDED", Color.FromArgb(255, 0, 0, 255), 10,
                                                              Esri.ArcGISRuntime.Symbology.HorizontalAlignment.Center,
                                                              Esri.ArcGISRuntime.Symbology.VerticalAlignment.Middle);

            drapedBillboardedText.OffsetY += 20;

            TextSymbol drapedFlatText = new TextSymbol("DRAPED FLAT", Color.FromArgb(255, 0, 0, 255), 10,
                                                       Esri.ArcGISRuntime.Symbology.HorizontalAlignment.Center,
                                                       Esri.ArcGISRuntime.Symbology.VerticalAlignment.Middle);

            drapedFlatText.OffsetY += 20;

            TextSymbol relativeToSurfaceText = new TextSymbol("RELATIVE TO SURFACE", Color.FromArgb(255, 0, 0, 255), 10,
                                                              Esri.ArcGISRuntime.Symbology.HorizontalAlignment.Center,
                                                              Esri.ArcGISRuntime.Symbology.VerticalAlignment.Middle);

            relativeToSurfaceText.OffsetY += 20;

            TextSymbol relativeToSceneText = new TextSymbol("RELATIVE TO SCENE", Color.FromArgb(255, 0, 0, 255), 10,
                                                            Esri.ArcGISRuntime.Symbology.HorizontalAlignment.Center,
                                                            Esri.ArcGISRuntime.Symbology.VerticalAlignment.Middle);

            relativeToSceneText.OffsetY -= 20;

            TextSymbol absoluteText = new TextSymbol("ABSOLUTE", Color.FromArgb(255, 0, 0, 255), 10,
                                                     Esri.ArcGISRuntime.Symbology.HorizontalAlignment.Center,
                                                     Esri.ArcGISRuntime.Symbology.VerticalAlignment.Middle);

            absoluteText.OffsetY += 20;

            // Add the point graphic and text graphic to the corresponding graphics overlay.
            _drapedBillboardedOverlay.Graphics.Add(new Graphic(surfaceRelatedPoint, triangleSymbol));
            _drapedBillboardedOverlay.Graphics.Add(new Graphic(surfaceRelatedPoint, drapedBillboardedText));

            _drapedFlatOverlay.Graphics.Add(new Graphic(surfaceRelatedPoint, triangleSymbol));
            _drapedFlatOverlay.Graphics.Add(new Graphic(surfaceRelatedPoint, drapedFlatText));

            relativeToSceneOverlay.Graphics.Add(new Graphic(sceneRelatedPoint, triangleSymbol));
            relativeToSceneOverlay.Graphics.Add(new Graphic(sceneRelatedPoint, relativeToSceneText));

            relativeToSurfaceOverlay.Graphics.Add(new Graphic(surfaceRelatedPoint, triangleSymbol));
            relativeToSurfaceOverlay.Graphics.Add(new Graphic(surfaceRelatedPoint, relativeToSurfaceText));

            absoluteOverlay.Graphics.Add(new Graphic(surfaceRelatedPoint, triangleSymbol));
            absoluteOverlay.Graphics.Add(new Graphic(surfaceRelatedPoint, absoluteText));

            BillboardButton.Checked += BillboardedClick;
            FlatButton.Checked      += FlatClick;
        }
Example #39
0
 public Tremor(Fighter source, SpellLevelRecord level, MapPoint castPoint, bool criticalHit)
     : base(source, level, castPoint, criticalHit)
 {
 }
Example #40
0
        private async void CreateNewFeatureCollection()
        {
            // Create the schema for a points table (one text field to contain a name attribute)
            List <Field> pointFields = new List <Field>();
            Field        placeField  = new Field(FieldType.Text, "Place", "Place Name", 50);

            pointFields.Add(placeField);

            // Create the schema for a lines table (one text field to contain a name attribute)
            List <Field> lineFields    = new List <Field>();
            Field        boundaryField = new Field(FieldType.Text, "Boundary", "Boundary Name", 50);

            lineFields.Add(boundaryField);

            // Create the schema for a polygon table (one text field to contain a name attribute)
            List <Field> polyFields = new List <Field>();
            Field        areaField  = new Field(FieldType.Text, "AreaName", "Area Name", 50);

            polyFields.Add(areaField);

            // Instantiate FeatureCollectionTables with schema and geometry type
            FeatureCollectionTable pointsTable = new FeatureCollectionTable(pointFields, GeometryType.Point, SpatialReferences.Wgs84);
            FeatureCollectionTable linesTable  = new FeatureCollectionTable(lineFields, GeometryType.Polyline, SpatialReferences.Wgs84);
            FeatureCollectionTable polysTable  = new FeatureCollectionTable(polyFields, GeometryType.Polygon, SpatialReferences.Wgs84);

            // Set rendering for each table
            pointsTable.Renderer = CreateRenderer(GeometryType.Point);
            linesTable.Renderer  = CreateRenderer(GeometryType.Polyline);
            polysTable.Renderer  = CreateRenderer(GeometryType.Polygon);

            // Create a new point feature, provide geometry and attribute values
            Feature pointFeature = pointsTable.CreateFeature();

            pointFeature.SetAttributeValue(placeField, "Current location");
            MapPoint point1 = new MapPoint(-79.497238, 8.849289, SpatialReferences.Wgs84);

            pointFeature.Geometry = point1;

            // Create a new line feature, provide geometry and attribute values
            Feature lineFeature = linesTable.CreateFeature();

            lineFeature.SetAttributeValue(boundaryField, "AManAPlanACanalPanama");
            MapPoint point2 = new MapPoint(-80.035568, 9.432302, SpatialReferences.Wgs84);
            Polyline line   = new Polyline(new MapPoint[] { point1, point2 });

            lineFeature.Geometry = line;

            // Create a new polygon feature, provide geometry and attribute values
            Feature polyFeature = polysTable.CreateFeature();

            polyFeature.SetAttributeValue(areaField, "Restricted area");
            MapPoint point3 = new MapPoint(-79.337936, 8.638903, SpatialReferences.Wgs84);
            MapPoint point4 = new MapPoint(-79.11409, 8.895422, SpatialReferences.Wgs84);
            Polygon  poly   = new Polygon(new MapPoint[] { point1, point3, point4 });

            polyFeature.Geometry = poly;

            try
            {
                // Add the new features to the appropriate feature collection table
                await pointsTable.AddFeatureAsync(pointFeature);

                await linesTable.AddFeatureAsync(lineFeature);

                await polysTable.AddFeatureAsync(polyFeature);

                // Create a feature collection and add the feature collection tables
                FeatureCollection featuresCollection = new FeatureCollection();
                featuresCollection.Tables.Add(pointsTable);
                featuresCollection.Tables.Add(linesTable);
                featuresCollection.Tables.Add(polysTable);

                // Create a FeatureCollectionLayer
                FeatureCollectionLayer collectionLayer = new FeatureCollectionLayer(featuresCollection);

                // When the layer loads, zoom the map view to the extent of the feature collection
                await collectionLayer.LoadAsync();

                MyMapView.SetViewpoint(new Viewpoint(collectionLayer.FullExtent));

                // Add the layer to the Map's Operational Layers collection
                MyMapView.Map.OperationalLayers.Add(collectionLayer);
            }
            catch (Exception e)
            {
                await new MessageDialog(e.ToString(), "Error").ShowAsync();
            }
        }
Example #41
0
        private void Initialize()
        {
            try
            {
                // Define the Uri for the service feature table (US state polygons)
                var myServiceFeatureTable_Uri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/3");

                // Create a new service feature table from the Uri
                ServiceFeatureTable myServiceFeatureTable = new ServiceFeatureTable(myServiceFeatureTable_Uri);

                // Create a new feature layer from the service feature table
                FeatureLayer myFeatureLayer = new FeatureLayer(myServiceFeatureTable);

                // Set the rendering mode of the feature layer to be dynamic (needed for extrusion to work)
                myFeatureLayer.RenderingMode = FeatureRenderingMode.Dynamic;

                // Create a new simple line symbol for the feature layer
                SimpleLineSymbol mySimpleLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Black, 1);

                // Create a new simple fill symbol for the feature layer
                SimpleFillSymbol mysimpleFillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, Color.Blue, mySimpleLineSymbol);

                // Create a new simple renderer for the feature layer
                SimpleRenderer mySimpleRenderer = new SimpleRenderer(mysimpleFillSymbol);

                // Get the scene properties from the simple renderer
                RendererSceneProperties myRendererSceneProperties = mySimpleRenderer.SceneProperties;

                // Set the extrusion mode for the scene properties to be base height
                myRendererSceneProperties.ExtrusionMode = ExtrusionMode.BaseHeight;

                // Set the initial extrusion expression
                myRendererSceneProperties.ExtrusionExpression = "[POP2007] / 10";

                // Set the feature layer's renderer to the define simple renderer
                myFeatureLayer.Renderer = mySimpleRenderer;

                // Create a new scene with the topographic backdrop
                Scene myScene = new Scene(BasemapType.Topographic);

                // Set the scene view's scene to the newly create one
                _mySceneView.Scene = myScene;

                // Add the feature layer to the scene's operational layer collection
                myScene.OperationalLayers.Add(myFeatureLayer);

                // Create a new map point to define where to look on the scene view
                MapPoint myMapPoint = new MapPoint(-10974490, 4814376, 0, SpatialReferences.WebMercator);

                // Create a new orbit location camera controller using the map point and defined distance
                OrbitLocationCameraController myOrbitLocationCameraController = new OrbitLocationCameraController(myMapPoint, 20000000);

                // Set the scene view's camera controller to the orbit location camera controller
                _mySceneView.CameraController = myOrbitLocationCameraController;
            }
            catch (Exception ex)
            {
                // Something went wrong, display the error
                UIAlertController alert = UIAlertController.Create("Error", ex.Message, UIAlertControllerStyle.Alert);
                alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(alert, true, null);
            }
        }
Example #42
0
    public override void DoFixedUpdate()
    {
        if (_status != Status_Dead)
        {
            if (_gameMap.IsDeadMapPoint(_gameMap.GetMapPointOfWorldPosition(transform.position)) == true)
            {
                FalldownToDie();
                return;
            }
        }

        switch (_status)
        {
        case Status_Inactive:
            break;

        case Status_BounceUp:
        {
            Vector3 pos = transform.position;
            pos += _speed * Time.fixedDeltaTime;
            transform.position = pos;

            _timer -= Time.fixedDeltaTime;
            if (_timer < 0)
            {
                _speed.y = -0.5f;
                SetStatus(Status_FallDown);
            }
            break;
        }

        case Status_Run: {
            Vector3 pos = transform.position;
            pos += _speed * Time.fixedDeltaTime;

            int detectDir = MapElement.Dir_Right;
            if (_speed.x > 0)
            {
                detectDir = MapElement.Dir_Left;
            }

            MapElement detectElement = GetFrontMapElement(pos);
            if (detectElement != null)
            {
                if (detectElement.IsBlock(detectDir) != MapElement.Block_None)
                {
                    if (_speed.x < 0)
                    {
                        pos.x = _gameMap.GetWorldPositionByMapPoint(detectElement.x, detectElement.y).x + 1.0f;
                    }
                    else
                    {
                        pos.x = _gameMap.GetWorldPositionByMapPoint(detectElement.x, detectElement.y).x - 1.0f;
                    }
                    _speed.x *= -1;
                }
                else
                {
                    if (_speed.x < 0)
                    {
                        if (detectElement.type == MapElement.Type_WallSlope03Follow)
                        {
                            pos.x = Mathf.Round(pos.x) - 0.3f;
                            pos.y = Mathf.Round(pos.y) - 0.1f;
                            SetRunSlopeDown01(false);
                        }
                        else if (detectElement.type == MapElement.Type_WallSlope04)
                        {
                            pos.x = Mathf.Round(pos.x) - 0.2f;
                            pos.y = Mathf.Round(pos.y) - 0.2f;
                            SetRunSlopeDown02(false);
                        }
                    }
                    else if (_speed.x > 0)
                    {
                        if (detectElement.type == MapElement.Type_WallSlope01)
                        {
                            pos.x = Mathf.Round(pos.x) + 0.3f;
                            pos.y = Mathf.Round(pos.y) - 0.1f;
                            SetRunSlopeUp01(true);
                        }
                        else if (detectElement.type == MapElement.Type_WallSlope02)
                        {
                            pos.x = Mathf.Round(pos.x) + 0.2f;
                            pos.y = Mathf.Round(pos.y) - 0.2f;
                            SetRunSlopeUp02(true);
                        }
                    }
                }
            }
            else
            {
                detectElement = GetFootBottomMiddleMapElement(pos);
                bool isEmptyBelow = false;
                if (detectElement == null)
                {
                    isEmptyBelow = true;
                }
                else
                {
                    if (detectElement.type == MapElement.Type_WallSlope01Follow)
                    {
                        pos    = _gameMap.GetWorldPositionByMapPoint(detectElement.x, detectElement.y);
                        pos.x += 0.4f;
                        pos.y += 1.0f;
                        SetRunSlopeUp01(false);
                    }
                    else if (detectElement.type == MapElement.Type_WallSlope02)
                    {
                        pos    = _gameMap.GetWorldPositionByMapPoint(detectElement.x, detectElement.y);
                        pos.x += 0.4f;
                        pos.y += 1.0f;
                        SetRunSlopeUp02(false);
                    }
                    else if (detectElement.type == MapElement.Type_WallSlope03)
                    {
                        pos    = _gameMap.GetWorldPositionByMapPoint(detectElement.x, detectElement.y);
                        pos.x -= 0.4f;
                        pos.y += 1.0f;
                        SetRunSlopeDown01(true);
                    }
                    else if (detectElement.type == MapElement.Type_WallSlope04)
                    {
                        pos    = _gameMap.GetWorldPositionByMapPoint(detectElement.x, detectElement.y);
                        pos.x -= 0.4f;
                        pos.y += 1.0f;
                        SetRunSlopeDown02(true);
                    }
                    else if (detectElement.IsBlock(MapElement.Dir_Up) == MapElement.Block_None)
                    {
                        isEmptyBelow = true;
                    }
                }

                if (isEmptyBelow == true)
                {
                    _speed.y = -0.5f;
                    SetStatus(Status_FallDown);
                }
            }

            transform.position = pos;
            break;
        }

        case Status_RunSlope01:
        case Status_RunSlope02:
        case Status_RunSlope03:
        case Status_RunSlope04: {
            Vector3 pos = transform.position;
            pos += _speed * Time.fixedDeltaTime;
            float angle = (45 - transform.localEulerAngles.z) * 3.1415927f / 180;

            Vector3 detectPos = pos;

            if (_speed.x < 0)
            {
                detectPos.x -= ((_width / 2 + _detectDelta) * 1.414f * Mathf.Sin(angle));
                detectPos.y -= (_height / 2 - _detectDelta) * 1.414f * Mathf.Cos(angle);
            }
            else
            {
                detectPos.x += ((_width / 2 + _detectDelta) * 1.414f * Mathf.Cos(angle));
                detectPos.y -= (_height / 2 - _detectDelta) * 1.414f * Mathf.Sin(angle);
            }

            MapPoint   detectMapPoint = _gameMap.GetMapPointOfWorldPosition(detectPos);
            MapElement detectElement  = _gameMap.GetMapElementByMapPoint(detectMapPoint.x, detectMapPoint.y);

            if (detectElement != null)
            {
                if ((((_status == Status_RunSlope01) || (_status == Status_RunSlope02)) && (_speed.x < 0)) || (((_status == Status_RunSlope03) || (_status == Status_RunSlope04)) && (_speed.x > 0)))
                {
                    if ((detectElement.type != MapElement.Type_WallSlope01) && (detectElement.type != MapElement.Type_WallSlope01Follow) && (detectElement.type != MapElement.Type_WallSlope02) &&
                        (detectElement.type != MapElement.Type_WallSlope03) && (detectElement.type != MapElement.Type_WallSlope03Follow) && (detectElement.type != MapElement.Type_WallSlope04) &&
                        (detectElement.type != MapElement.Type_WallSlopeBottom))
                    {
                        pos = SetSlopeToRunDown(detectMapPoint);
                    }
                }
            }
            detectPos = pos;

            if (_speed.x < 0)
            {
                detectPos.x -= ((_width / 2 + _detectDelta) * 1.414f * Mathf.Sin(angle));
                detectPos.y -= ((_height / 2 + _detectDelta) * 1.414f * Mathf.Cos(angle) + _detectDelta);
            }
            else
            {
                detectPos.x += ((_width / 2 + _detectDelta) * 1.414f * Mathf.Cos(angle));
                detectPos.y -= ((_height / 2 + _detectDelta) * 1.414f * Mathf.Sin(angle) + _detectDelta);
            }

            detectMapPoint = _gameMap.GetMapPointOfWorldPosition(detectPos);
            detectElement  = _gameMap.GetMapElementByMapPoint(detectMapPoint.x, detectMapPoint.y);

            if (detectElement == null)
            {
                pos = SetSlopeToRunUp(detectMapPoint);
            }

            transform.position = pos;
            break;
        }

        case Status_FallDown:
        {
            Vector3 pos = transform.position;
            pos += _speed * Time.fixedDeltaTime;

            _speed.y += Gravity * Time.fixedDeltaTime;

            MapElement detectElement = GetFrontTopMapElement(pos);

            bool isBlocked = false;
            int  detectDir = MapElement.Dir_Right;
            if (_speed.x > 0)
            {
                detectDir = MapElement.Dir_Left;
            }

            if (detectElement != null)
            {
                if (detectElement.IsBlock(detectDir) != MapElement.Block_None)
                {
                    if (_speed.x < 0)
                    {
                        pos.x = _gameMap.GetWorldPositionByMapPoint(detectElement.x, detectElement.y).x + 1.0f;
                    }
                    else
                    {
                        pos.x = _gameMap.GetWorldPositionByMapPoint(detectElement.x, detectElement.y).x - 1.0f;
                    }
                    _speed.x *= -1;
                    isBlocked = true;
                }
            }

            if (isBlocked == false)
            {
                detectElement = GetFrontMapElement(pos);
                if (detectElement != null)
                {
                    if (detectElement.IsBlock(detectDir) != MapElement.Block_None)
                    {
                        if (_speed.x < 0)
                        {
                            pos.x = _gameMap.GetWorldPositionByMapPoint(detectElement.x, detectElement.y).x + 1.0f;
                        }
                        else
                        {
                            pos.x = _gameMap.GetWorldPositionByMapPoint(detectElement.x, detectElement.y).x - 1.0f;
                        }
                        _speed.x *= -1;
                        isBlocked = true;
                    }
                }
            }

            bool    isMoveForward = _speed.x > 0;
            Vector3 detectPos     = pos;
            detectPos.y -= (_height / 2 + _detectDelta);

            MapPoint detectMapPoint = _gameMap.GetMapPointOfWorldPosition(detectPos);

            detectElement = _gameMap.GetMapElementByMapPoint(detectMapPoint.x, detectMapPoint.y);
            if (detectElement != null)
            {
                // 下面有障碍,判断是不是落在斜坡上
                if ((detectElement.type == MapElement.Type_WallSlope01) || (detectElement.type == MapElement.Type_WallSlope01Follow))
                {
                    Vector3 deltaPos = pos;
                    deltaPos.x += 0.2f;
                    deltaPos.x  = deltaPos.x - (int)deltaPos.x;
                    if (detectElement.type == MapElement.Type_WallSlope01)
                    {
                        deltaPos.y = deltaPos.x / 2;
                    }
                    else
                    {
                        Debug.Log("Add 0.5.");
                        deltaPos.y = deltaPos.x / 2 + 0.5f;
                    }
                    deltaPos.x += detectElement.transform.position.x - 0.5f;
                    deltaPos.y += detectElement.transform.position.y - 0.5f;

                    float angle = (45 - Slope01Angle) * 3.1415927f / 180;
                    if (isMoveForward)
                    {
                        pos.x = deltaPos.x - 0.707f * Mathf.Cos(angle);
                        pos.y = deltaPos.y + 0.707f * Mathf.Sin(angle);
                        SetRunSlopeUp01(isMoveForward);
                    }
                    else
                    {
                        // 向后走,前角在低处
                        pos.x = deltaPos.x + 0.707f * Mathf.Sin(angle);
                        pos.y = deltaPos.y + 0.707f * Mathf.Cos(angle);
                        SetRunSlopeUp01(isMoveForward);
                    }
                }
                else if (detectElement.type == MapElement.Type_WallSlope02)
                {
                    Vector3 deltaPos = pos;
                    deltaPos.x += 0.2f;
                    deltaPos.x  = deltaPos.x - (int)deltaPos.x;
                    deltaPos.y  = deltaPos.x;

                    deltaPos.x += detectElement.transform.position.x - 0.5f;
                    deltaPos.y += detectElement.transform.position.y - 0.5f;


                    float angle = (45 - Slope02Angle) * 3.1415927f / 180;
                    if (isMoveForward)
                    {
                        pos.x = deltaPos.x - 0.707f * Mathf.Cos(angle);
                        pos.y = deltaPos.y + 0.707f * Mathf.Sin(angle);
                        SetRunSlopeUp02(isMoveForward);
                    }
                    else
                    {
                        // 向后走,前角在低处
                        pos.x = deltaPos.x + 0.707f * Mathf.Sin(angle);
                        pos.y = deltaPos.y + 0.707f * Mathf.Cos(angle);
                        SetRunSlopeUp02(isMoveForward);
                    }
                }
                else if ((detectElement.type == MapElement.Type_WallSlope03) || (detectElement.type == MapElement.Type_WallSlope03Follow))
                {
                    // 碰到了斜坡
                    Vector3 deltaPos = pos;
                    deltaPos.x += 0.5f;
                    deltaPos.x  = deltaPos.x - (int)deltaPos.x;
                    if (detectElement.type == MapElement.Type_WallSlope03)
                    {
                        deltaPos.y = deltaPos.x / 2;
                    }
                    else
                    {
                        deltaPos.y = deltaPos.x / 2 + 0.5f;
                    }
                    deltaPos.x += detectElement.transform.position.x - 0.5f;
                    deltaPos.y  = detectElement.transform.position.y + 0.5f - deltaPos.y;

                    float angle = (Slope01Angle - 315) * 3.1415927f / 180;
                    if (isMoveForward)
                    {
                        pos.x = deltaPos.x - 0.707f * Mathf.Cos(angle);
                        pos.y = deltaPos.y + 0.707f * Mathf.Sin(angle);
                        SetRunSlopeDown01(isMoveForward);
                    }
                    else
                    {
                        // 向后走,前角在低处
                        pos.x = deltaPos.x + 0.707f * Mathf.Sin(angle);
                        pos.y = deltaPos.y + 0.707f * Mathf.Cos(angle);
                        SetRunSlopeDown01(isMoveForward);
                    }
                }
                else if (detectElement.type == MapElement.Type_WallSlope04)
                {
                    // 碰到了斜坡
                    Vector3 deltaPos = pos;
                    deltaPos.x += 0.4f;
                    deltaPos.x  = deltaPos.x - (int)deltaPos.x;
                    deltaPos.y  = deltaPos.x;

                    deltaPos.x += detectElement.transform.position.x - 0.5f;
                    deltaPos.y  = detectElement.transform.position.y + 0.5f - deltaPos.y;


                    float angle = (Slope02Angle - 315) * 3.1415927f / 180;
                    if (isMoveForward)
                    {
                        pos.x = deltaPos.x - 0.707f * Mathf.Cos(angle);
                        pos.y = deltaPos.y + 0.707f * Mathf.Sin(angle);
                        SetRunSlopeDown02(isMoveForward);
                    }
                    else
                    {
                        // 向后走,前角在低处
                        pos.x = deltaPos.x + 0.707f * Mathf.Sin(angle);
                        pos.y = deltaPos.y + 0.707f * Mathf.Cos(angle);
                        SetRunSlopeDown02(isMoveForward);
                    }
                }
                else if (detectElement.IsBlock(MapElement.Dir_Up) != MapElement.Block_None)
                {
                    _speed.y = 0;
                    pos.y    = detectElement.transform.position.y + 0.5f + _height / 2;
                    SetStatus(Status_Run);

                    if (this is Mushroom)
                    {
                        _speed.x = ActorController.instance.ActorSpeedX;
                    }
                }
            }

            transform.position = pos;
            break;
        }

        case Status_FlyToActor:
        {
            DoFixedUpdateFlyToActor();
            break;
        }
        }
    }
Example #43
0
        private void Initialize()
        {
            // Create a new Map.
            Map myMap = new Map();

            // Create the URL for the tiled layer.
            Uri tiledLayerUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer");

            // Create a tiled layer from the URL
            ArcGISTiledLayer tiledLayer = new ArcGISTiledLayer(tiledLayerUri)
            {
                Name = "Tiled Layer"
            };

            // Add the tiled layer to map.
            myMap.OperationalLayers.Add(tiledLayer);

            // Create the URL for the ArcGISMapImage layer.
            Uri imageLayerUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer");

            // Create ArcGISMapImage layer using a URL.
            ArcGISMapImageLayer imageLayer = new ArcGISMapImageLayer(imageLayerUri)
            {
                Name = "Image Layer",
                // Set the visible scale range for the image layer.
                MinScale = 40000000,
                MaxScale = 2000000
            };

            // Add the image layer to map.
            myMap.OperationalLayers.Add(imageLayer);

            // Create Uri for feature layer.
            Uri featureLayerUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Recreation/FeatureServer/0");

            // Create a feature layer using URL.
            FeatureLayer myFeatureLayer = new FeatureLayer(featureLayerUri)
            {
                Name = "Feature Layer"
            };

            // Add the feature layer to map.
            myMap.OperationalLayers.Add(myFeatureLayer);

            // Create a point the map should zoom to.
            MapPoint mapPoint = new MapPoint(-11000000, 4500000, SpatialReferences.WebMercator);

            // Set the initial viewpoint for map.
            myMap.InitialViewpoint = new Viewpoint(mapPoint, 50000000);

            // Initialize the model list with unknown status for each layer.
            foreach (Layer layer in myMap.OperationalLayers)
            {
                _layerStatusModels.Add(new LayerStatusModel(layer.Name, "Unknown"));
            }

            // Create the table view source and pass the list of models to it.
            _tableView.Source = new LayerViewStatusTableSource(_layerStatusModels);

            _myMapView.LayerViewStateChanged += OnLayerViewStateChanged;

            // Provide used Map to the MapView.
            _myMapView.Map = myMap;
        }
Example #44
0
    public bool Invocate(ManageDungeon dun)
    {
        if (IsInvocation == false)
        {
            return(false);
        }
        IsActive     = true;
        IsInvocation = false;
        int bresult;

        //オプションによるトラップ回避
        float t = 0;

        foreach (BaseOption o in Target.Options)
        {
            t += o.DexTrap();
        }

        if (CommonFunction.IsRandom(t) == true)
        {
            DisplayInformation.Info.AddMessage(CommonConst.Message.DexTrap);
            Target = null;
            return(false);
        }

        //スコア値の更新
        DungeonHistoryInformation.Info.iTrapInvokeCount++;

        //サウンドを鳴らす
        if (Target.Type == ObjectType.Player)
        {
            VoiceInformation.Voice.Play(PlayerInformation.Info.PType, VoiceInformation.Voice.PlayRandomDefence());
        }

        bool result = false;

        //効果発動
        switch (TType)
        {
        case TrapType.Bomb:

            //サウンドを鳴らす
            SoundInformation.Sound.Play(SoundInformation.SoundType.Bomb);

            //エフェクトの発動
            EffectBigBang.CreateObject(this).Play();

            //ダメージ処理
            int         damage  = Mathf.CeilToInt(Target.CurrentHp / PerPlayerDamage);
            AttackState atState = Target.AddDamage(damage);

            //プレイヤーが死亡したら
            if (atState == AttackState.Death)
            {
                DisplayInformation.Info.AddMessage(
                    Target.GetMessageDeath(Target.HaveExperience));

                ScoreInformation.Info.CauseDeath =
                    string.Format(CommonConst.DeathMessage.Trap, DisplayNameNormal);
                ScoreInformation.Info.CauseDeathType = DeathCouseType.Trap;

                Target.Death();
                Target.DeathAction(dun);
            }


            //ダメージエフェクト
            EffectDamage d = EffectDamage.CreateObject(Target);
            d.SetText(damage.ToString(), AttackState.Hit);
            d.Play();

            //ヒットメッセージ
            DisplayInformation.Info.AddMessage(
                Target.GetMessageAttackHit(damage));

            //周辺キャラのダメージ処理
            dun.SetUpCharacterMap();
            List <BaseCharacter> list = dun.GetNearCharacters(this.CurrentPoint, 1);
            foreach (BaseCharacter c in list)
            {
                atState = c.AddDamage(CommonNumber);
                EffectDamage d2 = EffectDamage.CreateObject(c);
                d2.SetText(CommonNumber.ToString(), AttackState.Hit);
                d2.Play();

                //対象が死亡したら
                if (atState == AttackState.Death)
                {
                    DisplayInformation.Info.AddMessage(
                        string.Format(CommonConst.Message.DeathCommon, c.DisplayNameInMessage));

                    c.Death();
                    c.DeathAction(dun);
                }
            }
            result = true;
            break;

        case TrapType.ColorMonitor:

            //サウンドを鳴らす
            SoundInformation.Sound.Play(SoundInformation.SoundType.Smoke);

            //エフェクトの発動
            EffectColorMonitor.CreateObject(this).Play();

            //効果
            bresult = Target.AddStateAbnormal((int)StateAbnormal.StiffShoulder);
            //対象が異常になったらメッセージを表示
            if (bresult != 0)
            {
                DisplayInformation.Info.AddMessage(
                    CommonFunction.GetAbnormalMessage(StateAbnormal.StiffShoulder, Target));
            }
            result = true;
            break;

        case TrapType.Cyclone:

            //サウンドを鳴らす
            SoundInformation.Sound.Play(SoundInformation.SoundType.Cyclone);

            //エフェクトの発動
            EffectCyclone.CreateObject(Target).Play();

            //メッセージの出力
            DisplayInformation.Info.AddMessage(
                string.Format(CommonConst.Message.TrapCyclone2, Target.DisplayNameInMessage));

            //効果

            result = true;
            break;

        case TrapType.Electric:

            //サウンドを鳴らす
            SoundInformation.Sound.Play(SoundInformation.SoundType.ElectricTrap);

            //エフェクトの発動
            EffectThunder.CreateObject(Target).Play();

            BaseItem[] equips = PlayerCharacter.ItemList.FindAll(i => i.IsEquip == true).ToArray();

            if (equips.Length > 0)
            {
                foreach (BaseItem i in equips)
                {
                    i.ForceRemoveEquip(Target);
                }

                DisplayInformation.Info.AddMessage(
                    string.Format(CommonConst.Message.TrapEquipRemove, Target.DisplayNameInMessage));
            }

            result = true;
            break;

        case TrapType.Mud:

            //サウンドを鳴らす
            SoundInformation.Sound.Play(SoundInformation.SoundType.Smoke);

            //エフェクトの発動
            EffectBadSmoke.CreateObject(Target).Play();

            //効果
            bresult = Target.AddStateAbnormal((int)StateAbnormal.Slow);
            //対象が異常になったらメッセージを表示
            if (bresult != 0)
            {
                DisplayInformation.Info.AddMessage(
                    CommonFunction.GetAbnormalMessage(StateAbnormal.Slow, Target));
            }
            result = true;
            break;

        case TrapType.Palalysis:

            //サウンドを鳴らす
            SoundInformation.Sound.Play(SoundInformation.SoundType.Smoke);

            //エフェクトの発動
            EffectBadSmoke.CreateObject(Target).Play();

            //効果
            bresult = Target.AddStateAbnormal((int)StateAbnormal.Palalysis);
            //対象が異常になったらメッセージを表示
            if (bresult != 0)
            {
                DisplayInformation.Info.AddMessage(
                    CommonFunction.GetAbnormalMessage(StateAbnormal.Palalysis, Target));
            }
            result = true;
            break;

        case TrapType.Photo:
            if (Target.Type == ObjectType.Player)
            {
                //サウンドを鳴らす
                SoundInformation.Sound.Play(SoundInformation.SoundType.Smoke);

                //エフェクトの発動
                EffectBadSmoke.CreateObject(Target).Play();

                //メッセージの出力
                DisplayInformation.Info.AddMessage(
                    string.Format(CommonConst.Message.TrapCroquette2, Target.DisplayNameInMessage));

                ((PlayerCharacter)Target).ReduceSatiety(CommonNumber);
                result = true;
            }
            break;

        case TrapType.Poison:

            //サウンドを鳴らす
            SoundInformation.Sound.Play(SoundInformation.SoundType.Smoke);

            //エフェクトの発動
            EffectBadSmoke.CreateObject(Target).Play();

            //効果
            bresult = Target.AddStateAbnormal((int)StateAbnormal.Poison);
            //対象が異常になったらメッセージを表示
            if (bresult != 0)
            {
                DisplayInformation.Info.AddMessage(
                    CommonFunction.GetAbnormalMessage(StateAbnormal.Poison, Target));
            }

            result = true;
            break;

        case TrapType.DeadlyPoison:

            //サウンドを鳴らす
            SoundInformation.Sound.Play(SoundInformation.SoundType.Smoke);

            //エフェクトの発動
            EffectBadSmoke.CreateObject(Target).Play();

            //効果
            bresult = Target.AddStateAbnormal((int)StateAbnormal.DeadlyPoison);
            //対象が異常になったらメッセージを表示
            if (bresult != 0)
            {
                DisplayInformation.Info.AddMessage(
                    CommonFunction.GetAbnormalMessage(StateAbnormal.DeadlyPoison, Target));
            }

            result = true;
            break;

        case TrapType.Rotation:

            //サウンドを鳴らす
            SoundInformation.Sound.Play(SoundInformation.SoundType.Rotation);

            //エフェクトの発動
            EffectRotation.CreateObject(Target).Play();

            //効果
            bresult = Target.AddStateAbnormal((int)StateAbnormal.Confusion);
            //対象が異常になったらメッセージを表示
            if (bresult != 0)
            {
                EffectSmoke.CreateObject(Target);
                DisplayInformation.Info.AddMessage(
                    CommonFunction.GetAbnormalMessage(StateAbnormal.Confusion, Target));
            }


            result = true;
            break;

        case TrapType.SandStorm:

            //サウンドを鳴らす
            SoundInformation.Sound.Play(SoundInformation.SoundType.Cyclone);

            //エフェクトの発動
            EffectSandStorm.CreateObject(Target).Play();

            //効果
            bresult = Target.AddStateAbnormal((int)StateAbnormal.Dark);
            //対象が異常になったらメッセージを表示
            if (bresult != 0)
            {
                DisplayInformation.Info.AddMessage(
                    CommonFunction.GetAbnormalMessage(StateAbnormal.Dark, Target));
            }
            result = true;
            break;

        case TrapType.Song:

            //サウンドを鳴らす
            SoundInformation.Sound.Play(SoundInformation.SoundType.Smoke);

            //エフェクトの発動
            EffectBadSmoke.CreateObject(Target).Play();

            //効果
            bresult = Target.AddStateAbnormal((int)StateAbnormal.Sleep);
            //対象が異常になったらメッセージを表示
            if (bresult != 0)
            {
                DisplayInformation.Info.AddMessage(
                    CommonFunction.GetAbnormalMessage(StateAbnormal.Sleep, Target));
            }
            result = true;
            break;

        case TrapType.Summon:

            //サウンドを鳴らす
            SoundInformation.Sound.Play(SoundInformation.SoundType.Summon);

            //エフェクトの発動
            EffectSummon.CreateObject(Target).Play();

            int cnt = CommonFunction.ConvergenceRandom(CountStart, ProbStart, ProbReduce);

            for (int i = 0; i < cnt; i++)
            {
                dun.SetUpCharacterMap();
                //敵の出現地点を取得
                MapPoint mp = dun.GetCharacterEmptyTarget(Target.CurrentPoint);
                if (CommonFunction.IsNull(mp) == true)
                {
                    break;
                }

                int  enemytype           = TableEnemyMap.GetValue(dun.DungeonObjNo, DisplayInformation.Info.Floor);
                uint rand                = CommonFunction.GetRandomUInt32();
                BaseEnemyCharacter enemy = TableEnemyIncidence.GetEnemy(enemytype, rand, DisplayInformation.Info.Floor);

                enemy.SetCharacterDisplayObject(mp.X, mp.Y);
                dun.AddNewCharacter(enemy);
            }
            DisplayInformation.Info.AddMessage(
                CommonConst.Message.TrapSummon);

            result = true;
            break;

        case TrapType.TheFly:

            if (Target.Type == ObjectType.Player)
            {
                //サウンドを鳴らす
                SoundInformation.Sound.Play(SoundInformation.SoundType.Smoke);

                //エフェクトの発動
                EffectBadSmoke.CreateObject(Target).Play();

                BaseItem[] foods = PlayerCharacter.ItemList.FindAll(i => i.IType == ItemType.Food).ToArray();

                if (foods.Length > 0)
                {
                    foreach (BaseItem i in foods)
                    {
                        PlayerCharacter.RemoveItem(i);
                        ((PlayerCharacter)Target).AddItem(TableFood.GetItem(CommonConst.ObjNo.FlyCroquette), i.SortNo);
                    }

                    //メッセージの出力
                    DisplayInformation.Info.AddMessage(
                        string.Format(CommonConst.Message.TrapFly2));
                }

                result = true;
            }
            break;

        case TrapType.WaterBucket:

            //サウンドを鳴らす
            SoundInformation.Sound.Play(SoundInformation.SoundType.BucketFall);

            //エフェクトの発動
            EffectWaterBucket.CreateObject(Target).Play();

            //効果
            bresult = Target.AddStateAbnormal((int)StateAbnormal.Reticent);
            //対象が異常になったらメッセージを表示
            if (bresult != 0)
            {
                DisplayInformation.Info.AddMessage(
                    CommonFunction.GetAbnormalMessage(StateAbnormal.Reticent, Target));
            }

            result = true;
            break;

        //花粉
        case TrapType.Pollen:

            //サウンドを鳴らす
            SoundInformation.Sound.Play(SoundInformation.SoundType.Smoke);

            //エフェクトの発動
            EffectSmoke d3 = EffectSmoke.CreateObject(Target);
            d3.SetColor(Color.yellow);
            d3.Play();

            //力減少
            Target.ReducePower((ushort)CommonNumber);

            //メッセージの出力
            DisplayInformation.Info.AddMessage(
                string.Format(CommonConst.Message.TrapPllen2, Target.DisplayNameInMessage));

            result = true;
            break;

        case TrapType.Ember:

            //ダメージ処理
            int damage2 = CommonNumber;

            //通常ダメージの場合
            if (CommonFunction.HasOptionType(this.Options, OptionType.ReverceDamage) == false)
            {
                AttackState atState2 = Target.AddDamage(damage2);

                //ダメージエフェクト
                EffectDamage d4 = EffectDamage.CreateObject(Target);
                d4.SetText(damage2.ToString(), AttackState.Hit);
                d4.Play();

                DisplayInformation.Info.AddMessage(
                    string.Format(CommonConst.Message.TrapDamage, Target.DisplayNameInMessage, this.DisplayNameInMessage, damage2));

                //対象が死亡したら
                if (atState2 == AttackState.Death)
                {
                    DisplayInformation.Info.AddMessage(
                        Target.GetMessageDeath(Target.HaveExperience));

                    if (Target.Type == ObjectType.Player)
                    {
                        ScoreInformation.Info.CauseDeath =
                            string.Format(CommonConst.DeathMessage.Trap, DisplayNameNormal);
                        ScoreInformation.Info.CauseDeathType = DeathCouseType.Trap;
                    }
                    Target.Death();
                    Target.DeathAction(dun);
                }
            }
            //反転回復の場合
            else
            {
                Target.RecoverHp(damage2);

                //ダメージエフェクト
                EffectDamage d4 = EffectDamage.CreateObject(Target);
                d4.SetText(damage2.ToString(), AttackState.Heal);
                d4.Play();


                DisplayInformation.Info.AddMessage(
                    string.Format(CommonConst.Message.TrapRecover, Target.DisplayNameInMessage, this.DisplayNameInMessage, damage2));
            }
            break;
        }
        Target = null;

        return(result);
    }
Example #45
0
 /// <summary>
 /// Точка расположения маркера.
 /// </summary>
 /// <param name="point">Точка расположения.</param>
 /// <returns></returns>
 public Marker SetPoint(MapPoint point)
 {
     Point = point;
     return(this);
 }
Example #46
0
 public Task Locate(double scale, MapPoint centerPoint)
 {
     this.Scale  = scale;
     this.Center = centerPoint;
     return(RefreshMap());
 }
        // Illustrates creating a feature in a File GDB.
        private static async Task FileGeodatabaseWorkFlow()
        {
            using (Geodatabase fileGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb"))))
                using (FeatureClass featureClass = fileGeodatabase.OpenDataset <FeatureClass>("PollingPlace"))
                {
                    RowBuffer rowBuffer = null;
                    Feature   feature   = null;

                    try
                    {
                        EditOperation editOperation = new EditOperation();
                        editOperation.Callback(context =>
                        {
                            FeatureClassDefinition featureClassDefinition = featureClass.GetDefinition();

                            int nameIndex = featureClassDefinition.FindField("NAME");
                            rowBuffer     = featureClass.CreateRowBuffer();

                            // Either the field index or the field name can be used in the indexer.
                            rowBuffer[nameIndex]   = "New School";
                            rowBuffer["POLLINGID"] = "260";
                            rowBuffer["FULLADD"]   = "100 New Street";
                            rowBuffer["CITY"]      = "Naperville";
                            rowBuffer["STATE"]     = "IL";
                            rowBuffer["OPERHOURS"] = "Yes";
                            rowBuffer["HANDICAP"]  = "6.00am=7.00pm";
                            rowBuffer["NEXTELECT"] = "11/6/2012";
                            rowBuffer["REGDATE"]   = "8/6/2012";
                            rowBuffer["PHONE"]     = "815-740-4782";
                            rowBuffer["EMAIL"]     = "*****@*****.**";

                            rowBuffer[featureClassDefinition.GetShapeField()] = new MapPointBuilder(1028367, 1809789).ToGeometry();

                            feature = featureClass.CreateRow(rowBuffer);

                            //To Indicate that the Map has to draw this feature and/or the attribute table to be updated
                            context.Invalidate(feature);

                            // Do some other processing with the newly-created feature.
                        }, featureClass);

                        bool editResult = editOperation.Execute();

                        // At this point the changes are visible in the process, but not persisted/visible outside.
                        long     objectID = feature.GetObjectID();
                        MapPoint mapPoint = feature.GetShape() as MapPoint;

                        // If the table is non-versioned this is a no-op. If it is versioned, we need the Save to be done for the edits to be persisted.
                        bool saveResult = await Project.Current.SaveEditsAsync();
                    }
                    catch (GeodatabaseException exObj)
                    {
                        Console.WriteLine(exObj);
                        throw;
                    }
                    finally
                    {
                        if (rowBuffer != null)
                        {
                            rowBuffer.Dispose();
                        }

                        if (feature != null)
                        {
                            feature.Dispose();
                        }
                    }
                }
        }
Example #48
0
        private async void Initialize()
        {
            // Create the scene with an imagery basemap.
            MySceneView.Scene = new Scene(Basemap.CreateImagery());

            // Add the elevation surface.
            ArcGISTiledElevationSource tiledElevationSource = new ArcGISTiledElevationSource(_elevationUri);
            Surface baseSurface = new Surface
            {
                ElevationSources = { tiledElevationSource }
            };

            MySceneView.Scene.BaseSurface = baseSurface;

            // Add buildings.
            ArcGISSceneLayer sceneLayer = new ArcGISSceneLayer(_buildingsUri);

            MySceneView.Scene.OperationalLayers.Add(sceneLayer);

            // Configure graphics overlay for the tank and add the overlay to the SceneView.
            _tankOverlay.SceneProperties.SurfacePlacement = SurfacePlacement.Relative;
            MySceneView.GraphicsOverlays.Add(_tankOverlay);

            // Configure heading expression for tank; this will allow the
            //     viewshed to update automatically based on the tank's position.
            SimpleRenderer renderer3D = new SimpleRenderer();

            renderer3D.SceneProperties.HeadingExpression = "[HEADING]";
            _tankOverlay.Renderer = renderer3D;

            try
            {
                // Create the tank graphic - get the model path.
                string modelPath = GetModelPath();
                // - Create the symbol and make it 10x larger (to be the right size relative to the scene).
                ModelSceneSymbol tankSymbol = await ModelSceneSymbol.CreateAsync(new Uri(modelPath), 10);

                // - Adjust the position.
                tankSymbol.Heading = 90;
                // - The tank will be positioned relative to the scene surface by its bottom.
                //       This ensures that the tank is on the ground rather than partially under it.
                tankSymbol.AnchorPosition = SceneSymbolAnchorPosition.Bottom;
                // - Create the graphic.
                _tank = new Graphic(new MapPoint(28.047199, -26.189105, SpatialReferences.Wgs84), tankSymbol);
                // - Update the heading.
                _tank.Attributes["HEADING"] = 0.0;
                // - Add the graphic to the overlay.
                _tankOverlay.Graphics.Add(_tank);

                // Create a viewshed for the tank.
                GeoElementViewshed geoViewshed = new GeoElementViewshed(
                    geoElement: _tank,
                    horizontalAngle: 90.0,
                    verticalAngle: 40.0,
                    minDistance: 0.1,
                    maxDistance: 250.0,
                    headingOffset: 0.0,
                    pitchOffset: 0.0)
                {
                    // Offset viewshed observer location to top of tank.
                    OffsetZ = 3.0
                };

                // Create the analysis overlay and add to the scene.
                AnalysisOverlay overlay = new AnalysisOverlay();
                overlay.Analyses.Add(geoViewshed);
                MySceneView.AnalysisOverlays.Add(overlay);

                // Create a camera controller to orbit the tank.
                OrbitGeoElementCameraController cameraController = new OrbitGeoElementCameraController(_tank, 200.0)
                {
                    CameraPitchOffset = 45.0
                };
                // - Apply the camera controller to the SceneView.
                MySceneView.CameraController = cameraController;

                // Create a timer; this will enable animating the tank.
                DispatcherTimer animationTimer = new DispatcherTimer()
                {
                    Interval = new TimeSpan(0, 0, 0, 0, 60)
                };
                // - Move the tank every time the timer expires.
                animationTimer.Tick += (o, e) => { AnimateTank(); };
                // - Start the timer.
                animationTimer.Start();

                // Allow the user to click to define a new destination.
                MySceneView.GeoViewTapped += (sender, args) => { _tankEndPoint = args.Location; };
            }
            catch (Exception e)
            {
                await new MessageDialog2(e.ToString(), "Error").ShowAsync();
            }
        }
Example #49
0
        /// <summary>
        /// 根据坐标点获取当前所在区域信息
        /// </summary>
        /// <param name="mapPoint">点位信息</param>
        /// <returns></returns>
        internal static MyGeoInfo GetLocationInfoByPoint(MapPoint mapPoint)
        {
            MyGeoInfo result = new MyGeoInfo();

            try
            {
                string           ak          = System.Configuration.ConfigurationManager.AppSettings["Baidu_ak"].ToString(); //百度开发秘钥
                string           url         = "http://api.map.baidu.com/geocoder/v2/?ak=" + ak + "&location=" + mapPoint.lat.ToString() + "," + mapPoint.lng.ToString() + "&output=json&pois=0";
                string           json_Result = HttpRequestHelp.Get(url);
                dynamic          postion     = JsonConvert.DeserializeObject(json_Result);
                addressComponent address     = new addressComponent();
                if (postion.status == "0")
                {
                    string citynane = postion.result.addressComponent.city;
                    #region -- 匹配艺龙城市ID(用于酒店搜索);
                    for (int i = citynane.Length; i > 0; i--)
                    {
                        citynane = citynane.Substring(0, i);
                        string cityid = BaseSysTemDataBaseManager.RsGetCityIdByCityName(citynane);
                        if (!string.IsNullOrEmpty(cityid))
                        {
                            address.elongcityid = cityid;
                            break;
                        }
                    }
                    #endregion
                    address.city          = postion.result.addressComponent.city;
                    address.district      = postion.result.addressComponent.district;
                    address.province      = postion.result.addressComponent.province;
                    address.street        = postion.result.addressComponent.street;
                    address.street_number = postion.result.addressComponent.street_number;

                    result.business          = postion.result.business;
                    result.formatted_address = postion.result.formatted_address;
                    MapPoint loc = new MapPoint();
                    loc.lat       = postion.result.location.lat;
                    loc.lng       = postion.result.location.lng;
                    result.point  = loc;
                    result.status = postion.status;
                    #region -- 如果未能成功匹配城市ID,则判断是否在自治州
                    if (string.IsNullOrEmpty(address.elongcityid))
                    {
                        if (address.city.Contains("自治州"))
                        {
                            //自治州
                            string district = address.district;
                            for (int i = district.Length; i > 0; i--)
                            {
                                district = district.Substring(0, i);
                                string cityid = BaseSysTemDataBaseManager.RsGetCityIdByCityName(district);
                                if (!string.IsNullOrEmpty(cityid))
                                {
                                    address.elongcityid = cityid;
                                    break;
                                }
                            }
                        }
                    }
                    #endregion
                    result.addressComponent = address;
                }
                else
                {
                    result.status = postion.status;
                    SysManagerService.SysSaveErrorLogMsg("从百度地图接口根据点位信息获取位置详情时发生错误,错误代码{0},错误代码对照表:1服务器内部错误.2请求参数非法.3权限校验失败.4配额校验失败.5ak不存在或者非法.101服务禁用.102不通过白名单或者安全码不对.2xx无权限.3xx配额错误", mapPoint);
                }
            }
            catch (Exception e) {
                SysManagerService.SysSaveErrorLogMsg(e.ToString(), mapPoint);
            }
            return(result);
        }
Example #50
0
        /// <summary>
        /// CanLaunchSpell() vérifie si le sort peut être lancé. (override)
        /// </summary>
        /// <param name="spellId">ID du sort</param>
        /// <param name="characterCellId">CellId du personnage</param>
        /// <param name="cellId">CellId cible</param>
        /// <returns>SpellInabilityReasons: Unknown, ActionPoints, TooManyLaunch, Cooldown, TooManyInvocations, None </returns>
        public SpellInabilityReason CanLaunchSpell(int spellId, int characterCellId, int cellId)
        {
            DataClass spellData       = GameData.GetDataObject(D2oFileEnum.Spells, spellId);
            ArrayList ids             = (ArrayList)spellData.Fields["spellLevels"];
            int       level           = Account.Spells.FirstOrDefault(Spell => Spell.Id == spellId).Level;
            int       id              = Convert.ToInt32(ids[level - 1]);
            DataClass spellLevelsData = GameData.GetDataObject(D2oFileEnum.SpellLevels, id);

            if (spellLevelsData == null)
            {
                return(SpellInabilityReason.Unknown);
            }

            MapPoint characterPoint   = new MapPoint(characterCellId);
            MapPoint targetPoint      = new MapPoint(cellId);
            int      distanceToTarget = characterPoint.DistanceToCell(targetPoint);
            int      minRange         = (spellId != 0) ? (int)spellLevelsData.Fields["minRange"] : 0; //weaponData.minRange;

            if ((spellId != 0 && (bool)spellLevelsData.Fields["castInDiagonal"]))                     // || (weaponData != null && weaponData.castInDiagonal))
            {
                minRange = (minRange * 2);
            }
            if (minRange < 0)
            {
                minRange = 0;
            }
            int maxRange = (spellId != 0) ? (int)((int)spellLevelsData.Fields["range"] + ((bool)spellLevelsData.Fields["rangeCanBeBoosted"] ? Account.CharacterStats.range.objectsAndMountBonus : 0)) : (int)spellLevelsData.Fields["range"];

            if ((spellId != 0 && (bool)spellLevelsData.Fields["castInDiagonal"]))// || (weaponData != null && weaponData.castInDiagonal))
            {
                maxRange = (maxRange * 2);
            }
            if (maxRange < 0)
            {
                maxRange = 0;
            }
            if (distanceToTarget < minRange && distanceToTarget > 0)
            {
                return(SpellInabilityReason.MinRange);
            }
            if (distanceToTarget > maxRange)
            {
                return(SpellInabilityReason.MaxRange);
            }
            if (((spellId != 0 && (bool)spellLevelsData.Fields["castInLine"])) &&// || (weaponData != null && weaponData.castInDiagonal)) &&
                characterPoint.X != targetPoint.X &&
                characterPoint.Y != targetPoint.Y)
            {
                return(SpellInabilityReason.NotInLine);
            }
            if ((spellId != 0 && (bool)spellLevelsData.Fields["castInDiagonal"]))// || (weaponData != null && weaponData.castInDiagonal))
            {
                ArrayList list = Dofus1Line.GetLine(characterPoint.X, characterPoint.Y, targetPoint.X, targetPoint.Y);

                int i = 0;
                while (i < list.Count - 1)
                {
                    Dofus1Line.Point actualPoint = (Dofus1Line.Point)list[i];
                    Dofus1Line.Point nextPoint   = (Dofus1Line.Point)list[i + 1];
                    i += 1;
                    if (actualPoint.X == nextPoint.X + 1 && actualPoint.Y == nextPoint.Y + 1)
                    {
                        continue;
                    }
                    else if (actualPoint.X == nextPoint.X - 1 && actualPoint.Y == nextPoint.Y - 1)
                    {
                        continue;
                    }
                    else if (actualPoint.X == nextPoint.X + 1 && actualPoint.Y == nextPoint.Y - 1)
                    {
                        continue;
                    }
                    else if (actualPoint.X == nextPoint.X - 1 && actualPoint.Y == nextPoint.Y + 1)
                    {
                        continue;
                    }
                    return(SpellInabilityReason.NotInDiagonal);
                }
            }
            if (((spellId != 0 && (bool)spellLevelsData.Fields["castTestLos"] && distanceToTarget > 1)))// || (weaponData != null && weaponData.castTestLos)) && distanceToTarget > 1)
            {
                ArrayList list = Dofus1Line.GetLine(characterPoint.X, characterPoint.Y, targetPoint.X, targetPoint.Y);
                int       i    = 0;
                while (i < list.Count - 1)
                {
                    Dofus1Line.Point point3 = (Dofus1Line.Point)list[i];
                    MapPoint         point4 = new MapPoint((int)Math.Round(Math.Floor(point3.X)), (int)Math.Round(Math.Floor(point3.Y)));
                    if (!(IsFreeCell(point4.CellId)) || !(Account.Map.Data.IsLineOfSight(point4.CellId)))
                    {
                        return(SpellInabilityReason.LineOfSight);
                    }
                    i += 1;
                }
            }
            if ((TotalLaunchByCellBySpell.ContainsKey(spellId) && TotalLaunchByCellBySpell[spellId].ContainsKey(targetPoint.CellId)) && this.TotalLaunchByCellBySpell[spellId][targetPoint.CellId] >= (int)spellLevelsData.Fields["maxCastPerTarget"] && (int)spellLevelsData.Fields["maxCastPerTarget"] > 0)
            {
                return(SpellInabilityReason.TooManyLaunchOnCell);
            }
            if (IsFreeCell(cellId))
            {
                if ((bool)spellLevelsData.Fields["needTakenCell"])
                {
                    return(SpellInabilityReason.NeedTakenCell);
                }
            }
            else if ((bool)spellLevelsData.Fields["needFreeCell"])
            {
                return(SpellInabilityReason.NeedFreeCell);
            }
            return(SpellInabilityReason.None);
        }
    private void Update()
    {
        if (!prepared)
        {
            return;
        }
        float   t   = Time.deltaTime * GameMaster.gameSpeed;
        Vector3 dir = Vector3.back;

        for (int i = 0; i < GlobalMap.RINGS_COUNT; i++)
        {
            rings[i].transform.rotation = Quaternion.Euler(0, 0, ringsRotation[i]);
        }
        //
        if (lastDrawnStateHash != globalMap.actionsHash)
        {
            RedrawMap();
        }
        else
        {
            if (mapMarkers.Count > 0)
            {
                Vector3 up = Vector3.up * mapRect.rect.height / 2f;
                for (int i = 0; i < mapMarkers.Count; i++)
                {
                    MapPoint mp = mapPoints[i];
                    mapMarkers[i].localPosition = Quaternion.AngleAxis(mp.angle, dir) * (up * mp.height);
                }
            }
        }
        //

        float deltaX = 0, deltaY = 0, deltaZoom = 0;

        if (FollowingCamera.touchscreen)
        {
            if (Input.touchCount > 0)
            {
                Touch tc = Input.GetTouch(0);
                if (Input.touchCount == 2)
                {
                    Touch   tc2       = Input.GetTouch(1);
                    Vector2 tPrevPos  = tc.position - tc.deltaPosition;
                    Vector2 t2PrevPos = tc2.position - tc2.deltaPosition;
                    deltaZoom = ((tPrevPos - t2PrevPos).magnitude - (tc.position - tc2.position).magnitude) / (float)Screen.height * (-2);
                }
                else
                {
                    if (Input.touchCount == 1)
                    {
                        if (tc.phase == TouchPhase.Began | tc.phase == TouchPhase.Moved)
                        {
                            float delta = tc.deltaPosition.x / (float)Screen.width * 10;
                            float swp   = Screen.width / 10f;
                            deltaX = tc.deltaPosition.x / swp;
                            deltaY = tc.deltaPosition.y / swp;
                        }
                    }
                }
            }
        }
        else
        {
            if (Input.GetMouseButton(2))
            {
                deltaX = Input.GetAxis("Mouse X");
                deltaY = Input.GetAxis("Mouse Y");
            }
            deltaZoom = Input.GetAxis("Mouse ScrollWheel");
        }

        if (deltaZoom != 0)
        {
            float newScale = mapRect.localScale.y + deltaZoom * mapRect.localScale.y;
            if (newScale > ZOOM_BORDER)
            {
                newScale = ZOOM_BORDER;
            }
            else
            {
                if (newScale < DIST_BORDER)
                {
                    newScale = DIST_BORDER;
                }
            }
            Vector3 one = Vector3.one;
            if (newScale != mapRect.localScale.x)
            {
                mapRect.localScale = one * newScale;
            }
            if (mapMarkers.Count > 0)
            {
                foreach (RectTransform marker in mapMarkers)
                {
                    marker.localScale = one * (1f / newScale);
                }
            }
        }
        float xpos = mapRect.position.x, ypos = mapRect.position.y;
        float sw     = Screen.width - infoPanelWidth;
        int   sh     = Screen.height;
        float radius = mapRect.rect.width * mapRect.localScale.x / 2f;

        if (2 * radius <= sw)
        {
            xpos = sw / 2f;
        }
        else
        {
            if (deltaX != 0)
            {
                xpos += deltaX * 30;
            }
            float leftExpart  = xpos - radius;
            float rightExpart = sw - (xpos + radius);
            if (leftExpart > 0)
            {
                if (rightExpart < 0)
                {
                    xpos = radius;
                }
            }
            else
            {
                if (rightExpart > 0)
                {
                    xpos = sw - (radius);
                }
            }
        }

        if (2 * radius <= sh)
        {
            ypos = sh / 2f;
        }
        else
        {
            if (deltaY != 0)
            {
                ypos += deltaY * 30;
            }
            float upExpart   = sh - ypos - radius;
            float downExpart = ypos - radius;
            if (upExpart > 0)
            {
                if (downExpart < 0)
                {
                    ypos = sh - radius;
                }
            }
            else
            {
                if (downExpart > 0)
                {
                    ypos = radius;
                }
            }
        }

        mapRect.position = new Vector3(xpos, ypos, 0);

        if (needExpeditionsRedraw)
        {
            ExpeditionsButtonsRedraw();
            PreparePointDescription();
        }
    }
Example #52
0
        public IEnumerable <FighterEntry> GetHandToHandAllies(short cellId = -1)
        {
            MapPoint charMp = MapPoint.FromCellId(cellId == -1 ? PlayedFighter.CellId : cellId);

            return(Allies.Where(a => a.Alive && charMp.DistanceToCell(MapPoint.FromCellId(a.CellId)) == 1));
        }
    public void OnCallGunFire(int idir)
    {
        //銃弾エフェクト

        //現在位置の取得
        Vector3 CurrentPoint = new Vector3(Character.CurrentPoint.X * Character.PositionUnit,
                                           PosY,
                                           Character.CurrentPoint.Y * Character.PositionUnit);

        foreach (GunFireActionNumber val in GunFireActionNumbers)
        {
            if (val == GunFireActionNumber.BothGun || val == GunFireActionNumber.LeftGun || val == GunFireActionNumber.RightGun)
            {
                continue;
            }
            if (((int)val & idir) != 0)
            {
                CharacterDirection dir = CharacterDirection.Top;
                //方向の取得
                switch (val)
                {
                case GunFireActionNumber.Top:
                    dir = Character.Direction;
                    break;

                case GunFireActionNumber.TopLeft:
                    dir = CommonFunction.RelativeFrontLeft[Character.Direction];
                    break;

                case GunFireActionNumber.TopRight:
                    dir = CommonFunction.RelativeFrontRight[Character.Direction];
                    break;

                case GunFireActionNumber.Left:
                    dir = CommonFunction.RelativeLeft[Character.Direction];
                    break;

                case GunFireActionNumber.Right:
                    dir = CommonFunction.RelativeRight[Character.Direction];
                    break;

                case GunFireActionNumber.BottomLeft:
                    dir = CommonFunction.ReverseLeftDirectionVector[Character.Direction];
                    break;

                case GunFireActionNumber.BottomRight:
                    dir = CommonFunction.ReverseRightDirectionVector[Character.Direction];
                    break;

                case GunFireActionNumber.Bottom:
                    dir = CommonFunction.ReverseDirection[Character.Direction];
                    break;
                }
                //MapPoint mp = Character.DeathBlowTargetPoint[dir].Add(CommonFunction.CharacterDirectionVector[CommonFunction.ReverseDirection[dir]]);
                MapPoint mp = Character.DeathBlowTargetPoint[dir];
                //目標位置の取得
                Vector3 TargetPoint = new Vector3(mp.X * Character.PositionUnit + ((float)CommonFunction.CharacterDirectionVector[CommonFunction.ReverseDirection[dir]].X * 0.5f),
                                                  PosY,
                                                  mp.Y * Character.PositionUnit + ((float)CommonFunction.CharacterDirectionVector[CommonFunction.ReverseDirection[dir]].Y * 0.5f));

                //銃弾エフェクト
                EffectGunBulletSingle.CreateObject(CurrentPoint, TargetPoint, Character.DeathBlowTargetCharacter[dir], dir).Play();
            }
        }

        //マズルエフェクト
        if (((int)GunFireActionNumber.LeftGun & idir) != 0)
        {
            EffectMuzzleFlash.CreateObject(GunLeftPos).Play();
        }
        else if (((int)GunFireActionNumber.RightGun & idir) != 0)
        {
            EffectMuzzleFlash.CreateObject(GunRightPos).Play();
        }
        else if (((int)GunFireActionNumber.BothGun & idir) != 0)
        {
            EffectMuzzleFlash.CreateObject(GunRightPos).Play();
            EffectMuzzleFlash.CreateObject(GunLeftPos).Play();
        }

        //音
        SoundInformation.Sound.Play(SoundInformation.SoundType.Gun);
    }
Example #54
0
        protected SpellInabilityReason CanLaunchSpellOn(int spellId, int characterCellId, int cellId,
                                                        bool withMove = false)
        {
            if (!withMove)
            {
                var canLaunchSpell = CanLaunchSpell(spellId);
                if (canLaunchSpell != SpellInabilityReason.None)
                {
                    return(canLaunchSpell);
                }
            }
            short spellLevel;

            try
            {
                spellLevel = Account.Character.Spells.First(s => s.SpellId == spellId).SpellLevel;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(SpellInabilityReason.UnknownSpell);
            }

            var spell = ObjectDataManager.Instance.Get <API.Datacenter.Spell>(spellId);
            var id    = Convert.ToInt32(spell.SpellLevels[spellLevel - 1]);

            var spellLevelsData = ObjectDataManager.Instance.Get <SpellLevel>(/*spellId */ id);

            if (spellLevelsData == null)
            {
                return(SpellInabilityReason.Unknown);
            }
            if (spellId == 0)
            {
                return(SpellInabilityReason.UnknownSpell);
            }
            var characterPoint   = new MapPoint(characterCellId);
            var targetPoint      = new MapPoint(cellId);
            var distanceToTarget = characterPoint.DistanceToCell(targetPoint);
            var minRange         = spellLevelsData.MinRange;

            if (spellId != 0 && spellLevelsData.CastInDiagonal)
            {
                minRange = minRange * 2;
            }
            if (minRange < 0)
            {
                minRange = 0;
            }
            var maxRange = spellId != 0
                ? spellLevelsData.Range + (spellLevelsData.RangeCanBeBoosted
                      ? Account.Character.Stats.Range.ObjectsAndMountBonus
                      : 0)
                : spellLevelsData.Range;

            if (spellId != 0 && spellLevelsData.CastInDiagonal)
            {
                maxRange = maxRange * 2;
            }
            if (maxRange < 0)
            {
                maxRange = 0;
            }
            if (distanceToTarget < minRange)
            {
                return(SpellInabilityReason.MinRange);
            }
            if (distanceToTarget > maxRange)
            {
                return(SpellInabilityReason.MaxRange);
            }
            if (spellId != 0 && spellLevelsData.CastInLine &&
                characterPoint.X != targetPoint.X &&
                characterPoint.Y != targetPoint.Y)
            {
                return(SpellInabilityReason.NotInLine);
            }
            if (spellId != 0 && spellLevelsData.CastInDiagonal)
            {
                var list = Dofus1Line.GetLine(characterPoint.X, characterPoint.Y, targetPoint.X, targetPoint.Y);
                var i    = 0;
                while (i < list.Count - 1)
                {
                    var actualPoint = (Dofus1Line.Point)list[i];
                    var nextPoint   = (Dofus1Line.Point)list[i + 1];
                    i += 1;
                    if (actualPoint.X == nextPoint.X + 1 && actualPoint.Y == nextPoint.Y + 1)
                    {
                        continue;
                    }
                    if (actualPoint.X == nextPoint.X - 1 && actualPoint.Y == nextPoint.Y - 1)
                    {
                        continue;
                    }
                    if (actualPoint.X == nextPoint.X + 1 && actualPoint.Y == nextPoint.Y - 1)
                    {
                        continue;
                    }
                    if (actualPoint.X == nextPoint.X - 1 && actualPoint.Y == nextPoint.Y + 1)
                    {
                        continue;
                    }
                    return(SpellInabilityReason.NotInDiagonal);
                }
            }
            if (spellId != 0 && spellLevelsData.CastTestLos && distanceToTarget > 1)
            {
                var list = Dofus1Line.GetLine(characterPoint.X, characterPoint.Y, targetPoint.X, targetPoint.Y);
                var i    = 0;
                while (i < list.Count - 1)
                {
                    var point3 = (Dofus1Line.Point)list[i];
                    var point4 = new MapPoint((int)Math.Round(Math.Floor(point3.X)),
                                              (int)Math.Round(Math.Floor(point3.Y)));
                    if (!IsFreeCell(point4.CellId) || !Account.Character.Map.Data.IsLineOfSight(point4.CellId))
                    {
                        return(SpellInabilityReason.LineOfSight);
                    }
                    i += 1;
                }
            }
            if (TotalLaunchByCellBySpell.ContainsKey(spellId) &&
                TotalLaunchByCellBySpell[spellId].ContainsKey(targetPoint.CellId) &&
                TotalLaunchByCellBySpell[spellId][targetPoint.CellId] >= spellLevelsData.MaxCastPerTarget &&
                spellLevelsData.MaxCastPerTarget > 0)
            {
                return(SpellInabilityReason.TooManyLaunchOnCell);
            }
            if (IsFreeCell(cellId))
            {
                if (spellLevelsData.NeedTakenCell)
                {
                    return(SpellInabilityReason.NeedTakenCell);
                }
            }
            else if (spellLevelsData.NeedFreeCell)
            {
                return(SpellInabilityReason.NeedFreeCell);
            }
            return(SpellInabilityReason.None);
        }
Example #55
0
        private IEnumerable <MapPoint> GetListPointAtGoodDistance(MapPoint characterPoint, MapPoint elementPoint,
                                                                  int weaponRange)
        {
            var list      = new List <MapPoint>();
            var num       = -1;
            var direction = 1;

            while (true)
            {
                var i = 0;
                while (i < weaponRange)
                {
                    i += 1;
                    var nearestCellInDirection = elementPoint.GetNearestCellInDirection(direction, i);
                    if (!nearestCellInDirection.IsInMap() ||
                        !_account.Character.Map.Data.IsWalkable(nearestCellInDirection.CellId))
                    {
                        continue;
                    }
                    var num4 = characterPoint.DistanceToCell(nearestCellInDirection);
                    if (num == -1 || num >= num4)
                    {
                        if (num4 < num)
                        {
                            list.Clear();
                        }
                        num = num4;
                        list.Add(nearestCellInDirection);
                    }
                    break;
                }
                direction = direction + 2;
                if (direction > 7)
                {
                    return(list);
                }
            }
        }
    private void RedrawMap()
    {
        if (!prepared)
        {
            return;
        }
        else
        {
            mapPoints = globalMap.mapPoints;
            int n = mapPoints.Count;
            //print(n);
            int c = mapMarkers.Count;
            if (n > 0)
            {
                mapRect.gameObject.SetActive(false);
                if (c != n)
                {
                    if (c > n)
                    {
                        for (int i = c - 1; i >= n; i--)
                        {
                            int a = mapMarkers.Count - 1;
                            Destroy(mapMarkers[a].gameObject);
                            mapMarkers.RemoveAt(a);
                        }
                    }
                    else
                    {
                        for (int i = c; i < n; i++)
                        {
                            mapMarkers.Add(Instantiate(exampleMarker, mapRect).GetComponent <RectTransform>());
                        }
                    }
                }
                RectTransform rt;
                MapPoint      mp;
                Vector3       dir = Vector3.back, up = Vector3.up * mapRect.rect.height / 2f;
                bool          checkForChosen = (chosenPoint != null);
                for (int i = 0; i < n; i++)
                {
                    mp = mapPoints[i];
                    rt = mapMarkers[i];
                    if (checkForChosen && mp == chosenPoint)
                    {
                        rt.GetComponent <Image>().color = chosenColor;
                    }
                    else
                    {
                        rt.GetComponent <Image>().color = mp is PointOfInterest ? interactableColor : notInteractableColor;
                    }
                    rt.GetChild(0).GetComponent <RawImage>().uvRect = GetMarkerRect(mp.type);
                    Button b = rt.GetComponent <Button>();;
                    b.onClick.RemoveAllListeners();
                    MapPoint mpLink = mp;
                    b.onClick.AddListener(() => { this.SelectPoint(mpLink); }); // переписываем каждый раз, поскольку массив видимых точек соответствует массиву всех точек по индексам

                    rt.localPosition = Quaternion.AngleAxis(mapPoints[i].angle, dir) * (up * mapPoints[i].height);

                    if (!rt.gameObject.activeSelf)
                    {
                        rt.gameObject.SetActive(true);
                    }
                }
                mapRect.gameObject.SetActive(true);
                //
                ExpeditionsButtonsRedraw();
            }
            else
            {
                if (mapMarkers.Count > 0)
                {
                    for (int i = 0; i < c; i++)
                    {
                        Destroy(mapMarkers[0].gameObject);
                        mapMarkers.RemoveAt(0);
                    }
                }
                expeditionFastButtonsPanel.gameObject.SetActive(false);
            }

            RingSector[] sectorsData = globalMap.mapSectors;
            for (int i = 0; i < sectorsData.Length; i++)
            {
                if (sectorsData[i] != null)
                {
                    var mp = sectorsData[i].centralPoint;
                    if (mp.type != MapMarkerType.Star)
                    {
                        sectorsImages[i].color = sectorsData[i].environment.GetMapColor();
                    }
                    else
                    {
                        sectorsImages[i].color = (mp as SunPoint).color;
                    }
                }
                else
                {
                    sectorsImages[i].color = inactiveSectorColor;
                }
            }

            if (globalMap.engineThrust > 0f)
            {
                if (!enginePanel.gameObject.activeSelf)
                {
                    enginePanel.gameObject.SetActive(true);
                }
            }
            else
            {
                if (enginePanel.gameObject.activeSelf)
                {
                    enginePanel.gameObject.SetActive(false);
                }
            }

            lastDrawnStateHash = globalMap.actionsHash;
        }
    }
        private async Task CalculateViewshed(MapPoint location)
        {
            // This function will define a new geoprocessing task that performs a custom viewshed analysis based upon a
            // user click on the map and then display the results back as a polygon fill graphics overlay. If there
            // is a problem with the execution of the geoprocessing task an error message will be displayed

            // Create new geoprocessing task using the url defined in the member variables section
            var myViewshedTask = new GeoprocessingTask(new Uri(_viewshedUrl));

            // Create a new feature collection table based upon point geometries using the current map view spatial reference
            var myInputFeatures = new FeatureCollectionTable(new List <Field>(), GeometryType.Point, MyMapView.SpatialReference);

            // Create a new feature from the feature collection table. It will not have a coordinate location (x,y) yet
            Feature myInputFeature = myInputFeatures.CreateFeature();

            // Assign a physical location to the new point feature based upon where the user clicked in the map view
            myInputFeature.Geometry = location;

            // Add the new feature with (x,y) location to the feature collection table
            await myInputFeatures.AddFeatureAsync(myInputFeature);

            // Create the parameters that are passed to the used geoprocessing task
            GeoprocessingParameters myViewshedParameters =
                new GeoprocessingParameters(GeoprocessingExecutionType.SynchronousExecute);

            // Request the output features to use the same SpatialReference as the map view
            myViewshedParameters.OutputSpatialReference = MyMapView.SpatialReference;

            // Add an input location to the geoprocessing parameters
            myViewshedParameters.Inputs.Add("Input_Observation_Point", new GeoprocessingFeatures(myInputFeatures));

            // Create the job that handles the communication between the application and the geoprocessing task
            var myViewshedJob = myViewshedTask.CreateJob(myViewshedParameters);

            try
            {
                // Execute analysis and wait for the results
                GeoprocessingResult myAnalysisResult = await myViewshedJob.GetResultAsync();

                // Get the results from the outputs
                GeoprocessingFeatures myViewshedResultFeatures = myAnalysisResult.Outputs["Viewshed_Result"] as GeoprocessingFeatures;

                // Add all the results as a graphics to the map
                IFeatureSet myViewshedAreas = myViewshedResultFeatures.Features;
                foreach (var myFeature in myViewshedAreas)
                {
                    _resultOverlay.Graphics.Add(new Graphic(myFeature.Geometry));
                }
            }
            catch (Exception ex)
            {
                // Display an error message if there is a problem
                if (myViewshedJob.Status == JobStatus.Failed && myViewshedJob.Error != null)
                {
                    var message = new MessageDialog("Executing geoprocessing failed. " + myViewshedJob.Error.Message, "Geoprocessing error");
                    await message.ShowAsync();
                }
                else
                {
                    var message = new MessageDialog("An error occurred. " + ex.ToString(), "Sample error");
                    await message.ShowAsync();
                }
            }
            finally
            {
                // Indicate that the geoprocessing is not running
                SetBusy(false);
            }
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here
            SetContentView(Resource.Layout.map);
            mapView = (GLMapView)FindViewById(Resource.Id.map_view);

            // Map list is updated, because download button depends on available map list and during first launch this list is empty
            GLMapManager.UpdateMapList(this, null);

            btnDownloadMap        = (Button)this.FindViewById(Resource.Id.button_dl_map);
            btnDownloadMap.Click += (object sender, EventArgs e) =>
            {
                if (mapToDownload != null)
                {
                    GLMapDownloadTask task = GLMapManager.GetDownloadTask(mapToDownload);
                    if (task != null)
                    {
                        task.Cancel();
                    }
                    else
                    {
                        GLMapManager.CreateDownloadTask(mapToDownload, this).Start();
                    }
                    updateMapDownloadButtonText();
                }
                else
                {
                    Intent i = new Intent(Application.Context, typeof(DownloadActivity));

                    MapPoint pt = mapView.MapCenter;
                    i.PutExtra("cx", pt.X);
                    i.PutExtra("cy", pt.Y);
                    Application.Context.StartActivity(i);
                }
            };

            GLMapManager.AddStateListener(this);

            localeSettings         = new GLMapLocaleSettings();
            mapView.LocaleSettings = localeSettings;
            mapView.LoadStyle(Assets, "DefaultStyle.bundle");
            mapView.SetUserLocationImages(mapView.ImageManager.Open("DefaultStyle.bundle/circle-new.svgpb", 1, 0), mapView.ImageManager.Open("DefaultStyle.bundle/arrow-new.svgpb", 1, 0));

            mapView.SetScaleRulerStyle(GLUnits.SI, GLMapPlacement.BottomCenter, new MapPoint(10, 10), 200);
            mapView.SetAttributionPosition(GLMapPlacement.TopCenter);

            CheckAndRequestLocationPermission();

            Bundle  b       = Intent.Extras;
            Samples example = (Samples)b.GetInt("example");

            switch (example)
            {
            case Samples.MAP_EMBEDD:
                if (!GLMapManager.AddMap(Assets, "Montenegro.vm", null))
                {
                    //Failed to unpack to caches. Check free space.
                }
                zoomToPoint();
                break;

            case Samples.MAP_ONLINE:
                GLMapManager.SetAllowedTileDownload(true);
                break;

            case Samples.MAP_ONLINE_RASTER:
                mapView.RasterTileSources = new GLMapRasterTileSource[] { new OSMTileSource(this) };
                break;

            case Samples.ZOOM_BBOX:
                zoomToBBox();
                break;

            case Samples.FLY_TO:
            {
                mapView.SetMapCenter(MapPoint.CreateFromGeoCoordinates(37.3257, -122.0353), false);
                mapView.SetMapZoom(14, false);

                Button btn = (Button)FindViewById(Resource.Id.button_action);
                btn.Visibility = ViewStates.Visible;
                btn.Text       = "Fly";
                btn.Click     += (object sender, EventArgs e) =>
                {
                    double min_lat = 33;
                    double max_lat = 48;
                    double min_lon = -118;
                    double max_lon = -85;

                    double lat = min_lat + (max_lat - min_lat) * new Random(1).NextDouble();
                    double lon = min_lon + (max_lon - min_lon) * new Random(2).NextDouble();

                    MapGeoPoint geoPoint = new MapGeoPoint(lat, lon);

                    mapView.FlyTo(geoPoint, 15, 0, 0);
                };
                GLMapManager.SetAllowedTileDownload(true);
                break;
            }

            case Samples.OFFLINE_SEARCH:
                GLMapManager.AddMap(Assets, "Montenegro.vm", null);
                zoomToPoint();
                offlineSearch();
                break;

            case Samples.MARKERS:
                mapView.LongClickable = true;

                gestureDetector = new GestureDetector(this, new SimpleOnGestureListenerAnonymousInnerClassHelper(this));

                mapView.SetOnTouchListener(new TouchListener(gestureDetector));

                addMarkers();
                GLMapManager.SetAllowedTileDownload(true);
                break;

            case Samples.MARKERS_MAPCSS:
                addMarkersWithMapcss();

                gestureDetector = new GestureDetector(this, new SimpleOnGestureListenerAnonymousInnerClassHelper2(this));

                mapView.SetOnTouchListener(new TouchListener(gestureDetector));

                GLMapManager.SetAllowedTileDownload(true);
                break;

            case Samples.MULTILINE:
                addMultiline();
                break;

            case Samples.POLYGON:
                addPolygon();
                break;

            case Samples.CAPTURE_SCREEN:
                zoomToPoint();
                captureScreen();
                break;

            case Samples.IMAGE_SINGLE:
            {
                Button btn = (Button)this.FindViewById(Resource.Id.button_action);
                btn.Visibility = ViewStates.Visible;
                delImage(btn, null);
                break;
            }

            case Samples.IMAGE_MULTI:
                mapView.LongClickable = true;

                gestureDetector = new GestureDetector(this, new SimpleOnGestureListenerAnonymousInnerClassHelper3(this));

                mapView.SetOnTouchListener(new TouchListener(gestureDetector));
                break;

            case Samples.GEO_JSON:
                loadGeoJSON();
                break;

            case Samples.STYLE_LIVE_RELOAD:
                styleLiveReload();
                break;
            }

            mapView.SetCenterTileStateChangedCallback(() =>
            {
                RunOnUiThread(() =>
                {
                    updateMapDownloadButton();
                });
            });

            mapView.SetMapDidMoveCallback(() =>
            {
                if (example == Samples.CALLBACK_TEST)
                {
                    Log.Warn("GLMapView", "Did move");
                }
                RunOnUiThread(() =>
                {
                    updateMapDownloadButtonText();
                });
            });
        }
Example #59
0
        private async Task CalculateViewshed(MapPoint location)
        {
            // This function will define a new geoprocessing task that performs a custom viewshed analysis based upon a
            // user click on the map and then display the results back as a polygon fill graphics overlay. If there
            // is a problem with the execution of the geoprocessing task an error message will be displayed.

            // Create new geoprocessing task using the URL defined in the member variables section.
            GeoprocessingTask viewshedTask = await GeoprocessingTask.CreateAsync(new Uri(ViewshedServiceUrl));

            // Create a new feature collection table based upon point geometries using the current map view spatial reference.
            FeatureCollectionTable inputFeatures = new FeatureCollectionTable(new List <Field>(), GeometryType.Point, _myMapView.SpatialReference);

            // Create a new feature from the feature collection table. It will not have a coordinate location (x,y) yet.
            Feature inputFeature = inputFeatures.CreateFeature();

            // Assign a physical location to the new point feature based upon where the user clicked in the map view.
            inputFeature.Geometry = location;

            // Add the new feature with (x,y) location to the feature collection table.
            await inputFeatures.AddFeatureAsync(inputFeature);

            // Create the parameters that are passed to the used geoprocessing task.
            GeoprocessingParameters viewshedParameters = new GeoprocessingParameters(GeoprocessingExecutionType.SynchronousExecute)
            {
                OutputSpatialReference = _myMapView.SpatialReference
            };

            // Add an input location to the geoprocessing parameters.
            viewshedParameters.Inputs.Add("Input_Observation_Point", new GeoprocessingFeatures(inputFeatures));

            // Create the job that handles the communication between the application and the geoprocessing task.
            GeoprocessingJob viewshedJob = viewshedTask.CreateJob(viewshedParameters);

            try
            {
                // Execute analysis and wait for the results.
                GeoprocessingResult analysisResult = await viewshedJob.GetResultAsync();

                // Get the results from the outputs.
                GeoprocessingFeatures viewshedResultFeatures = (GeoprocessingFeatures)analysisResult.Outputs["Viewshed_Result"];

                // Add all the results as a graphics to the map.
                foreach (Feature feature in viewshedResultFeatures.Features)
                {
                    _resultOverlay.Graphics.Add(new Graphic(feature.Geometry));
                }
            }
            catch (Exception ex)
            {
                // Display an error message if there is a problem.
                if (viewshedJob.Status == JobStatus.Failed && viewshedJob.Error != null)
                {
                    // Report error
                    UIAlertController alert = UIAlertController.Create("Geoprocessing Error", viewshedJob.Error.Message, UIAlertControllerStyle.Alert);
                    alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                    PresentViewController(alert, true, null);
                }
                else
                {
                    // Report error
                    UIAlertController alert = UIAlertController.Create("Sample Error", ex.ToString(), UIAlertControllerStyle.Alert);
                    alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                    PresentViewController(alert, true, null);
                }
            }
        }
        private async void Initialize()
        {
            try
            {
                // Disable the UI.
                FilterOptions.IsVisible = false;

                // Create and load the utility network.
                _utilityNetwork = await UtilityNetwork.CreateAsync(new Uri(FeatureServiceUrl));

                // Create a map with layers in this utility network.
                MyMapView.Map = new Map(new Basemap(new Uri("https://www.arcgis.com/home/item.html?id=1970c1995b8f44749f4b9b6e81b5ba45")));
                MyMapView.Map.OperationalLayers.Add(new FeatureLayer(new Uri($"{FeatureServiceUrl}/{LineLayerId}")));
                MyMapView.Map.OperationalLayers.Add(new FeatureLayer(new Uri($"{FeatureServiceUrl}/{DeviceLayerId}")));

                // Get a trace configuration from a tier.
                UtilityDomainNetwork domainNetwork = _utilityNetwork.Definition.GetDomainNetwork(DomainNetworkName) ?? throw new ArgumentException(DomainNetworkName);
                UtilityTier          tier          = domainNetwork.GetTier(TierName) ?? throw new ArgumentException(TierName);
                _configuration = tier.TraceConfiguration;

                // Create a trace filter.
                _configuration.Filter = new UtilityTraceFilter();

                // Get a default starting location.
                UtilityNetworkSource networkSource = _utilityNetwork.Definition.GetNetworkSource(NetworkSourceName) ?? throw new ArgumentException(NetworkSourceName);
                UtilityAssetGroup    assetGroup    = networkSource.GetAssetGroup(AssetGroupName) ?? throw new ArgumentException(AssetGroupName);
                UtilityAssetType     assetType     = assetGroup.GetAssetType(AssetTypeName) ?? throw new ArgumentException(AssetTypeName);
                Guid globalId = Guid.Parse(GlobalId);
                _startingLocation = _utilityNetwork.CreateElement(assetType, globalId);

                // Create a graphics overlay.
                GraphicsOverlay overlay = new GraphicsOverlay();
                MyMapView.GraphicsOverlays.Add(overlay);

                // Display starting location.
                IEnumerable <ArcGISFeature> elementFeatures = await _utilityNetwork.GetFeaturesForElementsAsync(new List <UtilityElement> {
                    _startingLocation
                });

                MapPoint startingLocationGeometry = elementFeatures.FirstOrDefault().Geometry as MapPoint;
                Symbol   symbol  = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Cross, System.Drawing.Color.LimeGreen, 25d);
                Graphic  graphic = new Graphic(startingLocationGeometry, symbol);
                overlay.Graphics.Add(graphic);

                // Set the starting viewpoint.
                await MyMapView.SetViewpointAsync(new Viewpoint(startingLocationGeometry, 3000));

                // Build the choice list for categories populated with the `Name` property of each `UtilityCategory` in the `UtilityNetworkDefinition`.
                CategoryPicker.ItemsSource  = _utilityNetwork.Definition.Categories.ToList();
                CategoryPicker.SelectedItem = _utilityNetwork.Definition.Categories.First();

                // Enable the UI.
                FilterOptions.IsVisible = true;
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert(ex.GetType().Name, ex.Message, "OK");
            }
            finally
            {
                LoadingIndicator.IsVisible = false;
            }
        }