Exemplo n.º 1
0
        public static void GradientCheck(LayerBase layer, int inputWidth, int inputHeight, int inputDepth, double epsilon = 1e-4)
        {
            layer.Init(inputWidth, inputHeight, inputDepth);

            // Forward pass
            var input = new Volume(inputWidth, inputHeight, inputDepth);
            var output = layer.Forward(input, true);

            // Set output gradients to 1
            for (var n = 0; n < output.WeightGradients.Length; n++)
            {
                output.WeightGradients[n] = 1.0;
            }

            // Backward pass to retrieve gradients
            layer.Backward();
            var computedGradients = input;

            // Now let's approximate gradient using derivate definition
            for (var d = 0; d < inputDepth; d++)
            {
                for (var y = 0; y < inputHeight; y++)
                {
                    for (var x = 0; x < inputWidth; x++)
                    {
                        var oldValue = input.Get(x, y, d);

                        input.Set(x, y, d, oldValue + epsilon);
                        var output1 = layer.Forward(input);
                        input.Set(x, y, d, oldValue - epsilon);
                        var output2 = layer.Forward(input);

                        input.Set(x, y, d, oldValue);

                        output1.AddFromScaled(output2, -1.0); // output1 = output1 - output2

                        var grad = new double[output.WeightGradients.Length];
                        for (var j = 0; j < output.WeightGradients.Length; j++)
                        {
                            grad[j] = output1.Weights[j] / (2.0 * epsilon);
                        }

                        var gradient = grad.Sum(); // approximated gradient
                        var actual = computedGradients.GetGradient(x, y, d);
                        Assert.AreEqual(gradient, actual, 1e-4); // compare layer gradient to the approximated gradient
                    }
                }
            }
        }
Exemplo n.º 2
0
        public static void GradienWrtParameterstCheck(int inputWidth, int inputHeight, int inputDepth, LayerBase layer, double epsilon = 1e-4)
        {
            layer.Init(inputWidth, inputHeight, inputDepth);

            // Forward pass
            var input = new Volume(inputWidth, inputHeight, inputDepth, 1.0);
            var output = layer.Forward(input);

            // Set output gradients to 1
            for (var n = 0; n < output.WeightGradients.Length; n++)
            {
                output.WeightGradients[n] = 1.0;
            }

            // Backward pass to retrieve gradients
            layer.Backward();

            List<ParametersAndGradients> paramsAndGrads = layer.GetParametersAndGradients();

            foreach (var paramAndGrad in paramsAndGrads)
            {
                double[] computedGradients = paramAndGrad.Gradients;

                // Now let's approximate gradient
                for (var i = 0; i < paramAndGrad.Parameters.Length; i++)
                {
                    input = new Volume(inputWidth, inputHeight, inputDepth, 1.0);

                    var oldValue = paramAndGrad.Parameters[i];
                    paramAndGrad.Parameters[i] = oldValue + epsilon;
                    var output1 = layer.Forward(input);
                    paramAndGrad.Parameters[i] = oldValue - epsilon;
                    var output2 = layer.Forward(input);
                    paramAndGrad.Parameters[i] = oldValue;

                    output1.AddFromScaled(output2, -1.0); // output1 = output1 - output2

                    var grad = new double[output.WeightGradients.Length];
                    for (var j = 0; j < output.WeightGradients.Length; j++)
                    {
                        grad[j] = output1.Weights[j] / (2.0 * epsilon);
                    }

                    var gradient = grad.Sum(); // approximated gradient
                    Assert.AreEqual(gradient, computedGradients[i], 1e-4); // compare layer gradient to the approximated gradient
                }
            }
        }
Exemplo n.º 3
0
        private static XmlNode getWmtsLayerNode(WmtsServiceDescription serviceDescription, LayerBase layer, XmlDocument doc)
        {
            XmlNode layerNode = doc.CreateNode(XmlNodeType.Element, "Layer", wmtsNamespaceURI);
            layerNode.AppendChild(createElement("Name", layer.Alias, doc, false, wmtsNamespaceURI));
            layerNode.AppendChild(createElement("Title", layer.Title, doc, false, wmtsNamespaceURI));
            layerNode.Attributes.Append(doc.CreateAttribute("queryable")).Value = 
                layer is FeatureLayer && (layer as FeatureLayer).FeaturesSelectable ? "1" : "0";

            layerNode.AppendChild(GenerateTileMatrixSet(serviceDescription, doc));

            return layerNode;
        }
Exemplo n.º 4
0
 public Rectangle(LayerBase layer)
     : base(layer)
 {
 }
Exemplo n.º 5
0
        private void processDataProvider(XmlNode layerNode, LayerBase l)
        {
            XmlNode dataProvider = tryGetNodeByName(layerNode.ChildNodes, "data_provider");
            if (dataProvider != null)
            {
                l.DataProviderRegName = dataProvider.Attributes["registration_name"].Value;
                XmlNode parameters = tryGetNodeByName(dataProvider.ChildNodes, "parameters");
                if (parameters != null)
                {
                    Dictionary<string, string> p = new Dictionary<string, string>();
                    foreach (XmlNode parameter in parameters)
                        p.Add(parameter.Attributes["name"].Value, parameter.Attributes["value"].Value);

                    l.DataProviderParameters = p;
                }
            }
        }
