예제 #1
0
        /// <summary>
        /// Performs the grouping of elements of the model according to the rules defined in the XML pointed by <paramref name="XMLfileName"/>
        /// </summary>
        /// <param name="XMLfileName">Name of the xml file defining the grouping rules.</param>
        /// <returns></returns>
        public bool GroupElements(string XMLfileName, IfcGroup rootGroup = null)
        {
            if (string.IsNullOrEmpty(XMLfileName))
            {
                throw new ArgumentNullException("File name cannot be null or empty.");
            }
            _xmlDoc = new XmlDocument();
            _xmlDoc.Load(XMLfileName);


            using (XbimReadWriteTransaction trans = _model.BeginTransaction())
            {
                if (rootGroup != null)
                {
                    if (((IPersistIfcEntity)rootGroup).ModelOf != _model)
                    {
                        throw new Exception("Model of the group is different than model to be used.");
                    }
                    _rootGroup = rootGroup;
                }
                else
                {
                    _rootGroup = _model.Instances.New <IfcGroup>(g => g.Name = "Root group");
                }

                bool result = PerformGrouping();
                trans.Commit();
                return(result);
            }
        }
예제 #2
0
 public void CreateGroups(XmlDocument xmlDocument)
 {
     _xmlDoc = xmlDocument;
     using (XbimReadWriteTransaction trans = _model.BeginTransaction())
     {
         Process();
         trans.Commit();
     }
 }
예제 #3
0
        //sample to show how to create a model from scratch

        static void Main(string[] args)
        {
            Logger.Debug("Creating Model...");
            XbimModel model = CreateModel("NewModel");

            if (model != null)
            {
                using (XbimReadWriteTransaction txn = model.BeginTransaction()) //start a readwrite transaction
                {
                    try
                    {
                        IfcProject project = model.Instances.New <IfcProject>(); //Project Created

                        txn.Commit();                                            //commit the changes if nothing went wrong
                    }
                    catch (Exception e)
                    {
                        Logger.DebugFormat("Error {0}\nRolling back changes.....", e.Message);
                    }
                }
                model.SaveAs("NewModel.ifc", XbimStorageType.IFC); //export as an Ifc File
                model.Close();                                     //close the model and release all resources and handles
            }

            Logger.Debug("Model Created Ended...");
            Console.ReadLine();
            // CreateProject
        }
예제 #4
0
        private void Modify_Click(object sender, RoutedEventArgs e)
        {
            XbimModel model = DataContext as XbimModel;

            foreach (var item in FederatedList.SelectedItems)
            {
                if (item is XbimReferencedModel)
                {
                    var rItem = item as XbimReferencedModel;
                    AddFederatedModel fdlg = new AddFederatedModel(rItem);

                    bool?done = fdlg.ShowDialog();
                    if (done.HasValue && done.Value == true)
                    {
                        string fileName = fdlg.FileName;
                        string ext      = System.IO.Path.GetExtension(fileName);
                        using (XbimModel refM = new XbimModel())
                        {
                            if (string.Compare(ext, ".xbim", true) != 0)
                            {
                                refM.CreateFrom(fileName, null, null, true);
                                var m3D = new Xbim3DModelContext(refM);
                                m3D.CreateContext();
                                fileName = System.IO.Path.ChangeExtension(fileName, "xbim");
                            }
                        }
                        using (var txn = model.BeginTransaction())
                        {
                            rItem.DocumentInformation.Name = fileName;
                            txn.Commit();
                        }
                    }
                }
            }
        }
예제 #5
0
        static private IfcBuilding CreateBuilding(XbimModel model, HndzBuilding hndzBuilding)
        {
            using (XbimReadWriteTransaction txn = model.BeginTransaction("Create Building"))
            {
                var building = model.Instances.New <IfcBuilding>();
                building.Name = hndzBuilding.Name;
                building.OwnerHistory.OwningUser        = model.DefaultOwningUser;
                building.OwnerHistory.OwningApplication = model.DefaultOwningApplication;
                building.ElevationOfRefHeight           = hndzBuilding.RefHeight;
                building.CompositionType = IfcElementCompositionEnum.ELEMENT;

                building.ObjectPlacement = model.Instances.New <IfcLocalPlacement>();
                var localPlacement = building.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, 0.0);
                }

                model.IfcProject.AddBuilding(building);
                //validate and commit changes
                if (model.Validate(txn.Modified(), Console.Out) == 0)
                {
                    txn.Commit();
                    return(building);
                }
            }
            return(null);
        }
예제 #6
0
        /// <summary>
        /// Sets up the basic parameters any model must provide, units, ownership etc
        /// </summary>
        /// <param name="projectName">Name of the project</param>
        /// <returns></returns>
        private XbimModel CreateandInitModel(string projectName)
        {
            XbimModel model = XbimModel.CreateModel(projectName + ".xBIM");;  //create an empty model

            //Begin a transaction as all changes to a model are transacted
            using (XbimReadWriteTransaction txn = model.BeginTransaction("Initialise Model"))
            {
                //do once only initialisation of model application and editor values
                model.DefaultOwningUser.ThePerson.GivenName              = "John";
                model.DefaultOwningUser.ThePerson.FamilyName             = "Bloggs";
                model.DefaultOwningUser.TheOrganization.Name             = "Department of Building";
                model.DefaultOwningApplication.ApplicationIdentifier     = "Construction Software inc.";
                model.DefaultOwningApplication.ApplicationDeveloper.Name = "Construction Programmers Ltd.";
                model.DefaultOwningApplication.ApplicationFullName       = "Ifc sample programme";
                model.DefaultOwningApplication.Version = "2.0.1";

                //set up a project and initialise the defaults

                IfcProject project = model.Instances.New <IfcProject>();
                project.Initialize(ProjectUnits.SIUnitsUK);
                project.Name = "testProject";
                project.OwnerHistory.OwningUser        = model.DefaultOwningUser;
                project.OwnerHistory.OwningApplication = model.DefaultOwningApplication;

                //validate and commit changes
                if (model.Validate(txn.Modified(), Console.Out) == 0)
                {
                    txn.Commit();
                    return(model);
                }
            }
            return(null); //failed so return nothing
        }
예제 #7
0
        /// <summary>
        /// Add the refrence models
        /// </summary>
        /// <param name="file">FileInfo for the xbimf file</param>
        /// <param name="organizationName">Organisation Name</param>
        /// <param name="role">RoleFilter</param>
        /// <param name="displayName"></param>
        public void AddRefModel(FileInfo file, string organizationName, RoleFilter roles = RoleFilter.Unknown, string displayName = null)
        {
            if (!file.Exists)
            {
                throw new FileNotFoundException("Cannot find reference model file", file.FullName);
            }

            //add model to list of referenced models
            IfcIdentifier docId = _fedModel.AddModelReference(file.FullName, organizationName, IfcRole.UserDefined).Identifier;

            using (var txn = _fedModel.BeginTransaction())
            {
                IfcDocumentInformation addDocId = _fedModel.ReferencedModels.Where(item => item.DocumentInformation.DocumentId == docId).Select(item => item.DocumentInformation).FirstOrDefault();
                IfcOrganization        org      = addDocId.DocumentOwner as IfcOrganization;
                if (org != null)
                {
                    org.Roles.Clear();
                    //Add Roles
                    foreach (var item in GetActorRoles(roles))
                    {
                        org.AddRole(item);
                    }
                }
                //add display name if required
                if (displayName != null)
                {
                    addDocId.Description = displayName;
                }
                txn.Commit();
            }
        }
예제 #8
0
        public void CreateSystem(XbimModel model, string classificationName)
        {
            //set model in which the systems are to be created
            _model = model;
            string data = null;

            //try to get data from resources

            //get list of classifications available
            var dir = Directory.EnumerateFiles("Classifications");
            string clasPath = null;
            foreach (var f in dir)
            {
                if (Path.GetFileNameWithoutExtension(f).ToLower() == classificationName.ToLower())
                {
                    clasPath = f;
                    break;
                }
            }
            if (clasPath == null)
                throw new ArgumentException("Specified classification doesn't exist");
            var clasName = Path.GetFileNameWithoutExtension(clasPath);

            //get data
            data = File.ReadAllText(clasPath);

            CsvLineParser parser = null;
            if (clasName.Contains("NRM"))
            {
                parser = new CsvLineParser(';');
            }
            else
                parser = new CsvLineParser();

            //create classification source
            var action = new Action<XbimModel>(m => {
                var source = model.Instances.New<IfcClassification>(c =>
                {
                    c.Source = clasName;
                    c.Edition = "Default edition";
                    c.Name = clasName;
                });
                ParseCSV(data, parser, source);
            });

            //process file
            if (_model.IsTransacting)
                action(_model);
            else
                using (var txn = model.BeginTransaction("Systems creation"))
                {
                    action(_model);
                    txn.Commit();
                }
        }
예제 #9
0
        private static IfcBeam CreateBeam(XbimModel model, HndzStructuralElement genericProducthndz)
        {
            using (XbimReadWriteTransaction txn = model.BeginTransaction("Create" + genericProducthndz.ToString()))
            {
                IfcBeam genericProductIfc        = model.Instances.New <IfcBeam>();
                IfcExtrudedAreaSolid body        = model.Instances.New <IfcExtrudedAreaSolid>();
                IfcBeamType          elementType = model.Instances.New <IfcBeamType>();
                elementType.PredefinedType = IfcBeamTypeEnum.BEAM;


                if (genericProducthndz.Profile is HndzRectangularProfile)
                {
                    HndzRectangularProfile genericProfilehndz = genericProducthndz.Profile as HndzRectangularProfile;

                    IfcRectangleProfileDef ifcGenericProfile = AssignRectangularProfile(model, genericProducthndz, genericProductIfc, elementType, genericProfilehndz);

                    //model as a swept area solid
                    body.SweptArea = ifcGenericProfile;
                }

                if (genericProducthndz.Profile is HndzISectionProfile)
                {
                    HndzISectionProfile genericProfilehndz = genericProducthndz.Profile as HndzISectionProfile;

                    IfcIShapeProfileDef ifcGenericProfile = AssignIProfile(model, genericProducthndz, genericProductIfc, elementType, genericProfilehndz);


                    //model as a swept area solid
                    body.SweptArea = ifcGenericProfile;
                }
                if (genericProducthndz.Profile is HndzCSectionProfile)
                {
                    HndzCSectionProfile genericProfilehndz = genericProducthndz.Profile as HndzCSectionProfile;
                    IfcCShapeProfileDef ifcGenericProfile  = AssignCsectionProfile(model, genericProducthndz, genericProductIfc, elementType, genericProfilehndz);


                    //model as a swept area solid
                    body.SweptArea = ifcGenericProfile;
                }

                AdjustExtrusion(model, body, genericProducthndz, genericProductIfc);

                if (model.Validate(txn.Modified(), Console.Out) == 0)
                {
                    txn.Commit();
                    return(genericProductIfc);
                }

                return(null);
            }
        }
