コード例 #1
0
ファイル: SetupOp.cs プロジェクト: PDXBES/AutoDelineator
        private void _DisposeTempDatasets()
        {
            try
            {
                foreach (IDataset dataset in _tempDatasets)
                {
                    if (dataset != null)
                    {
                        try
                        {
                            dataset.Delete();

                            UrbanDelineationExtension.ReleaseComObject(dataset);
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine("SetupOp: " + ex.GetType().FullName + ": " + ex.Message);
                        }
                    }
                }
            }
            finally
            {
                _tempDatasets.Clear();
            }
        }
コード例 #2
0
        private void _CheckLayer(ILayer layer, List <ComboBoxItem> geometricNetworks, List <ComboBoxItem> junctionLayers, List <ComboBoxItem> rasterLayers, List <ComboBoxItem> polygonLayers)
        {
            bool layerUsed = false;

            if (layer is IGroupLayer && layer is ICompositeLayer)
            {
                ICompositeLayer groupLayer = (ICompositeLayer)layer;
                int             layerCount = groupLayer.Count;
                for (int i = 0; i < layerCount; i++)
                {
                    ILayer subLayer = groupLayer.get_Layer(i);
                    _CheckLayer(subLayer, geometricNetworks, junctionLayers, rasterLayers, polygonLayers);
                }
            }
            else if (layer is IFeatureLayer)
            {
                if (((IFeatureLayer)layer).FeatureClass != null)
                {
                    if (((IFeatureLayer)layer).FeatureClass is INetworkClass)
                    {
                        _AddNetworkForLayer(layer, geometricNetworks);

                        INetworkClass networkClass = (INetworkClass)((IFeatureLayer)layer).FeatureClass;
                        if (networkClass.FeatureType == esriFeatureType.esriFTSimpleJunction)
                        {
                            junctionLayers.Add(new ComboBoxItem()
                            {
                                Name = layer.Name, Value = layer
                            });
                            layerUsed = true;
                        }
                    }

                    if (((IFeatureLayer)layer).FeatureClass.ShapeType == esriGeometryType.esriGeometryPolygon)
                    {
                        polygonLayers.Add(new ComboBoxItem()
                        {
                            Name = layer.Name, Value = layer
                        });
                        layerUsed = true;
                    }
                }
            }
            else if (layer is IRasterLayer && ((IRasterLayer)layer).BandCount == 1)
            {
                if (((IRasterLayer)layer).Raster != null)
                {
                    rasterLayers.Add(new ComboBoxItem()
                    {
                        Name = layer.Name, Value = layer
                    });
                    layerUsed = true;
                }
            }

            if (!layerUsed)
            {
                UrbanDelineationExtension.ReleaseComObject(layer);
            }
        }
コード例 #3
0
ファイル: SetupOp.cs プロジェクト: PDXBES/AutoDelineator
        private void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    //Managed classes
                }

                //Unmanaged classes
                _DisposeTempDatasets();

                UrbanDelineationExtension.ReleaseComObject(_geometricNetwork);
                _geometricNetwork = null;
                UrbanDelineationExtension.ReleaseComObject(_inletClass);
                _inletClass = null;
                UrbanDelineationExtension.ReleaseComObject(_dem);
                _dem = null;
                UrbanDelineationExtension.ReleaseComObject(_punchedDEM);
                _punchedDEM = null;
                UrbanDelineationExtension.ReleaseComObject(_filledDEM);
                _filledDEM = null;
                UrbanDelineationExtension.ReleaseComObject(_flowDir);
                _flowDir = null;
                UrbanDelineationExtension.ReleaseComObject(_drainClass);
                _drainClass = null;
                UrbanDelineationExtension.ReleaseComObject(_catchmentClass);
                _catchmentClass = null;

                _disposed = true;
            }
        }
コード例 #4
0
ファイル: SetupOp.cs プロジェクト: iluckyyang/AutoDelineator
        private void _CalculateFlowDir()
        {
            OnProgress("Filling DEM...");

            // - Fill & calculate flow direction
            IHydrologyOp   hydroOp         = new RasterHydrologyOpClass();
            IRasterMakerOp rasterMaker     = new RasterMakerOpClass();
            ILogicalOp     logicalOp       = new RasterMathOpsClass();
            IConditionalOp conditionalOp   = new RasterConditionalOpClass();
            IGeoDataset    fillTemp        = null;
            IGeoDataset    flowTemp        = null;
            IGeoDataset    flowTemp2       = null;
            IGeoDataset    demNulls        = null;
            IGeoDataset    zeroRaster      = null;
            IWorkspace     resultWorkspace = null;

            try
            {
                SetAnalysisEnvironment((IRasterAnalysisEnvironment)hydroOp);
                SetAnalysisEnvironment((IRasterAnalysisEnvironment)rasterMaker);
                SetAnalysisEnvironment((IRasterAnalysisEnvironment)conditionalOp);
                SetAnalysisEnvironment((IRasterAnalysisEnvironment)logicalOp);

                object zLimit = null;
                fillTemp = hydroOp.Fill((IGeoDataset)_punchedDEM, ref zLimit);

                //Make output permanent
                resultWorkspace = GetResultRasterWorkspace();
                ITemporaryDataset tempFillDataset = ((IRasterAnalysisProps)fillTemp).RasterDataset as ITemporaryDataset;
                string            fillPath        = CreateTempFileName(_GetResultDir(), "filldem", "");
                string            fillFileName    = System.IO.Path.GetFileName(fillPath);
                tempFillDataset.MakePermanentAs(fillFileName, resultWorkspace, "GRID");
                _filledDEM = ((IRasterWorkspace)resultWorkspace).OpenRasterDataset(fillFileName).CreateDefaultRaster() as IRaster;

                OnProgress("Calculating flow direction...");
                flowTemp = hydroOp.FlowDirection((IGeoDataset)fillTemp, false, true);

                //Set holes to flowdir of 0
                object boxedFlowTemp = flowTemp;
                zeroRaster = rasterMaker.MakeConstant(0.0, true);
                flowTemp2  = conditionalOp.Con(logicalOp.IsNull((IGeoDataset)fillTemp), zeroRaster, ref boxedFlowTemp);
                demNulls   = logicalOp.IsNull((IGeoDataset)_dem);
                string flowPath = CreateTempFileName(_GetResultDir(), "flowdir", "");
                _flowDir = GeoprocessingTools.SetNull((IRaster)demNulls, (IRaster)flowTemp2, flowPath);
            }
            finally
            {
                UrbanDelineationExtension.ReleaseComObject(flowTemp);
                UrbanDelineationExtension.ReleaseComObject(flowTemp2);
                UrbanDelineationExtension.ReleaseComObject(demNulls);
                UrbanDelineationExtension.ReleaseComObject(zeroRaster);
                UrbanDelineationExtension.ReleaseComObject(conditionalOp);
                UrbanDelineationExtension.ReleaseComObject(logicalOp);
                UrbanDelineationExtension.ReleaseComObject(rasterMaker);
                UrbanDelineationExtension.ReleaseComObject(hydroOp);
                UrbanDelineationExtension.ReleaseComObject(resultWorkspace);
            }

            OnProgress("Flow direction calculated.");
        }