Exemplo n.º 6
0
        private void addLayerElement(LayerBase layer, XmlDocument doc, XmlElement layersElement)
        {
            XmlElement layerElement = doc.CreateElement("layer");
            layersElement.AppendChild(layerElement);
            addAttribute(doc, layerElement, "title", layer.Title);
            addAttribute(doc, layerElement, "description", layer.Description);
            addAttribute(doc, layerElement, "alias", layer.Alias);
            addAttribute(doc, layerElement, "visible", layer.Visible ? "1" : "0");
            addAttribute(doc, layerElement, "controllable", layer.Controllable ? "1" : "0");
            addAttribute(doc, layerElement, "cacheable", layer.Cacheable ? "1" : "0");
            addAttribute(doc, layerElement, "minimum_visible_scale", layer.MinVisibleScale.ToString(CultureInfo.InvariantCulture));
            addAttribute(doc, layerElement, "maximum_visible_scale", layer.MaxVisibleScale.ToString(CultureInfo.InvariantCulture));

            FeatureLayer fl = layer as FeatureLayer;

            if (fl != null)
            {
                addAttribute(doc, layerElement, "type", "vector");
#pragma warning disable 618
                addAttribute(doc, layerElement, "datasource", fl.DataSource);
                addAttribute(doc, layerElement, "datasource_type", ((int)fl.DataSourceType).ToString(CultureInfo.InvariantCulture));
#pragma warning restore 618
                addAttribute(doc, layerElement, "shapes_selectable", fl.FeaturesSelectable ? "1" : "0");
                addAttribute(doc, layerElement, "dynamic_data_load", fl.AreFeaturesAutoLoadable ? "1" : "0");

                addTitleStyleElement(fl.TitleStyle, doc, layerElement);
                addPolygonStyleElement(fl.PolygonStyle, doc, layerElement);
                addPolylineStyleElement(fl.PolylineStyle, doc, layerElement);
                addPointStyleElement(fl.PointStyle, doc, layerElement);
                addIndiciesElements(fl, doc, layerElement);
                addLegendElement(fl, doc, layerElement);
                addAutoTitleSettingsElement(fl, doc, layerElement);
                addDataProviderElement(fl, doc, layerElement);
                addAppDataElement(fl, doc, layerElement);
                if (fl.FeatureLayerExtensions.Count>0)
                {
                    addFeatureLayerExtesions(fl.FeatureLayerExtensions, doc, layerElement);
                }
            }

            RasterLayer rl = layer as RasterLayer;
            if (rl != null)
            {
                addAttribute(doc, layerElement, "type", "raster");

                addRasterbindingElement(rl, doc, layerElement);
                addRasterStyleElement(rl, doc, layerElement);
                addDataProviderElement(rl, doc, layerElement);
                addAppDataElement(rl, doc, layerElement);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Request GetTile
        /// </summary>
        private void GetTile(NameValueCollection requestParams, Stream responseOutputStream, ref string responseContentType)
        {
            #region Verify the request

            if (requestParams["LAYERS"] == null)
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                              "Required parameter LAYER not specified.",
                              responseOutputStream,
                              ref responseContentType);
                return;
            }

            if (requestParams["STYLES"] == null)
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                              "Required parameter STYLE not specified.",
                              responseOutputStream,
                              ref responseContentType);
                return;
            }

            if (requestParams["TILEMATRIXSET"] == null)
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                              "Required parameter TILEMATRIXSET not specified.",
                              responseOutputStream,
                              ref responseContentType);
                return;
            }

            if (requestParams["TILEMATRIX"] == null)
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                              "Required parameter TILEMATRIX not specified.",
                              responseOutputStream,
                              ref responseContentType);
                return;
            }

            if (requestParams["TILEROW"] == null)
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                              "Required parameter TILEROW not specified.",
                              responseOutputStream,
                              ref responseContentType);
                return;
            }

            if (requestParams["TILECOL"] == null)
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                              "Required parameter TILECOL not specified.",
                              responseOutputStream,
                              ref responseContentType);
                return;
            }

            if (requestParams["FORMAT"] == null)
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                              "Required parameter FORMAT not specified.",
                              responseOutputStream,
                              ref responseContentType);
                return;
            }

            #endregion

            #region Render Settings

            Color backColor = Color.FromArgb(0, 0, 0, 0);

            if (_map.CosmeticRaster.Visible)
            {
                //Cosmetic layer all broken, this does not allow its use.
                WmtsException(WmtsExceptionCode.NotApplicable,
                              "WMTS  not support this settings rendering.",
                              responseOutputStream,
                              ref responseContentType);
                return;
            }
            //Render for inscriptions.
            var wmsFeatureRender = new WmsFeatureRender(_map.RenderingSettings);

            ImageCodecInfo imageEncoder = getEncoderInfo(requestParams["FORMAT"]);
            if (imageEncoder == null)
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                              "Wrong mime-type in FORMAT parameter.",
                              responseOutputStream,
                              ref responseContentType);
                return;
            }

            int tileRow = 0;
            int tileCol = 0;

            if (!int.TryParse(requestParams["TILEROW"], out tileRow))
            {
                WmtsException(WmtsExceptionCode.InvalidDimensionValue,
                              "Parameter TILEROW has wrong value.",
                              responseOutputStream,
                              ref responseContentType);
                return;
            }

            if (!int.TryParse(requestParams["TILECOL"], out tileCol))
            {
                WmsException(WmsExceptionCode.InvalidDimensionValue,
                             "Parameter TILECOL has wrong value.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }

            string tileMatrixName = "EPSG:3857:0";
            if (requestParams["TILEMATRIX"] != null)
            {
                tileMatrixName = requestParams["TILEMATRIX"];
            }



            Tile tile = new Tile(_map, (uint)tileRow, (uint)tileCol);
            tile.ScaleDenominator = _description.GetScaleDenominator(_description.ZoomLevel[tileMatrixName]);
            tile.PixelSize        = _description.GetPixelSize(_description.ZoomLevel[tileMatrixName]);
            tile.ZoomLevel        = (uint)_description.ZoomLevel[tileMatrixName];

            int width = tile.Width, height = tile.Height;

            BoundingRectangle originalBbox = tile.BBox;

            if (originalBbox == null)
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                              "Wrong Tile parameters.",
                              responseOutputStream,
                              ref responseContentType);
                return;
            }

            #endregion

            //Selected by default.
            bool[] _defaultVisibility      = new bool[_map.Layers.Count()];

            int j = 0;
            foreach (LayerBase layer in _map.Layers)
            {
                _defaultVisibility[j] = layer.Visible;
                layer.Visible         = false; //Turning off all the layers.
                j++;
            }

            lock (_syncRoot)
            {
                LayerBase[] useLayers   = null;
                int[]       indexLayers = null;
                #region Checking layers of inquiry

                if (!string.IsNullOrEmpty(requestParams["LAYER"]))
                {
                    #region Getting layers of inquiry

                    string[] layers = requestParams["LAYER"].Split(new[] { ',' });
                    if (_description.LayerLimit > 0)
                    {
                        if (layers.Length == 0 && _map.Layers.Count > _description.LayerLimit ||
                            layers.Length > _description.LayerLimit)
                        {
                            WmtsException(WmtsExceptionCode.OperationNotSupported,
                                          "The number of layers in the query exceeds the limit of layers in the WMTS.",
                                          responseOutputStream,
                                          ref responseContentType);
                            return;
                        }
                    }

                    #endregion

                    useLayers   = new LayerBase[layers.Length];
                    indexLayers = new int[layers.Length];
                    for (int i = 0; i < layers.Length; i++)
                    {
                        var layer     = layers[i];
                        var findLayer = false;
                        for (int k = 0; k < _map.Layers.Count; k++)
                        {
                            if (string.Equals(_map.Layers[k].Alias, layer,
                                              StringComparison.InvariantCultureIgnoreCase))
                            {
                                useLayers[i]   = _map.Layers[k];
                                indexLayers[i] = k;
                                findLayer      = true;
                                break;
                            }
                        }


                        if (!findLayer)
                        {
                            WmtsException(WmtsExceptionCode.LayerNotDefined,
                                          "Layer \"" + layer + "\" not found.",
                                          responseOutputStream,
                                          ref responseContentType);
                            return;
                        }
                    }

                    Array.Sort(indexLayers, useLayers);
                }

                #endregion

                BoundingRectangle bboxWithGutters = (BoundingRectangle)originalBbox.Clone();
                bboxWithGutters.Grow((double)GutterSize * originalBbox.Width / (double)width);

                try
                {
                    using (Image bmp = GetImage(width, height, backColor, useLayers, bboxWithGutters))
                    {
                        EncoderParameters encoderParams = new EncoderParameters(1);
                        encoderParams.Param[0] = new EncoderParameter(
                            System.Drawing.Imaging.Encoder.Quality, (long)_imageQuality);

                        using (MemoryStream ms = new MemoryStream())
                        {
                            bmp.Save(ms, imageEncoder, encoderParams);
                            byte[] buffer = ms.ToArray();
                            responseContentType = imageEncoder.MimeType;
                            responseOutputStream.Write(buffer, 0, buffer.Length);
                        }
                    }
                }
                catch (Exception except)
                {
                    WmtsException(WmtsExceptionCode.NotApplicable, except.Message, responseOutputStream, ref responseContentType);
                    return;
                }

                for (j = 0; j < _map.Layers.Count(); j++) //Restore it as it was.
                {
                    _map.Layers[j].Visible = _defaultVisibility[j];
                }
            }
        }
Exemplo n.º 8
0
 public DrawableBase(LayerBase layer)
 {
     InitializeInternal(layer);
     Initialize();
 }
Exemplo n.º 9
0
        /// <summary>
        /// Returns a vector of objects
        /// </summary>

        protected string GetVector(int layerNumber, int width, int height, LayerBase[] useLayers, BoundingRectangle bboxWithGutters, NameValueCollection requestParams)
        {
            StringWriter stringWriter = new StringWriter();
            Newtonsoft.Json.JsonWriter js = new JsonTextWriter(stringWriter);
            int i = layerNumber;
            JObject objResponse = new JObject();
            //Проверка, что вообще есть что отображать.
            if (!ReferenceEquals(useLayers, null) && (useLayers.Length > 0))
                //do
                {
                    JObject objLayer = new JObject();
                    try
                    {
                        //Делаем слой видимым. Все остальные слои мы отключили выше.
                        useLayers[i].Visible = true;

                        //Настройка слоя перед рендерингом.
                        if (useLayers[i] is FeatureLayer)
                            OnPrepareRenderFeatureLayer(new PrepareRenderFeatureLayerArgs((FeatureLayer)useLayers[i]));

                        //Загружаем данные (почему это делается вне WMS сам не понимаю).

                        OnBeforeRenderNewImage(new RenderNewImageEventArgs(bboxWithGutters, useLayers[i]));
                        //MapAround загрузит только видимые слои, по этому не заморачиваемся на загрузки слоев по отдельности.   
                        BoundingRectangle mapCoordsViewBox = Map.MapViewBoxFromPresentationViewBox(bboxWithGutters);
                    

                        // количество пикселей в единичном отрезке карты (в координатах представления)
                        double scaleFactor = Math.Min(width / bboxWithGutters.Width, height / bboxWithGutters.Height);

                        //Если информация уже загружена, извлекается из кэша, если нет - вызывается WriteLayer и кэшируется
                        if (ReferenceEquals(GetJSONFromCache(useLayers[i], requestParams), null))
                        {
                            if (scaleFactor >= useLayers[i].MinVisibleScale && scaleFactor <= useLayers[i].MaxVisibleScale)
                            {
                                WriteLayer(objLayer, useLayers[i] as FeatureLayer, bboxWithGutters, mapCoordsViewBox, scaleFactor, requestParams);
                                SetJSONToCache(useLayers[i], objLayer.ToString(), requestParams);
                            }
                        }
                        else
                        {
                            objLayer = JObject.Parse(GetJSONFromCache(useLayers[i], requestParams));
                        }
                        
                        objResponse.Add(useLayers[i].Alias,objLayer);
                        objResponse.WriteTo(js);
                    }
                    finally
                    {                                                       
                    }
                } //while (i < useLayers.Length);
                        
            return stringWriter.ToString();          
        }
