Example #1
0
        /// <summary>
        /// Listen for incoming connections from Grasshopper
        /// </summary>
        void ListenForIncomingConnections()
        {
            // Initialize a new component collection for the result
            componentCollection = new Grevit.Types.ComponentCollection();

            // Initialize the listener using IPAddress and Port
            listener = new TcpListener(new IPEndPoint(ListenIPAddress, Port));
            try
            {
                // Start the listener
                listener.Start();

                // Initialize the tcp callback
                tcpClientCallback = new AsyncCallback(ConnectCallback);

                // Begin to accept tcp connections (async)
                AcceptConnectionsAysnc(listener);
            }
            catch (SocketException e)
            {
                //unhandled Exception in case anything goes wrong
            }

            // Write debug messages to the client screen
            AppendDebugListMessage("Client started.");
            AppendDebugListMessage("Waiting for connections.");
        }
Example #2
0
        // Deserialze Component strings
        private static Grevit.Types.ComponentCollection StringToComponents(string dataxml)
        {
            // Deserialize xml data to an object
            object o = Utilities.Deserialize(dataxml, typeof(Grevit.Types.ComponentCollection));

            // Cast the object to a component collection and return it
            Grevit.Types.ComponentCollection cs = (Grevit.Types.ComponentCollection)o;

            return(cs);
        }
Example #3
0
 // Invokable method to set received component collections to the static component collection
 private void AddComponents(Grevit.Types.ComponentCollection componentCollection)
 {
     if (this.debugTextBox.InvokeRequired)
     {
         SetComponentsCallback d = new SetComponentsCallback(AddComponents);
         this.Invoke(d, new object[] { componentCollection });
     }
     else
     {
         this.componentCollection = componentCollection;
     }
 }