コード例 #5
0
        private void _CheckLayer(ILayer layer, List <ComboBoxItem> featureLayers)
        {
            bool layerUsed = false;

            if (layer is IGroupLayer && layer is ICompositeLayer)
            {
                ICompositeLayer groupLayer = (ICompositeLayer)layer;
                int             layerCount = groupLayer.Count;
                for (int i = 0; i < layerCount; i++)
                {
                    ILayer subLayer = groupLayer.get_Layer(i);
                    _CheckLayer(subLayer, featureLayers);
                }
            }
            else if (layer is IFeatureLayer)
            {
                if (((IFeatureLayer)layer).FeatureClass != null)
                {
                    featureLayers.Add(new ComboBoxItem()
                    {
                        Name = layer.Name, Value = layer
                    });
                    layerUsed = true;
                }
            }

            if (!layerUsed)
            {
                UrbanDelineationExtension.ReleaseComObject(layer);
            }
        }
コード例 #6
0
        private void _AddNetworkForLayer(ILayer layer, List <ComboBoxItem> geometricNetworks)
        {
            IFeatureLayer featureLayer = (IFeatureLayer)layer;
            INetworkClass networkClass = (INetworkClass)featureLayer.FeatureClass;

            try
            {
                IGeometricNetwork network = networkClass.GeometricNetwork;
                bool alreadyAdded         = false;
                foreach (ComboBoxItem element in geometricNetworks)
                {
                    if (element.Value == network)
                    {
                        alreadyAdded = true;
                        break;
                    }
                }
                if (!alreadyAdded)
                {
                    geometricNetworks.Add(new ComboBoxItem()
                    {
                        Name = ((IDataset)network).Name, Value = network
                    });
                }
            }
            finally
            {
                UrbanDelineationExtension.ReleaseComObject(networkClass);
            }
        }
コード例 #7
0
        private List <ILayer> _GetLayers(IMxDocument mxDocument)
        {
            List <ILayer> layers = new List <ILayer>();

            if (mxDocument != null)
            {
                IMap map = null;
                try
                {
                    map = mxDocument.FocusMap;
                    for (int i = 0; i < map.LayerCount; i++)
                    {
                        ILayer pLayer = map.get_Layer(i);
                        if (pLayer is ICompositeLayer)
                        {
                            _AddSubLayers((ICompositeLayer)pLayer, layers);
                        }
                        else
                        {
                            layers.Add(pLayer);
                        }
                    }
                }
                finally
                {
                    UrbanDelineationExtension.ReleaseComObject(map);
                }
            }

            return(layers);
        }
コード例 #8
0
        private void _UpdateComboBoxes()
        {
            _updatingLayers = true;
            try
            {
                List <ComboBoxItem> featureLayers = new List <ComboBoxItem>();

                if (_document != null)
                {
                    featureLayers.Add(new ComboBoxItem()
                    {
                        Name = Properties.Resources.Use_Selected_Nodes, Value = null
                    });

                    IMap focusMap = _document.FocusMap;
                    try
                    {
                        int layerCount = focusMap.LayerCount;
                        for (int i = 0; i < layerCount; i++)
                        {
                            ILayer layer = focusMap.get_Layer(i);
                            _CheckLayer(layer, featureLayers);
                        }
                    }
                    finally
                    {
                        UrbanDelineationExtension.ReleaseComObject(focusMap);
                    }
                }

                _UpdateCombobox(cbxOutletSource, featureLayers);

                if (UrbanDelineationForm.LastOutletSource != null)
                {
                    cbxOutletSource.SelectedValue = UrbanDelineationForm.LastOutletSource;
                }

                if (cbxOutletSource.SelectedValue != UrbanDelineationForm.LastOutletSource)
                {
                    cbxOutletSource.SelectedIndex         = 0;
                    UrbanDelineationForm.LastOutletSource = cbxOutletSource.SelectedValue as IFeatureLayer;
                }

                _UpdateOutletFields();
            }
            finally
            {
                _updatingLayers = false;
            }
        }
