Пример #1
0
 public XbimRegion(string name, XbimRect3D bounds, int population)
 {
     this.Name = name;
     this.Size = new XbimVector3D(bounds.SizeX,bounds.SizeY,bounds.SizeZ);
     this.Centre = bounds.Centroid();
     this.Population = population;
 }
Пример #2
0
 /// <summary>
 /// Adds a XbimPoint3D structure to a XbimVector3D and returns the result as a XbimPoint3D structure.
 /// </summary>
 /// <param name="p"></param>
 /// <param name="v"></param>
 /// <returns></returns>
 public static XbimPoint3D Add(XbimPoint3D p, XbimVector3D v)
 {
     return new XbimPoint3D (p.X + v.X,
                             p.Y + v.Y,
                             p.Z + v.Z
                             );
 }
Пример #3
0
        public override int GetHashCode()
        {
            XbimPoint3D p = new XbimPoint3D(1, 3, 5); //get a point

            p = Transform(p);                         //tranform
            return(p.GetHashCode());                  //use the hash of the point
        }
Пример #4
0
        static public XbimRect3D Inflate(XbimRect3D original, double x, double y, double z)
        {
            XbimPoint3D  p = new XbimPoint3D(original.X - x, original.Y - y, original.Z - z);
            XbimVector3D v = new XbimVector3D(original.SizeX + (x * 2), original.SizeY + (y * 2), original.SizeZ + (z * 2));

            return(new XbimRect3D(p, v));
        }
Пример #5
0
        static public XbimRect3D Inflate(XbimRect3D original, double inflate)
        {
            XbimPoint3D  p = new XbimPoint3D(original.X - inflate, original.Y - inflate, original.Z - inflate);
            XbimVector3D v = new XbimVector3D(original.SizeX + (inflate * 2), original.SizeY + (inflate * 2), original.SizeZ + (inflate * 2));

            return(new XbimRect3D(p, v));
        }
Пример #6
0
 /// <summary>
 /// Adds a XbimPoint3D structure to a XbimVector3D and returns the result as a XbimPoint3D structure.
 /// </summary>
 /// <param name="p"></param>
 /// <param name="v"></param>
 /// <returns></returns>
 public static XbimPoint3D Add(XbimPoint3D p, XbimVector3D v)
 {
     return(new XbimPoint3D(p.X + v.X,
                            p.Y + v.Y,
                            p.Z + v.Z
                            ));
 }
Пример #7
0
 public bool Contains(XbimPoint3D pt)
 {
     if (this.IsEmpty)
     {
         return(false);
     }
     return(this.ContainsCoords(pt.X, pt.Y, pt.Z));
 }
Пример #8
0
 public XbimRegion(string name, XbimRect3D bounds, int population, XbimMatrix3D worldCoordinateSystem)
 {
     Name                  = name;
     Size                  = new XbimVector3D(bounds.SizeX, bounds.SizeY, bounds.SizeZ);
     Centre                = bounds.Centroid();
     Population            = population;
     WorldCoordinateSystem = worldCoordinateSystem;
 }
Пример #9
0
 public XbimRect3D(XbimPoint3D Position, XbimVector3D Size)
 {
     this._x     = Position.X;
     this._y     = Position.Y;
     this._z     = Position.Z;
     this._sizeX = Size.X;
     this._sizeY = Size.Y;
     this._sizeZ = Size.Z;
 }
Пример #10
0
 public XbimRect3D(XbimPoint3D p1, XbimPoint3D p2)
 {
     this._x     = Math.Min(p1.X, p2.X);
     this._y     = Math.Min(p1.Y, p2.Y);
     this._z     = Math.Min(p1.Z, p2.Z);
     this._sizeX = Math.Max(p1.X, p2.X) - this._x;
     this._sizeY = Math.Max(p1.Y, p2.Y) - this._y;
     this._sizeZ = Math.Max(p1.Z, p2.Z) - this._z;
 }
Пример #11
0
 public XbimRect3D(XbimPoint3D highpt)
 {
     _x     = highpt.X;
     _y     = highpt.Y;
     _z     = highpt.Z;
     _sizeX = 0.0;
     _sizeY = 0.0;
     _sizeZ = 0.0;
 }
Пример #12
0
 public override bool Equals(object ob)
 {
     if (ob is XbimPoint3D)
     {
         XbimPoint3D v = (XbimPoint3D)ob;
         return(Math.Abs(X - v.X) < Tolerance && Math.Abs(Y - v.Y) < Tolerance && Math.Abs(Z - v.Z) < Tolerance);
     }
     return(false);
 }
Пример #13
0
 public override bool Equals(object ob)
 {
     if (ob is XbimPoint3D)
     {
         XbimPoint3D v = (XbimPoint3D)ob;
         return(X == v.X && Y == v.Y && Z == v.Z);
     }
     else
     {
         return(false);
     }
 }
Пример #14
0
        private XbimPoint3D[] MinMaxPoints(XbimRegion rect, double oneMeter =  1.0)
        {
            var pMin = new XbimPoint3D(
                (rect.Centre.X - (rect.Size.X / 2)) / oneMeter,
                (rect.Centre.Y - (rect.Size.Y / 2)) / oneMeter,
                (rect.Centre.Z - (rect.Size.Z / 2)) / oneMeter
                );

            var pMax = new XbimPoint3D(
                (rect.Centre.X + (rect.Size.X / 2)) / oneMeter,
                (rect.Centre.Y + (rect.Size.Y / 2)) / oneMeter,
                (rect.Centre.Z + (rect.Size.Z / 2)) / oneMeter
                );

            return new[] { pMin, pMax };
        }
Пример #15
0
        // Two CreateRotation functions below are adapted from the implementation of getRotation in
        // the VisualizationLibrary SDK (sources at http://visualizationlibrary.org/ )

        /// <summary>
        /// Creates a rotation matrix converting from a starting direction to a desired direction.
        /// </summary>
        /// <param name="fromDirection">Starting direction</param>
        /// <param name="toDirection">Desired direction</param>
        /// <returns>the matrix that applied to <see paramref="fromDirection"/> results in <see paramref="toDirection"/></returns>
        public static XbimMatrix3D CreateRotation(XbimPoint3D fromDirection, XbimPoint3D toDirection)
        {
            var a = new XbimVector3D(toDirection.X, toDirection.Y, toDirection.Z);
            var b = new XbimVector3D(fromDirection.X, fromDirection.Y, fromDirection.Z);

            a = a.Normalized();
            b = b.Normalized();

            double cosa = a.DotProduct(b);

            cosa = clamp(cosa, -1, +1);

            var    axis  = XbimVector3D.CrossProduct(a, b).Normalized();
            double alpha = Math.Acos(cosa);

            return(CreateRotation(alpha, axis));
        }
Пример #16
0
        public static XbimPoint3D Multiply(XbimPoint3D p, XbimMatrix3D m)
        {
            var x = p.X;
            var y = p.Y; 
            var z = p.Z;
            

            
            XbimPoint3D pRet = new XbimPoint3D(m.M11 * x + m.M21 * y + m.M31 * z + m.OffsetX,
                                   m.M12 * x + m.M22 * y + m.M32 * z + m.OffsetY,
                                   m.M13 * x + m.M23 * y + m.M33 * z + m.OffsetZ
                                  );
            if (m.IsAffine) return pRet;
            double affineRatio = x * m.M14 + y * m.M24 + z * m.M34 + m.M44;
            x = pRet.X / affineRatio;
            y = pRet.Y / affineRatio;
            z = pRet.Z / affineRatio;
            return new XbimPoint3D(x, y, z);
        }
Пример #17
0
        /// <summary>
        /// Transforms a bounding rect so that it is still axis aligned
        /// </summary>
        /// <param name="rect3d"></param>
        /// <param name="m"></param>
        /// <returns></returns>
        static public XbimRect3D TransformBy(XbimRect3D rect3d, XbimMatrix3D m)
        {
            XbimPoint3D  min      = rect3d.Min;
            XbimPoint3D  max      = rect3d.Max;
            XbimVector3D up       = m.Up;
            XbimVector3D right    = m.Right;
            XbimVector3D backward = m.Backward;
            var          xa       = right * min.X;
            var          xb       = right * max.X;

            var ya = up * min.Y;
            var yb = up * max.Y;

            var za = backward * min.Z;
            var zb = backward * max.Z;

            return(new XbimRect3D(
                       XbimVector3D.Min(xa, xb) + XbimVector3D.Min(ya, yb) + XbimVector3D.Min(za, zb) + m.Translation,
                       XbimVector3D.Max(xa, xb) + XbimVector3D.Max(ya, yb) + XbimVector3D.Max(za, zb) + m.Translation
                       ));
        }