예제 #10
0
        /// <summary>
        /// Add some properties to the wall,
        /// </summary>
        /// <param name="model">XbimModel</param>
        private void AddPropertiesToWall(XbimModel model, IfcWallStandardCase wall)
        {
            using (XbimReadWriteTransaction txn = model.BeginTransaction("Create Wall"))
            {
                IfcOwnerHistory ifcOwnerHistory = model.IfcProject.OwnerHistory; //we just use the project owner history for the properties, saves creating one
                CreateElementQuantity(model, wall, ifcOwnerHistory);
                CreateSimpleProperty(model, wall, ifcOwnerHistory);

                //if (model.Validate(txn.Modified(), Console.Out) == 0)
                //{
                txn.Commit();
                //}
                var xx = model.Instances.OfType <IfcPropertyReferenceValue>();
            }
        }
예제 #11
0
        /// <summary>
        /// Creat the federated file
        /// </summary>
        /// <param name="file">FileInfo for the xbimf file</param>
        /// <param name="author">Author name</param>
        /// <param name="organisation">Orgsnisation Name</param>
        /// <param name="prjName">Project Name</param>
        public void Create(FileInfo file, string author, string organisation, string prjName = null)
        {
            FileNameXbimf = file;
            //_fedModel = XbimModel.CreateTemporaryModel();
            _fedModel = XbimModel.CreateModel(file.FullName, XbimDBAccess.ReadWrite);

            _fedModel.Initialise(author, organisation, "xBIM", "xBIM Team", ""); //"" is version, but none to grab as yet

            using (var txn = _fedModel.BeginTransaction())
            {
                _fedModel.IfcProject.Name = (prjName != null) ? prjName : string.Empty;
                _fedModel.Header          = new IfcFileHeader(IfcFileHeader.HeaderCreationMode.InitWithXbimDefaults);
                txn.Commit();
            }
        }
예제 #12
0
 private IfcBuilding AddBuilding(XbimModel model, IfcBuilding _building)
 {
     using (XbimReadWriteTransaction txn = model.BeginTransaction("Add Building"))
     {
         //var building = model.Instances.New<IfcBuilding>();
         //var building = model.InsertCopy<IfcBuilding>(_building, txn);
         //_building.Bind
         model.IfcProject.AddBuilding(_building);
         //validate and commit changes
         if (model.Validate(txn.Modified(), Console.Out) == 0)
         {
             txn.Commit();
             return _building;
         }
     }
     return null;
 }
예제 #13
0
        /// <summary>
        /// This sample demonstrates the minimum steps to create a compliant IFC model that contains a single standard case wall
        /// </summary>
        /// <param name="args"></param>
        public void Run()
        {
            //first create and initialise a model called Hello Wall
            Console.WriteLine("Initialising the IFC Project....");
            XbimModel model = CreateandInitModel("HelloWall");

            if (model != null)
            {
                IfcBuilding building = CreateBuilding(model, "Default Building", 2000);


                IfcWallStandardCase wall = CreateWall(model, 4000, 300, 2400);
                if (wall != null)
                {
                    AddPropertiesToWall(model, wall);
                }
                using (XbimReadWriteTransaction txn = model.BeginTransaction("Add Wall"))
                {
                    building.AddElement(wall);
                    txn.Commit();
                }

                if (wall != null)
                {
                    try
                    {
                        Console.WriteLine("Standard Wall successfully created....");
                        //write the Ifc File
                        model.SaveAs("HelloWall.ifc", XbimStorageType.IFC);
                        Console.WriteLine("HelloWall.ifc has been successfully written");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Failed to save HelloWall.ifc");
                        Console.WriteLine(e.Message);
                    }
                }
            }
            else
            {
                Console.WriteLine("Failed to initialise the model");
            }

            Console.WriteLine("Press any key to exit....");
            Console.ReadKey();
        }
예제 #14
0
        static private XbimModel CreateandInitModel(HndzProject hndzProject)
        {
            //IfcRelAggregates
            //Crashes here.....Fixed in this update :D

            XbimModel model = XbimModel.CreateModel(hndzProject.Name + "No." + hndzProject.GlobalId + ".xBIM", Xbim.XbimExtensions.XbimDBAccess.ReadWrite); //create an empty model

            if (model != null)
            {
                //Begin a transaction as all changes to a model are transacted
                using (XbimReadWriteTransaction txn = model.BeginTransaction("Initialize Model"))
                {
                    //do once only initialization of model application and editor values
                    model.DefaultOwningUser.ThePerson.GivenName              = hndzProject.Owner.Name;
                    model.DefaultOwningUser.ThePerson.FamilyName             = hndzProject.Owner.LastName;
                    model.DefaultOwningUser.TheOrganization.Name             = hndzProject.Owner.Organization;
                    model.DefaultOwningApplication.ApplicationIdentifier     = IFCFileResources.ApplicationIdentifier;
                    model.DefaultOwningApplication.ApplicationDeveloper.Name = IFCFileResources.ApplicationDevelopers;
                    model.DefaultOwningApplication.ApplicationFullName       = IFCFileResources.ApplicationFullName;
                    model.DefaultOwningApplication.Version = IFCFileResources.CurrentApplicationVersion;

                    //set up a project and initialize the defaults

                    var project = model.Instances.New <IfcProject>();
                    project.Initialize(ProjectUnits.SIUnitsUK);
                    project.Name = hndzProject.Name;
                    project.OwnerHistory.OwningUser        = model.DefaultOwningUser;
                    project.OwnerHistory.OwningApplication = model.DefaultOwningApplication;

                    //validate and commit changes
                    if (model.Validate(txn.Modified(), Console.Out) == 0)
                    {
                        txn.Commit();
                        return(model);
                    }
                }
            }
            return(null); //failed so return nothing
        }
예제 #15
0
        private IfcProduct CopyProduct(XbimModel newmodel, XbimModel model, IfcProduct _prod)
        {
            using (XbimReadWriteTransaction txn = newmodel.BeginTransaction("CopyProduct"))
            {
                PropertyTranformDelegate propTransform = delegate (IfcMetaProperty prop, object toCopy)
                {
                    var value = prop.PropertyInfo.GetValue(toCopy, null);
                    return value;
                };

                var copied = new XbimInstanceHandleMap(model, newmodel);
                IPersistIfcEntity ent = _prod as IPersistIfcEntity;
                XbimInstanceHandle toCopyHandle = ent.GetHandle();
                XbimInstanceHandle copyHandle;
                if (copied.TryGetValue(toCopyHandle, out copyHandle))
                {
                    //Debug.Assert(copyHandle != null);
                    txn.Commit();
                    return copyHandle.GetEntity() as IfcProduct;
                }
                txn.Pulse();
                IfcType ifcType = IfcMetaData.IfcType(ent);
                //int copyLabel = ent.EntityLabel;
                var _ent = newmodel.Instances.New(ifcType.Type);
                copyHandle = _ent.GetHandle();//InsertNew(ifcType.Type, copyLabel);
                copied.Add(toCopyHandle, copyHandle);
                if (typeof(IfcCartesianPoint) == ifcType.Type || typeof(IfcDirection) == ifcType.Type)//special cases for cartesian point and direction for efficiency
                {
                    IPersistIfcEntity v = (IPersistIfcEntity)Activator.CreateInstance(ifcType.Type, new object[] { ent });
                    v.Bind(newmodel, copyHandle.EntityLabel, true);
                    v.Activate(true);
                    txn.Commit();
                    return copyHandle.GetEntity() as IfcProduct;
                    //read.TryAdd(copyHandle.EntityLabel, v);
                    //createdNew.TryAdd(copyHandle.EntityLabel, v);
                    //return (T)v;
                }
                else
                {
                    IPersistIfcEntity theCopy = (IPersistIfcEntity)Activator.CreateInstance(copyHandle.EntityType);
                    theCopy.Bind(newmodel, copyHandle.EntityLabel, true);
                    //read.TryAdd(copyHandle.EntityLabel, theCopy);
                    //createdNew.TryAdd(copyHandle.EntityLabel, theCopy);
                    // IfcRoot rt = theCopy as IfcRoot;
                    IEnumerable<IfcMetaProperty> props = ifcType.IfcProperties.Values.Where(p => !p.IfcAttribute.IsDerivedOverride);
                    // if (rt != null) rt.OwnerHistory = _model.OwnerHistoryAddObject;
                    foreach (IfcMetaProperty prop in props)
                    {
                        //if (rt != null && prop.PropertyInfo.Name == "OwnerHistory") //don't add the owner history in as this will be changed later
                        //    continue;
                        object value;
                        if (propTransform != null)
                            value = propTransform(prop, ent);
                        else
                            value = prop.PropertyInfo.GetValue(ent, null);
                        if (value != null)
                        {
                            Type theType = value.GetType();
                            //if it is an express type or a value type, set the value
                            if (theType.IsValueType || typeof(ExpressType).IsAssignableFrom(theType))
                            {
                                prop.PropertyInfo.SetValue(theCopy, value, null);
                            }

                        }
                    }
                    //  if (rt != null) rt.OwnerHistory = this.OwnerHistoryAddObject;
                    _prod = theCopy as IfcProduct;
                }

                if (newmodel.Validate(txn.Modified(), Console.Out) == 0)
                {
                    txn.Commit();
                    return _prod;
                }
            }
            return null;
        }
