Beispiel #1
0
        private VisualizationInfo ReadVisualizationInfo(string filePath, out bool isReadable)
        {
            VisualizationInfo visInfo = new VisualizationInfo();

            isReadable = false;
            try
            {
                if (File.Exists(filePath))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(VisualizationInfo));
                    FileStream    fs         = new FileStream(filePath, FileMode.Open);
                    XmlReader     reader     = XmlReader.Create(fs);
                    if (serializer.CanDeserialize(reader))
                    {
                        visInfo    = (VisualizationInfo)serializer.Deserialize(reader);
                        isReadable = true;
                    }
                    reader.Close();
                    fs.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to read markup.\n" + ex.Message, "ReadMarkup", MessageBoxButton.OK, MessageBoxImage.Warning);
                isReadable = false;
                return(null);
            }
            return(visInfo);
        }
        public override Tuple <string, string> getSnapshotAndViewpoint(int elemCheck)
        {
            if (false)
            {
                MessageBox.Show("I'm sorry,\nonly 3D and 2D views are supported.", "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
                return(null);
            }

            string tempPath    = Path.Combine(Path.GetTempPath(), "BCFtemp", Path.GetRandomFileName());
            string issueFolder = Path.Combine(tempPath, Guid.NewGuid().ToString());

            if (!Directory.Exists(issueFolder))
            {
                Directory.CreateDirectory(issueFolder);
            }

            Guid   viewpointGuid     = Guid.NewGuid();
            string snapshotFilePath  = Path.Combine(issueFolder, string.Format("{0}.png", viewpointGuid.ToString()));
            string viewpointFilePath = Path.Combine(issueFolder, string.Format("{0}.bcfv", viewpointGuid.ToString()));

            // save snapshot

            // save viewpoint
            VisualizationInfo vi          = window.generateViewpoint(elemCheck);
            XmlSerializer     serializerV = new XmlSerializer(typeof(VisualizationInfo));
            Stream            writerV     = new FileStream(viewpointFilePath, FileMode.Create);

            serializerV.Serialize(writerV, vi);
            writerV.Close();

            return(new Tuple <string, string>(snapshotFilePath, viewpointFilePath));
        }
Beispiel #3
0
        /// <summary>
        /// Open a 3D View
        /// </summary>
        /// <param name="v"></param>
        private void doOpen3DView(VisualizationInfo v)
        {
            try
            {
                UIDocument uidoc = uiapp.ActiveUIDocument;
                Document   doc   = uidoc.Document;

                if (uidoc.ActiveView.ViewType == ViewType.ThreeD)
                {
                    View3D view3D = (View3D)uidoc.ActiveView;
                    if (view3D.IsPerspective) //ORTHO
                    {
                        MessageBox.Show("This operation is not allowed in a Perspective View.\nPlease close the current window(s) and retry.",
                                        "Warning!", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                }
                m_Handler.v = v;

                //var touple = GetViewCoordinates(doc, v);
                //if (touple == null)
                //{
                //    MessageBox.Show("Viewpoint not formatted correctly.", "Viewpoint Error", MessageBoxButton.OK, MessageBoxImage.Error);
                //    return;
                //}

                //m_Handler.touple = touple;

                m_ExEvent.Raise();
            }
            catch (System.Exception ex1)
            {
                TaskDialog.Show("Error!", "exception: " + ex1);
            }
        }
        /// <summary>
        /// Open a 3D View
        /// </summary>
        /// <param name="v"></param>
        private void doOpen3DView(VisualizationInfo v)
        {
            try
            {
                UIDocument uidoc = uiapp.ActiveUIDocument;
                Document   doc   = uidoc.Document;

                if (uidoc.ActiveView.ViewType == ViewType.ThreeD)
                {
                    View3D view3D = (View3D)uidoc.ActiveView;
                    if (view3D.IsPerspective) //ORTHO
                    {
                        MessageBox.Show("This operation is not allowed in a Perspective View.\nPlease close the current window(s) and retry.",
                                        "Warning!", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                }
                m_Handler.v = v;

                m_ExEvent.Raise();
            }
            catch (System.Exception ex1)
            {
                TaskDialog.Show("Error!", "exception: " + ex1);
            }
        }
Beispiel #5
0
        public VisualizationInfo GetVisInfo(Dictionary <int, ElementProperties> elementDictionary, string imagePath)
        {
            VisualizationInfo visInfo = new VisualizationInfo();

            try
            {
                visInfo.Components = new Component[elementDictionary.Count];

                int i = 0;
                foreach (ElementProperties ep in elementDictionary.Values)
                {
                    Component component = new Component();
                    component.IfcGuid           = ep.IfcGuid;
                    component.Selected          = true;
                    component.Visible           = true;
                    component.Color             = ep.Definition.Color;
                    component.OriginatingSystem = m_app.Application.VersionName;
                    component.AuthoringToolId   = ep.ElementId.ToString();

                    visInfo.Components[i] = component;
                    i++;
                }

                visInfo.OrthogonalCamera = GetOrthogonalCamera(elementDictionary, imagePath);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to get the visualization information.\n" + ex.Message, "Get Visualization Information", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return(visInfo);
        }
Beispiel #6
0
        private void SetVisualizateInfo(OptionsVisualizate info)
        {
            var size     = VisualizationInfo.ReadSize(info.Size);
            var coloring = WordsColoringAssosiation.GetColoring(SkipSpaces(info.Coloring)) ??
                           WordsColoringAssosiation.GetColoring("random");

            vizInfo = new VisualizationInfo(coloring, size, SkipSpaces(info.Font));
        }
Beispiel #7
0
        private void WaitForConnectionCallBack(IAsyncResult iar)
        {
            try
            {
                // Get the pipe
                NamedPipeServerStream pipeServer = (NamedPipeServerStream)iar.AsyncState;
                // End waiting for the connection
                pipeServer.EndWaitForConnection(iar);

                byte[] buffer = new byte[1024];

                // Read the incoming message
                pipeServer.Read(buffer, 0, 1024);

                // Convert byte buffer to string
                string jsonRequestMsg = Encoding.UTF8.GetString(buffer, 0, buffer.Length);

                IpcOperationType type = IpcMessageStore.getIpcOperationType(jsonRequestMsg);

                string jsonResponseMsg = null;
                if (type == IpcOperationType.AddIssueRequest)
                {
                    AddIssueResponse response = handleAddIssueRequest();
                    jsonResponseMsg = IpcMessageStore.savePayload(IpcOperationType.AddIssueResponse, response);
                }
                else if (type == IpcOperationType.OpenViewpointRequest)
                {
                    VisualizationInfo visInfo = IpcMessageStore.getPayload <VisualizationInfo>(jsonRequestMsg);
                    jsonResponseMsg = "{}";
                    doOpen3DView(visInfo);
                }
                else if (type == IpcOperationType.SelectElementsRequest)
                {
                    List <Component> components = IpcMessageStore.getPayload <List <Component> >(jsonRequestMsg);
                    jsonResponseMsg = "{}";
                    selectElements(components, true);
                }

                // Send response
                byte[] _buffer = Encoding.UTF8.GetBytes(jsonResponseMsg);
                pipeServer.Write(_buffer, 0, _buffer.Length);
                pipeServer.Flush();

                // Kill original sever and create new wait server
                pipeServer.Close();
                pipeServer = null;
                pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);

                // Recursively wait for the connection again and again....
                pipeServer.BeginWaitForConnection(new AsyncCallback(WaitForConnectionCallBack), pipeServer);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
 public BcfInstance NewInstance(string instanceName, BitmapImage img, VisualizationInfo vi)
 {
     BcfInstance i = new BcfInstance();
     i.Markup.Topic.Title = instanceName;
     if (img != null)
         i.SnapShot = img;
     if (vi != null)
         i.VisualizationInfo = vi;
     _vm.File.Instances.Add(i);
     return i;
 }
 /// <summary>
 /// Open 3D View - BCF
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void Open3dViewBCF(object sender, EventArgs e)
 {
     try
     {
         VisualizationInfo v = mainPan.jira.Bcf.Issues[mainPan.bcfPan.listIndex].viewpoint;
         doOpen3DView(v);
     }
     catch (System.Exception ex1)
     {
         MessageBox.Show("exception: " + ex1);
     }
 }
Beispiel #10
0
        private void SetViewPoint(string imageFile)
        {
            try
            {
                var count = 5;
                while (!File.Exists(imageFile))
                {
                    count--;
                    if (count < 0)
                    {
                        break;
                    }
                    Thread.Sleep(100);
                }

                if (!File.Exists(imageFile))
                {
                    return;
                }

                var vp = new ViewPoint();
                vp.Guid          = Guid.NewGuid().ToString();
                vp.TopicGuid     = ViewPointViewModel.SelectedMarkup.Topic.Guid;
                vp.Snapshot      = Path.GetFileName(imageFile);
                vp.SnapshotImage = ImageUtil.GetImageArray(imageFile);

                var visInfo = new VisualizationInfo();
                visInfo.ViewPointGuid = vp.Guid;
                //update components
                visInfo.Components = GetElements(vp.Guid);

                //update camera
                var currentView = ActiveDoc.ActiveView as View3D;
                if (null != currentView)
                {
                    if (currentView.IsPerspective)
                    {
                        visInfo.PerspectiveCamera = GetPerspectiveCamera(currentView, vp.Guid);
                    }
                    else
                    {
                        visInfo.OrthogonalCamera = GetOrthogonalCamera(currentView, vp.Guid);
                    }
                }

                vp.VisInfo = visInfo;
                ViewPointViewModel.UserViewPoint = vp;
            }
            catch (Exception)
            {
                // ignored
            }
        }
Beispiel #11
0
 /// <summary>
 /// Open 3D View - BCF
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void Open3dViewBCF(object sender, EventArgs e)
 {
     try
     {
         VisualizationInfo VisInfo = (VisualizationInfo)((Button)sender).Tag;
         doOpen3DView(VisInfo);
     }
     catch (System.Exception ex1)
     {
         MessageBox.Show("exception: " + ex1);
     }
 }
Beispiel #12
0
        private void VisualizationsCmbBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            int selIndex = VisualizationsCmbBox.SelectedIndex;

            if (VisualizationsCmbBox.Items.Count <= 1 || selIndex < 0)
            {
                return;
            }

            if (IVizMgr == null)
            {
                return;
            }

            VizPluginInfo = (VisualizationInfo)VisualizationsCmbBox.SelectedItem;

            if (VizPluginInfo == null || VizPluginInfo.IsDummyPlugin)
            {
                return;
            }

            VizPresetsCmbBox.Items.Clear();

            if (VizPluginInfo.VisualizationType == VisualizationInfo.PluginType.Winamp)
            {
                groupBoxWinampVis.Visible  = true;
                groupBoxSoniqueVis.Visible = false;
            }
            else if (VizPluginInfo.VisualizationType == VisualizationInfo.PluginType.Sonique)
            {
                groupBoxWinampVis.Visible  = false;
                groupBoxSoniqueVis.Visible = true;
                groupBoxSoniqueVis.Show();
            }
            else
            {
                groupBoxWinampVis.Visible  = false;
                groupBoxSoniqueVis.Visible = false;
            }

            if (VizPluginInfo.HasPresets)
            {
                VizPresetsCmbBox.Items.AddRange(VizPluginInfo.PresetNames.ToArray());
                VizPresetsCmbBox.SelectedIndex = VizPluginInfo.PresetIndex;
                VizPresetsCmbBox.Enabled       = VizPresetsCmbBox.Items.Count > 1;
            }
            else
            {
                VizPresetsCmbBox.Enabled = false;
            }
        }
Beispiel #13
0
        private AddIssueResponse handleAddIssueRequest()
        {
            // generate BCF viewpoint first to retain selected elements
            VisualizationInfo visInfo = generateViewpoint();

            return(new AddIssueResponse()
            {
                isValidRequest = MSApp.ActiveModelReference.Type == MsdModelType.Normal,
                documentGuid = MSApp.ActiveDesignFile.GetHashCode().ToString(),
                documentName = MSApp.ActiveDesignFile.Name,
                tempSnapshotPath = generateSnapshot(),
                visualizationInfo = visInfo
            });
        }
 /// <summary>
 /// Open 3D View - Jira
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void Open3dViewJira(object sender, EventArgs e)
 {
     try
     {
         VisualizationInfo v = mainPan.getVisInfo();
         if (null != v)
         {
             doOpen3DView(v);
         }
     }
     catch (System.Exception ex1)
     {
         MessageBox.Show("exception: " + ex1);
     }
 }
Beispiel #15
0
        public BcfInstance NewInstance(string instanceName, BitmapImage img, VisualizationInfo vi)
        {
            BcfInstance i = new BcfInstance();

            i.Markup.Topic.Title = instanceName;
            if (img != null)
            {
                i.SnapShot = img;
            }
            if (vi != null)
            {
                i.VisualizationInfo = vi;
            }
            _vm.File.Instances.Add(i);
            return(i);
        }
Beispiel #16
0
        private static ViewpointContainer GetSingleViewpoint(VisualizationInfo GivenPhysicalViewpoint)
        {
            var ReturnObject = new ViewpointContainer();

            ReturnObject.Viewpoint = new viewpoint_GET();
            // Get the components
            foreach (var CurrentComponent in GivenPhysicalViewpoint.Components)
            {
                if (ReturnObject.Components == null)
                {
                    ReturnObject.Components = new List <component_GET>();
                }
                ReturnObject.Components.Add(GetSingleViewpointComponent(CurrentComponent));
            }
            if (GivenPhysicalViewpoint.ClippingPlanes.Count > 0)
            {
                ReturnObject.Viewpoint.clipping_planes = new clipping_planes();
                ReturnObject.Viewpoint.clipping_planes.clipping_plane = new List <clipping_plane>();
                foreach (var CurrentClippingPlane in GivenPhysicalViewpoint.ClippingPlanes)
                {
                    ReturnObject.Viewpoint.clipping_planes.clipping_plane.Add(GetViewpointClippingPlane(CurrentClippingPlane));
                }
            }
            if (GivenPhysicalViewpoint.Lines.Count > 0)
            {
                ReturnObject.Viewpoint.lines      = new lines();
                ReturnObject.Viewpoint.lines.line = new List <line>();
                foreach (var CurrentLine in GivenPhysicalViewpoint.Lines)
                {
                    ReturnObject.Viewpoint.lines.line.Add(GetViewpointLine(CurrentLine));
                }
            }
            ReturnObject.Viewpoint.guid = GivenPhysicalViewpoint.GUID;
            if (GivenPhysicalViewpoint.ShouldSerializeOrthogonalCamera())
            {
                ReturnObject.Viewpoint.orthogonal_camera = GetViewpointOrthogonalCamera(GivenPhysicalViewpoint.OrthogonalCamera);
            }
            // Else if here because only on of the cameras may be set
            else if (GivenPhysicalViewpoint.ShouldSerializePerspectiveCamera())
            {
                ReturnObject.Viewpoint.perspective_camera = GetViewpointPerspectiveCamera(GivenPhysicalViewpoint.PerspectiveCamera);
            }
            // Get the bitmaps if there are any
            // Bitmaps are CURRENTLY NOT SUPPORTED
            return(ReturnObject);
        }
Beispiel #17
0
        private void LoadVisualizationList(List <VisualizationInfo> vizPluginsInfo)
        {
            // If we're already populated the list we don't need to do it again so bail out
            if (VisualizationsInitialized)
            {
                return;
            }

            if (InvokeRequired)
            {
                LoadVisualizationListDelegate d = new LoadVisualizationListDelegate(LoadVisualizationList);
                Invoke(d, vizPluginsInfo);
                return;
            }

            VisualizationsCmbBox.Items.Clear();

            if (IVizMgr == null || vizPluginsInfo.Count == 0)
            {
                VisualizationsCmbBox.Items.Add(new VisualizationInfo("None", true));
                VisualizationsCmbBox.SelectedIndex = 0;
                return;
            }

            VisualizationsInitialized = true;
            int selectedIndex = -1;

            for (int i = 0; i < vizPluginsInfo.Count; i++)
            {
                VisualizationInfo pluginInfo = vizPluginsInfo[i];

                if (pluginInfo.IsIdenticalTo(VizPluginInfo))
                {
                    selectedIndex          = i;
                    pluginInfo.PresetIndex = VizPluginInfo.PresetIndex;
                }

                VisualizationsCmbBox.Items.Add(pluginInfo);
            }

            if (selectedIndex == -1 && VisualizationsCmbBox.Items.Count > 0)
            {
                selectedIndex = 0;
            }
            VisualizationsCmbBox.SelectedIndex = selectedIndex;
        }
Beispiel #18
0
        public IssueBCF()
        {
            guid = Guid.NewGuid();
            markup = new Markup();
            markup.Topic = new Topic();
            markup.Topic.Guid = guid.ToString();
            markup.Comment = new ObservableCollection<CommentBCF>();
            markup.Header = new HeaderFile[1];
            markup.Header[0] = new HeaderFile();
            markup.Header[0].Date = new DateTime();
            markup.Header[0].DateSpecified = true; 
            



            viewpoint = new VisualizationInfo();
            
        }
Beispiel #19
0
        private static VisualizationInfo DeserializeViewpoint(string path)
        {
            VisualizationInfo output = null;

            try
            {
                using (var viewpointFile = new FileStream(path, FileMode.Open))
                {
                    var serializerS = new XmlSerializer(typeof(VisualizationInfo));
                    output = serializerS.Deserialize(viewpointFile) as VisualizationInfo;
                }
            }
            catch (System.Exception ex1)
            {
                MessageBox.Show("exception: " + ex1);
            }
            return(output);
        }
Beispiel #20
0
 /// <summary>
 /// Open 3D View - Jira
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void Open3dViewJira(object sender, RoutedEventArgs e)
 {
     try
     {
         string            url = (string)((Button)sender).Tag;
         VisualizationInfo v   = mainPan.getVisInfo(url);
         if (v == null)
         {
             MessageBox.Show("Failed to open the viewpoint", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
             return;
         }
         doOpen3DView(v);
     }
     catch (System.Exception ex1)
     {
         MessageBox.Show("exception: " + ex1);
     }
 }
Beispiel #21
0
        public override Tuple <string, string> getSnapshotAndViewpoint(int elemCheck)
        {
            if (!(uidoc.ActiveView is View3D || uidoc.ActiveView is ViewSheet || uidoc.ActiveView is ViewPlan || uidoc.ActiveView is ViewSection || uidoc.ActiveView is ViewDrafting))
            {
                MessageBox.Show("I'm sorry,\nonly 3D and 2D views are supported.", "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
                return(null);
            }

            string tempPath    = Path.Combine(Path.GetTempPath(), "BCFtemp", Path.GetRandomFileName());
            string issueFolder = Path.Combine(tempPath, Guid.NewGuid().ToString());

            if (!Directory.Exists(issueFolder))
            {
                Directory.CreateDirectory(issueFolder);
            }

            Guid   viewpointGuid     = Guid.NewGuid();
            string snapshotFilePath  = Path.Combine(issueFolder, string.Format("{0}.png", viewpointGuid.ToString()));
            string viewpointFilePath = Path.Combine(issueFolder, string.Format("{0}.bcfv", viewpointGuid.ToString()));

            // save snapshot
            ImageExportOptions options = new ImageExportOptions();

            options.FilePath = snapshotFilePath;
            options.HLRandWFViewsFileType = ImageFileType.PNG;
            options.ShadowViewsFileType   = ImageFileType.PNG;
            options.ExportRange           = ExportRange.VisibleRegionOfCurrentView;
            options.ZoomType        = ZoomFitType.FitToPage;
            options.ImageResolution = ImageResolution.DPI_72;
            options.PixelSize       = 1000;
            doc.ExportImage(options);

            // save viewpoint
            VisualizationInfo vi          = window.generateViewpoint(elemCheck);
            XmlSerializer     serializerV = new XmlSerializer(typeof(VisualizationInfo));
            Stream            writerV     = new FileStream(viewpointFilePath, FileMode.Create);

            serializerV.Serialize(writerV, vi);
            writerV.Close();

            return(new Tuple <string, string>(snapshotFilePath, viewpointFilePath));
        }
Beispiel #22
0
        /// <summary>
        /// Define viewpoint class by the selected image file
        /// </summary>
        /// <param name="imgFile"></param>
        /// <returns></returns>
        private ViewPoint DefineViewPoint(string imgFile)
        {
            ViewPoint viewPoint = new ViewPoint();

            try
            {
                viewPoint.Guid          = Guid.NewGuid().ToString();
                viewPoint.TopicGuid     = selectedMarkup.Topic.Guid;
                viewPoint.Snapshot      = Path.GetFileName(imgFile);
                viewPoint.SnapshotImage = ImageUtil.GetImageArray(imgFile);

                VisualizationInfo visInfo = new VisualizationInfo();
                visInfo.ViewPointGuid = viewPoint.Guid;

                viewPoint.VisInfo = visInfo;
            }
            catch (Exception ex)
            {
                string message = ex.Message;
            }
            return(viewPoint);
        }
Beispiel #23
0
        private void SetVisualizateInfo()
        {
            vizInfo = null;
            Console.WriteLine("size to cut picture, write two numbers or \"dynamic\" for dynamic size");
            if (!TryGetValueOrWriteError(VisualizationInfo.ReadSize(Console.ReadLine()), out var size))
            {
                return;
            }
            Console.WriteLine("coloring text, write red, geen, blue, black, random, multi, line red, line green, line blue, line random");
            if (!TryGetValueOrWriteError(WordsColoringAssosiation.GetColoring(Console.ReadLine()), out var coloring))
            {
                return;
            }
            Console.WriteLine("font of words, write Arial, Calibri, ...");
            var font = Console.ReadLine();

            if (!VisualizationInfo.FontIsCorrect(font))
            {
                Console.WriteLine("Not correct font");
                return;
            }
            vizInfo = new VisualizationInfo(coloring, size, font);
        }
Beispiel #24
0
        public bool WriteVisualizationInfo(string filePath, VisualizationInfo visInfo)
        {
            bool result = false;

            try
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }

                XmlSerializer serializer = new XmlSerializer(typeof(VisualizationInfo));
                StreamWriter  writer     = new StreamWriter(filePath);
                serializer.Serialize(writer, visInfo);
                writer.Close();
                result = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(filePath + "\nFailed to write visualization info.\n" + ex.Message, "Write Visualization Info", MessageBoxButton.OK, MessageBoxImage.Warning);
                result = false;
            }
            return(result);
        }
    /// <summary>
    /// Open a 3D View
    /// </summary>
    /// <param name="v"></param>
    private void doOpen3DView(VisualizationInfo v)
    {
        try
        {
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document doc = uidoc.Document;

            if (uidoc.ActiveView.ViewType == ViewType.ThreeD)
            {
                View3D view3D = (View3D)uidoc.ActiveView;
                if (view3D.IsPerspective) //ORTHO
                {
                    MessageBox.Show("This operation is not allowed in a Perspective View.\nPlease close the current window(s) and retry.",
                        "Warning!", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

            }
            m_Handler.v = v;

            //var touple = GetViewCoordinates(doc, v);
            //if (touple == null)
            //{
            //    MessageBox.Show("Viewpoint not formatted correctly.", "Viewpoint Error", MessageBoxButton.OK, MessageBoxImage.Error);
            //    return;
            //}

            //m_Handler.touple = touple;

            m_ExEvent.Raise();
        }
        catch (System.Exception ex1)
        {
            TaskDialog.Show("Error!", "exception: " + ex1);
        }
    }
Beispiel #26
0
 /// <summary>
 /// Instantiates the visualisation info.
 /// </summary>
 private void InstantiateVisualisationInfo()
 {
     visualization_info = new VisualizationInfo();
     visualization_info.binary_image = new Texture2D(_width, _height);
     visualization_info.rgb_image    = new Texture2D(_width, _height);
 }
    /// <summary>
    /// Generate Viewpoint
    /// </summary>
    /// <param name="elemCheck"></param>
    /// <returns></returns>
    private VisualizationInfo generateViewpoint(int elemCheck)
    {

      try
      {
        UIDocument uidoc = uiapp.ActiveUIDocument;
        Document doc = uidoc.Document;

        VisualizationInfo v = new VisualizationInfo();

        XYZ centerIMP = new XYZ();
        string type = "";
        double zoomValue = 1;

          if (uidoc.ActiveView.ViewType != ViewType.ThreeD) //is a 2D view
          {
              XYZ TL = uidoc.GetOpenUIViews()[0].GetZoomCorners()[0];
              XYZ BR = uidoc.GetOpenUIViews()[0].GetZoomCorners()[1];
              v.SheetCamera = new SheetCamera();
              v.SheetCamera.SheetID = uidoc.ActiveView.Id.IntegerValue;
              v.SheetCamera.TopLeft = new IssueTracker.Classes.Point(TL.X, TL.Y, TL.Z);
              v.SheetCamera.BottomRight = new IssueTracker.Classes.Point(BR.X, BR.Y, BR.Z);
          }
          else
          {
              View3D view3D = (View3D)uidoc.ActiveView;
              if (!view3D.IsPerspective) //IS ORTHO
              {
                  XYZ TL = uidoc.GetOpenUIViews()[0].GetZoomCorners()[0];
                  XYZ BR = uidoc.GetOpenUIViews()[0].GetZoomCorners()[1];

                  double xO = (TL.X + BR.X) / 2;
                  double yO = (TL.Y + BR.Y) / 2;
                  double zO = (TL.Z + BR.Z) / 2;
                  //converto to METERS
                  centerIMP = new XYZ(xO, yO, zO);
                  double dist = TL.DistanceTo(BR) / 2; //custom sectet value to get solibri zoom value from Corners of Revit UiView
                  XYZ diagVector = TL.Subtract(BR);
                  // **** CUSTOM VALUE FOR TEKLA **** //
                  //zoomValue = UnitUtils.ConvertFromInternalUnits(dist * Math.Sin(diagVector.AngleTo(view3D.RightDirection)), DisplayUnitType.DUT_METERS);
                  // **** CUSTOM VALUE FOR TEKLA **** //
                  double customZoomValue = (MyProjectSettings.Get("useDefaultZoom", doc.PathName) == "1") ? 1 : 2.5;

                  zoomValue = UnitUtils.ConvertFromInternalUnits(dist * Math.Sin(diagVector.AngleTo(view3D.RightDirection)), DisplayUnitType.DUT_METERS) * customZoomValue;
                  type = "OrthogonalCamera";
              }
              else // it is a perspective view
              {
                  centerIMP = uidoc.ActiveView.Origin;
                  type = "PerspectiveCamera";
                  zoomValue = 45;
              }
              ViewOrientation3D t = ConvertBasePoint(centerIMP, uidoc.ActiveView.ViewDirection, uidoc.ActiveView.UpDirection, false);
              //ViewOrientation3D t = new ViewOrientation3D(centerIMP, uidoc.ActiveView.UpDirection, uidoc.ActiveView.ViewDirection);
              XYZ c = t.EyePosition;
              XYZ vi = t.ForwardDirection;
              XYZ up = t.UpDirection;

              if (type == "OrthogonalCamera")
              {
                  v.OrthogonalCamera = new OrthogonalCamera();
                  v.OrthogonalCamera.CameraViewPoint.X = UnitUtils.ConvertFromInternalUnits(c.X, DisplayUnitType.DUT_METERS);
                  v.OrthogonalCamera.CameraViewPoint.Y = UnitUtils.ConvertFromInternalUnits(c.Y, DisplayUnitType.DUT_METERS);
                  v.OrthogonalCamera.CameraViewPoint.Z = UnitUtils.ConvertFromInternalUnits(c.Z, DisplayUnitType.DUT_METERS);
                  v.OrthogonalCamera.CameraUpVector.X = UnitUtils.ConvertFromInternalUnits(up.X, DisplayUnitType.DUT_METERS);
                  v.OrthogonalCamera.CameraUpVector.Y = UnitUtils.ConvertFromInternalUnits(up.Y, DisplayUnitType.DUT_METERS);
                  v.OrthogonalCamera.CameraUpVector.Z = UnitUtils.ConvertFromInternalUnits(up.Z, DisplayUnitType.DUT_METERS);
                  v.OrthogonalCamera.CameraDirection.X = UnitUtils.ConvertFromInternalUnits(vi.X, DisplayUnitType.DUT_METERS) * -1;
                  v.OrthogonalCamera.CameraDirection.Y = UnitUtils.ConvertFromInternalUnits(vi.Y, DisplayUnitType.DUT_METERS) * -1;
                  v.OrthogonalCamera.CameraDirection.Z = UnitUtils.ConvertFromInternalUnits(vi.Z, DisplayUnitType.DUT_METERS) * -1;
                  v.OrthogonalCamera.ViewToWorldScale = zoomValue;
              }
              else
              {
                  v.PerspectiveCamera = new PerspectiveCamera();
                  v.PerspectiveCamera.CameraViewPoint.X = UnitUtils.ConvertFromInternalUnits(c.X, DisplayUnitType.DUT_METERS);
                  v.PerspectiveCamera.CameraViewPoint.Y = UnitUtils.ConvertFromInternalUnits(c.Y, DisplayUnitType.DUT_METERS);
                  v.PerspectiveCamera.CameraViewPoint.Z = UnitUtils.ConvertFromInternalUnits(c.Z, DisplayUnitType.DUT_METERS);
                  v.PerspectiveCamera.CameraUpVector.X = UnitUtils.ConvertFromInternalUnits(up.X, DisplayUnitType.DUT_METERS);
                  v.PerspectiveCamera.CameraUpVector.Y = UnitUtils.ConvertFromInternalUnits(up.Y, DisplayUnitType.DUT_METERS);
                  v.PerspectiveCamera.CameraUpVector.Z = UnitUtils.ConvertFromInternalUnits(up.Z, DisplayUnitType.DUT_METERS);
                  v.PerspectiveCamera.CameraDirection.X = UnitUtils.ConvertFromInternalUnits(vi.X, DisplayUnitType.DUT_METERS) * -1;
                  v.PerspectiveCamera.CameraDirection.Y = UnitUtils.ConvertFromInternalUnits(vi.Y, DisplayUnitType.DUT_METERS) * -1;
                  v.PerspectiveCamera.CameraDirection.Z = UnitUtils.ConvertFromInternalUnits(vi.Z, DisplayUnitType.DUT_METERS) * -1;
                  v.PerspectiveCamera.FieldOfView = zoomValue;
              }
          }

        
        //COMPONENTS PART
        FilteredElementCollector collector = new FilteredElementCollector(doc, doc.ActiveView.Id).WhereElementIsNotElementType();
        System.Collections.Generic.ICollection<ElementId> collection = null;

        if (elemCheck == 0)
          collection = collector.ToElementIds();
        else if (elemCheck == 1)
          collection = uidoc.Selection.GetElementIds();

        if (null != collection && collection.Any())
        {
            v.Components = new IssueTracker.Classes.Component[collection.Count];
          for (var i = 0; i < collection.Count; i++)
          {
            Guid guid = ExportUtils.GetExportId(doc, collection.ElementAt(i));
            string ifcguid = IfcGuid.ToIfcGuid(guid).ToString();
            ;
            v.Components[i] = new ARUP.IssueTracker.Classes.Component(doc.Application.VersionName, collection.ElementAt(i).ToString(), ifcguid);

          }
        }

        return v;

      }
      catch (System.Exception ex1)
      {
        TaskDialog.Show("Error!", "exception: " + ex1);
      }
      return null;
    }
Beispiel #28
0
        //<summary>
        //Generate a VisualizationInfo of the current view
        //</summary>
        //<returns></returns>
        private VisualizationInfo GenerateViewpoint()
        {
            try
            {
                var uidoc = uiapp.ActiveUIDocument;
                var doc   = uidoc.Document;

                var v = new VisualizationInfo();

                //Corners of the active UI view
                var topLeft     = uidoc.GetOpenUIViews()[0].GetZoomCorners()[0];
                var bottomRight = uidoc.GetOpenUIViews()[0].GetZoomCorners()[1];

                //It's a 2D view
                //not supported by BCF, but I store it under a custom
                //fields using 2D coordinates and sheet id
                if (uidoc.ActiveView.ViewType != ViewType.ThreeD)
                {
                    v.SheetCamera = new SheetCamera
                    {
                        SheetID = uidoc.ActiveView.Id.IntegerValue,
                        TopLeft = new Point {
                            X = topLeft.X, Y = topLeft.Y, Z = topLeft.Z
                        },
                        BottomRight = new Point {
                            X = bottomRight.X, Y = bottomRight.Y, Z = bottomRight.Z
                        }
                    };
                }
                //It's a 3d view
                else
                {
                    var    viewCenter = new XYZ();
                    var    view3D     = (View3D)uidoc.ActiveView;
                    double zoomValue  = 1;
                    // it is a orthogonal view
                    if (!view3D.IsPerspective)
                    {
                        double x = (topLeft.X + bottomRight.X) / 2;
                        double y = (topLeft.Y + bottomRight.Y) / 2;
                        double z = (topLeft.Z + bottomRight.Z) / 2;
                        //center of the UI view
                        viewCenter = new XYZ(x, y, z);

                        //vector going from BR to TL
                        XYZ diagVector = topLeft.Subtract(bottomRight);
                        //lenght of the vector
                        double dist = topLeft.DistanceTo(bottomRight) / 2;

                        //ViewToWorldScale value
                        zoomValue = dist * Math.Sin(diagVector.AngleTo(view3D.RightDirection)).ToMeters();

                        // **** CUSTOM VALUE FOR TEKLA **** //
                        // calculated sperimentally, not sure why but it works
                        //if (UserSettings.Get("optTekla") == "1")
                        //  zoomValue = zoomValue * 2.5;
                        // **** CUSTOM VALUE FOR TEKLA **** //

                        ViewOrientation3D t = RevitUtils.ConvertBasePoint(doc, viewCenter, uidoc.ActiveView.ViewDirection,
                                                                          uidoc.ActiveView.UpDirection, false);

                        XYZ c  = t.EyePosition;
                        XYZ vi = t.ForwardDirection;
                        XYZ up = t.UpDirection;


                        v.OrthogonalCamera = new OrthogonalCamera
                        {
                            CameraViewPoint =
                            {
                                X = c.X.ToMeters(),
                                Y = c.Y.ToMeters(),
                                Z = c.Z.ToMeters()
                            },
                            CameraUpVector =
                            {
                                X = up.X.ToMeters(),
                                Y = up.Y.ToMeters(),
                                Z = up.Z.ToMeters()
                            },
                            CameraDirection =
                            {
                                X = vi.X.ToMeters() * -1,
                                Y = vi.Y.ToMeters() * -1,
                                Z = vi.Z.ToMeters() * -1
                            },
                            ViewToWorldScale = zoomValue
                        };
                    }
                    // it is a perspective view
                    else
                    {
                        viewCenter = uidoc.ActiveView.Origin;
                        //revit default value
                        zoomValue = 45;

                        ViewOrientation3D t = RevitUtils.ConvertBasePoint(doc, viewCenter, uidoc.ActiveView.ViewDirection,
                                                                          uidoc.ActiveView.UpDirection, false);

                        XYZ c  = t.EyePosition;
                        XYZ vi = t.ForwardDirection;
                        XYZ up = t.UpDirection;

                        v.PerspectiveCamera = new PerspectiveCamera
                        {
                            CameraViewPoint =
                            {
                                X = c.X.ToMeters(),
                                Y = c.Y.ToMeters(),
                                Z = c.Z.ToMeters()
                            },
                            CameraUpVector =
                            {
                                X = up.X.ToMeters(),
                                Y = up.Y.ToMeters(),
                                Z = up.Z.ToMeters()
                            },
                            CameraDirection =
                            {
                                X = vi.X.ToMeters() * -1,
                                Y = vi.Y.ToMeters() * -1,
                                Z = vi.Z.ToMeters() * -1
                            },
                            FieldOfView = zoomValue
                        };
                    }
                }
                //COMPONENTS PART
                string versionName = doc.Application.VersionName;
                v.Components = new List <Component>();

                var visibleElems = new FilteredElementCollector(doc, doc.ActiveView.Id)
                                   .WhereElementIsNotElementType()
                                   .WhereElementIsViewIndependent()
                                   .ToElementIds();
                var hiddenElems = new FilteredElementCollector(doc)
                                  .WhereElementIsNotElementType()
                                  .WhereElementIsViewIndependent()
                                  .Where(x => x.IsHidden(doc.ActiveView) ||
                                         !doc.ActiveView.IsElementVisibleInTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate, x.Id)).ToList();//would need to check how much this is affecting performance

                var selectedElems = uidoc.Selection.GetElementIds();


                //include only hidden elements and selected in the BCF
                if (visibleElems.Count() > hiddenElems.Count())
                {
                    foreach (var elem in hiddenElems)
                    {
                        v.Components.Add(new Component
                        {
                            OriginatingSystem = versionName,
                            IfcGuid           = IfcGuid.ToIfcGuid(ExportUtils.GetExportId(doc, elem.Id)),
                            Visible           = false,
                            Selected          = false,
                            AuthoringToolId   = elem.Id.IntegerValue.ToString()
                        });
                    }
                    foreach (var elem in selectedElems)
                    {
                        v.Components.Add(new Component
                        {
                            OriginatingSystem = versionName,
                            IfcGuid           = IfcGuid.ToIfcGuid(ExportUtils.GetExportId(doc, elem)),
                            Visible           = true,
                            Selected          = true,
                            AuthoringToolId   = elem.IntegerValue.ToString()
                        });
                    }
                }
                //include only visigle elements
                //all the others are hidden
                else
                {
                    foreach (var elem in visibleElems)
                    {
                        v.Components.Add(new Component
                        {
                            OriginatingSystem = versionName,
                            IfcGuid           = IfcGuid.ToIfcGuid(ExportUtils.GetExportId(doc, elem)),
                            Visible           = true,
                            Selected          = selectedElems.Contains(elem),
                            AuthoringToolId   = elem.IntegerValue.ToString()
                        });
                    }
                }
                return(v);
            }
            catch (System.Exception ex1)
            {
                TaskDialog.Show("Error generating viewpoint", "exception: " + ex1);
            }
            return(null);
        }
Beispiel #29
0
        /// <summary>
        /// </summary>
        /// <param name="expectedViewpoint"></param>
        /// <param name="actualViewpoint"></param>
        /// <param name="originatesFromApiConversion">If true, Bitmaps are not compared since the API does not support them</param>
        public static void CompareSingleViewpoints(VisualizationInfo expectedViewpoint, VisualizationInfo actualViewpoint, bool originatesFromApiConversion)
        {
            Assert.Equal(expectedViewpoint.GUID, actualViewpoint.GUID);

            // Compare Bitmaps
            if (!originatesFromApiConversion && TestCompareUtilities.BothNotNull(expectedViewpoint.Bitmaps, actualViewpoint.Bitmaps, "Viewpoint.Bitmaps"))
            {
                Assert.Equal(expectedViewpoint.Bitmaps.Count, actualViewpoint.Bitmaps.Count);
                foreach (var expectedBitmap in expectedViewpoint.Bitmaps)
                {
                    var actualBitmap = actualViewpoint.Bitmaps
                                       .Where(curr => curr.Bitmap == expectedBitmap.Bitmap)
                                       .Where(curr => curr.Height == expectedBitmap.Height)
                                       .Where(curr => curr.Location.X == expectedBitmap.Location.X)
                                       .Where(curr => curr.Location.Y == expectedBitmap.Location.Y)
                                       .Where(curr => curr.Location.Z == expectedBitmap.Location.Z)
                                       .Where(curr => curr.Normal.X == expectedBitmap.Normal.X)
                                       .Where(curr => curr.Normal.Y == expectedBitmap.Normal.Y)
                                       .Where(curr => curr.Normal.Z == expectedBitmap.Normal.Z)
                                       .Where(curr => curr.Reference == expectedBitmap.Reference)
                                       .Where(curr => curr.Up.X == expectedBitmap.Up.X)
                                       .Where(curr => curr.Up.Y == expectedBitmap.Up.Y)
                                       .Where(curr => curr.Up.Z == expectedBitmap.Up.Z)
                                       .FirstOrDefault();
                    Assert.NotNull(actualViewpoint);
                }
            }

            // Compare Components
            if (TestCompareUtilities.BothNotNull(expectedViewpoint.Components, actualViewpoint.Components, "Viewpoint.Components"))
            {
                if (expectedViewpoint.Components.Count == 1 && actualViewpoint.Components.Count == 1)
                {
                    var expectedComponent = expectedViewpoint.Components.First();
                    var actualComponent   = actualViewpoint.Components.First();

                    Assert.Equal(expectedComponent.AuthoringToolId, actualComponent.AuthoringToolId);
                    Assert.True((expectedComponent.Color == null && actualComponent.Color == null) || expectedComponent.Color.SequenceEqual(actualComponent.Color), "Color");
                    Assert.Equal(expectedComponent.IfcGuid, actualComponent.IfcGuid);
                    Assert.Equal(expectedComponent.OriginatingSystem, actualComponent.OriginatingSystem);
                    Assert.Equal(expectedComponent.Selected, actualComponent.Selected);
                    Assert.Equal(expectedComponent.Visible, actualComponent.Visible);
                }
                else
                {
                    foreach (var currentComponent in expectedViewpoint.Components)
                    {
                        var actualComponent = actualViewpoint.Components
                                              .Where(curr => curr.AuthoringToolId == currentComponent.AuthoringToolId)
                                              .Where(curr => (curr.Color == null && currentComponent.Color == null) || curr.Color.SequenceEqual(currentComponent.Color))
                                              .Where(curr => curr.IfcGuid == currentComponent.IfcGuid)
                                              .Where(curr => curr.OriginatingSystem == currentComponent.OriginatingSystem)
                                              .Where(curr => curr.Selected == currentComponent.Selected)
                                              .Where(curr => curr.Visible == currentComponent.Visible)
                                              .FirstOrDefault();

                        Assert.NotNull(actualComponent);
                    }
                }
            }

            // Compare Lines
            if (TestCompareUtilities.BothNotNull(expectedViewpoint.Lines, actualViewpoint.Lines, "Viewpoint.Lines"))
            {
                foreach (var expectedLine in expectedViewpoint.Lines)
                {
                    var actualLine = actualViewpoint.Lines
                                     .Where(curr => curr.EndPoint.X == expectedLine.EndPoint.X)
                                     .Where(curr => curr.EndPoint.Y == expectedLine.EndPoint.Y)
                                     .Where(curr => curr.EndPoint.Z == expectedLine.EndPoint.Z)
                                     .Where(curr => curr.StartPoint.X == expectedLine.StartPoint.X)
                                     .Where(curr => curr.StartPoint.Y == expectedLine.StartPoint.Y)
                                     .Where(curr => curr.StartPoint.Z == expectedLine.StartPoint.Z)
                                     .FirstOrDefault();
                    Assert.NotNull(actualLine);
                }
            }

            // Compare Clipping planes
            if (TestCompareUtilities.BothNotNull(expectedViewpoint.ClippingPlanes, actualViewpoint.ClippingPlanes, "Viewpoint.ClippingPlanes"))
            {
                foreach (var expectedPlane in expectedViewpoint.ClippingPlanes)
                {
                    var actualPlane = actualViewpoint.ClippingPlanes
                                      .Where(curr => curr.Direction.X == expectedPlane.Direction.X)
                                      .Where(curr => curr.Direction.Y == expectedPlane.Direction.Y)
                                      .Where(curr => curr.Direction.Z == expectedPlane.Direction.Z)
                                      .Where(curr => curr.Location.X == expectedPlane.Location.X)
                                      .Where(curr => curr.Location.Y == expectedPlane.Location.Y)
                                      .Where(curr => curr.Location.Z == expectedPlane.Location.Z)
                                      .FirstOrDefault();
                    Assert.NotNull(actualPlane);
                }
            }

            // Compare OrthogonalCamera
            if (TestCompareUtilities.BothNotNull(expectedViewpoint.OrthogonalCamera, actualViewpoint.OrthogonalCamera, "Viewpoint.OrthogonalCamera"))
            {
                CompareOrthogonalCameras(expectedViewpoint.OrthogonalCamera, actualViewpoint.OrthogonalCamera);
            }
            // Compare PerspectiveCamera
            if (TestCompareUtilities.BothNotNull(expectedViewpoint.PerspectiveCamera, actualViewpoint.PerspectiveCamera, "Viewpoint.PerspectiveCamera"))
            {
                ComparePerspectiveCameras(expectedViewpoint.PerspectiveCamera, actualViewpoint.PerspectiveCamera);
            }
        }
Beispiel #30
0
        /// <summary>
        /// Generate Viewpoint
        /// </summary>
        /// <param name="elemCheck"></param>
        /// <returns></returns>
        public VisualizationInfo generateViewpoint(int elemCheck)
        {
            try
            {
                UIDocument uidoc = uiapp.ActiveUIDocument;
                Document   doc   = uidoc.Document;

                VisualizationInfo v = new VisualizationInfo();

                XYZ    centerIMP = new XYZ();
                string type      = "";
                double zoomValue = 1;

                if (uidoc.ActiveView.ViewType != ViewType.ThreeD) //is a 2D view
                {
                    XYZ TL = uidoc.GetOpenUIViews()[0].GetZoomCorners()[0];
                    XYZ BR = uidoc.GetOpenUIViews()[0].GetZoomCorners()[1];
                    v.SheetCamera             = new SheetCamera();
                    v.SheetCamera.SheetID     = uidoc.ActiveView.Id.IntegerValue;
                    v.SheetCamera.TopLeft     = new IssueTracker.Classes.BCF2.Point(TL.X, TL.Y, TL.Z);
                    v.SheetCamera.BottomRight = new IssueTracker.Classes.BCF2.Point(BR.X, BR.Y, BR.Z);
                }
                else
                {
                    View3D view3D = (View3D)uidoc.ActiveView;
                    if (!view3D.IsPerspective) //IS ORTHO
                    {
                        XYZ TL = uidoc.GetOpenUIViews()[0].GetZoomCorners()[0];
                        XYZ BR = uidoc.GetOpenUIViews()[0].GetZoomCorners()[1];

                        double xO = (TL.X + BR.X) / 2;
                        double yO = (TL.Y + BR.Y) / 2;
                        double zO = (TL.Z + BR.Z) / 2;
                        //converto to METERS
                        centerIMP = new XYZ(xO, yO, zO);
                        double dist       = TL.DistanceTo(BR) / 2; //custom sectet value to get solibri zoom value from Corners of Revit UiView
                        XYZ    diagVector = TL.Subtract(BR);
                        // **** CUSTOM VALUE FOR TEKLA **** //
                        //zoomValue = UnitUtils.ConvertFromInternalUnits(dist * Math.Sin(diagVector.AngleTo(view3D.RightDirection)), DisplayUnitType.DUT_METERS);
                        // **** CUSTOM VALUE FOR TEKLA **** //
                        double customZoomValue = (MyProjectSettings.Get("useDefaultZoom", doc.PathName) == "1") ? 1 : 2.5;

                        zoomValue = UnitUtils.ConvertFromInternalUnits(dist * Math.Sin(diagVector.AngleTo(view3D.RightDirection)), DisplayUnitType.DUT_METERS) * customZoomValue;
                        type      = "OrthogonalCamera";
                    }
                    else // it is a perspective view
                    {
                        centerIMP = uidoc.ActiveView.Origin;
                        type      = "PerspectiveCamera";
                        zoomValue = 45;
                    }
                    ViewOrientation3D t = ConvertBasePoint(centerIMP, uidoc.ActiveView.ViewDirection, uidoc.ActiveView.UpDirection, false);
                    //ViewOrientation3D t = new ViewOrientation3D(centerIMP, uidoc.ActiveView.UpDirection, uidoc.ActiveView.ViewDirection);
                    XYZ c  = t.EyePosition;
                    XYZ vi = t.ForwardDirection;
                    XYZ up = t.UpDirection;

                    if (type == "OrthogonalCamera")
                    {
                        v.OrthogonalCamera = new OrthogonalCamera();
                        v.OrthogonalCamera.CameraViewPoint.X = UnitUtils.ConvertFromInternalUnits(c.X, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraViewPoint.Y = UnitUtils.ConvertFromInternalUnits(c.Y, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraViewPoint.Z = UnitUtils.ConvertFromInternalUnits(c.Z, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraUpVector.X  = UnitUtils.ConvertFromInternalUnits(up.X, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraUpVector.Y  = UnitUtils.ConvertFromInternalUnits(up.Y, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraUpVector.Z  = UnitUtils.ConvertFromInternalUnits(up.Z, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraDirection.X = UnitUtils.ConvertFromInternalUnits(vi.X, DisplayUnitType.DUT_METERS) * -1;
                        v.OrthogonalCamera.CameraDirection.Y = UnitUtils.ConvertFromInternalUnits(vi.Y, DisplayUnitType.DUT_METERS) * -1;
                        v.OrthogonalCamera.CameraDirection.Z = UnitUtils.ConvertFromInternalUnits(vi.Z, DisplayUnitType.DUT_METERS) * -1;
                        v.OrthogonalCamera.ViewToWorldScale  = zoomValue;
                    }
                    else
                    {
                        v.PerspectiveCamera = new PerspectiveCamera();
                        v.PerspectiveCamera.CameraViewPoint.X = UnitUtils.ConvertFromInternalUnits(c.X, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraViewPoint.Y = UnitUtils.ConvertFromInternalUnits(c.Y, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraViewPoint.Z = UnitUtils.ConvertFromInternalUnits(c.Z, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraUpVector.X  = UnitUtils.ConvertFromInternalUnits(up.X, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraUpVector.Y  = UnitUtils.ConvertFromInternalUnits(up.Y, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraUpVector.Z  = UnitUtils.ConvertFromInternalUnits(up.Z, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraDirection.X = UnitUtils.ConvertFromInternalUnits(vi.X, DisplayUnitType.DUT_METERS) * -1;
                        v.PerspectiveCamera.CameraDirection.Y = UnitUtils.ConvertFromInternalUnits(vi.Y, DisplayUnitType.DUT_METERS) * -1;
                        v.PerspectiveCamera.CameraDirection.Z = UnitUtils.ConvertFromInternalUnits(vi.Z, DisplayUnitType.DUT_METERS) * -1;
                        v.PerspectiveCamera.FieldOfView       = zoomValue;
                    }


                    // handle section box if enabled
                    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);

                        // Convert to project unit
                        DisplayUnitType lengthUnitType = doc.GetUnits().GetFormatOptions(UnitType.UT_Length).DisplayUnits;
                        maxInModelCoords = new XYZ(UnitUtils.ConvertFromInternalUnits(maxInModelCoords.X, lengthUnitType),
                                                   UnitUtils.ConvertFromInternalUnits(maxInModelCoords.Y, lengthUnitType),
                                                   UnitUtils.ConvertFromInternalUnits(maxInModelCoords.Z, lengthUnitType));
                        minInModelCoords = new XYZ(UnitUtils.ConvertFromInternalUnits(minInModelCoords.X, lengthUnitType),
                                                   UnitUtils.ConvertFromInternalUnits(minInModelCoords.Y, lengthUnitType),
                                                   UnitUtils.ConvertFromInternalUnits(minInModelCoords.Z, lengthUnitType));

                        // Convert to shared coordinates
                        maxInModelCoords = ARUP.IssueTracker.Revit.Classes.Utils.ConvertToFromSharedCoordinate(doc, maxInModelCoords, false);
                        minInModelCoords = ARUP.IssueTracker.Revit.Classes.Utils.ConvertToFromSharedCoordinate(doc, minInModelCoords, false);

                        // Add to BCF clipping planes
                        v.ClippingPlanes = BcfAdapter.GetClippingPlanesFromBoundingBox
                                           (
                            maxInModelCoords.X, maxInModelCoords.Y, maxInModelCoords.Z,
                            minInModelCoords.X, minInModelCoords.Y, minInModelCoords.Z
                                           );
                    }
                }


                //COMPONENTS PART
                FilteredElementCollector collector = new FilteredElementCollector(doc, doc.ActiveView.Id).WhereElementIsNotElementType();
                System.Collections.Generic.ICollection <ElementId> collection = null;

                if (elemCheck == 0)
                {
                    collection = collector.ToElementIds();
                }
                else if (elemCheck == 1)
                {
                    collection = uidoc.Selection.GetElementIds();
                }

                if (null != collection && collection.Any())
                {
                    v.Components = new List <IssueTracker.Classes.BCF2.Component>();
                    foreach (var eId in collection)
                    {
                        Guid   guid    = ExportUtils.GetExportId(doc, eId);
                        string ifcguid = IfcGuid.ToIfcGuid(guid).ToString();
                        v.Components.Add(new ARUP.IssueTracker.Classes.BCF2.Component(doc.Application.VersionName, eId.ToString(), ifcguid));
                    }
                }

                return(v);
            }
            catch (System.Exception ex1)
            {
                TaskDialog.Show("Error!", "exception: " + ex1);
            }
            return(null);
        }
Beispiel #31
0
        public static bool Write(string bcfPath, BCFZIP bcf)
        {
            bool written = false;

            try
            {
                ProgressManager.InitializeProgress("Writing BCF..", bcf.Markups.Count);

                string tempDirectory = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "SmartBCF", bcf.FileId);
                if (Directory.Exists(tempDirectory))
                {
                    Directory.Delete(tempDirectory, true);
                }

                //Create root directory
                Directory.CreateDirectory(tempDirectory);

                //Project File
                string projectFilePath = System.IO.Path.Combine(tempDirectory, "project.bcfp");
                using (FileStream stream = new FileStream(projectFilePath, FileMode.Create))
                {
                    XmlSerializer projectSerializer = new XmlSerializer(typeof(ProjectExtension));
                    projectSerializer.Serialize(stream, bcf.ProjectFile);
                    stream.Close();
                }

                //Version File
                string versionFilePath = System.IO.Path.Combine(tempDirectory, "bcf.version");
                using (FileStream stream = new FileStream(versionFilePath, FileMode.Create))
                {
                    XmlSerializer versionSerializer = new XmlSerializer(typeof(Version));
                    versionSerializer.Serialize(stream, bcf.VersionFile);
                    stream.Close();
                }

                //Color File
                string colorFilePath = System.IO.Path.Combine(tempDirectory, "extension.color");
                using (FileStream stream = new FileStream(colorFilePath, FileMode.Create))
                {
                    XmlSerializer colorSerializer = new XmlSerializer(typeof(RevitExtensionInfo));
                    colorSerializer.Serialize(stream, bcf.ExtensionColor);
                    stream.Close();
                }

                //Markup and Viewpoint
                XmlSerializer markupSerializer  = new XmlSerializer(typeof(Markup));
                XmlSerializer visInfoSerializer = new XmlSerializer(typeof(VisualizationInfo));
                XmlSerializer extInfoSerializer = new XmlSerializer(typeof(ComponentExtensionInfo));
                foreach (Markup markup in bcf.Markups)
                {
                    ProgressManager.StepForward();

                    string topicDirectory = System.IO.Path.Combine(tempDirectory, markup.Topic.Guid);
                    Directory.CreateDirectory(topicDirectory);

                    string markupFilePath = System.IO.Path.Combine(topicDirectory, "markup.bcf");
                    using (FileStream stream = new FileStream(markupFilePath, FileMode.Create))
                    {
                        markupSerializer.Serialize(stream, markup);
                        stream.Close();
                    }

                    //Viewpoint
                    foreach (ViewPoint vp in markup.Viewpoints)
                    {
                        //Snapshot
                        if (!string.IsNullOrEmpty(vp.Snapshot) && null != vp.SnapshotImage)
                        {
                            string snapshotPath = System.IO.Path.Combine(topicDirectory, vp.Snapshot);
                            using (System.Drawing.Image image = System.Drawing.Image.FromStream(new MemoryStream(vp.SnapshotImage)))
                            {
                                image.Save(snapshotPath, System.Drawing.Imaging.ImageFormat.Png);
                            }
                        }

                        if (!string.IsNullOrEmpty(vp.Viewpoint))
                        {
                            //Visinfo
                            string visInfoPath = System.IO.Path.Combine(topicDirectory, vp.Viewpoint);
                            if (null != vp.VisInfo)
                            {
                                VisualizationInfo visInfo = vp.VisInfo;
                                using (FileStream stream = new FileStream(visInfoPath, FileMode.Create))
                                {
                                    visInfoSerializer.Serialize(stream, visInfo);
                                    stream.Close();
                                }

                                string extensionPath           = visInfoPath.Replace(".bcfv", ".bcfvx");
                                ComponentExtensionInfo extInfo = new ComponentExtensionInfo();
                                extInfo.ViewpointGuid = vp.Guid;
                                var revitComponents = from comp in visInfo.Components
                                                      where (null != comp.Action) && (null != comp.Responsibility)
                                                      select comp;
                                if (revitComponents.Count() > 0)
                                {
                                    var componentsToWrite = from comp in revitComponents
                                                            where (comp.Action.Guid != Guid.Empty.ToString()) || (comp.Responsibility.Guid != Guid.Empty.ToString()) || (!string.IsNullOrEmpty(comp.ElementName))
                                                            select comp;
                                    if (componentsToWrite.Count() > 0)
                                    {
                                        ObservableCollection <ComponentExtension> compExtensions = new ObservableCollection <ComponentExtension>();
                                        List <Component> componentList = revitComponents.ToList();
                                        foreach (Component comp in componentList)
                                        {
                                            compExtensions.Add(new ComponentExtension(comp));
                                        }
                                        extInfo.Extensions = compExtensions;
                                        using (FileStream stream = new FileStream(extensionPath, FileMode.Create))
                                        {
                                            extInfoSerializer.Serialize(stream, extInfo);
                                            stream.Close();
                                        }
                                    }
                                }

                                //Bitmap
                                if (vp.VisInfo.Bitmaps.Count > 0)
                                {
                                    foreach (VisualizationInfoBitmaps bitmap in visInfo.Bitmaps)
                                    {
                                        if (!string.IsNullOrEmpty(bitmap.Reference) && null != bitmap.BitmapImage)
                                        {
                                            string bitmapPath = System.IO.Path.Combine(topicDirectory, bitmap.Reference);
                                            using (System.Drawing.Image image = System.Drawing.Image.FromStream(new MemoryStream(bitmap.BitmapImage)))
                                            {
                                                if (bitmap.Bitmap == BitmapFormat.JPG)
                                                {
                                                    image.Save(bitmapPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                                                }
                                                else if (bitmap.Bitmap == BitmapFormat.PNG)
                                                {
                                                    image.Save(bitmapPath, System.Drawing.Imaging.ImageFormat.Png);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                ZipFile.CreateFromDirectory(tempDirectory, bcfPath, CompressionLevel.Fastest, false);
                if (File.Exists(bcfPath))
                {
                    written = true;
                }
                ProgressManager.FinalizeProgress();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to write the BCF file.\n" + ex.Message, "Write BCF", MessageBoxButton.OK, MessageBoxImage.Warning);
                ProgressManager.FinalizeProgress();
            }
            return(written);
        }
    /// <summary>
    /// returns XYZ and ZOOM/FOV value
    /// </summary>
    /// <param name="doc"></param>
    /// <param name="viewport"></param>
    /// <returns></returns>
    public Tuple<ViewOrientation3D, double, string, string> GetViewCoordinates(Document doc, VisualizationInfo viewport)
    {
      string type = ""; //change if i force ortho mode
      double zoom = 0; //fov or worldscale

      XYZ CameraDirection = new XYZ();
      XYZ CameraUpVector = new XYZ();
      XYZ CameraViewPoint = new XYZ();
      //retrive the force perspective value


      // IS ORTHOGONAL
      if (viewport.OrthogonalCamera != null)
      {
        if (viewport.OrthogonalCamera.ViewToWorldScale == null || viewport.OrthogonalCamera.CameraViewPoint == null || viewport.OrthogonalCamera.CameraUpVector == null || viewport.OrthogonalCamera.CameraDirection == null)
          return null;
        type = "OrthogonalCamera";
        zoom = UnitUtils.ConvertToInternalUnits(viewport.OrthogonalCamera.ViewToWorldScale, DisplayUnitType.DUT_METERS);
        CameraDirection = GetXYZ(viewport.OrthogonalCamera.CameraDirection.X, viewport.OrthogonalCamera.CameraDirection.Y, viewport.OrthogonalCamera.CameraDirection.Z);
        CameraUpVector = GetXYZ(viewport.OrthogonalCamera.CameraUpVector.X, viewport.OrthogonalCamera.CameraUpVector.Y, viewport.OrthogonalCamera.CameraUpVector.Z);
        CameraViewPoint = GetXYZ(viewport.OrthogonalCamera.CameraViewPoint.X, viewport.OrthogonalCamera.CameraViewPoint.Y, viewport.OrthogonalCamera.CameraViewPoint.Z);


      }

      else if (viewport.PerspectiveCamera != null)
      {
        if (viewport.PerspectiveCamera.FieldOfView == null || viewport.PerspectiveCamera.CameraViewPoint == null || viewport.PerspectiveCamera.CameraUpVector == null || viewport.PerspectiveCamera.CameraDirection == null)
          return null;

        type = "PerspectiveCamera";
        zoom = viewport.PerspectiveCamera.FieldOfView;
        double z1 = 18 / Math.Tan(zoom / 2 * Math.PI / 180);//focale 1
        double z = 18 / Math.Tan(25 / 2 * Math.PI / 180);//focale, da controllare il 18, vedi PDF
        double factor = z1 - z;

        CameraDirection = GetXYZ(viewport.PerspectiveCamera.CameraDirection.X, viewport.PerspectiveCamera.CameraDirection.Y, viewport.PerspectiveCamera.CameraDirection.Z);
        CameraUpVector = GetXYZ(viewport.PerspectiveCamera.CameraUpVector.X, viewport.PerspectiveCamera.CameraUpVector.Y, viewport.PerspectiveCamera.CameraUpVector.Z);
        XYZ oldO = GetXYZ(viewport.PerspectiveCamera.CameraViewPoint.X, viewport.PerspectiveCamera.CameraViewPoint.Y, viewport.PerspectiveCamera.CameraViewPoint.Z);
        CameraViewPoint = (oldO.Subtract(CameraDirection.Divide(factor)));
      }
      else
        return null;
      // CHAGE VALUES ACCORDING TO BASEPOINT 
      //THIS WAS the one with DOC
      ViewOrientation3D orient3d = ConvertBasePoint(CameraViewPoint, CameraDirection, CameraUpVector, true);

      return new Tuple<ViewOrientation3D, double, string, string>(orient3d, zoom, type, "New View");
    }
        /// <summary>
        /// Generate Viewpoint
        /// </summary>
        /// <param name="elemCheck"></param>
        /// <returns></returns>
        private VisualizationInfo generateViewpoint(int elemCheck)
        {
            try
            {
                UIDocument uidoc = uiapp.ActiveUIDocument;
                Document   doc   = uidoc.Document;

                VisualizationInfo v = new VisualizationInfo();

                XYZ    centerIMP = new XYZ();
                string type      = "";
                double zoomValue = 1;

                if (uidoc.ActiveView.ViewType != ViewType.ThreeD) //is a 2D view
                {
                    XYZ TL = uidoc.GetOpenUIViews()[0].GetZoomCorners()[0];
                    XYZ BR = uidoc.GetOpenUIViews()[0].GetZoomCorners()[1];
                    v.SheetCamera             = new SheetCamera();
                    v.SheetCamera.SheetID     = uidoc.ActiveView.Id.IntegerValue;
                    v.SheetCamera.TopLeft     = new IssueTracker.Data.Point(TL.X, TL.Y, TL.Z);
                    v.SheetCamera.BottomRight = new IssueTracker.Data.Point(BR.X, BR.Y, BR.Z);
                }
                else
                {
                    View3D view3D = (View3D)uidoc.ActiveView;
                    if (!view3D.IsPerspective) //IS ORTHO
                    {
                        XYZ TL = uidoc.GetOpenUIViews()[0].GetZoomCorners()[0];
                        XYZ BR = uidoc.GetOpenUIViews()[0].GetZoomCorners()[1];

                        double xO = (TL.X + BR.X) / 2;
                        double yO = (TL.Y + BR.Y) / 2;
                        double zO = (TL.Z + BR.Z) / 2;
                        //converto to METERS
                        centerIMP = new XYZ(xO, yO, zO);
                        double dist            = TL.DistanceTo(BR) / 2; //custom value to get solibri zoom value from Corners of Revit UiView
                        XYZ    diagVector      = TL.Subtract(BR);
                        double customZoomValue = (ProjectSettings.Get("useDefaultZoom", doc.PathName) == "1") ? 1 : 2.5;

                        zoomValue = UnitUtils.ConvertFromInternalUnits(dist * Math.Sin(diagVector.AngleTo(view3D.RightDirection)), DisplayUnitType.DUT_METERS) * customZoomValue;
                        type      = "OrthogonalCamera";
                    }
                    else // it is a perspective view
                    {
                        centerIMP = uidoc.ActiveView.Origin;
                        type      = "PerspectiveCamera";
                        zoomValue = 45;
                    }
                    ViewOrientation3D t = ConvertBasePoint(centerIMP, uidoc.ActiveView.ViewDirection, uidoc.ActiveView.UpDirection, false);
                    XYZ c  = t.EyePosition;
                    XYZ vi = t.ForwardDirection;
                    XYZ up = t.UpDirection;

                    if (type == "OrthogonalCamera")
                    {
                        v.OrthogonalCamera = new OrthogonalCamera();
                        v.OrthogonalCamera.CameraViewPoint.X = UnitUtils.ConvertFromInternalUnits(c.X, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraViewPoint.Y = UnitUtils.ConvertFromInternalUnits(c.Y, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraViewPoint.Z = UnitUtils.ConvertFromInternalUnits(c.Z, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraUpVector.X  = UnitUtils.ConvertFromInternalUnits(up.X, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraUpVector.Y  = UnitUtils.ConvertFromInternalUnits(up.Y, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraUpVector.Z  = UnitUtils.ConvertFromInternalUnits(up.Z, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraDirection.X = UnitUtils.ConvertFromInternalUnits(vi.X, DisplayUnitType.DUT_METERS) * -1;
                        v.OrthogonalCamera.CameraDirection.Y = UnitUtils.ConvertFromInternalUnits(vi.Y, DisplayUnitType.DUT_METERS) * -1;
                        v.OrthogonalCamera.CameraDirection.Z = UnitUtils.ConvertFromInternalUnits(vi.Z, DisplayUnitType.DUT_METERS) * -1;
                        v.OrthogonalCamera.ViewToWorldScale  = zoomValue;
                    }
                    else
                    {
                        v.PerspectiveCamera = new PerspectiveCamera();
                        v.PerspectiveCamera.CameraViewPoint.X = UnitUtils.ConvertFromInternalUnits(c.X, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraViewPoint.Y = UnitUtils.ConvertFromInternalUnits(c.Y, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraViewPoint.Z = UnitUtils.ConvertFromInternalUnits(c.Z, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraUpVector.X  = UnitUtils.ConvertFromInternalUnits(up.X, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraUpVector.Y  = UnitUtils.ConvertFromInternalUnits(up.Y, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraUpVector.Z  = UnitUtils.ConvertFromInternalUnits(up.Z, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraDirection.X = UnitUtils.ConvertFromInternalUnits(vi.X, DisplayUnitType.DUT_METERS) * -1;
                        v.PerspectiveCamera.CameraDirection.Y = UnitUtils.ConvertFromInternalUnits(vi.Y, DisplayUnitType.DUT_METERS) * -1;
                        v.PerspectiveCamera.CameraDirection.Z = UnitUtils.ConvertFromInternalUnits(vi.Z, DisplayUnitType.DUT_METERS) * -1;
                        v.PerspectiveCamera.FieldOfView       = zoomValue;
                    }
                }


                //COMPONENTS PART
                FilteredElementCollector collector = new FilteredElementCollector(doc, doc.ActiveView.Id).WhereElementIsNotElementType();
                System.Collections.Generic.ICollection <ElementId> collection = null;

                if (elemCheck == 0)
                {
                    collection = collector.ToElementIds();
                }
                else if (elemCheck == 1)
                {
                    collection = uidoc.Selection.GetElementIds();
                }

                if (null != collection && collection.Any())
                {
                    v.Components = new IssueTracker.Data.Component[collection.Count];
                    for (var i = 0; i < collection.Count; i++)
                    {
                        Guid   guid    = ExportUtils.GetExportId(doc, collection.ElementAt(i));
                        string ifcguid = IfcGuid.ToIfcGuid(guid).ToString();
                        ;
                        v.Components[i] = new Case.IssueTracker.Data.Component(doc.Application.VersionName, collection.ElementAt(i).ToString(), ifcguid);
                    }
                }

                return(v);
            }
            catch (System.Exception ex1)
            {
                TaskDialog.Show("Error!", "exception: " + ex1);
            }
            return(null);
        }
        public Tuple<Point3D, Vector3D, Vector3D, Autodesk.Navisworks.Api.ViewpointProjection, double> GetViewCoordinates(VisualizationInfo viewport)
        {
            try
            {
                double units = GetGunits();

                Point3D Position = new Point3D();
                Vector3D VectorUp = new Vector3D();
                Vector3D VectorTo = new Vector3D();
                ViewpointProjection vp = ViewpointProjection.Perspective;
                double zoom = 0;
                if (viewport.OrthogonalCamera != null)
                {
                    if (viewport.OrthogonalCamera.CameraViewPoint == null || viewport.OrthogonalCamera.CameraUpVector == null || viewport.OrthogonalCamera.CameraDirection == null)
                        return null;

                    vp = ViewpointProjection.Orthographic;
                    zoom = units * viewport.OrthogonalCamera.ViewToWorldScale;
                    Position = GetXYZ(viewport.OrthogonalCamera.CameraViewPoint.X, viewport.OrthogonalCamera.CameraViewPoint.Y, viewport.OrthogonalCamera.CameraViewPoint.Z);
                    VectorUp = GetXYZ(viewport.OrthogonalCamera.CameraUpVector.X, viewport.OrthogonalCamera.CameraUpVector.Y, viewport.OrthogonalCamera.CameraUpVector.Z).ToVector3D().Normalize();
                    VectorTo = GetXYZ(viewport.OrthogonalCamera.CameraDirection.X, viewport.OrthogonalCamera.CameraDirection.Y, viewport.OrthogonalCamera.CameraDirection.Z).ToVector3D().Normalize();
                }
                else if (viewport.PerspectiveCamera != null)
                {
                    if (viewport.PerspectiveCamera.CameraViewPoint == null || viewport.PerspectiveCamera.CameraUpVector == null || viewport.PerspectiveCamera.CameraDirection == null)
                        return null;

                    zoom = viewport.PerspectiveCamera.FieldOfView;
                    Position = GetXYZ(viewport.PerspectiveCamera.CameraViewPoint.X, viewport.PerspectiveCamera.CameraViewPoint.Y, viewport.PerspectiveCamera.CameraViewPoint.Z);
                    VectorUp = GetXYZ(viewport.PerspectiveCamera.CameraUpVector.X, viewport.PerspectiveCamera.CameraUpVector.Y, viewport.PerspectiveCamera.CameraUpVector.Z).ToVector3D().Normalize();
                    VectorTo = GetXYZ(viewport.PerspectiveCamera.CameraDirection.X, viewport.PerspectiveCamera.CameraDirection.Y, viewport.PerspectiveCamera.CameraDirection.Z).ToVector3D().Normalize();

                }
                else
                    return null;

                return new Tuple<Point3D, Vector3D, Vector3D, ViewpointProjection, double>(Position, VectorUp, VectorTo, vp, zoom);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            return null;
        }
        private VisualizationInfo generateViewpoint(Viewpoint oVP, int elemCheck)
        {
            double units = GetGunits();
            VisualizationInfo v = new VisualizationInfo();
            try
            {

                Vector3D vi = getViewDir(oVP);
                Vector3D up = getViewUp(oVP);
                Point3D center = new Point3D(oVP.Position.X / units, oVP.Position.Y / units, oVP.Position.Z / units);
                double zoomValue = 1;


                oVP = oVP.CreateCopy();
                if (!oVP.HasFocalDistance)
                    oVP.FocalDistance = 1;

                if (oVP.Projection == ViewpointProjection.Orthographic) //IS ORTHO
                {
                    // **** CUSTOM VALUE FOR TEKLA **** //
                    // otherwise = 1
                    // **** CUSTOM VALUE FOR TEKLA **** //


                    double dist = oVP.VerticalExtentAtFocalDistance / 2 / units;
                    zoomValue = 3.125 * dist / (up.Length * 1.25);
                    //zoomValue = Math.Tan(oVP.HeightField / 2) * oVP.FarPlaneDistance / _feet *1.25;
                    //  MessageBox.Show(oVP.HeightField.ToString() + "  " + oVP.FarPlaneDistance.ToString() + "   " + zoomValue + "   " + oVP.HasFocalDistance.ToString() + "   " + oVP.VerticalExtentAtFocalDistance.ToString());
                    v.OrthogonalCamera = new OrthogonalCamera();
                    v.OrthogonalCamera.CameraViewPoint.X = center.X;
                    v.OrthogonalCamera.CameraViewPoint.Y = center.Y;
                    v.OrthogonalCamera.CameraViewPoint.Z = center.Z;
                    v.OrthogonalCamera.CameraUpVector.X = up.X;
                    v.OrthogonalCamera.CameraUpVector.Y = up.Y;
                    v.OrthogonalCamera.CameraUpVector.Z = up.Z;
                    v.OrthogonalCamera.CameraDirection.X = vi.X;
                    v.OrthogonalCamera.CameraDirection.Y = vi.Y;
                    v.OrthogonalCamera.CameraDirection.Z = vi.Z;
                    v.OrthogonalCamera.ViewToWorldScale = zoomValue;
                }
                else // it is a perspective view
                {
                    double f = oVP.FocalDistance;
                    //there is an issue when using vewpoint generated from clashes
                    //their VerticalExtentAtFocalDistance is correct but the HorizontalExtentAtFocalDistance is too small!
                    //so results that the aspect ratio in that case is <1. In which I try to get an approximate valut of the HorizontalExtentAtFocalDistance
                    // by multiplying the vercial by 1.35
                    //double hfov = (oVP.AspectRatio < 1) ? oVP.VerticalExtentAtFocalDistance * 1.23245 / 2 : oVP.HorizontalExtentAtFocalDistance / 2;
                    //double angle = Math.Atan(hfov * (1 / f)) * 2;
                    //double angled = (180 * angle / Math.PI);


                    //NAVIS USES HFOV
                    //double vfov = oVP.VerticalExtentAtFocalDistance / 2;
                    //double fov = Math.Sqrt(hfov * hfov + vfov * vfov);
                    //double angle = Math.Atan(fov*(1/f)) *2;
                    //double angled = (180 * angle / Math.PI);
                    //MessageBox.Show(angled.ToString() + "   " + oVP.FarDistance + "   " +f + "   " + oVP.NearDistance );// + "\n zoom" + zoom);

                    zoomValue = f;

                    v.PerspectiveCamera = new PerspectiveCamera();
                    v.PerspectiveCamera.CameraViewPoint.X = center.X;
                    v.PerspectiveCamera.CameraViewPoint.Y = center.Y;
                    v.PerspectiveCamera.CameraViewPoint.Z = center.Z;
                    v.PerspectiveCamera.CameraUpVector.X = up.X;
                    v.PerspectiveCamera.CameraUpVector.Y = up.Y;
                    v.PerspectiveCamera.CameraUpVector.Z = up.Z;
                    v.PerspectiveCamera.CameraDirection.X = vi.X;
                    v.PerspectiveCamera.CameraDirection.Y = vi.Y;
                    v.PerspectiveCamera.CameraDirection.Z = vi.Z;
                    v.PerspectiveCamera.FieldOfView = zoomValue;
                }



                if (elemCheck == 0)//visible (0)
                    _elementList = _oDoc.Models.First.RootItem.DescendantsAndSelf.Where(o => o.InstanceGuid != Guid.Empty && ChechHidden(o.AncestorsAndSelf) && o.FindFirstGeometry() != null && !o.FindFirstGeometry().Item.IsHidden).ToList<ModelItem>();

                if (null != _elementList && _elementList.Any() && elemCheck != 2)//not if none (2)
                {
                    v.Components = new Classes.Component[_elementList.Count];
                    string appname = Autodesk.Navisworks.Api.Application.Title;
                    for (var i = 0; i < _elementList.Count; i++)
                    {
                        string ifcguid = IfcGuid.ToIfcGuid(_elementList.ElementAt(i).InstanceGuid).ToString();
                        v.Components[i] = new ARUP.IssueTracker.Classes.Component(appname, "", ifcguid);

                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            return v;
        }
 /// <summary>
 /// Instantiates the visualisation info.
 /// </summary>
 private void InstantiateVisualisationInfo()
 {
     visualization_info           = new VisualizationInfo();
     visualization_info.rgb_image = new Texture2D(widthValue, heightValue);
 }
Beispiel #37
0
        /// <summary>
        /// returns XYZ and ZOOM/FOV value
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="viewport"></param>
        /// <returns></returns>
        public Tuple <ViewOrientation3D, double, string, string> GetViewCoordinates(Document doc, VisualizationInfo viewport)
        {
            string type = ""; //change if i force ortho mode
            double zoom = 0;  //fov or worldscale

            XYZ CameraDirection = new XYZ();
            XYZ CameraUpVector  = new XYZ();
            XYZ CameraViewPoint = new XYZ();

            //retrive the force perspective value


            // IS ORTHOGONAL
            if (viewport.OrthogonalCamera != null)
            {
                if (viewport.OrthogonalCamera.ViewToWorldScale == null || viewport.OrthogonalCamera.CameraViewPoint == null || viewport.OrthogonalCamera.CameraUpVector == null || viewport.OrthogonalCamera.CameraDirection == null)
                {
                    return(null);
                }
                type            = "OrthogonalCamera";
                zoom            = UnitUtils.ConvertToInternalUnits(viewport.OrthogonalCamera.ViewToWorldScale, DisplayUnitType.DUT_METERS);
                CameraDirection = GetXYZ(viewport.OrthogonalCamera.CameraDirection.X, viewport.OrthogonalCamera.CameraDirection.Y, viewport.OrthogonalCamera.CameraDirection.Z);
                CameraUpVector  = GetXYZ(viewport.OrthogonalCamera.CameraUpVector.X, viewport.OrthogonalCamera.CameraUpVector.Y, viewport.OrthogonalCamera.CameraUpVector.Z);
                CameraViewPoint = GetXYZ(viewport.OrthogonalCamera.CameraViewPoint.X, viewport.OrthogonalCamera.CameraViewPoint.Y, viewport.OrthogonalCamera.CameraViewPoint.Z);
            }

            else if (viewport.PerspectiveCamera != null)
            {
                if (viewport.PerspectiveCamera.FieldOfView == null || viewport.PerspectiveCamera.CameraViewPoint == null || viewport.PerspectiveCamera.CameraUpVector == null || viewport.PerspectiveCamera.CameraDirection == null)
                {
                    return(null);
                }

                type = "PerspectiveCamera";
                zoom = viewport.PerspectiveCamera.FieldOfView;
                double z1     = 18 / Math.Tan(zoom / 2 * Math.PI / 180); //focale 1
                double z      = 18 / Math.Tan(25 / 2 * Math.PI / 180);   //focale, da controllare il 18, vedi PDF
                double factor = z1 - z;

                CameraDirection = GetXYZ(viewport.PerspectiveCamera.CameraDirection.X, viewport.PerspectiveCamera.CameraDirection.Y, viewport.PerspectiveCamera.CameraDirection.Z);
                CameraUpVector  = GetXYZ(viewport.PerspectiveCamera.CameraUpVector.X, viewport.PerspectiveCamera.CameraUpVector.Y, viewport.PerspectiveCamera.CameraUpVector.Z);
                XYZ oldO = GetXYZ(viewport.PerspectiveCamera.CameraViewPoint.X, viewport.PerspectiveCamera.CameraViewPoint.Y, viewport.PerspectiveCamera.CameraViewPoint.Z);
                CameraViewPoint = (oldO.Subtract(CameraDirection.Divide(factor)));
            }
            else
            {
                return(null);
            }
            // CHAGE VALUES ACCORDING TO BASEPOINT
            //THIS WAS the one with DOC
            ViewOrientation3D orient3d = ConvertBasePoint(CameraViewPoint, CameraDirection, CameraUpVector, true);

            return(new Tuple <ViewOrientation3D, double, string, string>(orient3d, zoom, type, "New View"));
        }
        private void Open3DView(VisualizationInfo v)
        {
            try
            {
                //    {
                //      
                Tuple<Point3D, Vector3D, Vector3D, ViewpointProjection, double> tuple = GetViewCoordinates(v);

                if (tuple == null)
                {
                    MessageBox.Show("Viewpoint not formatted correctly.", "Viewpoint Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                Document oDoc = Autodesk.Navisworks.Api.Application.ActiveDocument;

                // get current viewpoint
                // Viewpoint oCurVP = oDoc.vi.CurrentViewpoint.ToViewpoint;
                // get copy viewpoint
                Viewpoint oCopyVP = new Viewpoint();



                oCopyVP.AlignDirection(tuple.Item3);
                oCopyVP.AlignUp(tuple.Item2);
                oCopyVP.Projection = tuple.Item4;



                // **** CUSTOM VALUE FOR TEKLA **** //
                // otherwise = 1
                // **** CUSTOM VALUE FOR TEKLA **** //
                const double TEKLA = 1.25;

                double x = tuple.Item5 / TEKLA;


                if (oCopyVP.Projection == ViewpointProjection.Orthographic)
                {

                    oCopyVP.Position = tuple.Item1;
                    oCopyVP.FocalDistance = 1;
                    //top center point of view
                    Point3D xyzTL = oCopyVP.Position.Add(tuple.Item2.Multiply(x));
                    oCopyVP.SetExtentsAtFocalDistance(1, xyzTL.DistanceTo(oCopyVP.Position));
                }
                else
                {
                    //double angle = tuple.Item5 * Math.PI / 180;
                    // MessageBox.Show(tuple.Item5.ToString() + "  " +(Math.Tan(angle / 2)*2).ToString());
                    oCopyVP.FocalDistance = tuple.Item5;
                    //oCopyVP.SetExtentsAtFocalDistance(Math.Tan(angle / 2) * 2, Math.Tan(angle / 2) * 2 / oCopyVP.AspectRatio);
                    oCopyVP.Position = tuple.Item1;
                }

                oDoc.CurrentViewpoint.CopyFrom(oCopyVP);

                if (v.Components != null && v.Components.Any())
                {
                    // ModelItemCollection selected = new ModelItemCollection();
                    List<ModelItem> attachedElems = new List<ModelItem>();

                    List<ModelItem> elems = oDoc.Models.First.RootItem.DescendantsAndSelf.ToList<ModelItem>();


                    foreach (var item in elems.Where(o => o.InstanceGuid != Guid.Empty))
                    {
                        string ifcguid = IfcGuid.ToIfcGuid(item.InstanceGuid).ToString();
                        if (v.Components.Any(o => o.IfcGuid == ifcguid))
                            attachedElems.Add(item);

                    }
                    if (attachedElems.Any())//avoid to hide everything if no elements matches
                    {
                        if (MySettings.Get("selattachedelems") == "0")
                        {
                            List<ModelItem> elemsVisible = new List<ModelItem>();
                            foreach (var item in attachedElems)
                            {
                                elemsVisible.AddRange(item.AncestorsAndSelf);
                            }
                            foreach (var item in elemsVisible)
                                elems.Remove(item);

                            oDoc.Models.ResetAllHidden();
                            oDoc.Models.SetHidden(elems, true);
                        }

                        else
                        {
                            oDoc.CurrentSelection.Clear();
                            oDoc.CurrentSelection.AddRange(attachedElems);
                        }
                    }


                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            //setVisibility(v);


        }