Пример #18
0
        public static XbimPoint3D Multiply(XbimPoint3D p, XbimMatrix3D m)
        {
            var x = p.X;
            var y = p.Y;
            var z = p.Z;



            XbimPoint3D pRet = new XbimPoint3D(m.M11 * x + m.M21 * y + m.M31 * z + m.OffsetX,
                                               m.M12 * x + m.M22 * y + m.M32 * z + m.OffsetY,
                                               m.M13 * x + m.M23 * y + m.M33 * z + m.OffsetZ
                                               );

            if (!m.IsAffine)
            {
                double AffineRatio = x * m.M14 + y * m.M24 + z * m.M34 + m.M44;
                pRet.X /= AffineRatio;
                pRet.Y /= AffineRatio;
                pRet.Z /= AffineRatio;
            }
            return(pRet);
        }
Пример #19
0
        public static XbimPoint3D Multiply(XbimPoint3D p, XbimMatrix3D m)
        {
            var x = p.X;
            var y = p.Y; 
            var z = p.Z;
            

            
            XbimPoint3D pRet = new XbimPoint3D(m.M11 * x + m.M21 * y + m.M31 * z + m.OffsetX,
                                   m.M12 * x + m.M22 * y + m.M32 * z + m.OffsetY,
                                   m.M13 * x + m.M23 * y + m.M33 * z + m.OffsetZ
                                  );

            if (!m.IsAffine)
            {
                double AffineRatio = x * m.M14 + y * m.M24 + z * m.M34 + m.M44;
                pRet.X /= AffineRatio;
                pRet.Y /= AffineRatio;
                pRet.Z /= AffineRatio;
            }
            return pRet;

        }
Пример #20
0
 static XbimPoint3D()
 {
     Zero = new XbimPoint3D(0, 0, 0);
 }
Пример #21
0
        /// <summary>
        /// Extends to include the specified point; returns true if boundaries were changed.
        /// </summary>
        /// <param name="Point"></param>
        /// <returns></returns>
        internal bool IncludePoint(XbimPoint3D Point)
        {
            if (!IsValid)
            {
                PointMin = Point;
                PointMax = Point;
                IsValid = true;
                return true;
            }
            bool ret = false;

            if (PointMin.X > Point.X)
            { PointMin.X = Point.X; ret = true; }
            if (PointMin.Y > Point.Y)
            { PointMin.Y = Point.Y; ret = true; }
            if (PointMin.Z > Point.Z)
            { PointMin.Z = Point.Z; ret = true; }

            if (PointMax.X < Point.X)
            { PointMax.X = Point.X; ret = true; }
            if (PointMax.Y < Point.Y)
            { PointMax.Y = Point.Y; ret = true; }
            if (PointMax.Z < Point.Z)
            { PointMax.Z = Point.Z; ret = true; }

            IsValid = true;

            return ret;
        }
Пример #22
0
 public BoundingBox(double srXmin, double srYmin, double srZmin, double srXmax, double srYmax, double srZmax )
 {
     PointMin = new XbimPoint3D(srXmin, srYmin, srZmin);
     PointMax = new XbimPoint3D(srXmax, srYmax, srZmax);
     IsValid = true;
 }
Пример #23
0
 public static XbimPoint3D operator *(XbimPoint3D p, XbimMatrix3D m)
 {
     return(XbimPoint3D.Multiply(p, m));
 }
Пример #24
0
 void IXbimTriangulatesToPositionsIndices.AddPosition(XbimPoint3D XbimPoint3D)
 {
     _points.Add(XbimPoint3D);
 }
Пример #25
0
        public static void Read(this XbimMeshGeometry3D m3D, byte[] mesh, XbimMatrix3D? transform = null)
        {
            var indexBase = m3D.Positions.Count;
            var qrd = new XbimQuaternion();

            XbimMatrix3D? matrix3D = null;
            if (transform.HasValue)
            {
                qrd = transform.Value.GetRotationQuaternion();
                matrix3D = transform.Value;
            }
            using (var ms = new MemoryStream(mesh))
            {
                using (var br = new BinaryReader(ms))
                {
                    // ReSharper disable once UnusedVariable
                    var version = br.ReadByte(); //stream format version
                    var numVertices = br.ReadInt32();
                    var numTriangles = br.ReadInt32();

                    var uniqueVertices = new List<XbimPoint3D>(numVertices);
                    var vertices = new List<XbimPoint3D>(numVertices * 4); //approx the size
                    var triangleIndices = new List<int>(numTriangles * 3);
                    var normals = new List<XbimVector3D>(numVertices * 4);
                    for (var i = 0; i < numVertices; i++)
                    {
                        double x = br.ReadSingle();
                        double y = br.ReadSingle();
                        double z = br.ReadSingle();
                        var p = new XbimPoint3D(x, y, z);
                        if (matrix3D.HasValue)
                            p = matrix3D.Value.Transform(p);
                        uniqueVertices.Add(p);
                    }
                    var numFaces = br.ReadInt32();

                    for (var i = 0; i < numFaces; i++)
                    {
                        var numTrianglesInFace = br.ReadInt32();
                        if (numTrianglesInFace == 0) continue;
                        var isPlanar = numTrianglesInFace > 0;
                        numTrianglesInFace = Math.Abs(numTrianglesInFace);
                        if (isPlanar)
                        {
                            var normal = br.ReadPackedNormal().Normal;
                            if (!qrd.IsIdentity())
                            {
                                var baseVal = new XbimVector3D(normal.X, normal.Y, normal.Z);
                                XbimQuaternion.Transform(ref baseVal, ref qrd, out normal);
                            }
                            var uniqueIndices = new Dictionary<int, int>();
                            for (var j = 0; j < numTrianglesInFace; j++)
                            {
                                for (var k = 0; k < 3; k++)
                                {
                                    var idx = ReadIndex(br, numVertices);
                                    int writtenIdx;
                                    if (!uniqueIndices.TryGetValue(idx, out writtenIdx)) //we haven't got it, so add it
                                    {
                                        writtenIdx = vertices.Count;
                                        vertices.Add(uniqueVertices[idx]);
                                        uniqueIndices.Add(idx, writtenIdx);
                                        //add a matching normal
                                        normals.Add(normal);
                                    }
                                    triangleIndices.Add(indexBase + writtenIdx);
                                }
                            }
                        }
                        else
                        {
                            var uniqueIndices = new Dictionary<int, int>();
                            for (var j = 0; j < numTrianglesInFace; j++)
                            {
                                for (var k = 0; k < 3; k++)
                                {
                                    var idx = ReadIndex(br, numVertices);
                                    var normal = br.ReadPackedNormal().Normal;
                                    int writtenIdx;
                                    if (!uniqueIndices.TryGetValue(idx, out writtenIdx)) //we haven't got it, so add it
                                    {
                                        writtenIdx = vertices.Count;
                                        vertices.Add(uniqueVertices[idx]);
                                        uniqueIndices.Add(idx, writtenIdx);

                                        if (!qrd.IsIdentity())
                                        {
                                            var baseVal = new XbimVector3D(normal.X, normal.Y, normal.Z);
                                            XbimQuaternion.Transform(ref baseVal, ref qrd, out normal);
                                        }
                                        normals.Add(normal);
                                    }
                                    triangleIndices.Add(indexBase + writtenIdx);
                                }
                            }
                        }
                    }

                    m3D.Positions = m3D.Positions.Concat(vertices).ToList();
                    m3D.TriangleIndices = m3D.TriangleIndices.Concat(triangleIndices).ToList();
                    m3D.Normals = m3D.Normals.Concat(normals).ToList();
                }
            }
        }
Пример #26
0
 public XbimRect3D(XbimPoint3D p1, XbimPoint3D p2)
 {
     this._x = Math.Min(p1.X, p2.X);
     this._y = Math.Min(p1.Y, p2.Y);
     this._z = Math.Min(p1.Z, p2.Z);
     this._sizeX = Math.Max(p1.X, p2.X) - this._x;
     this._sizeY = Math.Max(p1.Y, p2.Y) - this._y;
     this._sizeZ = Math.Max(p1.Z, p2.Z) - this._z;
 }
Пример #27
0
 public IXbimPoint CreatePoint(XbimPoint3D p, double tolerance)
 {
     return _engine.CreatePoint(p, tolerance);
 }
