Beispiel #1
0
        //public List<BbPaintFinish> PaintFinishes { get; protected set; }


        //public void AddPaintFinish(BbPaintFinish paintFinish)
        //{
        //    if (PaintFinishes == null)
        //    {
        //        PaintFinishes = new List<BbPaintFinish>();
        //    }

        //    if (IfcRelCoversBldgElements == null)
        //    {
        //        IfcRelCoversBldgElements = new IfcRelCoversBldgElements
        //            {
        //                GlobalId = IfcGloballyUniqueId.NewGuid(),
        //                OwnerHistory = BbHeaderSetting.Setting3D.IfcOwnerHistory,
        //                RelatingBuildingElement = IfcObject as IfcElement,
        //                RelatedCoverings = new List<IfcCovering>(),
        //            };
        //    }

        //    IfcRelCoversBldgElements.RelatedCoverings.Add(paintFinish.IfcCovering);


        //    PaintFinishes.Add(paintFinish);
        //}

        //public void AddPaintFinish(SemPaintFinishPatch semPaintFinish, BbLocalPlacement3D semLocalPlacement3D)
        //{
        //    AddPaintFinish(semPaintFinish);
        //    semPaintFinish.BbLocalPlacement3D = semLocalPlacement3D;
        //}

        //public ICollection<BbElement> Retrieve();

        public void AddToSpatialElement(BbSpatialElement bbSpatialElement)
        {
            BbSpatialElement = bbSpatialElement;
            var a = EarlyBindingInstanceModel.GetReferencedEntities(bbSpatialElement.IfcSpatialStructureElement.EIN).Values;

            var b = (from x in a.OfType <IfcRelContainedInSpatialStructure>()
                     where x.RelatingStructure.EIN == bbSpatialElement.IfcSpatialStructureElement.EIN
                     select x).ToList();

            switch (b.Count)
            {
            case 0:
                IfcRelContainedInSpatialStructure = new IfcRelContainedInSpatialStructure
                {
                    GlobalId          = IfcGloballyUniqueId.NewGuid(),
                    OwnerHistory      = IfcObject.OwnerHistory,
                    RelatingStructure = bbSpatialElement.IfcSpatialStructureElement,
                    RelatedElements   = new List <IfcProduct>()
                    {
                    },
                };
                break;

            case 1:
                IfcRelContainedInSpatialStructure = b[0];
                break;

            default:
                throw new NotImplementedException();
            }

            IfcRelContainedInSpatialStructure.RelatedElements.Add(IfcObject as IfcElement);
        }
Beispiel #2
0
 protected BbAssembly(
     BbSpatialElement floor,
     IfcElementAssembly assembly,
     IfcRelContainedInSpatialStructure spatialStructure)
 {
     //BbSpatialElement = floor;
     _ifcElementAssembly = assembly;
     AddToSpatialElement(floor);
 }
Beispiel #3
0
        private void DoorInRoom(IModel model)
        {
            int doorCount = 0;
            IEnumerable <IfcRelContainedInSpatialStructure> relations = model.Instances.OfType <IfcRelContainedInSpatialStructure>();
            IfcRelContainedInSpatialStructure relation = relations.FirstOrDefault();

            if (relation != null)
            {
                IEnumerable <IfcDoor> doors = relation.RelatedElements.OfType <IfcDoor>();
                doorCount = doors.Count();
            }
        }
Beispiel #4
0
        public static void AddElement(this IfcSite site, IfcProduct element)
        {
            IEnumerable <IfcRelContainedInSpatialStructure> relatedElements = site.ContainsElements;

            if (relatedElements.Count() == 0) //none defined create the relationship
            {
                IfcRelContainedInSpatialStructure relSe =
                    site.ModelOf.Instances.New <IfcRelContainedInSpatialStructure>();
                relSe.RelatingStructure = site;
                relSe.RelatedElements.Add(element);
            }
            else
            {
                relatedElements.First().RelatedElements.Add(element);
            }
        }
        protected void AddRelatedElements(IfcRelContainedInSpatialStructure scRel, CompositionNode treeItem)
        {
            var applicableTypes = scRel.RelatedElements
                                  .Where(t => !t.GetType().IsSubclassOf(typeof(IfcFeatureElementSubtraction)));

            foreach (IfcObjectDefinition child in applicableTypes)
            {
                CompositionNode childItem;
                if (!NodeMap.TryGetValue(child, out childItem)) //already written
                {
                    childItem = new CompositionNode(child);
                    NodeMap.Add(child, childItem);
                }
                //Node family = GetFamily(treeItem, child);
                // TODO: Add child to family, not treeItem
                treeItem.Children.Add(childItem);
            }
        }
        /// <summary>
        ///   Adds the element to the set of elements which are contained in this spatialstructure
        /// </summary>
        /// <param name = "se"></param>
        /// <param name = "prod"></param>
        public static void AddElement(this IfcSpatialStructureElement se, IfcProduct prod)
        {
            if (prod == null)
            {
                return;
            }

            IEnumerable <IfcRelContainedInSpatialStructure> relatedElements = se.ContainsElements;

            if (relatedElements.Count() == 0) //none defined create the relationship
            {
                IfcRelContainedInSpatialStructure relSe =
                    se.Model.Instances.New <IfcRelContainedInSpatialStructure>();
                relSe.RelatingStructure = se;
                relSe.RelatedElements.Add(prod);
            }
            else
            {
                relatedElements.First().RelatedElements.Add(prod);
            }
        }