예제 #16
0
        private IfcBuilding CreateBuilding(XbimModel model, string name)
        {
            using (XbimReadWriteTransaction txn = model.BeginTransaction("Create Building"))
            {
                var building = model.Instances.New<IfcBuilding>();
                building.Name = name;
                building.OwnerHistory.OwningUser = model.DefaultOwningUser;
                building.OwnerHistory.OwningApplication = model.DefaultOwningApplication;
                //building.ElevationOfRefHeight = elevHeight;
                building.CompositionType = IfcElementCompositionEnum.ELEMENT;

                building.ObjectPlacement = model.Instances.New<IfcLocalPlacement>();
                var localPlacement = building.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, 0.0);
                }

                model.IfcProject.AddBuilding(building);
                //validate and commit changes
                if (model.Validate(txn.Modified(), Console.Out) == 0)
                {
                    txn.Commit();
                    return building;
                }

            }
            return null;
        }
예제 #17
0
        private void CopyInstance(XbimModel newmodel, XbimModel model, IPersistIfcEntity ent)
        {
            newmodel.AutoAddOwnerHistory = false;
            using (XbimReadWriteTransaction txn = newmodel.BeginTransaction("CopyInstance"))
            {
                PropertyTranformDelegate propTransform = delegate (IfcMetaProperty prop, object toCopy)
                {
                    var value = prop.PropertyInfo.GetValue(toCopy, null);
                    return value;
                };

                var copied = new XbimInstanceHandleMap(model, newmodel);

                try
                {
                    newmodel.InsertCopy(ent, copied, txn, propTransform);
                }
                catch(Exception ex)
                {
                    AddMessages(" " + ex.Message);
                    Debug.WriteLine(" " + ex.Message);
                }

                if (model.Validate(txn.Modified(), Console.Out) == 0)
                {
                    txn.Commit();
                }
            }
        }
예제 #18
0
        private void CopyInstances(XbimModel newmodel, XbimModel model)
        {
            newmodel.AutoAddOwnerHistory = false;
            using (XbimReadWriteTransaction txn = newmodel.BeginTransaction("CopyInstances"))
            {
                PropertyTranformDelegate propTransform = delegate (IfcMetaProperty prop, object toCopy)
                {
                    var value = prop.PropertyInfo.GetValue(toCopy, null);
                    return value;
                };

                var copied = new XbimInstanceHandleMap(model, newmodel);

                foreach (var ent in model.Instances)
                {
                    newmodel.InsertCopy(ent, copied, txn, propTransform);
                }

                if (model.Validate(txn.Modified(), Console.Out) == 0)
                {
                    txn.Commit();
                }
            }
        }
예제 #19
0
        public void BooleanCutShellTest()
        {
            using (var m = new XbimModel())
            {

                m.CreateFrom("SolidTestFiles\\7- Boolean_IfcHalfspace_With_IfcExtrudedAreaSolid.ifc", null, null,
                    true, true);
                var fbsm = m.Instances[57] as IfcConnectedFaceSet;
                Assert.IsFalse(fbsm == null, "IfcConnectedFaceSet is invalid");

                var shell = _xbimGeometryCreator.CreateShell(fbsm);

                using (var txn = m.BeginTransaction())
                {
                    var ifcCylinder = IfcModelBuilder.MakeRightCircularCylinder(m, 500, 1500);
                    ifcCylinder.Position.Location.SetXYZ(-23000, 12000, 2000);
                    var cylinder = _xbimGeometryCreator.CreateSolid(ifcCylinder);
                    var shellSet = (IXbimShellSet)shell.Cut(cylinder, m.ModelFactors.PrecisionBoolean);
                    Assert.IsTrue(shellSet.Count == 1, "Cutting this shell should return a single shell");
                    var resultShell = shellSet.First;
                    Assert.IsTrue(shell.SurfaceArea > resultShell.SurfaceArea,
                        "The surface area of the result should be less than the original");
                }
            }
        }
예제 #20
0
        private IfcBuildingStorey CopyBuildingStorey(XbimModel model, IfcBuildingStorey _buildingStory, IfcBuilding _building)
        {
            using (XbimReadWriteTransaction txn = model.BeginTransaction("Create Building Story"))
            {
                var buildingStory = model.Instances.New<IfcBuildingStorey>();
                buildingStory.GlobalId = _buildingStory.GlobalId;
                buildingStory.Name = _buildingStory.Name;
                buildingStory.OwnerHistory.OwningUser = model.DefaultOwningUser;
                buildingStory.OwnerHistory.OwningApplication = model.DefaultOwningApplication;
                buildingStory.CompositionType = _buildingStory.CompositionType;
                buildingStory.ObjectPlacement = model.Instances.New<IfcLocalPlacement>();

                var localPlacement = buildingStory.ObjectPlacement as IfcLocalPlacement;
                var _localPlacement = _buildingStory.ObjectPlacement as IfcLocalPlacement;

                if (localPlacement != null && localPlacement.RelativePlacement == null)
                {

                    localPlacement.RelativePlacement = model.Instances.New<IfcAxis2Placement3D>();
                    //IfcAxis2Placement axis = _localPlacement.RelativePlacement;
                    var placement = localPlacement.RelativePlacement as IfcAxis2Placement3D;
                    var _placement = _localPlacement.RelativePlacement as IfcAxis2Placement3D;
                    //placement.Axis = _placement.Axis;
                    //placement.Location = _placement.Location;
                    //placement.RefDirection = _placement.RefDirection;
                    placement.SetNewLocation(_placement.Location.X, _placement.Location.Y, _placement.Location.Z);
                }

                var ifcRel = model.Instances.New<IfcRelAggregates>();
                ifcRel.RelatingObject = _building;//.RelatingMaterial = material;
                ifcRel.RelatedObjects.Add(buildingStory);
                //_building.AddElement(buildingStory);

                if (model.Validate(txn.Modified(), Console.Out) == 0)
                {
                    txn.Commit();
                    return buildingStory;
                }

            }
            return null;
        }
예제 #21
0
        /// <summary>
        /// This creates a wall and it's geometry, many geometric representations are possible and extruded rectangular footprint is chosen as this is commonly used for standard case walls
        /// </summary>
        /// <param name="model"></param>
        /// <param name="length">Length of the rectangular footprint</param>
        /// <param name="width">Width of the rectangular footprint (width of the wall)</param>
        /// <param name="height">Height to extrude the wall, extrusion is vertical</param>
        /// <returns></returns>
        private IfcWallStandardCase CreateWall(XbimModel model, double length, double width, double height)
        {
            //
            //begin a transaction
            using (XbimReadWriteTransaction txn = model.BeginTransaction("Create Wall"))
            {
                var wall = model.Instances.New<IfcWallStandardCase>();
                wall.Name = "A Standard rectangular wall";

                // required parameters for IfcWall
                wall.OwnerHistory.OwningUser = model.DefaultOwningUser;
                wall.OwnerHistory.OwningApplication = model.DefaultOwningApplication;

                //represent wall as a rectangular profile
                var rectProf = model.Instances.New<IfcRectangleProfileDef>();
                rectProf.ProfileType = IfcProfileTypeEnum.AREA;
                rectProf.XDim = width;
                rectProf.YDim = length;

                var insertPoint = model.Instances.New<IfcCartesianPoint>();
                insertPoint.SetXY(0, 400); //insert at arbitrary position
                rectProf.Position = model.Instances.New<IfcAxis2Placement2D>();
                rectProf.Position.Location = insertPoint;

                //model as a swept area solid
                var body = model.Instances.New<IfcExtrudedAreaSolid>();
                body.Depth = height;
                body.SweptArea = rectProf;
                body.ExtrudedDirection = model.Instances.New<IfcDirection>();
                body.ExtrudedDirection.SetXYZ(0, 0, 1);

                //parameters to insert the geometry in the model
                var origin = model.Instances.New<IfcCartesianPoint>();
                origin.SetXYZ(0, 0, 0);
                body.Position = model.Instances.New<IfcAxis2Placement3D>();
                body.Position.Location = origin;

                //Create a Definition shape to hold the geometry
                var shape = model.Instances.New<IfcShapeRepresentation>();
                shape.ContextOfItems = model.IfcProject.ModelContext();
                shape.RepresentationType = "SweptSolid";
                shape.RepresentationIdentifier = "Body";
                shape.Items.Add(body);

                //Create a Product Definition and add the model geometry to the wall
                var rep = model.Instances.New<IfcProductDefinitionShape>();
                rep.Representations.Add(shape);
                wall.Representation = rep;

                //now place the wall into the model
                var lp = model.Instances.New<IfcLocalPlacement>();
                var ax3D = model.Instances.New<IfcAxis2Placement3D>();
                ax3D.Location = origin;
                ax3D.RefDirection = model.Instances.New<IfcDirection>();
                ax3D.RefDirection.SetXYZ(0, 1, 0);
                ax3D.Axis = model.Instances.New<IfcDirection>();
                ax3D.Axis.SetXYZ(0, 0, 1);
                lp.RelativePlacement = ax3D;
                wall.ObjectPlacement = lp;

                // Where Clause: The IfcWallStandard relies on the provision of an IfcMaterialLayerSetUsage
                var ifcMaterialLayerSetUsage = model.Instances.New<IfcMaterialLayerSetUsage>();
                var ifcMaterialLayerSet = model.Instances.New<IfcMaterialLayerSet>();
                var ifcMaterialLayer = model.Instances.New<IfcMaterialLayer>();
                ifcMaterialLayer.LayerThickness = 10;
                ifcMaterialLayerSet.MaterialLayers.Add(ifcMaterialLayer);
                ifcMaterialLayerSetUsage.ForLayerSet = ifcMaterialLayerSet;
                ifcMaterialLayerSetUsage.LayerSetDirection = IfcLayerSetDirectionEnum.AXIS2;
                ifcMaterialLayerSetUsage.DirectionSense = IfcDirectionSenseEnum.NEGATIVE;
                ifcMaterialLayerSetUsage.OffsetFromReferenceLine = 150;

                // Add material to wall
                var material = model.Instances.New<IfcMaterial>();
                material.Name = "some material";
                var ifcRelAssociatesMaterial = model.Instances.New<IfcRelAssociatesMaterial>();
                ifcRelAssociatesMaterial.RelatingMaterial = material;
                ifcRelAssociatesMaterial.RelatedObjects.Add(wall);

                ifcRelAssociatesMaterial.RelatingMaterial = ifcMaterialLayerSetUsage;

                // IfcPresentationLayerAssignment is required for CAD presentation in IfcWall or IfcWallStandardCase
                var ifcPresentationLayerAssignment = model.Instances.New<IfcPresentationLayerAssignment>();
                ifcPresentationLayerAssignment.Name = "some ifcPresentationLayerAssignment";
                ifcPresentationLayerAssignment.AssignedItems.Add(shape);

                // linear segment as IfcPolyline with two points is required for IfcWall
                var ifcPolyline = model.Instances.New<IfcPolyline>();
                var startPoint = model.Instances.New<IfcCartesianPoint>();
                startPoint.SetXY(0, 0);
                var endPoint = model.Instances.New<IfcCartesianPoint>();
                endPoint.SetXY(4000, 0);
                ifcPolyline.Points.Add(startPoint);
                ifcPolyline.Points.Add(endPoint);

                var shape2D = model.Instances.New<IfcShapeRepresentation>();
                shape2D.ContextOfItems = model.IfcProject.ModelContext();
                shape2D.RepresentationIdentifier = "Axis";
                shape2D.RepresentationType = "Curve2D";
                shape2D.Items.Add(ifcPolyline);
                rep.Representations.Add(shape2D);

                //validate write any errors to the console and commit if ok, otherwise abort

                //if (model.Validate(txn.Modified(), Console.Out) == 0)
                //{
                    txn.Commit();
                    return wall;
                //}
            }
            return null;
        }