Exemplo n.º 10
0
        /// <summary>
        /// Gets image
        /// </summary>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="backColor"></param>
        /// <param name="useLayers"></param>
        /// <param name="bboxWithGutters"></param>
        /// <returns></returns>
        protected Image GetImage(int width, int height, Color backColor, LayerBase[] useLayers, BoundingRectangle bboxWithGutters)
        {
            #region Проверка на занятость ресурсов

            // проверяем заняты ли ресурсы
            if (_drawingRequestSemaphore != null)
                if (!_drawingRequestSemaphore.WaitOne(_drawingResourcesTimeOut))                
                    throw new Exception(  "There are currently no resources on the server needed to generate the map image.");
            
            #endregion
            
            try
            {
                bool cacheable = true;
                string allLayerKey = "";

                foreach (var layer in useLayers.OrderBy(x=>x.Alias))
                {
                    cacheable &= layer.Cacheable;
                    allLayerKey += layer.Alias;
                }

                if (cacheable)
                {
                    Image res = GetImage(bboxWithGutters, allLayerKey);
                    
                        if (!ReferenceEquals(res,null))
                        {

                            return res;
                        }
                    
                }
                //Рендер для надписей.
                var wmsFeatureRender = new WmsFeatureRender(_map.RenderingSettings);

                using (Image bmpWithGutters = new Bitmap(width + _gutterSize * 2, height + _gutterSize * 2))
                {
                    // рисуем фон
                    using (Graphics g = Graphics.FromImage(bmpWithGutters))
                        g.Clear(backColor);
                    int i = 0;
                    //Проверка, что вообще есть что отображать.
                    if (!ReferenceEquals(useLayers, null) && (useLayers.Length > 0))
                        do
                        {
                            IFeatureRenderer _oldFeatureRender = null;
                            try
                            {

                                //Начинаем рисовать новый слой.
                                wmsFeatureRender.BeginLayerRender();

                                //Делаем слой видимым. Все остальные слои мы отключили выше.
                                useLayers[i].Visible = true;

                                //Настройка слоя перед рендерингом.
                                if (useLayers[i] is FeatureLayer)
                                    OnPrepareRenderFeatureLayer(new PrepareRenderFeatureLayerArgs((FeatureLayer)useLayers[i]));

                                //Устанавливаем свой рендер, что бы перекрыть отрисовку названий
                                if (useLayers[i] is FeatureLayer)
                                {
                                    _oldFeatureRender = (useLayers[i] as FeatureLayer).FeatureRenderer;
                                    (useLayers[i] as FeatureLayer).FeatureRenderer = wmsFeatureRender;
                                }

                                byte[] titleInfo = null;

                                //Смотрим в кэше.
                                using (Image bmpLayer = GetImageFromChach(useLayers[i], out titleInfo, bboxWithGutters))
                                {
                                    if (!ReferenceEquals(bmpLayer, null))
                                    {
                                        //Добавляем данные о названиях в wmsFeatureRender.
                                        wmsFeatureRender.AddTitleInfo(titleInfo);
                                        //Копируем картинку в результирующий тайл.
                                        CopyImage(bmpLayer, bmpWithGutters);
                                        continue;
                                    }
                                }

                                //Если промах по кэш
                                using (
                                    Image bmpLayer = new Bitmap(width + _gutterSize * 2, height + _gutterSize * 2,
                                                                PixelFormat.Format32bppArgb))
                                {
                                    //Загружаем данные (почему это делается вне WMS сам не понимаю).

                                    OnBeforeRenderNewImage(new RenderNewImageEventArgs(bboxWithGutters,useLayers[i]));
                                    //MapAround загрузит только видимые слои, по этому не заморачиваемся на загрузки слоев по отдельности.   


                                    // рисуем карту
                                    //MapAround отрендерит только видимые слои.
                                    //Также он попытается отрендерить косметический слой, по этой причине мы проверяем выше, что бы он не был задан.
                                    _map.Render(bmpLayer, bboxWithGutters);

                                    //Копируем результат на результирующий растр.
                                    CopyImage(bmpLayer, bmpWithGutters);

                                    // Кладем в кэш растр слоя + информацию о названиях.
                                    SetImageToChach(useLayers[i], bmpLayer, wmsFeatureRender.CurrentTitleInfo, bboxWithGutters);

                                }
                            }
                            finally
                            {

                                i++;
                                //Делаем слой не видимым.
                                useLayers[i - 1].Visible = false;

                                if (useLayers[i - 1] is FeatureLayer)
                                {
                                    //Меняем рендер на старый
                                    (useLayers[i - 1] as FeatureLayer).FeatureRenderer = _oldFeatureRender;
                                }
                            }
                        } while (i < useLayers.Length);

                    //После того как получили все слои запроса рендерим названия.
                    wmsFeatureRender.RenderTitle(bmpWithGutters, bboxWithGutters);

                    //Подготавливаем и отправляем результат.
                    Image bmp = new Bitmap(width, height);                  
                     CopyImageClipped(bmp, bmpWithGutters, width, height);
                     if (cacheable)
                     {
                         SetImage(bboxWithGutters,bmp,allLayerKey);
                     }
                    return bmp;
                }
            }
            finally
            {
                // освобождаем ресурсы, связанные с рисованием карты
                if (_drawingRequestSemaphore != null)
                    _drawingRequestSemaphore.Release();
            }
        }
Exemplo n.º 11
0
        private static XmlNode getWmsLayerNode(LayerBase layer, XmlDocument doc)
        {
            XmlNode layerNode = doc.CreateNode(XmlNodeType.Element, "Layer", wmsNamespaceURI);
            layerNode.AppendChild(createElement("Name", layer.Alias, doc, false, wmsNamespaceURI));
            layerNode.AppendChild(createElement("Title", layer.Title, doc, false, wmsNamespaceURI));
            layerNode.Attributes.Append(doc.CreateAttribute("queryable")).Value = 
                layer is FeatureLayer && (layer as FeatureLayer).FeaturesSelectable ? "1" : "0";

            return layerNode;
        }
 public override void initWeights(Random r, LayerBase nextLayer)
 {
     filters.Randomize(r);
 }
Exemplo n.º 13
0
        /// <summary>
        /// Creates legend elements for the specified layer and adds it
        /// to this legend.
        /// </summary>
        /// <param name="layer">A layer which is used to generate elements</param>
        /// <param name="imagesWidth">A value specifying a width of images of the elements</param>
        /// <param name="imagesHeight">A value specifying a height of images of the elements</param>
        public void AddElementsForLayer(LayerBase layer, int imagesWidth, int imagesHeight)
        {
            FeatureLayer l = layer as FeatureLayer;
            if (l == null) return;

            if (l.LegendSettings != null)
            {
                if ((l.LegendSettings.DisplayPointSample ||
                   l.LegendSettings.DisplayPolylineSample ||
                   l.LegendSettings.DisplayPolygonSample) &&
                   l.FeatureRenderer == null)
                    throw new InvalidOperationException("Unable to add items for the layer. Undefined feature renderer.");

                if (l.LegendSettings.DisplayPointSample)
                {
                    Bitmap bmp = new Bitmap(imagesWidth, imagesHeight);
                    l.RenderFeaturesSample(bmp, true, false, false);
                    LegendElement element = new LegendElement(bmp, l.LegendSettings.PointSampleTitle);
                    CheckNewElement(element);
                    AddElement(element);
                }

                if (l.LegendSettings.DisplayPolylineSample)
                {
                    Bitmap bmp = new Bitmap(imagesWidth, imagesHeight);
                    l.RenderFeaturesSample(bmp, false, true, false);
                    LegendElement element = new LegendElement(bmp, l.LegendSettings.PolylineSampleTitle);
                    CheckNewElement(element);
                    AddElement(element);
                }

                if (l.LegendSettings.DisplayPolygonSample)
                {
                    Bitmap bmp = new Bitmap(imagesWidth, imagesHeight);
                    l.RenderFeaturesSample(bmp, false, false, true);
                    LegendElement element = new LegendElement(bmp, l.LegendSettings.PolygonSampleTitle);
                    CheckNewElement(element);
                    AddElement(element);
                }
            }
        }
Exemplo n.º 14
0
 public InstantiatedObjectData(PrefabObjectData data, LayerBase owner, GameObject instantiatedObj)
 {
     Data  = data;
     Owner = owner;
     InstantiatedObject = instantiatedObj;
 }
