Exemple #1
0
        /// <summary>
        /// 获取一个ifcproduct的boundingbox
        /// </summary>
        /// <param name="product">指定的product</param>
        /// <returns>XbimRect3D精度为2位的盒子</returns>
        public XbimRect3D GetAABB(IIfcProduct product)
        {
            //Xbim3DModelContext context = new Xbim3DModelContext(model);
            //context.CreateContext();
            XbimRect3D prodBox = XbimRect3D.Empty;

            if (context.ShapeInstancesOf(product).Count() == 0)
            {
                return(prodBox);
            }

            foreach (var shp in context.ShapeInstancesOf(product))
            {
                var bb = shp.BoundingBox;
                bb = XbimRect3D.TransformBy(bb, shp.Transformation);
                if (prodBox.IsEmpty)
                {
                    prodBox = bb;
                }
                else
                {
                    prodBox.Union(bb);
                }
            }

            //精度为2位小数
            prodBox.Round(2);
            return(prodBox);
            //Console.WriteLine(prodBox.ToString());
        }
Exemple #2
0
        public static void AddElements(this MeshGeometry3D m, IPersistIfcEntity item, XbimMatrix3D wcsTransform)
        {
            var fromModel = item.ModelOf as XbimModel;

            if (fromModel == null || !(item is IfcProduct))
            {
                return;
            }
            switch (fromModel.GeometrySupportLevel)
            {
            case 2:
                var context = new Xbim3DModelContext(fromModel);

                var productShape = context.ShapeInstancesOf((IfcProduct)item)
                                   .Where(s => s.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded)
                                   .ToList();
                if (!productShape.Any() && item is IfcFeatureElement)
                {
                    productShape = context.ShapeInstancesOf((IfcProduct)item)
                                   .Where(
                        s => s.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded)
                                   .ToList();
                }

                if (!productShape.Any())
                {
                    return;
                }
                foreach (var shapeInstance in productShape)
                {
                    IXbimShapeGeometryData shapeGeom =
                        context.ShapeGeometry(shapeInstance.ShapeGeometryLabel);
                    switch ((XbimGeometryType)shapeGeom.Format)
                    {
                    case XbimGeometryType.PolyhedronBinary:
                        m.Read(shapeGeom.ShapeData,
                               XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform));
                        break;

                    case XbimGeometryType.Polyhedron:
                        m.Read(((XbimShapeGeometry)shapeGeom).ShapeData,
                               XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform));
                        break;
                    }
                }
                break;

            case 1:
                var xm3d        = new XbimMeshGeometry3D();
                var geomDataSet = fromModel.GetGeometryData(item.EntityLabel, XbimGeometryType.TriangulatedMesh);
                foreach (var geomData in geomDataSet)
                {
                    var gd = geomData.TransformBy(wcsTransform);
                    xm3d.Add(gd);
                }
                m.Add(xm3d);
                break;
            }
        }
        public static void AddElements(this MeshGeometry3D m, IPersistIfcEntity item, XbimMatrix3D wcsTransform)
        {

            var fromModel = item.ModelOf as XbimModel;
            if (fromModel == null || !(item is IfcProduct)) 
                return;
            switch (fromModel.GeometrySupportLevel)
            {
                case 2:
                    var context = new Xbim3DModelContext(fromModel);

                    var productShape = context.ShapeInstancesOf((IfcProduct) item)
                        .Where(s => s.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded)
                        .ToList();
                    if (!productShape.Any() && item is IfcFeatureElement)
                    {
                        productShape = context.ShapeInstancesOf((IfcProduct) item)
                            .Where(
                                s => s.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded)
                            .ToList();
                    }

                    if (!productShape.Any()) 
                        return;
                    foreach (var shapeInstance in productShape)
                    {
                        IXbimShapeGeometryData shapeGeom =
                            context.ShapeGeometry(shapeInstance.ShapeGeometryLabel);
                        switch ((XbimGeometryType) shapeGeom.Format)
                        {
                            case XbimGeometryType.PolyhedronBinary:
                                m.Read(shapeGeom.ShapeData,
                                    XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform));
                                break;
                            case XbimGeometryType.Polyhedron:
                                m.Read(((XbimShapeGeometry) shapeGeom).ShapeData,
                                    XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform));
                                break;
                        }
                    }
                    break;
                case 1:
                    var xm3d = new XbimMeshGeometry3D();
                    var geomDataSet = fromModel.GetGeometryData(item.EntityLabel, XbimGeometryType.TriangulatedMesh);
                    foreach (var geomData in geomDataSet)
                    {
                        var gd = geomData.TransformBy(wcsTransform);
                        xm3d.Add(gd);
                    }
                    m.Add(xm3d);
                    break;
            }
        }
Exemple #4
0
        private static XbimShapeTriangulation GetMeshes(Xbim3DModelContext context, IIfcProduct product)
        {
            XbimShapeTriangulation ifcMesh = null;;
            var productShape =
                context.ShapeInstancesOf(product)
                .Where(p => p.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded)
                .Distinct();

            if (productShape.Any())
            {
                var shapeInstance = productShape.FirstOrDefault();
                var shapeGeometry = context.ShapeGeometry(shapeInstance.ShapeGeometryLabel);

                byte[] data = ((IXbimShapeGeometryData)shapeGeometry).ShapeData;

                //If you want to get all the faces and triangulation use this
                using (var stream = new MemoryStream(data))
                {
                    using (var reader = new BinaryReader(stream))
                    {
                        ifcMesh = reader.ReadShapeTriangulation();
                    }
                }
            }

            return(ifcMesh);
        }
Exemple #5
0
        /// <summary>
        /// Constructor of spatial relations analyser of axis aligned bounding boxes of the products.
        /// If you already have a dictionary of the AABBoxes and products you should use the other constructor
        /// </summary>
        /// <param name="model">Building model</param>
        public XbimAABBoxAnalyser(XbimModel model)
        {
            _model = model;
            Xbim3DModelContext context = new Xbim3DModelContext(model);

            if (model.GeometriesCount == 0)
            {
                context.CreateContext();
            }


            //create cached BBoxes
            foreach (var prod in model.IfcProducts.Cast <IfcProduct>())
            {
                XbimRect3D prodBox = XbimRect3D.Empty;
                foreach (var shp in context.ShapeInstancesOf(prod))
                {
                    //bounding boxes are lightweight and are produced when geometry is created at first place

                    //get or cast to BBox
                    var bb = shp.BoundingBox;
                    bb = XbimRect3D.TransformBy(bb, shp.Transformation);
                    if (prodBox.IsEmpty)
                    {
                        prodBox = bb;
                    }
                    else
                    {
                        prodBox.Union(bb);
                    }
                    //add every BBox to the world to get the size and position of the world
                }
                _prodBBs.Add(prod, prodBox);
            }
        }