예제 #22
0
        /// <summary>
        /// This creates a wall and it's geometry, many geometric representations are possible and extruded rectangular footprint is chosen as this is commonly used for standard case walls
        /// </summary>
        /// <param name="model"></param>
        /// <param name="length">Length of the rectangular footprint</param>
        /// <param name="width">Width of the rectangular footprint (width of the wall)</param>
        /// <param name="height">Height to extrude the wall, extrusion is vertical</param>
        /// <returns></returns>
        private IfcWallStandardCase CreateWall(XbimModel model, double length, double width, double height)
        {
            //
            //begin a transaction
            using (XbimReadWriteTransaction txn = model.BeginTransaction("Create Wall"))
            {
                IfcWallStandardCase wall = model.Instances.New <IfcWallStandardCase>();
                wall.Name = "A Standard rectangular wall";

                // required parameters for IfcWall
                wall.OwnerHistory.OwningUser        = model.DefaultOwningUser;
                wall.OwnerHistory.OwningApplication = model.DefaultOwningApplication;

                //represent wall as a rectangular profile
                IfcRectangleProfileDef rectProf = model.Instances.New <IfcRectangleProfileDef>();
                rectProf.ProfileType = IfcProfileTypeEnum.AREA;
                rectProf.XDim        = width;
                rectProf.YDim        = length;

                IfcCartesianPoint insertPoint = model.Instances.New <IfcCartesianPoint>();
                insertPoint.SetXY(0, 400); //insert at arbitrary position
                rectProf.Position          = model.Instances.New <IfcAxis2Placement2D>();
                rectProf.Position.Location = insertPoint;

                //model as a swept area solid
                IfcExtrudedAreaSolid body = model.Instances.New <IfcExtrudedAreaSolid>();
                body.Depth             = height;
                body.SweptArea         = rectProf;
                body.ExtrudedDirection = model.Instances.New <IfcDirection>();
                body.ExtrudedDirection.SetXYZ(0, 0, 1);

                //parameters to insert the geometry in the model
                IfcCartesianPoint origin = model.Instances.New <IfcCartesianPoint>();
                origin.SetXYZ(0, 0, 0);
                body.Position          = model.Instances.New <IfcAxis2Placement3D>();
                body.Position.Location = origin;

                //Create a Definition shape to hold the geometry
                IfcShapeRepresentation shape = model.Instances.New <IfcShapeRepresentation>();
                shape.ContextOfItems           = model.IfcProject.ModelContext();
                shape.RepresentationType       = "SweptSolid";
                shape.RepresentationIdentifier = "Body";
                shape.Items.Add_Reversible(body);

                //Create a Product Definition and add the model geometry to the wall
                IfcProductDefinitionShape rep = model.Instances.New <IfcProductDefinitionShape>();
                rep.Representations.Add_Reversible(shape);
                wall.Representation = rep;

                //now place the wall into the model
                IfcLocalPlacement   lp   = model.Instances.New <IfcLocalPlacement>();
                IfcAxis2Placement3D ax3d = model.Instances.New <IfcAxis2Placement3D>();
                ax3d.Location     = origin;
                ax3d.RefDirection = model.Instances.New <IfcDirection>();
                ax3d.RefDirection.SetXYZ(0, 1, 0);
                ax3d.Axis = model.Instances.New <IfcDirection>();
                ax3d.Axis.SetXYZ(0, 0, 1);
                lp.RelativePlacement = ax3d;
                wall.ObjectPlacement = lp;


                // Where Clause: The IfcWallStandard relies on the provision of an IfcMaterialLayerSetUsage
                IfcMaterialLayerSetUsage ifcMaterialLayerSetUsage = model.Instances.New <IfcMaterialLayerSetUsage>();
                IfcMaterialLayerSet      ifcMaterialLayerSet      = model.Instances.New <IfcMaterialLayerSet>();
                IfcMaterialLayer         ifcMaterialLayer         = model.Instances.New <IfcMaterialLayer>();
                ifcMaterialLayer.LayerThickness = 10;
                ifcMaterialLayerSet.MaterialLayers.Add_Reversible(ifcMaterialLayer);
                ifcMaterialLayerSetUsage.ForLayerSet             = ifcMaterialLayerSet;
                ifcMaterialLayerSetUsage.LayerSetDirection       = IfcLayerSetDirectionEnum.AXIS2;
                ifcMaterialLayerSetUsage.DirectionSense          = IfcDirectionSenseEnum.NEGATIVE;
                ifcMaterialLayerSetUsage.OffsetFromReferenceLine = 150;

                // Add material to wall
                IfcMaterial material = model.Instances.New <IfcMaterial>();
                material.Name = "some material";
                IfcRelAssociatesMaterial ifcRelAssociatesMaterial = model.Instances.New <IfcRelAssociatesMaterial>();
                ifcRelAssociatesMaterial.RelatingMaterial = material;
                ifcRelAssociatesMaterial.RelatedObjects.Add_Reversible(wall);

                ifcRelAssociatesMaterial.RelatingMaterial = ifcMaterialLayerSetUsage;

                // IfcPresentationLayerAssignment is required for CAD presentation in IfcWall or IfcWallStandardCase
                IfcPresentationLayerAssignment ifcPresentationLayerAssignment = model.Instances.New <IfcPresentationLayerAssignment>();
                ifcPresentationLayerAssignment.Name = "some ifcPresentationLayerAssignment";
                ifcPresentationLayerAssignment.AssignedItems.Add(shape);


                // linear segment as IfcPolyline with two points is required for IfcWall
                IfcPolyline       ifcPolyline = model.Instances.New <IfcPolyline>();
                IfcCartesianPoint startPoint  = model.Instances.New <IfcCartesianPoint>();
                startPoint.SetXY(0, 0);
                IfcCartesianPoint endPoint = model.Instances.New <IfcCartesianPoint>();
                endPoint.SetXY(4000, 0);
                ifcPolyline.Points.Add_Reversible(startPoint);
                ifcPolyline.Points.Add_Reversible(endPoint);

                IfcShapeRepresentation shape2d = model.Instances.New <IfcShapeRepresentation>();
                shape2d.ContextOfItems           = model.IfcProject.ModelContext();
                shape2d.RepresentationIdentifier = "Axis";
                shape2d.RepresentationType       = "Curve2D";
                shape2d.Items.Add_Reversible(ifcPolyline);
                rep.Representations.Add_Reversible(shape2d);


                //validate write any errors to the console and commit if ok, otherwise abort

                if (model.Validate(txn.Modified(), Console.Out) == 0)
                {
                    txn.Commit();
                    return(wall);
                }
            }
            return(null);
        }
예제 #23
0
        public void AddRecordsCountRollbackTest()
        {
            using (XbimModel model = new XbimModel())
            {
                Assert.IsTrue(model.Open(SourceFile, XbimDBAccess.ReadWrite));
                int inserts = 100;
                long initTotalCount = model.Instances.Count;
                long initPointCount = model.Instances.CountOf<IfcCartesianPoint>();
                using (var txn = model.BeginTransaction())
                {
                    for (int i = 0; i < inserts; i++)
                    {
                        model.Instances.New<IfcCartesianPoint>(p => p.SetXYZ(1, 2, 3));
                    }
                    long newTotalCount = model.Instances.Count;
                    long newPointCount = model.Instances.CountOf<IfcCartesianPoint>();
                    Assert.AreEqual(inserts + initTotalCount, newTotalCount);
                    Assert.AreEqual(inserts + initPointCount, newPointCount);

                }
                long finalCount = model.Instances.Count;
                long finalPointCount = model.Instances.CountOf<IfcCartesianPoint>();
                model.Close();
                Assert.AreEqual(finalCount, initTotalCount); //check everything undid
                Assert.AreEqual(initPointCount, finalPointCount);
            }
        }