Пример #28
0
 /// <summary>
 /// Returns true if the triangle that contains the edge is facing away from the centroid of the mesh
 /// </summary>
 /// <param name="triangleEdge"></param>
 /// <returns></returns>
 public bool IsFacingOutward(XbimTriangleEdge edge)
 {
     //find the centroid of the triangle
     var p1 = _vertices[edge.StartVertexIndex].Position;
     var p2 = _vertices[edge.NextEdge.StartVertexIndex].Position;
     var p3 = _vertices[edge.NextEdge.NextEdge.StartVertexIndex].Position;
     var centroid = new XbimPoint3D((p1.X + p2.X + p3.X) / 3, (p1.Y + p2.Y + p3.Y) / 3, (p1.Z + p2.Z + p3.Z) / 3);
     var normal = TriangleNormal(edge);
     var vecOut = PointingOutwardFrom(centroid);
     var dot = vecOut.DotProduct(normal);
     return dot > 0;
 }
Пример #29
0
 public XbimVector3D PointingOutwardFrom(XbimPoint3D point3D)
 {
     var v = point3D - Centroid;
     v.Normalize();
     return v;
 }
        /// <summary>
        /// Clears the current graphics and initiates the cascade of events that result in viewing the scene.
        /// </summary>
        /// <param name="EntityLabels">If null loads the whole model, otherwise only elements listed in the enumerable</param>
        public void LoadGeometry(XbimModel model, bool recalcView = true)
        {
            // AddLayerToDrawingControl is the function that actually populates the geometry in the viewer.
            // AddLayerToDrawingControl is triggered by BuildRefModelScene and BuildScene below here when layers get ready.

            //reset all the visuals
            ClearGraphics(recalcView);
            short userDefinedId = 0;
            if (model == null)
                return; //nothing to show
            model.UserDefinedId = userDefinedId;
            Xbim3DModelContext context = new Xbim3DModelContext(model);
            XbimRegion largest = context.GetLargestRegion();
            XbimPoint3D c = new XbimPoint3D(0, 0, 0);
            XbimRect3D bb = XbimRect3D.Empty;
            if (largest != null)
                bb = new XbimRect3D(largest.Centre, largest.Centre);

            foreach (var refModel in model.ReferencedModels)
            {

                XbimRegion r;
                refModel.Model.UserDefinedId = ++userDefinedId;

                Xbim3DModelContext refContext = new Xbim3DModelContext(refModel.Model);
                r = refContext.GetLargestRegion();

                if (r != null)
                {
                    if (bb.IsEmpty)
                        bb = new XbimRect3D(r.Centre, r.Centre);
                    else
                        bb.Union(r.Centre);
                }
            }
            XbimPoint3D p = bb.Centroid();
            _modelTranslation = new XbimVector3D(-p.X, -p.Y, -p.Z);
            model.ReferencedModels.CollectionChanged += RefencedModels_CollectionChanged;
            //build the geometric scene and render as we go
            BuildScene(context);
            foreach (var refModel in model.ReferencedModels)
            {
                Xbim3DModelContext refContext = new Xbim3DModelContext(refModel.Model);
                BuildScene(refContext);
            }
            if (recalcView) RecalculateView(model);
        }
Пример #31
0
 public static XbimVector3D Subtract(XbimPoint3D a, XbimPoint3D b)
 {
     return new XbimVector3D(a.X - b.X,
                             a.Y - b.Y,
                             a.Z - b.Z);
 }
Пример #32
0
 public IXbimVertex CreateVertexPoint(XbimPoint3D point, double precision)
 {
     return _engine.CreateVertexPoint(point, precision);
 }
Пример #33
0
        private void OnOpenView(object sender, ExecutedRoutedEventArgs e)
        {
            if (Bcfier.SelectedBcf() == null)
                return;
            var view = e?.Parameter as ViewPoint;

            if (view == null)
                return;
            var v = view.VisInfo;

            var position = new XbimPoint3D();
            var direction = new XbimPoint3D();
            var upDirection = new XbimPoint3D();

            if (v.PerspectiveCamera != null)
            {
                // todo: this works internally, but we must ensure it's compatible with other bcf viewers
                var pc = v.PerspectiveCamera;
                position = new XbimPoint3D(pc.CameraViewPoint.X, pc.CameraViewPoint.Y, pc.CameraViewPoint.Z);
                direction = new XbimPoint3D(pc.CameraDirection.X, pc.CameraDirection.Y, pc.CameraDirection.Z);
                upDirection = new XbimPoint3D(pc.CameraUpVector.X, pc.CameraUpVector.Y, pc.CameraUpVector.Z);

                _xpWindow.DrawingControl.Viewport.Orthographic = false;
                var pCam = _xpWindow.DrawingControl.Viewport.Camera as System.Windows.Media.Media3D.PerspectiveCamera;
                if (pCam != null)
                    pCam.FieldOfView = pc.FieldOfView;
            }
            else if (v.OrthogonalCamera != null)
            {
                // todo: this works internally, but we must ensure it's compatible with other bcf viewers
                var pc = v.OrthogonalCamera;
                _xpWindow.DrawingControl.Viewport.Orthographic = true;
                position = new XbimPoint3D(pc.CameraViewPoint.X, pc.CameraViewPoint.Y, pc.CameraViewPoint.Z);
                direction = new XbimPoint3D(pc.CameraDirection.X, pc.CameraDirection.Y, pc.CameraDirection.Z);
                upDirection = new XbimPoint3D(pc.CameraUpVector.X, pc.CameraUpVector.Y, pc.CameraUpVector.Z);

                var pCam = _xpWindow.DrawingControl.Viewport.Camera as OrthographicCamera;
                if (pCam != null)
                    pCam.Width = pc.ViewToWorldScale;
            }
            var directionV = new XbimVector3D(direction.X, direction.Y, direction.Z);
            var upDirectionV = new XbimVector3D(upDirection.X, upDirection.Y, upDirection.Z);

            var pos = new Point3D(position.X, position.Y, position.Z);
            var dir = new Vector3D(directionV.X, directionV.Y, directionV.Z);
            var upDir = new Vector3D(upDirectionV.X, upDirectionV.Y, upDirectionV.Z);
            _xpWindow.DrawingControl.Viewport.SetView(pos, dir, upDir, 500);

            if (v.ClippingPlanes != null && v.ClippingPlanes.Any()) {
                var curP = v.ClippingPlanes[0];
                _xpWindow.DrawingControl.SetCutPlane(
                    curP.Location.X, curP.Location.Y, curP.Location.Z,
                    curP.Direction.X, curP.Direction.Y, curP.Direction.Z
                    );
            }
            else
            {
                _xpWindow.DrawingControl.ClearCutPlane();
            }

            // todo: components list to be implemented
        }
Пример #34
0
 public void Union(XbimPoint3D highpt)
 {
     Union(new XbimRect3D(highpt, highpt));
 }
Пример #35
0
 public XbimRect3D(XbimPoint3D Position, XbimVector3D Size)
 {
     this._x = Position.X;
     this._y = Position.Y;
     this._z = Position.Z;
     this._sizeX = Size.X;
     this._sizeY = Size.Y;
     this._sizeZ = Size.Z;
 }