Exemple #6
0
        //private void WriteInstances(JsonWriter writer)
        //{
        //    //write a flag node for all pickable instances
        //    writer.WriteStartObject();
        //    writer.WritePropertyName("type"); //instance node
        //    writer.WriteValue("matrix");
        //    writer.WritePropertyName("id");
        //    writer.WriteValue("instances");
        //    writer.WritePropertyName("elements");
        //   // WriteMatrix(writer, GetGlobalModelTransform());
        //    WriteMatrix(writer, XbimMatrix3D.Identity);
        //    writer.WritePropertyName("nodes");
        //    writer.WriteStartArray();

        //    WriteGeometry(writer);

        //    writer.WriteEndArray();
        //    writer.WriteEndObject();
        //}
        private void WriteInstances(JsonWriter writer)
        {
            XbimMatrix3D globalTrans = GetGlobalModelTransform();

            //write out the material nodes and then the instances for each material
            //  Dictionary<int, XbimTexture> styles = _context.SurfaceStyles().ToDictionary(s => s.DefinedObjectId);

            //write all pickable instances
            writer.WriteStartObject();
            foreach (var shapeGeom in _context.ShapeGeometries())
            {
                writer.WriteRaw(shapeGeom.ShapeData); //the vertex geometry
                writer.WritePropertyName("Shapes");   //instance nodes
                writer.WriteStartArray();
                foreach (var shapeInstance in _context.ShapeInstancesOf(shapeGeom))
                {
                    writer.WriteStartObject();
                    writer.WritePropertyName("id"); writer.WriteValue(shapeInstance.InstanceLabel);
                    writer.WritePropertyName("pid"); writer.WriteValue(shapeInstance.IfcProductLabel);
                    writer.WritePropertyName("tr"); WriteMatrix(writer, shapeInstance.Transformation);
                    writer.WritePropertyName("sid"); writer.WriteValue(shapeInstance.StyleLabel);
                    writer.WriteEndObject();
                }
                writer.WriteEndArray();
            }
            writer.WriteEndObject();
        }
        public static XbimMeshGeometry3D GetMesh(this XbimModel xbimModel, IEnumerable<IPersistIfcEntity> items, XbimMatrix3D wcsTransform)
        {
            var m = new XbimMeshGeometry3D();

            if (xbimModel.GeometrySupportLevel == 1)
            {
                // this is what happens for version 1 of the engine
                //
                foreach (var item in items)
                {
                    var fromModel = item.ModelOf as XbimModel;
                    if (fromModel == null)
                        continue;
                    var geomDataSet = fromModel.GetGeometryData(item.EntityLabel, XbimGeometryType.TriangulatedMesh);
                    foreach (var geomData in geomDataSet)
                    {
                        // todo: add guidance to the TransformBy method so that users can understand how to stop using it (it's marked absolete)
                        geomData.TransformBy(wcsTransform);
                        m.Add(geomData); // todo: what is the modelid value to be passed?
                    }
                }
            }
            else
            {
                // this is what happens for version 2 of the engine
                //
                foreach (var item in items)
                {
                    var fromModel = item.ModelOf as XbimModel;
                    if (fromModel == null || !(item is IfcProduct))
                        continue;
                    var context = new Xbim3DModelContext(fromModel);

                    var productShape =
                        context.ShapeInstancesOf((IfcProduct) item)
                            .Where(
                                s => s.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded)
                            .ToList();
                    foreach (var shapeInstance in productShape)
                    {
                        IXbimShapeGeometryData shapeGeom = context.ShapeGeometry(shapeInstance.ShapeGeometryLabel);
                        switch ((XbimGeometryType) shapeGeom.Format)
                        {
                            case XbimGeometryType.PolyhedronBinary:
                                m.Read(shapeGeom.ShapeData,
                                    XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform));
                                break;
                            case XbimGeometryType.Polyhedron:
                                m.Read(((XbimShapeGeometry) shapeGeom).ShapeData,
                                    XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform));
                                break;
                        }
                    }
                }
            }
            return m;
        }
        public void GetGeometryFromXbimModel_IFC4(MeshGeometry3D m, IPersistEntity item, XbimMatrix3D wcsTransform)
        {
            if (item.Model == null || !(item is Xbim.Ifc4.Kernel.IfcProduct))
            {
                return;
            }

            var context = new Xbim3DModelContext(item.Model);

            var productShape = context.ShapeInstancesOf((Xbim.Ifc4.Interfaces.IIfcProduct)item)
                               .Where(s => s.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded)
                               .ToList();

            if (!productShape.Any() && item is Xbim.Ifc4.Interfaces.IIfcFeatureElement)
            {
                productShape = context.ShapeInstancesOf((Xbim.Ifc4.Interfaces.IIfcProduct)item)
                               .Where(
                    s => s.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded)
                               .ToList();
            }

            if (!productShape.Any())
            {
                return;
            }
            foreach (var shapeInstance in productShape)
            {
                IXbimShapeGeometryData shapeGeom =
                    context.ShapeGeometry(shapeInstance.ShapeGeometryLabel);
                switch ((XbimGeometryType)shapeGeom.Format)
                {
                case XbimGeometryType.PolyhedronBinary:
                    m.Read(shapeGeom.ShapeData,
                           XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform));
                    break;

                case XbimGeometryType.Polyhedron:
                    m.Read(((XbimShapeGeometry)shapeGeom).ShapeData,
                           XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform));
                    break;
                }
            }
        }
Exemple #9
0
        private void GetGeometryData(XbimModel model, IfcProduct product)
        {
            var context = new Xbim3DModelContext(model);
            //TODO: WCS
            var metre = model.ModelFactors.OneMetre;

            var units = model.IfcProject.UnitsInContext.Units
                        .Where <IfcSIUnit>(u => u.UnitType == IfcUnitEnum.LENGTHUNIT)
                        .ToList();

            string defaultLengthUnit = "";

            if (units.Count > 0)
            {
                defaultLengthUnit = units.First().GetSymbol();
            }


            var styles = context.SurfaceStyles().ToList();

            var productShape =
                context.ShapeInstancesOf(product)
                .Where(p => p.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded)
                .Distinct();


            if (productShape.Any())
            {
                foreach (var shapeInstance in productShape)
                {
                    var shapeGeometry = context.ShapeGeometry(shapeInstance.ShapeGeometryLabel);

                    XbimColour style = XbimColour.Default;
                    if (shapeInstance.HasStyle)
                    {
                        style = styles.First(s => s.DefinedObjectId == shapeInstance.StyleLabel).ColourMap.FirstOrDefault();
                    }

                    Console.WriteLine("--Style: {0}", style);
                    Console.WriteLine("-- x:{0:0.0000} \n-- y:{1:0.0000} \n-- z:{2:0.0000} \n",
                                      shapeGeometry.BoundingBox.Location.X,
                                      shapeGeometry.BoundingBox.Location.Y,
                                      shapeGeometry.BoundingBox.Location.Z);

                    Console.WriteLine("-- sx:{0:0.0000} {3} \n-- sy:{1:0.0000} {3} \n-- sz:{2:0.0000} {3} \n",
                                      shapeGeometry.BoundingBox.SizeX,
                                      shapeGeometry.BoundingBox.SizeY,
                                      shapeGeometry.BoundingBox.SizeZ,
                                      defaultLengthUnit);
                }
            }
        }
