Example #1
0
        public void getOrientation()
        {
            Document doc         = this.ActiveUIDocument.Document;
            View     currentView = this.ActiveUIDocument.ActiveView;

            View3D            v3D     = (currentView as View3D);
            ViewOrientation3D vOrient = v3D.GetOrientation();

            XYZ eye     = vOrient.EyePosition;
            XYZ forward = vOrient.ForwardDirection;
            XYZ up      = vOrient.UpDirection;

            String eyex = (eye.X).ToString();
            String eyey = (eye.Y).ToString();
            String eyez = (eye.Z).ToString();

            String eyeXYZ = "eye orientation is \nX: " + eyex + "\nY: " + eyey + "\nZ: " + eyez;

            String forwardx = (forward.X).ToString();
            String forwardy = (forward.Y).ToString();
            String forwardz = (forward.Z).ToString();

            String forwardXYZ = "forward orientation is\nX: " + forwardx + "\nY: " + forwardy + "\nZ: " + forwardz;

            String upx = (up.X).ToString();
            String upy = (up.Y).ToString();
            String upz = (up.Z).ToString();

            String upXYZ = "up orientation is \nX: " + upx + "\nY: " + upy + "\nZ: " + upz;

            TaskDialog.Show("View Orientation", eyeXYZ + "\n" + forwardXYZ + "\n" + upXYZ);
        }
        /// <summary>
        /// Return relevant 3D view information (from
        /// Revit API documentation help file  sample).
        /// </summary>
        static string GetView3dInfo(View3D view3d)
        {
            string message = "3D View: ";

            // The position of the camera and view direction.

            ViewOrientation3D ori = view3d.GetOrientation();
            XYZ peye     = ori.EyePosition;
            XYZ vforward = ori.ForwardDirection;
            XYZ vup      = ori.UpDirection;

            message += string.Format(
                "\r\nCamera position: {0}"
                + "\r\nView direction: {1}"
                + "\r\nUp direction: {2}",
                Util.PointString(peye),
                Util.PointString(vforward),
                Util.PointString(vup));

            // Identifies whether the view is a perspective view.

            if (view3d.IsPerspective)
            {
                message += "\r\nThe view is a perspective view.";
            }

            // The section box of the 3D view can cut the model.

            if (view3d.IsSectionBoxActive)
            {
                BoundingBoxXYZ sectionBox = view3d.GetSectionBox();

                // Note that the section box can be rotated
                // and transformed. So the min/max corners
                // coordinates relative to the model must be
                // computed via the transform.

                Transform trf = sectionBox.Transform;

                XYZ max = sectionBox.Max; // Maximum coordinates (upper-right-front corner of the box before transform is applied).
                XYZ min = sectionBox.Min; // Minimum coordinates (lower-left-rear corner of the box before transform is applied).

                // Transform the min and max to model coordinates

                XYZ maxInModelCoords = trf.OfPoint(max);
                XYZ minInModelCoords = trf.OfPoint(min);

                message += "\r\nView has an active section box: ";

                message += "\r\n'Maximum' coordinates: "
                           + Util.PointString(maxInModelCoords);

                message += "\r\n'Minimum' coordinates: "
                           + Util.PointString(minInModelCoords);
            }
            return(message);
        }
 private static void CreatePerspectiveFrom3D(UIDocument uiDoc, View3D view3D)
 {
     var viewOrientation3D = view3D.GetOrientation();
     var centerOfScreen = UserView.GetMiddleOfActiveViewWindow(UserView.ActiveUIView(uiDoc, view3D));
     var view = View3D.CreatePerspective(uiDoc.Document,
         UserView.Get3DViewFamilyTypes(uiDoc.Document).First().Id);
     view.SetOrientation(new ViewOrientation3D(
         new XYZ(centerOfScreen.X, centerOfScreen.Y, viewOrientation3D.EyePosition.Z),
         viewOrientation3D.UpDirection, viewOrientation3D.ForwardDirection));
     view.Dispose();
     viewOrientation3D.Dispose();
 }