コード例 #9
0
        private void _UpdateComboBoxes()
        {
            List <ComboBoxItem> geometricNetworks = new List <ComboBoxItem>();
            List <ComboBoxItem> junctionLayers    = new List <ComboBoxItem>();
            List <ComboBoxItem> rasterLayers      = new List <ComboBoxItem>();
            List <ComboBoxItem> polygonLayers     = new List <ComboBoxItem>();

            if (_document != null)
            {
                geometricNetworks.Add(new ComboBoxItem()
                {
                    Name = Properties.Resources.No_Selection, Value = null
                });
                junctionLayers.Add(new ComboBoxItem()
                {
                    Name = Properties.Resources.No_Selection, Value = null
                });
                rasterLayers.Add(new ComboBoxItem()
                {
                    Name = Properties.Resources.No_Selection, Value = null
                });
                polygonLayers.Add(new ComboBoxItem()
                {
                    Name = Properties.Resources.No_Selection, Value = null
                });

                IMap focusMap = _document.FocusMap;
                try
                {
                    int layerCount = focusMap.LayerCount;
                    for (int i = 0; i < layerCount; i++)
                    {
                        ILayer layer = focusMap.get_Layer(i);
                        _CheckLayer(layer, geometricNetworks, junctionLayers, rasterLayers, polygonLayers);
                    }
                }
                finally
                {
                    UrbanDelineationExtension.ReleaseComObject(focusMap);
                }
            }

            _UpdateCombobox(cbxNetwork, geometricNetworks);
            _UpdateCombobox(cbxInlets, junctionLayers);
            _UpdateCombobox(cbxDEM, rasterLayers);
            _UpdateCombobox(cbxFlowDirGrid, rasterLayers);
            _UpdateCombobox(cbxCatchments, polygonLayers);
        }
コード例 #10
0
ファイル: SetupOp.cs プロジェクト: PDXBES/AutoDelineator
        private void _CalculateFlowDir()
        {
            OnProgress("Filling DEM...");

            // - Fill & calculate flow direction
            IHydrologyOp   hydroOp     = new RasterHydrologyOpClass();
            IRasterMakerOp rasterMaker = new RasterMakerOpClass();
            ILogicalOp     logicalOp   = new RasterMathOpsClass();
            IGeoDataset    flowTemp    = null;
            IRaster        flowTemp2   = null;
            IGeoDataset    demNulls    = null;
            IGeoDataset    zeroRaster  = null;

            try
            {
                SetAnalysisEnvironment((IRasterAnalysisEnvironment)hydroOp);
                SetAnalysisEnvironment((IRasterAnalysisEnvironment)rasterMaker);
                SetAnalysisEnvironment((IRasterAnalysisEnvironment)logicalOp);

                string fillPath = CreateTempFileName(_GetResultDir(), "filldem", "");
                _filledDEM = GeoprocessingTools.Fill(_punchedDEM, fillPath);

                OnProgress("Calculating flow direction...");
                flowTemp = hydroOp.FlowDirection((IGeoDataset)_filledDEM, false, true);

                //Set holes to flowdir of 0
                zeroRaster = rasterMaker.MakeConstant(0.0, true);
                string flowTemp2Path = CreateTempFileName(_GetTempDir(), "flowtemp2", "");
                flowTemp2 = GeoprocessingTools.Con((IRaster)logicalOp.IsNull((IGeoDataset)_filledDEM), (IRaster)zeroRaster, (IRaster)flowTemp, flowTemp2Path);
                demNulls  = logicalOp.IsNull((IGeoDataset)_dem);
                string flowPath = CreateTempFileName(_GetResultDir(), "flowdir", "");
                _flowDir = GeoprocessingTools.SetNull((IRaster)demNulls, flowTemp2, flowPath);
            }
            finally
            {
                UrbanDelineationExtension.ReleaseComObject(flowTemp);
                UrbanDelineationExtension.ReleaseComObject(flowTemp2);
                UrbanDelineationExtension.ReleaseComObject(demNulls);
                UrbanDelineationExtension.ReleaseComObject(zeroRaster);
                UrbanDelineationExtension.ReleaseComObject(logicalOp);
                UrbanDelineationExtension.ReleaseComObject(rasterMaker);
                UrbanDelineationExtension.ReleaseComObject(hydroOp);
            }

            OnProgress("Flow direction calculated.");
        }
コード例 #11
0
ファイル: SetupOp.cs プロジェクト: PDXBES/AutoDelineator
        internal IFeatureClass RasterToPolygon(IRaster inputRaster, string outputName, string outputDir, bool smoothShapes)
        {
            IWorkspace    workspace    = SetupOp.OpenShapeFileWorkspace(outputDir);
            IConversionOp conversionOp = new RasterConversionOpClass();

            try
            {
                IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace;

                //Delete any existing
                IEnumDatasetName datasets = workspace.get_DatasetNames(esriDatasetType.esriDTFeatureClass);
                datasets.Reset();
                IDataset     existing    = null;
                IDatasetName datasetName = datasets.Next();
                while (datasetName != null)
                {
                    if (string.Compare(outputName, datasetName.Name, true) == 0)
                    {
                        existing = (IDataset)((IName)datasetName).Open();
                        break;
                    }
                    datasetName = datasets.Next();
                }
                if (existing != null)
                {
                    try
                    {
                        existing.Delete();
                    }
                    finally
                    {
                        UrbanDelineationExtension.ReleaseComObject(existing);
                    }
                }

                //Convert to polygon feature
                SetAnalysisEnvironment((IRasterAnalysisEnvironment)conversionOp);
                IGeoDataset polygons = conversionOp.RasterDataToPolygonFeatureData((IGeoDataset)inputRaster, workspace, outputName, smoothShapes);
                return((IFeatureClass)polygons);
            }
            finally
            {
                UrbanDelineationExtension.ReleaseComObject(workspace);
                UrbanDelineationExtension.ReleaseComObject(conversionOp);
            }
        }