예제 #24
0
        private void FederationFromDialogbox(OpenFileDialog dlg)
        {
            if (!dlg.FileNames.Any())
                return;
            //use the first filename it's extension to decide which action should happen
            var s = Path.GetExtension(dlg.FileNames[0]);
            if (s == null)
                return;
            var firstExtension = s.ToLower();

            XbimModel fedModel = null;
            switch (firstExtension)
            {
                case ".xbimf":
                    if (dlg.FileNames.Length > 1)
                    {
                        var res = MessageBox.Show("Multiple files selected, open " + dlg.FileNames[0] + "?",
                            "Cannot open multiple Xbim files",
                            MessageBoxButton.OKCancel, MessageBoxImage.Warning);
                        if (res == MessageBoxResult.Cancel)
                            return;
                    }
                    fedModel = new XbimModel();
                    fedModel.Open(dlg.FileNames[0], XbimDBAccess.ReadWrite);
                    break;
                case ".ifc":
                case ".ifczip":
                case ".ifcxml":
                    //create temp file as a placeholder for the temperory xbim file
                    var filePath = Path.GetTempFileName();
                    filePath = Path.ChangeExtension(filePath, "xbimf");
                    fedModel = XbimModel.CreateModel(filePath);
                    fedModel.Initialise("Default Author", "Default Organization");
                    using (var txn = fedModel.BeginTransaction())
                    {
                        fedModel.IfcProject.Name = "Default Project Name";
                        txn.Commit();
                    }

                    var informUser = true;
                    for (var i = 0; i < dlg.FileNames.Length; i++)
                    {
                        var fileName = dlg.FileNames[i];
                        var builder = new XbimReferencedModelViewModel
                        {
                            Name = fileName,
                            OrganisationName = "OrganisationName " + i,
                            OrganisationRole = "Undefined"
                        };

                        var buildRes = false;
                        Exception exception = null;
                        try
                        {
                            buildRes = builder.TryBuild(fedModel);
                        }
                        catch (Exception ex)
                        {
                            //usually an EsentDatabaseSharingViolationException, user needs to close db first
                            exception = ex;
                        }

                        if (buildRes || !informUser)
                            continue;
                        var msg = exception == null ? "" : "\r\nMessage: " + exception.Message;
                        var res = MessageBox.Show(fileName + " couldn't be opened." + msg + "\r\nShow this message again?",
                            "Failed to open a file", MessageBoxButton.YesNoCancel, MessageBoxImage.Error);
                        if (res == MessageBoxResult.No)
                            informUser = false;
                        else if (res == MessageBoxResult.Cancel)
                        {
                            fedModel = null;
                            break;
                        }
                    }
                    break;
            }
            if (fedModel == null)
                return;
            CloseAndDeleteTemporaryFiles();
            ModelProvider.ObjectInstance = fedModel;
            ModelProvider.Refresh();
        }
예제 #25
0
        private void btnPerform_Click(object sender, RoutedEventArgs e)
        {
            if (Model == null)
            {
                MessageBox.Show("There is no model available.", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            string code = TxtCode.Text;

            if (String.IsNullOrEmpty(code) || String.IsNullOrWhiteSpace(code))
            {
                MessageBox.Show("You have to insert some C# code.", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }


            //create compiler
            Dictionary <string, string> providerOptions = new Dictionary <string, string> {
                { "CompilerVersion", "v4.0" }
            };
            CSharpCodeProvider provider       = new CSharpCodeProvider(providerOptions);
            CompilerParameters compilerParams = new CompilerParameters
            {
                GenerateInMemory   = true,
                GenerateExecutable = false
            };

            compilerParams.ReferencedAssemblies.Add("Microsoft.CSharp.dll");
            compilerParams.ReferencedAssemblies.Add("System.dll");
            compilerParams.ReferencedAssemblies.Add("System.Core.dll");
            compilerParams.ReferencedAssemblies.Add("System.Data.dll");
            compilerParams.ReferencedAssemblies.Add("System.Data.DataSetExtensions.dll");
            compilerParams.ReferencedAssemblies.Add("System.Xml.dll");
            compilerParams.ReferencedAssemblies.Add("System.Xml.Linq.dll");
            compilerParams.ReferencedAssemblies.Add("Xbim.Common.dll");
            compilerParams.ReferencedAssemblies.Add("Xbim.Ifc2x3.dll");
            compilerParams.ReferencedAssemblies.Add("Xbim.IO.dll");
            compilerParams.ReferencedAssemblies.Add("Xbim.Ifc.Extensions.dll");

            //get the code together
            string source = _codeSkeleton1 + code + _codeSkeleton2;
            //compile the source
            CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);

            //check the result
            if (results.Errors.Count != 0)
            {
                StringBuilder errors = new StringBuilder("Compiler Errors :\r\n");
                foreach (CompilerError error in results.Errors)
                {
                    errors.AppendFormat("Line {0},{1}\t: {2}\n", error.Line, error.Column, error.ErrorText);
                }
                MessageBox.Show("Compilation of your code has failed. \n" + errors, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            //create instance of the objekct from the compiled assembly
            object o = results.CompiledAssembly.CreateInstance("DynamicQuery.Query");

            if (o == null)
            {
                throw new Exception("Compiled code does not contain class DynamicQuery.Query");
            }
            MethodInfo miSelect   = o.GetType().GetMethod("Select", new[] { typeof(IModel) });
            MethodInfo miShowOnly = o.GetType().GetMethod("ShowOnly", new[] { typeof(IModel) });
            MethodInfo miExecute  = o.GetType().GetMethod("Execute", new[] { typeof(IModel) });
            MethodInfo miOutput   = o.GetType().GetMethod("GetOutput");


            //check for existance of the methods
            if (miOutput == null)
            {
                //this function should be there because it is my infrastructure
                throw new Exception("Code doesn't contain predefined method with the signature: public string GetOutput();");
            }
            try
            {
                if (miSelect != null)
                {
                    IEnumerable <IfcProduct> prods = miSelect.Invoke(o, new object[] { Model }) as IEnumerable <IfcProduct> ?? new List <IfcProduct>();

                    //raise the event about the selection change
                    OnRaiseProductSelectionChangedEvent(prods);
                }
                if (miShowOnly != null)
                {
                    IEnumerable <IfcProduct> prods = miShowOnly.Invoke(o, new object[] { Model }) as IEnumerable <IfcProduct> ?? new List <IfcProduct>();

                    //raise the event about the selection change
                    OnRaiseProductVisibilityChangedEvent(prods);
                }
                if (miExecute != null)
                {
                    XbimModel m = Model as XbimModel;
                    if (m != null)
                    {
                        using (var txn = m.BeginTransaction())
                        {
                            miExecute.Invoke(o, new object[] { Model });
                            txn.Commit();
                        }
                    }
                    else
                    {
                        miExecute.Invoke(o, new object[] { Model });
                    }
                }
            }
            catch (Exception ex)
            {
                var innerException = ex.InnerException;
                if (innerException != null)
                {
                    MessageBox.Show("There was a runtime exception during the code execution: \n" + innerException.Message + "\n" + innerException.StackTrace, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    throw ex;
                }
            }



            //get messages from the compiled code
            string msg = miOutput.Invoke(o, null) as string;

            TxtOutput.Text += msg;
            TxtOutput.ScrollToEnd();
        }
예제 #26
0
        public void BooleanIntersectonShellTest()
        {
            using (var m = new XbimModel())
            {

                m.CreateFrom("SolidTestFiles\\7- Boolean_IfcHalfspace_With_IfcExtrudedAreaSolid.ifc", null, null, true, true);
                var fbsm1 = m.Instances[57] as IfcConnectedFaceSet;
                Assert.IsNotNull(fbsm1, "IfcConnectedFaceSet is invalid");
                using (var txn = m.BeginTransaction())
                {

                    var ifcCylinder = IfcModelBuilder.MakeRightCircularCylinder(m, 500, 1500);
                    ifcCylinder.Position.Location.SetXYZ(-23000, 12000, 2000);
                    var cylinder = _xbimGeometryCreator.CreateSolid(ifcCylinder);
                    var shell1 = _xbimGeometryCreator.CreateShell(fbsm1);
                    var shell2 = ((IXbimShellSet)shell1.Cut(cylinder, m.ModelFactors.PrecisionBoolean)).First;
                    var shellSet = (IXbimShellSet)shell1.Intersection(shell2, m.ModelFactors.PrecisionBoolean);
                    Assert.IsTrue(shellSet.Count == 1,
                        string.Format("Cutting this shell should return a single shell, it returned {0}", shellSet.Count));
                    var resultShell = shellSet.First;
                    Assert.IsTrue(Math.Abs(shell2.SurfaceArea - resultShell.SurfaceArea) < m.ModelFactors.Precision,
                        "The surface area of the result should be the same as the second shell");

                }

            }
        }
예제 #27
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);
                    }
                }
            }
        }
예제 #28
0
        /// <summary>
        /// Creat the federated file
        /// </summary>
        /// <param name="file">FileInfo for the xbimf file</param>
        /// <param name="author">Author name</param>
        /// <param name="organisation">Orgsnisation Name</param>
        /// <param name="prjName">Project Name</param>
        public void Create(FileInfo file, string author, string organisation, string prjName = null)
        {
            FileNameXbimf = file;
            //_fedModel = XbimModel.CreateTemporaryModel();
            _fedModel = XbimModel.CreateModel(file.FullName, XbimDBAccess.ReadWrite);

            _fedModel.Initialise(author, organisation, "xBIM", "xBIM Team", ""); //"" is version, but none to grab as yet

            using (var txn = _fedModel.BeginTransaction())
            {
                _fedModel.IfcProject.Name = (prjName != null) ? prjName : string.Empty;
                _fedModel.Header = new IfcFileHeader(IfcFileHeader.HeaderCreationMode.InitWithXbimDefaults);
                txn.Commit();
            }
        }