Exemplo n.º 15
0
        /// <summary>
        ///GetFeatureInfo request
        /// </summary>
        protected override void GetFeatureInfo(NameValueCollection requestParams, Stream responseOutputStream, ref string responseContentType)
        {
            #region Request processing GetFeatureInfo

            int x = 0, y = 0, featureCount = 1;
            int row, column;

            if (requestParams["FEATURE_COUNT"] != null)
            {
                int.TryParse(requestParams["FEATURE_COUNT"], out featureCount);
            }

            if (requestParams["I"] == null)
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                              "Required parameter I undefined.",
                              responseOutputStream,
                              ref responseContentType);
                return;
            }
            else if (!int.TryParse(requestParams["I"], out x))
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                              "Parameter I has wrong value.",
                              responseOutputStream,
                              ref responseContentType);
                return;
            }

            if (requestParams["J"] == null)
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                              "Required parameter J undefined.",
                              responseOutputStream,
                              ref responseContentType);
                return;
            }
            else if (!int.TryParse(requestParams["J"], out y))
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                              "Parameter J has wrong value.",
                              responseOutputStream,
                              ref responseContentType);
                return;
            }

            if (requestParams["TILEROW"] == null)
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                              "Required parameter TILEROW undefined.",
                              responseOutputStream,
                              ref responseContentType);
                return;
            }
            else if (!int.TryParse(requestParams["TILEROW"], out row))
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                              "Parameter TILEROW has wrong value.",
                              responseOutputStream,
                              ref responseContentType);
                return;
            }

            if (requestParams["TILECOL"] == null)
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                              "Required parameter TILECOL undefined.",
                              responseOutputStream,
                              ref responseContentType);
                return;
            }
            else if (!int.TryParse(requestParams["TILECOL"], out column))
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                              "Parameter TILECOL has wrong value.",
                              responseOutputStream,
                              ref responseContentType);
                return;
            }

            string mimeTypeNeeded = "text/html";
            if (requestParams["INFO_FORMAT"] != null)
            {
                mimeTypeNeeded = requestParams["INFO_FORMAT"];
            }

            Tile tile             = new Tile(_map, (uint)row, (uint)column);
            //_description.Tile = tile; //
            //tile.PixelSize = _description.GetScaleDenominator(_description.ZoomLevel[tileMatrixName]); //
            //tile.ScaleDenominator = _description.GetPixelSize(_description.ZoomLevel[tileMatrixName]); //
            BoundingRectangle bbox = tile.BBox;
            int width = tile.Width, height = tile.Height;

            List <FeatureLayer> queryableLayers = new List <FeatureLayer>();
            if (!string.IsNullOrEmpty(requestParams["LAYER"]))
            {
                string[] layers = requestParams["LAYER"].Split(new[] { ',' });
                foreach (string layer in layers)
                {
                    LayerBase l = null;
                    int       i;
                    for (i = 0; i < _map.Layers.Count; i++)
                    {
                        if (string.Equals(_map.Layers[i].Alias, layer,
                                          StringComparison.InvariantCultureIgnoreCase))
                        {
                            l = _map.Layers[i];
                        }
                    }


                    if (l == null)
                    {
                        WmtsException(WmtsExceptionCode.LayerNotDefined,
                                      "Layer \"" + layer + "\" not found.",
                                      responseOutputStream,
                                      ref responseContentType);
                        return;
                    }
                    else if (!(l is FeatureLayer) || !((FeatureLayer)l).FeaturesSelectable)
                    {
                        WmtsException(WmtsExceptionCode.LayerNotQueryable,
                                      "Layer \"" + layer + "\" is not queryable.",
                                      responseOutputStream,
                                      ref responseContentType);
                        return;
                    }
                    else
                    {
                        queryableLayers.Add((FeatureLayer)l);
                    }
                }

                queryableLayers.Sort(
                    (FeatureLayer l1, FeatureLayer l2) =>
                    _map.Layers.IndexOf(l1) > _map.Layers.IndexOf(l2) ? -1 : 1);

                List <Feature> selectedFeatures = new List <Feature>();

                if (queryableLayers.Count > 0)
                {
                    lock (_syncRoot)
                    {
                        // calculate the error of selection of point and line objects
                        _map.SelectionPointRadius =
                            _selectionMargin * bbox.Width / width;

                        double resultX = bbox.Width / width * x + bbox.MinX;
                        double resultY = bbox.MaxY - bbox.Height / height * y;

                        ICoordinate point = PlanimetryEnvironment.NewCoordinate(resultX, resultY);

                        ICoordinate tempPoint = PlanimetryEnvironment.NewCoordinate(x, y);

                        if (_map.OnTheFlyTransform != null)
                        {
                            ICoordinate delta =
                                PlanimetryEnvironment.NewCoordinate(tempPoint.X + _map.SelectionPointRadius,
                                                                    tempPoint.Y);
                            IMathTransform inverseTransform = _map.OnTheFlyTransform.Inverse();

                            delta =
                                PlanimetryEnvironment.NewCoordinate(inverseTransform.Transform(delta.Values()));

                            _map.SelectionPointRadius =
                                PlanimetryAlgorithms.Distance(
                                    PlanimetryEnvironment.NewCoordinate(
                                        inverseTransform.Transform(tempPoint.Values())), delta);
                        }

                        if (queryableLayers[0].Map.OnTheFlyTransform != null)
                        {
                            IMathTransform inverseTransform = queryableLayers[0].Map.OnTheFlyTransform.Inverse();
                            point =
                                PlanimetryEnvironment.NewCoordinate(inverseTransform.Transform(point.Values()));
                        }

                        foreach (LayerBase l in queryableLayers)
                        {
                            FeatureLayer fl = l as FeatureLayer;
                            if (fl != null)
                            {
                                Feature feature = null;
                                fl.SelectObject(point, out feature);
                                if (feature != null)
                                {
                                    selectedFeatures.Add(feature);
                                }

                                if (selectedFeatures.Count == featureCount)
                                {
                                    break;
                                }
                            }
                        }
                    }
                }

                WmsFeaturesInfoNeededEventArgs args = new WmsFeaturesInfoNeededEventArgs(selectedFeatures,
                                                                                         mimeTypeNeeded,
                                                                                         responseOutputStream,
                                                                                         responseContentType);
                OnFeaturesInfoNeeded(args);
                responseContentType = args.ResponseContentType;

                return;
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("none");

            byte[] bytes = Encoding.UTF8.GetBytes(sb.ToString().ToCharArray());
            responseOutputStream.Write(bytes, 0, bytes.Length);
            responseContentType = "text/html";

            #endregion
        }