コード例 #12
0
ファイル: SetupOp.cs プロジェクト: PDXBES/AutoDelineator
        private void _PunchDEM()
        {
            OnProgress("Punching DEM with drainage points...");

            IConversionOp conversionOp   = new RasterConversionOpClass();
            ILogicalOp    logicalOp      = new RasterMathOpsClass();
            IGeoDataset   inletLocations = null;
            IWorkspace    tempWorkspace  = null;

            try
            {
                tempWorkspace = GetTempRasterWorkspace();

                SetAnalysisEnvironment((IRasterAnalysisEnvironment)conversionOp);
                SetAnalysisEnvironment((IRasterAnalysisEnvironment)logicalOp);

                IFeatureClassDescriptor sourceDescriptor = new FeatureClassDescriptorClass();
                sourceDescriptor.Create(_drainClass, null, _drainClass.OIDFieldName);
                string gridPath = SetupOp.CreateTempFileName(_GetTempDir(), "TmpInlets", null);
                string gridName = System.IO.Path.GetFileName(gridPath);

                IRasterDataset pRasterDataset = null;
                try
                {
                    pRasterDataset = conversionOp.ToRasterDataset((IGeoDataset)sourceDescriptor, "GRID", tempWorkspace, gridName);
                    inletLocations = logicalOp.BooleanNot(logicalOp.IsNull((IGeoDataset)pRasterDataset));
                    string outputPath = CreateTempFileName(_GetResultDir(), "punchdem", "");
                    _punchedDEM = GeoprocessingTools.SetNull((IRaster)inletLocations, _dem, outputPath);
                }
                finally
                {
                    _MarkForDisposal((IDataset)pRasterDataset);
                }
            }
            finally
            {
                UrbanDelineationExtension.ReleaseComObject(tempWorkspace);
                UrbanDelineationExtension.ReleaseComObject(conversionOp);
                UrbanDelineationExtension.ReleaseComObject(logicalOp);
            }

            OnProgress("DEM punched.");
        }
コード例 #13
0
ファイル: SetupOp.cs プロジェクト: iluckyyang/AutoDelineator
        private void _DelineateInletCatchments()
        {
            OnProgress("Delineating inlet catchments...");
            //Determine output path
            string outputDir          = _GetResultDir();
            string outputPathSmooth   = SetupOp.CreateTempFileName(outputDir, "Catchments_smooth", ".shp");
            string outputPathDetailed = SetupOp.CreateTempFileName(outputDir, "Catchments_detailed", ".shp");
            string outputNameSmooth   = System.IO.Path.GetFileNameWithoutExtension(outputPathSmooth);
            string outputNameDetailed = System.IO.Path.GetFileNameWithoutExtension(outputPathDetailed);

            //Calculate catchments
            IHydrologyOp hydroOp       = new RasterHydrologyOpClass();
            IGeoDataset  seedGrid      = null;
            IGeoDataset  catchmentGrid = null;

            try
            {
                SetAnalysisEnvironment((IRasterAnalysisEnvironment)hydroOp);
                seedGrid      = (IGeoDataset)_DrainagePointsToSeedGrid(_drainClass, "SeedPts", SetupOp.EID_FIELD_NAME);
                catchmentGrid = hydroOp.Watershed((IGeoDataset)_flowDir, seedGrid);
                OnProgress("Converting catchments to polygon...");
                IFeatureClass smoothCatchmentClass   = RasterToPolygon(catchmentGrid, outputNameSmooth, outputDir, true);
                IFeatureClass detailedCatchmentClass = RasterToPolygon(catchmentGrid, outputNameDetailed, outputDir, false);

                if (_smooth)
                {
                    _catchmentClass = smoothCatchmentClass;
                }
                else
                {
                    _catchmentClass = detailedCatchmentClass;
                }

                _MarkForDisposal((IDataset)seedGrid);
                _MarkForDisposal(catchmentGrid as IDataset);
            }
            finally
            {
                UrbanDelineationExtension.ReleaseComObject(hydroOp);
            }
            OnProgress("Inlet catchments delineated.");
        }
コード例 #14
0
        private void _RemoveDocumentEvents()
        {
            if (_activeView != null)
            {
                IActiveViewEvents_Event activeViewEvents = (IActiveViewEvents_Event)_activeView;
                activeViewEvents.FocusMapChanged -= new IActiveViewEvents_FocusMapChangedEventHandler(this._OnFocusMapChanged);
                activeViewEvents.ItemAdded       -= new IActiveViewEvents_ItemAddedEventHandler(this._OnLayersChanged);
                activeViewEvents.ItemDeleted     -= new IActiveViewEvents_ItemDeletedEventHandler(this._OnLayersChanged);
                activeViewEvents.ItemReordered   -= new IActiveViewEvents_ItemReorderedEventHandler(this._OnLayersReordered);
                UrbanDelineationExtension.ReleaseComObject(_activeView);
                _activeView = null;
            }

            if (_document != null)
            {
                IDocumentEvents_Event pDocEvents = (IDocumentEvents_Event)_document;
                pDocEvents.ActiveViewChanged -= new IDocumentEvents_ActiveViewChangedEventHandler(this._OnFocusMapChanged);
                UrbanDelineationExtension.ReleaseComObject(_document);
                _document = null;
            }
        }