Example #4
0
        public static List <LocalGrid> GetLocalGrids(List <Grid> revitGrids, View3D view3D, List <XYZ> conners, Rectangle viewRect)
        {
            var retDatas  = new List <LocalGrid>();
            var transform = Autodesk.Revit.DB.Transform.Identity;

            transform.BasisX = view3D.RightDirection;
            var ori = view3D.GetOrientation();

            transform.BasisZ = ori.ForwardDirection;
            transform.BasisY = ori.ForwardDirection.CrossProduct(view3D.RightDirection);

            var newLocation = new System.Drawing.PointF(viewRect.Left, viewRect.Top);
            var width       = (viewRect.Right - viewRect.Left) * 1.0;
            var height      = (viewRect.Bottom - viewRect.Top) * 1.0;

            var yLine       = Line.CreateUnbound(conners[0], transform.BasisY);
            var xLine       = Line.CreateUnbound(conners[0], transform.BasisX);
            var revitWidth  = yLine.Distance(conners[1]);
            var revitHeight = xLine.Distance(conners[1]);

            var revitConner0 = conners[0];
            var revitConner1 = revitConner0 + transform.BasisX * revitWidth;
            var revitConner2 = conners[1];
            var revitConner3 = revitConner0 - transform.BasisY * revitHeight;

            transform.Origin = revitConner3;

            var leftBottom  = ProjectToPlane(transform, revitConner0);
            var rightBottom = ProjectToPlane(transform, revitConner1);
            var rightTop    = ProjectToPlane(transform, revitConner2);
            var leftTop     = ProjectToPlane(transform, revitConner3);

            var xRatio = width / (leftTop.DistanceTo(rightTop));
            var yRatio = height / (leftTop.DistanceTo(leftBottom));

            foreach (var grid in revitGrids)
            {
                var curve = grid.Curve;
                if (curve != null)
                {
                    var localPoints = curve
                                      .Tessellate()
                                      .Select(a => ProjectToPlane(transform, a))
                                      .Select(a => a - leftTop)
                                      .Select(a => new System.Drawing.PointF((float)(a.X * xRatio), (float)(a.Y * yRatio)))
                                      .ToList();
                    retDatas.Add(new LocalGrid(grid.Name, localPoints));
                }
            }
            return(retDatas);
        }
Example #5
0
        public CameraViewInfo(View3D view3d)
        {
            ViewId   = view3d.Id.IntegerValue;
            ViewName = view3d.Name;

            ViewTemplateId = view3d.ViewTemplateId;

            Orientation    = view3d.GetOrientation();
            IsCropBoxOn    = view3d.CropBoxActive;
            CropBox        = view3d.CropBox;
            IsSectionBoxOn = view3d.IsSectionBoxActive;
            SectionBox     = view3d.GetSectionBox();

            Display = view3d.DisplayStyle;
            GetParameters(view3d.Parameters);
        }
        ////[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
        private static void CreatePerspectiveFrom3D(UIDocument udoc, View3D view)
        {
            var v = view.GetOrientation();

            using (var t = new Transaction(udoc.Document))
            {
                if (t.Start("Create perspective view") == TransactionStatus.Started)
                {
                    var centreOfScreen = GetMiddleOfActiveViewWindow(ActiveUIView(udoc, view));
                    var np             = View3D.CreatePerspective(udoc.Document, Get3DViewFamilyTypes(udoc.Document).First().Id);
                    np.SetOrientation(new ViewOrientation3D(new XYZ(centreOfScreen.X, centreOfScreen.Y, v.EyePosition.Z), v.UpDirection, v.ForwardDirection));
                    t.Commit();
                    np.Dispose();
                }
            }
            v.Dispose();
        }