Exemple #10
0
        public static DiffuseMaterial GetStyleFromXbimModel(IIfcProduct item, Xbim3DModelContext context, double opacity = 1)
        {
            // var context = new Xbim3DModelContext(item.Model);
            // context.CreateContext();

            var productShape = context.ShapeInstancesOf(item)
                               .Where(s => s.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded)
                               .ToList();
            Material wpfMaterial = GetWpfMaterial(item.Model, productShape.Count > 0 ? productShape[0].StyleLabel : 0);

            Material newmaterial = wpfMaterial.Clone();

            ((DiffuseMaterial)newmaterial).Brush.Opacity = opacity;
            return(newmaterial as DiffuseMaterial);
        }
        private void LoadObjectBuffer(IfcStore model)
        {
            _bboxBuffer  = new Dictionary <int, XbimRect3D>();
            _labelBuffer = new Dictionary <int, string>();
            _boundingBox = XbimRect3D.Empty;

            var context = new Xbim3DModelContext(model);

            context.CreateContext();
            List <IfcProduct> prods = model.Instances.OfType <IfcProduct>().ToList();

            foreach (var prod in prods)
            {
                List <XbimShapeInstance> prodShapes = context.ShapeInstancesOf(prod).Where(p => p.RepresentationType
                                                                                           != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded).Distinct().ToList();

                if (prodShapes == null || prodShapes.Count == 0)
                {
                    continue;
                }
                XbimRect3D bbox = XbimRect3D.Empty;
                foreach (var shape in prodShapes)
                {
                    if (bbox.IsEmpty)
                    {
                        bbox = shape.BoundingBox;
                    }
                    else
                    {
                        bbox.Union(shape.BoundingBox);
                    }
                }

                _bboxBuffer.Add(prod.EntityLabel, bbox);
                _labelBuffer.Add(prod.EntityLabel, prod.GetType().Name);

                if (_boundingBox.IsEmpty)
                {
                    _boundingBox = bbox;
                }
                else
                {
                    _boundingBox.Union(bbox);
                }
            }

            log.InfoFormat("{0} Objects loaded from the file.", _bboxBuffer.Count);
        }
Exemple #12
0
        public static MeshGeometry3D WriteTriangles(IIfcProduct ifcElement, Xbim3DModelContext context, XbimMatrix3D wcsTransformation)
        {
            MeshBuilder meshBuilder = new MeshBuilder(false, false);

            // var allTriangles = new List<Triangles>();
            // foreach (XbimShapeInstance instance in context.ShapeInstancesOf(ifcElement).Where(x => x.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded))
            foreach (XbimShapeInstance instance in context.ShapeInstancesOf(ifcElement).Where(x => x.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded))
            {
                XbimShapeGeometry geometry = context.ShapeGeometry(instance);
                var data = ((IXbimShapeGeometryData)geometry).ShapeData;
                using (var stream = new MemoryStream(data))
                {
                    using (var reader = new BinaryReader(stream))
                    {
                        XbimShapeTriangulation mesh = reader.ReadShapeTriangulation();
                        mesh = mesh.Transform(instance.Transformation);
                        // WCS transforms
                        mesh = mesh.Transform(wcsTransformation);

                        foreach (XbimFaceTriangulation face in mesh.Faces)
                        {
                            var j = 0;
                            for (var i = 0; i < face.TriangleCount; i++)
                            {
                                int k      = i + j;
                                var point1 = new Point3D {
                                    X = mesh.Vertices[face.Indices[k]].X, Y = mesh.Vertices[face.Indices[k]].Y, Z = mesh.Vertices[face.Indices[k]].Z
                                };
                                j++;
                                k = i + j;
                                var point2 = new Point3D {
                                    X = mesh.Vertices[face.Indices[k]].X, Y = mesh.Vertices[face.Indices[k]].Y, Z = mesh.Vertices[face.Indices[k]].Z
                                };
                                j++;
                                k = i + j;
                                var point3 = new Point3D {
                                    X = mesh.Vertices[face.Indices[k]].X, Y = mesh.Vertices[face.Indices[k]].Y, Z = mesh.Vertices[face.Indices[k]].Z
                                };

                                meshBuilder.AddTriangle(point1, point2, point3);
                            }
                        }
                    }
                }
            }
            return(meshBuilder.ToMesh());
            // return allTriangles;
        }
        /// <summary>
        /// Get Style of each Item
        ///
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public Material GetStyleFromXbimModel_IFC2x3(Xbim.Ifc2x3.Kernel.IfcProduct item, double opacity = 1)
        {
            var context = new Xbim3DModelContext(item.Model);

            var productShape = context.ShapeInstancesOf((Xbim.Ifc4.Interfaces.IIfcProduct)item)
                               .Where(s => s.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded)
                               .ToList();
            Material wpfMaterial = null;

            if (productShape.Count > 0)
            {
                wpfMaterial = GetWpfMaterial(item.Model, productShape[0].StyleLabel);
            }
            else
            {
                wpfMaterial = GetWpfMaterial(item.Model, 0);
            }

            ((System.Windows.Media.Media3D.DiffuseMaterial)wpfMaterial).Brush.Opacity = opacity;
            return(wpfMaterial);
        }
        /// <summary>
        /// Fill sheet rows for Coordinate sheet
        /// </summary>
        public override COBieSheet <COBieCoordinateRow> Fill()
        {
            //get the conversion to the COBie units (metres or feet)
            double conversionFactor;
            var    cobieUnits = Context.WorkBookUnits.LengthUnit.ToLowerInvariant();

            if (cobieUnits == "meters" || cobieUnits == "metres")
            {
                conversionFactor = Model.ModelFactors.OneMetre;
            }
            else if (cobieUnits == "millimeters" || cobieUnits == "millimetres")
            {
                conversionFactor = Model.ModelFactors.OneMilliMetre;
            }
            else if (cobieUnits == "feet" || cobieUnits == "foot")
            {
                conversionFactor = Model.ModelFactors.OneFoot;
            }
            else if (cobieUnits == "inch" || cobieUnits == "inches")
            {
                conversionFactor = Model.ModelFactors.OneInch;
            }
            else
            {
                throw new Exception(
                          string.Format("The COBie units are incorrectly set, the provided value {0} is invalid.",
                                        cobieUnits));
            }

            XbimMatrix3D globalTransform = XbimMatrix3D.CreateScale(1 / conversionFactor);

            var coordinates = new COBieSheet <COBieCoordinateRow>(Constants.WORKSHEET_COORDINATE);

            ProgressIndicator.ReportMessage("Starting Coordinates...");


            //Create new sheet

            //Get buildings and spaces
            var ifcBuildingStoreys = Model.FederatedInstances.OfType <IfcBuildingStorey>();
            var ifcSpaces          = Model.FederatedInstances.OfType <IfcSpace>()
                                     .OrderBy(ifcSpace => ifcSpace.Name, new CompareIfcLabel());
            var ifcProducts = ifcBuildingStoreys.Union <IfcProduct>(ifcSpaces); //add spaces

            //get component products as shown in Component sheet
            var relAggregates = Model.FederatedInstances.OfType <IfcRelAggregates>();
            var relSpatial    = Model.FederatedInstances.OfType <IfcRelContainedInSpatialStructure>();
            var ifcElements   = ((from x in relAggregates
                                  from y in x.RelatedObjects
                                  where !Context.Exclude.ObjectType.Component.Contains(y.GetType())
                                  select y).Union(from x in relSpatial
                                                  from y in x.RelatedElements
                                                  where !Context.Exclude.ObjectType.Component.Contains(y.GetType())
                                                  select y)).OfType <IfcProduct>(); //.GroupBy(el => el.Name).Select(g => g.First())

            ifcProducts = ifcProducts.Union(ifcElements);

            var productList = ifcProducts as IList <IfcProduct> ?? ifcProducts.ToList();

            ProgressIndicator.Initialise("Creating Coordinates", productList.Count());

            var m3D = new Xbim3DModelContext(Model);

            foreach (var ifcProduct in productList)
            {
                ProgressIndicator.IncrementAndUpdate();
                //if no name to link the row name too skip it, as no way to link back to the parent object
                //if (string.IsNullOrEmpty(ifcProduct.Name))
                //    continue;

                var coordinate = new COBieCoordinateRow(coordinates)
                {
                    Name = (string.IsNullOrEmpty(ifcProduct.Name.ToString()))
                        ? DEFAULT_STRING
                        : ifcProduct.Name.ToString(),
                    CreatedBy = GetTelecomEmailAddress(ifcProduct.OwnerHistory),
                    CreatedOn = GetCreatedOnDateAsFmtString(ifcProduct.OwnerHistory)
                };

                // (ifcBuildingStorey == null || ifcBuildingStorey.Name.ToString() == "") ? "CoordinateName" : ifcBuildingStorey.Name.ToString();

                coordinate.RowName = coordinate.Name;

                XbimPoint3D?ifcCartesianPointLower = null;
                XbimPoint3D?ifcCartesianPointUpper = null;
                var         transBox = new TransformedBoundingBox();
                if (ifcProduct is IfcBuildingStorey)
                {
                    XbimMatrix3D worldMatrix = ifcProduct.ObjectPlacement.ToMatrix3D();
                    ifcCartesianPointLower = new XbimPoint3D(worldMatrix.OffsetX, worldMatrix.OffsetY,
                                                             worldMatrix.OffsetZ);
                    //get the offset from the world coordinates system 0,0,0 point, i.e. origin point of this object in world space
                    coordinate.SheetName   = "Floor";
                    coordinate.Category    = "point";
                    ifcCartesianPointUpper = null;
                }
                else
                {
                    if (ifcProduct is IfcSpace)
                    {
                        coordinate.SheetName = "Space";
                    }
                    else
                    {
                        coordinate.SheetName = "Component";
                    }

                    coordinate.Category = "box-lowerleft"; //and box-upperright, so two values required when we do this

                    var          boundBox  = XbimRect3D.Empty;
                    XbimMatrix3D transform = XbimMatrix3D.Identity;
                    foreach (var shapeInstance in m3D.ShapeInstancesOf(ifcProduct))
                    {
                        if (boundBox.IsEmpty)
                        {
                            boundBox = shapeInstance.BoundingBox;
                        }
                        else
                        {
                            boundBox.Union(shapeInstance.BoundingBox);
                        }
                        transform = shapeInstance.Transformation;
                    }
                    if (!boundBox.IsEmpty)
                    {
                        XbimMatrix3D m = globalTransform * transform;
                        transBox = new TransformedBoundingBox(boundBox, m);
                        //set points
                        ifcCartesianPointLower = transBox.MinPt;
                        ifcCartesianPointUpper = transBox.MaxPt;
                    }
                }

                if (ifcCartesianPointLower.HasValue)
                {
                    coordinate.CoordinateXAxis = string.Format("{0}", (double)ifcCartesianPointLower.Value.X);
                    coordinate.CoordinateYAxis = string.Format("{0}", (double)ifcCartesianPointLower.Value.Y);
                    coordinate.CoordinateZAxis = string.Format("{0}", (double)ifcCartesianPointLower.Value.Z);
                    coordinate.ExtSystem       = GetExternalSystem(ifcProduct);
                    coordinate.ExtObject       = ifcProduct.GetType().Name;
                    if (!string.IsNullOrEmpty(ifcProduct.GlobalId))
                    {
                        coordinate.ExtIdentifier = ifcProduct.GlobalId.ToString();
                    }

                    coordinate.ClockwiseRotation   = transBox.ClockwiseRotation.ToString("F4");
                    coordinate.ElevationalRotation = transBox.ElevationalRotation.ToString("F4");
                    coordinate.YawRotation         = transBox.YawRotation.ToString("F4");

                    coordinates.AddRow(coordinate);
                }

                if (ifcCartesianPointUpper.HasValue) //we need a second row for upper point
                {
                    var coordinateUpper = new COBieCoordinateRow(coordinates);
                    coordinateUpper.Name                = coordinate.Name;
                    coordinateUpper.CreatedBy           = coordinate.CreatedBy;
                    coordinateUpper.CreatedOn           = coordinate.CreatedOn;
                    coordinateUpper.RowName             = coordinate.RowName;
                    coordinateUpper.SheetName           = coordinate.SheetName;
                    coordinateUpper.Category            = "box-upperright";
                    coordinateUpper.CoordinateXAxis     = string.Format("{0}", (double)ifcCartesianPointUpper.Value.X);
                    coordinateUpper.CoordinateYAxis     = string.Format("{0}", (double)ifcCartesianPointUpper.Value.Y);
                    coordinateUpper.CoordinateZAxis     = string.Format("{0}", (double)ifcCartesianPointUpper.Value.Z);
                    coordinateUpper.ExtSystem           = coordinate.ExtSystem;
                    coordinateUpper.ExtObject           = coordinate.ExtObject;
                    coordinateUpper.ExtIdentifier       = coordinate.ExtIdentifier;
                    coordinateUpper.ClockwiseRotation   = coordinate.ClockwiseRotation;
                    coordinateUpper.ElevationalRotation = coordinate.ElevationalRotation;
                    coordinateUpper.YawRotation         = coordinate.YawRotation;

                    coordinates.AddRow(coordinateUpper);
                }
            }

            coordinates.OrderBy(s => s.Name);

            ProgressIndicator.Finalise();


            return(coordinates);
        }