コード例 #15
0
        private IEnvelope _GetSurfaceOutputExtent(IPoint mapPoint)
        {
            IEnvelope extent = null;

            SetupOp setupOp = UrbanDelineationExtension.Extension.Setup;

            if (setupOp.Catchments != null)
            {
                // Find all inlet catchments that intersect any source feature and union envelopes
                IFeatureCursor catchCursor = setupOp.Catchments.Search(null, false);
                try
                {
                    IFeature catchment = catchCursor.NextFeature();
                    while (catchment != null)
                    {
                        try
                        {
                            IRelationalOperator relationOp = (IRelationalOperator)catchment.Shape;
                            if (!relationOp.Disjoint(mapPoint))
                            {
                                extent = new EnvelopeClass();
                                catchment.Extent.QueryEnvelope(extent);
                                break;
                            }
                        }
                        finally
                        {
                            UrbanDelineationExtension.ReleaseComObject(catchment);
                        }
                        catchment = catchCursor.NextFeature();
                    }
                }
                finally
                {
                    UrbanDelineationExtension.ReleaseComObject(catchCursor);
                }
            }

            return(extent);
        }
コード例 #16
0
ファイル: SetupOp.cs プロジェクト: PDXBES/AutoDelineator
        internal IFeatureClass CreateShapefile(string path, string name, esriGeometryType geometryType, ISpatialReference spatialRef, string idFieldName)
        {
            const string SHAPE_FIELD = "Shape";

            IFeatureClass shapeFile = null;
            IWorkspace    workspace = null;

            try
            {
                workspace = OpenShapeFileWorkspace(path);
                IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace;

                //Delete any existing
                IEnumDatasetName datasets = workspace.get_DatasetNames(esriDatasetType.esriDTFeatureClass);
                datasets.Reset();
                IDataset     existing    = null;
                IDatasetName datasetName = datasets.Next();
                while (datasetName != null)
                {
                    if (string.Compare(name, datasetName.Name, true) == 0)
                    {
                        existing = (IDataset)((IName)datasetName).Open();
                        break;
                    }
                    datasetName = datasets.Next();
                }
                if (existing != null)
                {
                    try
                    {
                        existing.Delete();
                    }
                    finally
                    {
                        UrbanDelineationExtension.ReleaseComObject(existing);
                    }
                }

                //Get elements to create a new table/feature class
                IFieldsEdit fields = new FieldsClass();

                IGeometryDefEdit geometryDef = new GeometryDefClass();
                geometryDef.GeometryType_2     = geometryType;
                geometryDef.SpatialReference_2 = spatialRef;

                IFieldEdit shapeField = new FieldClass();
                shapeField.Name_2        = SHAPE_FIELD;
                shapeField.Type_2        = esriFieldType.esriFieldTypeGeometry;
                shapeField.GeometryDef_2 = geometryDef;
                fields.AddField(shapeField);

                IFieldEdit eidField = new FieldClass();
                eidField.Name_2   = idFieldName;
                eidField.Type_2   = esriFieldType.esriFieldTypeInteger;
                eidField.Length_2 = 16;
                fields.AddField(eidField as IField);

                //Create feature class
                shapeFile = featureWorkspace.CreateFeatureClass(name, fields, null, null, esriFeatureType.esriFTSimple, SHAPE_FIELD, null);
            }
            finally
            {
                UrbanDelineationExtension.ReleaseComObject(workspace);
            }

            return(shapeFile);
        }
コード例 #17
0
ファイル: SetupOp.cs プロジェクト: PDXBES/AutoDelineator
        private void _ExtractDrainagePoints()
        {
            OnProgress("Extracting drainage points...");

            Dictionary <IPoint, int> drainagePoints = new Dictionary <IPoint, int>();

            if (_includeUpstreamEnds)
            {
                OnProgress("Extract drainage points: Finding upstream ends...");
                drainagePoints = _ExtractUpstreamPipeEnds();
            }

            List <int> excludedOids = new List <int>();

            if (_excludeDownstreamEnds)
            {
                OnProgress("Extract drainage points: Finding downstream ends...");
                excludedOids = _FindDownstreamPipeEnds();
            }

            //Add inlets
            OnProgress("Extract drainage points: Adding inlets...");
            IFeatureCursor cursor = null;

            try
            {
                cursor = _inletClass.Search(null, false);
                IFeature inlet = cursor.NextFeature();
                while (inlet != null)
                {
                    try
                    {
                        if (!(_excludeDownstreamEnds && excludedOids.Contains(inlet.OID)))
                        {
                            bool enabled = true;
                            if (_excludeDisabled)
                            {
                                enabled = _IsEnabled(inlet);
                            }
                            if (enabled)
                            {
                                drainagePoints.Add((IPoint)inlet.ShapeCopy, ((ISimpleJunctionFeature)inlet).EID);
                            }
                        }
                    }
                    finally
                    {
                        UrbanDelineationExtension.ReleaseComObject(inlet);
                    }
                    inlet = cursor.NextFeature();
                }
            }
            finally
            {
                UrbanDelineationExtension.ReleaseComObject(cursor);
            }

            //Create FeatureClass
            OnProgress("Extract drainage points: Saving drainage points...");
            string outputPath = CreateTempFileName(_GetResultDir(), "DrainPoints", "shp");
            string outputName = System.IO.Path.GetFileNameWithoutExtension(outputPath);

            _drainClass = CreateShapefile(_GetResultDir(), outputName, esriGeometryType.esriGeometryPoint, new UnknownCoordinateSystemClass(), SetupOp.EID_FIELD_NAME);

            cursor = _drainClass.Insert(true);
            try
            {
                int            idFieldIndex = _drainClass.FindField(EID_FIELD_NAME);
                IFeatureBuffer buffer       = _drainClass.CreateFeatureBuffer();
                foreach (IPoint point in drainagePoints.Keys)
                {
                    buffer.Shape = point;
                    buffer.set_Value(idFieldIndex, drainagePoints[point]);
                    cursor.InsertFeature(buffer);
                }
            }
            finally
            {
                UrbanDelineationExtension.ReleaseComObject(cursor);
            }

            OnProgress(string.Format("{0} drainage points extracted.", drainagePoints.Count));
        }