예제 #29
0
        /// <summary>
        /// Add some properties to the wall,
        /// </summary>
        /// <param name="model">XbimModel</param>
        /// <param name="wall"></param>
        private void AddPropertiesToWall(XbimModel model, IfcWallStandardCase wall)
        {
            using (XbimReadWriteTransaction txn = model.BeginTransaction("Create Wall"))
            {
                IfcOwnerHistory ifcOwnerHistory = model.IfcProject.OwnerHistory; //we just use the project owner history for the properties, saves creating one
                CreateElementQuantity(model, wall, ifcOwnerHistory);
                CreateSimpleProperty(model, wall, ifcOwnerHistory);

                //if (model.Validate(txn.Modified(), Console.Out) == 0)
                //{
                txn.Commit();
                //}
            }
        }
예제 #30
0
        private void AddProductInBuilding(XbimModel model, IfcBuilding _building, IfcProduct _prod)
        {
            using (XbimReadWriteTransaction txn = model.BeginTransaction("Add Product"))
            {
                //if (_prod is IfcSpatialStructureElement)
                try
                {
                    _building.AddElement(_prod);
                    txn.Commit();
                }
                catch
                {
                    //MessageBox.Show(_prod.GetType().Name);
                }

            }
        }
예제 #31
0
 private void ChangeRelProducts(XbimModel model, IfcBuildingStorey bs, IfcProduct _product)
 {
     //var products = model.Instances.OfType<IfcBuildingElement>();
     using (XbimReadWriteTransaction txn = model.BeginTransaction("ChangeRelProducts"))
     {
         var ifcRel = model.Instances.New<IfcRelContainedInSpatialStructure>();
         ifcRel.RelatingStructure = bs;
         ifcRel.RelatedElements.Add(_product);
         if (model.Validate(txn.Modified(), Console.Out) == 0)
         {
             txn.Commit();
         }
     }
 }
예제 #32
0
        public void TestDocExtraction()
        {
            var ifcFile  = "Clinic-Handover-v12.ifc";
            var xbimFile = Path.ChangeExtension(ifcFile, "xbim");

            using (var _model = new XbimModel())
            {
                _model.CreateFrom(ifcFile, xbimFile, null, true);
                var ifcRelAssociatesDocuments = _model.Instances.OfType <IfcRelAssociatesDocument>();

                var dups = ifcRelAssociatesDocuments.GroupBy(d => d.RelatingDocument).SelectMany(grp => grp.Skip(1));
                Dictionary <IfcDocumentSelect, List <IfcRoot> > docToObjs = null;
                if (dups.Any())
                {
                    var dupsMerge = dups.GroupBy(d => d.RelatingDocument).Select(p => new { x = p.Key, y = p.SelectMany(c => c.RelatedObjects) });
                    //remove the duplicates and convert to dictionary
                    docToObjs = ifcRelAssociatesDocuments.Except(dups).ToDictionary(p => p.RelatingDocument, p => p.RelatedObjects.ToList());

                    //add the duplicate doc referenced object lists to the original doc
                    foreach (var item in dupsMerge)
                    {
                        docToObjs[item.x] = docToObjs[item.x].Union(item.y).ToList();
                    }
                }
                else
                {
                    //no duplicates, so just convert to dictionary
                    docToObjs = ifcRelAssociatesDocuments.ToDictionary(p => p.RelatingDocument, p => p.RelatedObjects.ToList());
                }

                //Lets set up some children documents
                using (var txn = _model.BeginTransaction("Add Documents"))
                {
                    foreach (var item in docToObjs)
                    {
                        var doc1 = item.Key as IfcDocumentInformation;
                        if (doc1 != null)
                        {
                            var docRelChild1 = _model.Instances.New <IfcDocumentInformationRelationship>();
                            docRelChild1.RelatingDocument = doc1;
                            //add child docs
                            var childDocA = CreateDocInfo(_model, "ChildDoc1a", @"c:\TestDir\Dir1");
                            var childDocB = CreateDocInfo(_model, "ChildDoc1b", @"c:\TestDir\Dir1");
                            var childDocC = CreateDocInfo(_model, "ChildDoc1c", @"c:\TestDir\Dir1");
                            docRelChild1.RelatedDocuments.Add(childDocA);
                            docRelChild1.RelatedDocuments.Add(childDocB);
                            docRelChild1.RelatedDocuments.Add(childDocC);

                            //add another layer
                            var docRelChild2 = _model.Instances.New <IfcDocumentInformationRelationship>();
                            docRelChild2.RelatingDocument = childDocA;
                            var childDoc2D = CreateDocInfo(_model, "ChildDoc2d", @"c:\TestDir\Dir1\Dir2");
                            var childDoc2E = CreateDocInfo(_model, "ChildDoc2e", @"c:\TestDir\Dir1\Dir2");
                            docRelChild2.RelatedDocuments.Add(childDoc2D);
                            docRelChild2.RelatedDocuments.Add(childDoc2E);

                            //add another layer
                            var docRelChild3 = _model.Instances.New <IfcDocumentInformationRelationship>();
                            docRelChild3.RelatingDocument = childDoc2D;
                            var childDoc3F = CreateDocInfo(_model, "ChildDoc3f", @"c:\TestDir\Dir1\Dir2\Dir3");
                            docRelChild3.RelatedDocuments.Add(childDoc3F);
                        }
                    }

                    var orphanDocA = CreateDocInfo(_model, "orphanDocA", @"c:");


                    var orphanDocB = _model.Instances.New <IfcDocumentReference>();
                    orphanDocB.Name     = "orphanDocB";
                    orphanDocB.Location = @"x:";
                    txn.Commit();

                    _model.SaveAs("Clinic-Handover_ChildDocs.ifc", Xbim.XbimExtensions.Interfaces.XbimStorageType.IFC);
                }


                //Get all documents information objects held in model
                var docAllInfos = _model.Instances.OfType <IfcDocumentInformation>();
                //Get the child document relationships
                var childDocRels = _model.Instances.OfType <IfcDocumentInformationRelationship>();



                //get the already attached to entity documents
                var docInfosAttached = docToObjs.Select(Dictionary => Dictionary.Key).OfType <IfcDocumentInformation>();

                //see if we have any documents not attached to IfcRoot objects, but could be attached as children documents to a parent document
                var docInfosNotAttached = docAllInfos.Except(docInfosAttached);

                List <IfcDocumentInformation> docChildren = docInfosAttached.ToList(); //first check on docs attached to IfcRoot Objects
                int idx = 0;
                do
                {
                    //get the relationships that are attached to the docs already associated with an IfcRoot object on first pass, then associated with all children, drilling down until nothing found
                    docChildren         = childDocRels.Where(docRel => docChildren.Contains(docRel.RelatingDocument)).SelectMany(docRel => docRel.RelatedDocuments).ToList(); //docs that are children to attached entity docs, drilling down
                    docInfosNotAttached = docInfosNotAttached.Except(docChildren);                                                                                            //attached by association to the root parent document, so remove from none attached document list
                } while (docChildren.Any() && (++idx < 100));                                                                                                                 //assume that docs are not embedded deeper than 100

                Assert.IsTrue(docInfosNotAttached.Count() == 1);


                //get all the doc reference objects held in the model
                var docAllRefs = _model.Instances.OfType <IfcDocumentReference>();
                //get all attached document references
                var docRefsAttached = docToObjs.Select(Dictionary => Dictionary.Key).OfType <IfcDocumentReference>();
                //checked on direct attached to object document references
                var docRefsNotAttached = docAllRefs.Except(docRefsAttached).ToList();

                //Check for document references held in the IfcDocumentInformation objects
                var docRefsAttachedDocInfo = docAllInfos.Where(docInfo => docInfo.DocumentReferences != null).SelectMany(docInfo => docInfo.DocumentReferences);
                //remove from Not Attached list
                docRefsNotAttached = docRefsNotAttached.Except(docRefsAttachedDocInfo).ToList();

                Assert.IsTrue(docRefsNotAttached.Count() == 1);

                //reverse lookup to entity to list of documents
                var newDic = docToObjs
                             .SelectMany(pair => pair.Value
                                         .Select(val => new { Key = val, Value = pair.Key }))
                             .GroupBy(item => item.Key)
                             .ToLookup(gr => gr.Key, gr => gr.Select(item => item.Value));

                foreach (var group in newDic)
                {
                    foreach (var item in group)
                    {
                        Assert.IsTrue(item.Count() > 0);
                        //foreach (var doc in item)
                        //{
                        //    if (doc is IfcDocumentInformation)
                        //    {
                        //        Debug.WriteLine("Doc {0}", ((IfcDocumentInformation)doc).Name);
                        //    }
                        //    else
                        //    {
                        //        Debug.WriteLine("Doc {0}", ((IfcDocumentReference)doc).Name);
                        //    }

                        //}
                    }
                }
            }
        }
예제 #33
0
        public void CreateSystem(XbimModel model, string classificationName)
        {
            //set model in which the systems are to be created
            _model = model;
            string data = null;

            //try to get data from resources

            //get list of classifications available
            var    dir      = Directory.EnumerateFiles("Classifications");
            string clasPath = null;

            foreach (var f in dir)
            {
                if (Path.GetFileNameWithoutExtension(f).ToLower() == classificationName.ToLower())
                {
                    clasPath = f;
                    break;
                }
            }
            if (clasPath == null)
            {
                throw new ArgumentException("Specified classification doesn't exist");
            }
            var clasName = Path.GetFileNameWithoutExtension(clasPath);


            //get data
            data = File.ReadAllText(clasPath);


            CsvLineParser parser = null;

            if (clasName.Contains("NRM"))
            {
                parser = new CsvLineParser(';');
            }
            else
            {
                parser = new CsvLineParser();
            }


            //create classification source
            var action = new Action <XbimModel>(m => {
                var source = model.Instances.New <IfcClassification>(c =>
                {
                    c.Source  = clasName;
                    c.Edition = "Default edition";
                    c.Name    = clasName;
                });
                ParseCSV(data, parser, source);
            });


            //process file
            if (_model.IsTransacting)
            {
                action(_model);
            }
            else
            {
                using (var txn = model.BeginTransaction("Systems creation"))
                {
                    action(_model);
                    txn.Commit();
                }
            }
        }