Пример #36
0
        /// <summary>
        /// Reads an ascii string of Xbim mesh geometry data
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public bool Read(String data, XbimMatrix3D? trans = null)
        {
            var version = 2; //we are at at least verson 2 now
            var q = new XbimQuaternion();
            if (trans.HasValue)
                q = trans.Value.GetRotationQuaternion();
            using (var sr = new StringReader(data))
            {

                var vertexList = new List<XbimPoint3D>(); //holds the actual positions of the vertices in this data set in the mesh
                var normalList = new List<XbimVector3D>(); //holds the actual normals of the vertices in this data set in the mesh
                String line;
                // Read and display lines from the data until the end of
                // the data is reached.

                while ((line = sr.ReadLine()) != null)
                {

                    var tokens = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    if (tokens.Length > 1) //we need a command and some data
                    {
                        var command = tokens[0].Trim().ToUpper();
                        switch (command)
                        {
                            case "P":
                                version = Int32.Parse(tokens[1]);
                                var pointCount = 512;
                                //var faceCount = 128;
                                //var triangleCount = 256;
                                var normalCount = 512;
                                if (tokens.Length > 1) pointCount = Int32.Parse(tokens[2]);
                               // if (tokens.Length > 2) faceCount = Int32.Parse(tokens[3]);
                               // if (tokens.Length > 3) triangleCount = Int32.Parse(tokens[4]);
                                //version 2 of the string format uses packed normals
                                if (version < 2 && tokens.Length > 4) normalCount = Int32.Parse(tokens[5]);
                                vertexList = new List<XbimPoint3D>(pointCount);
                                normalList = new List<XbimVector3D>(normalCount);
                                break;
                            case "V": //process vertices
                                for (var i = 1; i < tokens.Length; i++)
                                {
                                    var xyz = tokens[i].Split(',');
                                    var p = new XbimPoint3D(Convert.ToDouble(xyz[0], CultureInfo.InvariantCulture),
                                                                      Convert.ToDouble(xyz[1], CultureInfo.InvariantCulture),
                                                                      Convert.ToDouble(xyz[2], CultureInfo.InvariantCulture));
                                    if (trans.HasValue)
                                        p = trans.Value.Transform(p);
                                    vertexList.Add(p);
                                }
                                break;
                            case "N": //processes normals
                                for (var i = 1; i < tokens.Length; i++)
                                {
                                    var xyz = tokens[i].Split(',');
                                    var v = new XbimVector3D(Convert.ToDouble(xyz[0], CultureInfo.InvariantCulture),
                                                                       Convert.ToDouble(xyz[1], CultureInfo.InvariantCulture),
                                                                       Convert.ToDouble(xyz[2], CultureInfo.InvariantCulture));
                                    normalList.Add(v);
                                }
                                break;
                            case "T": //process triangulated meshes
                                var currentNormal = XbimVector3D.Zero;
                                //each time we start a new mesh face we have to duplicate the vertices to ensure that we get correct shading of planar and non planar faces
                                var writtenVertices = new Dictionary<int, int>();

                                for (var i = 1; i < tokens.Length; i++)
                                {
                                    var triangleIndices = tokens[i].Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                                    if (triangleIndices.Length != 3) throw new Exception("Invalid triangle definition");
                                    for (var t = 0; t < 3; t++)
                                    {
                                        var indexNormalPair = triangleIndices[t].Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

                                        if (indexNormalPair.Length > 1) //we have a normal defined
                                        {
                                            var normalStr = indexNormalPair[1].Trim();
                                            if (version < 2)
                                            {
                                                switch (normalStr)
                                                {
                                                    case "F": //Front
                                                        currentNormal = new XbimVector3D(0, -1, 0);
                                                        break;
                                                    case "B": //Back
                                                        currentNormal = new XbimVector3D(0, 1, 0);
                                                        break;
                                                    case "L": //Left
                                                        currentNormal = new XbimVector3D(-1, 0, 0);
                                                        break;
                                                    case "R": //Right
                                                        currentNormal = new XbimVector3D(1, 0, 0);
                                                        break;
                                                    case "U": //Up
                                                        currentNormal = new XbimVector3D(0, 0, 1);
                                                        break;
                                                    case "D": //Down
                                                        currentNormal = new XbimVector3D(0, 0, -1);
                                                        break;
                                                    default: //it is an index number
                                                        var normalIndex = int.Parse(indexNormalPair[1]);
                                                        currentNormal = normalList[normalIndex];
                                                        break;
                                                }
                                            }
                                            else
                                            {
                                                var normalIndex = ushort.Parse(indexNormalPair[1]);
                                                var packedNormal = new XbimPackedNormal(normalIndex);
                                                currentNormal = packedNormal.Normal;
                                            }
                                            if (trans.HasValue)
                                            {
                                                XbimVector3D v;
                                                XbimQuaternion.Transform(ref currentNormal, ref q, out v);
                                                currentNormal = v;

                                            }
                                        }

                                        //now add the index
                                        var index = int.Parse(indexNormalPair[0]);

                                        int alreadyWrittenAt;
                                        if (!writtenVertices.TryGetValue(index, out alreadyWrittenAt)) //if we haven't  written it in this mesh pass, add it again unless it is the first one which we know has been written
                                        {
                                            //all vertices will be unique and have only one normal
                                            writtenVertices.Add(index, PositionCount);
                                            TriangleIndices.Add(PositionCount);
                                            Positions.Add(vertexList[index]);
                                            Normals.Add(currentNormal);
                                        }
                                        else //just add the index reference
                                        {
                                            TriangleIndices.Add(alreadyWrittenAt);
                                        }
                                    }
                                }

                                break;
                            case "F":
                                break;
                            default:
                                throw new Exception("Invalid Geometry Command");

                        }
                    }
                }
            }
            return true;
        }
Пример #37
0
 public XbimRect3D(XbimPoint3D highpt)
 {
     _x = highpt.X;
     _y = highpt.Y;
     _z = highpt.Z;
     _sizeX = 0.0;
     _sizeY = 0.0;
     _sizeZ = 0.0;
 }
Пример #38
0
        public double GetArea()
        {
            // the normal can be taken from the product of two segments on the polyline
            if (Count() < 3)
                return double.NaN;

            XbimVector3D normal = Normal() * -1;
            XbimVector3D firstSegment = this.FirstSegment();
            XbimVector3D up = XbimVector3D.CrossProduct(normal, firstSegment);
            
            XbimVector3D campos = new XbimVector3D(
                _geomPoints[0].Point.X,
                _geomPoints[0].Point.Y,
                _geomPoints[0].Point.Z
                ); 
            XbimVector3D target = campos + normal;
            XbimMatrix3D m = XbimMatrix3D.CreateLookAt(campos, target, up);


            XbimPoint3D[] point = new XbimPoint3D[Count()];
            for (int i = 0; i < point.Length; i++)
            {
                XbimPoint3D pBefore = new XbimPoint3D(
                    _geomPoints[i].Point.X,
                    _geomPoints[i].Point.Y,
                    _geomPoints[i].Point.Z
                    );
                XbimPoint3D pAft = m.Transform(pBefore);
                point[i] = pAft;
            }

            // http://stackoverflow.com/questions/2553149/area-of-a-irregular-shape
            // it assumes that the last point is NOT the same of the first one, but it tolerates the case.
            double area = 0.0f;
            
            int numVertices = Count();
            for (int i = 0; i < numVertices - 1; ++i)
            {
                area += point[i].X * point[i + 1].Y - point[i + 1].X * point[i].Y;
            }
            area += point[numVertices - 1].X * point[0].Y - point[0].X * point[numVertices - 1].Y;
            area /= 2.0;
            return area;
        }
Пример #39
0
 public bool Contains(XbimPoint3D pt)
 {
     if (this.IsEmpty)
     {
         return false;
     }
     return this.ContainsCoords(pt.X, pt.Y, pt.Z);
 }
Пример #40
0
 private bool GetPointFromRow(COBieCoordinateRow row, out XbimPoint3D point)
 {
     double x, y, z;
     if ((double.TryParse(row.CoordinateXAxis, out x)) &&
         (double.TryParse(row.CoordinateYAxis, out y)) &&
         (double.TryParse(row.CoordinateZAxis, out z))
         )
     {
         point = new XbimPoint3D(x, y, z);
         return true;
     }
     else
     {
         point = new XbimPoint3D();
         return false;
     }
 }
Пример #41
0
 void IXbimTriangulatesToPositionsNormalsIndices.AddPosition(XbimPoint3D XbimPoint3D)
 {
     Positions.Add(XbimPoint3D);
 }
Пример #42
0
 public void Union(XbimPoint3D highpt)
 {
     Union(new XbimRect3D(highpt, highpt));
 }