Beispiel #7
0
        /// <summary>
        /// Write the model to IFC.
        /// </summary>
        /// <param name="model"></param>
        /// <param name="path">The path to the generated IFC STEP file.</param>
        public static void ToIFC(this Model model, string path)
        {
            var ifc = new Document("Elements", "Elements", Environment.UserName,
                                   null, null, null, "Elements", null, null,
                                   null, null, null, null, null, null
                                   );

            var proj = ifc.AllInstancesOfType <IfcProject>().FirstOrDefault();

            // Add a site
            var site          = new IfcSite(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, IfcElementCompositionEnum.ELEMENT);
            var projAggregate = new IfcRelAggregates(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, proj, new List <IfcObjectDefinition> {
                site
            });

            // Add building and building storey
            var building  = new IfcBuilding(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, IfcElementCompositionEnum.ELEMENT);
            var storey    = new IfcBuildingStorey(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, IfcElementCompositionEnum.ELEMENT);
            var aggregate = new IfcRelAggregates(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, building, new List <IfcObjectDefinition> {
                storey
            });

            // Aggregate the building into the site
            var siteAggregate = new IfcRelAggregates(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, site, new List <IfcObjectDefinition> {
                building
            });

            ifc.AddEntity(site);
            ifc.AddEntity(projAggregate);
            ifc.AddEntity(building);
            ifc.AddEntity(storey);
            ifc.AddEntity(aggregate);
            ifc.AddEntity(siteAggregate);

            var products = new List <IfcProduct>();
            var context  = ifc.AllInstancesOfType <IfcGeometricRepresentationContext>().FirstOrDefault();

            foreach (var e in model.Elements.Values)
            {
                try
                {
                    products.AddRange(e.ToIfcProducts(context, ifc));
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"There was an error writing an element of type {e.GetType()} to IFC: " + ex.Message);
                    Console.WriteLine(ex.StackTrace);
                    continue;
                }
            }

            var spatialRel = new IfcRelContainedInSpatialStructure(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, products, storey);

            ifc.AddEntity(spatialRel);

            if (File.Exists(path))
            {
                File.Delete(path);
            }
            File.WriteAllText(path, ifc.ToSTEP(path));
        }
        /// <summary>
        /// Write the model to IFC.
        /// </summary>
        /// <param name="model"></param>
        /// <param name="path">The path to the generated IFC STEP file.</param>
        public static void ToIFC(this Model model, string path)
        {
            var ifc = new Document("Elements", "Elements", Environment.UserName,
                                   null, null, null, "Elements", null, null,
                                   null, null, null, null, null, null
                                   );

            var proj = ifc.AllInstancesOfType <IfcProject>().FirstOrDefault();

            // Add a site
            var site = new IfcSite(IfcGuid.ToIfcGuid(Guid.NewGuid()),
                                   null,
                                   "Hypar Site",
                                   "The default site generated by Hypar",
                                   null,
                                   null,
                                   null,
                                   null,
                                   IfcElementCompositionEnum.ELEMENT,
                                   new IfcCompoundPlaneAngleMeasure(new List <int> {
                0, 0, 0
            }),
                                   new IfcCompoundPlaneAngleMeasure(new List <int> {
                0, 0, 0
            }),
                                   0,
                                   null,
                                   null);
            var projAggregate = new IfcRelAggregates(IfcGuid.ToIfcGuid(Guid.NewGuid()), proj, new List <IfcObjectDefinition> {
                site
            });

            // Add building and building storey
            var building = new IfcBuilding(IfcGuid.ToIfcGuid(Guid.NewGuid()),
                                           null,
                                           "Default Building",
                                           "The default building generated by Hypar.",
                                           null,
                                           null,
                                           null,
                                           null,
                                           IfcElementCompositionEnum.ELEMENT,
                                           0,
                                           0,
                                           null);
            var storey = new IfcBuildingStorey(IfcGuid.ToIfcGuid(Guid.NewGuid()),
                                               null,
                                               "Default Storey",
                                               "The default storey generated by Hypar",
                                               null,
                                               null,
                                               null,
                                               null,
                                               IfcElementCompositionEnum.ELEMENT,
                                               0);
            var aggregate = new IfcRelAggregates(IfcGuid.ToIfcGuid(Guid.NewGuid()), building, new List <IfcObjectDefinition> {
                storey
            });

            // Aggregate the building into the site
            var siteAggregate = new IfcRelAggregates(IfcGuid.ToIfcGuid(Guid.NewGuid()), site, new List <IfcObjectDefinition> {
                building
            });

            ifc.AddEntity(site);
            ifc.AddEntity(projAggregate);
            ifc.AddEntity(building);
            ifc.AddEntity(storey);
            ifc.AddEntity(aggregate);
            ifc.AddEntity(siteAggregate);

            var products = new List <IfcProduct>();
            var context  = ifc.AllInstancesOfType <IfcGeometricRepresentationContext>().FirstOrDefault();

            // IfcRelAssociatesMaterial
            // IfcMaterialDefinitionRepresentation
            // https://forums.buildingsmart.org/t/where-and-how-will-my-colors-be-saved-in-ifc/1806/12
            var styleAssignments = new Dictionary <Guid, List <IfcStyleAssignmentSelect> >();

            var white = Colors.White.ToIfcColourRgb();

            ifc.AddEntity(white);

            // TODO: Fix color support in all applications.
            // https://forums.buildingsmart.org/t/why-is-it-so-difficult-to-get-colors-to-show-up/2312/12
            foreach (var m in model.AllElementsOfType <Material>())
            {
                var material = new IfcMaterial(m.Name, null, "Hypar");
                ifc.AddEntity(material);

                var color = m.Color.ToIfcColourRgb();
                ifc.AddEntity(color);

                var transparency = new IfcNormalisedRatioMeasure(1.0 - m.Color.Alpha);

                var shading = new IfcSurfaceStyleShading(color, transparency);
                ifc.AddEntity(shading);

                var styles = new List <IfcSurfaceStyleElementSelect> {
                    new IfcSurfaceStyleElementSelect(shading),
                };
                var surfaceStyle = new IfcSurfaceStyle(material.Name, IfcSurfaceSide.BOTH, styles);
                ifc.AddEntity(surfaceStyle);

                var styleAssign = new IfcStyleAssignmentSelect(surfaceStyle);
                var assignments = new List <IfcStyleAssignmentSelect>()
                {
                    styleAssign
                };
                styleAssignments.Add(m.Id, assignments);
            }


            foreach (var e in model.Elements.Values.Where(e =>
            {
                var t = e.GetType();
                return(((e is GeometricElement &&
                         !((GeometricElement)e).IsElementDefinition) || e is ElementInstance) &&
                       t != typeof(ModelCurve) &&
                       t != typeof(ModelPoints) &&
                       t != typeof(AnalysisMesh));
            }))
            {
                try
                {
                    products.AddRange(e.ToIfcProducts(context, ifc, styleAssignments));
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"There was an error writing an element of type {e.GetType()} to IFC: " + ex.Message);
                    Console.WriteLine(ex.StackTrace);
                    continue;
                }
            }

            var spatialRel = new IfcRelContainedInSpatialStructure(IfcGuid.ToIfcGuid(Guid.NewGuid()), products, storey);

            ifc.AddEntity(spatialRel);

            if (File.Exists(path))
            {
                File.Delete(path);
            }
            File.WriteAllText(path, ifc.ToSTEP(path));
        }