예제 #34
0
        public void CheckModelReadWrite()
        {
            using (XbimModel model1 = new XbimModel())
            {
                Assert.IsTrue(model1.Open(SourceFile, XbimDBAccess.ReadWrite));
                using (var txn1 = model1.BeginTransaction())
                {
                    model1.Instances.New<IfcWall>(); //DO SOMETHING
                }
            }

            using (XbimModel model2 = new XbimModel())
            {
                Assert.IsTrue(model2.Open(SourceFile, XbimDBAccess.ReadWrite));
                using (var txn2 = model2.BeginTransaction())
                {
                    model2.Instances.New<IfcWall>(); //DO SOMETHING
                }
            }
            //dispose should close the models, allowing us to open it for reading and writing

            try
            {
                FileStream f = File.OpenWrite(SourceFile); //check if file is unlocked
                f.Close();
            }
            catch (Exception)
            {
                Assert.Fail();
            }
            using (XbimModel model = new XbimModel())
            {
                model.Open(SourceFile, XbimDBAccess.ReadWrite);
                try
                {
                    FileStream f = File.OpenWrite(SourceFile); //check if file is unlocked
                    f.Close();
                    Assert.Fail(); //it should not be able to be opened
                }
                catch (System.IO.IOException) //we should get this exception
                {

                }

            }
            Assert.IsTrue(XbimModel.ModelOpenCount == 0);
        }
예제 #35
0
        private void AddProductInBuildingStorey(XbimModel model, IfcBuildingStorey _buildingStorey, IfcProduct _prod)
        {
            if (model.IsTransacting)
                return;
            using (XbimReadWriteTransaction txn = model.BeginTransaction("AddProductToBuildingStorey"))
            {
                //if (_prod is IfcSpatialStructureElement)
                try
                {
                    _buildingStorey.AddElement(_prod);
                    if (model.Validate(txn.Modified(), Console.Out) == 0)
                    {
                        txn.Commit();
                    }
                }
                catch(Exception ex)
                {
                    AddMessages("Error in AddProductInBuildingStorey: " + ex.Message);
                    Debug.WriteLine("Error in AddProductInBuildingStorey: " + ex.Message);
                }

            }
        }
예제 #36
0
        private static IfcBeam CreatePurlin(XbimModel model, HndzPurlin genericProducthndz)
        {
            using (XbimReadWriteTransaction txn = model.BeginTransaction("Create Purlin"))
            {
                IfcBeam beam = model.Instances.New <IfcBeam>();
                IfcExtrudedAreaSolid body = model.Instances.New <IfcExtrudedAreaSolid>();
                body.Depth = genericProducthndz.ExtrusionLine.RhinoLine.Length;

                IfcBeamType elementType = model.Instances.New <IfcBeamType>();
                elementType.PredefinedType = IfcBeamTypeEnum.USERDEFINED;

                IfcMaterial material = model.Instances.New <IfcMaterial>();
                material.Name = "STEEL";
                beam.SetMaterial(material);
                IfcCartesianPoint insertPoint = model.Instances.New <IfcCartesianPoint>();

                insertPoint.SetXY(genericProducthndz.ExtrusionLine.baseNode.Point.X, genericProducthndz.ExtrusionLine.baseNode.Point.Y); //insert at arbitrary position//****************Need Revision

                if (genericProducthndz.Profile is HndzRectangularProfile)
                {
                    HndzRectangularProfile recProfile = genericProducthndz.Profile as HndzRectangularProfile;

                    #region Type & Material &Tags

                    string typeText = "HANDAZ-Column-Rectangular " + (int)recProfile.Rectangle.Width + " x "
                                      + (int)recProfile.Rectangle.Height + " mm";

                    elementType.Tag  = typeText;
                    elementType.Name = typeText;
                    IfcLabel columnLabel = new IfcLabel(typeText);
                    elementType.ElementType          = columnLabel;
                    elementType.ApplicableOccurrence = columnLabel;



                    beam.Tag         = typeText;
                    beam.Name        = typeText;
                    beam.Description = typeText;
                    beam.SetDefiningType(elementType, model);

                    #endregion

                    //represent column as a rectangular profile
                    IfcRectangleProfileDef MyPurlinPofile = model.Instances.New <IfcRectangleProfileDef>();
                    MyPurlinPofile.ProfileType           = IfcProfileTypeEnum.AREA;
                    MyPurlinPofile.XDim                  = recProfile.Rectangle.Height;
                    MyPurlinPofile.YDim                  = recProfile.Rectangle.Width;
                    MyPurlinPofile.Position              = model.Instances.New <IfcAxis2Placement2D>();
                    MyPurlinPofile.Position.RefDirection = model.Instances.New <IfcDirection>();
                    MyPurlinPofile.Position.RefDirection.SetXY(recProfile.OrientationInPlane.X, recProfile.OrientationInPlane.Y);
                    //MyColumnPofile.Position.Location = insertPoint;

                    //model as a swept area solid
                    body.SweptArea = MyPurlinPofile;
                }
                if (genericProducthndz.Profile is HndzISectionProfile)
                {
                    HndzISectionProfile Iprofile = genericProducthndz.Profile as HndzISectionProfile;

                    #region Type & Material &Tags

                    string typeText = "HANDAZ-Purlin-I beam (flange " + Iprofile.I_Section.b_f + " x " + Iprofile.I_Section.t_fTop + " and web "
                                      + Iprofile.I_Section.d + " x " + Iprofile.I_Section.t_w + " mm";


                    elementType.Tag  = typeText;
                    elementType.Name = typeText;
                    IfcLabel columnLabel = new IfcLabel(typeText);
                    elementType.ElementType          = columnLabel;
                    elementType.ApplicableOccurrence = columnLabel;



                    beam.Tag         = typeText;
                    beam.Name        = typeText;
                    beam.Description = typeText;
                    beam.SetDefiningType(elementType, model);

                    #endregion
                    // IfcPolyline pl = model.Instances.New<IfcPolyline>();

                    //List<Point3d> tempPoints= Iprofile.ConvertItoPoints();
                    // foreach (Point3d point in tempPoints)
                    // {
                    //     IfcCartesianPoint tempPoint = model.Instances.New<IfcCartesianPoint>();
                    //     tempPoint.SetXYZ(point.X, point.Y, point.Z);
                    //     pl.Points.Add(tempPoint);
                    // }

                    IfcIShapeProfileDef MyPurlinPofile = model.Instances.New <IfcIShapeProfileDef>();
                    MyPurlinPofile.FlangeThickness = Iprofile.I_Section.tf;
                    MyPurlinPofile.WebThickness    = Iprofile.I_Section.t_w;
                    MyPurlinPofile.OverallWidth    = Iprofile.I_Section.b_f;
                    MyPurlinPofile.OverallDepth    = Iprofile.I_Section.d;
                    MyPurlinPofile.FilletRadius    = 10;

                    MyPurlinPofile.Position = model.Instances.New <IfcAxis2Placement2D>();
                    MyPurlinPofile.Position.RefDirection = model.Instances.New <IfcDirection>();
                    MyPurlinPofile.Position.RefDirection.SetXY(Iprofile.OrientationInPlane.X, Iprofile.OrientationInPlane.Y);
                    //MyColumnPofile.Position.Location = insertPoint;

                    //model as a swept area solid
                    body.SweptArea = MyPurlinPofile;
                }
                if (genericProducthndz.Profile is HndzCSectionProfile)
                {
                    HndzCSectionProfile Cprofile = genericProducthndz.Profile as HndzCSectionProfile;

                    #region Type & Material &Tags

                    string typeText = "HANDAZ-Purlin-C-Chanel (flange " + Cprofile.C_Section.b_f + " x " + Cprofile.C_Section.t_f + " and web "
                                      + Cprofile.C_Section.d + " x " + Cprofile.C_Section.t_w + " mm";


                    elementType.Tag  = typeText;
                    elementType.Name = typeText;
                    IfcLabel columnLabel = new IfcLabel(typeText);
                    elementType.ElementType          = columnLabel;
                    elementType.ApplicableOccurrence = columnLabel;


                    beam.Tag         = typeText;
                    beam.Name        = typeText;
                    beam.Description = typeText;
                    beam.SetDefiningType(elementType, model);

                    #endregion

                    IfcCShapeProfileDef MyPurlinPofile = model.Instances.New <IfcCShapeProfileDef>();
                    MyPurlinPofile.WallThickness = Cprofile.C_Section.t_f;
                    //MyColumnPofile.WebThickness = Iprofile.C_Section.t_w; //ToDo:purlin web and flange thickness are the same!!!!
                    MyPurlinPofile.Width = Cprofile.C_Section.b_f;
                    MyPurlinPofile.Depth = Cprofile.C_Section.d;
                    MyPurlinPofile.InternalFilletRadius = 10;

                    MyPurlinPofile.Position = model.Instances.New <IfcAxis2Placement2D>();
                    MyPurlinPofile.Position.RefDirection = model.Instances.New <IfcDirection>();
                    MyPurlinPofile.Position.RefDirection.SetXY(Cprofile.OrientationInPlane.X, Cprofile.OrientationInPlane.Y);


                    //model as a swept area solid
                    body.SweptArea = MyPurlinPofile;
                }
                body.ExtrudedDirection = model.Instances.New <IfcDirection>();
                body.ExtrudedDirection.SetXYZ(0, 0, 1);
                //body.ExtrudedDirection.SetXYZ(Hndzcol.ExtrusionLine.RhinoLine.Direction.X, Hndzcol.ExtrusionLine.RhinoLine.Direction.Y, Hndzcol.ExtrusionLine.RhinoLine.Direction.Z);


                //parameters to insert the geometry in the model
                IfcCartesianPoint origin = model.Instances.New <IfcCartesianPoint>();
                origin.SetXYZ(genericProducthndz.ExtrusionLine.baseNode.Point.X, genericProducthndz.ExtrusionLine.baseNode.Point.Y, genericProducthndz.ExtrusionLine.baseNode.Point.Z);

                body.Position = model.Instances.New <IfcAxis2Placement3D>();
                //body.Position.Location = origin;

                body.Position.RefDirection = model.Instances.New <IfcDirection>();
                body.Position.RefDirection.SetXYZ(1, 0, 0);

                //Create a Definition shape to hold the geometry
                IfcShapeRepresentation shape = model.Instances.New <IfcShapeRepresentation>();
                shape.ContextOfItems           = model.IfcProject.ModelContext();
                shape.RepresentationType       = "SweptSolid";
                shape.RepresentationIdentifier = "Body";
                shape.Items.Add(body);

                //Create a Product Definition and add the model geometry to the column
                IfcProductDefinitionShape rep = model.Instances.New <IfcProductDefinitionShape>();
                rep.Representations.Add(shape);

                beam.Representation = rep;

                //now place the column into the model
                IfcLocalPlacement   lp   = model.Instances.New <IfcLocalPlacement>();
                IfcAxis2Placement3D ax3d = model.Instances.New <IfcAxis2Placement3D>();
                ax3d.Location = origin;

                Vector3d perpendicularVector = new Vector3d(genericProducthndz.Profile.OrientationInPlane.X, genericProducthndz.Profile.OrientationInPlane.Y, 0);

                Plane extrusionPlane;
                bool  aa = genericProducthndz.ExtrusionLine.RhinoLine.TryGetPlane(out extrusionPlane);
                if (aa)
                {
                    perpendicularVector = extrusionPlane.ZAxis;
                }



                ax3d.RefDirection = model.Instances.New <IfcDirection>();
                ax3d.RefDirection.SetXYZ(perpendicularVector.X, perpendicularVector.Y, perpendicularVector.Z);
                ax3d.Axis = model.Instances.New <IfcDirection>();
                ax3d.Axis.SetXYZ(genericProducthndz.ExtrusionLine.RhinoLine.Direction.X, genericProducthndz.ExtrusionLine.RhinoLine.Direction.Y, genericProducthndz.ExtrusionLine.RhinoLine.Direction.Z);

                lp.RelativePlacement = ax3d;
                beam.ObjectPlacement = lp;

                #region Owner Data
                beam.OwnerHistory.OwningUser        = model.DefaultOwningUser;
                beam.OwnerHistory.OwningApplication = model.DefaultOwningApplication;
                #endregion

                //validate write any errors to the console and commit if OK, otherwise abort
                string temp = Path.GetTempPath();
                //if (model.Validate(txn.Modified(), File.CreateText("E:\\Column" + column.GlobalId + "Errors.txt")) == 0)
                // if (model.Validate(txn.Modified(), File.CreateText(temp + "Column" + column.GlobalId + "Errors.txt")) == 0)
                if (model.Validate(txn.Modified(), Console.Out) == 0)
                {
                    txn.Commit();
                    return(beam);
                }

                return(null);
            }
        }