コード例 #18
0
ファイル: SetupOp.cs プロジェクト: PDXBES/AutoDelineator
        private List <int> _FindDownstreamPipeEnds()
        {
            List <int> endPointOidList = new List <int>();

            INetwork     network     = _geometricNetwork.Network;
            INetTopology netTopology = network as INetTopology;

            bool inletInNetwork = false;
            IEnumFeatureClass junctionClasses = _geometricNetwork.get_ClassesByType(esriFeatureType.esriFTSimpleJunction);
            IFeatureClass     junctionClass   = junctionClasses.Next();

            while (junctionClass != null)
            {
                if (junctionClass == _inletClass)
                {
                    inletInNetwork = true;
                    break;
                }
                else
                {
                    UrbanDelineationExtension.ReleaseComObject(junctionClass);
                }
                junctionClass = junctionClasses.Next();
            }

            if (!inletInNetwork)
            {
                throw new Exception("The selected inlet class is not part of the pipe network.");
            }

            IFeatureCursor cursor = null;

            try
            {
                int  edgeId;
                bool towardJunction;

                cursor = _inletClass.Search(null, false);
                IFeature inlet = cursor.NextFeature();
                while (inlet != null)
                {
                    try
                    {
                        ISimpleJunctionFeature junction = inlet as ISimpleJunctionFeature;

                        //Check that inlet is a valid part of network before testing if it is at downstream end
                        if (!inlet.Shape.IsEmpty && junction.EID != 0)
                        {
                            bool isDownstream = junction.EdgeFeatureCount > 0;
                            for (int i = 0; i < junction.EdgeFeatureCount; i++)
                            {
                                netTopology.GetAdjacentEdge(junction.EID, i, out edgeId, out towardJunction);
                                if (!towardJunction)
                                {
                                    isDownstream = false;
                                    break;
                                }
                            }

                            if (isDownstream)
                            {
                                endPointOidList.Add(inlet.OID);
                            }
                        }
                    }
                    finally
                    {
                        UrbanDelineationExtension.ReleaseComObject(inlet);
                    }
                    inlet = cursor.NextFeature();
                }
            }
            finally
            {
                UrbanDelineationExtension.ReleaseComObject(cursor);
            }

            return(endPointOidList);
        }