Пример #43
0
        public void Run()
        {
            //to start we need an ifc file, here it is Clinic_Example.ifc
            string ifcFile = @"IfcFiles/Clinic_Example.ifc";
            string xbimFile = Path.ChangeExtension(ifcFile, "xBIM");  //will generate if not existing
            
            if (File.Exists(ifcFile))
            {
                using (XbimModel model = new XbimModel())
                {
                    if (File.Exists(xbimFile))
                    {
                        //assume the xbim file has the geometry already generated from ifc file, as below
                        model.Open(xbimFile, XbimDBAccess.Read);
                    }
                    else
                    {
                        //create the xbim file from the ifc file
                        model.CreateFrom(ifcFile, xbimFile, delegate(int percentProgress, object userState)
                        {
                            Console.Write("\rReading File {0}", percentProgress);
                        });

                        model.Open(xbimFile, XbimDBAccess.ReadWrite); //readwrite as we need to add the geometry
                        //add the the geometry information to the model
                        int total = (int)model.Instances.CountOf<IfcProduct>();
                        ReportProgressDelegate progDelegate = delegate(int percentProgress, object userState)
                        {
                            Console.Write("\rGeometry {0} / {1}", total, (total * percentProgress / 100));
                        };
                        XbimMesher.GenerateGeometry(model, null, progDelegate);
                    }
                    
                     //get all the IfcDoors in the model
                     IEnumerable<IfcDoor> ifcDoors = model.IfcProducts.OfType<IfcDoor>(); //get all the ifcdoors for this model
                     if (ifcDoors.Any()) 
                     {
                         IfcDoor ifcDoor = ifcDoors.First(); //we use the first door to get the bounding box from
                         XbimGeometryData geoData = model.GetGeometryData(ifcDoor, XbimGeometryType.BoundingBox).FirstOrDefault();
                         if (geoData != null)
                         {
                             XbimRect3D boundBox = XbimRect3D.FromArray(geoData.ShapeData);//size information for the IfcDoor, but the information is for the bounding box which encloses the door 

                             //if want want in World space 
                             XbimMatrix3D worldMatrix = geoData.Transform;
                             //if we want to convert to World space we can use the geoData.Transform property and create the world matrix
                             XbimPoint3D MinPtOCS = new XbimPoint3D(boundBox.X, boundBox.Y, boundBox.Z);
                             XbimPoint3D MaxPtOCS = new XbimPoint3D(boundBox.X + boundBox.SizeX, boundBox.Y + boundBox.SizeY, boundBox.Z + boundBox.SizeZ);
                             //transformed values, may no longer a valid bounding box in the new space if any Pitch or Yaw, i.e. stairs ceiling supports
                             XbimPoint3D MinPtWCS = worldMatrix.Transform(MinPtOCS);
                             XbimPoint3D MaxPtWCS = worldMatrix.Transform(MaxPtOCS);
                             //if you product is at any angle to the World space then the bounding box can be recalculated, 
                            //a example of this can be found here https://sbpweb.svn.codeplex.com/svn/SBPweb.Workbench/Workbench%20Framework%202.0.0.x/Presentation/Windows.WPF/Utils/Maths.cs 
                            //in the TransformBounds function
                            Console.WriteLine("\n-------------Bounding Box Information-------------");
                            Console.WriteLine("Entity Type = {0}", IfcMetaData.GetType(geoData.IfcTypeId).Name);
                            Console.WriteLine("Entity Label = {0}", Math.Abs(ifcDoor.EntityLabel).ToString());
                            Console.WriteLine("Size X = {0:F2}", boundBox.SizeX.ToString());
                            Console.WriteLine("Size Y = {0:F2}", boundBox.SizeY.ToString());
                            Console.WriteLine("Size Z = {0:F2}", boundBox.SizeZ.ToString());
                            Console.WriteLine("Object space minimum point {0}", MinPtOCS);
                            Console.WriteLine("Object space maximum point {0}", MaxPtOCS);
                            Console.WriteLine("World space minimum point {0}", MinPtWCS);
                            Console.WriteLine("World space maximum point {0}", MaxPtWCS);
                            Console.WriteLine("---------------------------------------------");
                         }
                     }
                     else
                     {
                         Console.WriteLine(string.Format("Failed to find any IfcDoor's in {0}", ifcFile));
                         return; //exit
                     }
                }
            }
            else
            {
                Console.WriteLine(string.Format("Failed to find {0} in executable directory", ifcFile));
            }
            Console.WriteLine("\nFinished");
          
        }
Пример #44
0
        /// <summary>
        /// Add a Bounding Box extrusion onto the ifcProduct
        /// </summary>
        /// <param name="row">COBieCoordinateRow holding the data for one corner</param>
        /// <param name="rowNext">COBieCoordinateRow holding the data for the other corner</param>
        /// <param name="placementRelToIfcProduct">Product which is parent of ifcProduct passed product to add extrusion onto</param>
        /// <param name="ifcProduct">IfcProduct to add the extrusion onto</param>
        private void AddExtrudedRectangle(COBieCoordinateRow row, COBieCoordinateRow rowNext, IfcProduct ifcProduct, IfcProduct placementRelToIfcProduct)
        {
            if (ifcProduct != null)
            {
                COBieCoordinateRow lowerLeftRow, upperRightRow;
                if (row.Category.ToLower() == "box-lowerleft")
                {
                    lowerLeftRow = row;
                    upperRightRow = rowNext;
                }
                else
                {
                    lowerLeftRow = rowNext;
                    upperRightRow = row;
                }
                IfcLocalPlacement objectPlacement = CalcObjectPlacement(lowerLeftRow, placementRelToIfcProduct);
                if (objectPlacement != null)
                {
                    //set the object placement for the space
                    ifcProduct.ObjectPlacement = objectPlacement;

                    //get matrix to the space placement
                    XbimMatrix3D matrix3D = ConvertMatrix3D(objectPlacement);
                    //invert matrix so we can convert row points back to the object space
                    matrix3D.Invert();
                    //lets get the points from the two rows
                    XbimPoint3D lowpt, highpt;
                    if ((GetPointFromRow(upperRightRow, out highpt)) &&
                         (GetPointFromRow(lowerLeftRow, out lowpt))
                        )
                    {
                        //transform the points back to object space
                        lowpt = matrix3D.Transform(lowpt);
                        highpt = matrix3D.Transform(highpt);
                        //in object space so we can use Rect3D as this will be aligned with coordinates systems X and Y
                        XbimRect3D bBox = new XbimRect3D();
                        bBox.Location = lowpt;
                        bBox.Union(highpt);
                        if ((double.NaN.CompareTo(bBox.SizeX) != 0) && (double.NaN.CompareTo(bBox.SizeY) != 0))
                        {
                            XbimPoint3D ctrPt = new XbimPoint3D(bBox.X + (bBox.SizeX / 2.0), bBox.Y + (bBox.SizeY / 2.0), bBox.Z + (bBox.SizeZ / 2.0));

                            //Create IfcRectangleProfileDef
                            IfcCartesianPoint IfcCartesianPointCtr = Model.Instances.New<IfcCartesianPoint>(cp => { cp.X = ctrPt.X; cp.Y = ctrPt.Y; cp.Z = 0.0; }); //centre point of 2D box
                            IfcDirection IfcDirectionXDir = Model.Instances.New<IfcDirection>(d => { d.X = 1.0; d.Y = 0; d.Z = 0.0; }); //default to X direction
                            IfcAxis2Placement2D ifcAxis2Placement2DCtr = Model.Instances.New<IfcAxis2Placement2D>(a2p => { a2p.Location = IfcCartesianPointCtr; a2p.RefDirection = IfcDirectionXDir; });
                            IfcRectangleProfileDef ifcRectangleProfileDef = Model.Instances.New<IfcRectangleProfileDef>(rpd => { rpd.ProfileType = IfcProfileTypeEnum.AREA; rpd.ProfileName = row.RowName; rpd.Position = ifcAxis2Placement2DCtr; rpd.XDim = bBox.SizeX; rpd.YDim = bBox.SizeY; });

                            //Create IfcExtrudedAreaSolid
                            IfcDirection IfcDirectionAxis = Model.Instances.New<IfcDirection>(d => { d.X = 0.0; d.Y = 0; d.Z = 1.0; }); //default to Z direction
                            IfcDirection IfcDirectionRefDir = Model.Instances.New<IfcDirection>(d => { d.X = 1.0; d.Y = 0; d.Z = 0.0; }); //default to X direction
                            IfcCartesianPoint IfcCartesianPointPosition = Model.Instances.New<IfcCartesianPoint>(cp => { cp.X = 0.0; cp.Y = 0.0; cp.Z = 0.0; }); //centre point of 2D box
                            IfcAxis2Placement3D ifcAxis2Placement3DPosition = Model.Instances.New<IfcAxis2Placement3D>(a2p3D => { a2p3D.Location = IfcCartesianPointPosition; a2p3D.Axis = IfcDirectionAxis; a2p3D.RefDirection = IfcDirectionRefDir; });
                            IfcDirection IfcDirectionExtDir = Model.Instances.New<IfcDirection>(d => { d.X = 0.0; d.Y = 0; d.Z = 1.0; }); //default to Z direction
                            IfcExtrudedAreaSolid ifcExtrudedAreaSolid = Model.Instances.New<IfcExtrudedAreaSolid>(eas => { eas.SweptArea = ifcRectangleProfileDef; eas.Position = ifcAxis2Placement3DPosition; eas.ExtrudedDirection = IfcDirectionExtDir; eas.Depth = bBox.SizeZ; });

                            //Create IfcShapeRepresentation
                            IfcShapeRepresentation ifcShapeRepresentation = Model.Instances.New<IfcShapeRepresentation>(sr => { sr.ContextOfItems = Model.IfcProject.ModelContext(); sr.RepresentationIdentifier = "Body"; sr.RepresentationType = "SweptSolid"; });
                            ifcShapeRepresentation.Items.Add(ifcExtrudedAreaSolid);

                            //create IfcProductDefinitionShape
                            IfcProductDefinitionShape ifcProductDefinitionShape = Model.Instances.New<IfcProductDefinitionShape>(pds => { pds.Name = row.Name; pds.Description = row.SheetName; });
                            ifcProductDefinitionShape.Representations.Add(ifcShapeRepresentation);

                            //Link to the IfcProduct
                            ifcProduct.Representation = ifcProductDefinitionShape;
                        }
                        else
                        {
#if DEBUG
                            Console.WriteLine("Failed to calculate box size for {0}", row.Name);
#endif
                        }
                    }
                    
                }
                else
                {
#if DEBUG
                    Console.WriteLine("Failed to add Object placement for {0}", row.Name);
#endif
                }

            }
        }