Beispiel #9
0
        private static void Main(string[] args)
        {
            var database = new DatabaseIfc(ModelView.Ifc4X3NotAssigned);

            database.Factory.ApplicationDeveloper = "Sebastian Esser";
            // turn owner history off
            database.Factory.Options.GenerateOwnerHistory = false;

            // basic setup
            var site    = new IfcSite(database, "SiteA");
            var project = new IfcProject(
                site,
                "SampleProject with a span annotation",
                IfcUnitAssignment.Length.Metre
                );

            // create an annotation
            var annotation = new IfcAnnotation(database)
            {
                Name = "DesignSpeed",
            };

            annotation.AddComment("Annotation item span-placed along the alignment");

            // link annotation with site
            var contained = new IfcRelContainedInSpatialStructure(site);

            contained.RelatedElements.Add(annotation);

            #region Alignment

            var alignment = new IfcAlignment(site)
            {
                Name = "Basic alignment with a single horizontal segment"
            };
            alignment.AddComment("Generate alignment representation");

            // semantic
            var horizSegment = new IfcAlignmentHorizontalSegment(
                new IfcCartesianPoint(database, 5, 10),
                0,
                0,
                0,
                200,
                IfcAlignmentHorizontalSegmentTypeEnum.LINE);

            // geometric representation of a single segment. It gets referenced by IfcCompositeCurve.segments and IfcAlignmentSegment.Representation
            var curveSegment = new IfcCurveSegment(
                IfcTransitionCode.CONTSAMEGRADIENTSAMECURVATURE,
                new IfcAxis2Placement2D(new IfcCartesianPoint(database, 0, 0)),
                new IfcParameterValue(0),
                new IfcParameterValue(200),
                null);


            var segments = new List <IfcSegment> {
                curveSegment
            };
            var compositeCurve = new IfcCompositeCurve(segments);

            var rep = new IfcShapeRepresentation(compositeCurve)
            {
                RepresentationIdentifier = "Axis",
                RepresentationType       = "Curve2D"
            };

            alignment.Representation = new IfcProductDefinitionShape(rep);
            alignment.Axis           = compositeCurve;

            // create an alignment horizontal instance that takes a list of horizontal segments
            var alignmentHorizontal = new IfcAlignmentHorizontal(database)
            {
                Segments = new LIST <IfcAlignmentHorizontalSegment>()
                {
                    horizSegment
                }
            };

            // link alignment and and its horizontal part semantically
            new IfcRelAggregates(alignment, alignmentHorizontal);

            // create a new alignmentSegment with then gets one curve segment as its geometric representation
            var alignmentSegment = new IfcAlignmentSegment(database);

            // link horizontal alignment with the recently created alignment segment
            new IfcRelNests(alignmentHorizontal, alignmentSegment); // sorted list -> IfcRelNests

            // connect geom representation to this segment
            alignmentSegment.Representation = new IfcProductDefinitionShape(new IfcShapeRepresentation(curveSegment));

            #endregion Alignment

            #region Annotation placement

            alignmentSegment.AddComment("Create placement for annotation");

            var axis2place = new IfcAxis2PlacementLinear(
                new IfcPointByDistanceExpression(25, compositeCurve),
                null,
                null);

            var linPlacement = new IfcLinearPlacement(axis2place);
            linPlacement.Distance      = new IfcPointByDistanceExpression(128, compositeCurve);
            annotation.ObjectPlacement = linPlacement;

            #endregion Annotation placement

            #region PSet

            //var lengthUnit = new IfcSIUnit(database, IfcUnitEnum.LENGTHUNIT, IfcSIPrefix.NONE, IfcSIUnitName.METRE);

            var lengthDerivedUnit = new IfcSIUnit(database, IfcUnitEnum.LENGTHUNIT, IfcSIPrefix.KILO, IfcSIUnitName.METRE);
            lengthDerivedUnit.AddComment("PSet setup");
            var timeBaseUnit    = new IfcSIUnit(database, IfcUnitEnum.TIMEUNIT, IfcSIPrefix.NONE, IfcSIUnitName.SECOND);
            var timeDerivedUnit = new IfcConversionBasedUnit(IfcUnitEnum.TIMEUNIT, "hour", new IfcMeasureWithUnit(new IfcPositiveInteger(3600), timeBaseUnit));

            var ifcderivedunitelem1 = new IfcDerivedUnitElement(lengthDerivedUnit, 1);
            var ifcderivedunitelem2 = new IfcDerivedUnitElement(timeDerivedUnit, -1);
            var speedUnit           = new IfcDerivedUnit(
                new List <IfcDerivedUnitElement> {
                ifcderivedunitelem1, ifcderivedunitelem2
            },
                IfcDerivedUnitEnum.LINEARVELOCITYUNIT);

            var pSet = new IfcPropertySet(annotation, "PSET_SpeedData", new List <IfcProperty>
            {
                new IfcPropertySingleValue(database, "CargoSpeed", new IfcLinearVelocityMeasure(60), speedUnit),
                new IfcPropertySingleValue(database, "DesignSpeed", new IfcLinearVelocityMeasure(110), speedUnit)
            });

            #endregion PSet

            database.WriteFile("AlignmentWithSpanAnnotation.ifc");
        }