Example #7
0
        private OrthogonalCamera GetOrthogonalCamera(Dictionary <int, ElementProperties> elementDictionary, string imagePath)
        {
            OrthogonalCamera orthoCamera = new OrthogonalCamera();

            try
            {
                BoundingBoxXYZ boundingBox = new BoundingBoxXYZ();
                boundingBox.Enabled = true;
                for (int i = 0; i < 3; i++)
                {
                    boundingBox.set_MinEnabled(i, true);
                    boundingBox.set_MaxEnabled(i, true);
                    boundingBox.set_BoundEnabled(0, i, true);
                    boundingBox.set_BoundEnabled(1, i, true);
                }

                BoundingBoxXYZ tempBoundingBox = elementDictionary.First().Value.RevitElement.get_BoundingBox(null);
                tempBoundingBox.Enabled = true;

                double maxX = tempBoundingBox.Max.X;
                double maxY = tempBoundingBox.Max.Y;
                double maxZ = tempBoundingBox.Max.Z;
                double minX = tempBoundingBox.Min.X;
                double minY = tempBoundingBox.Min.Y;
                double minZ = tempBoundingBox.Min.Z;

                List <ElementId>           elementIds = new List <ElementId>();
                Dictionary <int, Category> categories = new Dictionary <int, Category>();
                foreach (ElementProperties ep in elementDictionary.Values)
                {
                    Element element = ep.RevitElement;
                    if (null != element)
                    {
                        try
                        {
                            if (!categories.ContainsKey(element.Category.Id.IntegerValue))
                            {
                                categories.Add(element.Category.Id.IntegerValue, element.Category);
                            }
                            BoundingBoxXYZ bbBox = element.get_BoundingBox(null);
                            bbBox.Enabled = true;
                            elementIds.Add(element.Id);
                            if (null != boundingBox)
                            {
                                if (bbBox.Max.X > maxX)
                                {
                                    maxX = bbBox.Max.X;
                                }
                                if (bbBox.Max.Y > maxY)
                                {
                                    maxY = bbBox.Max.Y;
                                }
                                if (bbBox.Max.Z > maxZ)
                                {
                                    maxZ = bbBox.Max.Z;
                                }
                                if (bbBox.Min.X < minX)
                                {
                                    minX = bbBox.Min.X;
                                }
                                if (bbBox.Min.Y < minY)
                                {
                                    minY = bbBox.Min.Y;
                                }
                                if (bbBox.Min.Z < minZ)
                                {
                                    minZ = bbBox.Min.Z;
                                }
                            }
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }

                XYZ xyzMax = new XYZ(maxX, maxY, maxZ);
                XYZ xyzMin = new XYZ(minX, minY, minZ);

                boundingBox.set_Bounds(0, xyzMin);
                boundingBox.set_Bounds(1, xyzMax);


                ViewFamilyType           view3dFamilyType = null;
                FilteredElementCollector collector        = new FilteredElementCollector(m_doc);
                List <Element>           elements         = collector.OfClass(typeof(ViewFamilyType)).ToElements().ToList();
                foreach (Element element in elements)
                {
                    ViewFamilyType viewfamilytype = element as ViewFamilyType;
                    if (viewfamilytype.ViewFamily == ViewFamily.ThreeDimensional)
                    {
                        view3dFamilyType = viewfamilytype; break;
                    }
                }

                if (null != view3dFamilyType)
                {
                    using (TransactionGroup transGroup = new TransactionGroup(m_doc))
                    {
                        transGroup.Start("Start Creating View 3D");
                        using (Transaction trans = new Transaction(m_doc))
                        {
                            trans.Start("Create View");

                            View3D view3d = View3D.CreateIsometric(m_doc, view3dFamilyType.Id);
                            view3d.SetSectionBox(boundingBox);
                            view3d.GetSectionBox().Enabled = true;
                            view3d.DetailLevel = ViewDetailLevel.Fine;

                            foreach (Category category in categories.Values)
                            {
                                if (category.get_AllowsVisibilityControl(view3d))
                                {
#if RELEASE2017 || RELEASE2018
                                    view3d.SetCategoryHidden(category.Id, false);
#else
                                    view3d.SetVisibility(category, true);
#endif
                                }
                            }

                            view3d.get_Parameter(BuiltInParameter.MODEL_GRAPHICS_STYLE).Set(4);

                            //m_app.ActiveUIDocument.ActiveView = view3d;
                            //m_app.ActiveUIDocument.RefreshActiveView();

                            XYZ   eyePostion = view3d.GetOrientation().EyePosition;
                            Point viewPoint  = new Point();
                            viewPoint.X = eyePostion.X; viewPoint.Y = eyePostion.Y; viewPoint.Z = eyePostion.Z;
                            orthoCamera.CameraViewPoint = viewPoint;

                            XYZ       forwardDirection = view3d.GetOrientation().ForwardDirection;
                            Direction fDirection       = new Direction();
                            fDirection.X = forwardDirection.X; fDirection.Y = forwardDirection.Y; fDirection.Z = forwardDirection.Z;
                            orthoCamera.CameraDirection = fDirection;

                            XYZ       upDirection = view3d.GetOrientation().UpDirection;
                            Direction uDirection  = new Direction();
                            uDirection.X = upDirection.X; uDirection.Y = upDirection.Y; uDirection.Z = upDirection.Z;
                            orthoCamera.CameraUpVector = uDirection;

                            orthoCamera.ViewToWorldScale = view3d.Scale;
                            m_app.ActiveUIDocument.RefreshActiveView();
                            trans.Commit();

                            trans.Start("Export Image");
                            //create snapshot.png
                            ImageExportOptions option = new ImageExportOptions();
                            option.HLRandWFViewsFileType = ImageFileType.PNG;
                            option.ImageResolution       = ImageResolution.DPI_300;
                            option.ShouldCreateWebSite   = false;
                            option.ExportRange           = ExportRange.SetOfViews;
                            option.FilePath = imagePath;
                            List <ElementId> viewIds = new List <ElementId>();
                            viewIds.Add(view3d.Id);
                            option.SetViewsAndSheets(viewIds);

                            if (ImageExportOptions.IsValidFileName(option.FilePath))
                            {
                                m_doc.ExportImage(option);
                            }
                            trans.Commit();
                        }
                        transGroup.RollBack();
                    }

                    if (File.Exists(imagePath))
                    {
                        File.Delete(imagePath);
                    }
                    string[] fileNames = Directory.GetFiles(Path.GetDirectoryName(imagePath), "snapshot*");
                    foreach (string fName in fileNames)
                    {
                        if (Path.GetExtension(fName) == ".png" || Path.GetExtension(fName) == ".jpg")
                        {
                            File.Move(fName, imagePath);
                            if (File.Exists(fName))
                            {
                                File.Delete(fName);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to get the orthogonal camera.\n" + ex.Message, "Get Orthogonal Camera", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(orthoCamera);
        }
Example #8
0
        private void AddCameraActor(
            View3D InView3D,
            CameraInfo InViewCamera
            )
        {
            // Create a new Datasmith camera actor.
            // Hash the Datasmith camera actor name to shorten it.
            string HashedName = FDatasmithFacadeElement.GetStringHash(InView3D.UniqueId);
            FDatasmithFacadeActorCamera CameraActor = new FDatasmithFacadeActorCamera(HashedName);

            CameraActor.SetLabel(InView3D.Name);

            if (InView3D.Category != null)
            {
                // Set the Datasmith camera actor layer to be the 3D view category name.
                CameraActor.SetLayer(InView3D.Category.Name);
            }

            // Gets the current non-saved orientation of the 3D view.
            ViewOrientation3D ViewOrientation = InView3D.GetOrientation();

            // Set the world position (in right-handed Z-up coordinates) of the Datasmith camera actor.
            XYZ CameraPosition = ViewOrientation.EyePosition;

            CameraActor.SetCameraPosition((float)CameraPosition.X, (float)CameraPosition.Y, (float)CameraPosition.Z);

            // Set the world rotation of the Datasmith camera actor with
            // the camera world forward and up vectors (in right-handed Z-up coordinates).
            XYZ CameraForward = ViewOrientation.ForwardDirection;
            XYZ CameraUp      = ViewOrientation.UpDirection;

            CameraActor.SetCameraRotation((float)CameraForward.X, (float)CameraForward.Y, (float)CameraForward.Z, (float)CameraUp.X, (float)CameraUp.Y, (float)CameraUp.Z);

            // When the 3D view camera is not available, an orthographic view should be assumed.
            if (InViewCamera != null)
            {
                // Compute the aspect ratio (width/height) of the Revit 3D view camera, where
                // HorizontalExtent is the distance between left and right planes on the target plane,
                // VerticalExtent is the distance between top and bottom planes on the target plane.
                float AspectRatio = (float)(InViewCamera.HorizontalExtent / InViewCamera.VerticalExtent);

                // Set the aspect ratio of the Datasmith camera.
                CameraActor.SetAspectRatio(AspectRatio);

                if (InView3D.IsPerspective)
                {
                    // Set the sensor width of the Datasmith camera.
                    CameraActor.SetSensorWidth((float)(InViewCamera.HorizontalExtent * /* millimeters per foot */ 304.8));

                    // Get the distance from eye point along view direction to target plane.
                    // This value is appropriate for perspective views only.
                    float TargetDistance = (float)InViewCamera.TargetDistance;

                    // Set the Datasmith camera focus distance.
                    CameraActor.SetFocusDistance(TargetDistance);

                    // Set the Datasmith camera focal length.
                    CameraActor.SetFocalLength(TargetDistance * /* millimeters per foot */ 304.8F);
                }
            }

            // Add the camera actor to the Datasmith scene.
            DatasmithScene.AddActor(CameraActor);

            DirectLink?.MarkForExport(InView3D);
            DirectLink?.CacheElement(RevitDocument, InView3D, new FDocumentData.FBaseElementData(CameraActor, null, DocumentDataStack.Peek()));
        }