Пример #45
0
 public XbimPoint3D Transform(XbimPoint3D p)
 {
     return(XbimPoint3D.Multiply(p, this));
 }
Пример #46
0
 public static XbimVector3D operator -(XbimPoint3D a, XbimPoint3D b)
 {
     return(XbimPoint3D.Subtract(a, b));
 }
Пример #47
0
 public static XbimVector3D Subtract(XbimPoint3D a, XbimPoint3D b)
 {
     return(new XbimVector3D(a.X - b.X,
                             a.Y - b.Y,
                             a.Z - b.Z));
 }
Пример #48
0
 static XbimPoint3D()
 {
     Zero = new XbimPoint3D(0, 0, 0);
 }
Пример #49
0
        public void ExecuteCamera(object sender, ExecutedRoutedEventArgs e)
        {
            if (SelFile.T == null)
                return;
            var inst = SelFile.T.SelectedItem as BcfInstance;
            if (inst == null)
                return;
            var v = inst.VisualizationInfo;
            if (v == null)
                return;

            var position = new XbimPoint3D();
            var direction = new XbimPoint3D();
            var upDirection = new XbimPoint3D();

            XbimVector3D directionV;
            XbimVector3D upDirectionV;

            if (v.PerspectiveCamera != null)
            {
                var pc = v.PerspectiveCamera;
                position = new XbimPoint3D(pc.CameraViewPoint.X, pc.CameraViewPoint.Y, pc.CameraViewPoint.Z);
                direction = new XbimPoint3D(pc.CameraDirection.X, pc.CameraDirection.Y, pc.CameraDirection.Z);
                upDirection = new XbimPoint3D(pc.CameraUpVector.X, pc.CameraUpVector.Y, pc.CameraUpVector.Z);

                _xpWindow.DrawingControl.Viewport.Orthographic = false;
                var pCam = _xpWindow.DrawingControl.Viewport.Camera as System.Windows.Media.Media3D.PerspectiveCamera;
                if (pCam != null)
                    pCam.FieldOfView = pc.FieldOfView;
            }
            else if (v.OrthogonalCamera != null)
            {
                var pc = v.OrthogonalCamera;
                _xpWindow.DrawingControl.Viewport.Orthographic = true;
                position = new XbimPoint3D(pc.CameraViewPoint.X, pc.CameraViewPoint.Y, pc.CameraViewPoint.Z);
                direction = new XbimPoint3D(pc.CameraDirection.X, pc.CameraDirection.Y, pc.CameraDirection.Z);
                upDirection = new XbimPoint3D(pc.CameraUpVector.X, pc.CameraUpVector.Y, pc.CameraUpVector.Z);

                var pCam = _xpWindow.DrawingControl.Viewport.Camera as OrthographicCamera;
                if (pCam != null)
                    pCam.Width = pc.ViewToWorldScale;
            }
            directionV = new XbimVector3D(direction.X, direction.Y, direction.Z);
            upDirectionV = new XbimVector3D(upDirection.X, upDirection.Y, upDirection.Z);

            var pos = new Point3D(position.X, position.Y, position.Z);
            var dir = new Vector3D(directionV.X, directionV.Y, directionV.Z);
            var upDir = new Vector3D(upDirectionV.X, upDirectionV.Y, upDirectionV.Z);
            _xpWindow.DrawingControl.Viewport.SetView(pos, dir, upDir, 500);

            if (v.ClippingPlanes.Any())
            {
                var curP = v.ClippingPlanes[0];
                _xpWindow.DrawingControl.SetCutPlane(
                    curP.Location.X, curP.Location.Y, curP.Location.Z,
                    curP.Direction.X, curP.Direction.Y, curP.Direction.Z
                    );
            }
            else
            {
                _xpWindow.DrawingControl.ClearCutPlane();
            }

            // xpWindow.DrawingControl.Viewport.FieldOfViewText
        }