Exemple #15
0
        public static List <Point3D> GetFootPrintNonBREP(IIfcProduct ifcElement, Xbim3DModelContext context)
        {
            var resultList = new List <Point3D>();

            foreach (XbimShapeInstance instance in context.ShapeInstancesOf(ifcElement))
            {
                // Get the IFC Representation of the Footprint of the instance
                XbimShapeGeometry geometry = context.ShapeGeometry(instance);

                var data = ((IXbimShapeGeometryData)geometry).ShapeData;
                using (var stream = new MemoryStream(data))
                {
                    using (var reader = new BinaryReader(stream))
                    {
                        XbimShapeTriangulation mesh = reader.ReadShapeTriangulation();
                        mesh = mesh.Transform(instance.Transformation);

                        // find the minimal z coordinate
                        double minZ = 10000;
                        foreach (var vertex in mesh.Vertices)
                        {
                            if (vertex.Z <= minZ)
                            {
                                minZ = vertex.Z;
                            }
                        }
                        List <IVertex> points = new List <IVertex>();

                        foreach (var vertex in mesh.Vertices)
                        {
                            if (vertex.Z != minZ)
                            {
                                continue;
                            }

                            points.Add(new DefaultVertex {
                                Position = new[] { vertex.X, vertex.Y }
                            });
                        }

                        if (points.Count <= 2)
                        {
                            return(null);
                        }

                        // Compute ConvexHull
                        var cH = ConvexHull.Create(points);

                        foreach (var item in cH.Points)
                        {
                            var point = new Point3D()
                            {
                                X = item.Position[0], Y = item.Position[1], Z = minZ
                            };
                            bool duplicate = false;
                            foreach (var result in resultList)
                            {
                                if (result == point)
                                {
                                    duplicate = true;
                                    break;
                                }
                            }
                            if (!duplicate)
                            {
                                resultList.Add(point);
                            }
                        }
                    }
                }
            }
            return(resultList);
        }