コード例 #19
0
        protected override void OnMouseUp(MouseEventArgs arg)
        {
            base.OnMouseUp(arg);

            IMxDocument document = null;

            try
            {
                // Get user point
                document = ArcMap.Document;
                IPoint mapPoint = ArcMap.ThisApplication.Display.DisplayTransformation.ToMapPoint(arg.X, arg.Y);

                // Get flow direction
                SetupOp setupOp = UrbanDelineationExtension.Extension.Setup;
                IRaster flowDir = setupOp.FlowDirection;
                if (flowDir == null)
                {
                    MessageBox.Show(_appWindow, Properties.Resources.Error_NoFlowDirection, Properties.Resources.Category_UrbanDelineation);
                    return;
                }
                IGeoDataset flowDirDataset = (IGeoDataset)flowDir;

                // Process point
                IPointCollection pointCollection = new MultipointClass();
                ((IGeometry)pointCollection).SpatialReference = flowDirDataset.SpatialReference;
                mapPoint.Project(flowDirDataset.SpatialReference);
                IPoint[] points = new IPoint[] { mapPoint };
                pointCollection.AddPoints(1, ref points[0]);

                // Get flow path geometry
                IPolyline   flowPath   = null;
                string      outputDir  = null;
                IDistanceOp distanceOp = new RasterDistanceOpClass();
                try
                {
                    IEnvelope outputExtent = _GetSurfaceOutputExtent(mapPoint);
                    if (outputExtent == null)
                    {
                        setupOp.SetAnalysisEnvironment((IRasterAnalysisEnvironment)distanceOp);
                    }
                    else
                    {
                        // Expand to ensure full boundary of watershed is included.
                        double cellWidth  = ((IRasterAnalysisProps)setupOp.FlowDirection).PixelWidth;
                        double cellHeight = ((IRasterAnalysisProps)setupOp.FlowDirection).PixelHeight;
                        outputExtent.Expand(cellWidth * 3.0, cellHeight * 3.0, false);

                        setupOp.SetAnalysisEnvironment((IRasterAnalysisEnvironment)distanceOp, outputExtent);
                    }

                    // The RasterDistanceOpClass does not properly clean up after itself, so we have to do it ourselves
                    // To do this, we need to track the output directory and delete it, since we don't have direct access to the
                    // dataset that is left behind. To delete the directory, it must contain only the temp files generated by
                    // the RasterDistanceOpClass and no others, so we create one here. The directory is then deleted in the
                    // finally clause.
                    ((IRasterAnalysisEnvironment)distanceOp).OutWorkspace = _GetUniqueOutputWorkspace();
                    outputDir = ((IRasterAnalysisEnvironment)distanceOp).OutWorkspace.PathName;

                    IGeometryCollection flowPaths = distanceOp.CostPathAsPolyline(pointCollection, flowDirDataset, flowDirDataset);
                    if (flowPaths.GeometryCount > 0)
                    {
                        flowPath = flowPaths.get_Geometry(0) as IPolyline;
                    }
                }
                finally
                {
                    UrbanDelineationExtension.ReleaseComObject(distanceOp);
                    try
                    {
                        if (Directory.Exists(outputDir))
                        {
                            Directory.Delete(outputDir, true);
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine("FlowTracingTool.OnMouseUp: " + ex.GetType().FullName + ": " + ex.Message);
                    }
                }

                // Add flow path to map
                if (flowPath != null && !flowPath.IsEmpty)
                {
                    // Create graphic element
                    flowPath.SpatialReference = flowDirDataset.SpatialReference;
                    // Weed removes points that are in-line since flow path is generated with vertices for every cell, even if they are exactly in-line
                    ((IPolycurve)flowPath).Weed(0.001);
                    IElement flowElement = new LineElementClass();
                    ((IElementProperties3)flowElement).Name = ELEMENT_NAME;
                    flowElement.Geometry = flowPath;

                    // Set color
                    ILineSymbol lineSymbol  = ((ILineElement)flowElement).Symbol;
                    IRgbColor   color       = lineSymbol.Color as IRgbColor;
                    Color       systemColor = Color.Red;
                    color.Blue       = systemColor.B;
                    color.Red        = systemColor.R;
                    color.Green      = systemColor.G;
                    lineSymbol.Color = color;
                    ((ILineElement)flowElement).Symbol = lineSymbol;

                    ((IGraphicsContainer)document.FocusMap.BasicGraphicsLayer).AddElement(flowElement, 0);
                    ((IDocumentDirty)document).SetDirty();

                    document.ActiveView.Refresh();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(_appWindow, ex.Message, Properties.Resources.Caption_Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                UrbanDelineationExtension.ReleaseComObject(document);
            }
        }
コード例 #20
0
        private void btnDelineate_Click(object sender, EventArgs e)
        {
            try
            {
                if (_CheckInput())
                {
                    System.Windows.Forms.Cursor.Current = Cursors.WaitCursor;

                    Delineator delineator = new Delineator();
                    delineator.Setup                  = UrbanDelineationExtension.Extension.Setup;
                    delineator.OutletSource           = cbxOutletSource.SelectedValue as IFeatureLayer;
                    delineator.OutletIdField          = cbxOutletField.SelectedValue as string;
                    delineator.ExtendOverland         = chkExtendOverland.Checked;
                    delineator.StopAtDisabledFeatures = chkStopAtDisabled.Checked;

                    if (chkSnapToPourPoint.Enabled && chkSnapToPourPoint.Checked)
                    {
                        delineator.SnapToPourPoint = true;
                        double snapDistance;
                        if (double.TryParse(tbxSnapDistance.Text, out snapDistance))
                        {
                            delineator.SnapDistance = snapDistance;
                        }
                    }
                    else
                    {
                        delineator.SnapToPourPoint = false;
                    }

                    delineator.DelineateCatchments();

                    EnumLayer layers = new EnumLayer();

                    //Add results to map
                    IFeatureLayer watershedLayer = new FeatureLayerClass();
                    watershedLayer.FeatureClass = delineator.OutletWatersheds;
                    watershedLayer.Name         = delineator.OutletWatersheds.AliasName;
                    ((ILayerEffects)watershedLayer).Transparency = 50;
                    if (!string.IsNullOrEmpty(delineator.OutletIdField))
                    {
                        _AddLabel(watershedLayer, delineator.OutletIdField);
                    }
                    layers.Add(watershedLayer);

                    IMap map = null;
                    try
                    {
                        map = ArcMap.Document.FocusMap;
                        map.AddLayers(layers, true);
                    }
                    finally
                    {
                        UrbanDelineationExtension.ReleaseComObject(map);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, Properties.Resources.Caption_Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                System.Windows.Forms.Cursor.Current = Cursors.Default;
            }
        }
コード例 #21
0
        private void btnPreprocess_Click(object sender, EventArgs e)
        {
            try
            {
                System.Windows.Forms.Application.DoEvents();
                System.Windows.Forms.Cursor.Current = Cursors.WaitCursor;

                DialogResult choice = MessageBox.Show(this, "Depending on the size of the network and DEM, this operation may take a long time.",
                                                      Properties.Resources.Caption_Notice, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
                if (choice == DialogResult.OK)
                {
                    SetupOp setupOp = UrbanDelineationExtension.Extension.Setup;

                    setupOp.GeometricNetwork = cbxNetwork.SelectedValue as IGeometricNetwork;
                    IFeatureLayer inletLayer = cbxInlets.SelectedValue as IFeatureLayer;
                    setupOp.InletClass = inletLayer.FeatureClass;
                    IRasterLayer demLayer = cbxDEM.SelectedValue as IRasterLayer;
                    setupOp.DEM = demLayer.Raster;
                    setupOp.IncludeUpstreamPipeEnds   = chkIncludeUp.Checked;
                    setupOp.ExcludeDisabledNodes      = chkExcludeDisabled.Checked;
                    setupOp.ExcludeDownstreamPipeEnds = chkExcludeDown.Checked;
                    setupOp.SmoothBoundaries          = chkSmooth.Checked;
                    setupOp.Preprocess();

                    //Add results to map
                    EnumLayer layers = new EnumLayer();

                    IFeatureLayer drainLayer = new FeatureLayerClass();
                    drainLayer.FeatureClass = setupOp.DrainagePoints;
                    drainLayer.Name         = "Drainage Points";
                    drainLayer.Visible      = false;
                    layers.Add(drainLayer);

                    IRasterLayer punchedLayer = new RasterLayerClass();
                    punchedLayer.CreateFromRaster(setupOp.PunchedDEM);
                    punchedLayer.Name    = "Punched DEM";
                    punchedLayer.Visible = false;
                    layers.Add(punchedLayer);

                    IRasterLayer fillLayer = new RasterLayerClass();
                    fillLayer.CreateFromRaster(setupOp.FilledDEM);
                    fillLayer.Name    = "Filled DEM";
                    fillLayer.Visible = false;
                    layers.Add(fillLayer);

                    IRasterLayer flowDirLayer = new RasterLayerClass();
                    flowDirLayer.CreateFromRaster(setupOp.FlowDirection);
                    flowDirLayer.Name    = "Flow Direction";
                    flowDirLayer.Visible = false;
                    layers.Add(flowDirLayer);

                    IFeatureLayer catchmentLayer = new FeatureLayerClass();
                    catchmentLayer.FeatureClass = setupOp.Catchments;
                    catchmentLayer.Name         = "Inlet Catchments";
                    catchmentLayer.Visible      = false;
                    ((ILayerEffects)catchmentLayer).Transparency = 50;
                    layers.Add(catchmentLayer);

                    IMap map = null;
                    try
                    {
                        map = ArcMap.Document.FocusMap;
                        map.AddLayers(layers, true);

                        cbxFlowDirGrid.SelectedValue = flowDirLayer;
                        cbxCatchments.SelectedValue  = catchmentLayer;
                    }
                    finally
                    {
                        UrbanDelineationExtension.ReleaseComObject(map);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, Properties.Resources.Caption_Error);
            }
            finally
            {
                System.Windows.Forms.Cursor.Current = Cursors.Default;
            }
        }
コード例 #22
0
        private void _UpdateOutletFields()
        {
            cbxOutletField.DataSource = null;
            cbxOutletField.Items.Clear();

            List <ComboBoxItem> fieldNames = new List <ComboBoxItem>();

            fieldNames.Add(new ComboBoxItem()
            {
                Name = Properties.Resources.Optional_Field, Value = null
            });

            IFeatureLayer sourceLayer = cbxOutletSource.SelectedValue as IFeatureLayer;

            if (sourceLayer == null)
            {
                // If source layer is null, we use all junction layer fields
                if (UrbanDelineationExtension.Extension != null)
                {
                    if (UrbanDelineationExtension.Extension.Setup != null)
                    {
                        IGeometricNetwork geometricNetwork = UrbanDelineationExtension.Extension.Setup.GeometricNetwork;
                        if (geometricNetwork != null)
                        {
                            IEnumFeatureClass junctionClasses = geometricNetwork.get_ClassesByType(esriFeatureType.esriFTSimpleJunction);
                            IFeatureClass     junctionClass   = junctionClasses.Next();
                            while (junctionClass != null)
                            {
                                try
                                {
                                    for (int i = 0; i < junctionClass.Fields.FieldCount; i++)
                                    {
                                        string aliasName = junctionClass.Fields.get_Field(i).AliasName;
                                        string fieldName = junctionClass.Fields.get_Field(i).Name;

                                        if (fieldName != junctionClass.ShapeFieldName)
                                        {
                                            string displayFieldName = string.Format("{0}.{1}", junctionClass.AliasName, aliasName);
                                            fieldNames.Add(new ComboBoxItem()
                                            {
                                                Name = displayFieldName, Value = fieldName
                                            });
                                        }
                                    }
                                }
                                finally
                                {
                                    UrbanDelineationExtension.ReleaseComObject(junctionClass);
                                }
                                junctionClass = junctionClasses.Next();
                            }
                        }
                    }
                }
            }
            else
            {
                IFeatureClass sourceClass = sourceLayer.FeatureClass;
                if (sourceClass != null)
                {
                    try
                    {
                        for (int i = 0; i < sourceClass.Fields.FieldCount; i++)
                        {
                            string aliasName = sourceClass.Fields.get_Field(i).AliasName;
                            string fieldName = sourceClass.Fields.get_Field(i).Name;

                            if (fieldName != sourceClass.ShapeFieldName)
                            {
                                fieldNames.Add(new ComboBoxItem()
                                {
                                    Name = aliasName, Value = fieldName
                                });
                            }
                        }
                    }
                    finally
                    {
                        UrbanDelineationExtension.ReleaseComObject(sourceClass);
                    }
                }
            }

            _UpdateCombobox(cbxOutletField, fieldNames);
            if (!string.IsNullOrEmpty(UrbanDelineationForm.LastOutletFieldText))
            {
                cbxOutletField.SelectedValue = UrbanDelineationForm.LastOutletFieldText;
            }

            string selectedField = cbxOutletField.SelectedValue as string;

            if (selectedField != UrbanDelineationForm.LastOutletFieldText)
            {
                cbxOutletField.SelectedIndex             = 0;
                UrbanDelineationForm.LastOutletFieldText = cbxOutletField.SelectedValue as string;
            }
        }