Example #4
0
        public static void Send(Grevit.Types.ComponentCollection components, string host = "127.0.0.1", int port = 8002, int timeout = 10000)
        {
            bool   retry        = true;
            string responseData = "";

            try
            {
                while (retry)
                {
                    using (TcpClient tcpClient = new TcpClient())
                    {
                        tcpClient.Connect(IPAddress.Parse(host), port);
                        tcpClient.NoDelay        = true;
                        tcpClient.ReceiveTimeout = timeout;
                        tcpClient.SendTimeout    = timeout;

                        using (NetworkStream stream = tcpClient.GetStream())
                        {
                            using (StreamWriter writer = new StreamWriter(stream, new UTF8Encoding(false)))
                            {
                                writer.AutoFlush = true;
                                using (StreamReader reader = new StreamReader(stream))
                                {
                                    string line = Grevit.Serialization.Utilities.Serialize(components);
                                    writer.WriteLine(line);

                                    string response = reader.ReadLine();
                                    if (response == line)
                                    {
                                        retry = false;
                                    }
                                    responseData = reader.ReadLine();
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Console.Write(ex.Message);
            }
        }
Example #5
0
        /// <summary>
        /// Build Revit Model from a Grevit Component Collection
        /// Make sure the Component Collection has update, delete and scale properties set
        /// </summary>
        /// <param name="components">Grevit Component Collection</param>
        /// <returns></returns>
        public Result BuildModel(Grevit.Types.ComponentCollection components)
        {
            bool delete = false;

            // if components collection hasn't been supplied
            // open the Grevit UI and retrieve components from a Grevit Server
            if (components == null)
            {
                // Create new Grevit Client sending existing Families
                Grevit.Client.ClientWindow grevitClientDialog = new Grevit.Client.ClientWindow(document.GetFamilies());

                // Show Client Dialog
                grevitClientDialog.ShowWindow();

                // Set the received component collection
                components = grevitClientDialog.componentCollection;
            }

            // set element deletion flag and scale factor from collection
            delete = components.delete;
            Scale  = components.scale;


            RoofShapePoints = new List <Tuple <ElementId, CurveArray> >();


            // Set up a List for stalled components (with References)
            List <Component> componentsWithReferences = new List <Component>();

            // Get all existing Grevit Elements from the Document
            // If Update is false this will just be an empty List
            existing_Elements = document.GetExistingGrevitElements(components.update);

            // Set up an empty List for created Elements
            created_Elements = new Dictionary <string, ElementId>();


            #region createComponents

            // using one transaction for all elements
            // this way a Grevit import is one simple UNDO step in Revit
            Transaction trans = new Transaction(GrevitBuildModel.document, "GrevitCreate");
            trans.Start();

            // Walk thru all received components
            foreach (Component component in components.Items)
            {
                // If they are not reference dependent, create them directly
                // Otherwise add the component to a List of stalled elements
                if (!component.stalledForReference)
                {
                    try
                    {
                        component.Build(false);
                    }
                    catch (Exception e) { Grevit.Reporting.MessageBox.Show(component.GetType().Name + " Error", e.InnerException.Message); }
                }
                else
                {
                    componentsWithReferences.Add(component);
                }
            }

            // Walk thru all elements which are stalled because they are depending on
            // an Element which needed to be created first


            foreach (Component component in componentsWithReferences)
            {
                try
                {
                    component.Build(true);
                }
                catch (Exception e) { Grevit.Reporting.MessageBox.Show(component.GetType().Name + " Error", e.InnerException.Message); }
            }

            trans.Commit();
            trans.Dispose();



            foreach (Tuple <ElementId, CurveArray> rsp in RoofShapePoints)
            {
                if (rsp.Item1 != ElementId.InvalidElementId)
                {
                    Autodesk.Revit.DB.RoofBase roof = (Autodesk.Revit.DB.RoofBase)document.GetElement(rsp.Item1);
                    if (roof != null)
                    {
                        if (roof.SlabShapeEditor != null)
                        {
                            if (roof.SlabShapeEditor.IsEnabled)
                            {
                                Transaction pp = new Transaction(GrevitBuildModel.document, "GrevitPostProcessing");
                                pp.Start();
                                roof.SlabShapeEditor.Enable();
                                pp.Commit();
                                pp.Dispose();
                            }

                            List <XYZ> points = new List <XYZ>();
                            foreach (Curve c in rsp.Item2)
                            {
                                points.Add(c.GetEndPoint(0));
                            }

                            Transaction ppx = new Transaction(GrevitBuildModel.document, "GrevitPostProcessing");
                            ppx.Start();

                            foreach (SlabShapeVertex v in roof.SlabShapeEditor.SlabShapeVertices)
                            {
                                double Zdiff = 0;

                                foreach (XYZ pt in points)
                                {
                                    if (Math.Abs(v.Position.X - pt.X) < double.Epsilon &&
                                        Math.Abs(v.Position.Y - pt.Y) < double.Epsilon &&
                                        Math.Abs(v.Position.Z - pt.Z) > double.Epsilon)
                                    {
                                        Zdiff = pt.Z;
                                    }
                                }

                                if (Zdiff != 0)
                                {
                                    roof.SlabShapeEditor.ModifySubElement(v, Zdiff);
                                }
                            }

                            ppx.Commit();
                            ppx.Dispose();
                        }
                    }
                }
            }



            #endregion


            // If Delete Setting is activated
            if (delete)
            {
                // Create a new transaction
                Transaction transaction = new Transaction(document, "GrevitDelete");
                transaction.Start();

                // get the Difference between existing and new elements to erase them
                IEnumerable <KeyValuePair <string, ElementId> > unused =
                    existing_Elements.Except(created_Elements).Concat(created_Elements.Except(existing_Elements));

                // Delete those elements from the document
                foreach (KeyValuePair <string, ElementId> element in unused)
                {
                    document.Delete(element.Value);
                }

                // commit and dispose the transaction
                transaction.Commit();
                transaction.Dispose();
            }



            return(Result.Succeeded);
        }
Example #6
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            // Get Revit Environment
            UIApplication uiApp = commandData.Application;
            Document doc = uiApp.ActiveUIDocument.Document;
            UIDocument uidoc = uiApp.ActiveUIDocument;

            GrevitBuildModel c = new GrevitBuildModel(doc);
            GrevitBuildModel.Scale = 3.28084;

            System.Windows.Forms.OpenFileDialog filedialog = new System.Windows.Forms.OpenFileDialog();
            filedialog.Multiselect = false;
            if (filedialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                SketchUpNET.SketchUp skp = new SketchUpNET.SketchUp();
                if (skp.LoadModel(filedialog.FileName))
                {
                    Grevit.Types.ComponentCollection components = new ComponentCollection() { Items = new List<Component>() };

                    foreach (SketchUpNET.Instance instance in skp.Instances)
                    {
                        if (instance.Name.ToLower().Contains("wall"))
                        {
                            foreach (SketchUpNET.Surface surface in instance.Parent.Surfaces)
                            {
                                components.Items.Add(new WallProfileBased(instance.Parent.Name, instance.Parent.Name, new List<Types.Parameter>(), surface.ToGrevitOutline(instance.Transformation), "") { GID = instance.Guid });
                            }
                        }


                        if (instance.Name.ToLower().Contains("floor"))
                        {
                            foreach (SketchUpNET.Surface surface in instance.Parent.Surfaces)
                            {
                                Types.Point bottom = instance.Transformation.GetTransformed(surface.Vertices[0]).ToGrevitPoint();
                                int ctr = surface.Vertices.Count / 2;
                                Types.Point top = instance.Transformation.GetTransformed(surface.Vertices[ctr]).ToGrevitPoint();



                                components.Items.Add(new Slab()
                                {
                                    FamilyOrStyle = instance.Parent.Name,
                                    TypeOrLayer = instance.Parent.Name,
                                    parameters = new List<Types.Parameter>(),
                                    structural = true,
                                    height = 1,
                                    surface =
                                        surface.ToGrevitProfile(instance.Transformation),
                                    bottom = bottom,
                                    top = top,
                                    slope = top.z - bottom.z,
                                    GID = instance.Guid,
                                    levelbottom = "",
                                });
                            }
                        }

                        if (instance.Name.ToLower().Contains("column"))
                        {
                            Grevit.Types.Profile profile = null;
                            Grevit.Types.Point top = null;
                            Grevit.Types.Point btm = new Types.Point(instance.Transformation.X, instance.Transformation.Y, instance.Transformation.Z);

                            foreach (SketchUpNET.Surface surface in instance.Parent.Surfaces)
                            {

                                if (surface.Normal.Z == 1)
                                {
                                    top = new Types.Point(instance.Transformation.X, instance.Transformation.Y,
                                        surface.Vertices[0].ToGrevitPoint(instance.Transformation).z);
                                }

                            }

                            components.Items.Add(new Grevit.Types.Column(instance.Parent.Name, instance.Parent.Name, new List<Types.Parameter>(), btm, top, "", true)
                            {
                                GID = instance.Guid
                            });
                        }



                    }

                    c.BuildModel(components);

                }

            }



            // Return Success
            return Result.Succeeded;
        }
Example #7
0
        /// <summary>
        /// Listen for incoming connections from Grasshopper
        /// </summary>
        void ListenForIncomingConnections()
        {
            // Initialize a new component collection for the result
            componentCollection = new Grevit.Types.ComponentCollection();

            // Initialize the listener using IPAddress and Port
            listener = new TcpListener(new IPEndPoint(ListenIPAddress, Port));
            try
            {
                // Start the listener
                listener.Start();

                // Initialize the tcp callback
                tcpClientCallback = new AsyncCallback(ConnectCallback);

                // Begin to accept tcp connections (async)
                AcceptConnectionsAysnc(listener);
            }
            catch (SocketException e)
            { 
                //unhandled Exception in case anything goes wrong
            }
           
            // Write debug messages to the client screen
            AppendDebugListMessage("Client started.");
            AppendDebugListMessage("Waiting for connections.");
        }
Example #8
0
 // Invokable method to set received component collections to the static component collection
 private void AddComponents(Grevit.Types.ComponentCollection componentCollection)
 {
     if (this.debugTextBox.InvokeRequired)
     {
         SetComponentsCallback d = new SetComponentsCallback(AddComponents);
         this.Invoke(d, new object[] { componentCollection });
     }
     else
     {
         this.componentCollection = componentCollection;
     }
 }
Example #9
0
        public Result BuildModel(Grevit.Types.ComponentCollection components)
        {
            bool delete = false;

            if (components == null)
            {
                // Create new Grevit Client sending existing Families
                Grevit.Client.ClientWindow grevitClientDialog = new Grevit.Client.ClientWindow(document.GetFamilies());
                //Grevit.Serialization.Client grevitClientDialog = new Grevit.Serialization.Client(document.GetFamilies());

                // Show Client Dialog
                grevitClientDialog.ShowWindow();
                //if (grevitClientDialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) return Result.Cancelled;

                // Set the received component collection
                components = grevitClientDialog.componentCollection;

                delete = grevitClientDialog.componentCollection.delete;

                Scale = grevitClientDialog.componentCollection.scale;
            }



            // Set up a List for stalled components (with References)
            List <Component> componentsWithReferences = new List <Component>();

            // Get all existing Grevit Elements from the Document
            // If Update is false this will just be an empty List
            existing_Elements = document.GetExistingGrevitElements(components.update);

            // Set up an empty List for created Elements
            created_Elements = new Dictionary <string, ElementId>();


            #region createComponents

            Transaction trans = new Transaction(GrevitBuildModel.document, "GrevitCreate");
            trans.Start();

            // Walk thru all received components
            foreach (Component component in components.Items)
            {
                // If they are not reference dependent, create them directly
                // Otherwise add the component to a List of stalled elements
                if (!component.stalledForReference)
                {
                    try
                    {
                        component.Build(false);
                    }
                    catch (Exception e) { Grevit.Reporting.MessageBox.Show(component.GetType().Name + " Error", e.InnerException.Message); }
                }
                else
                {
                    componentsWithReferences.Add(component);
                }
            }

            // Walk thru all elements which are stalled because they are depending on
            // an Element which needed to be created first


            foreach (Component component in componentsWithReferences)
            {
                try
                {
                    component.Build(true);
                }
                catch (Exception e) { Grevit.Reporting.MessageBox.Show(component.GetType().Name + " Error", e.InnerException.Message); }
            }

            trans.Commit();
            trans.Dispose();

            #endregion


            // If Delete Setting is activated
            if (delete)
            {
                // Create a new transaction
                Transaction transaction = new Transaction(document, "GrevitDelete");
                transaction.Start();

                // get the Difference between existing and new elements to erase them
                IEnumerable <KeyValuePair <string, ElementId> > unused =
                    existing_Elements.Except(created_Elements).Concat(created_Elements.Except(existing_Elements));

                // Delete those elements from the document
                foreach (KeyValuePair <string, ElementId> element in unused)
                {
                    document.Delete(element.Value);
                }

                // commit and dispose the transaction
                transaction.Commit();
                transaction.Dispose();
            }



            return(Result.Succeeded);
        }
Example #10
0
        /// <summary>
        /// Handle an incoming connection
        /// </summary>
        private void HandleRecieve(IAsyncResult result, TcpListener listener)
        {
            // Print debug message waiting for data
            AppendDebugListMessage("Waiting for data.");

            // Interrupt this process once stop listenening is true
            if (StopListening)
            {
                return;
            }

            // Accept connection
            using (TcpClient client = listener.EndAcceptTcpClient(result))
            {
                client.NoDelay = true;

                // Get the data stream ftom the tcp client
                using (NetworkStream stream = client.GetStream())
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        using (StreamWriter writer = new StreamWriter(stream))
                        {
                            writer.AutoFlush = true;

                            // read data from sender
                            string data = reader.ReadLine();

                            // write the line to the console
                            Console.WriteLine(data);

                            // Send the received data back to the sender
                            // in Order to make sure we recieved the
                            // right amount and correct data.
                            writer.WriteLine(data);

                            // Send our Categories, Families and Types to Grasshopper
                            writer.WriteLine(FamiliesToRespond);

                            // if there is some useful data
                            if (data != null && data.Length > 5)
                            {
                                // Set the debugger message
                                AppendDebugListMessage("Received " + data.Length + " Bytes.");

                                // Deserialize the received data string
                                Grevit.Types.ComponentCollection cc = StringToComponents(data);

                                // If anything useful has been deserialized
                                if (cc != null && cc.Items.Count > 0)
                                {
                                    // Add Component collection to the client static component collection
                                    AddComponents(cc);

                                    // print another debug message about the component received
                                    AppendDebugListMessage("Translated " + cc.Items.Count.ToString() + " components.");

                                    // set stop listening switch
                                    StopListening = true;
                                }
                            }
                        }
                    }
                }
            }

            // If stop listening is set stop all listening processes
            if (StopListening)
            {
                // Stop the listener
                listener.Server.Close();
                listener.Stop();

                // Wait until processes are stopped
                Thread.Sleep(2000);

                // close the dialog automatically
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            }
        }
 // Invokable method to set received component collections to the static component collection
 private void AddComponents(Grevit.Types.ComponentCollection componentCollection)
 {
     this.Dispatcher.Invoke(new Action(() => { this.componentCollection = componentCollection; }));
 }
Example #12
0
 // Invokable method to set received component collections to the static component collection
 private void AddComponents(Grevit.Types.ComponentCollection componentCollection)
 {
     this.Dispatcher.Invoke(new Action(() => { this.componentCollection = componentCollection; }));
 }