Exemple #16
0
        public static void UpdateElementTransform(IfcStore _model, string projectNumber, string projectName)
        {
            DBOperation.beginTransaction();
            DBOperation.commitInterval = 5000;
            string      currStep        = string.Empty;
            BIMRLCommon _refBIMRLCommon = new BIMRLCommon();

            int commandStatus   = -1;
            int currInsertCount = 0;

            OracleCommand command = new OracleCommand(" ", DBOperation.DBConn);
            XbimMatrix3D  m3D     = new XbimMatrix3D();

            if (string.IsNullOrEmpty(projectName))
            {
                projectName = projectNumber + " - Federated";
            }

            string modelName;

            if (!string.IsNullOrEmpty(_model.FileName))
            {
                modelName = Path.GetFileNameWithoutExtension(_model.FileName);
            }
            else
            {
                modelName = projectNumber + " - " + projectName;
            }

            command.CommandText = "SELECT FEDERATEDID FROM bimrl_federatedmodel WHERE MODELNAME = '" + modelName + "' AND PROJECTNUMBER='" + projectNumber + "' AND PROJECTNAME='" + projectName + "'";
            object oFedID = command.ExecuteScalar();

            if (oFedID == null)
            {
                return;
            }

            int fedID = int.Parse(oFedID.ToString());

            command.CommandText = "SELECT ELEMENTID, LINENO FROM " + DBOperation.formatTabName("bimrl_element", fedID) + " WHERE GEOMETRYBODY IS NOT NULL";
            OracleDataReader reader = command.ExecuteReader();
            SortedDictionary <int, string> elemList = new SortedDictionary <int, string>();

            while (reader.Read())
            {
                string elemid = reader.GetString(0);
                int    lineNo = reader.GetInt32(1);
                elemList.Add(lineNo, elemid);
            }
            reader.Close();

            Xbim3DModelContext context = new Xbim3DModelContext(_model);

            foreach (KeyValuePair <int, string> elemListItem in elemList)
            {
                //IEnumerable<XbimGeometryData> geomDataList = _model.GetGeometryData(elemListItem.Key, XbimGeometryType.TriangulatedMesh);
                IIfcProduct product = _model.Instances[elemListItem.Key] as IIfcProduct;

                IEnumerable <XbimShapeInstance> shapeInstances = context.ShapeInstancesOf(product).Where(x => x.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded);
                if (shapeInstances.Count() == 0)
                {
                    continue;    // SKip if the product has no geometry
                }
                XbimMeshGeometry3D     prodGeom  = new XbimMeshGeometry3D();
                IXbimShapeGeometryData shapeGeom = context.ShapeGeometry(shapeInstances.FirstOrDefault().ShapeGeometryLabel);
                //XbimModelExtensions.Read(prodGeom, shapeGeom.ShapeData, shapeInstances.FirstOrDefault().Transformation);

                //XbimGeometryData sdoGeomData = geomDataList.First();
                //m3D = sdoGeomData.Transform;
                //m3D = XbimMatrix3D.FromArray(sdoGeomData.DataArray2);       // Xbim 3.0 removes Tranform property
                m3D = shapeInstances.FirstOrDefault().Transformation;
                string sqlStmt = "update " + DBOperation.formatTabName("BIMRL_ELEMENT", fedID) + " set TRANSFORM_COL1=:1, TRANSFORM_COL2=:2, TRANSFORM_COL3=:3, TRANSFORM_COL4=:4"
                                 + " Where elementid = '" + elemListItem.Value + "'";
                // int status = DBOperation.updateGeometry(sqlStmt, sdoGeomData);
                currStep            = sqlStmt;
                command.CommandText = sqlStmt;

                try
                {
                    OracleParameter[] sdoGeom = new OracleParameter[4];
                    for (int i = 0; i < sdoGeom.Count(); ++i)
                    {
                        sdoGeom[i]             = command.Parameters.Add((i + 1).ToString(), OracleDbType.Object);
                        sdoGeom[i].Direction   = ParameterDirection.Input;
                        sdoGeom[i].UdtTypeName = "MDSYS.SDO_GEOMETRY";
                        sdoGeom[i].Size        = 1;
                    }

                    SdoGeometry trcol1 = new SdoGeometry();
                    trcol1.Dimensionality = 3;
                    trcol1.LRS            = 0;
                    trcol1.GeometryType   = (int)SdoGeometryTypes.GTYPE.POINT;
                    int      gType   = trcol1.PropertiesToGTYPE();
                    SdoPoint trcol1V = new SdoPoint();
                    trcol1V.XD       = m3D.M11;
                    trcol1V.YD       = m3D.M12;
                    trcol1V.ZD       = m3D.M13;
                    trcol1.SdoPoint  = trcol1V;
                    sdoGeom[1].Value = trcol1;

                    SdoGeometry trcol2 = new SdoGeometry();
                    trcol2.Dimensionality = 3;
                    trcol2.LRS            = 0;
                    trcol2.GeometryType   = (int)SdoGeometryTypes.GTYPE.POINT;
                    gType = trcol2.PropertiesToGTYPE();
                    SdoPoint trcol2V = new SdoPoint();
                    trcol2V.XD       = m3D.M21;
                    trcol2V.YD       = m3D.M22;
                    trcol2V.ZD       = m3D.M23;
                    trcol2.SdoPoint  = trcol2V;
                    sdoGeom[2].Value = trcol2;

                    SdoGeometry trcol3 = new SdoGeometry();
                    trcol3.Dimensionality = 3;
                    trcol3.LRS            = 0;
                    trcol3.GeometryType   = (int)SdoGeometryTypes.GTYPE.POINT;
                    gType = trcol3.PropertiesToGTYPE();
                    SdoPoint trcol3V = new SdoPoint();
                    trcol3V.XD       = m3D.M31;
                    trcol3V.YD       = m3D.M32;
                    trcol3V.ZD       = m3D.M33;
                    trcol3.SdoPoint  = trcol3V;
                    sdoGeom[3].Value = trcol3;

                    SdoGeometry trcol4 = new SdoGeometry();
                    trcol4.Dimensionality = 3;
                    trcol4.LRS            = 0;
                    trcol4.GeometryType   = (int)SdoGeometryTypes.GTYPE.POINT;
                    gType = trcol4.PropertiesToGTYPE();
                    SdoPoint trcol4V = new SdoPoint();
                    trcol4V.XD       = m3D.OffsetX;
                    trcol4V.YD       = m3D.OffsetY;
                    trcol4V.ZD       = m3D.OffsetZ;
                    trcol4.SdoPoint  = trcol4V;
                    sdoGeom[4].Value = trcol4;

                    commandStatus = command.ExecuteNonQuery();
                    command.Parameters.Clear();

                    currInsertCount++;

                    if (currInsertCount % DBOperation.commitInterval == 0)
                    {
                        //Do commit at interval but keep the long transaction (reopen)
                        DBOperation.commitTransaction();
                    }
                }
                catch (OracleException e)
                {
                    string excStr = "%%Error - " + e.Message + "\n\t" + currStep;
                    _refBIMRLCommon.StackPushError(excStr);
                    //command.Dispose();   // Log Oracle error and continue
                    command = new OracleCommand(" ", DBOperation.DBConn);
                    // throw;
                }
                catch (SystemException e)
                {
                    string excStr = "%%Insert Error - " + e.Message + "\n\t" + currStep;
                    _refBIMRLCommon.StackPushError(excStr);
                    throw;
                }

                DBOperation.commitTransaction();
                command.Dispose();
            }
        }