Пример #50
0
        private void txtCommand_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Enter &&
                (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
                )
            {
            #if DEBUG
                // stores the commands being launched
                var fname = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "xbimquerying.txt");
                using (StreamWriter writer = File.CreateText(fname))
                {
                    writer.Write(txtCommand.Text);
                    writer.Flush();
                    writer.Close();
                }
            #endif

                e.Handled = true;
                if (bDoClear)
                    txtOut.Document = new FlowDocument();

                string[] CommandArray = txtCommand.Text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                if (txtCommand.SelectedText != string.Empty)
                    CommandArray = txtCommand.SelectedText.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

                foreach (var cmd_f in CommandArray)
                {
                    ReportAdd("> " + cmd_f, Brushes.ForestGreen);
                    var cmd = cmd_f;
                    int i = cmd.IndexOf("//");
                    if (i > 0)
                    {
                        cmd = cmd.Substring(0, i);
                    }
                    if (cmd.TrimStart().StartsWith("//"))
                        continue;

                    // put here all commands that don't require a database open
                    var mdbclosed = Regex.Match(cmd, @"help", RegexOptions.IgnoreCase);
                    if (mdbclosed.Success)
                    {
                        DisplayHelp();
                        continue;
                    }

                    mdbclosed = Regex.Match(cmd, @"xplorer", RegexOptions.IgnoreCase);
                    if (mdbclosed.Success)
                    {
                        if (ParentWindow != null)
                            ParentWindow.Focus();
                        else
                        {
                            // todo: bonghi: open the model in xplorer if needed.
                            XplorerMainWindow xp = new XplorerMainWindow();
                            ParentWindow = xp;
                            xp.Show();
                        }
                        continue;
                    }

                    mdbclosed = Regex.Match(cmd, @"clear *\b(?<mode>(on|off))*", RegexOptions.IgnoreCase);
                    if (mdbclosed.Success)
                    {
                        try
                        {
                            string option = mdbclosed.Groups["mode"].Value;

                            if (option == "")
                            {
                                txtOut.Document = new FlowDocument();
                                continue;
                            }
                            else if (option == "on")
                                bDoClear = true;
                            else if (option == "off")
                                bDoClear = false;
                            else
                            {
                                ReportAdd(string.Format("Autoclear not changed ({0} is not a valid option).", option));
                                continue;
                            }
                            ReportAdd(string.Format("Autoclear set to {0}", option.ToLower()));
                            continue;
                        }
                        catch (Exception)
                        {
                        }
                        txtOut.Document = new FlowDocument();
                        continue;
                    }

                    if (Model == null)
                    {
                        ReportAdd("Plaese open a database.", Brushes.Red);
                        continue;
                    }

                    // all commands here
                    //
                    var m = Regex.Match(cmd, @"^(entitylabel|el) (?<el>\d+)(?<recursion> -*\d+)*", RegexOptions.IgnoreCase);
                    if (m.Success)
                    {
                        int recursion = 0;
                        int v = Convert.ToInt32(m.Groups["el"].Value);
                        try
                        {
                            recursion = Convert.ToInt32(m.Groups["recursion"].Value);
                        }
                        catch (Exception)
                        {
                        }

                        ReportAdd(ReportEntity(v, recursion));
                        continue;
                    }

                    m = Regex.Match(cmd, @"^(Header|he)$", RegexOptions.IgnoreCase);
                    if (m.Success)
                    {
                        if (Model.Header == null)
                        {
                            ReportAdd("Model header is not defined.", Brushes.Red);
                            continue;
                        }
                        ReportAdd("FileDescription:");
                        foreach (var item in Model.Header.FileDescription.Description)
                        {
                            ReportAdd(string.Format("- Description: {0}", item));
                        }
                        ReportAdd(string.Format("- ImplementationLevel: {0}", Model.Header.FileDescription.ImplementationLevel));
                        ReportAdd(string.Format("- EntityCount: {0}", Model.Header.FileDescription.EntityCount));

                        ReportAdd("FileName:");
                        ReportAdd(string.Format("- Name: {0}", Model.Header.FileName.Name));
                        ReportAdd(string.Format("- TimeStamp: {0}", Model.Header.FileName.TimeStamp));
                        foreach (var item in Model.Header.FileName.Organization)
                        {
                            ReportAdd(string.Format("- Organization: {0}", item));
                        }
                        ReportAdd(string.Format("- OriginatingSystem: {0}", Model.Header.FileName.OriginatingSystem));
                        ReportAdd(string.Format("- PreprocessorVersion: {0}", Model.Header.FileName.PreprocessorVersion));
                        foreach (var item in Model.Header.FileName.AuthorName)
                        {
                            ReportAdd(string.Format("- AuthorName: {0}", item));
                        }

                        ReportAdd(string.Format("- AuthorizationName: {0}", Model.Header.FileName.AuthorizationName));
                        foreach (var item in Model.Header.FileName.AuthorizationMailingAddress)
                        {
                            ReportAdd(string.Format("- AuthorizationMailingAddress: {0}", item));
                        }

                        ReportAdd("FileSchema:");
                        foreach (var item in Model.Header.FileSchema.Schemas)
                        {
                            ReportAdd(string.Format("- Schema: {0}", item));
                        }
                        continue;
                    }

                    // SelectionHighlighting [WholeMesh|Normals]
                    m = Regex.Match(cmd, @"^(SelectionHighlighting|sh) (?<mode>(wholemesh|normals))+", RegexOptions.IgnoreCase);
                    if (m.Success)
                    {
                        string mode = m.Groups["mode"].Value.ToLowerInvariant();
                        if (mode == "normals")
                        {
                            ReportAdd("Selection visual style set to 'Normals'");
                            ParentWindow.DrawingControl.SelectionHighlightMode = DrawingControl3D.SelectionHighlightModes.Normals;
                        }
                        else
                        {
                            ReportAdd("Selection visual style set to 'WholeMesh'");
                            ParentWindow.DrawingControl.SelectionHighlightMode = DrawingControl3D.SelectionHighlightModes.WholeMesh;
                        }
                        continue;
                    }

                    m = Regex.Match(cmd, @"^(IfcSchema|is) (?<mode>(list|count|short|full) )*(?<type>.+)", RegexOptions.IgnoreCase);
                    if (m.Success)
                    {
                        string type = m.Groups["type"].Value;
                        string mode = m.Groups["mode"].Value;

                        if (type == "/")
                        {
                        }
                        else if (type == PrepareRegex(type)) // there's not a regex expression, we will prepare one assuming the search for a bare name.
                        {
                            type = @".*\." + type + "$"; // any character repeated then a dot then the name and the end of line
                        }
                        else
                            type = PrepareRegex(type);

                        var TypeList = MatchingTypes(type);

                        if (mode.ToLower() == "list ")
                        {
                            foreach (var item in TypeList)
                                ReportAdd(item);
                        }
                        else if (mode.ToLower() == "count ")
                        {
                            ReportAdd("count: " + TypeList.Count());
                        }
                        else
                        {
                            // report
                            int  BeVerbose = 1;
                            if (mode.ToLower() == "short ")
                                BeVerbose = 0;
                            if (mode.ToLower() == "full ")
                                BeVerbose = 2;
                            foreach (var item in TypeList)
                            {
                                ReportAdd(ReportType(item, BeVerbose));
                            }
                        }
                        continue;
                    }

                    m = Regex.Match(cmd, @"^(reload|re) *(?<entities>([\d,]+|[^ ]+))", RegexOptions.IgnoreCase);
                    if (m.Success)
                    {
                        string start = m.Groups["entities"].Value;
                        IEnumerable<int> labels = tointarray(start, ',');
                        if (labels.Count() > 0)
                        {
                            ParentWindow.DrawingControl.LoadGeometry(Model, labels);
                        }
                        else
                        {
                            ParentWindow.DrawingControl.LoadGeometry(Model);
                        }
                        continue;
                    }

                    m = Regex.Match(cmd, @"^(GeometryInfo|gi) (?<mode>(binary|viewer) )*(?<entities>([\d,]+|[^ ]+))", RegexOptions.IgnoreCase);
                    if (m.Success)
                    {
                        string start = m.Groups["entities"].Value;
                        string mode = m.Groups["mode"].Value;
                        IEnumerable<int> labels = tointarray(start, ',');
                        foreach (var item in labels)
                        {
                            ReportAdd("Geometry for: " + item.ToString(), Brushes.Green);
                            ReportAdd(GeomQuerying.GeomInfoBoundBox(Model, item));
                            ReportAdd(GeomQuerying.GeomLayers(Model, item, ParentWindow.DrawingControl.scenes));
                            if (mode == "binary ")
                            {
                                ReportAdd(GeomQuerying.GeomInfoMesh(Model, item));
                            }
                            if (mode == "viewer ")
                            {
                                ReportAdd(
                                    GeomQuerying.Viewerdata(ParentWindow.DrawingControl, Model, item)
                                    );
                            }
                        }
                        continue;
                    }

                    m = Regex.Match(cmd, @"^(select|se) (?<mode>(count|list|short) )*(?<tt>(transverse|tt) )*(?<hi>(highlight|hi) )*(?<start>([\d,-]+|[^ ]+)) *(?<props>.*)", RegexOptions.IgnoreCase);
                    if (m.Success)
                    {
                        string start = m.Groups["start"].Value;
                        string props = m.Groups["props"].Value;
                        string mode = m.Groups["mode"].Value;

                        // transverse tree mode
                        bool transverseT = false;
                        string transverse = m.Groups["tt"].Value;
                        if (transverse != "")
                            transverseT = true;

                        bool Highlight = false;
                        string HighlightT = m.Groups["hi"].Value;
                        if (HighlightT != "")
                            Highlight = true;

                        IEnumerable<int> labels = tointarray(start, ',');
                        IEnumerable<int> ret = null;
                        if (labels.Count() == 0)
                        {
                            // see if it's a type string instead
                            SquareBracketIndexer sbi = new SquareBracketIndexer(start);
                            labels = QueryEngine.EntititesForType(sbi.Property, Model);
                            labels = sbi.getItem(labels);
                        }
                        ret = QueryEngine.RecursiveQuery(Model, props, labels, transverseT);

                        // textual report
                        if (mode.ToLower() == "count ")
                        {
                            ReportAdd(string.Format("Count: {0}", ret.Count()));
                        }
                        else if (mode.ToLower() == "list ")
                        {
                            foreach (var item in ret)
                            {
                                ReportAdd(item.ToString());
                            }
                        }
                        else
                        {
                            bool BeVerbose = true;
                            if (mode.ToLower() == "short ")
                                BeVerbose = false;
                            foreach (var item in ret)
                            {
                                ReportAdd(ReportEntity(item, 0, Verbose: BeVerbose));
                            }
                        }
                        // visual selection
                        if (Highlight)
                        {
                            EntitySelection s = new EntitySelection();
                            foreach (var item in ret)
                            {
                                s.Add(Model.Instances[item]);
                            }
                            ParentWindow.DrawingControl.Selection = s;
                        }
                        continue;
                    }

                    m = Regex.Match(cmd, @"^zoom (" +
                        @"(?<RegionName>.+$)" +
                        ")", RegexOptions.IgnoreCase);
                    if (m.Success)
                    {
                        string RName = m.Groups["RegionName"].Value;
                        var regionData = Model.GetGeometryData(Xbim.XbimExtensions.XbimGeometryType.Region).FirstOrDefault();
                        if (regionData == null)
                        {
                            ReportAdd("data not found");
                        }
                        XbimRegionCollection regions = XbimRegionCollection.FromArray(regionData.ShapeData);
                        var reg = regions.Where(x => x.Name == RName).FirstOrDefault();
                        if (reg != null)
                        {
                            XbimMatrix3D mcp = XbimMatrix3D.Copy(ParentWindow.DrawingControl.wcsTransform);
                            var bb = reg.Centre;
                            var tC = mcp.Transform(reg.Centre);
                            var tS = mcp.Transform(reg.Size);
                            XbimRect3D r3d = new XbimRect3D(
                                tC.X - tS.X / 2, tC.Y - tS.Y / 2, tC.Z - tS.Z / 2,
                                tS.X, tS.X, tS.Z
                                );
                            ParentWindow.DrawingControl.ZoomTo(r3d);
                            ParentWindow.Activate();
                            continue;
                        }
                        else
                        {
                            ReportAdd(string.Format("Something wrong with region name: '{0}'", RName));
                            ReportAdd("Names that should work are: ");
                            foreach (var str in regions)
                            {
                                ReportAdd(string.Format(" - '{0}'", str.Name));
                            }
                            continue;
                        }
                    }

                    m = Regex.Match(cmd, @"^clip off$", RegexOptions.IgnoreCase);
                    if (m.Success)
                    {
                        ParentWindow.DrawingControl.ClearCutPlane();
                        ReportAdd("Clip removed");
                        ParentWindow.Activate();
                        continue;
                    }

                    m = Regex.Match(cmd, @"^clip (" +
                        @"(?<elev>[-+]?([0-9]*\.)?[0-9]+) *$" +
                        "|" +
                        @"(?<px>[-+]?([0-9]*\.)?[0-9]+) *, *" +
                        @"(?<py>[-+]?([0-9]*\.)?[0-9]+) *, *" +
                        @"(?<pz>[-+]?([0-9]*\.)?[0-9]+) *, *" +
                        @"(?<nx>[-+]?([0-9]*\.)?[0-9]+) *, *" +
                        @"(?<ny>[-+]?([0-9]*\.)?[0-9]+) *, *" +
                        @"(?<nz>[-+]?([0-9]*\.)?[0-9]+)" +
                        "|" +
                        @"(?<StoreyName>.+$)" +
                        ")", RegexOptions.IgnoreCase);
                    if (m.Success)
                    {
                        double px = 0, py = 0, pz = 0;
                        double nx = 0, ny = 0, nz = -1;

                        if (m.Groups["elev"].Value != string.Empty)
                        {
                            pz = Convert.ToDouble(m.Groups["elev"].Value);
                        }
                        else if (m.Groups["StoreyName"].Value != string.Empty)
                        {
                            string msg = "";
                            string storName = m.Groups["StoreyName"].Value;
                            var storey = Model.Instances.OfType<Xbim.Ifc2x3.ProductExtension.IfcBuildingStorey>().Where(x => x.Name == storName).FirstOrDefault();
                            if (storey != null)
                            {
                                //get the object position data (should only be one)
                                Xbim.XbimExtensions.XbimGeometryData geomdata = Model.GetGeometryData(storey.EntityLabel, Xbim.XbimExtensions.XbimGeometryType.TransformOnly).FirstOrDefault();
                                if (geomdata != null)
                                {
                                    Xbim.Common.Geometry.XbimPoint3D pt = new Xbim.Common.Geometry.XbimPoint3D(0, 0, geomdata.Transform.OffsetZ);
                                    Xbim.Common.Geometry.XbimMatrix3D mcp = Xbim.Common.Geometry.XbimMatrix3D.Copy(ParentWindow.DrawingControl.wcsTransform);
                                    var transformed = mcp.Transform(pt);
                                    msg = string.Format("Clip 1m above storey elevation {0} (height: {1})", pt.Z, transformed.Z + 1);
                                    pz = transformed.Z + 1;
                                }
                            }
                            if (msg == "")
                            {
                                ReportAdd(string.Format("Something wrong with storey name: '{0}'", storName));
                                ReportAdd("Names that should work are: ");
                                var strs = Model.Instances.OfType<Xbim.Ifc2x3.ProductExtension.IfcBuildingStorey>();
                                foreach (var str in strs)
                                {
                                    ReportAdd(string.Format(" - '{0}'", str.Name));
                                }
                                continue;
                            }
                            ReportAdd(msg);
                        }
                        else
                        {
                            px = Convert.ToDouble(m.Groups["px"].Value);
                            py = Convert.ToDouble(m.Groups["py"].Value);
                            pz = Convert.ToDouble(m.Groups["pz"].Value);
                            nx = Convert.ToDouble(m.Groups["nx"].Value);
                            ny = Convert.ToDouble(m.Groups["ny"].Value);
                            nz = Convert.ToDouble(m.Groups["nz"].Value);
                        }

                        ParentWindow.DrawingControl.ClearCutPlane();
                        ParentWindow.DrawingControl.SetCutPlane(
                            px, py, pz,
                            nx, ny, nz
                            );

                        ReportAdd("Clip command sent");
                        ParentWindow.Activate();
                        continue;
                    }

                    m = Regex.Match(cmd, @"^Styler (?<command>.+)", RegexOptions.IgnoreCase);
                    if (m.Success)
                    {
                        var st = ParentWindow.DrawingControl.LayerStyler as Xbim.Presentation.LayerStyling.LayerStylerTypeAndIFCStyleExtended;
                        if (st != null)
                        {
                            string command = m.Groups["command"].Value;
                            ReportAdd(
                                st.SendCommand(command, ParentWindow.DrawingControl.Selection)
                                );
                            ParentWindow.DrawingControl.ReloadModel();
                        }
                        else
                        {
                            ReportAdd("Command not valid under current styler configuration.");
                        }
                        continue;
                    }

                    m = Regex.Match(cmd, @"^Visual (?<action>list|tree|on|off|mode)( (?<Name>[^ ]+))*", RegexOptions.IgnoreCase);
                    if (m.Success)
                    {
                        string Name = m.Groups["Name"].Value;
                        if (m.Groups["action"].Value.ToLowerInvariant() == "list")
                        {
                            foreach (var item in ParentWindow.DrawingControl.ListItems(Name))
                            {
                                ReportAdd(item);
                            }
                        }
                        else if (m.Groups["action"].Value.ToLowerInvariant() == "tree")
                        {
                            foreach (var item in ParentWindow.DrawingControl.LayersTree())
                            {
                                ReportAdd(item);
                            }
                        }
                        else if (m.Groups["action"].Value.ToLowerInvariant() == "mode")
                        {
                            string t = Name.ToLowerInvariant();
                            if (t == "type")
                            {
                                ReportAdd("Visual mode set to EntityType.");
                                ParentWindow.DrawingControl.LayerStyler = new Xbim.Presentation.LayerStyling.LayerStylerTypeAndIFCStyle();
                                ParentWindow.DrawingControl.ReloadModel(Options: DrawingControl3D.ModelRefreshOptions.ViewPreserveAll);
                            }
                            else if (t == "entity")
                            {
                                ReportAdd("Visual mode set to EntityLabel.");
                                ParentWindow.DrawingControl.LayerStyler = new Xbim.Presentation.LayerStyling.LayerStylerPerEntity();
                                ParentWindow.DrawingControl.ReloadModel(Options: DrawingControl3D.ModelRefreshOptions.ViewPreserveAll);
                            }
                            else if (t == "oddeven")
                            {
                                ReportAdd("Visual mode set to Odd/Even.");
                                ParentWindow.DrawingControl.LayerStyler = new Xbim.Presentation.LayerStyling.LayerStylerEvenOdd();
                                ParentWindow.DrawingControl.ReloadModel(Options: DrawingControl3D.ModelRefreshOptions.ViewPreserveAll);
                            }
                            else if (t == "demo")
                            {
                                ReportAdd("Visual mode set to Demo.");
                                ParentWindow.DrawingControl.LayerStyler = new Xbim.Presentation.LayerStyling.LayerStylerTypeAndIFCStyleExtended();
                                ParentWindow.DrawingControl.ReloadModel(Options: DrawingControl3D.ModelRefreshOptions.ViewPreserveAll);
                            }
                            else
                                ReportAdd(string.Format("mode not understood: {0}.", t));
                        }
                        else
                        {
                            bool bVis = false;
                            if (m.Groups["action"].Value.ToLowerInvariant() == "on")
                                bVis = true;
                            ParentWindow.DrawingControl.SetVisibility(Name, bVis);
                        }
                        continue;
                        }
                    m = Regex.Match(cmd, @"^SimplifyGUI$", RegexOptions.IgnoreCase);
                    if (m.Success)
                    {
                        XbimXplorer.Simplify.IfcSimplify s = new Simplify.IfcSimplify();
                        s.Show();
                        continue;
                    }

                    m = Regex.Match(cmd, @"^test$", RegexOptions.IgnoreCase);
                    if (m.Success)
                    {
                        int iPass = -728;
                        ReportAdd(RunTestCode(iPass));
                        continue;
                    }
                    ReportAdd(string.Format("Command not understood: {0}.", cmd));
                }
            }
        }
Пример #51
0
 /// <summary>
 /// Returns the normal of the triangle that contains the specified edge
 /// </summary>
 /// <param name="edge"></param>
 /// <returns></returns>
 public XbimVector3D TriangleNormal(XbimTriangleEdge edge)
 {
     var p1 = _vertices[edge.StartVertexIndex].Position;
     var p2 = _vertices[edge.NextEdge.StartVertexIndex].Position;
     var p3 = _vertices[edge.NextEdge.NextEdge.StartVertexIndex].Position;
     var a = new XbimPoint3D(p1.X,p1.Y,p1.Z);
     var b = new XbimPoint3D(p2.X,p2.Y,p2.Z);
     var c = new XbimPoint3D(p3.X,p3.Y,p3.Z);
     var cv = XbimVector3D.CrossProduct(b - a, c - a );
     cv.Normalize();
     return cv;
 }
Пример #52
0
 public static XbimPoint3D operator +(XbimPoint3D p, XbimVector3D v)
 {
     return(XbimPoint3D.Add(p, v));
 }