예제 #37
0
        public void TestDocExtraction()
        {
            var ifcFile = "Clinic-Handover-v12.ifc";
            var xbimFile = Path.ChangeExtension(ifcFile, "xbim");
            using (var _model = new XbimModel())
            {
                _model.CreateFrom(ifcFile, xbimFile, null, true);
                var ifcRelAssociatesDocuments = _model.Instances.OfType<IfcRelAssociatesDocument>();

                var dups = ifcRelAssociatesDocuments.GroupBy(d => d.RelatingDocument).SelectMany(grp => grp.Skip(1));
                Dictionary<IfcDocumentSelect, List<IfcRoot>> docToObjs = null;
                if (dups.Any())
                {
                    var dupsMerge = dups.GroupBy(d => d.RelatingDocument).Select(p => new { x = p.Key, y = p.SelectMany(c => c.RelatedObjects) });
                    //remove the duplicates and convert to dictionary
                    docToObjs = ifcRelAssociatesDocuments.Except(dups).ToDictionary(p => p.RelatingDocument, p => p.RelatedObjects.ToList());

                    //add the duplicate doc referenced object lists to the original doc
                    foreach (var item in dupsMerge)
                    {
                        docToObjs[item.x] = docToObjs[item.x].Union(item.y).ToList();
                    }
                }
                else
                {
                    //no duplicates, so just convert to dictionary
                    docToObjs = ifcRelAssociatesDocuments.ToDictionary(p => p.RelatingDocument, p => p.RelatedObjects.ToList());
                }

                //Lets set up some children documents
                using (var txn = _model.BeginTransaction("Add Documents"))
                {
                    foreach (var item in docToObjs)
                    {
                        var doc1 = item.Key as IfcDocumentInformation;
                        if (doc1 != null)
                        {
                            var docRelChild1 = _model.Instances.New<IfcDocumentInformationRelationship>();
                            docRelChild1.RelatingDocument = doc1;
                            //add child docs
                            var childDocA = CreateDocInfo(_model, "ChildDoc1a", @"c:\TestDir\Dir1");
                            var childDocB = CreateDocInfo(_model, "ChildDoc1b", @"c:\TestDir\Dir1");
                            var childDocC = CreateDocInfo(_model, "ChildDoc1c", @"c:\TestDir\Dir1");
                            docRelChild1.RelatedDocuments.Add(childDocA);
                            docRelChild1.RelatedDocuments.Add(childDocB);
                            docRelChild1.RelatedDocuments.Add(childDocC);

                            //add another layer
                            var docRelChild2 = _model.Instances.New<IfcDocumentInformationRelationship>();
                            docRelChild2.RelatingDocument = childDocA;
                            var childDoc2D = CreateDocInfo(_model, "ChildDoc2d", @"c:\TestDir\Dir1\Dir2");
                            var childDoc2E = CreateDocInfo(_model, "ChildDoc2e", @"c:\TestDir\Dir1\Dir2");
                            docRelChild2.RelatedDocuments.Add(childDoc2D);
                            docRelChild2.RelatedDocuments.Add(childDoc2E);

                            //add another layer
                            var docRelChild3 = _model.Instances.New<IfcDocumentInformationRelationship>();
                            docRelChild3.RelatingDocument = childDoc2D;
                            var childDoc3F = CreateDocInfo(_model, "ChildDoc3f", @"c:\TestDir\Dir1\Dir2\Dir3");
                            docRelChild3.RelatedDocuments.Add(childDoc3F);

                        }
                    }

                    var orphanDocA = CreateDocInfo(_model, "orphanDocA", @"c:");
                    

                    var orphanDocB = _model.Instances.New<IfcDocumentReference>();
                    orphanDocB.Name = "orphanDocB";
                    orphanDocB.Location = @"x:";
                    txn.Commit();

                    _model.SaveAs("Clinic-Handover_ChildDocs.ifc", Xbim.XbimExtensions.Interfaces.XbimStorageType.IFC);
                }


                //Get all documents information objects held in model
                var docAllInfos = _model.Instances.OfType<IfcDocumentInformation>();
                //Get the child document relationships
                var childDocRels = _model.Instances.OfType<IfcDocumentInformationRelationship>();



                //get the already attached to entity documents 
                var docInfosAttached = docToObjs.Select(Dictionary => Dictionary.Key).OfType<IfcDocumentInformation>();
                
                //see if we have any documents not attached to IfcRoot objects, but could be attached as children documents to a parent document
                var docInfosNotAttached = docAllInfos.Except(docInfosAttached);

                List<IfcDocumentInformation> docChildren = docInfosAttached.ToList(); //first check on docs attached to IfcRoot Objects
                int idx = 0;
                do
                {
                    //get the relationships that are attached to the docs already associated with an IfcRoot object on first pass, then associated with all children, drilling down until nothing found
                    docChildren = childDocRels.Where(docRel => docChildren.Contains(docRel.RelatingDocument)).SelectMany(docRel => docRel.RelatedDocuments).ToList(); //docs that are children to attached entity docs, drilling down
                    docInfosNotAttached = docInfosNotAttached.Except(docChildren); //attached by association to the root parent document, so remove from none attached document list


                } while (docChildren.Any() && (++idx < 100)); //assume that docs are not embedded deeper than 100

                Assert.IsTrue(docInfosNotAttached.Count() == 1);


                //get all the doc reference objects held in the model
                var docAllRefs = _model.Instances.OfType<IfcDocumentReference>();
                //get all attached document references
                var docRefsAttached = docToObjs.Select(Dictionary => Dictionary.Key).OfType<IfcDocumentReference>();
                //checked on direct attached to object document references
                var docRefsNotAttached = docAllRefs.Except(docRefsAttached).ToList();
                
                //Check for document references held in the IfcDocumentInformation objects
                var docRefsAttachedDocInfo = docAllInfos.Where(docInfo => docInfo.DocumentReferences != null).SelectMany(docInfo => docInfo.DocumentReferences);
                //remove from Not Attached list
                docRefsNotAttached = docRefsNotAttached.Except(docRefsAttachedDocInfo).ToList();

                Assert.IsTrue(docRefsNotAttached.Count() == 1);

                //reverse lookup to entity to list of documents
                var newDic = docToObjs
                                .SelectMany(pair => pair.Value
                                .Select(val => new { Key = val, Value = pair.Key }))
                                .GroupBy(item => item.Key)
                                .ToLookup(gr => gr.Key, gr => gr.Select(item => item.Value));

                foreach (var group in newDic)
                {
                    foreach (var item in group)
                    {
                        Assert.IsTrue(item.Count() > 0);
                        //foreach (var doc in item)
                        //{
                        //    if (doc is IfcDocumentInformation)
                        //    {
                        //        Debug.WriteLine("Doc {0}", ((IfcDocumentInformation)doc).Name);
                        //    }
                        //    else
                        //    {
                        //        Debug.WriteLine("Doc {0}", ((IfcDocumentReference)doc).Name);
                        //    }
                            
                        //} 
                    }
                }
                    
            }
        }