Exemple #17
0
        public static XbimMeshGeometry3D GetMesh(this XbimModel xbimModel, IEnumerable <IPersistIfcEntity> items, XbimMatrix3D wcsTransform)
        {
            var m = new XbimMeshGeometry3D();

            if (xbimModel.GeometrySupportLevel == 1)
            {
                // this is what happens for version 1 of the engine
                //
                foreach (var item in items)
                {
                    var fromModel = item.ModelOf as XbimModel;
                    if (fromModel == null)
                    {
                        continue;
                    }
                    var geomDataSet = fromModel.GetGeometryData(item.EntityLabel, XbimGeometryType.TriangulatedMesh);
                    foreach (var geomData in geomDataSet)
                    {
                        // todo: add guidance to the TransformBy method so that users can understand how to stop using it (it's marked absolete)
                        geomData.TransformBy(wcsTransform);
                        m.Add(geomData, xbimModel.UserDefinedId);
                    }
                }
            }
            else
            {
                // this is what happens for version 2 of the engine
                //
                foreach (var item in items)
                {
                    var fromModel = item.ModelOf as XbimModel;
                    if (fromModel == null || !(item is IfcProduct))
                    {
                        continue;
                    }
                    var context = new Xbim3DModelContext(fromModel);

                    var productShape =
                        context.ShapeInstancesOf((IfcProduct)item)
                        .Where(s => s.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded)
                        .ToList();     // this also returns shapes of voids
                    foreach (var shapeInstance in productShape)
                    {
                        IXbimShapeGeometryData shapeGeom = context.ShapeGeometry(shapeInstance.ShapeGeometryLabel);
                        switch ((XbimGeometryType)shapeGeom.Format)
                        {
                        case XbimGeometryType.PolyhedronBinary:
                            m.Read(shapeGeom.ShapeData,
                                   XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform));
                            break;

                        case XbimGeometryType.Polyhedron:
                            m.Read(((XbimShapeGeometry)shapeGeom).ShapeData,
                                   XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform));
                            break;
                        }
                    }
                }
            }
            return(m);
        }
        public override void Calculate()
        {
            if (InputPorts[0].Data == null)
            {
                return;
            }

            var modelInfo = InputPorts[0].Data as ModelInfo;

            if (modelInfo == null)
            {
                return;
            }

            var model = modelController.GetModel(modelInfo.modelId) as IfcModel;

            if (model == null)
            {
                return;
            }

            // Get the model content
            xModel  = model.GetModel();
            context = model.xModelContext;

            // CREATE THE OPERATIONAL SPACE FOR DOORS
            var doors      = xModel.Instances.OfType <IIfcDoor>();
            var elementIds = new List <IfcGloballyUniqueId>();

            foreach (var item in doors)
            {
                elementIds.Add(item.GlobalId);
            }

            // control.InitViewPort();
            control.Visualize(control.CreateModelUiElementsDs(model, elementIds, false));

            foreach (var item in doors)
            {
                MeshBuilder meshBuilder = new MeshBuilder(false, false);


                // if (((IIfcDoorStyle)item.IsTypedBy.First().RelatingType).OperationType == IfcDoorStyleOperationEnum.DOUBLE_DOOR_SINGLE_SWING)
                // {

                var placement = ((IfcLocalPlacement)item.ObjectPlacement).PlacementRelTo.ReferencedByPlacements.First();
                var mat       = placement.ToMatrix3D();

                // Set the origin
                var x = mat.OffsetX;
                var y = mat.OffsetY;
                var z = mat.OffsetZ;

                var locPoint     = new Point3D(x, y, z);
                var allignVector = new Vector3D();
                var normalVector = new Vector3D();
                var heightVector = new Vector3D(0, 0, (double)item.OverallHeight);

                foreach (XbimShapeInstance instance in context.ShapeInstancesOf(item).Where(i => i.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded))
                {
                    allignVector = new Vector3D((double)(instance.Transformation.Left.X * item.OverallWidth), (double)(instance.Transformation.Left.Y * item.OverallWidth), (double)(instance.Transformation.Left.Z * item.OverallWidth));
                    normalVector = Vector3D.CrossProduct(allignVector, new Vector3D(0, 0, 1));
                }
                // allignVector.Negate();
                // Base Area
                // var listpoints = new List<Point>
                // {
                //     new Point(locPoint.X, locPoint.Y),
                //     new Point(locPoint.X + normalVector.X, locPoint.Y + normalVector.Y),
                //     new Point(locPoint.X + normalVector.X - allignVector.X, locPoint.Y + normalVector.Y - allignVector.Y),
                //     new Point(locPoint.X - allignVector.X, locPoint.Y - allignVector.Y)
                // };

                // var rec = new Rect3D(locPoint.X, locPoint.Y, locPoint.Z, Math.Abs(heightVector.X + allignVector.X + normalVector.X), Math.Abs(heightVector.Y + allignVector.Y + normalVector.Y), Math.Abs(heightVector.Z + allignVector.Z + normalVector.Z));
                //
                // meshBuilder.AddBox(rec);

                // var profile = new[] { new Point(0, 0.4), new Point(0.06, 0.36), new Point(0.1, 0.1), new Point(0.34, 0.1), new Point(0.4, 0.14), new Point(0.5, 0.5), new Point(0.7, 0.56), new Point(1, 0.46) };
                // meshBuilder.AddRevolvedGeometry(listpoints, null, locPoint, heightVector, 10);

                // meshBuilder.AddBox(new Rect3D(locPoint.X, locPoint.Y, locPoint.Z, Math.Abs(normalVector.X + allignVector.X), Math.Abs(normalVector.Y+ allignVector.Y), Math.Abs(normalVector.Z + allignVector.Z)));
                //meshBuilder.AddExtrudedGeometry(listpoints, new Vector3D(1,1,1), locPoint, Point3D.Add(locPoint, heightVector));
                // meshBuilder.AddExtrudedSegments(listpoints, new Vector3D(), locPoint, Point3D.Add(locPoint, heightVector));

                var listpoints3D = new List <Point3D>
                {
                    // 2D Rectangle
                    new Point3D(locPoint.X, locPoint.Y, locPoint.Z),
                    new Point3D(locPoint.X + normalVector.X, locPoint.Y + normalVector.Y, locPoint.Z),
                    new Point3D(locPoint.X + normalVector.X - allignVector.X, locPoint.Y + normalVector.Y - allignVector.Y, locPoint.Z),
                    new Point3D(locPoint.X - allignVector.X, locPoint.Y - allignVector.Y, locPoint.Z),

                    // 3D BOX
                    // new Point3D(locPoint.X, locPoint.Y, locPoint.Z),
                    // new Point3D(locPoint.X + normalVector.X , locPoint.Y + normalVector.Y, locPoint.Z),
                    // new Point3D(locPoint.X + normalVector.X - allignVector.X, locPoint.Y + normalVector.Y - allignVector.Y, locPoint.Z),
                    // new Point3D(locPoint.X - allignVector.X, locPoint.Y - allignVector.Y, locPoint.Z),
                    // new Point3D(locPoint.X, locPoint.Y, locPoint.Z),
                    // new Point3D(locPoint.X, locPoint.Y, locPoint.Z + heightVector.Z),
                    // new Point3D(locPoint.X + normalVector.X , locPoint.Y + normalVector.Y, locPoint.Z + heightVector.Z),
                    // new Point3D(locPoint.X + normalVector.X - allignVector.X, locPoint.Y + normalVector.Y - allignVector.Y, locPoint.Z + heightVector.Z),
                    // new Point3D(locPoint.X - allignVector.X, locPoint.Y - allignVector.Y, locPoint.Z + heightVector.Z),
                };

                meshBuilder.AddPolygon(listpoints3D);

                // meshBuilder.AddBox(new Point3D((locPoint.X + normalVector.X - allignVector.X) / 2 , (locPoint.Y + normalVector.Y - allignVector.Y) / 2, (locPoint.Z + normalVector.Z - allignVector.Z + heightVector.Z) / 2), normalVector.X - allignVector.X, normalVector.Y - allignVector.Y, heightVector.Z);

                //meshBuilder.AddPolygonByCuttingEars();

                //meshBuilder.AddLoftedGeometry(new List<IList<Point3D>> { listpoints3D}, new List<IList<Vector3D>> {new List<Vector3D> {heightVector}});
                // meshBuilder.AddBox();

                // Width Vector
                // meshBuilder.AddArrow(new Point3D(x, y, z), new Point3D((double) ((x + mat.Right.X) * item.OverallWidth), y + mat.Right.Y, z + mat.Right.Z), 0.01);
                // meshBuilder.AddArrow(new Point3D(x, y, z), new Point3D((double)((x + mat.Right.X) * item.OverallWidth), y + mat.Right.Y, z + mat.Right.Z), 0.01);

                // var vecHeight = new Vector3D(0, 0, (double) (z + item.OverallHeight) - z);
                // var vecFront = new Vector3D(mat.Forward.X, mat.Forward.Y, 0);
                // var vecWidth = Vector3D.CrossProduct(vecHeight, vecFront);

                var material = new DiffuseMaterial {
                    Brush = Brushes.Aqua
                };
                var myGeometryModel = new GeometryModel3D
                {
                    Material     = material,
                    BackMaterial = material,
                    Geometry     = meshBuilder.ToMesh(true)
                };

                var element = new ModelUIElement3D {
                    Model = myGeometryModel
                };

                control.Viewport3D.Children.Add(element);

                // }
            }

            // Create the floorplan
            // Create FloorPlan
            var walls = xModel.Instances.OfType <IIfcWall>();

            foreach (var wall in walls)
            {
                MeshBuilder meshBuilder = new MeshBuilder(false, false);

                //var points = GeometryHandler.DeriveGeometry2D(wall, context);
                var points = GeometryHandler.GetFootPrint(wall, context);

                meshBuilder.AddPolygon(points);


                var material = new DiffuseMaterial {
                    Brush = Brushes.Red
                };
                var myGeometryModel = new GeometryModel3D
                {
                    Material     = material,
                    BackMaterial = material,
                    Geometry     = meshBuilder.ToMesh(true)
                };

                var element = new ModelUIElement3D {
                    Model = myGeometryModel
                };

                control.Viewport3D.Children.Add(element);
            }
        }
        public override void Calculate()
        {
            if (InputPorts[0].Data == null)
            {
                return;
            }

            var modelInfo = InputPorts[0].Data as ModelInfo;

            if (_control.FrontWidth.Text == "" || _control.FrontWidth.Text == "" || _control.FrontWidth.Text == "" || _control.FrontWidth.Text == "")
            {
                _control.settingsExpander.Header = "Please Check Settings";
                return;
            }
            else
            {
                _control.settingsExpander.Header = "Settings";
            }

            var frontWidth = _control.FrontWidth.Text.ToDouble();
            var frontDepth = _control.FrontDepth.Text.ToDouble();
            var backWidth  = _control.BackWidth.Text.ToDouble();
            var backDepth  = _control.BackDepth.Text.ToDouble();

            if (modelInfo == null)
            {
                return;
            }

            var model = modelController.GetModel(modelInfo.modelId) as IfcModel;

            if (model == null)
            {
                return;
            }

            // Get the model content
            xModel  = model.GetModel();
            context = model.xModelContext;

            // CREATE THE OPERATIONAL SPACE FOR DOORS
            var doors      = xModel.Instances.OfType <IIfcDoor>();
            var elementIds = new List <IfcGloballyUniqueId>();

            foreach (var item in doors)
            {
                elementIds.Add(item.GlobalId);
            }

            // control.InitViewPort();
            _control.viewer.Visualize(_control.viewer.CreateModelUiElementsDs(model, elementIds, false));

            foreach (var item in doors)
            {
                MeshBuilder meshBuilder = new MeshBuilder(false, false);

                var placement = ((IfcLocalPlacement)item.ObjectPlacement).PlacementRelTo.ReferencedByPlacements.First();
                var mat       = placement.ToMatrix3D();

                // Set the origin
                var x = mat.OffsetX;
                var y = mat.OffsetY;
                var z = mat.OffsetZ;

                var locPoint     = new Point3D(x, y, z);
                var allignVector = new Vector3D();
                var normalVector = new Vector3D();
                // var heightVector = new Vector3D(0, 0, (double) item.OverallHeight);

                var doorWidth = item.OverallWidth;

                foreach (
                    XbimShapeInstance instance in
                    context.ShapeInstancesOf(item)
                    .Where(
                        i => i.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded)
                    )
                {
                    allignVector = new Vector3D((instance.Transformation.Left.X), (instance.Transformation.Left.Y),
                                                (instance.Transformation.Left.Z));
                    normalVector = Vector3D.CrossProduct(allignVector, new Vector3D(0, 0, 1));
                }

                // Create the operational spaces
                var operationalSpaces = new List <List <Point3D> >();


                // FRONT
                var listpoints3D = new List <Point3D>
                {
                    // 2D Rectangle
                    new Point3D(locPoint.X, locPoint.Y, locPoint.Z),
                    new Point3D(locPoint.X + normalVector.X * frontDepth, locPoint.Y + normalVector.Y * frontDepth,
                                locPoint.Z),
                    new Point3D(locPoint.X + normalVector.X * frontDepth - allignVector.X * frontWidth,
                                locPoint.Y + normalVector.Y * frontDepth - allignVector.Y * frontWidth, locPoint.Z),
                    new Point3D(locPoint.X - allignVector.X * frontWidth, locPoint.Y - allignVector.Y * frontWidth,
                                locPoint.Z),
                };
                meshBuilder.AddPolygon(listpoints3D);
                operationalSpaces.Add(listpoints3D);

                listpoints3D = new List <Point3D>
                {
                    // 2D Rectangle
                    new Point3D(locPoint.X, locPoint.Y, locPoint.Z),
                    new Point3D(locPoint.X + normalVector.X * backDepth, locPoint.Y + normalVector.Y * backDepth, locPoint.Z),
                    new Point3D(locPoint.X + normalVector.X * backDepth - allignVector.X * backWidth,
                                locPoint.Y + normalVector.Y * backDepth - allignVector.Y * backWidth, locPoint.Z),
                    new Point3D(locPoint.X - allignVector.X * backWidth, locPoint.Y - allignVector.Y * backWidth, locPoint.Z),
                };
                meshBuilder.AddPolygon(listpoints3D);
                operationalSpaces.Add(listpoints3D);

                var material = new DiffuseMaterial {
                    Brush = Brushes.Red
                };
                var myGeometryModel = new GeometryModel3D
                {
                    Material     = material,
                    BackMaterial = material,
                    Geometry     = meshBuilder.ToMesh(true)
                };

                var element = new ModelUIElement3D {
                    Model = myGeometryModel
                };

                _control.viewer.Viewport3D.Children.Add(element);
                // BACK
                meshBuilder = new MeshBuilder();
                // Negate the normal Vector!
                normalVector.Negate();

                listpoints3D = new List <Point3D>
                {
                    // 2D Rectangle
                    new Point3D(locPoint.X, locPoint.Y, locPoint.Z),
                    new Point3D(locPoint.X + normalVector.X * frontDepth, locPoint.Y + normalVector.Y * frontDepth,
                                locPoint.Z),
                    new Point3D(locPoint.X + normalVector.X * frontDepth - allignVector.X * frontWidth,
                                locPoint.Y + normalVector.Y * frontDepth - allignVector.Y * frontWidth, locPoint.Z),
                    new Point3D(locPoint.X - allignVector.X * frontWidth, locPoint.Y - allignVector.Y * frontWidth,
                                locPoint.Z),
                };
                meshBuilder.AddPolygon(listpoints3D);
                operationalSpaces.Add(listpoints3D);

                listpoints3D = new List <Point3D>
                {
                    // 2D Rectangle
                    new Point3D(locPoint.X, locPoint.Y, locPoint.Z),
                    new Point3D(locPoint.X + normalVector.X * backDepth, locPoint.Y + normalVector.Y * backDepth, locPoint.Z),
                    new Point3D(locPoint.X + normalVector.X * backDepth - allignVector.X * backWidth,
                                locPoint.Y + normalVector.Y * backDepth - allignVector.Y * backWidth, locPoint.Z),
                    new Point3D(locPoint.X - allignVector.X * backWidth, locPoint.Y - allignVector.Y * backWidth, locPoint.Z),
                };
                meshBuilder.AddPolygon(listpoints3D);
                operationalSpaces.Add(listpoints3D);

                material = new DiffuseMaterial {
                    Brush = Brushes.Aqua
                };
                myGeometryModel = new GeometryModel3D
                {
                    Material     = material,
                    BackMaterial = material,
                    Geometry     = meshBuilder.ToMesh(true)
                };

                element = new ModelUIElement3D {
                    Model = myGeometryModel
                };

                _control.viewer.Viewport3D.Children.Add(element);

                // Create the Spaces directly in the IFC File
                // Get the building
                var building = xModel.Instances.OfType <IIfcBuilding>();

                if (building == null)
                {
                    return;
                }

                foreach (var oSpace in operationalSpaces)
                {
                    var space = CreateSpace(xModel, 100, 100, 100);
                    using (var txn = xModel.BeginTransaction("Add Space"))
                    {
                        (building.FirstOrDefault() as IfcBuilding).AddElement(space);
                        txn.Commit();
                    }
                }
            }

            // Create the floorplan
            // Create FloorPlan
            // var walls = xModel.Instances.OfType<IIfcWall>();
            // foreach (var wall in walls)
            // {
            //     MeshBuilder meshBuilder = new MeshBuilder(false, false);
            //
            //     var points = GeometryHandler.GetFootPrint(wall, context);
            //
            //     meshBuilder.AddPolygon(points);
            //
            //     var material = new DiffuseMaterial {Brush = Brushes.Red};
            //     var myGeometryModel = new GeometryModel3D
            //     {
            //         Material = material,
            //         BackMaterial = material,
            //         Geometry = meshBuilder.ToMesh(true)
            //     };
            //
            //     var element = new ModelUIElement3D {Model = myGeometryModel};
            //
            //     _control.viewer.Viewport3D.Children.Add(element);
            //
            // }

            foreach (var storey in xModel.Instances.OfType <IIfcBuildingStorey>())
            {
                var spaces = storey.Spaces;
                foreach (var space in spaces)
                {
                    MeshBuilder meshBuilder = new MeshBuilder(false, false);

                    var points = GeometryHandler.GetFootPrintNonBREP(space, context);
                    // var points = GeometryHandler.GetFootPrint(space, context);
                    meshBuilder.AddPolygon(points);

                    var brush = new SolidColorBrush(Colors.Blue)
                    {
                        Opacity = 0.3
                    };

                    var material = new DiffuseMaterial {
                        Brush = brush
                    };
                    var myGeometryModel = new GeometryModel3D
                    {
                        Material     = material,
                        BackMaterial = material,
                        Geometry     = meshBuilder.ToMesh(true)
                    };

                    var element = new ModelUIElement3D {
                        Model = myGeometryModel
                    };
                    // element.Model.Transform.Transform(new Point3D(0, 0, 1.1));

                    _control.viewer.Viewport3D.Children.Add(element);
                }
            }
        }
        public IfcElementSignature(IfcElement elem, Xbim3DModelContext geometryContext)
        {
            XbimMatrix3D m3D = XbimMatrix3D.Identity;

            if (elem.ObjectPlacement != null)
            {
                m3D = elem.ObjectPlacement.ToMatrix3D();
            }
            var geomManager = elem.ModelOf.GeometryManager;

            ShapeId = 0;
            //get the 3D shape
            var shapes = geometryContext.ShapeInstancesOf(elem);

            if (shapes.Any())
            {
                XbimRect3D r3D = XbimRect3D.Empty;
                foreach (var shape in shapes)
                {
                    if (r3D.IsEmpty)
                    {
                        r3D = shape.BoundingBox;
                    }
                    else
                    {
                        r3D.Union(shape.BoundingBox);
                    }
                }
                XbimPoint3D p3D = r3D.Centroid();
                p3D = m3D.Transform(p3D);
                BoundingSphereRadius = r3D.Length() / 2;
                CentroidX            = p3D.X;
                CentroidY            = p3D.Y;
                CentroidZ            = p3D.Z;
            }
            //get the defining type
            IfcTypeObject     ot       = elem.GetDefiningType();
            IfcMaterialSelect material = elem.GetMaterial();
            //sort out property definitions
            List <IfcPropertySet> psets = elem.GetAllPropertySets();

            PropertyCount = psets.SelectMany(p => p.HasProperties).Count();
            psets.Sort(new PropertySetNameComparer());
            foreach (var pset in psets)
            {
                PropertySetNamesKey ^= pset.Name.GetHashCode();
            }
            List <IfcPropertySingleValue> props = psets.SelectMany(p => p.HasProperties).OfType <IfcPropertySingleValue>().ToList();

            props.Sort(new PropertySingleValueNameComparer());
            foreach (var prop in props)
            {
                PropertyNamesKey ^= prop.Name.GetHashCode();
            }
            props.Sort(new PropertySingleValueValueComparer());
            foreach (var prop in props)
            {
                PropertyValuesKey ^= prop.NominalValue.GetHashCode();
            }
            ModelID       = elem.EntityLabel;
            SchemaType    = elem.GetType().Name;
            DefinedTypeId = (ot == null ? "" : ot.GlobalId.ToPart21);
            GlobalId      = elem.GlobalId;
            OwningUser    = elem.OwnerHistory.LastModifyingUser != null?elem.OwnerHistory.LastModifyingUser.ToString() : elem.OwnerHistory.OwningUser.ToString();

            Name               = elem.Name ?? "";
            Description        = elem.Description ?? "";
            HasAssignmentsKey  = elem.HasAssignments.Count();
            IsDecomposedByKey  = elem.IsDecomposedBy.Count();
            DecomposesKey      = elem.Decomposes.Count();
            HasAssociationsKey = elem.HasAssociations.Count();
            ObjectType         = elem.ObjectType ?? "";
            MaterialName       = material == null ? "" : material.Name;
            ReferencedByKey    = elem.ReferencedBy.Count();
            Tag = elem.Tag ?? "";
            HasStructuralMemberKey    = elem.HasStructuralMember.Count();
            FillsVoidsKey             = elem.FillsVoids.Count();
            ConnectedToKey            = elem.ConnectedTo.Count();
            HasCoveringsKey           = elem.HasCoverings.Count();
            HasProjectionsKey         = elem.HasProjections.Count();
            ReferencedInStructuresKey = elem.ReferencedInStructures.Count();
            HasPortsKey                = elem.HasPorts.Count();
            HasOpeningsKey             = elem.HasOpenings.Count();
            IsConnectionRealizationKey = elem.IsConnectionRealization.Count();
            ProvidesBoundariesKey      = elem.ProvidesBoundaries.Count();
            ConnectedFromKey           = elem.ConnectedFrom.Count();
            ContainedInStructureKey    = elem.ContainedInStructure.Count();
        }