Exemplo n.º 16
0
        /// <summary>
        /// Request GetTile
        /// </summary>
        private void GetTile(NameValueCollection requestParams, Stream responseOutputStream, ref string responseContentType)
        {
            #region Verify the request

            if (requestParams["LAYERS"] == null)
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                             "Required parameter LAYER not specified.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }

            if (requestParams["STYLES"] == null)
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                             "Required parameter STYLE not specified.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }

            if (requestParams["TILEMATRIXSET"] == null)
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                             "Required parameter TILEMATRIXSET not specified.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }
            
            if (requestParams["TILEMATRIX"] == null)
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                             "Required parameter TILEMATRIX not specified.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }

            if (requestParams["TILEROW"] == null)
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                             "Required parameter TILEROW not specified.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }

            if (requestParams["TILECOL"] == null)
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                             "Required parameter TILECOL not specified.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }

            if (requestParams["FORMAT"] == null)
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                             "Required parameter FORMAT not specified.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }

            #endregion

            #region Render Settings

            Color backColor = Color.FromArgb(0, 0, 0, 0);

            if (_map.CosmeticRaster.Visible)
            {
                //Cosmetic layer all broken, this does not allow its use.
                WmtsException(WmtsExceptionCode.NotApplicable,
                             "WMTS  not support this settings rendering.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }
            //Render for inscriptions.
            var wmsFeatureRender = new WmsFeatureRender(_map.RenderingSettings);

            ImageCodecInfo imageEncoder = getEncoderInfo(requestParams["FORMAT"]);
            if (imageEncoder == null)
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                             "Wrong mime-type in FORMAT parameter.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }

            int tileRow = 0;
            int tileCol = 0;
            
            if (!int.TryParse(requestParams["TILEROW"], out tileRow))
            {
                WmtsException(WmtsExceptionCode.InvalidDimensionValue,
                             "Parameter TILEROW has wrong value.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }

            if (!int.TryParse(requestParams["TILECOL"], out tileCol))
            {
                WmsException(WmsExceptionCode.InvalidDimensionValue,
                             "Parameter TILECOL has wrong value.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }

            string tileMatrixName = "EPSG:3857:0";
            if (requestParams["TILEMATRIX"] != null)
                tileMatrixName = requestParams["TILEMATRIX"];

         

            Tile tile = new Tile(_map, (uint)tileRow, (uint)tileCol);
            tile.ScaleDenominator = _description.GetScaleDenominator(_description.ZoomLevel[tileMatrixName]);
            tile.PixelSize = _description.GetPixelSize(_description.ZoomLevel[tileMatrixName]);
            tile.ZoomLevel = (uint)_description.ZoomLevel[tileMatrixName];
         
            int width = tile.Width, height = tile.Height;

            BoundingRectangle originalBbox = tile.BBox;

            if (originalBbox == null)
            {
                WmtsException(WmtsExceptionCode.NotApplicable,
                             "Wrong Tile parameters.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }

            #endregion

            //Selected by default.
            bool[] _defaultVisibility = new bool[_map.Layers.Count()];

            int j = 0;
            foreach (LayerBase layer in _map.Layers)
            {
                _defaultVisibility[j] = layer.Visible;
                layer.Visible = false; //Turning off all the layers.
                j++;
            }

            lock (_syncRoot)
            {
                LayerBase[] useLayers = null;
                int[] indexLayers = null;
                #region Checking layers of inquiry

                if (!string.IsNullOrEmpty(requestParams["LAYER"]))
                {
                    #region Getting layers of inquiry

                    string[] layers = requestParams["LAYER"].Split(new[] { ',' });
                    if (_description.LayerLimit > 0)
                    {
                        if (layers.Length == 0 && _map.Layers.Count > _description.LayerLimit ||
                            layers.Length > _description.LayerLimit)
                        {
                            WmtsException(WmtsExceptionCode.OperationNotSupported,
                                         "The number of layers in the query exceeds the limit of layers in the WMTS.",
                                         responseOutputStream,
                                         ref responseContentType);
                            return;
                        }
                    }

                    #endregion

                    useLayers = new LayerBase[layers.Length];
                    indexLayers = new int[layers.Length];
                    for (int i = 0; i < layers.Length; i++)
                    {
                        var layer = layers[i];
                        var findLayer = false;
                        for (int k = 0; k < _map.Layers.Count; k++)
                            if (string.Equals(_map.Layers[k].Alias, layer,
                                              StringComparison.InvariantCultureIgnoreCase))
                            {
                                useLayers[i] = _map.Layers[k];
                                indexLayers[i] = k;
                                findLayer = true;
                                break;
                            }


                        if (!findLayer)
                        {
                            WmtsException(WmtsExceptionCode.LayerNotDefined,
                                         "Layer \"" + layer + "\" not found.",
                                         responseOutputStream,
                                         ref responseContentType);
                            return;
                        }
                    }

                    Array.Sort(indexLayers, useLayers);
                }

                #endregion

                BoundingRectangle bboxWithGutters = (BoundingRectangle)originalBbox.Clone();
                bboxWithGutters.Grow((double)GutterSize * originalBbox.Width / (double)width);

                try
                {
                    using (Image bmp = GetImage(width, height, backColor, useLayers, bboxWithGutters))
                    {
                        EncoderParameters encoderParams = new EncoderParameters(1);
                        encoderParams.Param[0] = new EncoderParameter(
                            System.Drawing.Imaging.Encoder.Quality, (long)_imageQuality);

                        using (MemoryStream ms = new MemoryStream())
                        {
                            bmp.Save(ms, imageEncoder, encoderParams);
                            byte[] buffer = ms.ToArray();
                            responseContentType = imageEncoder.MimeType;
                            responseOutputStream.Write(buffer, 0, buffer.Length);
                        }
                    }
                }
                catch(Exception except)
                {
                    WmtsException(WmtsExceptionCode.NotApplicable, except.Message, responseOutputStream, ref responseContentType);
                    return;
                }

                for (j = 0; j < _map.Layers.Count(); j++) //Restore it as it was.
                    _map.Layers[j].Visible = _defaultVisibility[j];
            }
        }
Exemplo n.º 17
0
 private void InitializeInternal(LayerBase layer)
 {
     InitializeLayer(layer);
     InitializeDrawEngine2d();
     InitializeChanged();
     InitializeVisible();
     InitializeBounds();
 }
Exemplo n.º 18
0
        /// <summary>
        /// Получение информации о карте в формате json.
        /// </summary>       
        protected void GetVectorInfo(NameValueCollection requestParams, Stream responseOutputStream,
                                                ref string responseContentType)
        {
            responseContentType = string.Empty;

            #region Проверка общих параметров запроса

            if (requestParams["LAYERS"] == null)
            {
                WmsException(WmsExceptionCode.NotApplicable,
                             "Required parameter LAYERS not specified.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }

            if (requestParams["STYLES"] == null)
            {
                WmsException(WmsExceptionCode.NotApplicable,
                             "Required parameter STYLES not specified.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }

            if (requestParams["FORMAT"] == null)
            {
                WmsException(WmsExceptionCode.NotApplicable,
                             "Required parameter FORMAT is not specified.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }

            #endregion

            BoundingRectangle originalBbox = null;
            int width, height;
            CheckRequestParams(requestParams, responseOutputStream, ref responseContentType, out originalBbox, out width, out height);

            //Видимость по умолчанию.
            bool[] _defaultVisibility = new bool[_map.Layers.Count()];

            int j = 0;
            foreach (LayerBase layer in _map.Layers)
            {
                _defaultVisibility[j] = layer.Visible;
                layer.Visible = false; //Отключаем все слои.
                j++;
            }

            lock (_syncRoot)
            {
                LayerBase[] useLayers = null;
                int[] indexLayers = null;
                #region Проверка слоев из запроса

                if (!string.IsNullOrEmpty(requestParams["LAYERS"]))
                {
                    #region Получение слоев из запроса

                    string[] layers = requestParams["LAYERS"].Split(new[] { ',' });
                    if (_description.LayerLimit > 0)
                    {
                        if (layers.Length == 0 && _map.Layers.Count > _description.LayerLimit ||
                            layers.Length > _description.LayerLimit)
                        {
                            WmsException(WmsExceptionCode.OperationNotSupported,
                                         "The number of layers in the query exceeds the limit of layers in the WMS.",
                                         responseOutputStream,
                                         ref responseContentType);
                            return;
                        }
                    }

                    #endregion

                    useLayers = new LayerBase[layers.Length];
                    indexLayers = new int[layers.Length];
                    for (int i = 0; i < layers.Length; i++)
                    {
                        var layer = layers[i];
                        var findLayer = false;
                        for (int k = 0; k < _map.Layers.Count; k++)
                            if (string.Equals(_map.Layers[k].Alias, layer,
                                              StringComparison.InvariantCultureIgnoreCase))
                            {
                                useLayers[i] = _map.Layers[k];
                                indexLayers[i] = k;
                                findLayer = true;
                                break;
                            }


                        if (!findLayer)
                        {
                            WmsException(WmsExceptionCode.LayerNotDefined,
                                         "Layer \"" + layer + "\" not found.",
                                         responseOutputStream,
                                         ref responseContentType);
                            return;
                        }
                    }

                    Array.Sort(indexLayers, useLayers);
                }

                #endregion

                BoundingRectangle bboxWithGutters = (BoundingRectangle)originalBbox.Clone();
                bboxWithGutters.Grow((double)GutterSize * originalBbox.Width / (double)width);

                try
                {
                    for (int i = 0; i < useLayers.Count(); i++)
                    {
                        var array =
                                System.Text.UTF8Encoding.UTF8.GetBytes(GetVector(i, width, height, useLayers,
                                                                                bboxWithGutters, requestParams)); //!!! layerNumber

                        responseContentType = "application/json";
                        responseOutputStream.Write(array, 0, array.Length);
                    }
                }
                catch (Exception except)
                {
                    WmsException(WmsExceptionCode.NotApplicable, except.Message, responseOutputStream, ref responseContentType);
                    return;
                }

                for (j = 0; j < _map.Layers.Count(); j++) //Восстанавливаем все как было.
                    _map.Layers[j].Visible = _defaultVisibility[j];
            }
        }
Exemplo n.º 19
0
 /// <summary>
 /// Initializes a new instance of the MapAround.Web.Wms.RenderNewImageEventArgs.
 /// </summary>
 /// <param name="bboxWithGutters">A bounding rectangle defining the drawing area with gutters</param>
 /// <param name="layer">Layer</param>
 internal RenderNewImageEventArgs(BoundingRectangle bboxWithGutters, LayerBase layer)
 {
     _bboxWithGutters = bboxWithGutters;
     _layer = layer;
 }
Exemplo n.º 20
0
        /// <summary>
        /// Загрузка данных из кэша
        /// </summary>        
        protected Image GetImageFromChach(LayerBase layer, out byte[] titleInfo, BoundingRectangle bboxWithGutters)
        {
            titleInfo = null;
            if ((_tileCacheAccessor != null) && (layer.Cacheable)) // можно работать с кэшем
            {
                byte[] tileBytes = _tileCacheAccessor.ExtractTileBytes(layer.Alias,bboxWithGutters, getTileString(bboxWithGutters),"png");
                titleInfo = _tileCacheAccessor.ExtractTileBytes(layer.Alias, bboxWithGutters,
                                                                            getTileString(bboxWithGutters), "title");
                if ( (tileBytes != null) && (titleInfo!=null) )
                {
                    using (MemoryStream resultStream = new MemoryStream(tileBytes))
                    {

                        return Image.FromStream(resultStream);

                    }

                }
                return null;
            }
            return null;
        }
Exemplo n.º 21
0
        private void addDataProviderElement(LayerBase layer, XmlDocument doc, XmlElement layerElement)
        {
            XmlElement dataProvider = doc.CreateElement("data_provider");
            layerElement.AppendChild(dataProvider);
            addAttribute(doc, dataProvider, "registration_name", layer.DataProviderRegName);

            XmlElement parameterList = doc.CreateElement("parameters");
            dataProvider.AppendChild(parameterList);
            foreach (string s in layer.DataProviderParameters.Keys)
            {
                XmlElement parameter = doc.CreateElement("parameter");
                parameterList.AppendChild(parameter);
                addAttribute(doc, parameter, "name", s);
                addAttribute(doc, parameter, "value", layer.DataProviderParameters[s]);
            }
        }
Exemplo n.º 22
0
        /// <summary>
        ///  Сохранения данных в кэш.
        /// </summary>        
         protected void SetImageToChach(LayerBase layer, Image image, byte[] titleInfo, BoundingRectangle bboxWithGutters)
        {
            if (ReferenceEquals(_tileCacheAccessor, null)) return;
            if (!layer.Cacheable) return;
            EncoderParameters encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)_imageQuality);

            using (MemoryStream resultStream = new MemoryStream())
            {
                image.Save(resultStream, _imageCodecInfo, encoderParams);

                byte[] imageBuffer = resultStream.ToArray();
                _tileCacheAccessor.SaveTileBytes(layer.Alias, bboxWithGutters, getTileString(bboxWithGutters),  imageBuffer,"png");
                _tileCacheAccessor.SaveTileBytes(layer.Alias, bboxWithGutters, getTileString(bboxWithGutters),titleInfo,"title");
            }

        }
Exemplo n.º 23
0
 private void addAppDataElement(LayerBase layer, XmlDocument doc, XmlElement layerElement)
 {
     if (!string.IsNullOrEmpty(layer.ApplicationXmlData))
     {
         XmlElement appData = doc.CreateElement("application_data");
         appData.InnerXml = layer.ApplicationXmlData;
         layerElement.AppendChild(appData);
     }
 }
Exemplo n.º 24
0
 /// <summary>
 /// Gets a JSON object from a cache
 /// </summary>
 protected string GetJSONFromCache(LayerBase layer, NameValueCollection requestParams)
 {
     if (jsonCacheAccesor != null)
     {
         string name = layer.Alias + (requestParams.AllKeys.Contains("FEATURES") ? "withFeatures" : "");
         return jsonCacheAccesor.ExtractJSONBytes(name);
     }
     return null;
 }
Exemplo n.º 25
0
 private void processAppData(XmlNode layerNode, LayerBase l)
 {
     XmlNode appData = tryGetNodeByName(layerNode.ChildNodes, "application_data");
     if (appData != null)
         l.ApplicationXmlData = appData.InnerXml;
 }
Exemplo n.º 26
0
 /// <summary>
 /// Sets a JSON object to a cache
 /// </summary>
 protected void SetJSONToCache(LayerBase layer, string jsonObject, NameValueCollection requestParams)
 {
     if (ReferenceEquals(jsonCacheAccesor, null))
         return;
     
     string name = layer.Alias + (requestParams.AllKeys.Contains("FEATURES") ? "withFeatures" : "");
     jsonCacheAccesor.SaveJSONBytes(name, jsonObject);
 }
Exemplo n.º 27
0
 public DebugLabel(LayerBase layer)
     : base(layer)
 {
 }
Exemplo n.º 28
0
        public override void ProcessStencil(TerrainWrapper terrainWrapper, LayerBase baseLayer, int stencilKey)
        {
            var layer = baseLayer as MMTerrainLayer;

            if (layer == null)
            {
                Debug.LogWarning(string.Format("Attempted to write {0} to incorrect layer type! Expected Layer {1} to be {2}, but it was {3}", name, baseLayer.name, GetLayerType(), baseLayer.GetType()), this);
                return;
            }
            stencilKey = GetPriority();
            var objectBounds  = GetObjectBounds();
            var flatObjBounds = objectBounds.Flatten();
            var flatBounds    = flatObjBounds.ToAxisBounds();
            var terrainSize   = terrainWrapper.Terrain.terrainData.size;
            var hRes          = terrainWrapper.Terrain.terrainData.heightmapResolution;

            var matrixMin = terrainWrapper.Terrain.WorldToHeightmapCoord(flatBounds.min,
                                                                         TerrainX.RoundType.Floor);
            var matrixMax = terrainWrapper.Terrain.WorldToHeightmapCoord(flatBounds.max,
                                                                         TerrainX.RoundType.Ceil);

            matrixMin = new Common.Coord(Mathf.Clamp(matrixMin.x, 0, hRes), Mathf.Clamp(matrixMin.z, 0, hRes));
            matrixMax = new Common.Coord(Mathf.Clamp(matrixMax.x, 0, hRes), Mathf.Clamp(matrixMax.z, 0, hRes));

            var floatArraySize = new Common.Coord(matrixMax.x - matrixMin.x, matrixMax.z - matrixMin.z);


            layer.BlendMode = MMTerrainLayer.EMMTerrainLayerBlendMode.Stencil;

            if (layer.Stencil == null || layer.Stencil.Width != hRes || layer.Stencil.Height != hRes)
            {
                layer.Stencil = new Stencil(hRes, hRes);
            }
            var layerHeights = layer.GetHeights(matrixMin.x, matrixMin.z, floatArraySize.x, floatArraySize.z, hRes) ??
                               new Serializable2DFloatArray(floatArraySize.x, floatArraySize.z);

            var objectBoundsPlane = new Plane((objectBounds.Rotation * Vector3.up).normalized, objectBounds.center);

            for (var dz = 0; dz < floatArraySize.z; ++dz)
            {
                for (var dx = 0; dx < floatArraySize.x; ++dx)
                {
                    var coordX = matrixMin.x + dx;
                    var coordZ = matrixMin.z + dz;

                    int   existingStencilKey;
                    float existingStencilVal;
                    MiscUtilities.DecompressStencil(layer.Stencil[coordX, coordZ], out existingStencilKey,
                                                    out existingStencilVal);

                    var worldPos = terrainWrapper.Terrain.HeightmapCoordToWorldPos(new Common.Coord(coordX, coordZ));
                    worldPos = new Vector3(worldPos.x, objectBounds.center.y, worldPos.z);
                    if (!flatObjBounds.Contains(new Vector3(worldPos.x, flatObjBounds.center.y, worldPos.z)))
                    {
                        continue;
                    }

                    var localPos = Quaternion.Inverse(objectBounds.Rotation) * (worldPos - objectBounds.min);
                    var xDist    = localPos.x / objectBounds.size.x;
                    var zDist    = localPos.z / objectBounds.size.z;

                    float falloff = GetFalloff(new Vector2(xDist, zDist));
                    if (Mathf.Approximately(falloff, 0))
                    {
                        continue;
                    }

                    var   planeRay = new Ray(worldPos, Vector3.up);
                    float dist;

                    objectBoundsPlane.Raycast(planeRay, out dist);

                    var heightAtPoint  = (planeRay.GetPoint(dist) - terrainWrapper.transform.position).y / terrainSize.y;
                    var blendedHeight  = heightAtPoint;
                    var existingHeight = layerHeights[dx, dz];

                    if (SetHeights)
                    {
                        if (BlendMode == HeightBlendMode.Max && existingHeight > heightAtPoint)
                        {
                            layer.Stencil[matrixMin.x + dx, matrixMin.z + dz] = MiscUtilities.CompressStencil(0, 0);
                            continue;
                        }
                        if (BlendMode == HeightBlendMode.Min && existingHeight < heightAtPoint)
                        {
                            layer.Stencil[matrixMin.x + dx, matrixMin.z + dz] = MiscUtilities.CompressStencil(0, 0);
                            continue;
                        }
                    }

                    switch (BlendMode)
                    {
                    case HeightBlendMode.Set:
                        blendedHeight = Mathf.Lerp(existingHeight, blendedHeight, falloff);
                        break;

                    case HeightBlendMode.Max:
                        blendedHeight = Mathf.Max(existingHeight, blendedHeight);
                        break;

                    case HeightBlendMode.Min:
                        blendedHeight = Mathf.Min(existingHeight, blendedHeight);
                        break;

                    case HeightBlendMode.Average:
                        blendedHeight = (existingHeight + blendedHeight) / 2;
                        break;
                    }

                    layer.Stencil[matrixMin.x + dx, matrixMin.z + dz] = MiscUtilities.CompressStencil(stencilKey, 1);
                }
            }
        }
Exemplo n.º 29
0
        public override void ProcessSplats(TerrainWrapper terrainWrapper, LayerBase baseLayer, int stencilKey)
        {
            var layer = baseLayer as MMTerrainLayer;

            if (layer == null)
            {
                Debug.LogWarning(string.Format("Attempted to write {0} to incorrect layer type! Expected Layer {1} to be {2}, but it was {3}", name, baseLayer.name, GetLayerType(), baseLayer.GetType()), this);
                return;
            }
            if (!SetSplat || Splat == null || SplatStrength == 0)
            {
                return;
            }
            stencilKey = GetPriority();
            var objectBounds = GetObjectBounds();
            var aRes         = terrainWrapper.Terrain.terrainData.alphamapResolution;
            var axisBounds   = objectBounds.Flatten().ToAxisBounds();

            var matrixMin = terrainWrapper.Terrain.WorldToSplatCoord(axisBounds.min);

            matrixMin = new Common.Coord(Mathf.Clamp(matrixMin.x, 0, aRes), Mathf.Clamp(matrixMin.z, 0, aRes));

            var matrixMax = terrainWrapper.Terrain.WorldToSplatCoord(axisBounds.max);

            matrixMax = new Common.Coord(Mathf.Clamp(matrixMax.x, 0, aRes), Mathf.Clamp(matrixMax.z, 0, aRes));

            var arraySize = new Common.Coord(matrixMax.x - matrixMin.x, matrixMax.z - matrixMin.z);

            var existingSplats = layer.GetSplatMaps(matrixMin.x, matrixMin.z, arraySize.x, arraySize.z, aRes);

            for (var dx = 0; dx < arraySize.x; ++dx)
            {
                var xF = dx / (float)arraySize.x;
                for (var dz = 0; dz < arraySize.z; ++dz)
                {
                    var zF      = dz / (float)arraySize.z;
                    var falloff = GetFalloff(new Vector2(xF, zF));

                    float splatStrength = falloff * SplatStrength;
                    if (!existingSplats.ContainsKey(Splat))
                    {
                        existingSplats.Add(Splat, new Serializable2DByteArray(arraySize.x, arraySize.z));
                    }
                    var existingbaseVal = existingSplats[Splat][dx, dz] / 255f;
                    var newBaseVal      = Mathf.Max(existingbaseVal, splatStrength);
                    var writeBaseValue  = (byte)Mathf.Clamp(newBaseVal * 255, 0, 255);
                    existingSplats[Splat][dx, dz] = writeBaseValue;

                    foreach (var serializable2DByteArray in existingSplats)
                    {
                        if (serializable2DByteArray.Key == Splat)
                        {
                            continue;
                        }

                        var readValue  = serializable2DByteArray.Value[dx, dz] / 255f;
                        var newValue   = readValue * (1 - newBaseVal);
                        var writeValue = (byte)Mathf.Clamp(newValue * 255, 0, 255);
                        serializable2DByteArray.Value[dx, dz] = writeValue;
                    }
                }
            }
            foreach (var serializable2DByteArray in existingSplats)
            {
                layer.SetSplatmap(serializable2DByteArray.Key, matrixMin.x, matrixMin.z, serializable2DByteArray.Value, aRes);
            }
        }
Exemplo n.º 30
0
        public override void ProcessObjects(TerrainWrapper wrapper, LayerBase baseLayer, int stencilKey)
        {
            var layer = baseLayer as MMTerrainLayer;

            if (layer == null)
            {
                Debug.LogWarning(string.Format("Attempted to write {0} to incorrect layer type! Expected Layer {1} to be {2}, but it was {3}", name, baseLayer.name, GetLayerType(), baseLayer.GetType()), this);
                return;
            }

            if (Configuration == null || !Network)
            {
                return;
            }

            var config = Configuration.GetConfig <Config>();

            if (config == null)
            {
                Debug.LogError("Invalid config for ConnectionObjectComponent " + name, this);
                return;
            }

            if (config.Objects == null || config.Objects.Count == 0)
            {
                return;
            }

            var seed = NodeConnection.ThisNode.Seed;
            var rand = new Random(seed);

            var spline = NodeConnection.GetSpline();
            var length = spline.Length;
            var step   = config.Distance;
            var tSize  = wrapper.Terrain.terrainData.size;

            for (var i = config.InitialOffset; i < length; i += step.GetRand(rand))
            {
                var randIndex = Mathf.FloorToInt((float)rand.NextDouble() * config.Objects.Count);
                var prefab    = config.Objects[randIndex];

                var roll = (float)rand.NextDouble();
                if (roll > config.Chance)
                {
                    continue;
                }

                var offset = config.LocalOffset.GetRand(rand);
                var scale  = config.Scale.GetRand(rand);
                if (config.UniformScale)
                {
                    scale = Vector3.one * scale.x;
                }

                var uniformT     = i / length;
                var splineOffset = config.SplineOffset.GetRand(rand) * (rand.Flip() ? -1 : 1);
                var tangent      = spline.GetTangent(uniformT).normalized;
                var rotation     = Quaternion.LookRotation(tangent) * Quaternion.Euler(config.Rotation.GetRand(rand));

                var worldPos = spline.GetUniformPointOnSpline(uniformT);
                worldPos += tangent * splineOffset;
                worldPos += offset;

                if (!config.AbsoluteHeight)
                {
                    worldPos.y = offset.y;
                }

                var tPos = worldPos - wrapper.transform.position;
                tPos = new Vector3(tPos.x / tSize.x, tPos.y, tPos.z / tSize.z);

                var prefabObject = new PrefabObjectData()
                {
                    AbsoluteHeight    = config.AbsoluteHeight,
                    Guid              = Guid.NewGuid().ToString(),
                    Position          = tPos,
                    Scale             = scale,
                    Rotation          = rotation.eulerAngles,
                    Prefab            = prefab,
                    ContainerMetadata = layer.name,
                };

                layer.Objects.Add(prefabObject);
            }
        }
Exemplo n.º 31
0
 public SpriteGroup(LayerBase layer, TiledTexture tiledTexture)
     : base(layer)
 {
     InitializeCustom(tiledTexture);
 }
Exemplo n.º 32
0
        public override void ProcessSplats(TerrainWrapper wrapper, LayerBase baseLayer, int stencilKey)
        {
            var layer = baseLayer as MMTerrainLayer;

            if (layer == null)
            {
                Debug.LogWarning(string.Format("Attempted to write {0} to incorrect layer type! Expected Layer {1} to be {2}, but it was {3}", name, baseLayer.name, GetLayerType(), baseLayer.GetType()), this);
                return;
            }
            if (!Network || Configuration == null)
            {
                return;
            }
            var config = Configuration.GetConfig <Config>();

            if (config == null)
            {
                Debug.LogError("Invalid configuration! Expected ConnectionTerrainHeightConfiguration");
                return;
            }

            var terrain    = wrapper.Terrain;
            var splatRes   = wrapper.Terrain.terrainData.alphamapResolution;
            var mainSpline = NodeConnection.GetSpline();
            var radius     = config.Radius;

            // Create bounds to encapsulate spline (axis aligned)
            var bounds = mainSpline.GetApproximateBounds();

            bounds.Expand(radius * 2 * Vector3.one);

            // Create object bounds
            var objectBounds = mainSpline.GetApproximateXZObjectBounds();

            objectBounds.Expand(radius * 2 * Vector3.one);
            objectBounds.Expand(Vector3.up * 10000);

            // Early cull
            var axisBounds    = objectBounds.ToAxisBounds();
            var terrainBounds = wrapper.Terrain.GetComponent <Collider>().bounds;

            if (!terrainBounds.Intersects(axisBounds))
            {
                return;
            }

            float planeGive = -(wrapper.Terrain.terrainData.size.x / wrapper.Terrain.terrainData.alphamapResolution) * SplatOffset;
            Plane startPlane, endPlane;

            GenerateSplinePlanes(planeGive, mainSpline, out startPlane, out endPlane);

            // Get matrix space min/max
            var matrixMin = terrain.WorldToSplatCoord(bounds.min, TerrainX.RoundType.Floor);
            var matrixMax = terrain.WorldToSplatCoord(bounds.max, TerrainX.RoundType.Ceil);

            matrixMin = new Common.Coord(Mathf.Clamp(matrixMin.x, 0, terrain.terrainData.alphamapResolution), Mathf.Clamp(matrixMin.z, 0, terrain.terrainData.alphamapResolution));
            matrixMax = new Common.Coord(Mathf.Clamp(matrixMax.x, 0, terrain.terrainData.alphamapResolution), Mathf.Clamp(matrixMax.z, 0, terrain.terrainData.alphamapResolution));

            var floatArraySize = new Common.Coord(matrixMax.x - matrixMin.x, matrixMax.z - matrixMin.z);

            // Get all the existing compound splats
            var currentPrototypes = wrapper.GetCompoundSplatPrototypes(layer, true);
            var baseData          = layer.GetSplatMaps(matrixMin.x, matrixMin.z, floatArraySize.x, floatArraySize.z, splatRes);

            stencilKey = GetStencilKey();
            Serializable2DFloatArray thisPatchStencil = new Serializable2DFloatArray(floatArraySize.x,
                                                                                     floatArraySize.z);

            foreach (var splatConfiguration in config.SplatConfigurations)
            {
                var splatPrototypeWrapper = splatConfiguration.SplatPrototype;
                Serializable2DByteArray baseLayerSplat;
                if (!baseData.TryGetValue(splatPrototypeWrapper, out baseLayerSplat))
                {
                    baseLayerSplat = new Serializable2DByteArray(floatArraySize.x, floatArraySize.z);
                    baseData[splatPrototypeWrapper] = baseLayerSplat;
                }

                for (var dz = 0; dz < floatArraySize.z; ++dz)
                {
                    for (var dx = 0; dx < floatArraySize.x; ++dx)
                    {
                        var coordX   = matrixMin.x + dx;
                        var coordZ   = matrixMin.z + dz;
                        var worldPos = terrain.SplatCoordToWorldPos(new Common.Coord(coordX, coordZ));
                        worldPos = new Vector3(worldPos.x, objectBounds.center.y, worldPos.z);

                        if (terrain.ContainsPointXZ(worldPos) &&
                            objectBounds.Contains(worldPos) &&
                            GeometryExtensions.BetweenPlanes(worldPos, startPlane, endPlane))
                        {
                            var uniformT                   = mainSpline.GetClosestUniformTimeOnSplineXZ(worldPos.xz()); // Expensive!
                            var closestOnSpline            = mainSpline.GetUniformPointOnSpline(uniformT);
                            var normalizedFlatDistToSpline = (worldPos - closestOnSpline).xz().magnitude / (config.Radius);
                            if (normalizedFlatDistToSpline != Mathf.Clamp01(normalizedFlatDistToSpline))
                            {
                                continue;
                            }
                            var maskValue       = config.SplatFalloff.Evaluate(normalizedFlatDistToSpline);
                            var writeFloatValue = splatConfiguration.SplatStrength * maskValue;
                            var writeValue      = (byte)Mathf.RoundToInt(Mathf.Clamp(writeFloatValue * 255f, 0, 255));
                            var mainRead        = baseLayerSplat[dx, dz];
                            var newVal          = (byte)Mathf.Clamp(Mathf.Max(writeValue, mainRead), 0, 255);
                            var delta           = newVal - mainRead;

                            if (delta < 1 / 255f)
                            {
                                continue;
                            }

                            foreach (var currentPrototype in currentPrototypes)
                            {
                                if (!baseData.ContainsKey(currentPrototype))
                                {
                                    continue;
                                }
                                if (currentPrototype == splatPrototypeWrapper)
                                {
                                    continue;
                                }
                                var otherSplatFloatValue    = baseData[currentPrototype][dx, dz] / 255f;
                                var otherSplatFloatWriteVal = (otherSplatFloatValue * (1 - (delta / 255f)));
                                var write = (byte)Mathf.Clamp(Mathf.RoundToInt(otherSplatFloatWriteVal * 255), 0, 255);
                                baseData[currentPrototype][dx, dz] = write;
                            }
                            //DebugHelper.DrawPoint(worldPos, 1, Color.red, 10);
                            baseLayerSplat[dx, dz]        = newVal;
                            layer.Stencil[coordX, coordZ] = MiscUtilities.CompressStencil(stencilKey, 1);
                            thisPatchStencil[dx, dz]      = 1;
                        }
                        else
                        {
                            thisPatchStencil[dx, dz] = 0;
                        }
                    }
                }
            }

            foreach (var existingSplatPrototype in baseData)
            {
                var splat = existingSplatPrototype.Key;
                var data  = existingSplatPrototype.Value;
                layer.SetSplatmap(splat, matrixMin.x, matrixMin.z, data, wrapper.Terrain.terrainData.alphamapResolution, thisPatchStencil);
            }
        }
Exemplo n.º 33
0
 private void CleanupLayer()
 {
     Layer.RemoveDrawable(this);
     Layer = null;
 }
Exemplo n.º 34
0
 public override ILayer Clone() => LayerBase.CopyWith(this, new GeometryStarLayer
 {
     Points      = this.Points,
     InnerRadius = this.InnerRadius,
 });
Exemplo n.º 35
0
 private void InitializeLayer(LayerBase layer)
 {
     Layer = layer;
     Layer.AddDrawable(this);
 }
Exemplo n.º 36
0
 public override ILayer Clone() => LayerBase.CopyWith(this, new PatternDiagonalLayer
 {
     Offset         = this.Offset,
     HorizontalStep = this.HorizontalStep,
 });
Exemplo n.º 37
0
        private void GetMap(NameValueCollection requestParams, Stream responseOutputStream, ref string responseContentType)
        {
            #region Verify the request

            if (requestParams["LAYERS"] == null)
            {
                WmsException(WmsExceptionCode.NotApplicable,
                             "Required parameter LAYERS not specified.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }
            if (requestParams["STYLES"] == null)
            {
                WmsException(WmsExceptionCode.NotApplicable,
                             "Required parameter STYLES not specified.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }
            if (requestParams["SRS"] == null)
            {
                WmsException(WmsExceptionCode.NotApplicable,
                             "Required parameter SRS not specified.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }
            else
            {
                string authCode = "EPSG:-1";
                if (!string.IsNullOrEmpty(_map.CoodrinateSystemWKT))
                {
                    IInfo coordinateSystem =
                        CoordinateSystemWktDeserializer.Parse(_map.CoodrinateSystemWKT);
                    authCode = coordinateSystem.Authority + ":" + coordinateSystem.AuthorityCode.ToString();
                }

                if (requestParams["SRS"] != authCode)
                {
                    WmsException(WmsExceptionCode.InvalidSRS,
                                 "SRS is not supported",
                                 responseOutputStream,
                                 ref responseContentType);
                    return;
                }
            }
            if (requestParams["BBOX"] == null)
            {
                WmsException(WmsExceptionCode.InvalidDimensionValue,
                             "Required parameter BBOX not specified.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }
            if (requestParams["WIDTH"] == null)
            {
                WmsException(WmsExceptionCode.InvalidDimensionValue,
                             "Required parameter WIDTH not specified.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }
            if (requestParams["HEIGHT"] == null)
            {
                WmsException(WmsExceptionCode.InvalidDimensionValue,
                             "Required parameter HEIGHT not specified.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }
            if (requestParams["FORMAT"] == null)
            {
                WmsException(WmsExceptionCode.NotApplicable,
                             "Required parameter FORMAT not specified.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }

            #endregion

            #region Render Settings

            Color backColor = Color.White;

            if (_map.CosmeticRaster.Visible)
            {
                //Cosmetic layer all broken, this does not allow its use.
                WmsException(WmsExceptionCode.NotApplicable,
                             "WMS  not support this settings rendering.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }
            

            if (string.Compare(requestParams["TRANSPARENT"], "TRUE", _ignoreCase) == 0)
                backColor = Color.Transparent;
            else if (requestParams["BGCOLOR"] != null)
            {
                try
                {
                    backColor = ColorTranslator.FromHtml("#" + requestParams["BGCOLOR"]);
                }
                catch
                {
                    WmsException(WmsExceptionCode.NotApplicable,
                                 "Parameter BGCOLOR has wrong value.",
                                 responseOutputStream,
                                 ref responseContentType);
                    return;
                }
            }


            ImageCodecInfo imageEncoder = getEncoderInfo(requestParams["FORMAT"]);
            if (imageEncoder == null)
            {
                WmsException(WmsExceptionCode.NotApplicable,
                             "Wrong mime-type in FORMAT parameter.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }


            int width = 0;
            int height = 0;

            if (!int.TryParse(requestParams["WIDTH"], out width))
            {
                WmsException(WmsExceptionCode.InvalidDimensionValue,
                             "Parameter WIDTH has wrong value.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }
            else if (_description.MaxWidth > 0 && width > _description.MaxWidth)
            {
                WmsException(WmsExceptionCode.OperationNotSupported,
                             "WIDTH parameter value is too large.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }
            if (!int.TryParse(requestParams["HEIGHT"], out height))
            {
                WmsException(WmsExceptionCode.InvalidDimensionValue,
                             "Parameter HEIGHT has wrong value.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }
            else if (_description.MaxHeight > 0 && height > _description.MaxHeight)
            {
                WmsException(WmsExceptionCode.OperationNotSupported,
                             "HEIGHT parameter value is too large.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }

            BoundingRectangle originalBbox = ParseBbox(requestParams["bbox"]);
            if (originalBbox == null)
            {
                WmsException(WmsExceptionCode.NotApplicable,
                             "Wrong BBOX parameter.",
                             responseOutputStream,
                             ref responseContentType);
                return;
            }

            #endregion

            //Selected by default.
            bool[] _defaultVisibility = new bool[_map.Layers.Count()];

            int j = 0;
            foreach (LayerBase layer in _map.Layers)
            {
                _defaultVisibility[j] = layer.Visible;
                layer.Visible = false; //Turning off all the layers.
                j++;
            }

            lock (_syncRoot)
            {
                LayerBase[] useLayers = null;
                int[] indexLayers = null;
                #region Checking layers of inquiry

                if (!string.IsNullOrEmpty(requestParams["LAYERS"]))
                {
                    #region Getting layers of inquiry

                    string[] layers = requestParams["LAYERS"].Split(new[] { ',' });
                    if (_description.LayerLimit > 0)
                    {
                        if (layers.Length == 0 && _map.Layers.Count > _description.LayerLimit ||
                            layers.Length > _description.LayerLimit)
                        {
                            WmsException(WmsExceptionCode.OperationNotSupported,
                                         "The number of layers in the query exceeds the limit of layers in the WMS.",
                                         responseOutputStream,
                                         ref responseContentType);
                            return;
                        }
                    }

                    #endregion

                    useLayers = new LayerBase[layers.Length];
                    indexLayers = new int[layers.Length];
                    for (int i = 0; i < layers.Length; i++)
                    {
                        var layer = layers[i];
                        var findLayer = false;
                        for (int k = 0; k < _map.Layers.Count; k++)
                            if (string.Equals(_map.Layers[k].Alias, layer,
                                              StringComparison.InvariantCultureIgnoreCase))
                            {
                                useLayers[i] = _map.Layers[k];
                                indexLayers[i] = k;
                                findLayer = true;
                                break;
                            }


                        if (!findLayer)
                        {
                            WmsException(WmsExceptionCode.LayerNotDefined,
                                         "Layer \"" + layer + "\" not found.",
                                         responseOutputStream,
                                         ref responseContentType);
                            return;
                        }
                    }

                    Array.Sort(indexLayers, useLayers);
                }

                #endregion

                BoundingRectangle bboxWithGutters = (BoundingRectangle)originalBbox.Clone();
                bboxWithGutters.Grow((double)GutterSize * originalBbox.Width / (double)width);

                try
                {
                    using (Image bmp = GetImage(width, height, backColor, useLayers, bboxWithGutters))
                    {
                        EncoderParameters encoderParams = new EncoderParameters(1);
                        encoderParams.Param[0] = new EncoderParameter(
                            System.Drawing.Imaging.Encoder.Quality, (long)_imageQuality);

                        using (MemoryStream ms = new MemoryStream())
                        {
                            bmp.Save(ms, imageEncoder, encoderParams);
                            byte[] buffer = ms.ToArray();
                            responseContentType = imageEncoder.MimeType;
                            responseOutputStream.Write(buffer, 0, buffer.Length);
                        }
                    }
                }
                catch(Exception except)
                {
                    WmsException(WmsExceptionCode.NotApplicable, except.Message, responseOutputStream, ref responseContentType);
                    return;
                }

                for (j = 0; j < _map.Layers.Count(); j++) // Restore everything as it was.
                    _map.Layers[j].Visible = _defaultVisibility[j];
            }
        }
Exemplo n.º 38
0
 internal void InitializeLayer(LayerBase layer)
 {
     layer.AttachToPanel(this.panel);
     layer.Owner = this;
 }
Exemplo n.º 39
0
 public Triangle(LayerBase layer)
     : base(layer)
 {
 }
Exemplo n.º 40
0
        public override void ProcessTrees(TerrainWrapper wrapper, LayerBase baseLayer, int stencilKey)
        {
            var layer = baseLayer as MMTerrainLayer;

            if (layer == null)
            {
                Debug.LogWarning(string.Format("Attempted to write {0} to incorrect layer type! Expected Layer {1} to be {2}, but it was {3}", name, baseLayer.name, GetLayerType(), baseLayer.GetType()), this);
                return;
            }

            if (!Network || Configuration == null)
            {
                return;
            }
            var config = Configuration.GetConfig <Config>();

            if (config == null)
            {
                Debug.LogError("Invalid configuration! Expected ConnectionTerrainHeightConfiguration");
                return;
            }

            var mainSpline = NodeConnection.GetSpline();
            var radius     = config.TreeRemoveDistance;

            // Create bounds to encapsulate spline (axis aligned)
            var bounds = mainSpline.GetApproximateBounds();

            bounds.Expand(radius * 2 * Vector3.one);

            // Create object bounds
            var objectBounds = mainSpline.GetApproximateXZObjectBounds();

            objectBounds.Expand(radius * 2 * Vector3.one);
            objectBounds.Expand(Vector3.up * 10000);

            var flatCullbounds = objectBounds.ToAxisBounds();
            //DebugHelper.DrawCube(flatCullbounds.center, flatCullbounds.extents, Quaternion.identity, Color.yellow, 20);
            //DebugHelper.DrawCube(objectBounds.center, objectBounds.extents, objectBounds.Rotation, Color.cyan, 20);

            Plane startPlane, endPlane;

            GenerateSplinePlanes(0, mainSpline, out startPlane, out endPlane);

            var trees       = wrapper.GetCompoundTrees(layer, true, flatCullbounds);
            int removeCount = 0;

            for (int i = trees.Count - 1; i >= 0; i--)
            {
                var treeInstance = trees[i];
                var wPos         = wrapper.Terrain.TreeToWorldPos(treeInstance.Position);
                if (!objectBounds.Contains(wPos) || !GeometryExtensions.BetweenPlanes(wPos, startPlane, endPlane))
                {
                    continue;
                }

                var ut        = mainSpline.GetClosestUniformTimeOnSplineXZ(wPos.xz());
                var splinePos = mainSpline.GetUniformPointOnSpline(ut);
                var d         = splinePos.xz() - wPos.xz();

                if (d.sqrMagnitude < config.TreeRemoveDistance * config.TreeRemoveDistance && !layer.TreeRemovals.Contains(treeInstance.Guid))
                {
                    layer.TreeRemovals.Add(treeInstance.Guid);
                    removeCount++;
                }
            }
            //Debug.Log(string.Format("{0} removed {1} trees.", this, removeCount), this);
        }