Beispiel #10
0
        public static int Main(string[] args)
        {
            var returnMessage      = (int)ExitCode.Success;
            var outputElements     = new List <JsonIfcElement>();
            var pathSource         = string.Empty;
            var pathDest           = string.Empty;
            var activeComptactJson = true;
            var readVersion        = false;
            var activeFullJson     = false;
            //var SCALE = 1.0;
            var context = new JsonConversionContext();
            JsonProjectIfcElement newProject = null;

            try
            {
                foreach (string arg in args)
                {
                    if (arg.ToLower().Trim() == "--version")
                    {
                        readVersion = true;
                    }
                    if (arg.ToLower().Trim() == "--indented")
                    {
                        activeComptactJson = false;
                    }
                    if (arg.ToLower().Trim() == "--full")
                    {
                        activeFullJson = true;
                    }
                    if (arg.Substring(0, 2) != "--" && pathSource != string.Empty && pathDest == string.Empty)
                    {
                        pathDest = arg;
                    }
                    if (arg.Substring(0, 2) != "--" && pathSource == string.Empty)
                    {
                        pathSource = arg;
                    }
                }

                if (readVersion)
                {
                    var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                    Console.WriteLine($"1. ConvertIfc2Json : {version}{Environment.NewLine}(.Net version {typeof(string).Assembly.ImageRuntimeVersion})");
                    return(returnMessage);
                }



                if (File.Exists(pathSource))
                {
                    if (pathDest == string.Empty)
                    {
                        pathDest = pathSource + ".json";
                    }
                    var        db = new DatabaseIfc();
                    IfcProject project;
                    var        projectId = "";
                    var        sites     = new List <IfcSite>();
                    var        buildings = new List <IfcBuilding>();

                    try
                    {
                        db      = new DatabaseIfc(pathSource);
                        project = db.Project;
                        sites   = project.Extract <IfcSite>();



                        // IFC Project
                        try
                        {
                            if (project.GlobalId != null)
                            {
                                // REVIEW ne semble pas servir
                                //foreach (var unit in project.UnitsInContext.Units)
                                //{
                                //    var u = project.UnitsInContext.Extract<IfcSIUnit>();
                                //    // Console.WriteLine("2." + unit.StepClassName);
                                //}

                                // Computing the json conversion scale from current Geogym project
                                context.SCALE = project.GetJsonConversionScale();
                                projectId     = project.GlobalId;
                            }

                            outputElements.Add(newProject = new JsonProjectIfcElement(project));
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("3. Element read error " + ex.Message);
                            returnMessage = (int)ExitCode.UnknownError;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("31. Write file : " + ex.Message);
                        returnMessage = (int)ExitCode.InvalidFile;
                    }

                    // IFC Site
                    foreach (var site in sites)
                    {
                        try
                        {
                            if (site.GlobalId != null)
                            {
                                var newSite = new JsonSiteIfcElement(site, newProject, context);
                                outputElements.Add(newSite);

                                // IFC Building
                                buildings = site.Extract <IfcBuilding>();
                                foreach (var building in buildings)
                                {
                                    var newBuildind = new JsonBuildingIfcElement(building, newSite, context); // REVIEW shouldn't create this unused instance if global id is null
                                    if (building.GlobalId != null)
                                    {
                                        outputElements.Add(newBuildind);
                                    }

                                    // IFC Building Storey // Levels
                                    var buildingStoreys = building.Extract <IfcBuildingStorey>();
                                    foreach (var buildingStorey in buildingStoreys)
                                    {
                                        var storeyElement = new JsonStoreyIfcElement(buildingStorey, newBuildind, context);
                                        outputElements.Add(storeyElement);


                                        // IFC Space // Rooms
                                        var spaces = buildingStorey.Extract <IfcSpace>();

                                        // Check IfcProduct Ids
                                        var productsIds    = new List <string>();
                                        var productCounter = 0;

                                        // IfcProduct
                                        var products = buildingStorey.Extract <IfcProduct>();
                                        foreach (var product in products)
                                        {
                                            try
                                            {
                                                if (product.GlobalId != null)
                                                {
                                                    var newElementProd = new JsonProductIfcElement(product, storeyElement, context);
                                                    var spaceCounter   = 0;

                                                    // Link to the Space
                                                    foreach (var space in spaces)
                                                    {
                                                        try
                                                        {
                                                            // REVIEW = LatestOrDefault
                                                            // IfcSpace
                                                            if (space.GlobalId == product.GlobalId)
                                                            {
                                                                try
                                                                {
                                                                    newElementProd.userData.name = space.LongName;
                                                                }
                                                                catch (NotSupportedException exEncode)
                                                                {
                                                                    newElementProd.userData.name = space.Name;
                                                                    Console.WriteLine("15. Space Name read error (id: " + space.GlobalId + ") " + exEncode.Message); // returnMessage = (int)ExitCode.NodataIsAvailableForEncoding;
                                                                }
                                                                catch (System.Exception ex)
                                                                {
                                                                    Console.WriteLine("29. Space Name LongName read error" + ex.Message);
                                                                }

                                                                newElementProd.userData.pset.Add("number", space.Name);

                                                                // Create boundary
                                                                geoGeometry geom = new geoGeometry();
                                                                IList <IList <IList <double> > > coords = new List <IList <IList <double> > >();
                                                                Dictionary <string, string>      props  = new Dictionary <string, string>();
                                                                string height    = "0.0";
                                                                string elevation = "0.0";


                                                                // Representation
                                                                if (space.Representation.Representations.Count > 0)
                                                                {
                                                                    foreach (IfcRepresentationItem item in space.Representation.Representations[0].Items)
                                                                    {
                                                                        try
                                                                        {
                                                                            if (item.StepClassName == "IfcExtrudedAreaSolid")
                                                                            {
                                                                                IfcExtrudedAreaSolid areaSolid = item as IfcExtrudedAreaSolid;
                                                                                IfcAxis2Placement3D  pos       = areaSolid.Position;
                                                                                Point3D loc = new Point3D(pos.Location.Coordinates[0], pos.Location.Coordinates[1], pos.Location.Coordinates[2]);
                                                                                height    = (areaSolid.Depth / context.SCALE).ToString();
                                                                                elevation = (buildingStorey.Elevation / context.SCALE).ToString();

                                                                                if (areaSolid.SweptArea.StepClassName == "IfcArbitraryClosedProfileDef")
                                                                                { // Polyline
                                                                                    IfcArbitraryClosedProfileDef arbitraryClosedProfiles = areaSolid.SweptArea as IfcArbitraryClosedProfileDef;
                                                                                    IList <IList <double> >      polyExt = new List <IList <double> >();

                                                                                    if (arbitraryClosedProfiles.OuterCurve.StepClassName == "IfcIndexedPolyCurve")
                                                                                    {
                                                                                        IfcIndexedPolyCurve     outerCurve = arbitraryClosedProfiles.OuterCurve as IfcIndexedPolyCurve;
                                                                                        IfcCartesianPointList2D points     = outerCurve.Points as IfcCartesianPointList2D;
                                                                                        foreach (double[] pts in points.CoordList)
                                                                                        {
                                                                                            if (pts.Length >= 2)
                                                                                            {
                                                                                                try
                                                                                                {
                                                                                                    IList <double> xy = new List <double>();
                                                                                                    xy.Add(pts[0] / context.SCALE);
                                                                                                    xy.Add(pts[1] / context.SCALE);
                                                                                                    polyExt.Add(xy);
                                                                                                }
                                                                                                catch (System.Exception exTransf)
                                                                                                {
                                                                                                    Console.WriteLine("6." + exTransf.Message);
                                                                                                }
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        List <IfcPolyline> poly = arbitraryClosedProfiles.OuterCurve.Extract <IfcPolyline>();

                                                                                        if (poly.Count > 0 && poly[0].Points.Count > 0)
                                                                                        {
                                                                                            foreach (IfcCartesianPoint pt in poly[0].Points)
                                                                                            {
                                                                                                if (pt.Coordinates.Count >= 2)
                                                                                                {
                                                                                                    try
                                                                                                    {
                                                                                                        IList <double> xy = new List <double>();
                                                                                                        xy.Add(pt.Coordinates[0] / context.SCALE);
                                                                                                        xy.Add(pt.Coordinates[1] / context.SCALE);
                                                                                                        polyExt.Add(xy);
                                                                                                    }
                                                                                                    catch (System.Exception exTransf)
                                                                                                    {
                                                                                                        Console.WriteLine("7. " + exTransf.Message);
                                                                                                    }
                                                                                                }
                                                                                            }
                                                                                        }
                                                                                    }


                                                                                    coords.Add(polyExt);

                                                                                    props.Add("location", pos.Location.Coordinates[0] / context.SCALE + "," + pos.Location.Coordinates[1] / context.SCALE + "," + pos.Location.Coordinates[2] / context.SCALE);
                                                                                    if (pos.RefDirection != null)
                                                                                    {
                                                                                        props.Add("refDirection", pos.RefDirection.DirectionRatios[0] + "," + pos.RefDirection.DirectionRatios[1] + "," + pos.RefDirection.DirectionRatios[2]);
                                                                                    }
                                                                                    if (pos.Axis != null)
                                                                                    {
                                                                                        props.Add("axis", pos.Axis.DirectionRatios[0] + "," + pos.Axis.DirectionRatios[1] + "," + pos.Axis.DirectionRatios[2]);
                                                                                    }
                                                                                }
                                                                                else if (areaSolid.SweptArea.StepClassName == "IfcRectangleProfileDef") // Rectangle
                                                                                {
                                                                                    List <IfcRectangleProfileDef> rectangleProfile = areaSolid.SweptArea.Extract <IfcRectangleProfileDef>();

                                                                                    if (rectangleProfile.Count > 0)
                                                                                    {
                                                                                        if (rectangleProfile[0].XDim > 0.0000001 && rectangleProfile[0].YDim > 0.0000001)
                                                                                        {
                                                                                            if (rectangleProfile[0].Position.Location.Coordinates.Count >= 2)
                                                                                            {
                                                                                                try
                                                                                                {
                                                                                                    Point3D lm   = new Point3D(0, 0, 0);
                                                                                                    double  XDim = rectangleProfile[0].XDim / 2;
                                                                                                    double  YDim = rectangleProfile[0].YDim / 2;

                                                                                                    // Left-Bottom
                                                                                                    IList <double> lb  = new List <double>();
                                                                                                    Point3D        lbP = new Point3D(lm.X - XDim, lm.Y - YDim, lm.Z);
                                                                                                    lb.Add(lbP.X / context.SCALE);
                                                                                                    lb.Add(lbP.Y / context.SCALE);
                                                                                                    // right-Bottom
                                                                                                    IList <double> rb  = new List <double>();
                                                                                                    Point3D        rbP = new Point3D(lm.X + XDim, lm.Y - YDim, lm.Z);
                                                                                                    rb.Add(rbP.X / context.SCALE);
                                                                                                    rb.Add(rbP.Y / context.SCALE);
                                                                                                    // right-top
                                                                                                    IList <double> rt  = new List <double>();
                                                                                                    Point3D        rtP = new Point3D(lm.X + XDim, lm.Y + YDim, lm.Z);
                                                                                                    rt.Add(rtP.X / context.SCALE);
                                                                                                    rt.Add(rtP.Y / context.SCALE);
                                                                                                    // left-top
                                                                                                    IList <double> lt  = new List <double>();
                                                                                                    Point3D        ltP = new Point3D(lm.X - XDim, lm.Y + YDim, lm.Z);
                                                                                                    lt.Add(ltP.X / context.SCALE);
                                                                                                    lt.Add(ltP.Y / context.SCALE);

                                                                                                    IList <IList <double> > polyExt = new List <IList <double> >();
                                                                                                    polyExt.Add(lb);
                                                                                                    polyExt.Add(rb);
                                                                                                    polyExt.Add(rt);
                                                                                                    polyExt.Add(lt);
                                                                                                    polyExt.Add(lb);
                                                                                                    coords.Add(polyExt);
                                                                                                    props.Add("location", pos.Location.Coordinates[0] / context.SCALE + "," + pos.Location.Coordinates[1] / context.SCALE + "," + pos.Location.Coordinates[2] / context.SCALE);
                                                                                                    if (pos.RefDirection != null)
                                                                                                    {
                                                                                                        props.Add("refDirection", pos.RefDirection.DirectionRatios[0] + "," + pos.RefDirection.DirectionRatios[1] + "," + pos.RefDirection.DirectionRatios[2]);
                                                                                                    }
                                                                                                    if (pos.Axis != null)
                                                                                                    {
                                                                                                        props.Add("axis", pos.Axis.DirectionRatios[0] + "," + pos.Axis.DirectionRatios[1] + "," + pos.Axis.DirectionRatios[2]);
                                                                                                    }
                                                                                                }
                                                                                                catch (System.Exception exMatrixTransf)
                                                                                                {
                                                                                                    Console.WriteLine("8. " + exMatrixTransf.Message);
                                                                                                }
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                }
                                                                                else if (areaSolid.SweptArea.StepClassName == "IfcArbitraryProfileDefWithVoids") //
                                                                                {
                                                                                    // OuterCurve [IfcCurve]
                                                                                    IfcArbitraryProfileDefWithVoids arbitraryProfileDefWithVoids = areaSolid.SweptArea as IfcArbitraryProfileDefWithVoids;
                                                                                    IfcArbitraryClosedProfileDef    arbitraryClosedProfiles      = areaSolid.SweptArea as IfcArbitraryClosedProfileDef;
                                                                                    IList <IList <double> >         polyExt = new List <IList <double> >();

                                                                                    if (arbitraryProfileDefWithVoids.OuterCurve.StepClassName == "IfcIndexedPolyCurve")
                                                                                    {
                                                                                        IfcIndexedPolyCurve     outerCurve = arbitraryClosedProfiles.OuterCurve as IfcIndexedPolyCurve;
                                                                                        IfcCartesianPointList2D points     = outerCurve.Points as IfcCartesianPointList2D;
                                                                                        foreach (double[] pts in points.CoordList)
                                                                                        {
                                                                                            if (pts.Length >= 2)
                                                                                            {
                                                                                                try
                                                                                                {
                                                                                                    IList <double> xy = new List <double>();
                                                                                                    xy.Add(pts[0] / context.SCALE);
                                                                                                    xy.Add(pts[1] / context.SCALE);
                                                                                                    polyExt.Add(xy);
                                                                                                }
                                                                                                catch (System.Exception exTransf)
                                                                                                {
                                                                                                    Console.WriteLine("9. " + exTransf.Message);
                                                                                                }
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        List <IfcPolyline> poly = arbitraryProfileDefWithVoids.OuterCurve.Extract <IfcPolyline>();

                                                                                        foreach (IfcCartesianPoint pt in poly[0].Points)
                                                                                        {
                                                                                            if (pt.Coordinates.Count >= 2)
                                                                                            {
                                                                                                try
                                                                                                {
                                                                                                    IList <double> xy = new List <double>();
                                                                                                    Point3D        p  = new Point3D(pt.Coordinates[0], pt.Coordinates[1], 0);
                                                                                                    xy.Add(p.X / context.SCALE);
                                                                                                    xy.Add(p.Y / context.SCALE);
                                                                                                    polyExt.Add(xy);
                                                                                                }
                                                                                                catch (System.Exception exTransf)
                                                                                                {
                                                                                                    Console.WriteLine("10. " + exTransf.Message);
                                                                                                }
                                                                                            }
                                                                                        }
                                                                                    }

                                                                                    coords.Add(polyExt);

                                                                                    props.Add("location", pos.Location.Coordinates[0] / context.SCALE + "," + pos.Location.Coordinates[1] / context.SCALE + "," + pos.Location.Coordinates[2] / context.SCALE);
                                                                                    if (pos.RefDirection != null)
                                                                                    {
                                                                                        props.Add("refDirection", pos.RefDirection.DirectionRatios[0] + "," + pos.RefDirection.DirectionRatios[1] + "," + pos.RefDirection.DirectionRatios[2]);
                                                                                    }
                                                                                    if (pos.Axis != null)
                                                                                    {
                                                                                        props.Add("axis", pos.Axis.DirectionRatios[0] + "," + pos.Axis.DirectionRatios[1] + "," + pos.Axis.DirectionRatios[2]);
                                                                                    }
                                                                                }
                                                                            }
                                                                            else if (item.StepClassName == "IfcFacetedBrep-XXX")  // TODO : Fix export 3D Object
                                                                            {                                                     // https://standards.buildingsmart.org/IFC/RELEASE/IFC4_1/FINAL/HTML/schema/ifcgeometricmodelresource/lexical/ifcfacetedbrep.htm
                                                                                List <IfcFacetedBrep> facetedBreps = item.Extract <IfcFacetedBrep>();
                                                                                if (facetedBreps.Count > 0)
                                                                                {
                                                                                    IfcFacetedBrep facetedBrep = facetedBreps[0];
                                                                                    elevation = (buildingStorey.Elevation / context.SCALE).ToString();
                                                                                    if (facetedBrep.Outer.StepClassName == "IfcClosedShell")
                                                                                    {
                                                                                        if (facetedBrep.Outer.CfsFaces.Count > 0) //
                                                                                        {
                                                                                            // CfsFaces[].Bounds[IfcFaceBound].Bound.Polgon[IfcCartesianPoint].Coordinates[3]
                                                                                            // OuterCurve [IfcCurve]
                                                                                            foreach (IfcFace cfsFace in facetedBrep.Outer.CfsFaces)
                                                                                            {
                                                                                                foreach (IfcFaceBound faceBound in cfsFace.Bounds)
                                                                                                {
                                                                                                    IList <IList <double> > polyExt = new List <IList <double> >();
                                                                                                    if (faceBound.Bound.StepClassName == "IfcPolyLoop")
                                                                                                    {
                                                                                                        IfcPolyLoop polyLoop = faceBound.Bound as IfcPolyLoop;
                                                                                                        foreach (IfcCartesianPoint pt in polyLoop.Polygon)
                                                                                                        {
                                                                                                            IList <double> xy = new List <double>();
                                                                                                            xy.Add(pt.Coordinates[0] / context.SCALE); //+ loc.X);
                                                                                                            xy.Add(pt.Coordinates[1] / context.SCALE); // + loc.Y);
                                                                                                            xy.Add(pt.Coordinates[2] / context.SCALE); // + loc.YZ;
                                                                                                            polyExt.Add(xy);
                                                                                                        }
                                                                                                    }

                                                                                                    // ERREUR OBJET 3D
                                                                                                    // TODO : Fix export 3D Object
                                                                                                    // coords.Add(polyExt);
                                                                                                }
                                                                                            }
                                                                                        }
                                                                                    }
                                                                                }
                                                                            }
                                                                        }
                                                                        catch (System.Exception exRepresentationItem)
                                                                        {
                                                                            Console.WriteLine("11. Element read error exRepresentationItem" + exRepresentationItem.Message);
                                                                            returnMessage = (int)ExitCode.UnknownError;
                                                                        }
                                                                    }
                                                                }

                                                                if (coords.Count == 0)
                                                                {
                                                                    // Console.WriteLine("12. " + coords.Count);
                                                                }

                                                                props.Add("height", height);
                                                                props.Add("elevation", elevation);

                                                                geom.type        = "Polygon";
                                                                geom.coordinates = coords;

                                                                newElementProd.boundary            = new geoFeature();
                                                                newElementProd.boundary.type       = "Feature";
                                                                newElementProd.boundary.id         = null;
                                                                newElementProd.boundary.properties = props;
                                                                newElementProd.boundary.geometry   = geom;
                                                            }
                                                            var builingElements = space.Extract <IfcBuildingElementProxy>();
                                                            // IFC Elements
                                                            foreach (var bElement in builingElements)
                                                            {
                                                                IfcRelContainedInSpatialStructure productIds = bElement.ContainedInStructure;
                                                                foreach (IfcProduct pId in productIds.RelatedElements)
                                                                {
                                                                    try
                                                                    {
                                                                        if (pId.GlobalId == product.GlobalId)
                                                                        {
                                                                            newElementProd.userData.spaceId = space.GlobalId;
                                                                        }
                                                                    }
                                                                    catch (System.Exception ex)
                                                                    {
                                                                        Console.WriteLine("13. Element read error" + ex.Message);
                                                                        returnMessage = (int)ExitCode.UnknownError;
                                                                    }
                                                                }
                                                            }
                                                        }

                                                        catch (Exception ex)
                                                        {
                                                            Console.WriteLine("16. Element read error" + ex.Message);
                                                            returnMessage = (int)ExitCode.UnknownError;
                                                        }

                                                        spaceCounter += 1;
                                                    }

                                                    // Add to list
                                                    productsIds.Add(newElementProd.id);

                                                    if (newElementProd.userData.type != "IfcBuildingStorey")
                                                    {
                                                        outputElements.Add(newElementProd);
                                                    }
                                                    else
                                                    {
                                                        // Console.WriteLine("14. Error IfcBuildingStorey");
                                                    }
                                                }
                                            }
                                            catch (NotSupportedException exEncode)
                                            {
                                                Console.WriteLine("28. Name read error (product counter: " + productCounter + ") " + exEncode.Message); // returnMessage = (int)ExitCode.NodataIsAvailableForEncoding;
                                            }
                                            catch (Exception ex)
                                            {
                                                Console.WriteLine("29. Element read error" + ex.Message);
                                                returnMessage = (int)ExitCode.UnknownError;
                                            }

                                            productCounter += 1;
                                        }



                                        // IFC Elements

                                        var elements = buildingStorey.Extract <IfcBuildingElementProxy>();
                                        foreach (IfcBuildingElementProxy element in elements
                                                 .Where(element => element.GlobalId != null && !productsIds.Contains(element.GlobalId)))
                                        {
                                            try
                                            {
                                                // Add to list
                                                outputElements.Add(new JsonBuildingElementProxyIfcElement(element, storeyElement, context));
                                            }
                                            catch (Exception ex)
                                            {
                                                Console.WriteLine("17. Element read error" + ex.Message);
                                                returnMessage = (int)ExitCode.UnknownError;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("18. Element read error" + ex.Message);
                            returnMessage = (int)ExitCode.UnknownError;
                        }
                    }



                    // Json Settings
                    Newtonsoft.Json.JsonSerializerSettings jsonSettings = new Newtonsoft.Json.JsonSerializerSettings {
                        NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
                    };

                    if (activeComptactJson)
                    {
                        if (activeFullJson)
                        {
                            // Original File
                            string jsonFormat = Newtonsoft.Json.JsonConvert.SerializeObject(db.JSON(), Newtonsoft.Json.Formatting.None, jsonSettings);
                            File.WriteAllText(pathDest, jsonFormat);
                        }
                        else
                        {
                            string jsonFormat = Newtonsoft.Json.JsonConvert.SerializeObject(outputElements, Newtonsoft.Json.Formatting.None, jsonSettings);
                            File.WriteAllText(pathDest, jsonFormat);
                        }
                    }
                    else
                    {
                        if (activeFullJson)
                        {
                            // Original File
                            db.WriteFile(pathDest);
                        }
                        else
                        {
                            string jsonFormat = Newtonsoft.Json.JsonConvert.SerializeObject(outputElements, Newtonsoft.Json.Formatting.Indented, jsonSettings);
                            File.WriteAllText(pathDest, jsonFormat);
                        }
                    }
                }
                else
                {
                    returnMessage = (int)ExitCode.InvalidFilename;
                }
            }
            catch (Exception ioEx)
            {
                Console.WriteLine("19. " + ioEx.Message);
                returnMessage = (int)ExitCode.InvalidFile;
            }

            Console.WriteLine("20. " + pathDest);
            return(returnMessage);
        }
        /// <summary>
        /// Add space placement
        /// </summary>
        /// <param name="row">COBieCoordinateRow holding the data for one corner</param>
        /// <param name="rowNext">COBieCoordinateRow holding the data for the other corner</param>
        private void AddBoundingBoxAsExtrudedAreaSolid(COBieCoordinateRow row, COBieCoordinateRow rowNext)
        {
            if (row.SheetName.ToLower() == "floor")
            {
                IfcBuildingStorey ifcBuildingStorey = null;
                if (ValidateString(row.ExtIdentifier))
                {
                    IfcGloballyUniqueId id = new IfcGloballyUniqueId(row.ExtIdentifier);
                    ifcBuildingStorey = Model.FederatedInstances.Where <IfcBuildingStorey>(bs => bs.GlobalId == id).FirstOrDefault();
                }

                if ((ifcBuildingStorey == null) && (ValidateString(row.RowName)))
                {
                    ifcBuildingStorey = Model.FederatedInstances.Where <IfcBuildingStorey>(bs => bs.Name == row.RowName).FirstOrDefault();
                }

                if (ifcBuildingStorey != null)
                {
                    //using statement will set the Model.OwnerHistoryAddObject to IfcRoot.OwnerHistory as OwnerHistoryAddObject is used upon any property changes,
                    //then swaps the original OwnerHistoryAddObject back in the dispose, so set any properties within the using statement
                    using (COBieXBimEditScope context = new COBieXBimEditScope(Model, ifcBuildingStorey.OwnerHistory))
                    {
                        var placementRelToIfcProduct = ifcBuildingStorey.GetContainingStructuralElement();
                        AddExtrudedRectangle(row, rowNext, ifcBuildingStorey, placementRelToIfcProduct);
                    }
                }
            }
            if (row.SheetName.ToLower() == "space")
            {
                IfcSpace ifcSpace = null;
                if (ValidateString(row.ExtIdentifier))
                {
                    IfcGloballyUniqueId id = new IfcGloballyUniqueId(row.ExtIdentifier);
                    ifcSpace = Model.FederatedInstances.Where <IfcSpace>(bs => bs.GlobalId == id).FirstOrDefault();
                }
                if ((ifcSpace == null) && (ValidateString(row.RowName)))
                {
                    ifcSpace = Model.FederatedInstances.Where <IfcSpace>(bs => bs.Name == row.RowName).FirstOrDefault();
                }
                if ((ifcSpace == null) && (ValidateString(row.RowName)))
                {
                    IEnumerable <IfcSpace> ifcSpaces = Model.FederatedInstances.Where <IfcSpace>(bs => bs.Description == row.RowName);
                    //check we have one, if >1 then no match
                    if ((ifcSpaces.Any()) && (ifcSpaces.Count() == 1))
                    {
                        ifcSpace = ifcSpaces.FirstOrDefault();
                    }
                }

                if (ifcSpace != null)
                {
                    if (ifcSpace.Representation != null) //check it has no graphics attached, if it has then skip
                    {
                        return;
                    }
                    //using statement will set the Model.OwnerHistoryAddObject to IfcRoot.OwnerHistory as OwnerHistoryAddObject is used upon any property changes,
                    //then swaps the original OwnerHistoryAddObject back in the dispose, so set any properties within the using statement
                    using (COBieXBimEditScope context = new COBieXBimEditScope(Model, ifcSpace.OwnerHistory))
                    {
                        var placementRelToIfcProduct = ifcSpace.GetContainingStructuralElement();
                        AddExtrudedRectangle(row, rowNext, ifcSpace, placementRelToIfcProduct);
                    }
                }
            }

            if (row.SheetName.ToLower() == "component")
            {
                IfcElement ifcElement = null;
                if (ValidateString(row.ExtIdentifier))
                {
                    IfcGloballyUniqueId id = new IfcGloballyUniqueId(row.ExtIdentifier);
                    ifcElement = Model.FederatedInstances.Where <IfcElement>(bs => bs.GlobalId == id).FirstOrDefault();
                }
                if ((ifcElement == null) && (ValidateString(row.RowName)))
                {
                    ifcElement = Model.FederatedInstances.Where <IfcElement>(bs => bs.Name == row.RowName).FirstOrDefault();
                }

                if ((ifcElement == null) && (ValidateString(row.RowName)))
                {
                    IEnumerable <IfcElement> ifcElements = Model.FederatedInstances.Where <IfcElement>(bs => bs.Description == row.RowName);
                    //check we have one, if >1 then no match
                    if ((ifcElements.Any()) && (ifcElements.Count() == 1))
                    {
                        ifcElement = ifcElements.FirstOrDefault();
                    }
                }

                if (ifcElement != null)
                {
                    if (ifcElement.Representation != null) //check it has no graphics attached, if it has then skip
                    {
                        return;
                    }

                    //using statement will set the Model.OwnerHistoryAddObject to IfcRoot.OwnerHistory as OwnerHistoryAddObject is used upon any property changes,
                    //then swaps the original OwnerHistoryAddObject back in the dispose, so set any properties within the using statement
                    using (COBieXBimEditScope context = new COBieXBimEditScope(Model, ifcElement.OwnerHistory))
                    {
                        IfcProduct placementRelToIfcProduct = ifcElement.ContainedInStructure as IfcProduct;
                        IfcRelContainedInSpatialStructure ifcRelContainedInSpatialStructure = Model.FederatedInstances.OfType <IfcRelContainedInSpatialStructure>().Where(rciss => rciss.RelatedElements.Contains(ifcElement)).FirstOrDefault();
                        if ((ifcRelContainedInSpatialStructure != null) &&
                            (ifcRelContainedInSpatialStructure.RelatingStructure != null)
                            )
                        {
                            placementRelToIfcProduct = ifcRelContainedInSpatialStructure.RelatingStructure;
                            AddExtrudedRectangle(row, rowNext, ifcElement, placementRelToIfcProduct);
                        }
                        else
                        {
#if DEBUG
                            Console.WriteLine("COBieXBimCoordinate.AddBoundingBoxAsExtrudedAreaSolid: Cannot find Parent object placement");
#endif
                        }
                    }
                }
                else
                {
#if DEBUG
                    Console.WriteLine("COBieXBimCoordinate.AddBoundingBoxAsExtrudedAreaSolid: Cannot find object to relate points too");
#endif
                }
            }
        }
Beispiel #12
0
        /// <summary>
        /// Write the model to IFC.
        /// </summary>
        /// <param name="model"></param>
        /// <param name="path">The path to the generated IFC STEP file.</param>
        public static void ToIFC(this Model model, string path)
        {
            var ifc = new Document("elements", "elements", Environment.UserName,
                                   null, null, null, "elements", null, null,
                                   null, null, null, null, null, null
                                   );

            var proj = ifc.AllInstancesOfType <IfcProject>().FirstOrDefault();

            // Add a site
            var site          = new IfcSite(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, IfcElementCompositionEnum.ELEMENT);
            var projAggregate = new IfcRelAggregates(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, proj, new List <IfcObjectDefinition> {
                site
            });

            // Add building and building storey
            var building  = new IfcBuilding(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, IfcElementCompositionEnum.ELEMENT);
            var storey    = new IfcBuildingStorey(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, IfcElementCompositionEnum.ELEMENT);
            var aggregate = new IfcRelAggregates(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, building, new List <IfcObjectDefinition> {
                storey
            });

            // Aggregate the building into the site
            var siteAggregate = new IfcRelAggregates(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, site, new List <IfcObjectDefinition> {
                building
            });

            ifc.AddEntity(site);
            ifc.AddEntity(projAggregate);
            ifc.AddEntity(building);
            ifc.AddEntity(storey);
            ifc.AddEntity(aggregate);
            ifc.AddEntity(siteAggregate);

            // Materials
            // foreach(var m in model.Materials.Values)
            // {
            //     var ifcMaterial = new IfcMaterial(m.Name);
            //     ifc.AddEntity(ifcMaterial);
            // }

            var products = new List <IfcProduct>();
            var context  = ifc.AllInstancesOfType <IfcGeometricRepresentationContext>().FirstOrDefault();

            foreach (var e in model.Elements.Values)
            {
                try
                {
                    if (e is Wall)
                    {
                        var w       = (Wall)e;
                        var ifcWall = w.ToIfcWallStandardCase(context, ifc);
                        products.Add(ifcWall);
                    }

                    if (e is Beam)
                    {
                        var b       = (Beam)e;
                        var ifcBeam = b.ToIfcBeam(context, ifc);
                        products.Add(ifcBeam);
                    }
                }
                catch
                {
                    continue;
                }
            }

            var spatialRel = new IfcRelContainedInSpatialStructure(IfcGuid.ToIfcGuid(Guid.NewGuid()), null, products, storey);

            ifc.AddEntity(spatialRel);

            if (File.Exists(path))
            {
                File.Delete(path);
            }
            File.WriteAllText(path, ifc.ToSTEP(path));
        }
Beispiel #13
0
        private static void CreateStorey(XbimModel model, IfcBuilding building, float levelHeight, List <List <IfcProduct> > productsLists)
        {
            using (XbimReadWriteTransaction txn = model.BeginTransaction("Create Storey"))
            {
                int floorNumber = 0;
                if (productsLists != null)
                {
                    foreach (List <IfcProduct> ProductsStorey in productsLists)
                    {
                        var storey = model.Instances.New <IfcBuildingStorey>();
                        storey.Name = "Level " + ++floorNumber;
                        storey.OwnerHistory.OwningUser        = model.DefaultOwningUser;
                        storey.OwnerHistory.OwningApplication = model.DefaultOwningApplication;
                        storey.Elevation       = levelHeight;
                        storey.CompositionType = IfcElementCompositionEnum.ELEMENT;
                        //storey.GlobalId = new Xbim.Ifc2x3.UtilityResource.IfcGloballyUniqueId();

                        storey.ObjectPlacement = model.Instances.New <IfcLocalPlacement>();
                        var localPlacement = storey.ObjectPlacement as IfcLocalPlacement;

                        if (localPlacement != null && localPlacement.RelativePlacement == null)
                        {
                            localPlacement.RelativePlacement = model.Instances.New <IfcAxis2Placement3D>();
                            var placement = localPlacement.RelativePlacement as IfcAxis2Placement3D;
                            placement.SetNewLocation(0.0, 0.0, floorNumber * levelHeight);
                        }


                        IfcRelContainedInSpatialStructure RelationSpatial = model.Instances.New <IfcRelContainedInSpatialStructure>();


                        foreach (IfcProduct item in ProductsStorey)
                        {
                            //storey.AddElement(item);
                            RelationSpatial.RelatedElements.Add(item);
                            ///=============================
                            //IfcRelContainedInSpatialStructure RelationSpatial = model.Instances.New<IfcRelContainedInSpatialStructure>();
                            //RelationSpatial.RelatedElements.Add(item);
                            //RelationSpatial.RelatingStructure = storey;
                        }

                        RelationSpatial.RelatingStructure = storey;

                        building.AddToSpatialDecomposition(storey);
                    }
                }

                //validate and commit changes
                if (model.Validate(txn.Modified(), Console.Out) == 0)
                {
                    txn.Commit();
                }
                else
                {
                    using (StreamWriter str = new StreamWriter("E:\\storey " + floorNumber + " Errors"))
                    {
                        model.Validate(txn.Modified(), str);
                    }
                }
            }
        }
Beispiel #14
0
        //public List<BbPaintFinish> PaintFinishes { get; protected set; }
        //public void AddPaintFinish(BbPaintFinish paintFinish)
        //{
        //    if (PaintFinishes == null)
        //    {
        //        PaintFinishes = new List<BbPaintFinish>();
        //    }
        //    if (IfcRelCoversBldgElements == null)
        //    {
        //        IfcRelCoversBldgElements = new IfcRelCoversBldgElements
        //            {
        //                GlobalId = IfcGloballyUniqueId.NewGuid(),
        //                OwnerHistory = BbHeaderSetting.Setting3D.IfcOwnerHistory,
        //                RelatingBuildingElement = IfcObject as IfcElement,
        //                RelatedCoverings = new List<IfcCovering>(),
        //            };
        //    }
        //    IfcRelCoversBldgElements.RelatedCoverings.Add(paintFinish.IfcCovering);
        //    PaintFinishes.Add(paintFinish);
        //}
        //public void AddPaintFinish(SemPaintFinishPatch semPaintFinish, BbLocalPlacement3D semLocalPlacement3D)
        //{
        //    AddPaintFinish(semPaintFinish);
        //    semPaintFinish.BbLocalPlacement3D = semLocalPlacement3D;
        //}
        //public ICollection<BbElement> Retrieve();
        public void AddToSpatialElement(BbSpatialElement bbSpatialElement)
        {
            BbSpatialElement = bbSpatialElement;
            var a = EarlyBindingInstanceModel.GetReferencedEntities(bbSpatialElement.IfcSpatialStructureElement.EIN).Values;

            var b = (from x in a.OfType<IfcRelContainedInSpatialStructure>()
                     where x.RelatingStructure.EIN == bbSpatialElement.IfcSpatialStructureElement.EIN
                     select x).ToList();

            switch (b.Count)
            {

                case 0:
                    IfcRelContainedInSpatialStructure = new IfcRelContainedInSpatialStructure
                    {
                        GlobalId = IfcGloballyUniqueId.NewGuid(),
                        OwnerHistory = IfcObject.OwnerHistory,
                        RelatingStructure = bbSpatialElement.IfcSpatialStructureElement,
                        RelatedElements = new List<IfcProduct>() { },
                    };
                    break;
                case 1:
                    IfcRelContainedInSpatialStructure = b[0];
                    break;
                default:
                    throw new NotImplementedException();
            }

            IfcRelContainedInSpatialStructure.RelatedElements.Add(IfcObject as IfcElement);
        }
Beispiel #15
0
        protected BbAssembly(
            BbSpatialElement floor,
            IfcElementAssembly assembly,
            IfcRelContainedInSpatialStructure spatialStructure)
        {
            //BbSpatialElement = floor;
            _ifcElementAssembly = assembly;
            AddToSpatialElement(floor);

        }